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

Requirements index · View definition

evidence Valid

Requirement

The harness MUST stop retrying a completion request under cite requirements.authoring.provider_backoff when the next attempt would start more than one minute after the first of its consecutive transient failures, including when a provider Retry-After delay would pass that point. It MUST then fail the assessment with an error naming the number of attempts and the last failure’s HTTP status and provider error code, when available.

Rationale

The two marked tests adequately cover requirements.authoring.provider_backoff.limit.

Obligations. I derived four from the requirement text:

  1. Stop retrying when the next attempt would start more than one minute after the first of the consecutive transient failures.
  2. Apply that limit when a Retry-After delay would pass that point.
  3. Fail the assessment once retrying stops.
  4. Name the number of attempts, and the last failure’s HTTP status and provider error code when available, in that error.

Unit test src/authoring/providers.rs#mod[tests]/fn[retrying_stops_once_a_request_has_failed_for_a_minute].

  • It loops ProviderBackoff::retry with throttling errors, advancing the clock by each returned delay. It asserts that no attempt starts after start + 60s, that more than 3 attempts occur, and that the loop ends in Retry::Stop.
  • A second failure at 58s still waits, with a delay of at most 2s.
  • It checks the boundary with Retry-After. A value of 60 gives Wait(60s), and a value of 61 gives Stop. This is the exact “more than one minute” edge.
  • A Retry-After of 90 stops at once, which covers the “including when a provider Retry-After delay would pass that point” clause.
  • The stop message contains “kept failing for a minute”, “after {attempts+1} attempts” and “HTTP 429 ThrottlingException”.
  • The last-failure naming is checked for status only, code only, and a timeout with neither. These cover the “when available” qualifier.
  • The first failure arrives at start+60s and the second at start+180s, so the limit is measured from the first failure rather than the latest. The first call must wait, and the second must stop.
  • A permanent 400 failure stops with its own error and not the “kept failing” message.

Integration test src/authoring/mod.rs#mod[tests]/fn[a_request_failing_for_a_minute_fails_the_assessment].

  • It runs the whole assess flow with a provider that always returns 503 ServiceUnavailableException, under a paused tokio clock.
  • It asserts that elapsed time is at most RETRY_LIMIT, that more than 3 requests were made, and that the error contains “after {attempts} attempts; last failure: HTTP 503 ServiceUnavailableException”. The attempt count matches the number of requests actually made.
  • It also asserts that the final attempt’s usage-log entry has retried == false.

Delegated to the parent requirement. Resetting backoff after a success, and the retry, timeout and cancellation behaviour, belong to requirements.authoring.provider_backoff. Its tests in src/authoring/mod.rs carry that reference, including success_resets_backoff_and_retries_keep_history_without_repeating_tools. They are not assessed here.

I found no plausible violating behavior that these tests would accept.

Inputs

Implementation

Input 5: outline src/authoring/providers.rs impl[ProviderBackoff]
impl ProviderBackoff {
    /// Decides whether to retry a failed request at `now`: after a
    /// transient failure while the next attempt still starts within
    /// [`RETRY_LIMIT`] of the first consecutive failure.
    // {impl}`requirements.authoring.provider_backoff.limit`
    pub(super) fn retry(&mut self, error: io::Error, now: Instant) -> Retry {
        let Some(delay) = self.next_delay(&error) else {
            return Retry::Stop(error);
        };
        let (first, attempts) = self.failing.get_or_insert((now, 0));
        *attempts += 1;
        if now + delay > *first + RETRY_LIMIT {
            let (status, code) = failure_codes(&error);
            let last = match (status, code) {
                (Some(status), Some(code)) => format!("HTTP {status} {code}"),
                (Some(status), None) => format!("HTTP {status}"),
                (None, Some(code)) => code,
                (None, None) => error.to_string(),
            };
            return Retry::Stop(io::Error::new(
                io::ErrorKind::TimedOut,
                format!(
                    "the provider kept failing for a minute after {attempts} attempts; last failure: {last}"
                ),
            ));
        }
        Retry::Wait(delay)
    }

    pub(super) fn next_delay(&mut self, error: &io::Error) -> Option<Duration> {
        // Rig preserves HTTP status and Bedrock's exception code. Do not infer
        // throttling from "tokens" in a message: a too-large input cannot be
        // fixed by resending the same request.
        let provider = error
            .get_ref()
            .and_then(|inner| inner.downcast_ref::<ProviderError>());
        let transient = if error.kind() == io::ErrorKind::TimedOut {
            true
        } else {
            // Either signal is enough: AWS JSON services may report a
            // throttling or unavailability code with another status, such as
            // `ThrottlingException` with HTTP 400.
            let report = provider?.report();
            matches!(report.http_status, Some(429 | 500 | 502 | 503 | 504))
                || matches!(
                    report.code.as_deref(),
                    Some(
                        "ThrottlingException"
                            | "ServiceUnavailableException"
                            | "InternalServerException"
                            | "ModelNotReadyException"
                    )
                )
        };
        if !transient {
            return None;
        }

        let millis = self.window.as_millis() as u64;
        self.window = (self.window * 2).min(Duration::from_secs(60));
        // Equal jitter keeps parallel assessments from retrying in lockstep,
        // while ensuring each retry waits at least half the current window.
        let jittered = Duration::from_millis(fastrand::u64(millis / 2..=millis));
        let minimum = provider
            .and_then(|provider| retry_after(provider, SystemTime::now()))
            .unwrap_or_default();
        Some(jittered.max(minimum))
    }
}

Tests

