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.usage_requests.failures

Requirements index · View definition

evidence Valid

Requirement

Usage MUST record, for each failed provider request, its HTTP status and provider error code when the provider reports them, and whether the harness retried it. It MUST NOT record the failure’s message text.

Rationale

The reviewed tests adequately check requirements.authoring.usage_requests.failures.

Obligations derived from the text

  1. For each failed provider request, usage records the HTTP status when the provider reports it.
  2. It records the provider error code when the provider reports it.
  3. It records whether the harness retried the request.
  4. It does not record the failure’s message text.

Test mapping

  • Status, code and retried=true, end to end. src/authoring/mod.rs#mod[tests]/fn[throttled_requests_retry_unchanged_and_record_every_attempt] has ThrottledProvider fail five requests with status 429 and code ThrottlingException.
    • Each failing request’s persisted failure value must equal {"http_status":429,"error_code":"ThrottlingException","retried":true}.
    • The final successful request must have no failure key.
    • This covers status, code and retried=true through the real retry loop and the persisted log.
  • Message text excluded. The same test’s provider error is built from the body “Too many tokens”. The exact-equality assertion on the failure object would fail if that message, or any other field, were recorded there. src/authoring/usage.rs#mod[tests]/fn[failed_submission_can_be_confirmed_on_a_later_attempt] makes the same exact-equality check. It also notes that no message text is recorded.
  • retried=false and the later flip to true. The same usage test records a failure through end_request and asserts retried:false. It then calls retried() and asserts retried becomes true. This covers the not-retried state and the transition.
  • Extraction of the codes. src/authoring/providers.rs#mod[tests]/fn[failure_codes_are_the_status_and_code_a_provider_reports] covers three cases.
    • A provider error with status and code returns both.
    • A plain io::Error returns (None, None).
    • A TimedOut error returns (None, None).
    • Together these cover the “when the provider reports them” condition, both reported and not reported.
  • Unmarked supporting test. mod.rs#mod[tests]/fn[permanent_provider_failure_returns_without_waiting_or_retrying] also asserts a 400/ValidationException failure recorded with retried:false end to end. It carries no {test} reference to this requirement. The marked tests already cover that state, so this is only a marking nicety and not a gap.

Residual considerations (not gaps)

  • No test persists a failure whose status and code are both unreported. The text only requires recording them “when the provider reports them”. The path from failure_codes through end_request has no branch that depends on whether codes are present. Absent values serialize as Option::None.
  • The no-message check asserts on the failure object rather than scanning the whole log. The text’s obligation concerns the failure record, and the exact-equality assertion enforces it.

No unacknowledged gap was found.

Inputs

Implementation

Input 6: outline src/authoring/usage.rs struct[RequestFailure]
/// What usage records of a failed request.
// {impl}`requirements.authoring.usage_requests.failures`
#[derive(Serialize)]
struct RequestFailure {
    http_status: Option<u16>,
    error_code: Option<String>,
    retried: bool,
}
Input 8: outline src/authoring/usage.rs impl[UsageLog]/fn[retried]
    /// Records that a failed request is being retried.
    // {impl}`requirements.authoring.usage_requests.failures`
    pub(super) fn retried(&mut self, index: usize) -> io::Result<()> {
        if let Some(failure) = &mut self.record.requests[index].failure {
            failure.retried = true;
        }
        self.save()
    }

Tests

Input 2: outline src/authoring/mod.rs mod[tests]/fn[throttled_requests_retry_unchanged_and_record_every_attempt]
    // {test}`requirements.authoring.provider_backoff`
    // {test}`requirements.authoring.usage_requests`
    // {test}`requirements.authoring.usage_requests.failures`
    // {test}`requirements.authoring.usage_inputs`
    // {test}`requirements.ci.reference_set`
    #[tokio::test(start_paused = true)]
    async fn throttled_requests_retry_unchanged_and_record_every_attempt() {
        let (_project, _state, mut sources, mut usage) = retry_fixture();
        let provider = ThrottledProvider {
            failures: 5,
            status: 429,
            code: "ThrottlingException",
            requests: RefCell::default(),
        };
        let started = tokio::time::Instant::now();
        let (_, record) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        assert!(started.elapsed() >= Duration::from_millis(500));
        let requests = provider.requests.borrow();
        assert_eq!(requests.len(), 6);
        assert!(requests.iter().all(|request| request == &requests[0]));
        assert_eq!(record["inputs"], json!(sources.mandatory_inputs()));
        assert_eq!(record["references"], json!(sources.reference_set));

        let log: Value = serde_json::from_slice(&fs::read(&usage.path).unwrap()).unwrap();
        assert_eq!(log["request_count"], 6);
        for attempt in 0..5 {
            assert_eq!(log["requests"][attempt]["outcome"], "failed");
            assert_eq!(log["requests"][attempt]["tokens"]["complete"], false);
            assert_eq!(
                log["requests"][attempt]["failure"],
                json!({"http_status": 429, "error_code": "ThrottlingException", "retried": true})
            );
        }
        assert!(log["requests"][5].get("failure").is_none());
        assert_eq!(log["requests"][5]["outcome"], "completed");
        assert_eq!(log["tool_calls"]["submit_judgment"], 1);
        for input in log["inputs"].as_array().unwrap() {
            assert_eq!(input["submitted_in_request"], 0);
            assert_eq!(input["sent_in_request"], 5);
        }
    }
Input 3: outline src/authoring/providers.rs mod[tests]/fn[failure_codes_are_the_status_and_code_a_provider_reports]
    // {test}`requirements.authoring.usage_requests.failures`
    #[test]
    fn failure_codes_are_the_status_and_code_a_provider_reports() {
        assert_eq!(
            failure_codes(&io::Error::other(provider_error(
                Some(429),
                Some("ThrottlingException")
            ))),
            (Some(429), Some("ThrottlingException".to_owned()))
        );
        assert_eq!(failure_codes(&io::Error::other("plain")), (None, None));
        assert_eq!(
            failure_codes(&io::Error::new(io::ErrorKind::TimedOut, "no response")),
            (None, None)
        );
    }
