Skip to content

Retry transient failures and reuse connections in HTTP targets - #189

Merged
kelkalot merged 1 commit into
devfrom
fix/targets-http
Dec 4, 2026
Merged

kelkalot merged 1 commit into
devfrom
fix/targets-http

Conversation

@Robrusi

@Robrusi Robrusi commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #107 (gaps 2 and 3). #131 fixed both for DecisionTarget and was merged into dev on 28 Oct, but the force-push of dev on 4 Nov dropped it, so it has not been on dev or in a release since. This PR covers the same two gaps for HTTPAppTarget, DecisionTarget and ASRTarget.

Differences from #131:

Problem

  • HTTPAppTarget, DecisionTarget and ASRTarget sent each turn once. A single 408, 429 or 5xx, a timeout or a dropped connection made the scenario an ERROR.
  • Each turn opened and closed its own httpx.AsyncClient.
  • DecisionTarget failed with a bare JSONDecodeError on a body that isn't JSON, and didn't show the body when the reply had no answer.
  • ASRTarget read the audio file on the event loop.

Fix

  • Retries.
    • 408, 429, 5xx other than 501/505/511, timeouts, and failed or dropped connections are retried max_retries times (new, default 2).
    • The wait is retry_backoff * 2**attempt (default 0.5 s) plus up to 25% jitter, or the server's Retry-After (seconds or an HTTP date), capped at 60 s.
    • Any other 4xx fails at once.
    • These are the target's own settings: the Auditor's max_retries does not apply to them.
  • Connections.
    • There is one client per target per event loop. It is closed when the loop shuts down, when the target is garbage-collected, or by the new aclose().
    • There is no connection cap. With max_retries=0 the client keeps no idle connections, so each turn goes out once on a fresh connection.
    • timeout is sent with each request, so changing it takes effect.
    • Copies and pickles start without clients.
    • An injected client= is never closed by the target, and keeps its own timeout and limits.
  • DecisionTarget.
    • A body that isn't JSON raises ValueError, and a reply without an answer raises RuntimeError. Both show the start of the body.
    • post_systemone gains max_retries (default 0) and request_timeout (default None), so the decision judge is unchanged.
  • ASRTarget reads the file with asyncio.to_thread.
  • Docs. The README and docstrings cover duplicate requests, the jitter, the rough worst-case turn time and closing a loop you run yourself.

Notes:

  • Retries are on by default, so a POST can be resent after a timeout, protocol error or 500 that the server may already have processed. Every attempt carries the same X-SimpleAudit-Turn-ID and traceparent.
  • A loop closed without shutdown_asyncgens() keeps connections open until aclose() is called or the target is collected.
  • The worst-case turn time is roughly (max_retries + 1) × timeout plus the waits: about 5 minutes for HTTP, about 17 for Decision and ASR. It is not a hard limit, because httpx times each phase of a request separately.
  • ASR holds the whole audio file in memory. The API limit is 25 MB.
  • For a decision body that isn't JSON, the failure records ValueError instead of JSONDecodeError. The failure kind is unchanged.

Testing

  • tests/test_http_targets.py: 3 tests, 10 cases, all of which fail on dev.
  • test_asr.py::test_bad_responses uses retry_backoff=0. test_decision_target.py checks the client timeout rather than the exact constructor arguments.
  • Against a real local keep-alive server:
    • stale idle connections with max_retries=0: 48/48 turns ok;
    • 400 concurrent turns: all ok;
    • changing timeout takes effect;
    • deepcopy and pickle of a used target work;
    • 501, 505 and 511 are sent once.
  • Lifecycle, with ResourceWarnings captured, on Python 3.11–3.14: asyncio.run, Runner, threads, GC, cancellation, and an injected client left open.
  • 200k-value Retry-After fuzz: no exceptions.
  • Full suite on Python 3.12: 4233 passed, 14 skipped.

Written by Opus 5.5

HTTPAppTarget, DecisionTarget and ASRTarget sent each turn once, so a
single 408, 429 or 5xx, a timeout or a dropped connection turned the
whole scenario into ERROR. They also opened a new httpx.AsyncClient for
every turn. DecisionTarget failed with a bare JSONDecodeError on a body
that is not JSON and did not show the body when the reply had no
answer, and ASRTarget read the audio file on the event loop.

