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.provider_backoff

Requirements index · View definition

evidence Valid

Requirement

When a provider reports a transient failure, the harness MUST wait and retry the same completion request. Transient failures are throttling, reported through HTTP 429 or a Bedrock ThrottlingException; temporary unavailability, reported through HTTP 500, 502, 503, or 504 or a Bedrock ServiceUnavailableException, InternalServerException, or ModelNotReadyException; and a request with no response after ten minutes, which the harness MUST abandon. The retry MUST retain its prompt, history, tools, and pending inputs. It MUST NOT restart the assessment or repeat already completed tool calls. A permanent input/context-length error, authentication failure, or invalid request MUST remain an error; mentioning tokens in an error message alone MUST NOT trigger retries.

The backoff window MUST start at one second and double after each consecutive transient failure, up to sixty seconds. Each delay MUST be randomly selected between half and all of that window to spread parallel retries. An available provider Retry-After value, in seconds or HTTP-date form, MUST be honored as a minimum delay even when longer than the window. A successful response MUST reset backoff for the next completion request, and interruption MUST cancel both the wait and further retries.

Each attempt MUST be recorded under cite requirements.authoring.usage_requests. Hidden SDK retries MUST remain disabled so the harness can account for attempts. Transient retries MUST NOT be reported as finished judgments or terminal assessment errors while recovery is still in progress. Pending inputs MUST be recorded as evidence only after the request succeeds. cite requirements.authoring.provider cite requirements.authoring.delivered_inputs

Rationale

I judge the tests adequate for requirements.authoring.provider_backoff. I did not read the implementation beyond a search for where interruption is handled.

Classification of transient and permanent failures

  • providers.rs#mod[tests]/fn[retries_throttling_unavailability_and_timeouts_but_not_permanent_errors] covers each listed trigger:
    • HTTP 429, 500, 502, 503 and 504.
    • The Bedrock codes ThrottlingException, ServiceUnavailableException, InternalServerException and ModelNotReadyException.
    • An io::ErrorKind::TimedOut error.
  • The same test asserts no retry for 400 ValidationException, 403 AccessDeniedException, 501 and an unclassified error. It also asserts no retry for an error message that only mentions tokens (“Too many tokens; HTTP 429”). This covers the clause that mentioning tokens alone MUST NOT trigger retries.
  • fn[transient_bedrock_codes_retry_whatever_their_http_status] checks that Bedrock transient codes retry regardless of HTTP status. It also checks that a transient status wins over a permanent code.
  • fn[rig_failures_keep_their_provider_report_for_backoff] checks that classification still works after the error passes through Rig’s failure type.
  • In mod.rs#mod[tests]/fn[permanent_provider_failure_returns_without_waiting_or_retrying], a 400 context-length-style error is returned as an error. There is exactly one request and no elapsed time, and the failure is recorded with retried: false.

Retry behavior

  • mod.rs#mod[tests]/fn[throttled_requests_retry_unchanged_and_record_every_attempt] has five 429 failures followed by a success. It asserts all six requests are identical, the usage log has six requests with five failed and one completed, and the failures carry the status and code. It also asserts the tool call was counted once and the recorded inputs match.
  • fn[success_resets_backoff_and_retries_keep_history_without_repeating_tools] covers a retry after a tool turn. The history and tool results are resent unchanged, and the tool runs once (habeas count is 1). The pending read input is recorded only after the retried request succeeds. Both retry delays fall within the initial one-second window, which shows the window reset after a success.
  • fn[unanswered_requests_are_abandoned_and_retried] uses a hanging provider and paused time. It asserts the first request is abandoned after about 600 seconds, the second request completes, and the usage log has two requests (failed, then completed).

Backoff timing

  • providers.rs#mod[tests]/fn[jittered_backoff_grows_to_a_ceiling] runs 100 attempts. Each delay is checked against half to all of a window that starts at 1s, doubles, and caps at 60s.
  • fn[retry_after_accepts_seconds_and_dates_without_shortening_provider_delay] covers Retry-After in seconds, a future HTTP-date, a past date (zero) and an invalid value. It asserts a 90s Retry-After exceeds the window and is honored through next_delay. It also checks that values of 0, 5 and 45 act as a minimum on top of a 30–60s window.

