Retry the authenticated download hop under a declared set, in every SDK

Merged
JE
4mo ago
+2623-413

SPEC §14 prescribed a two-hop download that threw on the first error, while conformance/tests/downloads.json asserted retry at hop 1 — so four of the five runners carried a skip for the same two fixtures and the spec was the thing that was wrong. This makes §14 honest and brings every SDK to it.

The policy (§14, new "Hop-1 Retry [conformance]" subsection):

  • Hop 1 retries network errors plus {429, 502, 503, 504} — never 500. 500 stays out deliberately: the download hop keeps the main GET loop's declared-set discipline rather than the error taxonomy's broader "all 5xx retryable" flag.
  • Exponential backoff from a 1-second base, Retry-After honored on 429.
  • Every hop-1 attempt is authenticated — each attempt re-runs the auth strategy so a rotated token is picked up.
  • Hop 2 is exempt: never retried, never authenticated. The signed URL is single-purpose and credentials must not leak to the storage host.
  • Disabling retry yields exactly one hop-1 attempt everywhere.

Attempt budgets, per SDK:

SDKBudget
GoMaxRetries as total attempts (hand-written client rejects < 1)
Pythonmax_retries as total attempts, floored at one
Rubymax_retries as total attempts, floored at one for downloads; the ungoverned GET path's zero-attempt behavior stays tracked in #532
KotlinmaxRetries as total attempts, floored at one, gated on enableRetry
TypeScriptFixed three attempts when enableRetry, one when false. No public numeric knob.
SwiftFixed three attempts when enableRetry, one when false. No public numeric knob.

DownloadURL is deliberately absent from behavior-model.json, so every SDK passes this policy to its retry primitive directly rather than looking it up by operation.

Per-SDK

TypeScript — lifted the retry loop out of createRetryingFetch into retry.ts as executeWithRetry(makeAttempt, config, emit, signal) with four seams: attempt begin/finalize/retrying emission, caller-owned attempt preparation (request rebuild + auth refresh, terminal-marked so auth faults keep their identity past retry classification), per-attempt fetch, and the signal-aware backoff sleep. The client's middleware path delegates to it unchanged; download.ts adopts it with the fixed policy.

Python — get_no_retry becomes get_download, running through _request_with_retry with an explicit retry_on. Sync and async transports change identically.

Ruby — get_no_retry becomes get_download, running through request_with_retry with an explicit retry_on; the declared set is authoritative in both directions (the taxonomy neither widens nor vetoes it).

