Commit 1280b860 by 黄南光

Merge remote-tracking branch 'origin/codex/file-list-sort-filter' into codex/file-list-sort-filter

# Conflicts:
#	src/api/routes/ingest.py
2 parents d05f2472 49138246
...@@ -35,6 +35,16 @@ INGEST_MODEL_NAME = os.environ.get("INGEST_MODEL_NAME", "qwen3.7-plus") ...@@ -35,6 +35,16 @@ INGEST_MODEL_NAME = os.environ.get("INGEST_MODEL_NAME", "qwen3.7-plus")
QUERY_MODEL_NAME = os.environ.get("QUERY_MODEL_NAME", "deepseek-v4-flash") QUERY_MODEL_NAME = os.environ.get("QUERY_MODEL_NAME", "deepseek-v4-flash")
LINT_MODEL_NAME = os.environ.get("LINT_MODEL_NAME", "deepseek-v4-flash") LINT_MODEL_NAME = os.environ.get("LINT_MODEL_NAME", "deepseek-v4-flash")
# ==================================================================================
# 摄入并发控制
# ==================================================================================
# #2: 同时允许并行摄入的文件数量上限。设为 1 等价于旧的全局串行锁。
# 建议根据 LLM API 速率限制调整(默认 3 份文件并行)。
INGEST_MAX_CONCURRENT_FILES = int(os.environ.get("INGEST_MAX_CONCURRENT_FILES", "3"))
# #11: 单个文件内 Phase 2 Writer 并发数(同时向 LLM 提交的页面写作请求数)。
INGEST_WRITER_CONCURRENCY = int(os.environ.get("INGEST_WRITER_CONCURRENCY", "20"))
# INGEST_MODEL_NAME = os.environ.get("INGEST_MODEL_NAME", "qwen3.7-plus") # INGEST_MODEL_NAME = os.environ.get("INGEST_MODEL_NAME", "qwen3.7-plus")
# QUERY_MODEL_NAME = os.environ.get("QUERY_MODEL_NAME", "qwen3.7-plus") # QUERY_MODEL_NAME = os.environ.get("QUERY_MODEL_NAME", "qwen3.7-plus")
# LINT_MODEL_NAME = os.environ.get("LINT_MODEL_NAME", "qwen3.7-plus") # LINT_MODEL_NAME = os.environ.get("LINT_MODEL_NAME", "qwen3.7-plus")
......
...@@ -51,6 +51,13 @@ async def startup_event(): ...@@ -51,6 +51,13 @@ async def startup_event():
await init_db() await init_db()
await ensure_wiki_schema() await ensure_wiki_schema()
logger.info("Database initialized.") logger.info("Database initialized.")
# #3: 重启恢复 — 将上次中断的 Ingesting 文件回滚为 Pending
try:
from src.api.routes.ingest import recover_interrupted_ingests
recovered = await recover_interrupted_ingests()
logger.info("Ingest recovery check finished: recovered=%d", recovered)
except Exception as exc:
logger.warning("Ingest recovery check failed: %s", exc)
try: try:
from src.rag.service import repair_interrupted_indexes from src.rag.service import repair_interrupted_indexes
......
...@@ -206,6 +206,15 @@ ecosystem_names: ...@@ -206,6 +206,15 @@ ecosystem_names:
- 嘀加 # 合作生态/产品服务品牌,不是车辆 brand - 嘀加 # 合作生态/产品服务品牌,不是车辆 brand
- 广联数科 # 公司/生态名称,不是车辆 brand - 广联数科 # 公司/生态名称,不是车辆 brand
# Planner 未返回或无法确定某维度时的兜底默认值。
# Python 摄入网关从此处读取,避免业务默认值散布在代码中。
dim_defaults:
series: "未知系列[待确认]"
brand: "未知品牌[待确认]"
business_category: "未知业务[待确认]"
sub_business: "未知子业务[待确认]"
role: "通用"
# tags 建议词表。tags 是自由检索标签,不参与 5 维结构化过滤。 # tags 建议词表。tags 是自由检索标签,不参与 5 维结构化过滤。
tag_suggestions: tag_suggestions:
- 异议处理 # 销售异议处理场景 - 异议处理 # 销售异议处理场景
......
...@@ -3,6 +3,8 @@ import ast ...@@ -3,6 +3,8 @@ import ast
import os import os
import json import json
import re import re
import shutil
import tempfile
import frontmatter import frontmatter
import yaml import yaml
from datetime import datetime from datetime import datetime
...@@ -18,7 +20,11 @@ from fastapi.concurrency import run_in_threadpool ...@@ -18,7 +20,11 @@ from fastapi.concurrency import run_in_threadpool
from src.database.session import AsyncSessionLocal from src.database.session import AsyncSessionLocal
from src.database.models import WikiFile, WikiFilePage, WikiOperationLog from src.database.models import WikiFile, WikiFilePage, WikiOperationLog
from config import RAW_DIR, WIKI_DIR, BASE_DIR, INGEST_MODEL_NAME from config import (
RAW_DIR, WIKI_DIR, BASE_DIR, INGEST_MODEL_NAME,
INGEST_MAX_CONCURRENT_FILES, # #2: 同时允许摄入的文件数
INGEST_WRITER_CONCURRENCY, # #11: Writer 并发数
)
from src.utils.llm_tracker import ( from src.utils.llm_tracker import (
current_llm_call_context, current_llm_call_context,
current_task_token_usage, current_task_token_usage,
...@@ -28,8 +34,7 @@ from src.utils.llm_tracker import ( ...@@ -28,8 +34,7 @@ from src.utils.llm_tracker import (
load_skill_prompt, load_skill_prompt,
new_token_counter, new_token_counter,
print_thinking, print_thinking,
) )from src.utils.ingest_contract import (
from src.utils.ingest_contract import (
as_value_list as contract_as_value_list, as_value_list as contract_as_value_list,
canonicalize_type, canonicalize_type,
contract_prompt_text, contract_prompt_text,
...@@ -37,6 +42,7 @@ from src.utils.ingest_contract import ( ...@@ -37,6 +42,7 @@ from src.utils.ingest_contract import (
load_ingest_contract, load_ingest_contract,
merge_field_sources as contract_merge_field_sources, merge_field_sources as contract_merge_field_sources,
recompute_after_source_removal as contract_recompute_after_source_removal, recompute_after_source_removal as contract_recompute_after_source_removal,
validate_planner_output, # #5: Planner 输出校验
) )
from src.tools.document_parser import extract_text_from_file, get_last_extract_stats from src.tools.document_parser import extract_text_from_file, get_last_extract_stats
...@@ -500,9 +506,10 @@ async def ingest_file(file_id: str, background_tasks: BackgroundTasks): ...@@ -500,9 +506,10 @@ async def ingest_file(file_id: str, background_tasks: BackgroundTasks):
# ================================================================================== # ==================================================================================
# 摄入全局锁保证同一时间只有一个摄入任务;文件级锁保证同一文件的摄入/摄出互斥。 # 摄入并发控制:信号量允许最多 INGEST_MAX_CONCURRENT_FILES 份文件并行摄入;
# 文件级锁保证同一文件的摄入/摄出互斥。
# ================================================================================== # ==================================================================================
ingest_global_lock = asyncio.Lock() ingest_global_semaphore = asyncio.Semaphore(INGEST_MAX_CONCURRENT_FILES) # #2: 可配置并发数
file_operation_locks: dict[str, asyncio.Lock] = {} file_operation_locks: dict[str, asyncio.Lock] = {}
ingest_tasks: dict[str, asyncio.Task] = {} ingest_tasks: dict[str, asyncio.Task] = {}
ingest_cancel_requested: set[str] = set() ingest_cancel_requested: set[str] = set()
...@@ -559,6 +566,36 @@ def _raise_if_ingest_cancelled(file_id: str) -> None: ...@@ -559,6 +566,36 @@ def _raise_if_ingest_cancelled(file_id: str) -> None:
raise asyncio.CancelledError() raise asyncio.CancelledError()
async def recover_interrupted_ingests() -> int:
"""#3: 服务启动时调用,将上次中断遗留的 Ingesting 状态文件回滚为 Pending。
防止进程重启后文件永远卡在 Ingesting 状态无法再摄入。
"""
async with AsyncSessionLocal() as session:
result = await session.execute(
select(WikiFile).where(WikiFile.status == "Ingesting")
)
stuck_files = result.scalars().all()
count = 0
for db_file in stuck_files:
logger.warning(
f"[Recovery] resetting_stuck_file file_id={db_file.id}, "
f"name={db_file.name}, old_status=Ingesting"
)
db_file.status = "Pending"
db_file.error_message = "服务重启时自动回滚(上次摄入被中断)"
session.add(WikiOperationLog(
file_id=db_file.id,
file_name=db_file.name,
operation="INGEST_RECOVERY",
details=json.dumps({"reason": "service_restart"}, ensure_ascii=False),
))
count += 1
if count:
await session.commit()
logger.info(f"[Recovery] reset {count} stuck Ingesting file(s) to Pending")
return count
async def _mark_ingest_cancelled(file_id: str) -> None: async def _mark_ingest_cancelled(file_id: str) -> None:
logger.info(f"[IngestCancel] mark_cancelled_start file_id={file_id}") logger.info(f"[IngestCancel] mark_cancelled_start file_id={file_id}")
ingest_cancel_requested.discard(file_id) ingest_cancel_requested.discard(file_id)
...@@ -646,9 +683,12 @@ def _recompute_after_source_removal(md: dict, removed_source: str) -> None: ...@@ -646,9 +683,12 @@ def _recompute_after_source_removal(md: dict, removed_source: str) -> None:
async def run_ingest_agent(file_id: str): async def run_ingest_agent(file_id: str):
try: try:
_raise_if_ingest_cancelled(file_id) _raise_if_ingest_cancelled(file_id)
logger.info(f"[IngestTask] waiting_for_ingest_global_lock file_id={file_id}") logger.info(
async with ingest_global_lock: f"[IngestTask] waiting_for_ingest_global_semaphore file_id={file_id}, "
logger.info(f"[IngestTask] acquired_ingest_global_lock file_id={file_id}") f"max_concurrent={INGEST_MAX_CONCURRENT_FILES}"
)
async with ingest_global_semaphore: # #2: 信号量,允许最多 N 份文件并行
logger.info(f"[IngestTask] acquired_ingest_global_semaphore file_id={file_id}")
_raise_if_ingest_cancelled(file_id) _raise_if_ingest_cancelled(file_id)
logger.info(f"[IngestTask] waiting_for_file_lock file_id={file_id}") logger.info(f"[IngestTask] waiting_for_file_lock file_id={file_id}")
async with _get_file_operation_lock(file_id): async with _get_file_operation_lock(file_id):
...@@ -836,7 +876,12 @@ async def _run_ingest_agent_impl(file_id: str): ...@@ -836,7 +876,12 @@ async def _run_ingest_agent_impl(file_id: str):
except Exception as e: except Exception as e:
raise ValueError(f"无法解析 JSON 格式: {clean_json[:200]}..., error: {e}") raise ValueError(f"无法解析 JSON 格式: {clean_json[:200]}..., error: {e}")
pages = plan_data.get("pages", []) # #5: 使用 validate_planner_output 做结构校验,格式非法时立即抛异常
try:
raw_global_dims, pages = validate_planner_output(plan_data)
except ValueError as ve:
raise ValueError(f"[Phase 1] Planner 输出格式校验失败: {ve}") from ve
logger.info( logger.info(
f"[{filename}] [Phase 1] plan_parsed pages_count={len(pages)}, " f"[{filename}] [Phase 1] plan_parsed pages_count={len(pages)}, "
f"page_paths={[p.get('file_path') for p in pages if isinstance(p, dict)]}" f"page_paths={[p.get('file_path') for p in pages if isinstance(p, dict)]}"
...@@ -844,7 +889,7 @@ async def _run_ingest_agent_impl(file_id: str): ...@@ -844,7 +889,7 @@ async def _run_ingest_agent_impl(file_id: str):
_raise_if_ingest_cancelled(file_id) _raise_if_ingest_cancelled(file_id)
# 解析结构化 5 维(兼容旧 global_tags 数组格式做兜底) # 解析结构化 5 维(兼容旧 global_tags 数组格式做兜底)
raw_dims = plan_data.get("global_dims") or {} raw_dims = raw_global_dims # #5: 由 validate_planner_output 已提取
def _norm_scalar(v, default): def _norm_scalar(v, default):
if isinstance(v, list): if isinstance(v, list):
...@@ -865,12 +910,14 @@ async def _run_ingest_agent_impl(file_id: str): ...@@ -865,12 +910,14 @@ async def _run_ingest_agent_impl(file_id: str):
raw_dims = {"series": gt[1], "brand": gt[0], "business_category": gt[2], raw_dims = {"series": gt[1], "brand": gt[0], "business_category": gt[2],
"sub_business": gt[3], "role": gt[4]} "sub_business": gt[3], "role": gt[4]}
# #9: 从 schema contract 读取维度默认值,避免硬编码在代码中
_defaults = schema_contract.dim_defaults
global_dims = { global_dims = {
"series": _norm_scalar(raw_dims.get("series"), "未知系列[待确认]"), "series": _norm_scalar(raw_dims.get("series"), _defaults.get("series", "未知系列[待确认]")),
"brand": _norm_list(raw_dims.get("brand")) or ["未知品牌[待确认]"], "brand": _norm_list(raw_dims.get("brand")) or [_defaults.get("brand", "未知品牌[待确认]")],
"business_category": _norm_scalar(raw_dims.get("business_category"), "未知业务[待确认]"), "business_category": _norm_scalar(raw_dims.get("business_category"), _defaults.get("business_category", "未知业务[待确认]")),
"sub_business": _norm_scalar(raw_dims.get("sub_business"), "未知子业务[待确认]"), "sub_business": _norm_scalar(raw_dims.get("sub_business"), _defaults.get("sub_business", "未知子业务[待确认]")),
"role": _norm_list(raw_dims.get("role")) or ["通用"], "role": _norm_list(raw_dims.get("role")) or [_defaults.get("role", "通用")],
} }
logger.info(f"[{filename}] [Phase 1] 规划完成。全局维度: {global_dims},规划页面数: {len(pages)}") logger.info(f"[{filename}] [Phase 1] 规划完成。全局维度: {global_dims},规划页面数: {len(pages)}")
...@@ -966,14 +1013,24 @@ async def _run_ingest_agent_impl(file_id: str): ...@@ -966,14 +1013,24 @@ async def _run_ingest_agent_impl(file_id: str):
except Exception as check_err: except Exception as check_err:
logger.warning(f"[{filename}] [Phase 2] 页面校验失败 {page_info.get('file_path')} (第 {attempt+1} 次): {check_err}") logger.warning(f"[{filename}] [Phase 2] 页面校验失败 {page_info.get('file_path')} (第 {attempt+1} 次): {check_err}")
if attempt < max_retries: if attempt < max_retries:
msg_write = Msg("user", f"你上一次的输出未通过规范校验!错误原因:{str(check_err)}。请修复后重新输出完整的 Markdown 页面。", role="user") # #6: 将上次失败的完整输出一并传给 LLM,让它精准修复而非重头生成
failed_output = content if 'content' in dir() and content else "(上次未能解析出有效内容)"
msg_write = Msg(
"user",
f"你上一次的输出未通过规范校验!\n"
f"错误原因:{str(check_err)}\n\n"
f"以下是你上次的完整输出(请在此基础上修复,而非从头重写):\n\n"
f"{failed_output}\n\n"
f"请修复后重新输出完整的 Markdown 页面。",
role="user",
)
else: else:
error_msg = f"页面 {page_info.get('file_path')} 连续重试校验失败,摄入中止。" error_msg = f"页面 {page_info.get('file_path')} 连续重试校验失败,摄入中止。"
logger.error(f"[{filename}] [Phase 2] {error_msg}") logger.error(f"[{filename}] [Phase 2] {error_msg}")
raise ValueError(error_msg) raise ValueError(error_msg)
# 引入 asyncio.Semaphore(20) 作为并发信号量控制器 # #11: Writer 并发信号量,数量由配置项 INGEST_WRITER_CONCURRENCY 控制
sem = asyncio.Semaphore(20) sem = asyncio.Semaphore(INGEST_WRITER_CONCURRENCY)
async def sem_write_single_page(page_info): async def sem_write_single_page(page_info):
async with sem: async with sem:
return await write_single_page_with_retry(page_info) return await write_single_page_with_retry(page_info)
...@@ -1029,7 +1086,7 @@ async def _run_ingest_agent_impl(file_id: str): ...@@ -1029,7 +1086,7 @@ async def _run_ingest_agent_impl(file_id: str):
# 阶段三:合并保存与同步 (Phase 3: Batch Save & Sync) # 阶段三:合并保存与同步 (Phase 3: Batch Save & Sync)
# ================================================================================== # ==================================================================================
if valid_files: if valid_files:
logger.info(f"[{filename}] [Phase 3] 开始批量安全保存...") logger.info(f"[{filename}] [Phase 3] 开始批量原子保存 (staging)...")
_raise_if_ingest_cancelled(file_id) _raise_if_ingest_cancelled(file_id)
# 构建磁盘上现有 slug -> 路径 映射,用于 slug 全局唯一性预检 # 构建磁盘上现有 slug -> 路径 映射,用于 slug 全局唯一性预检
...@@ -1052,132 +1109,188 @@ async def _run_ingest_agent_impl(file_id: str): ...@@ -1052,132 +1109,188 @@ async def _run_ingest_agent_impl(file_id: str):
segs = [s for s in tail.split("/") if s] segs = [s for s in tail.split("/") if s]
return segs[0] if segs else "misc" return segs[0] if segs else "misc"
for vf in valid_files: # ── #4 原子保存:staging + backup + rollback ──────────────────────────
_raise_if_ingest_cancelled(file_id) # staging_dir: 临时目录,所有新文件/合并文件先写入此处
slug = os.path.splitext(os.path.basename(vf["file_path"]))[0] # backup_pairs: [(原始路径, 备份路径)],仅已存在的文件才备份
# 解析失败兜底用的预备落点(Planner 原始路径) # staged_pairs: [(staging文件路径, 最终目标路径)],全部成功后才 shutil.move
fpath = os.path.join(BASE_DIR, vf["file_path"]) staging_dir = tempfile.mkdtemp(
prefix=f"ingest_{file_id[:8]}_", dir=os.path.dirname(WIKI_DIR)
)
backup_pairs: list[tuple[str, str]] = []
staged_pairs: list[tuple[str, str]] = []
try: try:
post = frontmatter.loads(vf["content"]) for vf in valid_files:
_raise_if_ingest_cancelled(file_id)
slug = os.path.splitext(os.path.basename(vf["file_path"]))[0]
# 解析失败兜底用的预备落点(Planner 原始路径)
fpath = os.path.join(BASE_DIR, vf["file_path"])
# —— 路径确定性化:按 type 推导落点,忽略 Planner 自加的子目录 —— try:
page_type = canonicalize_type( post = frontmatter.loads(vf["content"])
post.metadata.get("type") or _type_dir_of(vf["file_path"]),
schema_contract, # —— 路径确定性化:按 type 推导落点,忽略 Planner 自加的子目录 ——
) page_type = canonicalize_type(
post.metadata["type"] = page_type post.metadata.get("type") or _type_dir_of(vf["file_path"]),
if page_type == "sources": schema_contract,
series_value = _as_value_list(post.metadata.get("series")) or ["未分类"] )
series = str(series_value[0]).strip() post.metadata["type"] = page_type
series = re.sub(r'[\\/:*?"<>|]', "_", series) or "未分类" if page_type == "sources":
rel_path = f"ware/wiki/sources/{series}/{slug}.md" series_value = _as_value_list(post.metadata.get("series")) or ["未分类"]
else: series = str(series_value[0]).strip()
rel_path = f"ware/wiki/{page_type}/{slug}.md" series = re.sub(r'[\\/:*?"<>|]', "_", series) or "未分类"
fpath = os.path.join(BASE_DIR, rel_path) rel_path = f"ware/wiki/sources/{series}/{slug}.md"
else:
# —— slug 冲突 → 合并而非报错 —— rel_path = f"ware/wiki/{page_type}/{slug}.md"
conflict = disk_slug_paths.get(slug) fpath = os.path.join(BASE_DIR, rel_path)
if conflict and os.path.abspath(conflict) != os.path.abspath(fpath):
if _type_dir_of(conflict) == page_type: # —— slug 冲突 → 合并而非报错 ——
# 同类型:同一 slug = 同一页面,重定向合并到既有页面 conflict = disk_slug_paths.get(slug)
if conflict and os.path.abspath(conflict) != os.path.abspath(fpath):
if _type_dir_of(conflict) == page_type:
# 同类型:同一 slug = 同一页面,重定向合并到既有页面
logger.info(
f"[{filename}] [Phase 3] slug '{slug}' 已存在于 "
f"{os.path.relpath(conflict, BASE_DIR)},本次内容合并入既有页面"
)
fpath = conflict
rel_path = os.path.relpath(conflict, BASE_DIR).replace("\\", "/")
else:
# 跨类型撞名:真正的命名歧义,保证 [[slug]] 可解析
raise ValueError(
f"slug 跨类型冲突:'{slug}' 已存在于 "
f"{os.path.relpath(conflict, BASE_DIR)}(type={_type_dir_of(conflict)}),"
f"无法作为 {page_type} 重复创建"
)
# 记录真实落点,供后续 DB(WikiFilePage)/log/摄出精确定位
vf["file_path"] = rel_path
logger.info(
f"[{filename}] [Phase 3] staging_page slug={slug}, "
f"rel_path={rel_path}, abs_path={fpath}, exists={os.path.exists(fpath)}"
)
# 归一化 sources 为规范路径 ware/raw/{filename}
sources = _as_value_list(post.metadata.get("sources"))
sources = [s for s in sources if s not in (
f"raw/{filename}", canonical_source
) and not s.startswith("ware/raw/sources/")]
sources.append(canonical_source)
post.metadata["sources"] = sources
# 被 HTML 注释包裹的正文块
wrapped_content = f"\n<!-- SOURCE_START: {canonical_source} -->\n{post.content.strip()}\n<!-- SOURCE_END: {canonical_source} -->\n"
block_re = re.compile(
rf"<!-- SOURCE_START: {re.escape(canonical_source)} -->.*?<!-- SOURCE_END: {re.escape(canonical_source)} -->",
re.DOTALL,
)
# 确定 staging 路径(与 fpath 结构对应但在 staging_dir 下)
rel_to_base = os.path.relpath(fpath, BASE_DIR)
staging_path = os.path.join(staging_dir, rel_to_base)
os.makedirs(os.path.dirname(staging_path), exist_ok=True)
if os.path.exists(fpath):
# 已有文件:先备份,再在 staging 中操作合并结果
backup_path = fpath + f".ingest_{file_id[:8]}.bak"
shutil.copy2(fpath, backup_path)
backup_pairs.append((fpath, backup_path))
# 以磁盘原文件为基础,在 staging_path 上做合并写入
shutil.copy2(fpath, staging_path)
old_post = frontmatter.load(staging_path)
# 1. 合并 sources
old_sources = _as_value_list(old_post.metadata.get("sources"))
if canonical_source not in old_sources:
old_sources.append(canonical_source)
old_post.metadata["sources"] = old_sources
# 2. 统一字段级溯源合并(含 5 结构化字段 + title/tags/related 等)
_merge_field_sources(old_post.metadata, post.metadata, canonical_source)
# 3. 正文:已存在本源 SOURCE 块则替换(避免重复摄入叠加),否则追加
old_body = old_post.content
if block_re.search(old_body):
old_body = block_re.sub(wrapped_content.strip(), old_body)
else:
old_body = old_body.strip() + "\n" + wrapped_content
old_post.content = old_body
save_post_with_formatting(old_post, staging_path)
logger.info( logger.info(
f"[{filename}] [Phase 3] slug '{slug}' 已存在于 " f"[{filename}] [Phase 3] staged_merge slug={slug}, "
f"{os.path.relpath(conflict, BASE_DIR)},本次内容合并入既有页面" f"rel_path={rel_path}, source={canonical_source}"
) )
fpath = conflict
rel_path = os.path.relpath(conflict, BASE_DIR).replace("\\", "/")
else: else:
# 跨类型撞名:真正的命名歧义,保证 [[slug]] 可解析 # 新建:从零初始化 field_sources(覆盖全部受追踪字段)
raise ValueError( fs = {}
f"slug 跨类型冲突:'{slug}' 已存在于 " for key, val in post.metadata.items():
f"{os.path.relpath(conflict, BASE_DIR)}(type={_type_dir_of(conflict)})," if key in SOURCE_TRACKED_EXCLUDE:
f"无法作为 {page_type} 重复创建" continue
vals = _as_value_list(val)
if not vals:
continue
fs[key] = {item: [canonical_source] for item in vals}
if fs:
post.metadata["field_sources"] = fs
post.content = wrapped_content.strip()
save_post_with_formatting(post, staging_path)
logger.info(
f"[{filename}] [Phase 3] staged_new slug={slug}, "
f"rel_path={rel_path}, source={canonical_source}"
) )
# 记录真实落点,供后续 DB(WikiFilePage)/log/摄出精确定位 staged_pairs.append((staging_path, fpath))
vf["file_path"] = rel_path # 记录新落盘的 slug,供后续页面的唯一性预检
os.makedirs(os.path.dirname(fpath), exist_ok=True) disk_slug_paths[slug] = os.path.abspath(fpath)
logger.info(
f"[{filename}] [Phase 3] saving_page slug={slug}, "
f"rel_path={rel_path}, abs_path={fpath}, exists={os.path.exists(fpath)}"
)
# 归一化 sources 为规范路径 ware/raw/{filename}
sources = _as_value_list(post.metadata.get("sources"))
sources = [s for s in sources if s not in (
f"raw/{filename}", canonical_source
) and not s.startswith("ware/raw/sources/")]
sources.append(canonical_source)
post.metadata["sources"] = sources
# 被 HTML 注释包裹的正文块
wrapped_content = f"\n<!-- SOURCE_START: {canonical_source} -->\n{post.content.strip()}\n<!-- SOURCE_END: {canonical_source} -->\n"
block_re = re.compile(
rf"<!-- SOURCE_START: {re.escape(canonical_source)} -->.*?<!-- SOURCE_END: {re.escape(canonical_source)} -->",
re.DOTALL,
)
if os.path.exists(fpath):
old_post = frontmatter.load(fpath)
# 1. 合并 sources
old_sources = _as_value_list(old_post.metadata.get("sources"))
if canonical_source not in old_sources:
old_sources.append(canonical_source)
old_post.metadata["sources"] = old_sources
# 2. 统一字段级溯源合并(含 5 结构化字段 + title/tags/related 等) except ValueError:
_merge_field_sources(old_post.metadata, post.metadata, canonical_source) raise
except Exception as e:
# 3. 正文:已存在本源 SOURCE 块则替换(避免重复摄入叠加),否则追加 logger.error(
old_body = old_post.content f"[{filename}] [Phase 3] 解析或 staging 文件时发生错误: {e}",
if block_re.search(old_body): exc_info=True
old_body = block_re.sub(wrapped_content.strip(), old_body)
else:
old_body = old_body.strip() + "\n" + wrapped_content
old_post.content = old_body
save_post_with_formatting(old_post, fpath)
logger.info(
f"[{filename}] [Phase 3] merged_existing_page slug={slug}, "
f"rel_path={rel_path}, source={canonical_source}"
)
else:
# 新建:从零初始化 field_sources(覆盖全部受追踪字段)
fs = {}
for key, val in post.metadata.items():
if key in SOURCE_TRACKED_EXCLUDE:
continue
vals = _as_value_list(val)
if not vals:
continue
fs[key] = {item: [canonical_source] for item in vals}
if fs:
post.metadata["field_sources"] = fs
post.content = wrapped_content.strip()
save_post_with_formatting(post, fpath)
logger.info(
f"[{filename}] [Phase 3] created_new_page slug={slug}, "
f"rel_path={rel_path}, source={canonical_source}"
) )
raise # 直接向上抛出,触发下面的 rollback
# 记录新落盘的 slug,供后续页面的唯一性预检 # ── 全部 staging 成功 → 原子性移动到目标路径 ──
disk_slug_paths[slug] = os.path.abspath(fpath) logger.info(
except ValueError: f"[{filename}] [Phase 3] all staging done, committing "
raise f"{len(staged_pairs)} file(s) to final paths..."
except Exception as e: )
logger.error(f"[{filename}] [Phase 3] 解析或保存文件时发生错误,退化为直接写入: {e}", exc_info=True) for staging_path, final_path in staged_pairs:
wrapped_raw = f"\n<!-- SOURCE_START: {canonical_source} -->\n{vf['content']}\n<!-- SOURCE_END: {canonical_source} -->\n" os.makedirs(os.path.dirname(final_path), exist_ok=True)
os.makedirs(os.path.dirname(fpath), exist_ok=True) shutil.move(staging_path, final_path)
if os.path.exists(fpath):
with open(fpath, "a", encoding="utf-8") as f_out: # ── 提交成功 → 清理备份 ──
f_out.write(wrapped_raw) for _, backup_path in backup_pairs:
else: if os.path.exists(backup_path):
with open(fpath, "w", encoding="utf-8") as f_out: os.remove(backup_path)
f_out.write(wrapped_raw)
logger.info(f"[{filename}] [Phase 3] 文件原子保存完成,共 {len(staged_pairs)} 个页面。")
logger.info(f"[{filename}] [Phase 3] 文件保存完成。")
except Exception:
# ── 回滚:恢复备份文件,确保磁盘与改动前一致 ──
logger.error(
f"[{filename}] [Phase 3] 保存过程中发生错误,正在回滚 "
f"{len(backup_pairs)} 个备份文件...",
exc_info=True
)
for original_path, backup_path in backup_pairs:
if os.path.exists(backup_path):
try:
shutil.move(backup_path, original_path)
logger.info(f"[{filename}] [Phase 3] rollback_restored path={original_path}")
except Exception as rb_err:
logger.error(
f"[{filename}] [Phase 3] rollback_failed path={original_path}, err={rb_err}"
)
raise
finally:
# ── 无论成败,清理临时目录 ──
if os.path.exists(staging_dir):
shutil.rmtree(staging_dir, ignore_errors=True)
# 统计本次生成内容中的 wikilink 总数(供 lint 增量模式使用) # 统计本次生成内容中的 wikilink 总数(供 lint 增量模式使用)
total_wikilinks = sum( total_wikilinks = sum(
...@@ -1186,7 +1299,7 @@ async def _run_ingest_agent_impl(file_id: str): ...@@ -1186,7 +1299,7 @@ async def _run_ingest_agent_impl(file_id: str):
) )
pages_list = ", ".join([vf.get('file_path', '') for vf in valid_files]) pages_list = ", ".join([vf.get('file_path', '') for vf in valid_files])
print(f"[{filename}] [阶段三] 正在重建 index.md 并写入 log.md...") logger.info(f"[{filename}] [Phase 3] 正在重建 index.md 并写入 log.md...") # #14
# index.md 确定性全量重建(替换历史的「只追加」方式) # index.md 确定性全量重建(替换历史的「只追加」方式)
rebuild_index(WIKI_DIR) rebuild_index(WIKI_DIR)
logger.info(f"[{filename}] [Phase 3] index_rebuilt wiki_dir={WIKI_DIR}") logger.info(f"[{filename}] [Phase 3] index_rebuilt wiki_dir={WIKI_DIR}")
...@@ -1199,7 +1312,7 @@ async def _run_ingest_agent_impl(file_id: str): ...@@ -1199,7 +1312,7 @@ async def _run_ingest_agent_impl(file_id: str):
f" - 模式: 3-phase\n" f" - 模式: 3-phase\n"
) )
append_wiki_file("ware/wiki/log.md", log_entry) append_wiki_file("ware/wiki/log.md", log_entry)
print(f"[{filename}] [阶段三] 数据同步完成,摄入流水线整体结束。") logger.info(f"[{filename}] [Phase 3] 数据同步完成,摄入流水线整体结束。") # #14
# ================================================================================== # ==================================================================================
# 任务后处理:元数据与统计指标记录 # 任务后处理:元数据与统计指标记录
......
...@@ -11,6 +11,9 @@ import yaml ...@@ -11,6 +11,9 @@ import yaml
CONTRACT_START = "<!-- INGEST_CONTRACT_START -->" CONTRACT_START = "<!-- INGEST_CONTRACT_START -->"
CONTRACT_END = "<!-- INGEST_CONTRACT_END -->" CONTRACT_END = "<!-- INGEST_CONTRACT_END -->"
# #5: Planner 每个 page 必须包含的字段
_PLANNER_PAGE_REQUIRED = ("type", "slug", "file_path", "title")
@dataclass(frozen=True) @dataclass(frozen=True)
class IngestContract: class IngestContract:
...@@ -23,6 +26,7 @@ class IngestContract: ...@@ -23,6 +26,7 @@ class IngestContract:
business_categories: tuple[str, ...] business_categories: tuple[str, ...]
vehicle_brands: tuple[str, ...] vehicle_brands: tuple[str, ...]
ecosystem_names: tuple[str, ...] ecosystem_names: tuple[str, ...]
dim_defaults: dict[str, str] # #9: Planner 维度兜底默认值
prompt_text: str prompt_text: str
...@@ -73,6 +77,10 @@ def load_ingest_contract(schema_path: str | None = None) -> IngestContract: ...@@ -73,6 +77,10 @@ def load_ingest_contract(schema_path: str | None = None) -> IngestContract:
if not canonical_types: if not canonical_types:
raise ValueError("schema contract 缺少 canonical_types") raise ValueError("schema contract 缺少 canonical_types")
# #9: 解析 dim_defaults,不存在时使用空字典(代码内有硬编码兜底)
dim_defaults_raw = raw.get("dim_defaults") or {}
dim_defaults = {str(k): str(v) for k, v in dim_defaults_raw.items()}
return IngestContract( return IngestContract(
schema_version=str(raw.get("schema_version") or "").strip(), schema_version=str(raw.get("schema_version") or "").strip(),
required_fields=tuple(raw.get("required_fields") or ()), required_fields=tuple(raw.get("required_fields") or ()),
...@@ -83,6 +91,7 @@ def load_ingest_contract(schema_path: str | None = None) -> IngestContract: ...@@ -83,6 +91,7 @@ def load_ingest_contract(schema_path: str | None = None) -> IngestContract:
business_categories=tuple(raw.get("business_categories") or ()), business_categories=tuple(raw.get("business_categories") or ()),
vehicle_brands=_flatten_vehicle_brands(raw.get("vehicle_brands") or {}), vehicle_brands=_flatten_vehicle_brands(raw.get("vehicle_brands") or {}),
ecosystem_names=tuple(raw.get("ecosystem_names") or ()), ecosystem_names=tuple(raw.get("ecosystem_names") or ()),
dim_defaults=dim_defaults,
prompt_text=schema_text, prompt_text=schema_text,
) )
...@@ -186,3 +195,53 @@ def recompute_after_source_removal( ...@@ -186,3 +195,53 @@ def recompute_after_source_removal(
md["field_sources"] = fs md["field_sources"] = fs
else: else:
md.pop("field_sources", None) md.pop("field_sources", None)
def validate_planner_output(plan_data: dict) -> tuple[dict, list[dict]]:
"""#5: 校验 Planner JSON 输出结构,返回 (global_dims, pages)。
格式不合规时抛 ValueError,让 Phase 1 直接终止或触发重试,
而非静默地将格式错误延迟到 Phase 2/3 才暴露。
"""
if not isinstance(plan_data, dict):
raise ValueError(
f"Planner 输出必须是 JSON 对象,实际类型为 {type(plan_data).__name__}"
)
pages = plan_data.get("pages")
if not isinstance(pages, list) or len(pages) == 0:
raise ValueError(
f"Planner 输出的 pages 必须是非空数组,"
f"实际类型为 {type(pages).__name__ if pages is not None else 'null'}"
)
for i, page in enumerate(pages):
if not isinstance(page, dict):
raise ValueError(
f"pages[{i}] 必须是 JSON 对象,实际类型为 {type(page).__name__}"
)
missing = [f for f in _PLANNER_PAGE_REQUIRED if not page.get(f)]
if missing:
raise ValueError(
f"pages[{i}](slug={page.get('slug', '?')})缺少必填字段: {missing}"
)
global_dims = plan_data.get("global_dims")
if global_dims is not None and not isinstance(global_dims, dict):
raise ValueError(
f"global_dims 必须是 JSON 对象或 null,实际类型为 {type(global_dims).__name__}"
)
# 必须包含至少 1 个 sources 类型页面
has_sources = any(
isinstance(p, dict) and str(p.get("type", "")).strip() in ("sources", "source")
for p in pages
)
if not has_sources:
raise ValueError(
"Planner 规划必须包含至少 1 个 type=sources 的来源摘要页"
)
return global_dims or {}, pages
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!