Interruption and SDK retries

  • mod.rs#mod[tests]/fn[cancelling_during_backoff_prevents_another_request] drops the assessment future during the wait. After advancing time by 120s there is still only one request. No inputs are recorded, and the log shows one failed request.
  • That test drops the future directly. The real ctrl-c path (the tokio::select! in author_evidence_with_options) drops the same future, so I treat this as adequate.
  • providers.rs#mod[tests]/fn[bedrock_sdk_retries_are_disabled] asserts max_attempts() == 1.

Recording and completion

  • Per-attempt recording and recording inputs only after success are covered by the throttled and tool-retry tests above.
  • Retries are not reported as a final judgment or terminal error while recovery is in progress. The retry tests only get a successful judgment after the transient failures. They never see an error or early judgment.

No obligation lacks a test and no assertion contradicts the requirement.

Inputs

Implementation

Input 16: outline src/authoring/mod.rs fn[author_evidence_with_options]
/// Assesses one subject under its assessment policy, returning `None`
/// without resolving configuration or invoking a model when, under
/// `--missing`, its evidence is current. `--stdout` implies `--force`.
// {impl}`requirements.authoring.invocation`
// {impl}`requirements.configuration.state_location`
// {impl}`requirements.authoring.policy`
// {impl}`requirements.authoring.read_denial.mandatory`
// {impl}`requirements.authoring.provider_backoff`
// {impl}`requirements.references.citation_review`
pub async fn author_evidence_with_options(
    root: &Path,
    subject: &str,
    selection: Option<&str>,
    output: EvidenceOutput,
    options: AuthoringOptions,
) -> io::Result<Option<AuthoringOutcome>> {
    let root = fs::canonicalize(root)?;
    let force = options.force || matches!(output, EvidenceOutput::Stdout);
    if !force && batch::subject_is_current(&root, &AuthoringSubject::parse(subject))? {
        return Ok(None);
    }
    let state = usage_state_root(&root)?;
    let mut usage = UsageLog::start(&state, &root, subject)?;
    usage.record.subject_kind = AuthoringSubject::parse(subject)
        .kind_noun(&root)
        .map(str::to_owned);
    usage.record.evidence_output = match output {
        EvidenceOutput::File => "file",
        EvidenceOutput::Stdout => "stdout",
    };
    usage.save()?;
    let result = tokio::select! {
        result = configured_assessment(&root, subject, selection, output, options.policy, &mut usage) => result,
        signal = tokio::signal::ctrl_c() => {
            match signal {
                Ok(()) => Err(io::Error::new(io::ErrorKind::Interrupted, "evidence authoring cancelled")),
                Err(error) => Err(error),
            }
        }
    };
    let outcome = match &result {
        Ok(_) => "completed",
        Err(error) if error.kind() == io::ErrorKind::Interrupted => "cancelled",
        Err(_) => "failed",
    };
    usage.finish(outcome).map_err(|error| {
        let cause = result
            .as_ref()
            .err()
            .map_or(String::new(), |cause| format!("{cause}; "));
        io::Error::new(
            result.as_ref().err().map_or(error.kind(), io::Error::kind),
            format!(
                "{cause}cannot record usage at {} (evidence written: {}): {error}",
                usage.path.display(),
                usage.record.evidence_written
            ),
        )
    })?;
    result.map(Some).map_err(|error| {
        io::Error::new(
            error.kind(),
            format!("{error}; usage: {}", usage.path.display()),
        )
    })
}

Tests

Input 5: 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 6: 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/mod.rs mod[tests]/fn[cancelling_during_backoff_prevents_another_request]
    // {test}`requirements.authoring.provider_backoff`
    #[tokio::test(start_paused = true)]
    async fn cancelling_during_backoff_prevents_another_request() {
        let (_project, _state, mut sources, mut usage) = retry_fixture();
        let provider = ThrottledProvider {
            failures: 8,
            status: 429,
            code: "ThrottlingException",
            requests: RefCell::default(),
        };
        assert!(
            tokio::time::timeout(
                Duration::from_millis(100),
                assess(&provider, &mut sources, &mut usage),
            )
            .await
            .is_err()
        );
        tokio::time::advance(Duration::from_secs(120)).await;
        assert_eq!(provider.requests.borrow().len(), 1);
        assert!(sources.recorded_inputs().is_empty());
        let log: Value = serde_json::from_slice(&fs::read(&usage.path).unwrap()).unwrap();
        assert_eq!(log["request_count"], 1);
        assert_eq!(log["requests"][0]["outcome"], "failed");
    }
