Files

53 lines
2.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Kernel 不可插拔不变量(lingtai-runtime.md §1 硬核例外)。
M0 落地其中两条的可执行断言:
- "模型可见即可重建":投影中的每条模型可见消息必须能在事件日志(llm.requested)中找到;
- 流一致性:llm.delta 事件重组文本必须与进入接纳检查的文本一致。
镜树不变量(重生成不覆盖/未归真不入忆/归真不回滚)随 M2 镜树域落地时进入本模块;
禁域裁决点随 M5 司命落地。断言失败即抛 ``InvariantViolation``:Kernel 视其为缺陷
而非业务错误,Run 进入 interrupted 并带 HJ-9000 段错误码。
"""
from __future__ import annotations
from app.modules.runtime.events import Event
from app.shenshi_client.types import ShenshiChatRequest
class InvariantViolation(Exception):
"""Kernel 不变量被违反:缺陷信号,必须中断并留痕。"""
def __init__(self, invariant: str, detail: str) -> None:
super().__init__(f"[{invariant}] {detail}")
self.invariant = invariant
self.detail = detail
def assert_model_visible_logged(
request: ShenshiChatRequest, events: list[Event]
) -> None:
"""投影消息 ⊆ 已记录的 llm.requested 消息("模型可见即可重建")。"""
requested = next((e for e in events if e.type == "llm.requested"), None)
if requested is None:
raise InvariantViolation(
"model-visible-means-logged", "存在模型请求但事件日志缺少 llm.requested"
)
logged = requested.payload.get("request", {}).get("messages", [])
if logged != [m.model_dump() for m in request.messages]:
raise InvariantViolation(
"model-visible-means-logged", "llm.requested 事件与实际发送的 IR 消息不一致"
)
def assert_stream_reconstruction(events: list[Event], accepted_text: str) -> None:
"""llm.delta 重组文本 == 进入接纳的文本(流不丢帧、不重帧)。"""
reconstructed = "".join(
e.payload.get("delta", "") for e in events if e.type == "llm.delta"
)
if reconstructed != accepted_text:
raise InvariantViolation(
"stream-reconstruction",
f"事件重组文本与接纳文本不一致:{len(reconstructed)} != {len(accepted_text)} 字符",
)