From 1d2b0c0ba0aaa9ace42322ce5383542c00a5617b Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Thu, 19 Nov 2026 15:24:01 -0500 Subject: [PATCH] test(model_loop): model the provider retry ladder in process `retry_stream` is public and takes its backoff `sleep`, so a test can script each attempt's error, the salvage, and the retry notice, and record every effect. retry_stream_test compares the whole trace with a model of the documented ladder (eight attempts, waits doubling from 250 ms, one more go for an accepted timeout across salvage, resume on kept output, no sleep after a cancelled notice). Replaces these end-to-end cases, which waited out scaled socket timeouts and backoff: - provider_timeout_test.test_salvaging_a_broken_stream_keeps_the_accepted_timeout_budget (silent budget lost across salvage) - provider_timeout_test.test_a_provider_that_never_answers_gets_the_whole_retry_ladder (attempt count, waits) - requests_test.test_a_failing_gateway_is_retried_with_doubling_waits (503 retried, waits double) provider_timeout keeps the real-socket case that classifies silence after headers as accepted and records both rows. --- apps/albedo/src/albedo/model_loop/loop.gleam | 12 +- .../albedo/model_loop/retry_stream_test.gleam | 264 ++++++++++++++++++ e2e/provider_timeout_test.py | 48 +--- e2e/requests_test.py | 42 +-- 4 files changed, 281 insertions(+), 85 deletions(-) create mode 100644 apps/albedo/test/albedo/model_loop/retry_stream_test.gleam diff --git a/apps/albedo/src/albedo/model_loop/loop.gleam b/apps/albedo/src/albedo/model_loop/loop.gleam index 24717054b..4f4bcbca8 100644 --- a/apps/albedo/src/albedo/model_loop/loop.gleam +++ b/apps/albedo/src/albedo/model_loop/loop.gleam @@ -1708,6 +1708,7 @@ fn call( state.run_id, reset_progress, salvage, + albedo_clock.sleep, first, accepted_timeouts, ) @@ -1725,7 +1726,7 @@ type Called { } /// How a provider call ended for its turn. -type Attempt(a) { +pub type Attempt(a) { Answered(a) /// The stream broke after it showed output; `kept` is what was committed /// of it, and the turn goes on from there at attempt `next`. @@ -1878,13 +1879,15 @@ const accepted_timeout_retries = 1 /// Reissue transient transport and gateway failures. A failed attempt that /// showed nothing is sent again as it was; one that showed output keeps it -/// through `salvage`, and the call resumes from it instead. -fn retry_stream( +/// through `salvage`, and the call resumes from it instead. `sleep` waits +/// out each backoff; the loop passes `albedo_clock.sleep`. +pub fn retry_stream( run: fn(Int) -> Result(a, types.Error), publish: fn(view.Event) -> Bool, run_id: String, reset_progress: fn(Int) -> Nil, salvage: fn(String) -> Result(#(Int, List(types.Input)), String), + sleep: fn(Int) -> Nil, attempt: Int, accepted_timeouts: Int, ) -> Result(Attempt(a), types.Error) { @@ -1924,7 +1927,7 @@ fn retry_stream( False -> Error(types.Cancelled) True -> { reset_progress(attempt) - albedo_clock.sleep(delay) + sleep(delay) case kept { [] -> retry_stream( @@ -1933,6 +1936,7 @@ fn retry_stream( run_id, reset_progress, salvage, + sleep, attempt + 1, accepted_timeouts, ) diff --git a/apps/albedo/test/albedo/model_loop/retry_stream_test.gleam b/apps/albedo/test/albedo/model_loop/retry_stream_test.gleam new file mode 100644 index 000000000..a7044ab98 --- /dev/null +++ b/apps/albedo/test/albedo/model_loop/retry_stream_test.gleam @@ -0,0 +1,264 @@ +//// The provider retry ladder (`loop.retry_stream`). +//// +//// Defects: retrying an error that should end the call, retrying a call the +//// provider accepted and then went silent on more than once in a step +//// (including after a salvaged attempt), the wrong number of attempts, waits +//// that do not double from 250 ms, sleeping or retrying after the run was +//// cancelled, and losing salvaged output. Each needs a provider that fails in +//// a chosen order. The end-to-end versions waited out real socket timeouts +//// and backoff; here the provider, the publisher, and the sleep are scripted +//// and every call is recorded, so the whole trace is compared with a model +//// written from the ladder's documentation: eight attempts, waits doubling +//// from 250 ms, one more go for an accepted timeout, and a salvaged attempt +//// resuming instead of retrying. + +import albedo/model_loop/loop.{Answered, Resumed} +import albedo/observation/events as view +import albedo_model as types +import albedo_property +import gleam/erlang/process.{type Subject} +import gleam/list +import gleam/option.{None, Some} +import qcheck.{type Generator} + +/// What one scripted attempt does. +type Step { + Succeeds + Fails(error: types.Error, salvage: Salvage) +} + +/// What salvaging a failed attempt's output yields. +type Salvage { + Nothing + Kept + SalvageFails +} + +/// Every effect `retry_stream` has, in order. +type Effect { + Ran(attempt: Int) + Salvaged + Published(attempt: Int, delay: Int) + Reset(attempt: Int) + Slept(delay: Int) +} + +type Outcome { + AnsweredAt(attempt: Int) + ResumedAt(next: Int, accepted_timeouts: Int) + Failed(types.Error) +} + +const kept = [types.User("kept")] + +fn error() -> Generator(types.Error) { + qcheck.from_generators(qcheck.return(types.ConnectionError("reset")), [ + qcheck.return(types.Timeout(types.Connecting, 1000)), + qcheck.return(types.Timeout(types.AwaitingHeaders, 1000)), + qcheck.return(types.Timeout(types.AwaitingFirstEvent, 1000)), + qcheck.return(types.Timeout(types.Streaming, 1000)), + qcheck.return(types.UnexpectedEnd), + qcheck.return(types.Refused(types.Unavailable, Some(503), "busy")), + qcheck.return(types.Refused(types.ContextTooLong, None, "too long")), + qcheck.return(types.InvalidRequest("bad")), + qcheck.return(types.Cancelled), + ]) +} + +fn step() -> Generator(Step) { + let salvage = + qcheck.from_weighted_generators(#(6, qcheck.return(Nothing)), [ + #(1, qcheck.return(Kept)), + #(1, qcheck.return(SalvageFails)), + ]) + qcheck.from_weighted_generators(#(1, qcheck.return(Succeeds)), [ + #(5, qcheck.map2(error(), salvage, Fails)), + ]) +} + +type Case { + Case( + script: List(Step), + first: Int, + accepted_timeouts: Int, + /// The retry notice for this attempt finds the run cancelled. + cancel_at: Int, + ) +} + +fn case_() -> Generator(Case) { + qcheck.map4( + qcheck.generic_list(step(), qcheck.bounded_int(0, 10)), + qcheck.bounded_int(1, 3), + qcheck.bounded_int(0, 1), + qcheck.bounded_int(1, 14), + Case, + ) +} + +/// The documented waits before attempts 2 through 8. +const waits = [250, 500, 1000, 2000, 4000, 8000, 16_000] + +fn at(items: List(a), index: Int) -> Result(a, Nil) { + list.drop(items, index) |> list.first +} + +fn transient(error: types.Error) -> Bool { + case error { + types.ConnectionError(_) + | types.Timeout(..) + | types.UnexpectedEnd + | types.Refused(types.Unavailable, ..) -> True + _ -> False + } +} + +/// The provider accepted the request and then went silent. +fn accepted(error: types.Error) -> Bool { + case error { + types.Timeout(types.AwaitingFirstEvent, _) + | types.Timeout(types.Streaming, _) -> True + _ -> False + } +} + +/// The model of the ladder: the effects in order and the outcome. +fn model(case_: Case) -> #(List(Effect), Outcome) { + model_loop(case_, case_.first, case_.accepted_timeouts, []) +} + +fn model_loop( + case_: Case, + attempt: Int, + silent: Int, + effects: List(Effect), +) -> #(List(Effect), Outcome) { + let effects = [Ran(attempt), ..effects] + case at(case_.script, attempt - case_.first) { + Error(Nil) | Ok(Succeeds) -> #(list.reverse(effects), AnsweredAt(attempt)) + Ok(Fails(error, salvage)) -> { + let silent = case accepted(error) { + True -> silent + 1 + False -> silent + } + case attempt < 8 && transient(error) && silent <= 1 { + False -> #(list.reverse(effects), Failed(error)) + True -> { + let assert Ok(delay) = at(waits, attempt - 1) + let effects = [Published(attempt + 1, delay), Salvaged, ..effects] + case case_.cancel_at == attempt + 1 { + True -> #(list.reverse(effects), Failed(types.Cancelled)) + False -> { + let effects = [Slept(delay), Reset(attempt), ..effects] + case salvage { + Kept -> #(list.reverse(effects), ResumedAt(attempt + 1, silent)) + Nothing | SalvageFails -> + model_loop(case_, attempt + 1, silent, effects) + } + } + } + } + } + } + } +} + +fn run(case_: Case) -> #(List(Effect), Outcome) { + let effects = process.new_subject() + let record = fn(effect) { process.send(effects, effect) } + // The attempt that just failed, for `salvage` to read. + let failed = process.new_subject() + let result = + loop.retry_stream( + fn(attempt) { + record(Ran(attempt)) + process.send(failed, attempt) + case at(case_.script, attempt - case_.first) { + Error(Nil) | Ok(Succeeds) -> Ok(attempt) + Ok(Fails(error, _)) -> Error(error) + } + }, + fn(event) { + case event { + view.Retry(run_id: "run", attempt:, delay_ms:, ..) -> { + record(Published(attempt, delay_ms)) + case_.cancel_at != attempt + } + _ -> panic as "retry_stream published something besides a retry" + } + }, + "run", + fn(attempt) { record(Reset(attempt)) }, + fn(_reason) { + record(Salvaged) + let assert Ok(attempt) = process.receive(failed, 0) + let assert Ok(Fails(_, salvage)) = + at(case_.script, attempt - case_.first) + case salvage { + Nothing -> Ok(#(0, [])) + Kept -> Ok(#(7, kept)) + SalvageFails -> Error("disk full") + } + }, + fn(delay) { record(Slept(delay)) }, + case_.first, + case_.accepted_timeouts, + ) + let outcome = case result { + Ok(Answered(attempt)) -> AnsweredAt(attempt) + Ok(Resumed(timestamp: 7, kept: k, next:, accepted_timeouts:)) if k == kept -> + ResumedAt(next, accepted_timeouts) + Ok(Resumed(..)) -> panic as "resumed without the salvaged output" + Error(error) -> Failed(error) + } + #(drain(effects, []), outcome) +} + +fn drain(effects: Subject(Effect), acc: List(Effect)) -> List(Effect) { + case process.receive(effects, 0) { + Ok(effect) -> drain(effects, [effect, ..acc]) + Error(Nil) -> list.reverse(acc) + } +} + +pub fn the_retry_ladder_follows_its_documented_policy_test() { + use case_ <- albedo_property.run(500, case_()) + assert run(case_) == model(case_) +} + +/// A provider that never answers gets the whole ladder: eight attempts and +/// seven doubling waits, about 32 s. +pub fn a_provider_that_never_answers_gets_eight_attempts_test() { + let silent = Fails(types.Timeout(types.AwaitingHeaders, 1000), Nothing) + let #(effects, outcome) = run(Case(list.repeat(silent, 9), 1, 0, 0)) + assert outcome == Failed(types.Timeout(types.AwaitingHeaders, 1000)) + assert list.count(effects, is_ran) == 8 + let slept = + list.filter_map(effects, fn(effect) { + case effect { + Slept(delay) -> Ok(delay) + _ -> Error(Nil) + } + }) + assert slept == waits +} + +fn is_ran(effect: Effect) -> Bool { + case effect { + Ran(_) -> True + _ -> False + } +} + +/// A call the provider accepted and then went silent on is sent once more, +/// and a salvaged broken stream in between keeps that budget spent. +pub fn a_silent_accepted_call_is_retried_once_across_a_salvage_test() { + let silent = Fails(types.Timeout(types.AwaitingFirstEvent, 1000), Nothing) + let broken = Fails(types.UnexpectedEnd, Kept) + let #(_, outcome) = run(Case([silent, broken], 1, 0, 0)) + assert outcome == ResumedAt(3, 1) + // The resumed call starts with that budget spent. + let #(effects, outcome) = run(Case([silent], 3, 1, 0)) + assert outcome == Failed(types.Timeout(types.AwaitingFirstEvent, 1000)) + assert effects == [Ran(3)] +} diff --git a/e2e/provider_timeout_test.py b/e2e/provider_timeout_test.py index 35e022c9b..831499b36 100644 --- a/e2e/provider_timeout_test.py +++ b/e2e/provider_timeout_test.py @@ -1,11 +1,12 @@ -"""Provider timeouts: where a call was when its budget ran out decides how often -it is retried. +"""Provider timeouts: a real socket that stalls after its headers is classified +as a call the provider accepted, retried once, and recorded as such. -Catches: a call the provider accepted and then went silent on (a model thinking -past the budget, billed the whole time) being re-sent through the whole retry -ladder, the error that reaches the user not saying what happened, and request -rows that cannot tell a dead connection from a silent model. Only a real socket -that stalls before or after its headers shows these. +Catches: a silent model (thinking past the budget, billed the whole time) being +re-sent through the whole retry ladder, the error that reaches the user not +saying what happened, and request rows that cannot tell a dead connection from a +silent model. The ladder itself, given each attempt's error, is checked in +apps/albedo/test/albedo/model_loop/retry_stream_test.gleam; only the socket's +classification and the rows need the daemon. """ import json @@ -76,39 +77,6 @@ class ProviderTimeoutTest(unittest.TestCase): ], ) - def test_salvaging_a_broken_stream_keeps_the_accepted_timeout_budget(self): - def broken(): - yield {"type": "response.created", "response": {"id": "fixture"}} - yield { - "type": "response.output_text.delta", - "output_index": 0, - "content_index": 0, - "delta": "partial answer", - } - raise ConnectionResetError("scripted provider stream broke") - - silent = Reply("text", "never", hang=True) - provider, rows, _ = self.run_turn( - [silent, Reply("text", events=broken()), silent] - ) - self.assertEqual(len(provider.requests), 3, json.dumps(rows)) - self.assertIn("partial answer", json.dumps(provider.requests[2]["request"])) - self.assertEqual([row["outcome"] for row in rows], ["failed"] * 3) - - def test_a_provider_that_never_answers_gets_the_whole_retry_ladder(self): - provider, rows, errors = self.run_turn(Reply("text", "never", silent=True)) - self.assertEqual(len(provider.requests), 8) - self.assertEqual(len(rows), 8) - for row in rows: - self.assertEqual( - row["failure"]["detail"], "Timeout awaiting headers after 1000 ms" - ) - self.assertIsNone(row["first_byte_ms"]) - self.assertEqual( - errors, - ["the provider request timed out awaiting headers (1 s) on every attempt"], - ) - if __name__ == "__main__": unittest.main() diff --git a/e2e/requests_test.py b/e2e/requests_test.py index e6894f031..c691bf836 100644 --- a/e2e/requests_test.py +++ b/e2e/requests_test.py @@ -10,7 +10,7 @@ import urllib.error from datetime import datetime from urllib.parse import urlencode -from harness import Albedo, Provider, Reply, latest_user, quota_error, text +from harness import Albedo, Provider, latest_user, quota_error, text FIRST = { "input_tokens": 100, @@ -117,43 +117,3 @@ class ProviderRequestsTest(unittest.TestCase): self.assertIsNone(usage["tokens_per_second"]) finally: provider.close() - - def test_a_failing_gateway_is_retried_with_doubling_waits(self): - failures = [] - - def script(request): - if len(failures) < 4: - failures.append(1) - return Reply("error", "gateway down", status=503) - return text("recovered") - - provider = Provider(script) - try: - with Albedo(provider, protocol="responses") as app: - session = app.session(name="requests test") - app.prompt(session, "hello").close() - app.idle(session, timeout=60) - rows = self.rows(app, session)["items"] - self.assertEqual( - [row["outcome"] for row in rows], ["failed"] * 4 + ["completed"] - ) - self.assertEqual({row["http_status"] for row in rows[:4]}, {503}) - self.assertTrue(rows[4]["transcript_positions"]) - # Each wait doubles from 250ms, measured from the failed - # attempt's end to the next one's start. - gaps = [ - ( - datetime.fromisoformat( - after["started_at"].replace("Z", "+00:00") - ) - - datetime.fromisoformat( - before["ended_at"].replace("Z", "+00:00") - ) - ).total_seconds() - * 1000 - for before, after in zip(rows, rows[1:]) - ] - for gap, wait in zip(gaps, (250, 500, 1000, 2000)): - self.assertGreaterEqual(gap, wait) - finally: - provider.close() -- knotmirror 0.0.1