Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.authoring.submission.searches.recovery

Requirements index · View definition

evidence Valid

Requirement

An outstanding-search rejection MUST leave the assessment open for the model to finish its searches and submit again. It MUST NOT accept a judgment or publish evidence.

Rationale

The reviewed test adequately checks requirements.authoring.submission.searches.recovery.

Obligations derived from the text

  1. A rejection for outstanding searches leaves the assessment open, so the model can finish its searches and submit again.
  2. The rejected submission is not accepted as a judgment.
  3. The rejected submission does not publish evidence.
  4. The linked example requirements.authoring.search_accounting.recovery adds three checks:
    • The error names both UUIDs.
    • After only the first search is finished, the rejection names only the second UUID.
    • Finishing the empty search with used: [] allows an otherwise valid submission.

Test: src/authoring/mod.rs#mod[tests]/fn[every_submission_kind_waits_for_all_searches_and_can_recover]. It is marked {test} for the subject and for the example. It runs once for submit_judgment and once for submit_verification, driving assess or verify with the scripted SearchProvider.

The scripted turns are:

  • Turn 0: two searches are delivered. One is a ripgrep search with matches. The other is an ast_grep search with no matches.
  • Turn 1: the model sends Finish(0), a habeas read, a ripgrep call and the submission in one response. The submission is rejected, and the other calls are reported as “not run”.
  • Turn 2: the model finishes search 0.
  • Turn 3: the model submits alone and is rejected again.
  • Turn 4: the model finishes the empty search with used: [].
  • Turn 5: the model submits and the call succeeds.

The scripted submissions map to the obligations as follows:

  • Assessment stays open: the conversation continues through six requests. assert_eq!(requests.len(), 6) would fail if the first or second submission had been accepted and the conversation ended early. assess and verify also unwrap() successfully only at the end.
  • Error names both UUIDs: the last tool result in requests[2] is the submission’s rejection. The test asserts that it contains both search_ids and the text “Call finish_search for every listed search_id” and “then resubmit”.
  • Partial completion: requests[4] is the rejection after only search 0 was finished. The test asserts that it contains “outstanding searches” and the second UUID but not the first.
  • Empty search finished with used: []: Finish(1, vec![]) is followed by a successful final submission.
  • Not accepted: assess returns Ok only after the last turn, and verify returns a result with real == false. The usage log counts finish_search calls (3) and skipped tools. The failure total of 2 covers exactly the two rejected submissions.
  • No evidence published from the rejected attempts: the skipped read of fn[untouched] is never recorded in recorded_inputs(). fn[helper] is recorded exactly once, and the evidence contains it only after the final accepted submission. In converse, rejection takes the continue path with no record or return of a result.

Both submission kinds are covered. Both rejection shapes are covered: submit alongside other calls, and submit alone. Partial and full completion are both covered.

I found no unaddressed obligation, and the supplied acknowledgments list is empty, so none applies. The {test} references on the test are in place, so there is no marking gap.

Inputs

Implementation

Input 7: outline src/authoring/mod.rs fn[converse]
/// 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: requirements selection requirements.authoring.search_accounting.recovery
:::{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 mod[tests]/fn[every_submission_kind_waits_for_all_searches_and_can_recover]
    // {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.submission.searches.recovery
:::{req} submission.searches.recovery
An outstanding-search rejection MUST leave the assessment open for the model
to finish its searches and submit again. It MUST NOT accept a judgment or
publish evidence.
:::
Input 4: outline src/authoring/mod.rs mod[tests]/struct[SearchProvider]
    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]
    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);
                }
            }
            _ => {}
        }
    }
Input 6: outline src/authoring/mod.rs mod[tests]/impl[SearchProvider/CompletionProvider]
    impl CompletionProvider for SearchProvider {
        async fn complete(&self, request: CompletionRequest) -> io::Result<CompletionResponse> {
            let history = serde_json::to_value(&request.chat_history).unwrap();
            let turn = self.requests.borrow().len();
            self.requests.borrow_mut().push(history.clone());
            if self.turns[turn].is_empty() {
                return Ok(CompletionResponse::new(
                    vec![AssistantContent::text("The review is complete.")],
                    Usage::default(),
                    Origin::new("fixture", "fixture", "fixture"),
                    Value::Null,
                ));
            }
            let mut searches = Vec::new();
            delivered_searches(&history, &mut searches);
            let calls = self.turns[turn]
                .iter()
                .enumerate()
                .map(|(index, action)| {
                    let (name, arguments) = match action {
                        SearchAction::Call(name, arguments) => (*name, arguments.clone()),
                        SearchAction::Finish(index, used) => (
                            "finish_search",
                            json!({"search_id":searches[*index]["search_id"],"used":used}),
                        ),
                        SearchAction::RetainRejected => {
                            let text = history.to_string();
                            let captures =
                                regex::Regex::new(r"rationale set to exactly ([0-9a-f-]{36})")
                                    .unwrap()
                                    .captures_iter(&text)
                                    .last()
                                    .unwrap()
                                    .get(1)
                                    .unwrap();
                            (
                                self.submit,
                                json!({"determination":true,"rationale":captures.as_str()}),
                            )
                        }
                    };
                    AssistantContent::ToolCall(ToolCall::from_wire(
                        format!("search-{turn}-{index}"),
                        ToolFunction::new(ToolName::new(name).unwrap(), arguments),
                    ))
                })
                .collect();
            Ok(CompletionResponse::new(
                calls,
                Usage::default(),
                Origin::new("fixture", "fixture", "fixture"),
                Value::Null,
            )
            .with_finish_reason(FinishReason::ToolCalls))
        }
    }