Input 8: outline src/authoring/mod.rs mod[tests]/fn[unanswered_requests_are_abandoned_and_retried]
    // {test}`requirements.authoring.provider_backoff`
    // {test}`requirements.authoring.usage_requests`
    #[tokio::test(start_paused = true)]
    async fn unanswered_requests_are_abandoned_and_retried() {
        let (_project, _state, mut sources, mut usage) = retry_fixture();
        let provider = HangingProvider {
            requests: RefCell::default(),
        };
        let started = tokio::time::Instant::now();
        let (judgment, _) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        assert_eq!(judgment.to_value(), json!(true));
        assert!(
            (Duration::from_secs(600)..=Duration::from_secs(601)).contains(&started.elapsed()),
            "{:?}",
            started.elapsed()
        );
        assert_eq!(*provider.requests.borrow(), 2);
        let log: Value = serde_json::from_slice(&fs::read(&usage.path).unwrap()).unwrap();
        assert_eq!(log["request_count"], 2);
        assert_eq!(log["requests"][0]["outcome"], "failed");
        assert_eq!(log["requests"][1]["outcome"], "completed");
    }
Input 9: outline src/authoring/mod.rs mod[tests]/fn[success_resets_backoff_and_retries_keep_history_without_repeating_tools]
  • File: src/authoring/mod.rs
  • Selector: mod[tests]/fn[success_resets_backoff_and_retries_keep_history_without_repeating_tools]
  • Kind: fn
  • src/authoring/mod.rs:2429–2469
    // {test}`requirements.authoring.provider_backoff`
    // {test}`requirements.authoring.usage_requests`
    #[tokio::test(start_paused = true)]
    async fn success_resets_backoff_and_retries_keep_history_without_repeating_tools() {
        let (project, _state, mut sources, mut usage) = retry_fixture();
        fs::write(project.path().join("src/lib.rs"), "fn run() {}\n").unwrap();
        let provider = ThrottledToolProvider {
            requests: RefCell::default(),
        };
        let (_, record) = assess(&provider, &mut sources, &mut usage).await.unwrap();
        let requests = provider.requests.borrow();
        assert_eq!(requests.len(), 4);
        // Each throttled request waits within the initial one-second window:
        // the successful tool turn reset the window doubled by the first failure.
        for (failed, retried) in [(0, 1), (2, 3)] {
            let delay = requests[retried].0 - requests[failed].0;
            assert!(
                delay >= Duration::from_millis(500) && delay <= Duration::from_secs(1),
                "{delay:?}"
            );
        }
        assert_eq!(requests[0].1, requests[1].1);
        // The retry after the tool turn resends the same history, tool
        // results, and tools.
        assert_eq!(requests[2].1, requests[3].1);
        assert_ne!(requests[1].1, requests[2].1);
        assert!(requests[3].1.to_string().contains("fn run()"));

        // The read ran once, and its input was recorded after the retried
        // request succeeded.
        let log: Value = serde_json::from_slice(&fs::read(&usage.path).unwrap()).unwrap();
        assert_eq!(log["tool_calls"]["habeas"], 1, "{log:#}");
        assert_eq!(log["request_count"], 4);
        let inputs = record["inputs"].as_array().unwrap();
        assert!(
            inputs
                .iter()
                .any(|input| input["file"] == "src/lib.rs" && input["item"] == "fn[run]"),
            "{inputs:#?}"
        );
    }