Input 4: outline src/authoring/usage.rs mod[tests]/fn[failed_submission_can_be_confirmed_on_a_later_attempt]
    // {test}`requirements.authoring.usage_inputs`
    // {test}`requirements.authoring.usage_requests`
    // {test}`requirements.authoring.usage_requests.failures`
    #[test]
    fn failed_submission_can_be_confirmed_on_a_later_attempt() {
        let state = tempfile::tempdir().unwrap();
        let mut log =
            UsageLog::start(state.path(), Path::new("/project"), "requirements.case").unwrap();
        log.prepared(
            "mandatory",
            &[json!({"file": "source", "text": ["source content"]})],
        );
        let first = log.begin_request().unwrap();
        log.end_request(
            first,
            2,
            None,
            Some((Some(429), Some("ThrottlingException".to_owned()))),
        )
        .unwrap();
        assert!(persisted(&log)["inputs"][0]["sent_in_request"].is_null());
        // A failed request records its status, code, and retry, but no
        // message text.
        assert_eq!(
            persisted(&log)["requests"][first]["failure"],
            json!({"http_status": 429, "error_code": "ThrottlingException", "retried": false})
        );
        log.retried(first).unwrap();
        assert_eq!(
            persisted(&log)["requests"][first]["failure"]["retried"],
            true
        );
        let retry = log.begin_request().unwrap();
        log.end_request(retry, 3, Some(&Usage::new()), None)
            .unwrap();
        let value = persisted(&log);
        assert_eq!(value["inputs"][0]["submitted_in_request"], first);
        assert_eq!(value["inputs"][0]["sent_in_request"], retry);
        assert_eq!(value["request_count"], 2);
    }

Other sources

Input 1: requirements selection requirements.authoring.usage_requests.failures
:::{req} usage_requests.failures
Usage MUST record, for each failed provider request, its HTTP status and
provider error code when the provider reports them, and whether the harness
retried it. It MUST NOT record the failure's message text.
:::
Input 5: outline src/authoring/mod.rs mod[tests]/fn[permanent_provider_failure_returns_without_waiting_or_retrying]
    // {test}`requirements.authoring.provider_backoff`
    #[tokio::test(start_paused = true)]
    async fn permanent_provider_failure_returns_without_waiting_or_retrying() {
        let (_project, _state, mut sources, mut usage) = retry_fixture();
        let provider = ThrottledProvider {
            failures: 8,
            status: 400,
            code: "ValidationException",
            requests: RefCell::default(),
        };
        let started = tokio::time::Instant::now();
        let error = assess(&provider, &mut sources, &mut usage)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("Too many tokens"));
        assert_eq!(started.elapsed(), Duration::ZERO);
        assert_eq!(provider.requests.borrow().len(), 1);
        // The failure is recorded as not retried.
        let log: Value = serde_json::from_slice(&fs::read(&usage.path).unwrap()).unwrap();
        assert_eq!(
            log["requests"][0]["failure"],
            json!({"http_status": 400, "error_code": "ValidationException", "retried": false})
        );
    }
Input 7: outline src/authoring/usage.rs impl[UsageLog]/fn[end_request]
    pub(super) fn end_request(
        &mut self,
        index: usize,
        elapsed: u128,
        usage: Option<&Usage>,
        failure: Option<(Option<u16>, Option<String>)>,
    ) -> io::Result<()> {
        let tokens = usage.map(TokenCounts::from_usage).unwrap_or_default();
        if usage.is_some() {
            for input in &mut self.record.inputs {
                if input.sent_in_request.is_none() && input.submitted_in_request.is_some() {
                    input.sent_in_request = Some(index);
                }
            }
        }
        self.record.requests[index] = RequestUsage {
            outcome: if usage.is_some() {
                "completed"
            } else {
                "failed"
            }
            .into(),
            elapsed_ms: elapsed,
            tokens,
            failure: failure.map(|(http_status, error_code)| RequestFailure {
                http_status,
                error_code,
                retried: false,
            }),
        };
        self.record.tokens = TokenCounts::sum(&self.record.requests);
        self.active_request = None;
        self.record.elapsed_ms = self.started.elapsed().as_millis();
        if let Some(finished) = self.first_request_finished.take() {
            finished();
        }
        self.save()
    }
Input 9: outline src/authoring/mod.rs mod[tests]/impl[ThrottledProvider/CompletionProvider]
    impl CompletionProvider for ThrottledProvider {
        // {cite}`habeas:util`
        async fn complete(&self, request: CompletionRequest) -> io::Result<CompletionResponse> {
            self.requests
                .borrow_mut()
                .push(serde_json::to_value(&request).unwrap());
            if self.requests.borrow().len() <= self.failures {
                return Err(io::Error::other(
                    rig_core::error::ProviderError::from_provider_body("Too many tokens")
                        .with_provider_status(Some(self.status.try_into().unwrap()))
                        .with_provider_code(Some(self.code.into())),
                ));
            }
            JudgmentProvider(json!(true)).complete(request).await
        }
    }
Input 10: outline src/authoring/providers.rs mod[tests]/fn[provider_error]
    // {cite}`habeas:util`
    fn provider_error(status: Option<u16>, code: Option<&str>) -> ProviderError {
        ProviderError::from_provider_body("Too many tokens")
            .with_provider_status(status.map(|status| status.try_into().unwrap()))
            .with_provider_code(code.map(str::to_owned))
    }