requirements.authoring.output_limit
Requirements index · View definition
Requirement
When a Bedrock configuration sets no
maxTokensoption, each provider request MUST ask for at most 16,384 output tokens. A configuredmaxTokensMUST be used as given.When a response stops because it reached a known output limit, the harness MUST continue the same conversation once, adding a user message with an error result for each tool call in the cut-off response, followed by this text with
<limit>replaced by the limit:Your previous response reached the <limit>-token output limit and was cut off, so its tool call was incomplete. Keep within the limit: make your rationale shorter, then call the tool again.A second response that reaches the limit, or a response that stops at an output limit that is not known, MUST fail the assessment as an incomplete response. Where the provider reports whether a response stopped at the output limit or because the conversation exceeded the model’s context window, the harness SHOULD continue only the former and fail the assessment on the latter; where it does not, the stop MUST be treated as reaching the output limit.
Rationale
The reviewed tests cover each obligation in requirements.authoring.output_limit, and their assertions enforce the expected outcomes.
Default and configured maxTokens
- A Bedrock configuration with no
maxTokensmust ask for at most 16,384 output tokens.tests/authoring_cli.rs#fn[bedrock_requests_without_max_tokens_ask_for_at_most_16k_output_tokens]runs two models. It assertsinferenceConfig == {"maxTokens":16384}on every request body.- The unit test
src/authoring/providers.rs#mod[tests]/fn[bedrock_native_option_types_are_checked_and_only_max_tokens_is_defaulted]assertsrequest.max_tokens == Some(16_384)when the option is absent.
- A configured
maxTokensmust be used as given.tests/authoring_cli.rs#fn[bedrock_cli_uses_selected_profile_region_and_converse_tools]configures 321 and asserts it on both requests.tests/authoring_cli.rs#fn[a_configured_bedrock_limit_controls_requests_and_the_continuation_note]also uses 321. It asserts it on both requests and in the note text.- The unit test also rejects invalid values such as -1 and 2147483648.
Continuation after a known-limit cut-off
tests/authoring_cli.rs#fn[a_response_cut_off_at_the_output_limit_is_continued_once]checks the following.- The same conversation continues. The second request’s messages equal the first request’s messages, then the cut-off assistant turn, then one new user message.
- The user message carries an error
toolResultfor each of the two tool calls in the cut-off response (cutandread-cut). - The message ends with text equal to
LIMIT_NOTE. That constant matches the requirement’s wording with<limit>replaced by 16384. - The cut-off calls never ran, and there were exactly two requests.
- The configured-limit test asserts that
<limit>is replaced by the configured value 321. - The Ollama test
a_configured_ollama_num_predict_is_the_known_output_limitasserts that the note contains “reached the 512-token output limit”.
Failure cases
- A second response that reaches the limit:
tests/authoring_cli.rs#fn[a_second_response_at_the_output_limit_fails_the_assessment]asserts a non-zero exit, “incomplete” in stderr, exactly two requests and outcomefailed. - A stop at an output limit that is not known:
tests/authoring_cli.rs#fn[a_stop_at_an_output_limit_that_is_not_known_fails_the_assessment]uses Ollama with nonum_predict. It asserts failure with “incomplete” and “does not set”, only one request, and that the evidence file is unchanged.src/authoring/mod.rs#mod[tests]/fn[a_cut_off_response_without_a_known_output_limit_fails_without_continuing]asserts the same message, exactly one provider call, and that no determination was accepted.
Context window versus output limit
- Where the provider distinguishes them (Bedrock
model_context_window_exceeded),tests/authoring_cli.rs#fn[a_context_window_overflow_fails_without_a_continuation]asserts failure mentioning “context window” and one request, with no continuation. Themax_tokensstop is continued in the other tests. - Where the provider does not distinguish them, the stop must be treated as the output limit. The Ollama
num_predicttest covers this: the stop is continued with the known limit.
I found no unacknowledged gaps. All tests carry {test} references to the requirement.
Inputs
Implementation
Input 12: outline src/authoring/mod.rs fn[converse]
- File:
src/authoring/mod.rs - Selector:
fn[converse] - Kind:
fn src/authoring/mod.rs:1325–1589
/// One conversation: sends the prompt with the source tools and the named
/// submission tool, delivers tool results until a submission is accepted,
/// and returns the parsed submission.
// {impl}`requirements.authoring.delivered_inputs`
// {impl}`requirements.authoring.usage_requests`
// {impl}`requirements.authoring.mandatory_inputs`
// {impl}`requirements.authoring.provider_backoff`
// {impl}`requirements.authoring.submission_count`
// {impl}`requirements.authoring.source_tools`
// {impl}`requirements.authoring.file_discovery`
// {impl}`requirements.authoring.text_search`
// {impl}`requirements.definitions.authoring_inputs`
// {impl}`requirements.authoring.prompt_parts`
// {impl}`requirements.authoring.result_pages`
// {impl}`requirements.authoring.output_limit`
// {impl}`requirements.authoring.line_numbers.rejection`
// {impl}`requirements.authoring.line_numbers.resubmission`
// {impl}`requirements.authoring.submission`
// {impl}`requirements.authoring.no_line_numbers`
// {impl}`requirements.authoring.usage_requests.failures`
// {impl}`requirements.authoring.provider_backoff.limit`
// {impl}`requirements.authoring.tool_descriptions.special_cases`
// {impl}`requirements.authoring.cache_checkpoints`
// {impl}`requirements.authoring.submission.searches`
// {impl}`requirements.authoring.submission.searches.recovery`
// {impl}`requirements.authoring.submission.searches.line_numbers`
// {impl}`requirements.authoring.submission.searches.accompanying_calls`
async fn converse<T>(
provider: &impl CompletionProvider,
sources: &mut AssessmentSources,
usage: &mut UsageLog,
prompt: Prompt,
(submit, site): (&str, bool),
parse: impl Fn(&Value) -> io::Result<T>,
) -> io::Result<T> {
let mut request = prompt.request();
request.tools = tool_definitions_with(submit, site)?;
let mut pending = sources.mandatory_inputs().to_vec();
let mut backoff = providers::ProviderBackoff::default();
// Pages are kept only until this assessment finishes.
let mut pages = pages::ResultPages::default();
// Whether the one continuation after a cut-off response has been used.
let mut continued = false;
// The one rejection of a rationale citing line numbers.
let mut rejection = line_numbers::Rejection::default();
// Whether the one reminder to submit has been sent.
let mut reminded = false;
loop {
let index = usage.begin_request()?;
let started = Instant::now();
// An abandoned request is retried like any other transient failure.
let response =
match tokio::time::timeout(REQUEST_TIMEOUT, provider.complete(request.clone())).await {
Ok(response) => response,
Err(_) => Err(io::Error::new(
io::ErrorKind::TimedOut,
"provider request had no response within ten minutes",
)),
};
let failure = response.as_ref().err().map(providers::failure_codes);
usage.end_request(
index,
started.elapsed().as_millis(),
response.as_ref().ok().map(|r| &r.usage),
failure,
)?;
let response = match response {
Ok(response) => response,
// Tokio's clock, so a paused test clock reaches the limit too.
Err(error) => match backoff.retry(error, tokio::time::Instant::now().into_std()) {
providers::Retry::Wait(delay) => {
usage.retried(index)?;
tokio::time::sleep(delay).await;
continue;
}
providers::Retry::Stop(error) => return Err(error),
},
};
backoff = providers::ProviderBackoff::default();
sources.record_inputs(&pending);
pending.clear();
if matches!(response.finish_reason(), Some(FinishReason::Length)) {
// Rig reports a context-window overflow as `Length` too; Bedrock's
// raw reply tells the two apart, and continuing would only grow
// the conversation further.
if response.raw.get("stopReason").and_then(Value::as_str)
== Some("model_context_window_exceeded")
{
return Err(io::Error::other(
"the model's response was incomplete: the conversation exceeded the model's context window",
));
}
if continued {
return Err(io::Error::other(
"the model's response was incomplete: it reached the output limit again after one continuation",
));
}
let limit = provider.output_limit().ok_or_else(|| {
io::Error::other(
"the model's response was incomplete: it reached an output limit the configuration does not set",
)
})?;
continued = true;
request
.chat_history
.extend(cut_off_continuation(&response, limit, usage));
usage.save()?;
continue;
}
if let Some(error) = turn_failure(
&response.choice,
Some(&response.stop()),
response.finish_reason().as_ref(),
) {
return Err(io::Error::other(error));
}
let calls: Vec<_> = response.tool_calls().cloned().collect();
let submissions: Vec<_> = calls
.iter()
.filter(|call| call.function.name.as_str() == submit)
.collect();
if !submissions.is_empty() {
for call in &calls {
if call.function.name.as_str() != submit {
usage.skipped_tool(call.function.name.as_str());
}
}
if submissions.len() != 1 {
for _ in &submissions {
usage.tool(submit, true);
}
return Err(io::Error::other(format!(
"{submit} must be invoked exactly once; multiple submissions received"
)));
}
let arguments = Value::Object(submissions[0].function.arguments.clone());
let resubmitted = rejection.resubmitted(&arguments);
let result = parse(resubmitted.as_ref().unwrap_or(&arguments));
if result.is_err() {
usage.tool(submit, true);
return result;
}
let outstanding = pages.outstanding_searches();
if !outstanding.is_empty() {
usage.tool(submit, true);
let message = format!(
"Submission not accepted: outstanding searches: {}. Call finish_search for every listed search_id, using used:[] when no snippets qualify, then resubmit.",
outstanding.join(", ")
);
request.chat_history.push(
response
.message()
.ok_or_else(|| io::Error::other("model returned an empty response"))?,
);
let results = calls
.iter()
.map(|call| {
let text = if call.function.name.as_str() == submit {
message.clone()
} else {
"not run: the response also made a submission".to_owned()
};
call.error_result(vec![ToolResultContent::text(text)])
})
.collect();
usage.save()?;
request.chat_history.push(Message::tool_results(results));
continue;
}
if resubmitted.is_some() {
usage.tool(submit, false);
return result;
}
match rejection.decide(submit, &arguments, location_guidance()) {
line_numbers::Outcome::Accept => {
usage.tool(submit, false);
return result;
}
line_numbers::Outcome::Fail(error) => {
usage.tool(submit, true);
return Err(io::Error::other(error));
}
line_numbers::Outcome::Reject(message) => {
usage.tool(submit, true);
request.chat_history.push(
response
.message()
.ok_or_else(|| io::Error::other("model returned an empty response"))?,
);
let results = calls
.iter()
.map(|call| {
let text = if call.function.name.as_str() == submit {
message.clone()
} else {
"not run: the response also made a submission".to_owned()
};
call.error_result(vec![ToolResultContent::text(text)])
})
.collect();
usage.save()?;
request.chat_history.push(Message::tool_results(results));
continue;
}
}
}
if calls.is_empty() {
if reminded {
return Err(io::Error::other(format!(
"model finished without invoking {submit}, even after a reminder"
)));
}
reminded = true;
request.chat_history.extend(response.message());
request.chat_history.push(Message::User {
content: vec![UserContent::text(format!(
"Reminder: you MUST submit your result with the {submit} tool."
))],
});
usage.save()?;
continue;
}
request.chat_history.push(
response
.message()
.ok_or_else(|| io::Error::other("model returned an empty response"))?,
);
let mut results = Vec::new();
for call in calls {
match tools::dispatch_paged(
sources,
&mut pages,
call.function.name.as_str(),
&Value::Object(call.function.arguments.clone()),
) {
Ok(delivery) => {
usage.tool(call.function.name.as_str(), false);
if call.function.name.as_str() == "finish_search" {
// These dependencies describe snippets already delivered,
// not a new source read. Record them before acknowledgment.
sources.record_inputs(&delivery.inputs);
} else {
usage.prepared(call.function.name.as_str(), &delivery.inputs);
pending.extend(delivery.inputs);
}
usage.search_result(&delivery.result);
results.push(
call.result(vec![ToolResultContent::text(delivery.result.to_string())]),
);
}
// A denied read is an ordinary tool error the model can see;
// only a denied mandatory input aborts, before any request.
// {impl}`requirements.authoring.read_denial`
Err(error) => {
usage.tool(call.function.name.as_str(), true);
results.push(call.error_result(vec![ToolResultContent::text(
line_numbers::without_source_lines(&error.to_string()),
)]));
}
}
}
usage.save()?;
request.chat_history.push(Message::tool_results(results));
}
}
Tests
Input 2: outline src/authoring/mod.rs mod[tests]/fn[a_cut_off_response_without_a_known_output_limit_fails_without_continuing]
- File:
src/authoring/mod.rs - Selector:
mod[tests]/fn[a_cut_off_response_without_a_known_output_limit_fails_without_continuing] - Kind:
fn src/authoring/mod.rs:1745–1782
// {test}`requirements.authoring.output_limit`
#[tokio::test]
async fn a_cut_off_response_without_a_known_output_limit_fails_without_continuing() {
struct CutOffProvider(std::cell::Cell<usize>);
impl CompletionProvider for CutOffProvider {
async fn complete(&self, request: CompletionRequest) -> io::Result<CompletionResponse> {
self.0.set(self.0.get() + 1);
Ok(JudgmentProvider(json!(true))
.complete(request)
.await?
.with_finish_reason(FinishReason::Length))
}
}
let project = inputs::tests::project();
let state = tempfile::tempdir().unwrap();
let mut sources = AssessmentSources::prepare(project.path(), "requirements.ready").unwrap();
let mut usage =
UsageLog::start(state.path(), project.path(), &sources.subject_name).unwrap();
let provider = CutOffProvider(std::cell::Cell::new(0));
let error = assess(&provider, &mut sources, &mut usage)
.await
.unwrap_err();
let message = error.to_string();
assert!(message.contains("response was incomplete"), "{message}");
assert!(
message.contains("output limit the configuration does not set"),
"{message}"
);
assert_eq!(
provider.0.get(),
1,
"an unknown limit must not start a continuation"
);
assert!(
usage.record.determination.is_none(),
"the cut-off judgment is not accepted"
);
}
Input 3: outline src/authoring/providers.rs mod[tests]/fn[bedrock_native_option_types_are_checked_and_only_max_tokens_is_defaulted]
- File:
src/authoring/providers.rs - Selector:
mod[tests]/fn[bedrock_native_option_types_are_checked_and_only_max_tokens_is_defaulted] - Kind:
fn src/authoring/providers.rs:806–831
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.output_limit`
#[test]
fn bedrock_native_option_types_are_checked_and_only_max_tokens_is_defaulted() {
let mut request = CompletionRequest::new("prompt");
let mut options = Map::from_iter([("top_k".into(), json!(12))]);
apply_bedrock_options(&mut request, &mut options).unwrap();
assert!(request.temperature.is_none());
assert_eq!(request.max_tokens, Some(16_384));
assert!(request.options.is_default());
assert_eq!(options["top_k"], 12);
for value in [
json!({"temperature":"hot"}),
json!({"maxTokens":-1}),
json!({"maxTokens":2147483648_u64}),
json!({"topP":true}),
json!({"stopSequences":"stop"}),
json!({"inferenceConfig":{}}),
] {
let mut options = value.as_object().unwrap().clone();
assert!(
apply_bedrock_options(&mut CompletionRequest::new("prompt"), &mut options).is_err()
);
}
}
Input 4: outline tests/authoring_cli.rs fn[bedrock_cli_uses_selected_profile_region_and_converse_tools]
- File:
tests/authoring_cli.rs - Selector:
fn[bedrock_cli_uses_selected_profile_region_and_converse_tools] - Kind:
fn tests/authoring_cli.rs:1727–1920
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.initial_prompt`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.source_tools`
// {test}`requirements.authoring.submission`
// {test}`requirements.authoring.delivered_inputs`
// {test}`requirements.authoring.output_limit`
#[test]
fn bedrock_cli_uses_selected_profile_region_and_converse_tools() {
for typed in [false, true] {
let mut read_call = json!({"toolUseId":"bedrock-read","name":"habeas",
"input":{"file":"extra.txt","line_start":1,"line_end":2}});
let mut submit_call = json!({"toolUseId":"bedrock-submit","name":"submit_judgment",
"input":{"determination":true,"rationale":"The supplied sources support the subject."}});
if typed {
read_call["type"] = json!("tool_use");
submit_call["type"] = json!("tool_use");
}
let first_message = json!({"role":"assistant","content":[
{"text":"Reading source."},{"toolUse":read_call}
]});
let server = Server::start(vec![
json!({
"output":{"message":first_message.clone()},
"stopReason":"tool_use",
"usage":{"inputTokens":19,"outputTokens":5,"totalTokens":24},
"metrics":{"latencyMs":1}
}),
json!({
"output":{"message":{"role":"assistant","content":[{"toolUse":submit_call}]}},
"stopReason":"tool_use",
"usage":{"inputTokens":19,"outputTokens":5,"totalTokens":24},
"metrics":{"latencyMs":1}
}),
]);
let fixture = Fixture::new(&server.endpoint);
let credentials = fixture.temp.path().join("aws-credentials");
let aws_config = fixture.temp.path().join("aws-config");
fs::write(&credentials, "[default]\naws_access_key_id = WRONG_DEFAULT_ACCESS_KEY\naws_secret_access_key = wrong-default-secret\n[habeas-test]\naws_access_key_id = FAKE_PROFILE_ACCESS_KEY\naws_secret_access_key = fake-profile-secret-for-local-test-only\n").unwrap();
fs::write(&aws_config, "[profile habeas-test]\nregion = eu-west-1\n").unwrap();
fs::write(fixture.config.join("habeas/config.toml"), "version = 1\n[authoring]\ndefault = 'cloud'\n[authoring.configs.cloud]\npolicy = 'once'\nbackend = 'bedrock'\nmodel = 'fixture-bedrock-model'\naws_profile = 'habeas-test'\nregion = 'us-west-2'\n[authoring.configs.cloud.options]\ntemperature = 0.25\nmaxTokens = 321\ntopP = 0.75\nstopSequences = ['END']\ntop_k = 12\n").unwrap();
let mut command = fixture.command();
for key in [
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AWS_SECURITY_TOKEN",
"AWS_PROFILE",
"AWS_DEFAULT_PROFILE",
"AWS_REGION",
"AWS_DEFAULT_REGION",
"AWS_ENDPOINT_URL",
"AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",
"AWS_BEARER_TOKEN_BEDROCK",
] {
command.env_remove(key);
}
let output = command
.env("AWS_CONFIG_FILE", aws_config)
.env("AWS_SHARED_CREDENTIALS_FILE", credentials)
.env("AWS_ENDPOINT_URL_BEDROCK_RUNTIME", &server.endpoint)
.env("AWS_EC2_METADATA_DISABLED", "true")
.args(["author-evidence", SUBJECT])
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = server.finish();
assert_eq!(requests.len(), 2);
assert_eq!(requests[1].body["messages"][1], first_message);
let result = &requests[1].body["messages"][2]["content"][0]["toolResult"];
assert_eq!(result["toolUseId"], "bedrock-read");
let delivered = result["content"][0]["text"].as_str().unwrap();
assert!(delivered.contains("extra.txt") && delivered.contains("context line 1"));
assert!(
requests[0]
.headers
.starts_with("POST /model/fixture-bedrock-model/converse HTTP/1.1\r\n")
);
assert!(
requests[0]
.headers
.contains("Credential=FAKE_PROFILE_ACCESS_KEY/")
);
assert!(
requests[0]
.headers
.contains("/us-west-2/bedrock/aws4_request")
);
assert!(!requests[0].headers.contains("WRONG_DEFAULT_ACCESS_KEY"));
let body = &requests[0].body;
assert_eq!(
body["inferenceConfig"],
json!({"temperature":0.25,"maxTokens":321,"topP":0.75,"stopSequences":["END"]})
);
// A configured maxTokens is used as given on every request.
assert_eq!(requests[1].body["inferenceConfig"]["maxTokens"], 321);
assert_eq!(body["additionalModelRequestFields"], json!({"top_k":12}));
let prompt = prompt_text(body);
assert!(
prompt.contains("Assess whether a project's tests adequately check")
&& prompt.contains(REQUIREMENT)
);
let tool_specs = body["toolConfig"]["tools"].as_array().unwrap();
for tool in tool_specs {
let schema = &tool["toolSpec"]["inputSchema"]["json"];
assert_eq!(schema["type"], "object");
for unsupported in ["oneOf", "allOf", "anyOf"] {
assert!(
schema.get(unsupported).is_none(),
"Bedrock rejects {unsupported} at the root of {}'s input schema",
tool["toolSpec"]["name"]
);
}
}
let habeas_schema = &tool_specs
.iter()
.find(|tool| tool["toolSpec"]["name"] == "habeas")
.unwrap()["toolSpec"]["inputSchema"]["json"];
assert_eq!(habeas_schema["additionalProperties"], false);
for field in ["file", "item", "requirements", "definition"] {
assert_eq!(habeas_schema["properties"][field]["type"], "string");
}
for field in ["line_start", "line_end"] {
assert_eq!(habeas_schema["properties"][field]["type"], "integer");
assert_eq!(habeas_schema["properties"][field]["minimum"], 1);
}
let judgment_schema = &tool_specs
.iter()
.find(|tool| tool["toolSpec"]["name"] == "submit_judgment")
.unwrap()["toolSpec"]["inputSchema"]["json"]["properties"]["determination"];
let outcomes = judgment_schema["oneOf"].as_array().unwrap();
assert!(outcomes.iter().any(|outcome| outcome["type"] == "boolean"));
let fixme = &outcomes
.iter()
.find(|outcome| outcome["type"] == "object")
.unwrap()["properties"]["FIXME"];
assert_eq!(fixme["type"], "array");
assert_eq!(fixme["minItems"], 1);
assert_eq!(fixme["items"]["type"], "string");
assert_eq!(fixme["items"]["minLength"], 1);
let mut tools = tool_specs
.iter()
.map(|tool| tool["toolSpec"]["name"].as_str().unwrap())
.collect::<Vec<_>>();
tools.sort();
assert_eq!(
tools,
[
"ast_grep",
"finish_search",
"github",
"habeas",
"list_files",
"next_page",
"outline",
"references",
"ripgrep",
"submit_judgment"
]
);
let evidence: Value =
serde_json::from_slice(&fs::read(&fixture.evidence).unwrap()).unwrap();
assert_eq!(evidence["determination"], true);
assert!(
evidence["inputs"]
.as_array()
.unwrap()
.iter()
.filter(|input| input["file"] == "extra.txt")
.collect::<Vec<_>>()
== habeas::outline_inputs_for_lines(&fixture.project, "extra.txt", 1, 2)
.unwrap()
.iter()
.collect::<Vec<_>>()
);
let usage = fixture.usage();
assert_eq!(usage["backend"], "bedrock");
assert_eq!(usage["model"], "fixture-bedrock-model");
assert_eq!(usage["tokens"]["input"], 38);
assert_eq!(usage["tokens"]["output"], 10);
assert_eq!(usage["request_count"], 2);
assert_eq!(usage["tool_calls"]["habeas"], 1);
assert_eq!(usage["tool_calls"]["submit_judgment"], 1);
assert_eq!(usage["outcome"], "completed");
}
}
Input 5: outline tests/authoring_cli.rs fn[bedrock_requests_without_max_tokens_ask_for_at_most_16k_output_tokens]
- File:
tests/authoring_cli.rs - Selector:
fn[bedrock_requests_without_max_tokens_ask_for_at_most_16k_output_tokens] - Kind:
fn tests/authoring_cli.rs:2084–2103
// {test}`requirements.authoring.output_limit`
#[test]
fn bedrock_requests_without_max_tokens_ask_for_at_most_16k_output_tokens() {
for model in [
"us.anthropic.claude-sonnet-4-5-20250929-v1:0",
"fixture-uncached-model",
] {
let (bodies, usage) = bedrock_run(model);
assert_eq!(usage["outcome"], "completed");
assert_eq!(bodies.len(), 2);
for body in &bodies {
assert_eq!(
body["inferenceConfig"],
json!({"maxTokens":16384}),
"{body}"
);
assert!(body.get("additionalModelRequestFields").is_none(), "{body}");
}
}
}
Input 6: outline tests/authoring_cli.rs fn[a_configured_bedrock_limit_controls_requests_and_the_continuation_note]
- File:
tests/authoring_cli.rs - Selector:
fn[a_configured_bedrock_limit_controls_requests_and_the_continuation_note] - Kind:
fn tests/authoring_cli.rs:2123–2155
// {test}`requirements.authoring.output_limit`
#[test]
fn a_configured_bedrock_limit_controls_requests_and_the_continuation_note() {
let mut cut_off = cut_off_submission("cut");
cut_off["usage"] = json!({"inputTokens":7,"outputTokens":321,"totalTokens":328});
let (output, bodies, usage) = bedrock_exchange_with_limit(
"fixture-uncached-model",
vec![
cut_off,
json!({
"output":{"message":{"role":"assistant","content":[{"toolUse":
{"toolUseId":"submit","name":"submit_judgment","input":
{"determination":true,"rationale":"Short."}}}]}},
"stopReason":"tool_use",
"usage":{"inputTokens":9,"outputTokens":5,"totalTokens":14},
"metrics":{"latencyMs":1}
}),
],
Some(321),
);
assert!(output.status.success(), "{output:?}");
assert_eq!(bodies.len(), 2);
for body in &bodies {
assert_eq!(body["inferenceConfig"]["maxTokens"], 321);
}
let note = bodies[1]["messages"].as_array().unwrap().last().unwrap();
assert_eq!(
note["content"][1]["text"],
LIMIT_NOTE.replace("16384", "321")
);
assert_eq!(usage["request_count"], 2);
assert_eq!(usage["outcome"], "completed");
}
Input 7: outline tests/authoring_cli.rs fn[a_response_cut_off_at_the_output_limit_is_continued_once]
- File:
tests/authoring_cli.rs - Selector:
fn[a_response_cut_off_at_the_output_limit_is_continued_once] - Kind:
fn tests/authoring_cli.rs:2157–2219
// {test}`requirements.authoring.output_limit`
// {test}`requirements.authoring.submission`
#[test]
fn a_response_cut_off_at_the_output_limit_is_continued_once() {
let mut cut_off = cut_off_submission("cut");
cut_off["output"]["message"]["content"].as_array_mut().unwrap().push(
json!({"toolUse":{"toolUseId":"read-cut","name":"habeas","input":{"file":"src/lib.rs"}}}),
);
let (output, bodies, usage) = bedrock_exchange(
"us.anthropic.claude-sonnet-4-5-20250929-v1:0",
vec![
cut_off,
json!({
"output":{"message":{"role":"assistant","content":[{"toolUse":
{"toolUseId":"submit","name":"submit_judgment","input":
{"determination":true,"rationale":"Short."}}}]}},
"stopReason":"tool_use",
"usage":{"inputTokens":9,"outputTokens":5,"totalTokens":14},
"metrics":{"latencyMs":1}
}),
],
);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let bodies: Vec<_> = bodies.iter().map(without_cache_points).collect();
assert_eq!(bodies.len(), 2);
// The same conversation continues: the cut-off turn as sent, then one
// user message answering its incomplete call and carrying the note.
let first = bodies[0]["messages"].as_array().unwrap();
let second = bodies[1]["messages"].as_array().unwrap();
assert_eq!(second.len(), first.len() + 2);
assert_eq!(&second[..first.len()], first.as_slice());
let cut = &second[first.len()];
assert_eq!(cut["role"], "assistant");
assert_eq!(cut["content"][1]["toolUse"]["toolUseId"], "cut");
let note = &second[first.len() + 1];
assert_eq!(note["role"], "user");
let content = note["content"].as_array().unwrap();
assert_eq!(content.len(), 3, "{note}");
assert_eq!(content[0]["toolResult"]["toolUseId"], "cut");
assert_eq!(content[0]["toolResult"]["status"], "error");
assert!(
content[0]["toolResult"].to_string().contains("not run"),
"{note}"
);
assert_eq!(content[1]["toolResult"]["toolUseId"], "read-cut");
assert_eq!(content[1]["toolResult"]["status"], "error");
assert!(
content[1]["toolResult"].to_string().contains("not run"),
"{note}"
);
assert_eq!(content[2]["text"], LIMIT_NOTE);
// Both requests are recorded, and the cut-off call never ran.
assert_eq!(usage["request_count"], 2);
assert_eq!(usage["requests"].as_array().unwrap().len(), 2);
assert_eq!(usage["tool_calls"]["submit_judgment"], 2);
assert_eq!(usage["tool_skipped"]["submit_judgment"], 1);
assert_eq!(usage["tool_skipped"]["habeas"], 1);
assert_eq!(usage["outcome"], "completed");
}
Input 8: outline tests/authoring_cli.rs fn[a_second_response_at_the_output_limit_fails_the_assessment]
- File:
tests/authoring_cli.rs - Selector:
fn[a_second_response_at_the_output_limit_fails_the_assessment] - Kind:
fn tests/authoring_cli.rs:2221–2243
// {test}`requirements.authoring.output_limit`
#[test]
fn a_second_response_at_the_output_limit_fails_the_assessment() {
let (output, bodies, usage) = bedrock_exchange(
"fixture-uncached-model",
vec![cut_off_submission("cut"), cut_off_submission("again")],
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!output.status.success(), "{stderr}");
assert!(stderr.contains("incomplete"), "{stderr}");
assert!(!String::from_utf8_lossy(&output.stdout).contains("1 authored"));
assert_eq!(bodies.len(), 2);
let last = bodies[1]["messages"]
.as_array()
.unwrap()
.last()
.unwrap()
.clone();
assert_eq!(last["content"][1]["text"], LIMIT_NOTE);
assert_eq!(usage["request_count"], 2);
assert_eq!(usage["tool_skipped"]["submit_judgment"], 1);
assert_eq!(usage["outcome"], "failed");
}
Input 9: outline tests/authoring_cli.rs fn[a_context_window_overflow_fails_without_a_continuation]
- File:
tests/authoring_cli.rs - Selector:
fn[a_context_window_overflow_fails_without_a_continuation] - Kind:
fn tests/authoring_cli.rs:2245–2257
// {test}`requirements.authoring.output_limit`
#[test]
fn a_context_window_overflow_fails_without_a_continuation() {
let mut overflow = cut_off_submission("overflow");
overflow["stopReason"] = json!("model_context_window_exceeded");
let (output, bodies, usage) = bedrock_exchange("fixture-uncached-model", vec![overflow]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!output.status.success(), "{stderr}");
assert!(stderr.contains("context window"), "{stderr}");
assert_eq!(bodies.len(), 1);
assert_eq!(usage["request_count"], 1);
assert_eq!(usage["outcome"], "failed");
}
Input 10: outline tests/authoring_cli.rs fn[a_stop_at_an_output_limit_that_is_not_known_fails_the_assessment]
- File:
tests/authoring_cli.rs - Selector:
fn[a_stop_at_an_output_limit_that_is_not_known_fails_the_assessment] - Kind:
fn tests/authoring_cli.rs:2272–2294
// {test}`requirements.authoring.output_limit`
#[test]
fn a_stop_at_an_output_limit_that_is_not_known_fails_the_assessment() {
// The fixture's Ollama configuration sets no `num_predict`, so the
// limit the response reached is not known.
let server = Server::start(vec![ollama_cut_off_reply()]);
let fixture = Fixture::new(&server.endpoint);
let output = fixture.run(&["author", SUBJECT]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!output.status.success(), "{stderr}");
assert!(
stderr.contains("incomplete") && stderr.contains("does not set"),
"{stderr}"
);
assert_eq!(server.finish().len(), 1);
assert_eq!(
fs::read_to_string(&fixture.evidence).unwrap(),
fixture.original
);
let usage = fixture.usage();
assert_eq!(usage["request_count"], 1);
assert_eq!(usage["outcome"], "failed");
}
Input 11: outline tests/authoring_cli.rs fn[a_configured_ollama_num_predict_is_the_known_output_limit]
- File:
tests/authoring_cli.rs - Selector:
fn[a_configured_ollama_num_predict_is_the_known_output_limit] - Kind:
fn tests/authoring_cli.rs:2296–2330
// {test}`requirements.authoring.output_limit`
#[test]
fn a_configured_ollama_num_predict_is_the_known_output_limit() {
let server = Server::start(vec![
ollama_cut_off_reply(),
reply(vec![call(
"submit",
"submit_judgment",
json!({"determination":true,"rationale":"Short."}),
)]),
]);
let fixture = Fixture::new(&server.endpoint);
let config_path = fixture.config.join("habeas/config.toml");
let config = fs::read_to_string(&config_path).unwrap();
fs::write(&config_path, format!("{config}num_predict = 512\n")).unwrap();
let output = fixture.run(&["author", SUBJECT]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let requests = server.finish();
assert_eq!(requests.len(), 2);
let last = requests[1].body["messages"]
.as_array()
.unwrap()
.last()
.unwrap()
.to_string();
assert!(
last.contains("reached the 512-token output limit"),
"{last}"
);
assert_eq!(fixture.usage()["outcome"], "completed");
}
Other sources
Input 1: requirements selection requirements.authoring.output_limit
requirements.authoring.output_limit:md/requirements/authoring.md:1844–1866
:::{req} output_limit
When a Bedrock configuration sets no `maxTokens` option, each provider request
MUST ask for at most 16,384 output tokens. A configured `maxTokens` MUST be used
as given.
When a response stops because it reached a known output limit, the harness MUST
continue the same conversation once, adding a user message with an error result
for each tool call in the cut-off response, followed by this text with `<limit>`
replaced by the limit:
```text
Your previous response reached the <limit>-token output limit and was cut off,
so its tool call was incomplete. Keep within the limit: make your rationale
shorter, then call the tool again.
```
A second response that reaches the limit, or a response that stops at an
output limit that is not known, MUST fail the assessment as an incomplete
response. Where the provider reports whether a response stopped at the output
limit or because the conversation exceeded the model's context window, the
harness SHOULD continue only the former and fail the assessment on the latter;
where it does not, the stop MUST be treated as reaching the output limit.
:::
Input 13: outline tests/authoring_cli.rs const[LIMIT_NOTE]
- File:
tests/authoring_cli.rs - Selector:
const[LIMIT_NOTE] - Kind:
const tests/authoring_cli.rs:2120–2121
/// The user message Habeas sends after a response cut off at 16,384 tokens.
const LIMIT_NOTE: &str = "Your previous response reached the 16384-token output limit and was cut off,\nso its tool call was incomplete. Keep within the limit: make your rationale\nshorter, then call the tool again.";
Input 14: outline vendor/habeas-rig/src/streaming.rs fn[finish_reason]
- File:
vendor/habeas-rig/src/streaming.rs - Selector:
fn[finish_reason] - Kind:
fn vendor/habeas-rig/src/streaming.rs:418–430
/// Every stop reason Converse documents. An end of turn or a stop sequence
/// is `Stop`, the token limit and an exceeded context window are `Length`,
/// guardrail and content-filter interventions are `ContentFilter`, and any
/// other reason keeps its wire spelling in `Other`, which fails the turn.
fn finish_reason(reason: &str) -> FinishReason {
match reason {
"end_turn" | "stop_sequence" => FinishReason::Stop,
"max_tokens" | "model_context_window_exceeded" => FinishReason::Length,
"tool_use" => FinishReason::ToolCalls,
"content_filtered" | "guardrail_intervened" => FinishReason::ContentFilter,
other => FinishReason::Other(other.to_owned()),
}
}