Kotlin — hop 1 now runs in downloadHop1, a directive-shaped loop mirroring BasecampHttpClient.requestWithRetry (#517): catch clauses only classify the attempt's outcome, and the retry side effects run outside any catch, so a CancellationException from the backoff propagates raw and no phantom request events fire for an attempt that already ended. A throwing auth strategy surfaces raw through an internal tag, spending no retry budget.

Swift — performDownloadRequest gains the same #517 directive loop. Pinned by native XCTests only; the Swift conformance runner lands in #558.

Go — already conformed; this is a pin, no behavior change. Its tests covered only three of five edges (503, 429-with-Retry-After, network errors), so 502/504 rode along untested, the 500 carve-out was only implied by a 404 case, and nothing asserted a retried attempt still carries Authorization.

Red proofs

Each SDK's new tests run against that SDK's pristine (pre-change) implementation, swapped in with git show origin/main:<path>.

TypeScript — npx vitest run tests/download.test.ts against pristine download.ts:

× retries hop 1 on 429, then follows the redirect
× retries hop 1 on 502, then follows the redirect
× retries hop 1 on 503, then follows the redirect
× retries hop 1 on 504, then follows the redirect
× retries hop 1 on a network error
× exhausts the three-attempt budget and surfaces the final error
× sends Authorization on every hop-1 attempt and never on hop 2
× fires balanced start/end hooks and one onRetry per backoff
× honors Retry-After on 429 at the client level
Tests  9 failed | 32 passed (41)

Python — uv run pytest tests/test_download.py against pristine download.py + _http.py + _async_http.py:

FAILED tests/test_download.py::TestHop1Retry::test_retries_declared_status_then_succeeds[429]
FAILED tests/test_download.py::TestHop1Retry::test_retries_declared_status_then_succeeds[502]
FAILED tests/test_download.py::TestHop1Retry::test_retries_declared_status_then_succeeds[503]
FAILED tests/test_download.py::TestHop1Retry::test_retries_declared_status_then_succeeds[504]
FAILED tests/test_download.py::TestHop1Retry::test_retries_network_error_then_succeeds
FAILED tests/test_download.py::TestHop1Retry::test_exhausts_cap_then_surfaces_error
FAILED tests/test_download.py::TestHop1Retry::test_auth_on_every_hop1_attempt_never_on_hop2
FAILED tests/test_download.py::TestHop1Retry::test_balanced_hooks_across_retries
FAILED tests/test_download.py::TestHop1Retry::test_honors_retry_after_on_429
FAILED tests/test_download.py::TestHop1RetryAsync::test_retries_declared_status_then_succeeds[429]
FAILED tests/test_download.py::TestHop1RetryAsync::test_retries_declared_status_then_succeeds[502]
FAILED tests/test_download.py::TestHop1RetryAsync::test_retries_declared_status_then_succeeds[503]
FAILED tests/test_download.py::TestHop1RetryAsync::test_retries_declared_status_then_succeeds[504]
FAILED tests/test_download.py::TestHop1RetryAsync::test_retries_network_error_then_succeeds
14 failed, 15 passed in 0.59s

Ruby — bundle exec ruby -Itest -Ilib test/basecamp/download_test.rb against pristine http.rb + client.rb:

Basecamp::ApiError: Gateway error (502)
Basecamp::ApiError: Gateway error (503)
Basecamp::ApiError: Gateway error (504)
Basecamp::RateLimitError: Rate limit exceeded
Basecamp::NetworkError: Connection failed
NoMethodError: undefined method 'get_download' for #<Basecamp::Http>
41 runs, 54 assertions, 1 failures, 8 errors, 0 skips

Kotlin — ./gradlew :basecamp-sdk:jvmTest --tests "com.basecamp.sdk.DownloadTest" --rerun-tasks against pristine Download.kt:

DownloadTest[jvm] > downloadURL_exhaustsCapThenSurfacesError()[jvm] FAILED
    org.opentest4j.AssertionFailedError at DownloadTest.kt:572

DownloadTest[jvm] > downloadURL_authOnEveryHop1AttemptNeverOnHop2()[jvm] FAILED
    com.basecamp.sdk.BasecampException$Api at DownloadTest.kt:642

DownloadTest[jvm] > downloadURL_honorsRetryAfterOn429()[jvm] FAILED
    com.basecamp.sdk.BasecampException$RateLimit at DownloadTest.kt:735

DownloadTest[jvm] > downloadURL_retriesNetworkErrorThenSucceeds()[jvm] FAILED
    com.basecamp.sdk.BasecampException$Network at DownloadTest.kt:546

DownloadTest[jvm] > downloadURL_retriesDeclaredStatusesThenFollowsRedirect()[jvm] FAILED
    com.basecamp.sdk.BasecampException$RateLimit at DownloadTest.kt:479

DownloadTest[jvm] > downloadURL_balancedHooksAcrossRetries()[jvm] FAILED
    com.basecamp.sdk.BasecampException$Api at DownloadTest.kt:685

36 tests completed, 6 failed

Kotlin conformance, same pristine Download.kt with KOTLIN_SKIPS already emptied:

  FAIL: DownloadURL retries on 503 at the auth'd first hop
        Expected 4 requests, got 1
  FAIL: DownloadURL retries hop 1 on a network error
        Expected 3 requests, got 1
  PASS: DownloadURL does not retry hop 1 on 500
  FAIL: DownloadURL honors Retry-After on 429 at the auth'd first hop
        Expected 3 requests, got 1
Passed: 129, Failed: 3, Skipped: 1, Total: 133

Swift — swift test --filter DownloadTests against pristine HTTPClient.swift + Download.swift:

testDownloadURL_authOnEveryHop1AttemptNeverOnHop2 : failed: caught error: "api(message: "service unavailable", httpStatus: Optional(503))"
testDownloadURL_balancedHooksAcrossRetries : failed: caught error: "api(message: "service unavailable", httpStatus: Optional(503))"
testDownloadURL_cancellationDuringBackoffPropagatesRaw : failed - Expected CancellationError, got api(message: "service unavailable", httpStatus: Optional(503))
testDownloadURL_cancellationDuringBackoffPropagatesRaw : XCTAssertEqual failed: ("[]") is not equal to ("[2]") - A cancelled backoff must not emit a second onRetry
testDownloadURL_exhaustsThreeAttemptsThenSurfaces : XCTAssertEqual failed: ("1") is not equal to ("3")
testDownloadURL_honorsRetryAfterOn429 : failed: caught error: "rateLimit(message: "client error", retryAfterSeconds: Optional(2))"
testDownloadURL_retriesDeclaredStatusesThenFollowsRedirect : failed: caught error: "rateLimit(message: "client error", retryAfterSeconds: nil)"
testDownloadURL_retriesNetworkErrorThenSucceeds : failed: caught error: "network(message: "Network error", cause: Optional(TestError()))"

Executed 33 tests, with 8 failures (5 unexpected) in 0.544 seconds

testDownloadURL_neverRetries500 and testDownloadURL_enableRetryFalseSendsExactlyOneAttempt pass against pristine by construction — pristine never retries. They pin the ceiling, not the floor.

Go — the implementation is unchanged, so the pins are proved by mutating it instead. Three mutations, each restored:

Narrow the switch back to {429, 503}:

--- FAIL: TestDownloadURL_AuthHopDeclaredRetrySet
    --- PASS: .../429_is_retried
    --- FAIL: .../502_is_retried
    --- PASS: .../503_is_retried
    --- FAIL: .../504_is_retried
    --- PASS: .../500_is_outside_the_set

Widen it to the all-5xx taxonomy shape (429 || >= 500):

--- FAIL: TestDownloadURL_AuthHopDeclaredRetrySet
    --- PASS: .../429_is_retried
    --- PASS: .../502_is_retried
    --- PASS: .../503_is_retried
    --- PASS: .../504_is_retried
    --- FAIL: .../500_is_outside_the_set

Authenticate only on attempt 1:

    download_test.go:1005: hop-1 attempt 2: expected "Bearer test-token", got ""
--- FAIL: TestDownloadURL_AuthHopAuthOnEveryAttemptNeverOnHop2

Hop-2 no-auth verification

The credential boundary is asserted at three levels, and every level checks both directions — present on hop 1, absent on hop 2:

  1. Fixture — downloads.json's 503 case now asserts headerPresent: Authorization at index 0, 1, and 2 (previously index 0 only, so a retry that dropped the token would have passed) and headerAbsent: Authorization at index -1. Both new cases carry the same pair.
  2. Native, every SDK — a dedicated test records the Authorization header on each hop-1 attempt and on the signed hop across a 503 → 302 → 200 flow, asserting ["Bearer test-token", "Bearer test-token"] then absent. Go's is new in this PR; the others ship with their SDK commit. Proved load-bearing in Go by authenticating only on attempt 1 (above).
  3. Implementation — hop 2 is a separate bare call in all six SDKs (fetchSignedDownload, a fresh unauthenticated client, a bare Net::HTTP GET, a Ktor request with no auth block, raw fetch), outside the retry loop entirely.

Fixture and roster deltas

conformance/tests/downloads.json:

  • 503 case — description corrected (it claimed "SDK-wide GET retry semantics: retry on 5xx", which was never true and contradicts the 500 carve-out); Authorization now asserted on every hop-1 attempt, not just the first.
  • New: "DownloadURL retries hop 1 on a network error" — {networkError: true} → 302 → 200, 3 requests, delayBetweenRequests ≥ 1000, auth on both hop-1 attempts and absent on hop 2.
  • New: "DownloadURL does not retry hop 1 on 500" — one request, status 500.

Both new cases are registered in SPEC Appendix D (§14, §7). The §19 category table needs no new row — they live in the already-listed downloads.json.

SPEC §19 zero-skip roster — all eight download-retry lines deleted (Python ×2, Ruby ×2, TypeScript ×2, Kotlin ×2), matching the runners:

RunnerBeforeAfter
Python SKIPS20 — none
Ruby RUBY_SKIPS1311 (all waiver 2B.3 GET-only)
TypeScript TS_SDK_SKIPS31 (waiver 1B.6, 53-bit Number)
Kotlin KOTLIN_SKIPS20 — empty; one tag-based link-header branch remains (architectural)
Go goSDKSkips22 (unchanged, architectural)

No unwaivered skips remain in any runner.

Guard repoint

scripts/check-retry-metadata-parity.py's token smoke watched client.ts and http.rb for expressions the refactors relocated — TypeScript's loop moved to retry.ts, and Ruby's status gate became retry_eligible?, where the declared set arrives from either the operation's metadata or an explicit set. The guard now watches where the behavior lives: a client.ts row for resolving the tuple and delegating, a new retry.ts row for the loop, and a Ruby row requiring the metadata read and the membership test as separate tokens. Strength is unchanged — stubbing config.retryOn.includes in retry.ts or declared.include? in http.rb still reddens the check.

Verification

make check green end to end.

SuiteResult
Gook all packages
TypeScript76 files, 1051 tests passed
Python759 passed
Ruby1009 runs, 2280 assertions, 0 failures, 0 errors
KotlinBUILD SUCCESSFUL
Swift275 tests, 0 failures
Conformance runnerResult
Go131 passed, 0 failed, 2 skipped
Kotlin132 passed, 0 failed, 1 skipped
TypeScript153 passed, 2 skipped, 0 failed
Ruby122 passed, 0 failed, 11 skipped
Python133 passed, 0 failed, 0 skipped

Follow-up

Draft PR #558 (Swift conformance runner) carries two temporary skips for exactly these fixtures — "DownloadURL retries on 503 at the auth'd first hop" and "DownloadURL honors Retry-After on 429 at the auth'd first hop" — which it flips to live once this merges. Not touched here; that flip belongs to #558's own landing checklist.


Review round

14 threads (Codex ×1, cubic ×13; Copilot errored out again). Four changed the code, four became issues or were declined on verified evidence, the rest are recorded below with reasoning.

Fixed

  • Python + Ruby hop 1 sent Accept: application/json (4710daa7c). Real, and a §14 violation — line 988 has always said hop 1 sets Authorization and User-Agent only. Not a regression, though: main's get_no_retry went through the same header builder, so the header rode on the single attempt too. Both transports now thread an accept seam from the retry entry point to the header builder, defaulting to the JSON Accept so every other caller is untouched; the download hop passes none, and the 401-refresh replay carries it through. What remains on the wire is the HTTP library's own default (httpx */*, Faraday nothing) — the tests pin hop 1 against the bare hop-2 client rather than pretending the SDK controls it. Red against the un-fixed transports in both languages.
  • Kotlin's DownloadAuthFailure duplicated AuthPhaseFailure (b1fd56787). Same shape, same job. AuthPhaseFailure is now internal and shared.
  • Swift's cancellation test polled unbounded (b1fd56787). while transport.requests.isEmpty now gives up after five seconds with a named failure instead of hanging the suite.

Filed, not fixed here

  • #564 — Retry-After ignores the HTTP-date form and non-positive deltas. SPEC §6:421 specifies integer-> 0, then HTTP-date, then fall through. No SDK does step 2; TypeScript also skips the > 0 guard, so Retry-After: 0 gives a 0 ms delay. All pre-existing — the TypeScript block is a character-for-character lift of client.ts:1114-1121 on main. Fixing it means six parsers plus a fixture for the date form, and a decision on whether §6 step 2 survives.
  • #565 — a 401 refresh replay is not counted against the attempt cap. True, and unchanged by this PR: the replay lives in _single_request, which main's get_no_retry already called. Definitional rather than mechanical — is re-authentication a retry? — so it wants a decision before a patch.

Declined, with evidence

  • "Release the discarded Ktor response before retrying" (Codex P2 + cubic, 2 threads). The premise does not hold on Ktor 3.5.1: HttpClient's constructor installs SaveBody unconditionally (verified in javap output), and the plugin's own deprecation text states "Request bodies are now saved in memory by default for all non-streaming responses". downloadHop1 uses client.request(url) — non-streaming — so the connection is released before it returns and response.cancel() would be a no-op. The shipping BasecampHttpClient.requestWithRetry has the identical shape, so if the premise held it would be a live bug on main.
  • "Retry a BasecampError.network from the transport" (Swift). Deliberate, and identical to performRequest's documented classification: the response-type guard raises it for a programming error, and a transport that pre-wraps failures as BasecampError has opted into terminal handling. Diverging one loop from the other on a shared rule is worse than the gap.
  • A Swift base-delay test seam. The ~13s buys a red proof that swaps in origin/main's files untouched. A seam has to exist in the source for the tests to compile, which makes "pristine" no longer pristine.
  • delays[:-1] in the Python conformance runner. The change was an alignment, not a regression — Go and Ruby already gate on the first gap, and any(...) failed on a correct implementation because the download flow's final gap is the deliberately un-delayed redirect hop. [:-1] is a better rule, but applying it to one runner of five is how a regression gets caught in one language and tolerated in the rest.
  • Ruby final-attempt "no sleep, no on_retry" pin, and hoisting DOWNLOAD_RETRY_ON out of the two Python transports. Both fair; both wrong to do in one SDK when five carry the same shape.

make check re-run green end to end after the round (REAL_EXIT=0): Go ok, TypeScript 1051, Python 761, Ruby 1010 runs / 2283 assertions, Kotlin BUILD SUCCESSFUL, Swift 275 — conformance 131/132/153/122/133, zero failures.