requirements.authoring.search_accounting.recovery
Requirements index · View definition
Example
Two search results remain outstanding; one has no matches. Submission MUST return an error naming both UUIDs. Finishing only the first MUST leave submission rejected with the second UUID. Finishing the empty search with
used: []MUST permit an otherwise valid subsequent submission.![]()
Rationale
The example describes a concrete case with three expected outcomes. Two searches are outstanding and one has no matches. Submission must return an error naming both UUIDs. Finishing only the first must leave the second UUID in the rejection. Finishing the empty search with used: [] must permit a valid submission.
src/authoring/mod.rs#mod[tests]/fn[every_submission_kind_waits_for_all_searches_and_can_recover] is the only test that references this example. It covers the scenario for both submit_judgment and submit_verification.
- Setup. Turn 0 issues a
ripgrepcall that matchesassertinsrc/lib.rs. It also issues anast_grepcall forabsent(), which has no matches. That leaves two delivered, outstanding searches. The test asserts thatdelivered_searchesfinds exactly 2. - Both UUIDs in the error. Turn 1 submits while both searches are outstanding. The
Finish(0, ...)in that turn is skipped because the response also contains a submission. The test asserts that the tool-result message after that turn (requests[2]) contains bothsearches[0]andsearches[1]search_idvalues. It also asserts the text “Call finish_search for every listed search_id” and “then resubmit”.conversebuilds the “Submission not accepted: outstanding searches: …” message frompages.outstanding_searches()and returns it as the error result for the submit call. It also confirms that the accompanying calls were “not run”. - Finishing only the first. Turn 2 is
Finish(0, ["1"]). Turn 3 then submits. The test asserts that the resulting message (requests[4]) contains “outstanding searches”, does not contain the first UUID, and does contain the second UUID. The recordedfn[helper]input appears exactly once, so the first finish used its snippet. - Finishing the empty search. Turn 4 is
Finish(1, vec![]), which finishes the empty search with no used tags. Turn 5 submits, andassessorverifyreturnsOk. The test also checks the returned evidence (fn[helper]has a hash) or!result.real.requests.len() == 6shows the final submission was accepted and ended the run. - Extra checks.
finish_searchwas called 3 times, and 2 submissions failed. The skippedhabeascall never recordedfn[untouched].
Minor limitations that I do not treat as gaps:
- The first rejection happens with accompanying calls in the same response, not as a standalone submit with two outstanding searches. It uses the same outstanding-search check and message, and the example does not exclude accompanying calls.
- The test does not assert directly which of the two searches is the empty one. The
ast_grepcall forabsent()is by construction the empty one, and the order and identity of the UUIDs are checked.
The example’s outcomes are each asserted, so I judge the test adequate.
Inputs
Tests
Input 2: outline src/authoring/mod.rs mod[tests]/fn[every_submission_kind_waits_for_all_searches_and_can_recover]
- File:
src/authoring/mod.rs - Selector:
mod[tests]/fn[every_submission_kind_waits_for_all_searches_and_can_recover] - Kind:
fn src/authoring/mod.rs:2735–2855
// {test}`requirements.authoring.submission.searches`
// {test}`requirements.authoring.submission.searches.diagnostic`
// {test}`requirements.authoring.submission.searches.recovery`
// {test}`requirements.authoring.submission.searches.accompanying_calls`
// {test}`requirements.authoring.finish_search.inputs`
// {test}`requirements.authoring.search_accounting.recovery`
#[tokio::test]
async fn every_submission_kind_waits_for_all_searches_and_can_recover() {
use SearchAction::{Call, Finish};
for submit in ["submit_judgment", "submit_verification"] {
let root = inputs::tests::project();
fs::write(
root.path().join("src/lib.rs"),
"fn helper() { assert!(true); }\nfn untouched() {}\n",
)
.unwrap();
let mut sources =
AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let state = tempfile::tempdir().unwrap();
let mut usage =
UsageLog::start(state.path(), root.path(), &sources.subject_name).unwrap();
let arguments = if submit == "submit_judgment" {
json!({"determination":true,"rationale":"Helper checks its assertion."})
} else {
json!({"real":false,"acknowledged":false,"acknowledgments":[],
"rationale":"Helper checks its assertion."})
};
let provider = SearchProvider {
submit,
turns: vec![
vec![
Call("ripgrep", json!({"pattern":"assert","path":"src/lib.rs"})),
Call(
"ast_grep",
json!({"language":"rust","rule":{"rule":{"pattern":"absent()"}}}),
),
],
// Accompanying completion is skipped, so both IDs remain open.
vec![
Finish(0, vec!["1"]),
Call(
"habeas",
json!({"file":"src/lib.rs","item":"fn[untouched]"}),
),
Call("ripgrep", json!({"pattern":"absent","path":"src/lib.rs"})),
Call(submit, arguments.clone()),
],
vec![Finish(0, vec!["1"])],
vec![Call(submit, arguments.clone())],
vec![Finish(1, vec![])],
vec![Call(submit, arguments)],
],
requests: RefCell::default(),
};
if submit == "submit_judgment" {
let (_, evidence) = assess(&provider, &mut sources, &mut usage).await.unwrap();
assert!(
evidence["inputs"]
.as_array()
.unwrap()
.iter()
.any(|input| input["item"] == "fn[helper]" && input.get("hash").is_some())
);
} else {
let result = verify(
&provider,
&mut sources,
&mut usage,
&Judgment::False,
"Alleged gap",
)
.await
.unwrap();
assert!(!result.real);
}
let requests = provider.requests.borrow();
assert_eq!(requests.len(), 6);
let mut searches = Vec::new();
delivered_searches(&requests[1], &mut searches);
assert_eq!(searches.len(), 2);
let blocked = requests[2].as_array().unwrap().last().unwrap().to_string();
assert!(blocked.contains("not run: the response also made a submission"));
assert!(blocked.contains(searches[0]["search_id"].as_str().unwrap()));
assert!(blocked.contains(searches[1]["search_id"].as_str().unwrap()));
assert!(blocked.contains("Call finish_search for every listed search_id"));
assert!(blocked.contains("then resubmit"));
let latest = requests[4].as_array().unwrap().last().unwrap().to_string();
assert!(latest.contains("outstanding searches"));
assert!(!latest.contains(searches[0]["search_id"].as_str().unwrap()));
assert!(latest.contains(searches[1]["search_id"].as_str().unwrap()));
assert_eq!(
sources
.recorded_inputs()
.iter()
.filter(|input| input["item"] == "fn[helper]")
.count(),
1
);
let log: Value =
serde_json::from_str(&fs::read_to_string(&usage.path).unwrap()).unwrap();
assert_eq!(log["tool_calls"]["finish_search"], 3);
assert_eq!(log["tool_skipped"]["finish_search"], 1);
assert_eq!(log["tool_skipped"]["habeas"], 1);
assert_eq!(log["tool_skipped"]["ripgrep"], 1);
assert!(
!sources
.recorded_inputs()
.iter()
.any(|input| input["item"] == "fn[untouched]")
);
assert_eq!(
log["tool_failures"]
.as_object()
.unwrap()
.values()
.filter_map(Value::as_u64)
.sum::<u64>(),
2
);
}
}
Other sources
Input 1: requirements selection requirements.authoring.search_accounting.recovery
requirements.authoring.search_accounting.recovery:md/requirements/authoring.md:1080–1087
:::{example} search_accounting.recovery
Two search results remain outstanding; one has no matches. Submission MUST
return an error naming both UUIDs. Finishing only the first MUST leave
submission rejected with the second UUID. Finishing the empty search with
`used: []` MUST permit an otherwise valid subsequent submission.
{test}`requirements.authoring.submission.searches`
{test}`requirements.authoring.submission.searches.recovery`
:::
Input 3: 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));
}
}
Input 4: outline src/authoring/mod.rs mod[tests]/struct[SearchProvider]
- File:
src/authoring/mod.rs - Selector:
mod[tests]/struct[SearchProvider] - Kind:
struct src/authoring/mod.rs:2647–2651
struct SearchProvider {
submit: &'static str,
turns: Vec<Vec<SearchAction>>,
requests: RefCell<Vec<Value>>,
}
Input 5: outline src/authoring/mod.rs mod[tests]/fn[delivered_searches]
- File:
src/authoring/mod.rs - Selector:
mod[tests]/fn[delivered_searches] - Kind:
fn src/authoring/mod.rs:2653–2676
fn delivered_searches(value: &Value, results: &mut Vec<Value>) {
match value {
Value::Object(object) => {
if object.contains_key("search_id") && object.contains_key("matches") {
results.push(value.clone());
} else {
for value in object.values() {
delivered_searches(value, results);
}
}
}
Value::Array(array) => {
for value in array {
delivered_searches(value, results);
}
}
Value::String(text) => {
if let Ok(value) = serde_json::from_str::<Value>(text) {
delivered_searches(&value, results);
}
}
_ => {}
}
}