fix: close the failure modes review found in the new code

Three of them were the same shape as the bug this branch exists to fix:
something goes wrong, the library swallows it, and the caller is left
with a number that means the opposite of what happened.

The throttle key had no source in it. Five sources on one model is the
normal case here, so the first one to break would warn once and silence
the other four for the life of the process, and the message never said
which gateway to look at.

An unknown verdict in a cached entry threw away the whole response. The
rehydrator tolerates unknown fields but not unknown values of a known
field, so two library versions sharing a Redis would each invalidate
the other's entries: halved hit rate, and the only log line says the
cache rebuild failed. A purely observational field should not be able
to void a response whose content is intact.

Normalising for telemetry now degrades instead of raising, both for a
bare string and for a value outside the domain. Either one used to
reach the same except and cost the whole row, which is exactly how
1.3.0 lost nineteen calls without anyone noticing.
This commit is contained in:
2026-08-26 02:37:24 -04:00
parent c0b544d233
commit 1307a02b92
9 changed files with 270 additions and 30 deletions
+27 -3
View File
@@ -28,6 +28,31 @@ _KEY_PREFIX = "pgw:cache:"
_RESPONSE_FIELDS = {f.name for f in dataclasses.fields(LLMResponse)}
def _coerce_observation(raw: Any) -> ThinkingObservation:
"""缓存里的三态取值 → 枚举;域外取值降级为 `UNKNOWN`,**不作废整条缓存**。
方向选择的理由: `_rehydrate` 对 JSON 里的**新字段**已经是宽容的(先按
`_RESPONSE_FIELDS` 过滤),对同一字段的**新取值**却不该是致命的。真实场景是
多个项目共用一个 Redis,先升级的那个写入了本版没有的取值,未升级的项目若把
这些条目判成未命中,就会每次真打网关、随后覆写回旧值,两个版本互相打对方的
缓存(表现是命中率莫名腰斩,而通用的"重建失败"文案给不出任何线索)。一个纯
可观测性字段不该有能力废掉内容完好的缓存响应——"整条作废"留给真正破坏内容
完整性的失败(JSON 坏了、结构化重建不过)。
降级到 `UNKNOWN` 而不是别的态: 它的语义恰好就是"本次判不出来",对一个本库
读不懂的取值,这是唯一诚实的说法。
"""
try:
return ThinkingObservation(raw)
except ValueError:
logger.warning(
"缓存条目的 thinking_observation 取值 {!r} 不在本版取值域内(多半由更新版本的"
"进程写入),已降级为 UNKNOWN;响应内容照常复活——可观测性字段不作废缓存",
raw,
)
return ThinkingObservation.UNKNOWN
def digest_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""多模态 content part 先各自 sha256 摘要再参与序列化;文本原文参与。
@@ -134,10 +159,9 @@ class CacheMW:
structured_data = self._rebuild_structured(fields.get("content", ""), request)
# JSON 里存的是 StrEnum 的字符串值,不转就复活成裸 str,与字段注解分叉
# (下游 `is ThinkingObservation.OBSERVED` 会在命中路径上静默为 False);
# 键缺失即升级前写入的旧条目,交给 dataclass 默认值。域外值抛
# ValueError,由下方 except 吞成"按未命中回源"——降级方向正确。
# 键缺失即升级前写入的旧条目,交给 dataclass 默认值
if "thinking_observation" in fields:
fields["thinking_observation"] = ThinkingObservation(fields["thinking_observation"])
fields["thinking_observation"] = _coerce_observation(fields["thinking_observation"])
fields.update(
cache_hit=True,
latency_ms=0,
+32 -5
View File
@@ -55,6 +55,31 @@ def _canonical_meta_json(meta: Mapping[str, Any]) -> str:
return json.dumps(dict(meta), sort_keys=True, ensure_ascii=False, allow_nan=False)
def _normalize_observation(raw: object) -> str:
"""三态裁定 → 落库用的裸 str;不是枚举也不在取值域时降级为 `unknown` 并告警。
**不写 `raw.value`**: `LLMResponse` 是无运行时校验的 frozen dataclass,下游
(尤其迁移期的测试替身)写 `LLMResponse(..., thinking_observation="observed")`
完全自然、`==` 比较照常成立,而 `.value` 会当场抛 `AttributeError`,被 `_record`
的 `except Exception` 吞成一条泛化 warning —— 丢的不是这一列,是**整行**,而
"遥测必录"是铁律。
域外取值同样只降级不抛: 直接 `ThinkingObservation(raw)` 会抛 `ValueError`,
落到同一个 `except` 上、同样丢整行,那只修好了裸 str 一半(口误值对测试替身
一样自然)。降级到 `unknown` 是诚实的——库确实判不出这个取值的含义,而单独
一条点名取值的 warning 保证它不被掩盖(P5 不许默认值掩盖错误)。
"""
try:
return ThinkingObservation(raw).value
except ValueError:
logger.warning(
"thinking_observation 取值 {!r} 不在取值域内,本行降级记为 unknown"
"(其余列照常落库);调用方应传 ThinkingObservation 成员",
raw,
)
return ThinkingObservation.UNKNOWN.value
def _cap_text(text: str, cap: int | None) -> str:
"""超出 cap 时头部硬切并附省略标记 `…(略 N 字)`;cap 为 None 原样返回。"""
if cap is None or len(text) <= cap:
@@ -285,7 +310,9 @@ class TelemetryEmitter:
model_reported: str | None,
sampling: str | None,
reasoning_tokens: int | None,
# issue #16: 枚举形态进来,取 `.value` 后才下沉(归一化同样在本方法内收口)
# issue #16: 枚举形态进来,归一化成裸 str 后才下沉(收口在 `_record` 内)。
# 注解是契约,但 `LLMResponse` 无运行时校验,故 `_normalize_observation`
# 仍按外部输入防御——违约的代价不该是丢掉整行遥测
thinking_observation: ThinkingObservation,
# issue #11: 未归一化的调用方维度,归一化在本方法内收口(recorder 只落库)
tenant_id: str | None,
@@ -339,10 +366,10 @@ class TelemetryEmitter:
# 对所有人永久不可见,空串则可用一条 SQL 审计出未归属的行
tenant_id=tenant_id or "",
meta=_canonical_meta_json(meta),
# 取 `.value` 落裸 str: `StrEnum` 虽是 `str` 子类,asyncpg 的参数
# 编码对子类不保证接受,而遥测写失败只降级成一条 warning——不会当场
# 炸,只会让 Postgres 那一路悄悄少一列数据
thinking_observation=thinking_observation.value,
# 落裸 str: `StrEnum` 虽是 `str` 子类,asyncpg 的参数编码对子类不
# 保证接受,而遥测写失败只降级成一条 warning——不会当场炸,只会让
# Postgres 那一路悄悄少一列数据
thinking_observation=_normalize_observation(thinking_observation),
)
except asyncio.CancelledError:
raise
+5 -1
View File
@@ -32,7 +32,11 @@ def observe_thinking(*, thinking: str, reasoning_tokens: int | None) -> Thinking
"""
if thinking.strip():
return ThinkingObservation.OBSERVED
if reasoning_tokens is None:
# 负数与 None 同档: `ABSENT` 是"上游明确上报未推理"这个最强的正面结论,坏
# 数据给不出它。当前 transport 已在边界把负数归 None,这里仍要自己闭合——本
# 函数对外承诺"外部输入校验后使用",第二个 transport 直接填该值时,漏判会
# 给出一个方向相反的强结论(P5)
if reasoning_tokens is None or reasoning_tokens < 0:
return ThinkingObservation.UNKNOWN
return ThinkingObservation.OBSERVED if reasoning_tokens > 0 else ThinkingObservation.ABSENT
+24 -10
View File
@@ -322,9 +322,12 @@ class OpenAICompatTransport:
# 未登记模型只喊一次: 装配期已喊过,逐次调用再喊是日志洪水。
# 实例级而非模块级 —— 模块级可变状态违反纯 asyncio 中立铁律
self._warned_models: set[str] = set()
# 对账告警独立节流,**不复用** `_warned_models`: 那个 set 的语义是"未登
# 能力已告警过",两件事共用一个开关会互相压制——一方喊过就把另一方静音
self._warned_mismatches: set[tuple[str, bool | None]] = set()
# 对账告警独立节流,**不复用** `_warned_models`: 两者语义不同(那个 set 记
# 的是"未登记能力已告警过",这个记的是"某源某方向的矛盾已告警过"),共用
# 一个容器会让两种告警的生命周期纠缠在一起——将来任一侧想加清空/过期策略,
# 都会连带改掉另一侧的行为。(键空间恰好不相交,故当下**不会**互相压制;
# 分开维护的理由是语义,不是碰撞)
self._warned_mismatches: set[tuple[str, str, bool | None]] = set()
self._client_factory = client_factory or _default_client_factory
self._clients: dict[str, httpx.AsyncClient] = {}
@@ -410,11 +413,20 @@ class OpenAICompatTransport:
return result
def _warn_on_thinking_mismatch(self, source: SourceConfig, result: TransportResult) -> None:
"""声明与观测矛盾即 warning;按 (model, direction) 节流,同组合只喊一次。
"""声明与观测矛盾即 warning;按 (source, model, direction) 节流,同组合只喊一次。
节流键必须含方向: 同一模型的开、关两档是两个独立的矛盾,合并键会让先出现
的那一档把另一档永久静音。逐次调用刷屏会把告警变成噪声,噪声等于没有告警。
三段缺一不可。**方向**: 同一模型的开、关两档是两个独立的矛盾。**源名**:
多源多账号是本库的核心场景,同一 model 跨 N 个源是常态,而每个源背后是
独立的账号/网关,一个源的行为不代表另一个——漏掉源名,5 个源里第一个出
问题的喊完一次,其余四个永久静音。逐次调用刷屏会把告警变成噪声,噪声等于
没有告警。
**先判键再对账**: `reconcile_thinking` 会拼含完整 `evidence` 的长字符串,
而非流式档每次调用都命中这一分支,节流后再拼是纯粹的热路径浪费。
"""
key = (source.name, source.model, source.enable_thinking)
if key in self._warned_mismatches:
return
message = reconcile_thinking(
enable_thinking=source.enable_thinking,
observation=result.thinking_observation,
@@ -423,11 +435,13 @@ class OpenAICompatTransport:
)
if message is None:
return
key = (source.model, source.enable_thinking)
if key in self._warned_mismatches:
return
self._warned_mismatches.add(key)
logger.warning(message)
# 源名拼在调用点而不是加进 `reconcile_thinking` 的签名: 那是纯判定函数,
# 输入只该含判定依据(声明/观测/能力/模型),源名是**定位信息**,进不了判据。
# 单参数传入 loguru: 文案里带 `thinking:{type:disabled}` 这类字面花括号
# (能力表 evidence),将来有人给这行加个格式化参数就会炸在成功调用的返回
# 路径上(与 telemetry/sqlite.py 的缺列告警同一先例)
logger.warning("{} —— {}", source.name, message)
async def embed(
self, *, texts: list[str], source: SourceConfig, call_id: str