Input 3: outline src/authoring/mod.rs mod[tests]/fn[a_request_failing_for_a_minute_fails_the_assessment]
    // {test}`requirements.authoring.provider_backoff.limit`
    #[tokio::test(start_paused = true)]
    async fn a_request_failing_for_a_minute_fails_the_assessment() {
        let (_project, _state, mut sources, mut usage) = retry_fixture();
        let provider = ThrottledProvider {
            failures: usize::MAX,
            status: 503,
            code: "ServiceUnavailableException",
            requests: RefCell::default(),
        };
        let started = tokio::time::Instant::now();
        let error = assess(&provider, &mut sources, &mut usage)
            .await
            .unwrap_err()
            .to_string();
        assert!(
            started.elapsed() <= providers::RETRY_LIMIT,
            "{:?}",
            started.elapsed()
        );
        let attempts = provider.requests.borrow().len();
        assert!(attempts > 3, "{attempts}");
        assert!(
            error.contains(&format!(
                "after {attempts} attempts; last failure: HTTP 503 ServiceUnavailableException"
            )),
            "{error}"
        );
        let log: Value = serde_json::from_slice(&fs::read(&usage.path).unwrap()).unwrap();
        assert_eq!(log["requests"][attempts - 1]["failure"]["retried"], false);
    }
Input 4: outline src/authoring/providers.rs mod[tests]/fn[retrying_stops_once_a_request_has_failed_for_a_minute]
    // {test}`requirements.authoring.provider_backoff.limit`
    #[test]
    fn retrying_stops_once_a_request_has_failed_for_a_minute() {
        let throttled = || io::Error::other(provider_error(Some(429), Some("ThrottlingException")));
        let start = Instant::now();
        let mut backoff = ProviderBackoff::default();
        let mut now = start;
        let mut attempts = 0;
        let message = loop {
            match backoff.retry(throttled(), now) {
                Retry::Wait(delay) => {
                    attempts += 1;
                    now += delay;
                    // No attempt starts after the minute.
                    assert!(now <= start + Duration::from_secs(60));
                }
                Retry::Stop(error) => break error.to_string(),
            }
        };
        assert!(attempts > 3, "{attempts}");
        let mut within_minute = ProviderBackoff::default();
        assert!(matches!(
            within_minute.retry(throttled(), start),
            Retry::Wait(_)
        ));
        assert!(
            matches!(within_minute.retry(throttled(),start + Duration::from_secs(58)),
            Retry::Wait(delay) if delay <= Duration::from_secs(2))
        );
        for (minimum, should_wait) in [("60", true), ("61", false)] {
            let error = io::Error::other(with_retry_after(
                provider_error(Some(429), Some("ThrottlingException")),
                minimum,
            ));
            match ProviderBackoff::default().retry(error, start) {
                Retry::Wait(delay) => {
                    assert!(should_wait, "waited past one minute");
                    assert_eq!(delay, Duration::from_secs(60));
                }
                Retry::Stop(_) => assert!(!should_wait, "stopped exactly at one minute"),
            }
        }
        assert!(message.contains("kept failing for a minute"), "{message}");
        assert!(
            message.contains(&format!("after {} attempts", attempts + 1)),
            "{message}"
        );
        assert!(
            message.contains("HTTP 429 ThrottlingException"),
            "{message}"
        );
        // A Retry-After past the minute stops at once.
        let late = io::Error::other(with_retry_after(
            provider_error(Some(429), Some("ThrottlingException")),
            "90",
        ));
        assert!(matches!(
            ProviderBackoff::default().retry(late, Instant::now()),
            Retry::Stop(_)
        ));
        // The last failure is named by whatever it reports.
        for (error, last) in [
            (
                io::Error::other(provider_error(Some(503), None)),
                "last failure: HTTP 503",
            ),
            (
                io::Error::other(provider_error(None, Some("ThrottlingException"))),
                "last failure: ThrottlingException",
            ),
            (
                io::Error::new(io::ErrorKind::TimedOut, "no response within ten minutes"),
                "last failure: no response within ten minutes",
            ),
        ] {
            let mut backoff = ProviderBackoff::default();
            let message = match backoff.retry(error, start + RETRY_LIMIT) {
                Retry::Stop(error) => panic!("first failure stops: {error}"),
                Retry::Wait(_) => {
                    let again = match last {
                        _ if last.contains("503") => {
                            io::Error::other(provider_error(Some(503), None))
                        }
                        _ if last.contains("Throttling") => {
                            io::Error::other(provider_error(None, Some("ThrottlingException")))
                        }
                        _ => io::Error::new(
                            io::ErrorKind::TimedOut,
                            "no response within ten minutes",
                        ),
                    };
                    match backoff.retry(again, start + RETRY_LIMIT * 3) {
                        Retry::Stop(error) => {
                            assert_eq!(error.kind(), io::ErrorKind::TimedOut);
                            error.to_string()
                        }
                        Retry::Wait(_) => panic!("retrying passed the limit"),
                    }
                }
            };
            assert!(message.contains(last), "{message}");
        }
        // A permanent failure stops with its own error.
        let permanent = io::Error::other(provider_error(Some(400), Some("ValidationException")));
        assert!(matches!(
            ProviderBackoff::default().retry(permanent, Instant::now()),
            Retry::Stop(error) if !error.to_string().contains("kept failing")
        ));
    }

Referenced definitions

Input 2: 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`
:::

Other sources

Input 1: requirements selection requirements.authoring.provider_backoff.limit
:::{req} provider_backoff.limit
The harness MUST stop retrying a completion request under
{cite}`requirements.authoring.provider_backoff` when the next attempt would
start more than one minute after the first of its consecutive transient
failures, including when a provider `Retry-After` delay would pass that point.
It MUST then fail the assessment with an error naming the number of attempts
and the last failure's HTTP status and provider error code, when available.
:::