From c49d0ff12f167cd04c01ac9ed45dbe8cc747adf3 Mon Sep 17 00:00:00 2001 From: iomgaa Date: Tue, 14 Jul 2026 05:43:28 -0400 Subject: [PATCH] fix(sampler): validate level param rejects invalid values Add ValueError guard at the top of sample_material_v2 for level not in {1, 2, 3}, preventing silent fallthrough to L1 sampling. Add unit test for the new validation. Co-Authored-By: Claude Opus 4.6 (1M context) --- app/question_gen/sampler_v2.py | 4 ++++ tests/unit/test_sampler_v2.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/app/question_gen/sampler_v2.py b/app/question_gen/sampler_v2.py index 5dc735d..23d5959 100644 --- a/app/question_gen/sampler_v2.py +++ b/app/question_gen/sampler_v2.py @@ -525,8 +525,12 @@ def sample_material_v2( MaterialContext 实例。 异常: + ValueError: level 不在 {1, 2, 3} 中。 RuntimeError: 耗尽 max_attempts 次尝试仍无法满足约束。 """ + if level not in (1, 2, 3): + msg = f"level 必须为 1、2 或 3,收到: {level}" + raise ValueError(msg) for attempt in range(max_attempts): # Phase 1: 按层级采样候选节点 diff --git a/tests/unit/test_sampler_v2.py b/tests/unit/test_sampler_v2.py index 2f1cea4..dacc751 100644 --- a/tests/unit/test_sampler_v2.py +++ b/tests/unit/test_sampler_v2.py @@ -291,6 +291,21 @@ class TestSampleMaterialV2: has_related = any(pattern in s for s in result.subtitle_sentences) assert has_related + def test_invalid_level_raises(self, real_tree: TreeIndex) -> None: + """无效的 level 参数应抛出 ValueError。""" + from app.question_gen.sampler_v2 import sample_material_v2 + + rng = random.Random(42) + with pytest.raises(ValueError, match="level 必须为"): + sample_material_v2( + tree=real_tree, + task_type="Object Recognition", + used_node_ids=set(), + rng=rng, + level=4, + constraint=RETRIEVAL_FAMILY.sampling, + ) + class TestValidateSamplingConstraints: """_validate_sampling_constraints 辅助函数测试。"""