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.search_accounting.outstanding

Requirements index · View definition

evidence Valid

Requirement

A successfully delivered search result MUST become outstanding, including a result with no matches, and remain outstanding until accepted by finish_search. Failed searches and undelivered results MUST NOT create outstanding searches.

Rationale

The tests cover each obligation in requirements.authoring.search_accounting.outstanding.

Obligations

  1. A successfully delivered search becomes outstanding. This includes a result with no matches.
  2. A search stays outstanding until finish_search accepts it.
  3. Failed searches create no outstanding search.
  4. Undelivered results create no outstanding search.

Mapping to tests

  • Delivered searches become outstanding, including empty ones.

    • src/authoring/searches.rs#mod[tests]/fn[delivered_searches_including_empty_results_need_explicit_completion] runs a search that matches (fn), a search with no matches (absent, which asserts matches == []), and a repeat search.
    • It asserts outstanding_searches().len() == 3, so the empty result is counted.
    • The same test runs empty ripgrep and ast_grep searches through dispatch_paged and checks that each returns a result with a UUID.
    • src/authoring/pages.rs#mod[tests]/fn[search_pages_are_accounted_only_when_delivered_and_replay_stays_closed] asserts that outstanding_searches() equals exactly the first page’s search_id for both ripgrep and ast_grep.
  • A search stays outstanding until finish_search accepts it.

    • In the pages test, two finish_search calls fail: one with the undelivered page’s id, and one with the first page’s id and a tag from the undelivered page.
    • The test then delivers the second page and asserts that 2 searches are outstanding. The first one therefore survived the rejected finishes.
    • After the second page is finished, only the first search remains outstanding. After the first search is finished, none remain.
    • In the searches test, the three results stay outstanding until each is finished, and the set is then empty.
    • invalid_completion_is_atomic_and_can_be_corrected and selected_dependencies_keep_the_delivered_hash_and_accumulate_without_reads also check this for invalid finishes. Neither carries a {test} reference to this requirement, so I did not rely on them.
    • Calling finish_search on a fresh ResultPages fails with “delivered in this assessment”.
  • Failed searches create nothing. The searches test runs ripgrep with the invalid regex ( and asserts that dispatch_paged returns an error and outstanding_searches() is empty.

    • Only ripgrep is tested as a failing search. ast_grep failures go through the same dispatch_paged path, and the requirement does not distinguish tools.
  • Undelivered results create nothing. The pages test reads the held next page (pages.pages[&token]) before delivery. The outstanding set equals only the first page’s id at that point, and finish_search on the undelivered page’s id is rejected. Delivering it through next_page then raises the count to 2.

The assertions check the actual outstanding set, not just that the code ran. The implementation in src/authoring/searches.rs (Searches::outstanding, delivered, prepare) agrees with the tested behavior. I read it only to confirm which tool paths are involved, and I derived the expectations from the requirement text. I found no gap.

Inputs

Implementation

Input 5: outline src/authoring/searches.rs impl[Searches]/fn[delivered]
    // {impl}`requirements.authoring.search_accounting.outstanding`
    // {impl}`requirements.authoring.search_accounting.page_replay`
    pub(super) fn delivered(&mut self, result: &Value) {
        if let Some(id) = result.get("search_id").and_then(Value::as_str) {
            let id = Uuid::parse_str(id).expect("prepared search UUID");
            self.results
                .get_mut(&id)
                .expect("prepared search")
                .delivered = true;
            self.delivered_any = true;
        }
    }

Tests

Input 2: outline src/authoring/pages.rs mod[tests]/fn[search_pages_are_accounted_only_when_delivered_and_replay_stays_closed]
  • File: src/authoring/pages.rs
  • Selector: mod[tests]/fn[search_pages_are_accounted_only_when_delivered_and_replay_stays_closed]
  • Kind: fn
  • src/authoring/pages.rs:662–738
    // {test}`requirements.authoring.search_accounting.pagination`
    // {test}`requirements.authoring.search_accounting.page_replay`
    // {test}`requirements.authoring.search_accounting.outstanding`
    // {test}`requirements.authoring.search_accounting.entry_tags`
    // {test}`requirements.authoring.search_accounting.result_ids`
    // {test}`requirements.authoring.search_accounting.instructions`
    // {test}`requirements.authoring.finish_search.completion`
    // {test}`requirements.authoring.finish_search.invalid`
    // {test}`requirements.authoring.result_pages`
    #[test]
    fn search_pages_are_accounted_only_when_delivered_and_replay_stays_closed() {
        let root = project();
        let source: String = (0..600)
            .map(|i| format!("fn needle_{i:04}() {{ let marker = 1; }}\n"))
            .collect();
        fs::write(root.path().join("src/lib.rs"), source).unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for (tool, arguments) in [
            ("ripgrep", json!({"pattern":"marker","path":"src/lib.rs"})),
            (
                "ast_grep",
                json!({"language":"rust","rule":{"rule":{"pattern":"let marker = 1;"}}}),
            ),
        ] {
            let mut pages = ResultPages::default();
            let first = dispatch_paged(&sources, &mut pages, tool, &arguments)
                .unwrap()
                .result;
            let token = first["page"]["next"].as_str().unwrap().to_owned();
            assert_eq!(
                first["instructions"],
                super::super::approved_text("search_accounting.instructions", 0)
            );
            uuid::Uuid::parse_str(first["search_id"].as_str().unwrap()).unwrap();
            assert_eq!(
                pages.outstanding_searches(),
                [first["search_id"].as_str().unwrap()]
            );
            let undelivered = pages.pages[&token].0.clone();
            assert!(
                pages
                    .finish_search(&json!({"search_id":undelivered["search_id"],"used":[]}))
                    .is_err()
            );
            assert!(
                pages
                    .finish_search(&json!({"search_id":first["search_id"],
                "used":[undelivered["matches"][0]["tag"]]}))
                    .is_err()
            );
            let second = pages.next_page(&token).unwrap().result;
            uuid::Uuid::parse_str(second["search_id"].as_str().unwrap()).unwrap();
            assert_eq!(second, undelivered);
            assert_ne!(first["search_id"], second["search_id"]);
            assert!(second.get("instructions").is_none());
            assert_eq!(pages.outstanding_searches().len(), 2);
            let finished = pages
                .finish_search(&json!({"search_id":second["search_id"],
                "used":[second["matches"][0]["tag"]]}))
                .unwrap();
            assert_eq!(finished.inputs.len(), 1);
            assert_eq!(finished.inputs[0]["item"], second["matches"][0]["item"]);
            let replay = pages.next_page(&token).unwrap().result;
            assert_eq!(replay, second);
            assert_eq!(
                pages.outstanding_searches(),
                [first["search_id"].as_str().unwrap()]
            );
            pages
                .finish_search(&json!({"search_id":first["search_id"],"used":[]}))
                .unwrap();
            assert!(pages.outstanding_searches().is_empty());
            assert!(sources.recorded_inputs().is_empty());
            assert!(first.to_string().len() <= PAGE_LIMIT);
            assert!(second.to_string().len() <= PAGE_LIMIT);
        }
    }
Input 3: outline src/authoring/searches.rs mod[tests]/fn[delivered_searches_including_empty_results_need_explicit_completion]
    // {test}`requirements.authoring.search_accounting.result_ids`
    // {test}`requirements.authoring.search_accounting.entry_tags`
    // {test}`requirements.authoring.search_accounting.outstanding`
    // {test}`requirements.authoring.search_accounting.instructions`
    // {test}`requirements.authoring.finish_search.empty`
    // {test}`requirements.authoring.finish_search.invalid`
    // {test}`requirements.authoring.finish_search`
    #[test]
    fn delivered_searches_including_empty_results_need_explicit_completion() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn first() {}\nfn second() {}\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let mut pages = ResultPages::default();
        assert!(dispatch_paged(&sources, &mut pages, "ripgrep", &json!({"pattern":"("})).is_err());
        assert!(pages.outstanding_searches().is_empty());
        let first = search(&sources, &mut pages, "fn");
        assert_eq!(
            first["instructions"],
            super::super::approved_text("search_accounting.instructions", 0)
        );
        let tags: Vec<_> = first["matches"]
            .as_array()
            .unwrap()
            .iter()
            .map(|entry| entry["tag"].as_str().unwrap())
            .collect();
        assert_eq!(tags, ["1", "2"]);
        for entry in first["matches"].as_array().unwrap() {
            assert!(entry.get("hash").is_none());
        }
        let empty = search(&sources, &mut pages, "absent");
        assert_eq!(empty["matches"], json!([]));
        assert!(empty.get("instructions").is_none());
        let repeated = search(&sources, &mut pages, "fn");
        assert!(repeated.get("instructions").is_none());
        let ids = [&first, &empty, &repeated]
            .map(|result| Uuid::parse_str(result["search_id"].as_str().unwrap()).unwrap());
        assert_eq!(
            ids.into_iter()
                .collect::<std::collections::BTreeSet<_>>()
                .len(),
            3
        );
        assert_eq!(pages.outstanding_searches().len(), 3);
        let mut other = ResultPages::default();
        let error = other
            .finish_search(&json!({"search_id":first["search_id"],"used":[]}))
            .err()
            .unwrap()
            .to_string();
        assert!(error.contains("delivered in this assessment"), "{error}");
        for result in [&first, &empty, &repeated] {
            let finished = pages
                .finish_search(&json!({"search_id":result["search_id"],"used":[]}))
                .unwrap();
            assert!(finished.inputs.is_empty());
            assert_eq!(
                finished.result,
                json!({"search_id":result["search_id"],"finished":true})
            );
        }
        assert!(pages.outstanding_searches().is_empty());
        assert!(sources.recorded_inputs().is_empty());
        for (tool, args) in [
            ("ripgrep", json!({"pattern":"absent","path":"src/lib.rs"})),
            (
                "ast_grep",
                json!({"language":"rust","rule":{"rule":{"pattern":"absent()"}}}),
            ),
        ] {
            let mut fresh = ResultPages::default();
            let result = dispatch_paged(&sources, &mut fresh, tool, &args)
                .unwrap()
                .result;
            assert_eq!(result["matches"], json!([]));
            assert_eq!(
                result["instructions"],
                super::super::approved_text("search_accounting.instructions", 0)
            );
            Uuid::parse_str(result["search_id"].as_str().unwrap()).unwrap();
            let again = dispatch_paged(&sources, &mut fresh, tool, &args)
                .unwrap()
                .result;
            assert_ne!(result["search_id"], again["search_id"]);
        }
    }

