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.finish_search.repetition

Requirements index · View definition

evidence Valid

Requirement

Repeated valid calls for a finished search MUST retain previously recorded dependencies and add dependencies for newly selected tags.

Rationale

The requirement requirements.authoring.finish_search.repetition has two obligations. Repeated valid finish_search calls for the same search must keep the dependencies already recorded. They must also add dependencies for newly selected tags.

The marked test src/authoring/searches.rs#mod[tests]/fn[selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads] covers both:

  • Setup: it runs one search that delivers two items, fn[first] and fn[second].
  • First call: used:["1","1"] returns only fn[first], and recording it leaves one recorded input.
  • Adding new tags: a second call on the same, already finished search_id with used:["2"] returns exactly fn[second]. After recording it, recorded_inputs() has two entries.
  • Retaining earlier dependencies: a third call repeats used:["2"], and a fourth uses used:[]. Both succeed. A separate habeas read of the same item is also recorded. The test then asserts that the recorded inputs are still exactly two, fn[first] followed by fn[second]. This shows the first dependency survives later calls and nothing is duplicated.
  • Real recording path: record_inputs in src/authoring/inputs.rs appends only inputs not already present. converse in src/authoring/mod.rs calls sources.record_inputs(&delivery.inputs) after each finish_search result. The test therefore exercises the same path as production.

The related edge case of a failed call is covered by the separate test invalid_completion_is_atomic_and_can_be_corrected, which is outside this requirement’s “valid calls” scope. I found no gap, and there are no acknowledgments.

Inputs

Tests

Input 2: outline src/authoring/searches.rs mod[tests]/fn[selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads]
  • File: src/authoring/searches.rs
  • Selector: mod[tests]/fn[selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads]
  • Kind: fn
  • src/authoring/searches.rs:269–353
    // {test}`requirements.authoring.finish_search.completion`
    // {test}`requirements.authoring.finish_search.no_additional_source`
    // {test}`requirements.authoring.finish_search.inputs`
    // {test}`requirements.authoring.finish_search.snapshot`
    // {test}`requirements.authoring.finish_search.unselected`
    // {test}`requirements.authoring.finish_search.deduplication`
    // {test}`requirements.authoring.finish_search.repetition`
    // {test}`requirements.authoring.delivered_inputs`
    // {test}`requirements.authoring.finish_search`
    #[test]
    fn selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn first() { assert!(true); }\nfn second() {}\n",
        )
        .unwrap();
        let mut sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mut pages = ResultPages::default();
        let result = search(&sources, &mut pages, "fn");
        let original =
            crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[first]").unwrap();
        // Mutation after delivery must not silently substitute a new hash.
        fs::write(
            root.path().join("src/lib.rs"),
            "fn first() {}\nfn second() {}\n",
        )
        .unwrap();
        let finish = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":["1","1"]}))
            .unwrap();
        assert_eq!(finish.inputs, [original]);
        assert_eq!(
            finish.result,
            json!({"search_id":result["search_id"],"finished":true})
        );
        assert!(finish.result.get("text").is_none());
        assert!(pages.outstanding_searches().is_empty());
        sources.record_inputs(&finish.inputs);
        assert_eq!(sources.recorded_inputs().len(), 1);
        assert_eq!(sources.recorded_inputs()[0]["item"], "fn[first]");
        let mut errors = Vec::new();
        crate::evidence::validate_input(
            root.path(),
            &BTreeMap::new(),
            &crate::inputs::OutlineCache::default(),
            &finish.inputs[0],
            "selected",
            &mut errors,
        );
        assert!(
            errors.iter().any(|error| error.contains("hash")),
            "{errors:?}"
        );

        let second = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":["2"]}))
            .unwrap();
        assert_eq!(
            second.inputs,
            [crate::inputs::outline_input(root.path(), "src/lib.rs", "fn[second]").unwrap()]
        );
        sources.record_inputs(&second.inputs);
        assert_eq!(sources.recorded_inputs().len(), 2);
        // A separately read item can be included harmlessly, or omitted.
        let read = dispatch_paged(
            &sources,
            &mut pages,
            "habeas",
            &json!({"file":"src/lib.rs","item":"fn[second]"}),
        )
        .unwrap();
        sources.record_inputs(&read.inputs);
        let repeated = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":["2"]}))
            .unwrap();
        sources.record_inputs(&repeated.inputs);
        let empty = pages
            .finish_search(&json!({"search_id":result["search_id"],"used":[]}))
            .unwrap();
        sources.record_inputs(&empty.inputs);
        assert_eq!(sources.recorded_inputs().len(), 2);
        assert_eq!(sources.recorded_inputs()[0]["item"], "fn[first]");
        assert_eq!(sources.recorded_inputs()[1]["item"], "fn[second]");
    }

Other sources

Input 1: requirements selection requirements.authoring.finish_search.repetition
:::{req} finish_search.repetition
Repeated valid calls for a finished search MUST retain previously recorded dependencies
and add dependencies for newly selected tags.
:::
Input 3: outline src/authoring/inputs.rs impl[AssessmentSources]/fn[record_inputs]
    // {impl}`requirements.authoring.delivered_inputs`
    // {impl}`requirements.ci.outline_inputs`
    pub(crate) fn record_inputs(&mut self, inputs: &[Value]) {
        // A built-in's fixed text is supplied to the model but is not an
        // evidence input form.
        for input in inputs.iter().filter(|input| input.get("builtin").is_none()) {
            let input = recorded_input(input);
            if !self.recorded.contains(&input) {
                self.recorded.push(input);
            }
        }
    }
Input 4: 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));
    }
}