Skip to content

fix(server): respect upstream Retry-After during retries - #723

Open
Yezheng Li (yezhengli-Mr9) wants to merge 1 commit into
microsoft:mainfrom
yezhengli-Mr9:fix/proxy-retry-after-20261204
Open

Yezheng Li (yezhengli-Mr9) wants to merge 1 commit into
microsoft:mainfrom
yezhengli-Mr9:fix/proxy-retry-after-20261204

Conversation

@yezhengli-Mr9

@yezhengli-Mr9 Yezheng Li (yezhengli-Mr9) commented Dec 5, 2026 •

Copy link
Copy Markdown

Counterpart tools, related PRs, and research

Counterpart / related work Verified status Capability and nonduplicate boundary
OpenAI Python SDK retry policy Existing counterpart implementation Parses Retry-After seconds/dates and supports bounded server-directed delays. This PR uses the standard header as a minimum while keeping Agent Lightning's existing jittered backoff; it does not add OpenAI's millisecond extension or copy its retry policy.
HTTP Retry-After specification Protocol standard A server can advertise delay-seconds or an HTTP date. This is protocol handling, not a novel research algorithm.
#604 Merged PR Cancels gateway requests when agents disconnect. Existing cancellation and request ownership are unchanged, including during the new longer backoff.
#658 Open PR Handles invalid upstream response bodies. This PR changes retry scheduling only, not response decoding or error-event recording.
#673 Open issue Concerns deterministic 4xx retry eligibility in the agent-side client. This PR handles a separate boundary: upstream gateway HTTP response backoff.

Statuses verified on 2026-12-04 (Pacific time). Counterparts are comparisons, not added dependencies.

Sample and measured improvement

Concrete sample / input Pinned original Patched Measured improvement / preserved behavior
Constructed model endpoint is busy for 2 seconds, returning HTTP 503 with Retry-After: 2; fixed jitter multiplier 1.0. Requests at approximately 0, 0.5, 1.5 and 3.5 s: 4 requests. Requests at approximately 0 and 2 s: 2 requests. 2 fewer HTTP requests (50%), in each of three paired Windows trials. No model inference work is measured.
Same real-loopback-HTTP experiment; end-to-end retry recovery time, median of three alternating paired trials. 3.568719 s. 2.029792 s. 1.538927 s saved (43.12%) in this controlled overload fixture, not a production throughput estimate.
No-header control: endpoint busy for 0.25 s. 2 requests, median 0.534253 s. 2 requests, median 0.532484 s. Identical request work and scheduling policy. The ~1.8 ms difference is timing noise, not an attributed improvement.
Fixed-clock HTTP-date regression: now 12:00:00 UTC; header Fri, 04 Dec 2026 12:00:03 GMT. Sleeps 0.5 s, ignoring the date. Sleeps 3 s. Respects the remaining server cooldown; not a latency-saving claim for this case.
Same endpoint's successful response. {"choices":[{"message":{"content":"patch ready"}}]}. Identical parsed JSON and HTTP 200. Visible response unchanged in every paired trial.

Evidence: Windows / Python 3.12.16, actual gateway retry functions, real loopback HTTP sockets, three alternating baseline/patched pairs per condition. Baseline is 6d7f272806d0f210f6c98b32081adeccdeb343f7; jitter is fixed to 1.0 for both arms to isolate scheduling. These are constructed overload fixtures, not model inference, token savings, training, coding-task score or a research benchmark.

Summary

Fixes #722.

The gateway currently retries overloaded model servers without observing their cooldown headers. Pass Retry-After from a retryable HTTP response into the existing sleep, preserving max(jittered_backoff, server_delay).

Area Change / boundary
Standard header Accept nonnegative integer delay-seconds and HTTP dates.
Existing backoff Remains the minimum: a missing, zero or expired header does not shorten it.
Invalid header Log a warning and retain the established backoff; reject nonfinite numeric overflow.
Compatibility Retryable statuses, six-attempt limit, timeout/transport handling, response closure, cancellation and return values remain unchanged.
Delay limit Does not cap a valid server-directed delay below its advertised minimum. An unusually long valid delay remains cancellable; no new retry-budget configuration is introduced.
Source / tests Two changed files; 18 added source lines plus the focused docstring/imports and one eight-case parametrized regression in an existing test file.
Documentation Focused helper docstring and this PR description; no repository Markdown, dependency, version, model or workflow changes.