- Retry HTTP 408, 429 and 5xx other than 501, 505 and 511, timeouts and
  dropped connections, waiting retry_backoff * 2**attempt seconds plus
  up to 25% jitter, or the server's Retry-After (seconds or an HTTP
  date; one that cannot be parsed falls back to the backoff), each wait
  capped at 60 s. New max_retries (default 2) and retry_backoff (default
  0.5) parameters, separate from the Auditor's max_retries;
  max_retries=0 sends each turn once. Any other 4xx fails at once.
  HTTPAppTarget and DecisionTarget resend the same body and headers;
  ASRTarget resends the same form fields, file contents, authorization
  and trace headers, under a new multipart boundary.
- Keep one client per running event loop, closed when the loop shuts
  down, when the target is garbage-collected, or by the new aclose().
  The client has no connection cap, so concurrent turns never wait for
  a connection, and with max_retries=0 it keeps no idle connections, so
  each turn goes out once on a new connection. The target's timeout is
  sent with each request, so changing target.timeout takes effect. A
  copied or pickled target starts without clients. An injected client
  stays the caller's, with its own timeout and limits.
  ModelAuditor.aclose() still closes only the auditor's own model
  clients.
- DecisionTarget: a body that is not JSON raises a ValueError, and a
  reply without an answer a RuntimeError, both showing the start of the
  body. post_systemone takes max_retries (default 0) and
  request_timeout, so DecisionJudgeClient keeps its own retry loop and
  timeout handling as before.
- ASRTarget reads the audio file with asyncio.to_thread.

The target docstrings and the README describe duplicate requests
(X-SimpleAudit-Turn-ID), the rough worst-case turn time (httpx applies
the timeout to each phase of a request, not to the whole of it), the
jitter, closing a manually run event loop, and that the Auditor's
max_retries does not apply to these targets.
@avalyset

avalyset commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

#131 added retries and client reuse to DecisionTarget (gaps 2 and 3 in #107), together with the endpoint provenance from #119. It was merged into dev on 28 Oct (9cdb464). The force-push of dev on 4 Nov (543e6ca → dac3fcc) reset the branch to a commit from 2 Oct, and #131 was not merged again. It has not been on dev since, and it has never been in a release. #189 covers the same two gaps for all three targets. Could the description reference #107 and #131, so the history can be traced?

@Robrusi

Robrusi commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for tracing that. I've added #107 and #131 to the description, along with how this PR differs from #131. #119's endpoint provenance isn't part of this PR, so it is still missing from dev.

@kelkalot kelkalot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review notes. One point I'd like fixed before merging; the rest can follow later.

Before merging

  1. Cookies are now shared between scenarios (simpleaudit/targets/_http.py, LoopClients.get). An httpx.AsyncClient stores every Set-Cookie it receives and sends it with later requests. Until now each turn had its own client, so no request carried a cookie. With one client per event loop, an app that keeps conversation state in a session cookie receives scenario A's cookie on scenario B's turns. Checked with httpx 0.28.1 and a mock transport: the second request on a shared client carries the cookie from the first reply. A client created with cookies=CookieJar(policy=DefaultCookiePolicy(allowed_domains=[])) (from http.cookiejar) stores nothing, and a Cookie header set by the caller is still sent. Could the targets' own clients be created like that, with a test?

Can follow later

  1. max_retries and retry_backoff are not validated. max_retries=None fails on the first turn with a TypeError, and a negative value is silently treated as 0.
  2. A wait taken from Retry-After gets no jitter, so parallel scenarios that were rate-limited together also retry together.
  3. A Retry-After longer than 60 s is shortened to 60 s, and the request is sent again before the server allows it.
  4. copy.copy(target) shares the original's clients. Only deepcopy and pickle start without clients, while the docstring says every copy does.
  5. test_without_a_client_one_is_created_per_request_and_closed now covers one client per loop. Its name and the loosened assertion no longer say that.
  6. Failures that a retry cannot fix (unknown host, refused connection, certificate error) are retried like transient ones.

Retries are on by default, so the release notes should list this under behaviour changes.

@kelkalot
kelkalot merged commit 6e94212 into dev Dec 4, 2026
8 checks passed
kelkalot pushed a commit that referenced this pull request Dec 4, 2026
Restores #119's endpoint provenance, which went into dev with #131 and was
lost in the 4 Nov force-push, on top of #189's _http.py.

ASRTarget, DecisionTarget and HTTPAppTarget add an endpoint block (scheme,
host, port, via_proxy) to TargetResponse.raw and warn once at construction
on plain http to a non-loopback host. ASRTarget uploads the file as
audio<suffix>. The warning now points at the caller also when the target is
built through a classmethod, and a suffix that is not a short extension is
dropped from the upload name. Retries and client reuse from #189 are
unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants