test_ingest_planning.py 18.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
import sys
import inspect
import tempfile
import types
import unittest
from importlib.machinery import ModuleSpec
from datetime import date
from pathlib import Path

import frontmatter


sqlalchemy_stub = types.ModuleType("sqlalchemy")
sqlalchemy_stub.__spec__ = ModuleSpec("sqlalchemy", loader=None)
sqlalchemy_stub.select = lambda *_args, **_kwargs: None
sqlalchemy_stub.delete = lambda *_args, **_kwargs: None
sys.modules["sqlalchemy"] = sqlalchemy_stub

fastapi_stub = types.ModuleType("fastapi")
fastapi_stub.__spec__ = ModuleSpec("fastapi", loader=None)


class _Router:
    def post(self, *_args, **_kwargs):
        return lambda func: func

    def delete(self, *_args, **_kwargs):
        return lambda func: func


class _HTTPException(Exception):
    def __init__(self, status_code=500, detail=""):
        super().__init__(detail)
        self.status_code = status_code
        self.detail = detail


fastapi_stub.APIRouter = _Router
fastapi_stub.HTTPException = _HTTPException
fastapi_stub.Body = lambda default=None, **_kwargs: default
fastapi_stub.BackgroundTasks = object
sys.modules["fastapi"] = fastapi_stub

fastapi_concurrency_stub = types.ModuleType("fastapi.concurrency")
fastapi_concurrency_stub.run_in_threadpool = None
sys.modules["fastapi.concurrency"] = fastapi_concurrency_stub

models_stub = types.ModuleType("src.database.models")
models_stub.WikiFile = type("WikiFile", (), {"id": None})
models_stub.WikiFilePage = type("WikiFilePage", (), {"file_id": None})
models_stub.WikiOperationLog = type("WikiOperationLog", (), {})
sys.modules["src.database.models"] = models_stub

session_stub = types.ModuleType("src.database.session")
session_stub.AsyncSessionLocal = object
sys.modules["src.database.session"] = session_stub

config_stub = types.ModuleType("config")
config_stub.RAW_DIR = "ware/raw"
config_stub.WIKI_DIR = "ware/wiki"
config_stub.BASE_DIR = "."
config_stub.INGEST_MODEL_NAME = "test-model"
sys.modules["config"] = config_stub

tracker_stub = types.ModuleType("src.utils.llm_tracker")
tracker_stub.current_task_tokens = object()
tracker_stub.print_thinking = object()
tracker_stub.current_task_token_usage = lambda: {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}
tracker_stub.get_llm_formatter = lambda *_args, **_kwargs: None
tracker_stub.get_llm_model = lambda *_args, **_kwargs: None
tracker_stub.load_skill_prompt = lambda *_args, **_kwargs: ""
tracker_stub.new_token_counter = lambda: {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}
sys.modules["src.utils.llm_tracker"] = tracker_stub

parser_stub = types.ModuleType("src.tools.document_parser")
parser_stub.extract_text_from_file = lambda *_args, **_kwargs: ""
sys.modules["src.tools.document_parser"] = parser_stub

wiki_tools_stub = types.ModuleType("src.tools.wiki_tools")
wiki_tools_stub.append_wiki_file = lambda *_args, **_kwargs: None
wiki_tools_stub.rebuild_index = lambda *_args, **_kwargs: 0
wiki_tools_stub.normalize_br_tags = lambda text: text
wiki_tools_stub.execute_terminal_command = lambda *_args, **_kwargs: None
wiki_tools_stub.read_local_file = lambda *_args, **_kwargs: None
wiki_tools_stub.write_wiki_file = lambda *_args, **_kwargs: None
sys.modules["src.tools.wiki_tools"] = wiki_tools_stub

agent_stub = types.ModuleType("agentscope.agent")
agent_stub.ReActAgent = object
sys.modules["agentscope.agent"] = agent_stub
message_stub = types.ModuleType("agentscope.message")
message_stub.Msg = object
sys.modules["agentscope.message"] = message_stub
tool_stub = types.ModuleType("agentscope.tool")
tool_stub.Toolkit = object
sys.modules["agentscope.tool"] = tool_stub

from src.api.routes.ingest import (
    _ingest_status_action,
    _preflight_generated_pages,
    _prepare_ingest_page_overrides,
    _prepare_planner_result,
    build_writer_system_prompt,
)


