Skip to content

Commit f0796a5

Browse files
committed
refactor(yaml): cache PyYAML parses instead of routing through libyaml
The libyaml path needed guards and adversarial testing to match PyYAML on every input, which is a lot of code for a parser speedup. yamlio now parses with PyYAML itself and caches each text up to 128 KiB per loader, handing out deep copies. full-sweep takes 2.9 s instead of 1.9 s with libyaml (18 s uncached), plan 1.5 s instead of 0.45 s, and outputs are byte-identical. 中文:libyaml 路径需要大量守卫和对抗测试才能在所有输入上与 PyYAML 一致,为了解析加速 付出的代码量过大。yamlio 现在直接使用 PyYAML 解析,并按加载器缓存每个不超过 128 KiB 的文本,返回深拷贝。full-sweep 耗时 2.9 秒(libyaml 为 1.9 秒,无缓存为 18 秒),plan 耗时 1.5 秒(libyaml 为 0.45 秒),输出逐字节一致。
1 parent cad5f17 commit f0796a5

2 files changed

Lines changed: 27 additions & 374 deletions

File tree

‎inferencex-e2e/infx/tests/test_yamlio.py‎

Lines changed: 12 additions & 162 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,9 @@
1-
import io
2-
import sys
3-
41
import pytest
52
import yaml
63

74
from infx import yamlio
85

96

10-
@pytest.mark.parametrize(
11-
("text", "message"),
12-
[
13-
("a:\n b\tc: 1\n", "that cannot start any token"),
14-
("a: {b: c?d}\n", "expected ',' or '}', but got '?'"),
15-
("a: 1\n\ufeff\nb: 2\n", "could not find expected ':'"),
16-
("a: |#\n x\n", "expected chomping or indentation indicators"),
17-
("[!!str, a]\n", "could not determine a constructor for the tag"),
18-
("[?]]\n", "expected '<document start>', but found ']'"),
19-
],
20-
ids=[
21-
"tab-in-plain-scalar",
22-
"question-mark-in-flow-scalar",
23-
"inner-byte-order-mark",
24-
"comment-on-block-scalar-header",
25-
"tag-before-flow-comma",
26-
"token-after-empty-flow-key",
27-
],
28-
)
29-
def test_documents_only_libyaml_accepts_raise_pyyamls_error(text, message):
30-
with pytest.raises(yaml.YAMLError, match=message):
31-
yamlio.safe_load(text)
32-
33-
34-
def test_a_tagged_empty_flow_key_is_null_as_in_pyyaml():
35-
assert yamlio.safe_load("{a: 1, ! }\n") == {"a": 1, None: None}
36-
37-
38-
@pytest.mark.parametrize(
39-
"text",
40-
["[" * 2000 + "]" * 2000, "#\r" + "- " * 600 + "x\r"],
41-
ids=["flow", "block-after-carriage-returns"],
42-
)
43-
def test_nesting_past_pyyamls_recursion_limit_raises_its_recursion_error(text):
44-
with pytest.raises(RecursionError):
45-
yamlio.safe_load(text)
46-
47-
487
def test_stream_errors_name_the_file_with_pyyamls_wording(tmp_path):
498
path = tmp_path / "bad.yaml"
509
path.write_text("a: [1\n")
@@ -58,133 +17,23 @@ def test_stream_errors_name_the_file_with_pyyamls_wording(tmp_path):
5817
)
5918

6019

61-
def test_a_file_that_fails_to_decode_late_raises_pyyamls_earlier_syntax_error(tmp_path):
62-
path = tmp_path / "bad.yaml"
63-
path.write_bytes(b"a: b: c\n" + b"# padding\n" * 2000 + b"x: \xff\n")
64-
65-
with path.open(encoding="utf-8") as stream, pytest.raises(yaml.YAMLError) as error:
66-
yamlio.safe_load(stream)
67-
68-
assert "mapping values are not allowed here" in str(error.value)
69-
70-
71-
def test_a_file_iterated_before_loading_loads_its_remaining_lines(tmp_path):
72-
path = tmp_path / "x.yaml"
73-
path.write_text("skip: 1\na: 1\n")
74-
75-
with path.open() as stream:
76-
next(stream)
77-
assert yamlio.safe_load(stream) == {"a": 1}
78-
79-
80-
def test_a_closed_file_raises_reads_closed_file_error(tmp_path):
81-
path = tmp_path / "x.yaml"
82-
path.write_text("a: 1\n")
83-
with path.open() as stream:
84-
pass
85-
86-
with pytest.raises(ValueError, match=r"^I/O operation on closed file\.$"):
87-
yamlio.safe_load(stream)
88-
89-
90-
def test_text_streams_that_need_a_read_size_load():
91-
class Chunks(io.TextIOBase):
92-
def __init__(self) -> None:
93-
self.left = "a: 1\n"
94-
95-
def read(self, size: int) -> str:
96-
chunk, self.left = self.left[:size], self.left[size:]
97-
return chunk
98-
99-
assert yamlio.safe_load(Chunks()) == {"a": 1}
100-
101-
102-
def test_str_subclasses_load_like_str():
103-
class Text(str):
104-
__slots__ = ()
20+
def test_a_text_that_fails_to_parse_raises_on_every_load():
21+
for _ in range(2):
22+
with pytest.raises(yaml.YAMLError, match="expected ',' or ']'"):
23+
yamlio.safe_load("a: [1\n")
10524

