feat: add an optional per-call wall-clock deadline

Give one logical call an optional hard wall-clock boundary (issue #22).
Leaving it unset keeps 1.3.5 behaviour verbatim: the timeout context is
never entered when deadline_s is None.

- new deadline.py: ensure_call_deadline() range check (None or a finite
  positive number; bool/0/nan/inf and out-of-range ints are rejected as
  ValueError so OverflowError never leaks) plus with_call_deadline(),
  which distinguishes an expiry from a TimeoutError raised by the body
  or its cleanup via a local-variable identity comparison rather than
  cm.expired() alone
- new CallDeadlineExceeded: deliberately outside the four categories and
  not a GatewayUnavailableError, and carries no retry_after_s
- new {SCOPE}__CALL_DEADLINE_S key, guarded on the env, direct
  construction and dataclasses.replace paths
- three clients take a call_deadline_s constructor argument and a
  keyword-only per-call override on chat/embed/recognize_text/
  parse_layout; None inherits the assembled value
- validation runs before the awaitable is created, so an illegal value
  cannot strand an un-awaited coroutine
- one embed call shares a single deadline across all of its batches
- import-linter gains a polygateway.deadline layer

- cover where the deadline lands: backoff sleep, admission polling,
  the structured re-ask ladder and embedding's batch loop, plus the
  empty-texts early return that stays outside it
- cover what an expiry costs: exactly one terminal_failure row carrying
  error_type=CallDeadlineExceeded, a cancelled attempt row sharing its
  logical_call_id, cleanup that outlives the deadline (lower bound only)
  and an already-billed success being discarded
- pin the injected clock as orthogonal: a 10^6 second jump never expires
  a call, yet total_latency_ms still reads that clock
This commit is contained in:
2026-09-10 01:13:00 -04:00
parent 1ff83bbfe0
commit 9474c76ab0
13 changed files with 730 additions and 5 deletions
+55
View File
@@ -1041,3 +1041,58 @@ def test_live_unknown_wire_assembly_is_local_only():
GatewayClient.from_settings(
dataclasses.replace(settings, sources=(source,)), registry=register_provider(mystery)
)
class TestCallDeadlineConfig:
"""`{SCOPE}__CALL_DEADLINE_S` 与三个 client 入口参数的值域四条路(issue #22)。"""
def test_key_unset_means_disabled(self):
assert GatewaySettings.from_env("LLM", env=_env()).call_deadline_s is None
def test_env_key_parsed(self):
s = GatewaySettings.from_env("LLM", env=_env(**{"LLM__CALL_DEADLINE_S": "30"}))
assert s.call_deadline_s == 30.0
@pytest.mark.parametrize("bad", ["0", "-1", "nan", "inf", "abc"])
def test_env_illegal_value_reports_the_actual_key_name(self, bad):
"""origin 必须是实际命中的 env 键名,多 scope 部署里才定位得到是哪个键。"""
with pytest.raises(ValueError, match="LLM__CALL_DEADLINE_S"):
GatewaySettings.from_env("LLM", env=_env(**{"LLM__CALL_DEADLINE_S": bad}))
def test_direct_construction_is_guarded(self):
base = GatewaySettings.from_env("LLM", env=_env())
with pytest.raises(ValueError, match="GatewaySettings.call_deadline_s"):
dataclasses.replace(base, call_deadline_s=0)
def test_plain_constructor_call_is_guarded_too(self):
"""`dataclasses.replace` 与直接构造是两条路: 守卫在 `__post_init__` 才两条都盖住。
只在 `from_env` 里校验的话,直接 `GatewaySettings(...)` 装配的下游(测试/高级
注入路径,CLAUDE.md §4.5 的第二条装配路)会把非法期限一路带到第一次调用才炸。
"""
base = GatewaySettings.from_env("LLM", env=_env())
fields = {f.name: getattr(base, f.name) for f in dataclasses.fields(base)}
with pytest.raises(ValueError, match="GatewaySettings.call_deadline_s"):
GatewaySettings(**{**fields, "call_deadline_s": float("inf")})
# 合法值走同一条路不受影响(守卫对合法值是幂等空操作)
assert GatewaySettings(**{**fields, "call_deadline_s": 7}).call_deadline_s == 7.0
def test_replace_with_legal_value_is_idempotent(self):
base = GatewaySettings.from_env("LLM", env=_env())
assert dataclasses.replace(base, call_deadline_s=5).call_deadline_s == 5.0
def test_deadline_shorter_than_timeout_is_legal(self):
"""期限短于单次 timeout_s 是调用方的合法选择,不做跨字段耦合校验。"""
s = GatewaySettings.from_env("LLM", env=_env(**{"LLM__CALL_DEADLINE_S": "1"}))
assert s.call_deadline_s == 1.0 and s.sources[0].timeout_s == 120.0
def test_from_settings_propagates_to_client(self):
s = GatewaySettings.from_env("LLM", env=_env(**{"LLM__CALL_DEADLINE_S": "12"}))
assert GatewayClient.from_settings(s)._call_deadline_s == 12.0
def test_client_init_validates_at_entry(self):
"""三个 client 的 `__init__` 直传非法值也当场报错(不经 settings 那道守卫)。"""
from tests.unit.test_client import _client
with pytest.raises(ValueError, match=r"GatewayClient\(call_deadline_s"):
_client(call_deadline_s=0)