Input 10: outline src/authoring/providers.rs mod[tests]/fn[retries_throttling_unavailability_and_timeouts_but_not_permanent_errors]
    // {test}`requirements.authoring.provider_backoff`
    #[test]
    fn retries_throttling_unavailability_and_timeouts_but_not_permanent_errors() {
        for (status, code) in [
            (Some(429), None),
            (Some(429), Some("ThrottlingException")),
            (None, Some("ThrottlingException")),
            (Some(500), None),
            (Some(502), None),
            (Some(503), Some("ServiceUnavailableException")),
            (Some(504), None),
            (None, Some("ServiceUnavailableException")),
            (None, Some("InternalServerException")),
            (None, Some("ModelNotReadyException")),
        ] {
            assert!(
                ProviderBackoff::default()
                    .next_delay(&io::Error::other(provider_error(status, code)))
                    .is_some()
            );
        }
        for (status, code) in [
            (Some(400), Some("ValidationException")),
            (Some(403), Some("AccessDeniedException")),
            (Some(501), None),
            (None, None),
        ] {
            assert!(
                ProviderBackoff::default()
                    .next_delay(&io::Error::other(provider_error(status, code)))
                    .is_none()
            );
        }
        assert!(
            ProviderBackoff::default()
                .next_delay(&io::Error::other("Too many tokens; HTTP 429"))
                .is_none()
        );
        assert!(
            ProviderBackoff::default()
                .next_delay(&io::Error::new(io::ErrorKind::TimedOut, "no response"))
                .is_some()
        );
    }
Input 11: outline src/authoring/providers.rs mod[tests]/fn[transient_bedrock_codes_retry_whatever_their_http_status]
    // {test}`requirements.authoring.provider_backoff`
    #[test]
    fn transient_bedrock_codes_retry_whatever_their_http_status() {
        for (status, code) in [
            (Some(400), "ThrottlingException"),
            (Some(400), "ServiceUnavailableException"),
            (Some(501), "InternalServerException"),
            (Some(424), "ModelNotReadyException"),
        ] {
            assert!(
                ProviderBackoff::default()
                    .next_delay(&io::Error::other(provider_error(status, Some(code))))
                    .is_some(),
                "{status:?} {code}"
            );
        }
        // A permanent code does not override a transient status.
        assert!(
            ProviderBackoff::default()
                .next_delay(&io::Error::other(provider_error(
                    Some(503),
                    Some("ValidationException")
                )))
                .is_some()
        );
    }
Input 12: outline src/authoring/providers.rs mod[tests]/fn[jittered_backoff_grows_to_a_ceiling]
    // {test}`requirements.authoring.provider_backoff`
    #[test]
    fn jittered_backoff_grows_to_a_ceiling() {
        let error = io::Error::other(provider_error(Some(429), Some("ThrottlingException")));
        let mut backoff = ProviderBackoff::default();
        for attempt in 0..100 {
            let window = Duration::from_secs(1_u64 << attempt.min(6)).min(Duration::from_secs(60));
            let delay = backoff.next_delay(&error).unwrap();
            assert!((window / 2..=window).contains(&delay));
        }
    }
Input 13: outline src/authoring/providers.rs mod[tests]/fn[retry_after_accepts_seconds_and_dates_without_shortening_provider_delay]
    // {test}`requirements.authoring.provider_backoff`
    #[test]
    fn retry_after_accepts_seconds_and_dates_without_shortening_provider_delay() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        let future = httpdate::fmt_http_date(now + Duration::from_secs(90));
        let past = httpdate::fmt_http_date(now - Duration::from_secs(90));
        for (header, expected) in [
            ("90", Some(Duration::from_secs(90))),
            (future.as_str(), Some(Duration::from_secs(90))),
            (past.as_str(), Some(Duration::ZERO)),
            ("invalid", None),
        ] {
            let error = with_retry_after(provider_error(Some(429), None), header);
            assert_eq!(retry_after(&error, now), expected);
        }
        let error = io::Error::other(with_retry_after(provider_error(Some(429), None), "90"));
        assert_eq!(
            ProviderBackoff::default().next_delay(&error),
            Some(Duration::from_secs(90))
        );
        for minimum in ["0", "5", "45"] {
            let mut backoff = ProviderBackoff::default();
            let throttled = io::Error::other(provider_error(Some(429), None));
            for _ in 0..6 {
                backoff.next_delay(&throttled).unwrap();
            }
            let error =
                io::Error::other(with_retry_after(provider_error(Some(429), None), minimum));
            for _ in 0..100 {
                let delay = backoff.next_delay(&error).unwrap();
                let lower = Duration::from_secs(minimum.parse::<u64>().unwrap().max(30));
                assert!((lower..=Duration::from_secs(60)).contains(&delay));
            }
        }
    }
