main
py 61 lines 2.01 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 """Tests for regex compilation timeout guard.
4
5 Verifies that adversarial regex patterns that would cause exponential
6 DFA state-space explosion are rejected with a timeout rather than
7 hanging indefinitely.
8
9 Addresses advisory GHSA-rwxx-mrjm-wc2m.
10 """
11
12 import time
13 from unittest.mock import patch
14
15 import pytest
16
17 from vllm.v1.structured_output.utils import compile_regex_with_timeout
18
19
20 class TestCompileRegexWithTimeout:
21 """Unit tests for the compile_regex_with_timeout utility."""
22
23 def test_normal_regex_compiles_successfully(self):
24 result = compile_regex_with_timeout(lambda pat: "compiled", r"[a-z]+")
25 assert result == "compiled"
26
27 def test_timeout_raises_value_error(self):
28 def slow_compile(pattern: str):
29 time.sleep(10)
30 return "never"
31
32 with (
33 patch("vllm.envs.VLLM_REGEX_COMPILATION_TIMEOUT_S", 1),
34 pytest.raises(ValueError, match="timed out"),
35 ):
36 compile_regex_with_timeout(slow_compile, r"(a+)+b")
37
38 def test_timeout_disabled_when_zero(self):
39 result = None
40 with patch("vllm.envs.VLLM_REGEX_COMPILATION_TIMEOUT_S", 0):
41 result = compile_regex_with_timeout(lambda pat: "no_timeout", r"(a+)+b")
42 assert result == "no_timeout"
43
44 def test_compilation_error_propagates(self):
45 def failing_compile(pattern: str):
46 raise RuntimeError("compilation failed")
47
48 with pytest.raises(RuntimeError, match="compilation failed"):
49 compile_regex_with_timeout(failing_compile, r"bad")
50
51 def test_pattern_included_in_error_message(self):
52 def slow_compile(pattern: str):
53 time.sleep(10)
54 return "never"
55
56 pattern = r"(a+)+b"
57 with (
58 patch("vllm.envs.VLLM_REGEX_COMPILATION_TIMEOUT_S", 1),
59 pytest.raises(ValueError, match=r"\(a\+\)\+b"),
60 ):
61 compile_regex_with_timeout(slow_compile, pattern)