class IngestPlanningTest(unittest.TestCase):
    def test_ingest_status_action_requires_egress_for_indexed_files(self):
        self.assertEqual(_ingest_status_action("Pending"), "start")
        self.assertEqual(_ingest_status_action("Failed"), "start")
        self.assertEqual(_ingest_status_action("Ingesting"), "already")
        self.assertEqual(_ingest_status_action("Uploading"), "busy")
        self.assertEqual(_ingest_status_action("Indexed"), "requires_egress")

    def test_planner_success_log_includes_dimension_values_and_types(self):
        import src.api.routes.ingest as ingest_route

        source = inspect.getsource(ingest_route._run_ingest_agent_impl)

        self.assertIn("planner_dimensions=", source)
        self.assertIn("actual_type", source)
        self.assertLess(
            source.index("planner_dimensions="),
            source.index("_prepare_planner_result(plan_data"),
        )

    def test_ingest_docs_use_list_only_dimensions(self):
        schema = Path("skills/llm-ingest/references/schema.md").read_text(encoding="utf-8")
        skill = Path("skills/llm-ingest/SKILL.md").read_text(encoding="utf-8")

        self.assertNotIn("string 或 list", schema)
        for scalar_example in (
            "series: 鸿蒙智行",
            "business_category: 权益类",
            "sub_business: 售前延保",
            "sub_business: 售后延保",
        ):
            with self.subTest(example=scalar_example):
                self.assertNotIn(scalar_example, schema)
                self.assertNotIn(scalar_example, skill)

    def test_writer_prompt_requires_quoted_yaml_block_lists(self):
        import src.api.routes.ingest as ingest_route

        prompt = build_writer_system_prompt(
            skill_prompt="",
            schema_contract_text="",
            page_info={},
            global_dims={},
            filename="test.pdf",
            schema_version="v1.0",
        )

        self.assertIn("禁止使用 field: [value]", prompt)
        self.assertIn('brand:\n  - "未知品牌[待确认]"', prompt)
        source = inspect.getsource(ingest_route._run_ingest_agent_impl)
        self.assertIn("_YAML_BLOCK_LIST_GUIDANCE", source)

    def test_schema_writer_examples_avoid_nonempty_inline_lists(self):
        schema = Path("skills/llm-ingest/references/schema.md").read_text(encoding="utf-8")

        for field in (
            "series",
            "brand",
            "business_category",
            "sub_business",
            "role",
            "related",
            "sources",
            "tags",
            "skill_tag",
        ):
            with self.subTest(field=field):
                self.assertNotRegex(schema, rf"(?m)^\s*{field}:\s*\[[^\]]")
        self.assertIn('brand:\n  - "未知品牌[待确认]"', schema)

    def _plan_data(self):
        return {
            "global_dims": {
                "series": ["鸿蒙智行"],
                "brand": ["问界"],
                "business_category": ["权益类"],
                "sub_business": ["售后延保"],
                "role": ["驻店销售"],
            },
            "pages": [
                {
                    "type": "sources",
                    "slug": "资料摘要",
                    "title": "资料摘要",
                    "related_links": ["测试产品"],
                    "source_content_range": "全文摘要",
                },
                {
                    "type": "products",
                    "slug": "测试产品",
                    "title": "测试产品",
                    "related_links": ["资料摘要"],
                    "source_content_range": "产品参数章节",
                },
            ],
        }

    def test_prepare_planner_result_adds_contract_paths(self):
        from src.utils.ingest_contract import load_ingest_contract

        dims, pages = _prepare_planner_result(self._plan_data(), load_ingest_contract())

        self.assertEqual(dims["series"], ["鸿蒙智行"])
        self.assertEqual(pages[0]["series"], ["鸿蒙智行"])
        self.assertEqual(pages[0]["file_path"], "ware/wiki/sources/鸿蒙智行/资料摘要.md")
        self.assertEqual(pages[1]["file_path"], "ware/wiki/products/测试产品.md")

    def test_prepare_planner_result_applies_page_dimension_overrides(self):
        from src.utils.ingest_contract import load_ingest_contract

        data = self._plan_data()
        data["global_dims"]["sub_business"] = ["太阳膜", "漆面保护膜"]
        data["pages"][1]["sub_business"] = ["太阳膜"]

        dims, pages = _prepare_planner_result(data, load_ingest_contract())

        self.assertEqual(dims["sub_business"], ["太阳膜", "漆面保护膜"])
        self.assertEqual(pages[0]["sub_business"], ["太阳膜", "漆面保护膜"])
        self.assertEqual(pages[1]["sub_business"], ["太阳膜"])

    def test_prepare_planner_result_rejects_scalar_dimension_with_diagnostics(self):
        from src.utils.ingest_contract import load_ingest_contract

        data = self._plan_data()
        data["global_dims"]["sub_business"] = "太阳膜"

        with self.assertRaisesRegex(
            ValueError,
            r"global_dims\.sub_business.*太阳膜.*str.*非空字符串列表",
        ):
            _prepare_planner_result(data, load_ingest_contract())

    def test_prepare_planner_result_rejects_invalid_page_override_with_allowed_values(self):
        from src.utils.ingest_contract import load_ingest_contract

        data = self._plan_data()
        data["pages"][1]["business_category"] = ["不存在的业务"]

        with self.assertRaisesRegex(
            ValueError,
            r"pages\[1\]\.business_category.*不存在的业务.*list.*允许值.*轻改类",
        ):
            _prepare_planner_result(data, load_ingest_contract())

    def test_prepare_planner_result_rejects_model_file_path(self):
        from src.utils.ingest_contract import load_ingest_contract

        data = self._plan_data()
        data["pages"][0]["file_path"] = "ware/wiki/fake.md"

        with self.assertRaisesRegex(ValueError, "file_path"):
            _prepare_planner_result(data, load_ingest_contract())

    def test_prepare_planner_result_rejects_unknown_page_fields(self):
        from src.utils.ingest_contract import load_ingest_contract

        data = self._plan_data()
        data["pages"][1]["unexpected"] = "模型自由扩展"

        with self.assertRaisesRegex(ValueError, "unexpected"):
            _prepare_planner_result(data, load_ingest_contract())

    def test_prepare_planner_result_requires_exactly_one_sources_page(self):
        from src.utils.ingest_contract import load_ingest_contract

        for pages in (
            [self._plan_data()["pages"][1]],
            [self._plan_data()["pages"][0], self._plan_data()["pages"][0]],
        ):
            with self.subTest(count=len(pages)), self.assertRaisesRegex(ValueError, "sources"):
                _prepare_planner_result({**self._plan_data(), "pages": pages}, load_ingest_contract())

    def test_prepare_planner_result_rejects_invalid_dimensions_and_slug(self):
        from src.utils.ingest_contract import load_ingest_contract

        invalid_dims = self._plan_data()
        invalid_dims["global_dims"]["brand"] = "问界"
        with self.assertRaisesRegex(ValueError, "brand"):
            _prepare_planner_result(invalid_dims, load_ingest_contract())

        invalid_slug = self._plan_data()
        invalid_slug["pages"][1]["slug"] = "../测试产品"
        with self.assertRaisesRegex(ValueError, "slug"):
            _prepare_planner_result(invalid_slug, load_ingest_contract())

        reserved_slug = self._plan_data()
        reserved_slug["pages"][1]["slug"] = "CON"
        with self.assertRaisesRegex(ValueError, "slug"):
            _prepare_planner_result(reserved_slug, load_ingest_contract())

        invalid_links = self._plan_data()
        invalid_links["pages"][1]["related_links"] = [123]
        with self.assertRaisesRegex(ValueError, "related_links"):
            _prepare_planner_result(invalid_links, load_ingest_contract())

        duplicate_slug = self._plan_data()
        duplicate_slug["pages"][1]["slug"] = "资料摘要"
        with self.assertRaisesRegex(ValueError, "重复规划 slug"):
            _prepare_planner_result(duplicate_slug, load_ingest_contract())

    def test_preflight_generated_pages_rejects_type_or_path_mismatch(self):
        from src.utils.ingest_contract import load_ingest_contract

        metadata = {
            "schema_version": "v1.0",
            "type": "products",
            "title": "测试产品",
            "series": ["鸿蒙智行"],
            "brand": ["问界"],
            "business_category": ["权益类"],
            "sub_business": ["售后延保"],
            "role": ["驻店销售"],
            "related": [],
            "sources": ["ware/raw/test.pdf"],
            "created": date(2026, 7, 13),
            "updated": date(2026, 7, 13),
        }
        content = "---\n" + "\n".join(
            [
                "schema_version: v1.0",
                "type: products",
                "title: 测试产品",
                "series: [鸿蒙智行]",
                "brand: [问界]",
                "business_category: [权益类]",
                "sub_business: [售后延保]",
                "role: [驻店销售]",
                "related: []",
                "sources: [ware/raw/test.pdf]",
                "created: 2026-07-13",
                "updated: 2026-07-13",
            ]
        ) + "\n---\n正文"
        base = {
            "page_info": {
                "type": "products",
                "slug": "测试产品",
                "series": ["鸿蒙智行"],
                "brand": ["问界"],
                "business_category": ["权益类"],
                "sub_business": ["售后延保"],
                "role": ["驻店销售"],
                "file_path": "ware/wiki/products/测试产品.md",
            },
            "file_path": "ware/wiki/products/测试产品.md",
            "content": content,
        }

        checked = _preflight_generated_pages([base], load_ingest_contract())
        self.assertEqual(checked[0]["post"].metadata, metadata)

        with self.assertRaisesRegex(ValueError, "当前来源"):
            _preflight_generated_pages(
                [base],
                load_ingest_contract(),
                expected_source="ware/raw/other.pdf",
            )

        with self.assertRaisesRegex(ValueError, "路径"):
            _preflight_generated_pages(
                [{**base, "file_path": "ware/wiki/policies/测试产品.md"}],
                load_ingest_contract(),
            )

        wrong_planned_path = {
            **base,
            "page_info": {**base["page_info"], "file_path": "ware/wiki/policies/测试产品.md"},
            "file_path": "ware/wiki/policies/测试产品.md",
        }
        with self.assertRaisesRegex(ValueError, "type/series/slug"):
            _preflight_generated_pages([wrong_planned_path], load_ingest_contract())

        alias_content = content.replace("type: products", "type: product")
        with self.assertRaisesRegex(ValueError, "canonical"):
            _preflight_generated_pages([{**base, "content": alias_content}], load_ingest_contract())

        wrong_series = content.replace("series: [鸿蒙智行]", "series: [岚图]")
        with self.assertRaisesRegex(ValueError, "series"):
            _preflight_generated_pages(
                [{**base, "content": wrong_series}],
                load_ingest_contract(),
            )

        scalar_series = content.replace("series: [鸿蒙智行]", "series: 鸿蒙智行")
        with self.assertRaisesRegex(ValueError, "series.*invalid_type"):
            _preflight_generated_pages(
                [{**base, "content": scalar_series}],
                load_ingest_contract(),
            )

    def test_sources_path_uses_fixed_multi_series_directory(self):
        from src.utils.ingest_contract import load_ingest_contract

        data = self._plan_data()
        data["global_dims"]["series"] = ["鸿蒙智行", "岚图"]

        _, pages = _prepare_planner_result(data, load_ingest_contract())

        self.assertEqual(pages[0]["file_path"], "ware/wiki/sources/多系列/资料摘要.md")

    def test_preflight_accepts_multi_series_sources_path(self):
        from src.utils.ingest_contract import load_ingest_contract

        page_info = {
            "type": "sources",
            "slug": "资料摘要",
            "series": ["鸿蒙智行", "岚图"],
            "brand": ["问界", "岚图"],
            "business_category": ["轻改类"],
            "sub_business": ["太阳膜"],
            "role": ["驻店销售"],
            "file_path": "ware/wiki/sources/多系列/资料摘要.md",
        }
        content = """---
schema_version: v1.0
type: sources
title: 资料摘要
series: [鸿蒙智行, 岚图]
brand: [问界, 岚图]
business_category: [轻改类]
sub_business: [太阳膜]
role: [驻店销售]
related: []
sources: [ware/raw/test.pdf]
created: 2026-07-14
updated: 2026-07-14
---
正文
"""

        checked = _preflight_generated_pages(
            [{"page_info": page_info, "file_path": page_info["file_path"], "content": content}],
            load_ingest_contract(),
            expected_source="ware/raw/test.pdf",
        )

        self.assertEqual(len(checked), 1)

    def test_publish_overrides_keep_multi_series_sources_path(self):
        import src.api.routes.ingest as ingest_route
        from src.utils.ingest_contract import load_ingest_contract

        post = frontmatter.loads("""---
schema_version: v1.0
type: sources
title: 资料摘要
series: [鸿蒙智行, 岚图]
brand: [问界, 岚图]
business_category: [轻改类]
sub_business: [太阳膜]
role: [驻店销售]
related: []
sources: [ware/raw/test.pdf]
created: 2026-07-14
updated: 2026-07-14
---
正文
""")
        with tempfile.TemporaryDirectory() as tmp:
            original_base_dir = ingest_route.BASE_DIR
            original_wiki_dir = ingest_route.WIKI_DIR
            ingest_route.BASE_DIR = tmp
            ingest_route.WIKI_DIR = str(Path(tmp) / "ware" / "wiki")
            try:
                overrides = _prepare_ingest_page_overrides(
                    [{
                        "post": post,
                        "file_path": "ware/wiki/sources/多系列/资料摘要.md",
                    }],
                    filename="test.pdf",
                    schema_contract=load_ingest_contract(),
                )
            finally:
                ingest_route.BASE_DIR = original_base_dir
                ingest_route.WIKI_DIR = original_wiki_dir

        self.assertEqual(
            list(overrides),
            [str(Path(tmp) / "ware" / "wiki" / "sources" / "多系列" / "资料摘要.md")],
        )


if __name__ == "__main__":
    unittest.main()