|
| 1 | +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Failure handling, degradation, and availability tests. |
| 16 | +
|
| 17 | +The decision model is optional and sits in hot paths, so every failure has to |
| 18 | +reach callers as a ``DecisionModelError`` they can fall back from, and a |
| 19 | +down endpoint must stop costing the retry and timeout budget. |
| 20 | +""" |
| 21 | + |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +import logging |
| 25 | +import time |
| 26 | + |
| 27 | +import httpx |
| 28 | +import pytest |
| 29 | + |
| 30 | +from veadk.extensions.decisions import ( |
| 31 | + DecisionExtension, |
| 32 | + DecisionModelConfig, |
| 33 | + DecisionModelRequestError, |
| 34 | + DecisionModelResponseError, |
| 35 | + DecisionModelUnavailableError, |
| 36 | + SystemOneClient, |
| 37 | + noul_question, |
| 38 | +) |
| 39 | +from veadk.extensions.decisions.types import parse_answers |
| 40 | + |
| 41 | +from .fake_system_one import FakeSystemOneServer, fake_system_one |
| 42 | + |
| 43 | +QUESTION = {"q": noul_question("Is this a greeting?")} |
| 44 | + |
| 45 | + |
| 46 | +def _config( |
| 47 | + server_url: str, |
| 48 | + *, |
| 49 | + timeout: float = 5.0, |
| 50 | + max_retries: int = 0, |
| 51 | + failure_threshold: int = 3, |
| 52 | + cooldown_seconds: float = 30.0, |
| 53 | +) -> DecisionModelConfig: |
| 54 | + return DecisionModelConfig( |
| 55 | + enabled=True, |
| 56 | + api_base=server_url, |
| 57 | + api_key="test-key", |
| 58 | + name="jev-latest", |
| 59 | + timeout=timeout, |
| 60 | + max_retries=max_retries, |
| 61 | + failure_threshold=failure_threshold, |
| 62 | + cooldown_seconds=cooldown_seconds, |
| 63 | + ) |
| 64 | + |
| 65 | + |
| 66 | +def _extension(server_url: str, **settings: float | int) -> DecisionExtension: |
| 67 | + return DecisionExtension(_config(server_url, **settings)) |
| 68 | + |
| 69 | + |
| 70 | +def _schedule_outage(server: FakeSystemOneServer, count: int = 1) -> None: |
| 71 | + """Make the next ``count`` requests fail like a down endpoint.""" |
| 72 | + server.script.extend([(503, {}, {"detail": "unavailable"})] * count) |
| 73 | + |
| 74 | + |
| 75 | +def _judge(extension: DecisionExtension) -> float: |
| 76 | + """Ask one noul question and return the probability.""" |
| 77 | + return extension.noul("state", "Is this a greeting?").noul |
| 78 | + |
| 79 | + |
| 80 | +# -- every failure is a decision-model error ------------------------------- |
| 81 | + |
| 82 | + |
| 83 | +def test_a_malformed_answer_is_a_response_error() -> None: |
| 84 | + """A payload that fails pydantic validation must not escape as itself.""" |
| 85 | + with pytest.raises(DecisionModelResponseError, match="not a valid choice"): |
| 86 | + parse_answers({"q": {"type": "choice"}}) |
| 87 | + with pytest.raises(DecisionModelResponseError, match="not a valid noul"): |
| 88 | + parse_answers({"q": {"type": "noul", "noul": "certainly"}}) |
| 89 | + |
| 90 | + |
| 91 | +def test_a_broken_answer_payload_reaches_callers_as_a_decision_error() -> None: |
| 92 | + script = [(200, {}, {"model": "fake", "answers": {"q": {"type": "choice"}}})] |
| 93 | + with fake_system_one(script) as server: |
| 94 | + with pytest.raises(DecisionModelResponseError): |
| 95 | + _judge(_extension(server.base_url)) |
| 96 | + |
| 97 | + |
| 98 | +def test_a_send_failure_that_is_not_an_http_error_is_normalized( |
| 99 | + monkeypatch: pytest.MonkeyPatch, |
| 100 | +) -> None: |
| 101 | + """``httpx.InvalidURL`` is not an ``httpx.HTTPError``, so it needs our own.""" |
| 102 | + assert not issubclass(httpx.InvalidURL, httpx.HTTPError) |
| 103 | + |
| 104 | + def _raise_invalid_url(*_args: object, **_kwargs: object) -> None: |
| 105 | + raise httpx.InvalidURL("Invalid port: ':1'") |
| 106 | + |
| 107 | + monkeypatch.setattr(httpx.Client, "post", _raise_invalid_url) |
| 108 | + client = SystemOneClient(_config("https://api.example.com")) |
| 109 | + with pytest.raises(DecisionModelRequestError, match="could not be sent"): |
| 110 | + client.evaluate(state="state", questions=QUESTION) |
| 111 | + |
| 112 | + |
| 113 | +def test_a_transport_outage_is_a_request_error() -> None: |
| 114 | + with fake_system_one() as server: |
| 115 | + base_url = server.base_url |
| 116 | + with pytest.raises(DecisionModelRequestError): |
| 117 | + SystemOneClient(_config(base_url)).evaluate(state="state", questions=QUESTION) |
| 118 | + |
| 119 | + |
| 120 | +# -- the endpoint stops being called once it is known to be down ----------- |
| 121 | + |
| 122 | + |
| 123 | +def test_repeated_failures_open_the_circuit_and_skip_the_endpoint() -> None: |
| 124 | + with fake_system_one() as server: |
| 125 | + extension = _extension(server.base_url, failure_threshold=2) |
| 126 | + _schedule_outage(server, 2) |
| 127 | + for _ in range(2): |
| 128 | + with pytest.raises(DecisionModelRequestError): |
| 129 | + _judge(extension) |
| 130 | + assert len(server.calls) == 2 |
| 131 | + |
| 132 | + with pytest.raises(DecisionModelUnavailableError, match="marked down"): |
| 133 | + _judge(extension) |
| 134 | + assert len(server.calls) == 2 |
| 135 | + |
| 136 | + |
| 137 | +def test_a_successful_probe_resumes_judgements() -> None: |
| 138 | + with fake_system_one() as server: |
| 139 | + extension = _extension( |
| 140 | + server.base_url, failure_threshold=1, cooldown_seconds=0.05 |
| 141 | + ) |
| 142 | + _schedule_outage(server) |
| 143 | + with pytest.raises(DecisionModelRequestError): |
| 144 | + _judge(extension) |
| 145 | + with pytest.raises(DecisionModelUnavailableError): |
| 146 | + _judge(extension) |
| 147 | + |
| 148 | + time.sleep(0.06) |
| 149 | + assert _judge(extension) == pytest.approx(0.9) |
| 150 | + assert _judge(extension) == pytest.approx(0.9) |
| 151 | + |
| 152 | + |
| 153 | +def test_a_failed_probe_keeps_the_circuit_open() -> None: |
| 154 | + with fake_system_one() as server: |
| 155 | + extension = _extension( |
| 156 | + server.base_url, failure_threshold=1, cooldown_seconds=0.05 |
| 157 | + ) |
| 158 | + _schedule_outage(server) |
| 159 | + with pytest.raises(DecisionModelRequestError): |
| 160 | + _judge(extension) |
| 161 | + |
| 162 | + time.sleep(0.06) |
| 163 | + _schedule_outage(server) |
| 164 | + with pytest.raises(DecisionModelRequestError): |
| 165 | + _judge(extension) |
| 166 | + with pytest.raises(DecisionModelUnavailableError): |
| 167 | + _judge(extension) |
| 168 | + # 三次失败里只有两次真的打了上游:冷却期内的那次被拦下了 |
| 169 | + assert len(server.calls) == 2 |
| 170 | + |
| 171 | + |
| 172 | +def test_the_circuit_closes_after_isolated_failures() -> None: |
| 173 | + with fake_system_one() as server: |
| 174 | + extension = _extension(server.base_url, failure_threshold=2) |
| 175 | + _schedule_outage(server) |
| 176 | + with pytest.raises(DecisionModelRequestError): |
| 177 | + _judge(extension) |
| 178 | + assert _judge(extension) == pytest.approx(0.9) |
| 179 | + |
| 180 | + _schedule_outage(server) |
| 181 | + with pytest.raises(DecisionModelRequestError): |
| 182 | + _judge(extension) |
| 183 | + assert _judge(extension) == pytest.approx(0.9) |
| 184 | + |
| 185 | + |
| 186 | +def test_the_circuit_can_be_disabled() -> None: |
| 187 | + with fake_system_one() as server: |
| 188 | + extension = _extension(server.base_url, failure_threshold=0) |
| 189 | + _schedule_outage(server, 3) |
| 190 | + for _ in range(3): |
| 191 | + with pytest.raises(DecisionModelRequestError): |
| 192 | + _judge(extension) |
| 193 | + assert len(server.calls) == 3 |
| 194 | + |
| 195 | + |
| 196 | +# -- the timeout is a budget for the whole judgement ----------------------- |
| 197 | + |
| 198 | + |
| 199 | +def test_one_judgement_stays_within_its_time_budget() -> None: |
| 200 | + """Retries and backoff cannot outlive the configured budget.""" |
| 201 | + script = [(503, {"retry-after": "5"}, {"detail": "unavailable"})] * 4 |
| 202 | + with fake_system_one(script) as server: |
| 203 | + client = SystemOneClient(_config(server.base_url, timeout=0.3, max_retries=3)) |
| 204 | + started = time.perf_counter() |
| 205 | + with pytest.raises(DecisionModelRequestError, match="time budget"): |
| 206 | + client.evaluate(state="state", questions=QUESTION) |
| 207 | + elapsed = time.perf_counter() - started |
| 208 | + assert elapsed < 0.6 |
| 209 | + assert len(server.calls) == 1 |
| 210 | + |
| 211 | + |
| 212 | +# -- what ends up in the log ---------------------------------------------- |
| 213 | + |
| 214 | + |
| 215 | +def test_retries_and_outages_are_logged(caplog: pytest.LogCaptureFixture) -> None: |
| 216 | + script = [(503, {"retry-after": "0"}, {"detail": "unavailable"})] * 2 |
| 217 | + with fake_system_one(script) as server: |
| 218 | + extension = _extension(server.base_url, max_retries=1, failure_threshold=1) |
| 219 | + with caplog.at_level(logging.WARNING): |
| 220 | + with pytest.raises(DecisionModelRequestError): |
| 221 | + _judge(extension) |
| 222 | + |
| 223 | + messages = [record.getMessage() for record in caplog.records] |
| 224 | + assert any("retrying" in message for message in messages) |
| 225 | + assert any("in a row" in message for message in messages) |
| 226 | + assert all("test-key" not in message for message in messages) |
| 227 | + |
| 228 | + |
| 229 | +def test_the_judged_state_is_never_logged(caplog: pytest.LogCaptureFixture) -> None: |
| 230 | + with fake_system_one() as server: |
| 231 | + extension = _extension(server.base_url) |
| 232 | + with caplog.at_level(logging.DEBUG): |
| 233 | + extension.noul("SECRET-USER-TEXT", "Is this a greeting?") |
| 234 | + |
| 235 | + assert caplog.records, "a successful judgement should be observable" |
| 236 | + assert all( |
| 237 | + "SECRET-USER-TEXT" not in record.getMessage() for record in caplog.records |
| 238 | + ) |
0 commit comments