-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtest_calibration_retry.py
More file actions
255 lines (198 loc) · 8.87 KB
/
test_calibration_retry.py
File metadata and controls
255 lines (198 loc) · 8.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
"""Calibration retry strategy tests
Tests for the calibration retry optimization:
- Error classification (timeout, truncation, format errors)
- Self-Correction smart behavior (only for format errors)
- LLMClient error mapping (llm-compat errors -> project errors)
- Per-chunk time budget
- Default timeout value
"""
import json
import time
from dataclasses import dataclass
from unittest.mock import MagicMock, patch
import pytest
from video_transcript_api.llm.core.errors import (
classify_error,
map_llm_compat_error,
FatalError,
RetryableError,
TimeoutError as LLMTimeoutError,
TruncationError,
)
# ============================================================
# Phase 1: Error classification
# ============================================================
class TestErrorClassification:
"""Test enhanced error classification for timeout and truncation."""
def test_classify_read_timeout(self):
error = Exception(
"HTTPConnectionPool(host='100.107.95.24', port=3001): "
"Read timed out. (read timeout=900)"
)
assert classify_error(error) == LLMTimeoutError
def test_classify_connect_timeout(self):
error = Exception("Connection timed out")
assert classify_error(error) == LLMTimeoutError
def test_classify_generic_timeout(self):
error = Exception("Request timeout after 120s")
assert classify_error(error) == LLMTimeoutError
def test_classify_unterminated_string_as_truncation(self):
error = Exception(
"Structured output failed: json_object call failed: "
"JSON parse failed: Unterminated string starting at: "
"line 206 column 21 (char 9793)"
)
assert classify_error(error) == TruncationError
def test_classify_unexpected_end_as_truncation(self):
error = Exception("JSON parse failed: Unexpected end of JSON input")
assert classify_error(error) == TruncationError
def test_subclass_backward_compatible(self):
assert issubclass(LLMTimeoutError, RetryableError)
assert issubclass(TruncationError, RetryableError)
def test_fatal_errors_unchanged(self):
assert classify_error(Exception("401 Unauthorized")) == FatalError
assert classify_error(Exception("403 Forbidden")) == FatalError
assert classify_error(Exception("404 Not Found")) == FatalError
def test_generic_retryable_unchanged(self):
assert classify_error(Exception("Internal server error 500")) == RetryableError
def test_timeout_takes_priority_over_retryable(self):
error = Exception("Read timed out")
result = classify_error(error)
assert result == LLMTimeoutError
assert result != RetryableError
# ============================================================
# Phase 2: Self-Correction smart behavior (via llm-compat)
# ============================================================
@dataclass
class _FakeChatResult:
"""Minimal ChatResult stand-in for tests."""
content: str = ""
fallback_from: str = None
model: str = "test"
def __str__(self):
return self.content
class TestSelfCorrectionSmartBehavior:
"""Test that _call_with_json_object_mode only retries on format errors."""
@patch("video_transcript_api.llm.llm.get_sync_client")
def test_truncation_raises_immediately(self, mock_get_client):
"""Truncated JSON output should raise immediately, no Self-Correction."""
from video_transcript_api.llm.llm import (
_call_with_json_object_mode,
LLMCallError,
)
truncated_json = '{"calibrated_dialogs": [{"start_time": "00:00:01", "speaker": "A", "text": "hello'
mock_client = MagicMock()
mock_client.chat.return_value = _FakeChatResult(content=truncated_json)
mock_get_client.return_value = mock_client
config = {"llm": {"json_output": {"max_retries": 2}}}
with pytest.raises(LLMCallError, match="[Tt]runcated"):
_call_with_json_object_mode(
model="deepseek-v4-flash",
prompt="test",
schema={
"type": "object",
"properties": {"calibrated_dialogs": {"type": "array"}},
"required": ["calibrated_dialogs"],
},
config=config,
system_prompt="test",
reasoning_effort=None,
task_type="calibrate_chunk",
)
assert mock_client.chat.call_count == 1
@patch("video_transcript_api.llm.llm.get_sync_client")
def test_json_format_error_allows_self_correction(self, mock_get_client):
"""JSON format errors (non-truncation) should allow Self-Correction."""
from video_transcript_api.llm.llm import _call_with_json_object_mode
mock_client = MagicMock()
mock_client.chat.side_effect = [
_FakeChatResult(content='{"wrong_field": true}'),
_FakeChatResult(content='{"calibrated_dialogs": []}'),
]
mock_get_client.return_value = mock_client
config = {"llm": {"json_output": {"max_retries": 2}}}
result = _call_with_json_object_mode(
model="deepseek-v4-flash",
prompt="test",
schema={
"type": "object",
"properties": {"calibrated_dialogs": {"type": "array"}},
"required": ["calibrated_dialogs"],
},
config=config,
system_prompt="test",
reasoning_effort=None,
task_type="calibrate_chunk",
)
assert result.success is True
assert mock_client.chat.call_count == 2
@patch("video_transcript_api.llm.llm.get_sync_client")
def test_config_max_retries_respected(self, mock_get_client):
"""json_output.max_retries from config controls Self-Correction attempts."""
from video_transcript_api.llm.llm import _call_with_json_object_mode
mock_client = MagicMock()
mock_client.chat.return_value = _FakeChatResult(content='{"wrong": true}')
mock_get_client.return_value = mock_client
config = {"llm": {"json_output": {"max_retries": 1}}}
result = _call_with_json_object_mode(
model="deepseek-v4-flash",
prompt="test",
schema={
"type": "object",
"properties": {"data": {"type": "string"}},
"required": ["data"],
},
config=config,
system_prompt="test",
reasoning_effort=None,
task_type="calibrate_chunk",
)
assert result.success is False
assert mock_client.chat.call_count == 2 # 1 + 1 retry from config
# ============================================================
# Phase 4: LLMClient error mapping (llm-compat -> project)
# ============================================================
class TestLLMClientErrorMapping:
"""Test that map_llm_compat_error maps llm-compat errors correctly."""
def test_llm_compat_timeout_mapped(self):
from llm_compat import TimeoutError as LCTimeout
err = LCTimeout("timed out")
mapped = map_llm_compat_error(err)
assert isinstance(mapped, LLMTimeoutError)
def test_llm_compat_fatal_mapped(self):
from llm_compat import FatalError as LCFatal
err = LCFatal("401 Unauthorized")
mapped = map_llm_compat_error(err)
assert isinstance(mapped, FatalError)
def test_llm_compat_json_parse_mapped(self):
from llm_compat import JSONParseError
err = JSONParseError("bad json", raw_content="{", model="test", request_id="r1")
mapped = map_llm_compat_error(err)
assert isinstance(mapped, TruncationError)
def test_generic_error_mapped_to_retryable(self):
err = RuntimeError("something broke")
mapped = map_llm_compat_error(err)
assert isinstance(mapped, RetryableError)
# ============================================================
# Phase 5: Per-chunk time budget
# ============================================================
class TestChunkTimeBudget:
"""Test per-chunk time budget enforcement."""
def test_chunk_time_budget_triggers_fallback(self):
from video_transcript_api.llm.core.config import LLMConfig
config = LLMConfig(
api_key="test",
base_url="http://test",
calibrate_model="test-model",
summary_model="test-model",
)
assert hasattr(config, "chunk_time_budget")
assert config.chunk_time_budget == 300
# ============================================================
# Phase 6: Default timeout value
# ============================================================
class TestDefaultTimeout:
"""Test the default LLM timeout value."""
def test_default_timeout_is_180(self):
from video_transcript_api.llm.llm import DEFAULT_LLM_TIMEOUT
assert DEFAULT_LLM_TIMEOUT == 180