Executed validation

Validation Result
Original method, identical new cases 2 fail, 6 pass: numeric and future-date cases expose the missing header handling.
Patched focused retry/disconnect file 11 passed. Existing disconnect/backoff cancellation tests remain passing.
Gateway endpoints + disconnect/retry files 44 passed.
Whole-repository Ruff / formatting Passed, 123 Python files already formatted.
Focused Pyright 0 errors, 0 warnings.
Compilation / package build Passed; built the wheel without dependency changes.
Repository hooks All applicable pre-commit hooks passed on the two changed files.
Existing warnings Latest validation dependencies report fixture-loop-scope and Starlette/httpx deprecations; no unrelated configuration changes.
Azure experiment Authorized isolated compute, but not executed: selected subscription returned Forbidden before resource creation; the alternate subscription required interactive security-default authentication. No resources created or shared configuration changed; $0 provisioning spend.
Ubuntu full-suite CI 257 passed, 4 skipped on Linux/Python 3.12.16; all five existing workflow jobs succeeded: tests, whole-repository lint/hooks, full Pyright, package and documentation build. Fork-only validation, not green upstream CI or an Ubuntu timing experiment.

Reproduce tests

From a checkout with the dev dependencies installed:

python -m pytest tests/server/test_endpoints.py tests/server/test_proxy_disconnect.py -q
python -m ruff check .
python -m ruff format --check .
python -m pyright agentlightning/server/proxy.py tests/server/test_proxy_disconnect.py

The new tests need no model, GPU, API key or Docker daemon. They exercise actual HTTPX request/response handling with fixed clock/backoff and inspect the awaited delay. The timing experiment uses a separate real loopback HTTP server; its exact standalone runner is included below.

Review checklist

  • Numeric and HTTP-date regressions fail against the original methods.
  • Missing/invalid/expired/zero headers preserve established backoff.
  • Existing gateway endpoint and disconnect tests pass.
  • Complete two-file change reviewed; lint, typecheck, compilation and build passed.
  • No repository Markdown, dependency, model or workflow changes.
  • Live model overload experiment or coding benchmark executed.
  • Existing Ubuntu full-suite CI succeeded with identical production code.
  • Azure execution / Ubuntu timing experiment executed.
  • Upstream automatic CI completed successfully.

This is an engineering reliability contribution; no novelty or inference-efficiency claim is made.

Standalone paired HTTP experiment runner

Save as retry_after_experiment.py outside the repository and run in the installed development environment:

python retry_after_experiment.py --output retry-after-results.json
import argparse
import ast
import asyncio
import io
import json
import platform
import statistics
import subprocess
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from unittest.mock import patch

import httpx
import structlog

from agentlightning.server import proxy