106-
assert yamlio.safe_load(Text("a: 1\n")) == {"a": 1}
107-
108-
109-
def test_a_metaclass_table_property_is_ignored_as_pyyaml_ignores_it():
110-
class Meta(type):
111-
@property
112-
def yaml_constructors(cls):
113-
return {
114-
**yaml.SafeLoader.yaml_constructors,
115-
"tag:yaml.org,2002:int": lambda _, node: f"META:{node.value}",
116-
}
117-
118-
class Loader(yaml.SafeLoader, metaclass=Meta):
119-
pass
120-
121-
assert yamlio.load("n: 1\n", Loader) == {"n": 1}
122-
123-
124-
def test_a_replaced_constructor_that_refuses_comparison_applies():
125-
class Fussy:
126-
__hash__ = object.__hash__
127-
128-
def __init__(self, label):
129-
self.label = label
130-
131-
def __eq__(self, other):
132-
raise TypeError("ambiguous comparison")
133-
134-
def __call__(self, _, node):
135-
return f"{self.label}:{node.value}"
136-
137-
class Loader(yaml.SafeLoader):
138-
pass
139-
140-
Loader.add_constructor("tag:yaml.org,2002:int", Fussy("OLD"))
141-
first = yamlio.load("n: 1\n", Loader)
142-
Loader.add_constructor("tag:yaml.org,2002:int", Fussy("NEW"))
143-
144-
assert (first, yamlio.load("n: 1\n", Loader)) == ({"n": "OLD:1"}, {"n": "NEW:1"})
145-
146-
147-
def test_methods_patched_onto_a_loader_after_a_load_apply_to_the_same_text():
148-
class Loader(yaml.SafeLoader):
149-
pass
150-
151-
def construct_mapping(self, node, deep=False):
152-
return {**yaml.SafeLoader.construct_mapping(self, node, deep), "patched": True}
153-
154-
first = yamlio.load("a: 1\n", Loader)
155-
Loader.construct_mapping = construct_mapping
156-
157-
assert (first, yamlio.load("a: 1\n", Loader)) == ({"a": 1}, {"a": 1, "patched": True})
158-
159-
160-
def test_constructors_added_after_a_load_apply_to_the_same_text():
161-
class Loader(yaml.SafeLoader):
162-
pass
163-
164-
first = yamlio.load("n: 12\n", Loader)
165-
Loader.add_constructor("tag:yaml.org,2002:int", lambda _, node: f"INT {node.value}")
166-
167-
assert (first, yamlio.load("n: 12\n", Loader)) == ({"n": 12}, {"n": "INT 12"})
16825

26+
def test_custom_loader_constructors_apply():
27+
with pytest.raises(yaml.YAMLError, match="found duplicate key 'a'"):
28+
yamlio.load("x: 1\ny: {a: 1, a: 2}\n", yamlio.UniqueKeyLoader)
16929

170-
def test_the_int_digit_limit_applies_to_a_text_loaded_under_a_higher_limit():
171-
text = "n: " + "1" * 4400 + "\n"
172-
limit = sys.get_int_max_str_digits()
173-
sys.set_int_max_str_digits(5000)
174-
try:
175-
yamlio.safe_load(text)
176-
finally:
177-
sys.set_int_max_str_digits(4300)
178-
try:
179-
with pytest.raises(ValueError, match="Exceeds the limit"):
180-
yamlio.safe_load(text)
181-
finally:
182-
sys.set_int_max_str_digits(limit)
18330

31+
def test_one_text_loads_through_each_loader_separately():
32+
text = "a: 1\na: 2\n"
18433

185-
def test_custom_loader_constructors_apply():
34+
assert yamlio.safe_load(text) == {"a": 2}
18635
with pytest.raises(yaml.YAMLError, match="found duplicate key 'a'"):
187-
yamlio.load("x: 1\ny: {a: 1, a: 2}\n", yamlio.UniqueKeyLoader)
36+
yamlio.load(text, yamlio.UniqueKeyLoader)
18837

18938

19039
def test_safe_unique_key_loader_merges_and_rejects_repeated_own_keys():
@@ -236,6 +85,7 @@ def test_repeated_loads_keep_anchor_sharing():
23685
def test_a_deep_alias_chain_loads_as_pyyaml_builds_it():
23786
chain = "".join(f"k{i}: &a{i} [{f'*a{i - 1}' if i else 'x'}]\n" for i in range(1200))
23887
text = "first: null\n" + chain + "first: *a1199\n"
88+
yamlio.safe_load(text)
23989

24090
loaded = yamlio.safe_load(text)
24191

0 commit comments

Comments
 (0)