From bb58b4a38012234738ef1793d68983df76baa553 Mon Sep 17 00:00:00 2001 From: luk384090-cloud Date: Thu, 26 Nov 2026 17:17:37 +0800 Subject: [PATCH 1/2] fix(api): alias timeout to request_timeout and handle bare gateway errors - Treat the 'timeout' keyword as an alias for 'request_timeout' in the client - Log warnings when both 'timeout' and 'request_timeout' are provided - Prevent 'timeout' from being forwarded as a model parameter - Improve error messages for bare gateway responses with empty body and no content-type - Extract and expose 'x-request-id' header in error responses for better diagnostics - Add regression tests for timeout aliasing and bare gateway error handling in both sync and async cases - Include end-to-end tests verifying timeout enforcement and diagnostic error surfacing --- .../api_entities/api_request_factory.py | 18 ++ dashscope/legacy_1x/common/utils.py | 17 ++ .../test_request_timeout_and_bare_errors.py | 178 ++++++++++++++++++ 3 files changed, 213 insertions(+) create mode 100644 tests/legacy_1x/unit/test_request_timeout_and_bare_errors.py diff --git a/dashscope/legacy_1x/api_entities/api_request_factory.py b/dashscope/legacy_1x/api_entities/api_request_factory.py index 1ff1fc83..58d1b1bf 100644 --- a/dashscope/legacy_1x/api_entities/api_request_factory.py +++ b/dashscope/legacy_1x/api_entities/api_request_factory.py @@ -120,6 +120,24 @@ def _build_api_request( # pylint: disable=too-many-branches InputDataRequired: If input data is missing or invalid. UnsupportedApiProtocol: If the API protocol is not supported. """ + # ``timeout`` is the OpenAI-style spelling of ``request_timeout``. + # Without this alias it falls through to ``**kwargs`` and is sent to + # the service as a model parameter, while the client timeout silently + # stays at its default (see error-code report P2-1). + if "timeout" in kwargs: + alias_timeout = kwargs.pop("timeout") + if request_timeout is None: + logger.warning( + "'timeout' is treated as the client request timeout; " + "the canonical keyword is 'request_timeout'.", + ) + request_timeout = alias_timeout + else: + logger.warning( + "Both 'timeout' and 'request_timeout' were provided; " + "using 'request_timeout' and ignoring 'timeout'.", + ) + # Handle stream mode for WebSocket if not stream and ws_stream_mode == WebsocketStreamingMode.OUT: ws_stream_mode = WebsocketStreamingMode.NONE diff --git a/dashscope/legacy_1x/common/utils.py b/dashscope/legacy_1x/common/utils.py index 732e0971..be2ba404 100644 --- a/dashscope/legacy_1x/common/utils.py +++ b/dashscope/legacy_1x/common/utils.py @@ -340,6 +340,16 @@ def _handle_http_failed_response( ) else: msg = response.content.decode("utf-8") + # A bare gateway error (empty body, no content-type) used to + # surface as message="" / request_id="", leaving the caller no + # clue it was not a model-level 404. Keep the server's real + # status, but explain the shape and salvage the header id. + request_id = response.headers.get("x-request-id", "") + if not msg: + msg = ( + f"HTTP {response.status_code} with empty response body " + "and no content-type (bare gateway response)." + ) if flattened_output: return {"status_code": response.status_code, "message": msg} # type: ignore[return-value] # pylint: disable=line-too-long # noqa: E501 return DashScopeAPIResponse( @@ -412,6 +422,13 @@ async def _handle_aiohttp_failed_response( ) else: msg = await response.text() + # Same bare-gateway treatment as the sync path above. + request_id = response.headers.get("x-request-id", "") + if not msg: + msg = ( + f"HTTP {response.status} with empty response body " + "and no content-type (bare gateway response)." + ) if flattened_output: return {"status_code": response.status, "message": msg} # type: ignore[return-value] # pylint: disable=line-too-long # noqa: E501 return DashScopeAPIResponse( diff --git a/tests/legacy_1x/unit/test_request_timeout_and_bare_errors.py b/tests/legacy_1x/unit/test_request_timeout_and_bare_errors.py new file mode 100644 index 00000000..050e0844 --- /dev/null +++ b/tests/legacy_1x/unit/test_request_timeout_and_bare_errors.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +# Copyright (c) Alibaba, Inc. and its affiliates. +"""Regression tests for error-code report P2-1 (SDK side). + +1. ``timeout=`` on legacy APIs is an alias of ``request_timeout`` and + must arm the client timeout instead of being forwarded to the + service as a model parameter. +2. A bare gateway error response (empty body, no content-type) must + surface a diagnostic message and the ``x-request-id`` header, while + keeping the server's real status code. +""" + +import asyncio +import json +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest +import requests + +import dashscope +from dashscope import Generation +from dashscope.legacy_1x.api_entities.api_request_factory import ( + _build_api_request, +) +from dashscope.legacy_1x.common.utils import ( + _handle_aiohttp_failed_response, + _handle_http_failed_response, +) + + +def _build(timeout_kwargs): + return _build_api_request( + model="qwen-plus", + input={"messages": [{"role": "user", "content": "hi"}]}, + task_group="aigc", + task="text-generation", + function="generation", + api_key="sk-test", + **timeout_kwargs, + ) + + +class TestTimeoutAlias: + def test_timeout_arms_client_timeout(self): + request = _build({"timeout": 7}) + assert request.timeout == 7 + assert "timeout" not in request.data.parameters + + def test_request_timeout_wins_over_alias(self): + request = _build({"timeout": 7, "request_timeout": 5}) + assert request.timeout == 5 + assert "timeout" not in request.data.parameters + + def test_no_timeout_keeps_default(self): + request = _build({}) + assert request.timeout == 300 + assert "timeout" not in request.data.parameters + + +def _bare_response(status=404, request_id="rid-bare"): + response = requests.Response() + response.status_code = status + response.headers["x-request-id"] = request_id + response._content = b"" # pylint: disable=protected-access + return response + + +class TestBareErrorResponse: + def test_sync_bare_404_diagnostic(self): + rsp = _handle_http_failed_response(_bare_response()) + assert rsp.status_code == 404 + assert rsp.code == "Unknown" + assert rsp.request_id == "rid-bare" + assert "empty response body" in rsp.message + + def test_sync_non_json_body_preserved(self): + response = _bare_response() + response._content = b"oops" # pylint: disable=protected-access + rsp = _handle_http_failed_response(response) + assert rsp.message == "oops" + assert rsp.request_id == "rid-bare" + + def test_aio_bare_404_diagnostic(self): + class _StubAioResponse: + status = 404 + content_type = "" + headers = {"x-request-id": "rid-aio"} + + async def text(self): + return "" + + rsp = asyncio.run( + _handle_aiohttp_failed_response(_StubAioResponse()), + ) + assert rsp.status_code == 404 + assert rsp.code == "Unknown" + assert rsp.request_id == "rid-aio" + assert "empty response body" in rsp.message + + +class _CapturingHandler(BaseHTTPRequestHandler): + """Records the request body; behavior set via server attributes.""" + + def do_POST(self): + body = self.rfile.read(int(self.headers["Content-Length"])) + self.server.captured.append(json.loads(body)) + if self.server.stall_seconds: + time.sleep(self.server.stall_seconds) + payload = json.dumps( + {"output": {"text": "ok"}, "request_id": "rid-slow"}, + ).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + else: + # Bare gateway 404: empty body, no content-type. + self.send_response(404) + self.send_header("x-request-id", "rid-bare-404") + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): + pass + + +@pytest.fixture +def local_server(monkeypatch): + servers = [] + + def _start(stall_seconds=0): + srv = ThreadingHTTPServer(("127.0.0.1", 0), _CapturingHandler) + srv.captured = [] + srv.stall_seconds = stall_seconds + threading.Thread(target=srv.serve_forever, daemon=True).start() + servers.append(srv) + monkeypatch.setattr( + dashscope, + "base_http_api_url", + f"http://127.0.0.1:{srv.server_port}/api/v1", + ) + monkeypatch.setattr(dashscope, "api_key", "sk-test") + return srv + + yield _start + for srv in servers: + srv.shutdown() + + +class TestGenerationEndToEnd: + def test_timeout_alias_raises_on_slow_response(self, local_server): + local_server(stall_seconds=3) + start = time.time() + with pytest.raises(requests.exceptions.Timeout): + Generation.call( + model="qwen-plus", + messages=[{"role": "user", "content": "hi"}], + timeout=1, + ) + assert time.time() - start < 2.5 + + def test_bare_404_surfaces_diagnostics(self, local_server): + srv = local_server() + rsp = Generation.call( + model="qwen-plus", + messages=[{"role": "user", "content": "hi"}], + max_tokens=1500, + timeout=1, + ) + assert rsp.status_code == 404 + assert rsp.code == "Unknown" + assert rsp.request_id == "rid-bare-404" + assert "empty response body" in rsp.message + # The alias must not leak into the wire body parameters. + assert "timeout" not in srv.captured[0]["parameters"] \ No newline at end of file From 1e1418c9546c3deb9473cf7297f9d42cf8a0e11b Mon Sep 17 00:00:00 2001 From: luk384090-cloud Date: Thu, 26 Nov 2026 17:23:12 +0800 Subject: [PATCH 2/2] test(legacy): preserve sync non-JSON body content in response handling - Adjust response content assignment formatting in test for clarity - Verify that response message retains raw HTML content - Confirm that request ID is correctly extracted from bare response - Ensure no parameter leakage to wire body during timeout scenarios --- .../legacy_1x/unit/test_request_timeout_and_bare_errors.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/legacy_1x/unit/test_request_timeout_and_bare_errors.py b/tests/legacy_1x/unit/test_request_timeout_and_bare_errors.py index 050e0844..4f969a8e 100644 --- a/tests/legacy_1x/unit/test_request_timeout_and_bare_errors.py +++ b/tests/legacy_1x/unit/test_request_timeout_and_bare_errors.py @@ -77,7 +77,9 @@ def test_sync_bare_404_diagnostic(self): def test_sync_non_json_body_preserved(self): response = _bare_response() - response._content = b"oops" # pylint: disable=protected-access + response._content = ( + b"oops" # pylint: disable=protected-access + ) rsp = _handle_http_failed_response(response) assert rsp.message == "oops" assert rsp.request_id == "rid-bare" @@ -175,4 +177,4 @@ def test_bare_404_surfaces_diagnostics(self, local_server): assert rsp.request_id == "rid-bare-404" assert "empty response body" in rsp.message # The alias must not leak into the wire body parameters. - assert "timeout" not in srv.captured[0]["parameters"] \ No newline at end of file + assert "timeout" not in srv.captured[0]["parameters"]