async def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--baseline", default="6d7f272806d0f210f6c98b32081adeccdeb343f7")
    args = parser.parse_args()
    root = Path(proxy.__file__).parents[2]
    baseline_source = subprocess.check_output(
        ["git", "-C", str(root), "show", f"{args.baseline}:agentlightning/server/proxy.py"]
    ).decode("utf-8")
    tree = ast.parse(baseline_source)
    names = {"_send_upstream_with_retries", "_sleep_before_retry"}
    namespace = vars(proxy).copy()
    for node in tree.body:
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names:
            exec(compile(ast.Module(body=[node], type_ignores=[]), "<pinned-baseline>", "exec"), namespace)
    structlog.configure(logger_factory=structlog.PrintLoggerFactory(file=io.StringIO()))
    expected_body = {"choices": [{"message": {"content": "patch ready"}}]}
    rows = []
    for trial in range(3):
        for arm in (["baseline", "patched"] if trial % 2 == 0 else ["patched", "baseline"]):
            for busy_seconds, with_header in [(2.0, True), (0.25, False)]:
                calls = []
                started = None

                class Handler(BaseHTTPRequestHandler):
                    def do_POST(self):
                        nonlocal started
                        self.rfile.read(int(self.headers["Content-Length"]))
                        now = time.perf_counter()
                        if started is None:
                            started = now
                        elapsed = now - started
                        calls.append(elapsed)
                        ready = elapsed >= busy_seconds
                        payload = json.dumps(expected_body if ready else {"error": "busy"}).encode()
                        self.send_response(200 if ready else 503)
                        self.send_header("Content-Type", "application/json")
                        if not ready and with_header:
                            self.send_header("Retry-After", "2")
                        self.send_header("Content-Length", str(len(payload)))
                        self.end_headers()
                        self.wfile.write(payload)

                    def log_message(self, *args):
                        pass

                server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
                worker = threading.Thread(target=server.serve_forever, daemon=True)
                worker.start()
                try:
                    send = namespace["_send_upstream_with_retries"] if arm == "baseline" else proxy._send_upstream_with_retries
                    begin = time.perf_counter()
                    with patch.object(proxy.random, "uniform", return_value=1.0):
                        async with httpx.AsyncClient(timeout=10, trust_env=False) as client:
                            result = await send(
                                client=client, url=f"http://127.0.0.1:{server.server_port}/v1/chat/completions",
                                body={"messages": [{"role": "user", "content": "Return the patch"}]},
                            )
                    elapsed = time.perf_counter() - begin
                    assert result.status_code == 200 and result.json() == expected_body
                    assert len(calls) == (4 if arm == "baseline" and with_header else 2)
                    rows.append({
                        "trial": trial, "arm": arm, "retry_after": with_header,
                        "busy_seconds": busy_seconds, "requests": len(calls),
                        "seconds": elapsed, "request_offsets_seconds": calls,
                        "response_identical": True,
                    })
                finally:
                    server.shutdown()
                    server.server_close()
                    worker.join()
    summary = {}
    for with_header in [True, False]:
        medians = {
            arm: statistics.median(
                row["seconds"] for row in rows if row["arm"] == arm and row["retry_after"] == with_header
            )
            for arm in ["baseline", "patched"]
        }
        summary["retry_after" if with_header else "no_header_control"] = {
            "median_seconds": medians,
            "seconds_saved": medians["baseline"] - medians["patched"],
            "percent_saved": 100 * (medians["baseline"] - medians["patched"]) / medians["baseline"],
        }
    report = {
        "platform": platform.platform(), "python": platform.python_version(),
        "baseline_commit": args.baseline,
        "method": "Actual gateway retry functions against a real loopback HTTP server; three alternating paired trials; fixed jitter multiplier 1.0.",
        "limits": "Constructed CPU-only overload fixture. No live model, token savings, training, coding-task score or production-throughput claim.",
        "rows": rows, "summary": summary,
    }
    args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"output": str(args.output), "summary": summary}))


if __name__ == "__main__":
    asyncio.run(main())

Publication and CI status

Check Verified result
Fork Ubuntu CI All five jobs green at 5ed180ed10c3ef7c4da7f55d2f8addd39d8b952e. The only difference from the upstream feature head is the one-line push trigger in the fork's workflow; production source and tests are identical. No fork-only PR was created or merged.
Upstream workflow Exact-head run is action_required, waiting for maintainer approval; not claimed green. CLA processing was pending at publication.
Azure Execution blocked before provisioning; no resources created or modified.

@yezhengli-Mr9
Yezheng Li (yezhengli-Mr9) marked this pull request as ready for review December 5, 2026 02:46
Copilot AI balanced review requested due to automatic review settings December 5, 2026 02:46
@microsoft-github-policy-service

Copy link
Copy Markdown

Yezheng Li (@yezhengli-Mr9) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues are reported for the change to honor upstream Retry-After headers.

No open issues 🎉

What changed in this PR

Updates gateway retries to respect upstream Retry-After headers, addressing #722 while preserving existing jittered backoff and cancellation behavior.

Changes:

  • Handles delay-seconds and HTTP dates as minimum retry delays.
  • Logs invalid headers and retains existing backoff.
  • Adds eight regression cases covering valid, missing, invalid, and expired headers.
File Description
tests/​server/​test_proxy_disconnect.py Adds parametrized retry-delay regression coverage.
agentlightning/​server/​proxy.py Passes and parses Retry-After when scheduling retries.

Review effort: Balanced

This branch has not been deployed

No deployments
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.

Gateway ignores upstream Retry-After during overloaded model retries

2 participants