test_vector_store.py 7.08 KB
"""索引:增量 upsert(v1 的致命 bug)与原子落盘。"""
from __future__ import annotations
import sys
from pathlib import Path

import numpy as np
import pytest

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

from app.store import vector_store as vs   # noqa: E402


@pytest.fixture(autouse=True)
def stub_embed(monkeypatch):
    """不打网络:用可复现的哈希伪向量替代真实 embedding。"""
    def fake(texts, *a, **kw):
        if not texts:
            return np.zeros((0, 8), dtype=np.float32)
        arr = np.zeros((len(texts), 8), dtype=np.float32)
        for i, t in enumerate(texts):
            for j, ch in enumerate(t[:8]):
                arr[i][j] = (ord(ch) % 97) / 97.0
            if not arr[i].any():
                arr[i][0] = 1.0
        norms = np.linalg.norm(arr, axis=1, keepdims=True)
        norms[norms == 0] = 1.0
        return arr / norms
    monkeypatch.setattr(vs.llm, "embed", fake)


def _chunks(doc_id: int, n: int) -> list[dict]:
    return [{"id": f"d{doc_id}:c{i}", "doc_id": doc_id, "order": i,
             "heading": f"文档{doc_id}章节{i}", "text": f"文档{doc_id}的第{i}段正文内容", "tokens": 10}
            for i in range(n)]


class TestIncrementalUpsert:
    def test_second_document_does_not_wipe_the_first(self, tmp_path: Path):
        """v1 的 build_chunks 是整体覆盖 —— 实测线上索引里只剩最后一篇文档的 79 个片段,
        先抽的文档实体还在图里,证据却永远检索不到。"""
        idx = vs.HybridIndex(tmp_path)
        idx.upsert_chunks(1, _chunks(1, 5))
        idx.upsert_chunks(2, _chunks(2, 7))

        ids = {c["id"] for c in idx.chunks.records}
        assert len(ids) == 12
        assert "d1:c0" in ids and "d2:c0" in ids

    def test_reextract_replaces_only_that_document(self, tmp_path: Path):
        idx = vs.HybridIndex(tmp_path)
        idx.upsert_chunks(1, _chunks(1, 5))
        idx.upsert_chunks(2, _chunks(2, 7))
        idx.upsert_chunks(1, _chunks(1, 2))      # 文档 1 重抽,片段变少

        by_doc = {}
        for c in idx.chunks.records:
            by_doc[c["doc_id"]] = by_doc.get(c["doc_id"], 0) + 1
        assert by_doc == {1: 2, 2: 7}

    def test_delete_doc_removes_only_its_chunks(self, tmp_path: Path):
        idx = vs.HybridIndex(tmp_path)
        idx.upsert_chunks(1, _chunks(1, 5))
        idx.upsert_chunks(2, _chunks(2, 7))
        removed = idx.delete_doc(1)
        assert removed == 5
        assert all(c["doc_id"] == 2 for c in idx.chunks.records)

    def test_search_can_scope_to_documents(self, tmp_path: Path):
        idx = vs.HybridIndex(tmp_path)
        idx.upsert_chunks(1, _chunks(1, 5))
        idx.upsert_chunks(2, _chunks(2, 5))
        hits = idx.search_chunks("正文内容", k=5, doc_ids=[2])
        assert hits and all(h["doc_id"] == 2 for h in hits)


class TestManualIndexUpsert:
    def test_entity_upsert_appends_and_keeps_existing(self, tmp_path: Path):
        idx = vs.HybridIndex(tmp_path)
        idx.rebuild_entities([{"id": "门店", "label": "门店", "type": "门店",
                               "description": "线下网点", "aliases": [], "doc_ids": [1],
                               "community": None, "degree": 2}])
        idx.upsert_entity({"id": "人工点", "label": "人工点", "type": "指标",
                           "description": "人工补录", "aliases": [], "doc_ids": [],
                           "community": None, "degree": 0})
        assert len(idx.entities.records) == 2
        hits = idx.link_entity("人工点", k=5)
        assert hits and hits[0]["id"] == "人工点"
        assert any(h["id"] == "门店" for h in idx.link_entity("门店", k=5))

    def test_entity_upsert_replaces_single_record(self, tmp_path: Path):
        idx = vs.HybridIndex(tmp_path)
        idx.upsert_entity({"id": "人工点", "label": "人工点", "type": "其他",
                           "description": "旧描述", "aliases": [], "doc_ids": [],
                           "community": None, "degree": 0})
        idx.upsert_entity({"id": "人工点", "label": "人工点", "type": "指标",
                           "description": "新描述", "aliases": ["别名"], "doc_ids": [],
                           "community": None, "degree": 1})
        assert len(idx.entities.records) == 1
        assert idx.entities.records[0]["description"] == "新描述"
        assert idx.entities.records[0]["aliases"] == ["别名"]

    def test_relation_upsert_is_searchable(self, tmp_path: Path):
        idx = vs.HybridIndex(tmp_path)
        idx.rebuild_relations([{"id": "A__关联__B", "source": "A", "target": "B",
                                "relation": "关联", "description": "抽取关系", "occurrence": 1,
                                "doc_ids": [1], "sources": []}])
        idx.upsert_relation({"id": "人工点1__关联__人工点2", "source": "人工点1",
                             "target": "人工点2", "relation": "关联", "description": "人工关系",
                             "occurrence": 0, "doc_ids": [], "sources": []})
        assert len(idx.relations.records) == 2
        hits = idx.search_relations("人工点1 关联 人工点2", k=5)
        assert hits and hits[0]["id"] == "人工点1__关联__人工点2"


class TestPersistence:
    def test_embeddings_survive_reload(self, tmp_path: Path):
        """曾经踩过的坑:np.save 收到路径会自动补 .npy,导致原子替换找不到临时文件,
        整个索引落盘在最后一步失败。"""
        idx = vs.HybridIndex(tmp_path)
        idx.upsert_chunks(1, _chunks(1, 4))
        idx.rebuild_entities([{"id": "门店", "label": "门店", "type": "门店",
                               "description": "线下网点", "aliases": []}])
        idx.rebuild_relations([{"id": "a__关联__b", "source": "a", "target": "b",
                                "relation": "关联", "description": "", "occurrence": 1}])

        assert (tmp_path / "chunks_emb.npy").exists()
        assert not list(tmp_path.glob("*.tmp*")), "不应残留临时文件"

        again = vs.HybridIndex(tmp_path)
        assert len(again.chunks.records) == 4
        assert again.chunks.emb is not None
        assert again.chunks.emb.shape[0] == 4
        assert again.stats()["entities"]["count"] == 1
        assert again.stats()["relations"]["count"] == 1

    def test_mismatched_embeddings_are_discarded_not_crashed(self, tmp_path: Path):
        idx = vs.HybridIndex(tmp_path)
        idx.upsert_chunks(1, _chunks(1, 4))
        # 人为制造记录数与向量数不一致
        with open(tmp_path / "chunks_emb.npy", "wb") as fh:
            np.save(fh, np.zeros((2, 8), dtype=np.float32))
        again = vs.HybridIndex(tmp_path)
        assert len(again.chunks.records) == 4
        assert again.chunks.emb is None          # 丢掉向量而不是崩溃
        assert again.search_chunks("正文", k=2)   # BM25 仍可用

    def test_clear(self, tmp_path: Path):
        idx = vs.HybridIndex(tmp_path)
        idx.upsert_chunks(1, _chunks(1, 3))
        idx.clear()
        assert idx.chunks.records == []
        assert not (tmp_path / "chunks_emb.npy").exists()