Other sources

Input 1: requirements selection requirements.authoring.search_accounting.outstanding
:::{req} search_accounting.outstanding
A successfully delivered search result MUST become outstanding, including
a result with no matches, and remain outstanding until accepted by
`finish_search`. Failed searches and undelivered results MUST NOT create
outstanding searches.
:::
Input 4: outline src/authoring/searches.rs impl[Searches]/fn[prepare]
    /// Assigns an identity and retains hashes from the already-parsed source.
    /// Preparing an undelivered page does not make its search outstanding.
    // {impl}`requirements.authoring.search_accounting.result_ids`
    // {impl}`requirements.authoring.finish_search.snapshot`
    pub(super) fn prepare(
        &mut self,
        sources: &AssessmentSources,
        result: &mut Value,
    ) -> io::Result<()> {
        let Some(matches) = result.get("matches").and_then(Value::as_array) else {
            return Ok(());
        };
        let mut inputs = BTreeMap::new();
        for entry in matches {
            let file = entry["file"].as_str().expect("search file");
            let item = entry["item"].as_str().expect("search item");
            // Search construction already checked access and populated this
            // assessment's immutable outline cache. No model read is needed.
            let parsed = sources.outlines.parse(&sources.root, file);
            let parsed = parsed
                .as_ref()
                .as_ref()
                .map_err(|error| io::Error::other(error.clone()))?;
            let index = parsed.resolve(file, item).map_err(io::Error::other)?;
            inputs.insert(
                entry["tag"].as_str().expect("search tag").to_owned(),
                json!({"file": file, "item": item,
                    "hash": parsed.outline.nodes[index].structural_hash}),
            );
        }
        let id = loop {
            let id = Uuid::new_v4();
            if !self.results.contains_key(&id) {
                break id;
            }
        };
        result["search_id"] = json!(id.to_string());
        self.results.insert(
            id,
            SearchResult {
                inputs,
                delivered: false,
                finished: false,
            },
        );
        Ok(())
    }
Input 6: outline src/authoring/searches.rs impl[Searches]/fn[outstanding]
    // {impl}`requirements.authoring.submission.searches.diagnostic`
    pub(super) fn outstanding(&self) -> Vec<String> {
        self.results
            .iter()
            .filter(|(_, result)| result.delivered && !result.finished)
            .map(|(id, _)| id.to_string())
            .collect()
    }