Input 14: outline src/authoring/providers.rs mod[tests]/fn[bedrock_sdk_retries_are_disabled]
    // {test}`requirements.authoring.provider_backoff`
    // {test}`requirements.authoring.usage_requests`
    #[tokio::test]
    async fn bedrock_sdk_retries_are_disabled() {
        let config: BedrockConfig =
            toml::from_str("model = 'test'\nregion = 'us-west-2'\n").unwrap();
        let sdk = bedrock_sdk_config(&config).await;
        let retry = sdk.retry_config().expect("retry configuration is set");
        assert_eq!(retry.max_attempts(), 1, "{retry:?}");
    }
Input 15: outline src/authoring/providers.rs mod[tests]/fn[rig_failures_keep_their_provider_report_for_backoff]
    // {test}`requirements.authoring.provider_backoff`
    #[test]
    fn rig_failures_keep_their_provider_report_for_backoff() {
        let mut backoff = ProviderBackoff::default();
        let error = provider_failure(provider_error(Some(429), None));
        assert!(backoff.next_delay(&error).is_some());
        let error = provider_failure(provider_error(None, Some("ServiceUnavailableException")));
        assert!(backoff.next_delay(&error).is_some());
        let error = provider_failure(provider_error(Some(400), Some("ValidationException")));
        assert_eq!(backoff.next_delay(&error), None);
    }

Referenced definitions

Input 2: requirements selection requirements.authoring.usage_requests
:::{req} usage_requests
Usage MUST record each provider request's outcome and available input/output
token counts, including retries, with cached or reasoning-token counts when
provided, and for a failed request the failure under
{cite}`requirements.authoring.usage_requests.failures`. Missing measurements MUST be recorded as unavailable, not zero.
Run totals MUST include request and tool-call counts by tool, elapsed time, and
available token usage, identifying incomplete totals without double counting
provider counters that overlap.
:::
Input 3: requirements selection requirements.authoring.provider
:::{req} provider
The authoring harness MUST use Rig and support Bedrock, Ollama, and OpenAI. Users MUST be
able to select a backend and model through configuration without changing the
assessment tools, prompt, or evidence format.
:::
Input 4: requirements selection requirements.authoring.delivered_inputs
:::{req} delivered_inputs
The harness MUST record the sources it supplies to the model, including
mandatory inputs, additional reads, and selected search dependencies under
{cite}`requirements.authoring.finish_search.inputs`, using the evidence input formats
defined by {cite}`requirements.ci.outline_inputs`,
{cite}`requirements.ci.requirements_inputs`, and
{cite}`requirements.definitions.inputs`. The harness MUST create these records
itself so ordinary evidence validation can check them later.
:::

Other sources

Input 1: requirements selection requirements.authoring.provider_backoff
:::{req} provider_backoff
When a provider reports a transient failure, the harness MUST wait and retry
the same completion request. Transient failures are throttling, reported
through HTTP 429 or a Bedrock `ThrottlingException`; temporary unavailability,
reported through HTTP 500, 502, 503, or 504 or a Bedrock
`ServiceUnavailableException`, `InternalServerException`, or
`ModelNotReadyException`; and a request with no response after ten minutes,
which the harness MUST abandon. The retry MUST retain its prompt, history,
tools, and pending inputs. It MUST NOT
restart the assessment or repeat already completed tool calls. A permanent
input/context-length error, authentication failure, or invalid request MUST
remain an error; mentioning tokens in an error message alone MUST NOT trigger
retries.

The backoff window MUST start at one second and double after each consecutive
transient failure, up to sixty seconds. Each delay MUST be randomly selected
between half and all of that window to spread parallel retries. An available
provider `Retry-After` value, in seconds or HTTP-date form, MUST be honored as a
minimum delay even when longer than the window. A successful response MUST reset
backoff for the next completion request, and interruption MUST cancel both the
wait and further retries.

Each attempt MUST be recorded under {cite}`requirements.authoring.usage_requests`.
Hidden SDK retries MUST remain disabled so the harness can account for attempts.
Transient retries MUST NOT be reported as finished judgments or terminal
assessment errors while recovery is still in progress. Pending inputs MUST be
recorded as evidence only after the request succeeds.
{cite}`requirements.authoring.provider` {cite}`requirements.authoring.delivered_inputs`
:::