语义召回"恒空"的根因分四层,本提交修掉投递层与读取层(另两层——重试计数
门禁、episode 不投 rebuild 事件——已在前两个提交修复)。
R2 投递层:dispatch_profile_rebuild 只做图投影,没有任何 Milvus 投递,
长期记忆的向量从未被写入过(实测客户 9001 在 memory_sync_outbox 里 0 行)。
新增 _enqueue_memory_vector_projection(),在画像重建后投
MemorySyncOutbox(target_store="milvus")。走事件而不是同步写,是为了拿
Outbox 的重试/退避/死信,且不把 embedding 的网络等待拖进事务。
⚠️ payload 必须带 version(正整数):适配器 _coerce_profile_version 缺它
直接抛 ValueError(实测踩到,事件立刻 failed)。
R4 读取层:写的集合与读的集合不是同一个 ——
写(MilvusProfileProjection)用 "user_long_term_memory_v1",
读(bootstrap.get_vector_memory_adapter)与删(projection_cleanup_service)
却用 settings.milvus_collection = "jr_memory",而该集合从未被创建。
⇒ 召回:MilvusClient 构造不校验集合存在,适配器"构造成功"但每次 search
抛异常被 VectorMemoryAdapter 吞成 degraded → 召回恒
degraded_reasons=('milvus_unavailable',)、向量命中恒 0 条;
⇒ 清理:jr_memory 不在集合列表 → 走 vector_collection_absent 分支 →
报清理成功但一个向量都没删,陈旧向量永久留存。
修法:PROFILE_COLLECTION 成为唯一常量,读/删两侧直接引用它;
并删除 Settings.milvus_collection 配置项、清掉 .env.example 的
MILVUS_COLLECTION —— 写侧从来没读过它,一个只在契约一侧生效的配置项
比没有配置项更危险(Settings 的 extra="ignore" 会让其他环境残留的该
变量被安全忽略)。
顺带:
- 语义检索把客户过滤下推到 Milvus(filter="customer_id == N")。此前不带
过滤,别家客户的命中会白占 limit 名额,稀释本客户的召回条数。
- upsert 在 sources 为空时先返回,不再无条件 load_collection ——
"本来就没有可写内容"不该被记成投递失败(10001/10002 那两条事件即如此
重试 5 次进死信)。
回归守卫:tests/unit/infrastructure/test_memory_vector_collection_consistency.py
断言读侧与删侧用的都是 PROFILE_COLLECTION,且被删掉的配置项不得回归。
这个缺陷能活下来,正是因为两侧单测全绿而接缝无人守。
验证(走生产装配、进程内调用,未重启你正在跑的 API 窗口):
读侧集合打印 user_long_term_memory_v1(修前为 jr_memory);
召回 degraded=False / reasons=() / sources 含 milvus,且排序随 query 语义
变化(投资期限→horizon 0.288 > risk_level 0.201;风险偏好→risk_level 0.287);
query="进取型" 双通道合并且 vector_score=0.9987;query=None 走 mysql 全量。
pytest tests/unit tests/contract → 1432 passed, 2 skipped, 1 failed
(唯一失败是同事正在改的投顾页面,与记忆链路无关)。
文档:docs/演示用/记忆召回恒空-根因与修复-2026-09-14.md(新增,四层根因+证据)、
docs/37-记忆投影链路实现说明.md(补集合名三侧契约)。
143 lines
5.3 KiB
Python
143 lines
5.3 KiB
Python
from dataclasses import dataclass
|
|
from typing import Any, Protocol
|
|
|
|
|
|
class VectorClient(Protocol):
|
|
def search(
|
|
self, collection_name: str, data: list[list[float]], limit: int,
|
|
filter: str | None = None,
|
|
) -> Any: ...
|
|
|
|
|
|
class VectorSearchResult:
|
|
def __init__(self, hits: Any, degraded: bool = False) -> None:
|
|
self.hits = hits
|
|
self.degraded = degraded
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class VectorHit:
|
|
"""标准化后的向量命中;`memory_uuid` 用于回表,`score` 为集合内相似度。"""
|
|
|
|
memory_uuid: str
|
|
score: float
|
|
|
|
|
|
class VectorMemoryAdapter:
|
|
"""Milvus 读边界:查询失败一律降级,绝不让向量库故障冒泡到主链路。"""
|
|
|
|
# `memory_uuid` 的候选字段名,覆盖实体列与常见别名。
|
|
_UUID_FIELDS = ("memory_uuid", "uuid", "memory_id", "id")
|
|
_SCORE_FIELDS = ("score", "distance", "similarity")
|
|
|
|
def __init__(self, client: VectorClient, collection: str) -> None:
|
|
self.client = client
|
|
self.collection = collection
|
|
|
|
def search(
|
|
self,
|
|
embedding: list[float],
|
|
limit: int = 10,
|
|
*,
|
|
customer_id: int | None = None,
|
|
) -> VectorSearchResult:
|
|
"""按向量检索;给了 `customer_id` 就**在集合内按客户过滤**。
|
|
|
|
过滤必须下推到 Milvus:召回服务回表时虽然也会按客户筛一次,但不过滤的话
|
|
别家客户的命中会白占 `limit` 名额,本客户能拿到的条数被稀释甚至清零——
|
|
这在多客户数据集上会表现成"语义召回时有时无"。
|
|
|
|
过滤表达式在 `try` **之外**求值:`customer_id` 不是整数属调用方编码错误,
|
|
应当直接抛出,不能伪装成"Milvus 不可用"而被降级吞掉。
|
|
"""
|
|
expr = None if customer_id is None else f"customer_id == {int(customer_id)}"
|
|
try:
|
|
kwargs: dict[str, Any] = {} if expr is None else {"filter": expr}
|
|
hits = self.client.search(
|
|
collection_name=self.collection,
|
|
data=[embedding],
|
|
limit=max(1, min(limit, 100)),
|
|
**kwargs,
|
|
)
|
|
return VectorSearchResult(hits)
|
|
except Exception:
|
|
return VectorSearchResult([], degraded=True)
|
|
|
|
def parse_hits(self, hits: Any) -> list[VectorHit]:
|
|
"""把 pymilvus 的嵌套命中结构折叠为 `VectorHit` 列表(纯函数,不抛异常)。
|
|
|
|
pymilvus 返回 `[[{id, distance, entity}]]`(每查询一组),行内既有实体字典
|
|
也有命名为 `id` / `distance` 的字段,这里两种形态都吸收;没有可识别
|
|
`memory_uuid` 的行被丢弃而不是猜造标识,避免召回无法回表的假引用。
|
|
"""
|
|
parsed: list[VectorHit] = []
|
|
for row in self._flatten(hits):
|
|
hit = self._parse_hit(row)
|
|
if hit is not None:
|
|
parsed.append(hit)
|
|
return parsed
|
|
|
|
def _flatten(self, hits: Any) -> list[Any]:
|
|
rows: list[Any] = []
|
|
for group in hits if isinstance(hits, (list, tuple)) else [hits]:
|
|
if isinstance(group, (list, tuple)):
|
|
rows.extend(group)
|
|
else:
|
|
rows.append(group)
|
|
return rows
|
|
|
|
def _parse_hit(self, row: Any) -> VectorHit | None:
|
|
if isinstance(row, dict):
|
|
fields = dict(row)
|
|
elif isinstance(row, (list, tuple)) and len(row) >= 2:
|
|
# 无实体字典时的裸数组形态:约定 (主键, 距离)。
|
|
return self._hit_from_pair(str(row[0]), row[1])
|
|
else:
|
|
fields = self._object_fields(row)
|
|
entity = fields.get("entity")
|
|
if isinstance(entity, dict):
|
|
merged = dict(entity)
|
|
merged.update({key: value for key, value in fields.items() if key != "entity"})
|
|
fields = merged
|
|
uuid = self._first_string(fields, self._UUID_FIELDS)
|
|
if uuid is None:
|
|
return None
|
|
return VectorHit(memory_uuid=uuid, score=self._score(fields))
|
|
|
|
def _hit_from_pair(self, raw_id: str, raw_score: Any) -> VectorHit | None:
|
|
if not raw_id:
|
|
return None
|
|
return VectorHit(memory_uuid=raw_id, score=self._as_float(raw_score) or 0.0)
|
|
|
|
def _object_fields(self, row: Any) -> dict[str, Any]:
|
|
fields: dict[str, Any] = {}
|
|
for name in (*self._UUID_FIELDS, *self._SCORE_FIELDS, "entity"):
|
|
if hasattr(row, name):
|
|
fields[name] = getattr(row, name)
|
|
return fields
|
|
|
|
def _first_string(self, fields: dict[str, Any], names: tuple[str, ...]) -> str | None:
|
|
for name in names:
|
|
value = fields.get(name)
|
|
if value is None:
|
|
continue
|
|
if isinstance(value, str) and value.strip():
|
|
return value.strip()
|
|
if isinstance(value, int):
|
|
return str(value)
|
|
return None
|
|
|
|
def _score(self, fields: dict[str, Any]) -> float:
|
|
for name in self._SCORE_FIELDS:
|
|
score = self._as_float(fields.get(name))
|
|
if score is not None:
|
|
return score
|
|
return 0.0
|
|
|
|
def _as_float(self, value: Any) -> float | None:
|
|
try:
|
|
return float(value)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|