背景:memory_sync_outbox 这条链此前**完全没有消费者**,且生产端照 docs/00 §6.4.6
写成大写 MILVUS/NEO4J + 中文「待处理」,而消费端按 target_store 的**值**分派 handler、
且只领 status in {pending, failed} —— 两个条件都不满足,事件任何消费者都领不到、
永久滞留且不报错(唯一键 (event_uuid, target_store) 对大小写无约束,MySQL 也不报错)。
根因是代码与测试都硬编码字面量,所以测试跟着一起错、谁也没拦住。
订正
- profile_generation_service:取值改为全仓一致的小写(milvus/neo4j/upsert/pending)
- 测试改为引用常量并断言消费端契约,不再硬编码(硬编码是本次跑偏的直接原因)
- 新增契约回归测试:断言大写值分派不到 handler、会进死信,谁改回大写立刻红
- 新增 tools/normalize_memory_sync_outbox.py:订正历史脏行(默认 dry-run、幂等)
接通投影链路(此前零消费者)
- 新增 Milvus 集合 user_long_term_memory_v1 及建集合工具(幂等、不覆盖已有集合)
- 新增 MilvusProfileProjection / MilvusProfileVectorClient,并修掉移植带来的两处必炸点:
customer_id 由「必须 int」放宽为接受数字字符串(本仓所有生产者都写 str,
不放宽则每个事件必然失败);不可投影的 memory_key 由「整批 raise」改为跳过留痕
(否则一条 constraint: 记忆毒死该客户整批,而受控词表 13 个键里有 7 个不满足前缀)
- 新增 MemorySyncOutboxWorker(领取/指数退避/死信骨架保留原样)并接入 WorkerRuntime
- milvus → 向量投影;neo4j → 复用主干 ProfileGraphProjectionService(方案 A,
不引入第二套投影,避免同一事实在图中两种说法、违反主干既有的只投影已确认事实的不变式)
- 生产端从 memory_unit(status=active) 组装 memory_sources,随事件带上确定快照
- 前置移植 conversation_privacy:写外部存储前脱敏手机号/证件号/银行卡等
验证
- 新增 17 个单测;全量 2 failed, 1307 passed, 2 skipped
(2 个失败为既有环境项:断言请求体中文原文而 httpx 序列化成 \uXXXX,非本次引入)
- mypy app → 0 错(227 文件);audit_schema → 89 张业务表无缺失/意外,未改动表结构
- 真机:真实 embedding(1024 维) + 真实 Milvus 写入并回读通过
- 整合链路(测试记忆 → 生产端组装 → outbox → 消费端投递 → Milvus 回读)通过,
且 MySQL 已回滚、Milvus 无残留
文档
- 新增 docs/32-记忆投影链路实现说明.md:真实口径、根因、契约与验证证据(供接手)
- AGENTS.md:新增该易错点;新增 Windows 中文输出乱码的正确命令(-X utf8);
校正测试基线与 mypy 文件数
未做:未改 docs/00 基线、未动数据库迁移、未改投顾线代码、未启动常驻 Worker。
遗留:投顾线两处生产者的 payload 缺 memory_sources,会被消费至死信,待架构师确认是否投影。
145 lines
4.9 KiB
Python
145 lines
4.9 KiB
Python
"""幂等创建长期记忆画像向量集合 `user_long_term_memory_v1`。
|
|
|
|
写入侧是 `app/infrastructure/milvus_profile_projection.py`,字段必须与之一致。
|
|
|
|
用法:
|
|
.\\.venv\\Scripts\\python.exe tools\\setup_milvus_profile_collection.py
|
|
|
|
安全口径(与 `setup_milvus_knowledge_collections.py` 相同:这是**共享** Milvus 实例,
|
|
里面还有别的项目在用的集合):
|
|
- 只碰 `user_long_term_memory_v1` 这一个集合,绝不 list 后批量删除;
|
|
- 集合已存在时**只做结构比对并报告**,不覆盖、不删重建;
|
|
- 结构不一致时明确报错退出,由人决定怎么处理,避免静默丢数据。
|
|
"""
|
|
|
|
import asyncio
|
|
import sys
|
|
from typing import Any
|
|
|
|
COLLECTION = "user_long_term_memory_v1"
|
|
VECTOR_FIELD = "embedding"
|
|
VECTOR_DIM = 1024
|
|
PRIMARY_FIELD = "memory_uuid"
|
|
|
|
#: (字段名, 最大长度)。`memory_uuid` 是主键(UUID 字符串)。
|
|
VARCHAR_FIELDS: tuple[tuple[str, int], ...] = (
|
|
("memory_uuid", 64),
|
|
("content", 2048),
|
|
("memory_type", 32),
|
|
("memory_key", 64),
|
|
("status", 16),
|
|
)
|
|
#: INT64 字段;可空,因为 `valid_until_ts` 对永久记忆为空。
|
|
INT64_FIELDS: tuple[str, ...] = (
|
|
"customer_id",
|
|
"version",
|
|
"valid_until_ts",
|
|
"updated_at_ts",
|
|
)
|
|
FLOAT_FIELDS: tuple[str, ...] = ("confidence",)
|
|
|
|
|
|
def _build_schema() -> Any:
|
|
from pymilvus import DataType, MilvusClient # type: ignore[import-untyped]
|
|
|
|
schema = MilvusClient.create_schema(auto_id=False, enable_dynamic_field=False)
|
|
for name, max_length in VARCHAR_FIELDS:
|
|
schema.add_field(
|
|
field_name=name,
|
|
datatype=DataType.VARCHAR,
|
|
max_length=max_length,
|
|
is_primary=(name == PRIMARY_FIELD),
|
|
nullable=False,
|
|
)
|
|
for name in INT64_FIELDS:
|
|
# 可空:`valid_until_ts` 对永久记忆必须能不写。
|
|
schema.add_field(
|
|
field_name=name, datatype=DataType.INT64, nullable=name != "customer_id"
|
|
)
|
|
for name in FLOAT_FIELDS:
|
|
schema.add_field(field_name=name, datatype=DataType.DOUBLE, nullable=False)
|
|
schema.add_field(
|
|
field_name=VECTOR_FIELD, datatype=DataType.FLOAT_VECTOR, dim=VECTOR_DIM
|
|
)
|
|
return schema
|
|
|
|
|
|
def _build_index_params() -> Any:
|
|
from pymilvus import MilvusClient # type: ignore[import-untyped]
|
|
|
|
index_params = MilvusClient.prepare_index_params()
|
|
index_params.add_index(
|
|
field_name=VECTOR_FIELD,
|
|
index_name="profile_vector_index",
|
|
index_type="AUTOINDEX",
|
|
metric_type="COSINE",
|
|
)
|
|
return index_params
|
|
|
|
|
|
def describe_mismatch(described: dict[str, Any]) -> list[str]:
|
|
"""比对已存在集合与期望结构,返回差异列表(一致时为空)。"""
|
|
problems: list[str] = []
|
|
actual = {field["name"]: field for field in described.get("fields", [])}
|
|
expected_names = (
|
|
[name for name, _ in VARCHAR_FIELDS] + list(INT64_FIELDS)
|
|
+ list(FLOAT_FIELDS) + [VECTOR_FIELD]
|
|
)
|
|
for name in expected_names:
|
|
if name not in actual:
|
|
problems.append(f"缺少字段 {name}")
|
|
for name, _ in VARCHAR_FIELDS:
|
|
if name in actual and not actual[name].get("is_primary") and name == PRIMARY_FIELD:
|
|
problems.append(f"{name} 不是主键")
|
|
vector = actual.get(VECTOR_FIELD)
|
|
if vector is not None:
|
|
params = vector.get("params") or {}
|
|
dim = params.get("dim")
|
|
if dim is not None and int(dim) != VECTOR_DIM:
|
|
problems.append(f"{VECTOR_FIELD} 维度是 {dim},期望 {VECTOR_DIM}")
|
|
return problems
|
|
|
|
|
|
async def ensure_collection(uri: str, token: str = "") -> str:
|
|
"""返回 `created` / `exists` / `conflict:<原因>`。"""
|
|
from pymilvus import AsyncMilvusClient # type: ignore[import-untyped]
|
|
|
|
client = AsyncMilvusClient(uri=uri, token=token or None)
|
|
try:
|
|
if await client.has_collection(COLLECTION):
|
|
described = await client.describe_collection(COLLECTION)
|
|
problems = describe_mismatch(described)
|
|
if problems:
|
|
return "conflict:" + "; ".join(problems)
|
|
return "exists"
|
|
await client.create_collection(
|
|
collection_name=COLLECTION,
|
|
schema=_build_schema(),
|
|
index_params=_build_index_params(),
|
|
)
|
|
return "created"
|
|
finally:
|
|
close = getattr(client, "close", None)
|
|
if close is not None:
|
|
await close()
|
|
|
|
|
|
async def main() -> int:
|
|
from app.core.config import get_settings
|
|
|
|
settings = get_settings()
|
|
uri = settings.milvus_uri
|
|
if not uri:
|
|
print("未配置 milvus_uri,无法创建集合")
|
|
return 1
|
|
outcome = await ensure_collection(uri, settings.milvus_token or "")
|
|
print(f"{COLLECTION}: {outcome}")
|
|
if outcome.startswith("conflict:"):
|
|
print("结构不一致,未做任何修改。请人工确认后再处理。")
|
|
return 2
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(asyncio.run(main()))
|