test_retrieve.py 6.77 KB
"""检索侧:上下文预算装配、束搜索排序、抽取输出解析。"""
from __future__ import annotations
import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from app.extract.prompts import parse_records                      # noqa: E402
from app.retrieve import context as ctx                            # noqa: E402
from app.retrieve.engine import _Cfg, _beam_expand, _collect_citations  # noqa: E402
from app.store.graph_store import GraphStore                       # noqa: E402


class TestContextBudget:
    def test_respects_budget(self):
        entities = [{"label": f"实体{i}", "type": "指标", "description": "描述" * 40}
                    for i in range(100)]
        relations = [{"source": f"A{i}", "target": f"B{i}", "relation": "关联",
                      "description": "说明" * 30, "occurrence": 1} for i in range(100)]
        chunks = [{"id": f"d1:c{i}", "heading": "章节", "text": "正文" * 300} for i in range(30)]
        b = ctx.build_context(entities, relations, chunks, [], budget=2000)
        assert b.used_tokens <= 2000 * 1.1
        assert b.dropped["entities"] > 0

    def test_keeps_high_ranked_first(self):
        """预算不够时,先进来的(分数高的)必须留住。"""
        entities = [{"label": "最相关", "type": "指标", "description": "短"}] + [
            {"label": f"次要{i}", "type": "指标", "description": "很长的描述" * 50} for i in range(50)]
        b = ctx.build_context(entities, [], [], [], budget=300)
        assert b.entities[0]["label"] == "最相关"

    def test_chunk_ids_are_citable(self):
        chunks = [{"id": "d2:c17", "heading": "赔付规则", "text": "门店未达标按差额赔付。"}]
        b = ctx.build_context([], [], chunks, [], budget=4000)
        assert "[d2:c17]" in b.text

    def test_empty_inputs(self):
        b = ctx.build_context([], [], [], [], budget=1000)
        assert b.text == "" and b.used_tokens == 0

    def test_ratio_parsing(self):
        assert ctx.parse_ratio("1,1,1,1") == (0.25, 0.25, 0.25, 0.25)
        assert ctx.parse_ratio("garbage") == ctx.DEFAULT_RATIO
        assert sum(ctx.parse_ratio("2,3,4,1")) == pytest.approx(1.0)


class TestBeamExpand:
    """v1 用无排序 BFS,`门店`(度 110)一跳就 110 条边,然后盲截前 80 条。"""

    @pytest.fixture()
    def hub_graph(self, tmp_path: Path) -> GraphStore:
        g = GraphStore(tmp_path / "g.json")
        for i in range(110):
            g.add_relation("门店", f"邻居{i}", "关联", f"说明{i}", doc_id=1)
        # 让其中一条边被多处佐证,它应当排在前面
        for _ in range(9):
            g.add_relation("门店", "邻居7", "关联", "重要关系", doc_id=1)
        return g

    def test_beam_width_caps_expansion(self, hub_graph: GraphStore):
        cfg = _Cfg({"BEAM_WIDTH": "20", "MAX_NODE_DEGREE": "60"})
        chosen, newly, pruned = _beam_expand(
            hub_graph, ["门店"], {"门店": 1.0}, {"门店"}, {}, cfg, 0)
        assert len(chosen) == 20
        assert pruned == 40          # 度数上限先砍到 60,再按分数留 20
        assert len(newly) == 20

    def test_results_are_sorted_by_score(self, hub_graph: GraphStore):
        cfg = _Cfg({"BEAM_WIDTH": "30"})
        chosen, _, _ = _beam_expand(hub_graph, ["门店"], {"门店": 1.0}, {"门店"}, {}, cfg, 0)
        scores = [e["score"] for e in chosen]
        assert scores == sorted(scores, reverse=True)

    def test_high_occurrence_edge_ranks_first(self, hub_graph: GraphStore):
        cfg = _Cfg({"BEAM_WIDTH": "5"})
        chosen, _, _ = _beam_expand(hub_graph, ["门店"], {"门店": 1.0}, {"门店"}, {}, cfg, 0)
        assert chosen[0]["to"] == "邻居7"

    def test_relation_relevance_dominates(self, hub_graph: GraphStore):
        """关系向量相关度高的边,即使佐证少也要能排上来。"""
        cfg = _Cfg({"BEAM_WIDTH": "3"})
        rel_scores = {"门店__关联__邻居42": 1.0}
        chosen, _, _ = _beam_expand(hub_graph, ["门店"], {"门店": 1.0}, {"门店"},
                                    rel_scores, cfg, 0)
        assert any(e["to"] == "邻居42" for e in chosen)

    def test_hop_decay(self, hub_graph: GraphStore):
        cfg = _Cfg({"BEAM_WIDTH": "5"})
        a, _, _ = _beam_expand(hub_graph, ["门店"], {"门店": 1.0}, {"门店"}, {}, cfg, 0)
        b, _, _ = _beam_expand(hub_graph, ["门店"], {"门店": 1.0}, {"门店"}, {}, cfg, 2)
        assert b[0]["score"] < a[0]["score"]


class TestRecordParsing:
    def test_parses_tuple_format(self):
        raw = ('("entity"<|>生态系数<|>指标<|>衡量门店生态经营水平的综合评分<|>0.95)##\n'
               '("relation"<|>生态系数<|>渗透率<|>计算依赖<|>生态系数由多项渗透率加权得出<|>0.9)##\n'
               '<|完成|>')
        ents, rels = parse_records(raw)
        assert len(ents) == 1 and ents[0]["name"] == "生态系数"
        assert ents[0]["type"] == "指标" and ents[0]["confidence"] == 0.95
        assert len(rels) == 1 and rels[0]["relation"] == "计算依赖"

    def test_bad_record_does_not_kill_the_batch(self):
        """v1 用整段 JSON,一处写坏整块内容全丢。"""
        raw = ('("entity"<|>好的实体<|>指标<|>描述<|>0.9)##\n'
               '这是模型吐出来的一句废话\n'
               '("entity"<|>另一个<|>周期<|>描述<|>0.8)##')
        ents, _ = parse_records(raw)
        assert [e["name"] for e in ents] == ["好的实体", "另一个"]

    def test_missing_optional_fields(self):
        ents, rels = parse_records('("entity"<|>只有名字和类型<|>指标)##\n'
                                   '("relation"<|>A<|>B<|>关联)##')
        assert ents[0]["description"] == "" and ents[0]["confidence"] == 0.8
        assert rels[0]["target"] == "B"

    def test_empty_input(self):
        assert parse_records("") == ([], [])


class TestCitations:
    def test_extracts_marked_citations(self):
        chunks = [{"id": "d2:c17", "heading": "赔付", "doc_id": 2, "text": "正文"},
                  {"id": "d2:c18", "heading": "口径", "doc_id": 2, "text": "正文2"}]
        cites = _collect_citations("门店未达标按差额赔付 [^d2:c17]。", chunks)
        assert len(cites) == 1 and cites[0]["chunk_id"] == "d2:c17"

    def test_falls_back_when_model_forgets_to_cite(self):
        chunks = [{"id": f"d1:c{i}", "heading": "H", "doc_id": 1, "text": "t"} for i in range(8)]
        cites = _collect_citations("一段没有任何标注的回答。", chunks)
        assert 0 < len(cites) <= 6

    def test_ignores_unknown_ids(self):
        chunks = [{"id": "d1:c1", "heading": "H", "doc_id": 1, "text": "t"}]
        cites = _collect_citations("引用了不存在的 [^d9:c99]。", chunks)
        assert all(c["chunk_id"] == "d1:c1" for c in cites)