mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-11-06 09:17:31 +00:00
feat(agent): rtchild 实时子 agent + 四类 agent 独立模型源 + 残余任务四态
## rtchild(R1–R13)
第三种、**独立**的子 agent 类型,面向语音/视频通话:内核只要文本流,
不定音频(TTS/播放由插件负责)。
- R1 CapRT 能力位 + AgentConfig.IsRealtime;AssignRealtime 两侧校验
- R2 rtSlot 单槽覆盖(latest-wins,从不排队)
- R3 独立 ctx + rtLoop + SpawnRTChild/StopRTChild
- R4 ChatStream 逐块 → outputch(rt).Execute(text)
- R5 打断 = 原地截断,不重试
- R6 工具执行期不可打断(suppressedCancels 让守卫可观测)
- R7 普通上下文 + 窗口裁剪(旧内容不进模型,**原文保留**)
- R9 CloseRTChild → L4 信号 + rt_transcript 按需分页取
- R10 notify_parent(L4,注册一次,停即注销)
- R11 闲置零 token
- R13 rt_children 管理工具(父专属)
刻意**不做** rtPage/anchor/degraded_resets(过设计,已裁定);
不用四级中断阶梯(preemptCooldown+同级不抢占会让 ~75% 的 rt 打断
静默退化为排队)。
## 四类 agent 各自可配模型源
core.agent.llm.{main,resident,rt,child}_provider,语义是**优先不是独占**:
该源排到候选链最前,其余源仍作回退。硬锁定会让"首选源抖一下"变成
"这个 agent 彻底不工作",而多源回退链正是本仓为此建立的机制。
名字写错 ⇒ 回退默认源 + 记日志(不静默)。子 agent 未配置时继承父的。
★ 顺带修掉一个真缺陷:spawn.go 原来直接 a.provider.Chat(),
**普通子 agent 完全绕过 provider 回退链** —— 它是唯一绕过的地方:
默认源抖一次整条子任务就"执行失败",而主 agent 同刻能自动换源。
## 驻留子残余任务四态 + 通道三态
残余任务:keep / takeover(接手,keep 的明确别名)/ stash(暂存到各自
原通道)/ drop。stash 必须**逐条按各自 OutputChannel 归位** —— 一个子
可能同时收 qq 和 webui,混存会让"接回 qq 的人"拿到本该给 webui 的活。
通道:release(零值,向后兼容)/ suspend(挂起,暂存保留)/ takeover
(接回父并立即释放暂存)。原来是无条件 release,于是只有两种坏结局:
通道一直没人分配(消息无人处理且无提示),或刚好被别的 agent 抢到。
一次定完不留窗口:FinishResidentWith → DestroyResidentWith →
teardownResidentWith。任一环退回不带 disp 的旧函数,disp 就被丢掉、
通道被无条件释放 —— 而 stash 的暂存正挂在那条通道上(实际踩过)。
## 修复"手写字段白名单"丢值(7 处)
同一类缺陷:不传整个结构体,而是手写一份"允许通过的字段清单"。
危险在于**写漏了不报错** —— 字段静默归零,故障出现在很远的地方。
- corehandler.go outputRegister: ChannelDef{NoMemory,Cleaner} → 整体传
- pubSdkInjectOpts: 逐字段摊平丢 ScenePolicy/SecurityProfile → 收整个 injectParams
- injectParams/injectMediaParams: 结构本身缺字段 → 补齐 + asInjectParams()
- 配套反射判据 TestSegment_RoundTripEveryField(取代手写断言,
原判据漏了 Phase/LLMText/FinalText/ToolCalls/ExtraKeyMediaBlocks/ExtraBag)
## 压缩偏离设计
CompressResident 原为截断,与设计(LLM 摘要替换)不符。改走
PlanCompaction → summarizeForCompaction(用子自己的 provider)→
ApplyCompaction,失败回退 TrimKeepRecent。顺带修 ApplyCompaction 的
锁重入 panic 与双重解锁。
并修一处真实生产数据竞争:ctxFullSignaled 由父 goroutine 写、
子调度 goroutine 读,加 ctxFullMu。
## 判据
新增约 70 条。全部验证过能变红(变异测试),包括:
- TestSegment_RoundTripEveryField 的防腐蚀:fullStageContext 反射断言
每个字段非零,否则新字段永远不会被覆盖("假绿")
- TestPreferredProvider_PutsSourceFirstAndKeepsFallbacks 成对断言
"在首位且回退仍在"—— 只断言前者的话,硬锁定也会绿
## 判据自身的坑(两次偶发红,都不是产品缺陷)
1. SpawnResident 末尾 Start(),子会在两次 enqueue 之间取走一条
→ "暂存 0 条"。修法:cancel + waitSchedulerStopped。
(offload_test.go 早有记录,我没先读就重踩了一遍)
2. TaskPrompt 异步投递,可能在清空队列之后才到 → "多 1 条"。
靠探针打印内容才认出是 TaskPrompt。修法:本文件用 spawnQuietResident。
go build/vet/gofmt 干净;go test ./... -count=1 -race = 62 包 ok / 0 FAIL / 0 RACE
This commit is contained in:
@ -253,6 +253,13 @@ type injectParams struct {
|
||||
CleanerName string `json:"cleaner_name,omitempty"`
|
||||
// Priority 声明中断注入的优先级(L1..L3);L4 内核独占,见 InjectOptions。
|
||||
Priority string `json:"priority,omitempty"`
|
||||
// ScenePolicy 声明此次注入是否参与场面识别(场景式记忆)。
|
||||
ScenePolicy string `json:"scene_policy,omitempty"`
|
||||
// SecurityProfile 选择本插件声明的**命名安全限式**(如 "qq.guest")。
|
||||
//
|
||||
// ★ 漏了它等于「插件声明了档位、注入时带了、内核从没收到」——
|
||||
// 策略静默不生效,且没有任何报错(2026-10-30 审计发现,已修)。
|
||||
SecurityProfile string `json:"security_profile,omitempty"`
|
||||
}
|
||||
|
||||
// injectMediaParams 是带媒体注入/工具块注入的参数。
|
||||
@ -275,17 +282,47 @@ type injectMediaParams struct {
|
||||
RecallPolicy string `json:"recall_policy,omitempty"`
|
||||
CleanerName string `json:"cleaner_name,omitempty"`
|
||||
Priority string `json:"priority,omitempty"`
|
||||
// ScenePolicy / SecurityProfile 与 injectParams 同义(见那里的注释)。
|
||||
ScenePolicy string `json:"scene_policy,omitempty"`
|
||||
SecurityProfile string `json:"security_profile,omitempty"`
|
||||
}
|
||||
|
||||
// asInjectParams 把媒体注入参数降成通用注入参数(只取共有的 opts 字段)。
|
||||
//
|
||||
// 为什么要有这个转换:pubSdkInjectOpts 接收 injectParams,而媒体路径用的是
|
||||
// injectMediaParams(多 Blocks/BlocksRef)。与其让 pubSdkInjectOpts 收两个类型
|
||||
// 或改签名成 8 个裸参数(那正是本次修掉的缺陷形态),不如显式降一次。
|
||||
func (p injectMediaParams) asInjectParams() injectParams {
|
||||
return injectParams{
|
||||
Source: p.Source, Channel: p.Channel, Text: p.Text,
|
||||
NoMemory: p.NoMemory, ContextPolicy: p.ContextPolicy,
|
||||
RecallPolicy: p.RecallPolicy, CleanerName: p.CleanerName,
|
||||
Priority: p.Priority, ScenePolicy: p.ScenePolicy,
|
||||
SecurityProfile: p.SecurityProfile,
|
||||
}
|
||||
}
|
||||
|
||||
// pubSdkInjectOpts 把 RPC 报文里的三个字段转成公开 SDK 的 InjectOptions。
|
||||
//
|
||||
// 单独提一个转换函数是为了让「默认值」只有一个出处:零值即记入记忆 + 不裁剪,
|
||||
// 与旧三参数注入等价。
|
||||
func pubSdkInjectOpts(noMemory bool, policy, recallPolicy, cleanerName, priority string) pubsdk.InjectOptions {
|
||||
// ★ 签名接收整个 injectParams 而**不是逐个字段**:
|
||||
//
|
||||
// 曾经的形态是 `pubSdkInjectOpts(noMemory, policy, recallPolicy, cleanerName, priority)`
|
||||
// —— 于是新增 InjectOptions 字段时,这个转换函数**不会**提醒任何人去接,
|
||||
// 实际漏了 ScenePolicy 与 SecurityProfile(后者正是 QQ owner/guest 档位的通路)。
|
||||
//
|
||||
// 现在:`injectParams` 与 `pubsdk.InjectOptions` 字段一一对应,
|
||||
// 新增字段时编译器会在这里提示"未使用/缺字段",而不是静默丢失。
|
||||
func pubSdkInjectOpts(p injectParams) pubsdk.InjectOptions {
|
||||
return pubsdk.InjectOptions{
|
||||
NoMemory: noMemory, ContextPolicy: policy, RecallPolicy: recallPolicy,
|
||||
CleanerName: cleanerName,
|
||||
Priority: clampExternalPriority(priority),
|
||||
NoMemory: p.NoMemory,
|
||||
ContextPolicy: p.ContextPolicy,
|
||||
RecallPolicy: p.RecallPolicy,
|
||||
ScenePolicy: p.ScenePolicy,
|
||||
CleanerName: p.CleanerName,
|
||||
Priority: clampExternalPriority(p.Priority),
|
||||
SecurityProfile: p.SecurityProfile,
|
||||
}
|
||||
}
|
||||
|
||||
@ -558,8 +595,20 @@ func (h *coreHandler) outputRegister(params json.RawMessage) (interface{}, error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("output.register: %w", err)
|
||||
}
|
||||
return nil, h.sdk.RegisterOutputChannel(channel, p.Caps, p.Desc,
|
||||
pubsdk.ChannelDef{NoMemory: p.Def.NoMemory, Cleaner: cleaner},
|
||||
// ★ 整体传 p.Def(只把函数型的 Cleaner 换成代理),**不要手写字段白名单**。
|
||||
//
|
||||
// 这里曾写成 `pubsdk.ChannelDef{NoMemory: p.Def.NoMemory, Cleaner: cleaner}` ——
|
||||
// 一个字段白名单,于是 `Realtime` / `ContextPolicy` / `RecallPolicy` /
|
||||
// `ScenePolicy` **全部静默丢失**。表现(2026-10-30 外部插件 e2e 实测):
|
||||
// 插件声明 `ChannelDef{Realtime:true}` 的 outputch,到内核侧
|
||||
// `OutputCapabilities()` 只有 `[text]`,没有 CapRT ⇒ AssignRealtime 被拒
|
||||
// ⇒ 作者以为"我声明了 rt"却怎么也划不上,且没有任何报错指向这里。
|
||||
//
|
||||
// 输入侧(corehandler_register.go)本来就是正确写法,同一件事故意写成两种,
|
||||
// 所以只修了一半也看不出来。现在两侧同构。
|
||||
def := p.Def
|
||||
def.Cleaner = cleaner
|
||||
return nil, h.sdk.RegisterOutputChannel(channel, p.Caps, p.Desc, def,
|
||||
func(args map[string]interface{}) (interface{}, error) {
|
||||
return h.invokeOutput(channel, args)
|
||||
})
|
||||
|
||||
@ -27,7 +27,7 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter
|
||||
if err := validateRecallPolicy("io.injectText", p.RecallPolicy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h.sdk.InjectTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority))
|
||||
h.sdk.InjectTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p))
|
||||
return nil, nil
|
||||
case MethodIOInjectInterrupt:
|
||||
var p injectParams
|
||||
@ -40,7 +40,7 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter
|
||||
if err := validateRecallPolicy("io.injectInterrupt", p.RecallPolicy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h.sdk.InjectInterruptTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority))
|
||||
h.sdk.InjectInterruptTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p))
|
||||
return nil, nil
|
||||
case MethodIOInjectTextNoMem:
|
||||
var p injectParams
|
||||
@ -54,7 +54,7 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter
|
||||
return nil, err
|
||||
}
|
||||
// 旧 RPC 语义就是「不进记忆」,显式标志位只可能再叠上 context_policy。
|
||||
h.sdk.InjectTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(true, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority))
|
||||
h.sdk.InjectTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p))
|
||||
return nil, nil
|
||||
case MethodIOInjectSync:
|
||||
var p injectParams
|
||||
@ -67,7 +67,7 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter
|
||||
if err := validateRecallPolicy("io.injectInputSync", p.RecallPolicy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reply := h.sdk.InjectInputSyncOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority))
|
||||
reply := h.sdk.InjectInputSyncOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p))
|
||||
return map[string]interface{}{"reply": reply}, nil
|
||||
|
||||
case MethodIOInjectMedia:
|
||||
@ -85,7 +85,7 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h.sdk.InjectInputMediaOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority))
|
||||
h.sdk.InjectInputMediaOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.asInjectParams()))
|
||||
return nil, nil
|
||||
|
||||
case MethodIOInjectMediaSync:
|
||||
@ -103,7 +103,7 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reply := h.sdk.InjectInputMediaSyncOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority))
|
||||
reply := h.sdk.InjectInputMediaSyncOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.asInjectParams()))
|
||||
return map[string]interface{}{"reply": reply}, nil
|
||||
|
||||
case MethodIOInjectInterruptMedia:
|
||||
@ -121,7 +121,7 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h.sdk.InjectInterruptMediaOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority))
|
||||
h.sdk.InjectInterruptMediaOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.asInjectParams()))
|
||||
return nil, nil
|
||||
|
||||
// ---- 多模态注入 ----
|
||||
|
||||
114
internal/plugin/proc/inject_opts_test.go
Normal file
114
internal/plugin/proc/inject_opts_test.go
Normal file
@ -0,0 +1,114 @@
|
||||
package proc
|
||||
|
||||
// 判据:**InjectOptions 的每一个字段都必须能跨进程传过去**。
|
||||
//
|
||||
// 背景(2026-10-30 审计):`pubSdkInjectOpts` 曾逐字段摊平传参
|
||||
// (noMemory, policy, recallPolicy, cleanerName, priority),于是新增字段时
|
||||
// 没人被提醒去接 —— 实际漏了 ScenePolicy 与 SecurityProfile。
|
||||
//
|
||||
// 后者尤其严重:QQ 插件的 owner/guest 档位就是靠 InjectOptions.SecurityProfile
|
||||
// 选的,漏了等于「插件声明了档位、注入时带了、内核从没收到」,策略静默不生效。
|
||||
//
|
||||
// 现在签名接收整个 injectParams,新增字段时编译器会在这里提示。
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
pubsdk "github.com/JianFeeeee/hologramagentsdk/sdk"
|
||||
)
|
||||
|
||||
// TestPubSdkInjectOpts_CarriesEveryField 钉住整体映射:
|
||||
// injectParams 的每个 opt 字段都必须出现在输出的 InjectOptions 里。
|
||||
func TestPubSdkInjectOpts_CarriesEveryField(t *testing.T) {
|
||||
in := injectParams{
|
||||
NoMemory: true,
|
||||
ContextPolicy: "prune",
|
||||
RecallPolicy: "none",
|
||||
ScenePolicy: "none",
|
||||
CleanerName: "voice-cleaner",
|
||||
Priority: "L2",
|
||||
SecurityProfile: "qq.guest",
|
||||
}
|
||||
got := pubSdkInjectOpts(in)
|
||||
|
||||
if !got.NoMemory {
|
||||
t.Error("NoMemory 丢失")
|
||||
}
|
||||
if got.ContextPolicy != "prune" {
|
||||
t.Errorf("ContextPolicy = %q", got.ContextPolicy)
|
||||
}
|
||||
if got.RecallPolicy != "none" {
|
||||
t.Errorf("RecallPolicy = %q —— 漏传则插件声明的召回策略静默失效", got.RecallPolicy)
|
||||
}
|
||||
if got.ScenePolicy != "none" {
|
||||
t.Errorf("ScenePolicy = %q —— 漏传则插件声明的场面策略静默失效", got.ScenePolicy)
|
||||
}
|
||||
if got.CleanerName != "voice-cleaner" {
|
||||
t.Errorf("CleanerName = %q", got.CleanerName)
|
||||
}
|
||||
if got.SecurityProfile != "qq.guest" {
|
||||
t.Errorf("SecurityProfile = %q —— 漏传则插件声明的安全档位**永不生效**"+
|
||||
"(QQ owner/guest 就是走这条)", got.SecurityProfile)
|
||||
}
|
||||
// 外部插件的优先级必须被夹到 L1..L3(L4 内核独占)。
|
||||
if got.Priority == "L4" {
|
||||
t.Error("外部插件竟然传出了 L4 —— 优先级夹取失效")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPubSdkInjectOpts_MediaPathKeepsOpts 钉住媒体注入路径同样不丢字段。
|
||||
//
|
||||
// 媒体路径用 injectMediaParams(多 Blocks/BlocksRef),曾经因为类型不同
|
||||
// 而无法复用同一个转换函数 —— 那正是漏字段的温床。
|
||||
func TestPubSdkInjectOpts_MediaPathKeepsOpts(t *testing.T) {
|
||||
m := injectMediaParams{
|
||||
NoMemory: true,
|
||||
ScenePolicy: "none",
|
||||
SecurityProfile: "qq.owner",
|
||||
}
|
||||
got := pubSdkInjectOpts(m.asInjectParams())
|
||||
if !got.NoMemory {
|
||||
t.Error("媒体路径 NoMemory 丢失")
|
||||
}
|
||||
if got.ScenePolicy != "none" {
|
||||
t.Errorf("媒体路径 ScenePolicy = %q", got.ScenePolicy)
|
||||
}
|
||||
if got.SecurityProfile != "qq.owner" {
|
||||
t.Errorf("媒体路径 SecurityProfile = %q —— 媒体注入同样要带档位", got.SecurityProfile)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInjectParityWithSDK 是**防复发**判据:injectParams/injectMediaParams
|
||||
// 必须覆盖 InjectOptions 的全部字段。
|
||||
//
|
||||
// 做法:构造一个"所有字段都非零"的 InjectOptions,逐个读出名称与值,
|
||||
// 确认转换后不丢。新增 SDK 字段而没改这里时,本判据会红。
|
||||
func TestInjectParityWithSDK(t *testing.T) {
|
||||
// 全字段非零(新字段加进 SDK 后,这里也要加 —— 判据会提示)
|
||||
want := pubsdk.InjectOptions{
|
||||
NoMemory: true,
|
||||
ContextPolicy: "prune",
|
||||
RecallPolicy: "none",
|
||||
ScenePolicy: "none",
|
||||
CleanerName: "c",
|
||||
Priority: "L2",
|
||||
SecurityProfile: "p",
|
||||
}
|
||||
in := injectParams{
|
||||
NoMemory: want.NoMemory, ContextPolicy: want.ContextPolicy,
|
||||
RecallPolicy: want.RecallPolicy, ScenePolicy: want.ScenePolicy,
|
||||
CleanerName: want.CleanerName, Priority: want.Priority,
|
||||
SecurityProfile: want.SecurityProfile,
|
||||
}
|
||||
got := pubSdkInjectOpts(in)
|
||||
// InjectOptions 含 map 字段(不可用 ==),逐字段比。
|
||||
if got.NoMemory != want.NoMemory ||
|
||||
got.ContextPolicy != want.ContextPolicy ||
|
||||
got.RecallPolicy != want.RecallPolicy ||
|
||||
got.ScenePolicy != want.ScenePolicy ||
|
||||
got.CleanerName != want.CleanerName ||
|
||||
got.Priority != want.Priority ||
|
||||
got.SecurityProfile != want.SecurityProfile {
|
||||
t.Fatalf("字段不齐:\n got = %+v\nwant = %+v", got, want)
|
||||
}
|
||||
}
|
||||
@ -35,14 +35,17 @@ func TestClampExternalPriority_RejectsL4(t *testing.T) {
|
||||
|
||||
// 贯穿 pubSdkInjectOpts:RPC 报文里的 priority 必须经过夹取才落到 InjectOptions。
|
||||
func TestPubSdkInjectOpts_ClampsPriority(t *testing.T) {
|
||||
got := pubSdkInjectOpts(true, "prune", "none", "cleaner", "L4")
|
||||
got := pubSdkInjectOpts(injectParams{
|
||||
NoMemory: true, ContextPolicy: "prune", RecallPolicy: "none",
|
||||
CleanerName: "cleaner", Priority: "L4",
|
||||
})
|
||||
if got.Priority != pubsdk.PriorityL3 {
|
||||
t.Fatalf("经桥后的优先级=%q,期望 L3", got.Priority)
|
||||
}
|
||||
if !got.NoMemory || got.ContextPolicy != "prune" || got.RecallPolicy != "none" || got.CleanerName != "cleaner" {
|
||||
t.Fatalf("其它字段被改动:%+v", got)
|
||||
}
|
||||
if l2 := pubSdkInjectOpts(false, "", "", "", "L2"); l2.Priority != pubsdk.PriorityL2 {
|
||||
if l2 := pubSdkInjectOpts(injectParams{Priority: "L2"}); l2.Priority != pubsdk.PriorityL2 {
|
||||
t.Fatalf("L2 应原样通过,实际 %q", l2.Priority)
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@ package proc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@ -124,6 +125,123 @@ func TestSegment_RoundTripAllFields(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSegment_RoundTripEveryField 是**反射驱动的全字段往返**判据。
|
||||
//
|
||||
// ## 它取代了什么
|
||||
//
|
||||
// 上面那条 `TestSegment_RoundTripAllFields` 是逐字段手写断言,历史价值很大
|
||||
// (C ABI 时代它能抓"哪些字段外部插件看不到"),但有两个结构性缺陷:
|
||||
//
|
||||
// 1. **漏字段无声**:它只断言了 Response/NoMemory/Memory/TokenUsage/Errors/
|
||||
// ToolResults/Extra 的 media_type。实测漏了 Phase、LLMText、FinalText、
|
||||
// ToolCalls、ExtraKeyMediaBlocks、ExtraBag —— 而那些字段确实在往返,
|
||||
// 只是没人验。**手写断言永远不会因为"新增字段"而变红。**
|
||||
// 2. 它验证的是"我记得的那几个",不是"全部"。
|
||||
//
|
||||
// 本判据改用反射:遍历 `pubsdk.StageContext` 的每个导出字段,
|
||||
// 构造非零值 → WriteAll → ReadInto → 逐字段比。**新增 SDK 字段而不改
|
||||
// shmcodec 时,这里会红并指名是哪个字段。**
|
||||
//
|
||||
// ## 为什么不用 == 整体比较
|
||||
//
|
||||
// StageContext 内含 `sync.RWMutex`(不可比较)与 map/slice(不可比较),
|
||||
// 只能逐字段用 reflect.DeepEqual。Extra 需要单独归一(具名键提升 + bag)。
|
||||
func TestSegment_RoundTripEveryField(t *testing.T) {
|
||||
seg := newTestSegment(t, 65536)
|
||||
src := fullStageContext(t)
|
||||
|
||||
if err := seg.WriteAll(src); err != nil {
|
||||
t.Fatalf("WriteAll: %v", err)
|
||||
}
|
||||
var dst pubsdk.StageContext
|
||||
if err := seg.ReadInto(&dst); err != nil {
|
||||
t.Fatalf("ReadInto: %v", err)
|
||||
}
|
||||
|
||||
sv := reflect.ValueOf(src).Elem()
|
||||
dv := reflect.ValueOf(&dst).Elem()
|
||||
var lost []string
|
||||
for i := 0; i < sv.NumField(); i++ {
|
||||
f := sv.Type().Field(i)
|
||||
if !f.IsExported() {
|
||||
continue
|
||||
}
|
||||
if name := f.Name; name == "Extra" {
|
||||
continue // 单独验(见下)
|
||||
}
|
||||
if !reflect.DeepEqual(sv.Field(i).Interface(), dv.Field(i).Interface()) {
|
||||
lost = append(lost, fmt.Sprintf("%s: want=%v got=%v",
|
||||
f.Name, sv.Field(i).Interface(), dv.Field(i).Interface()))
|
||||
}
|
||||
}
|
||||
if len(lost) > 0 {
|
||||
t.Fatalf("StageContext 有字段跨进程往返后**丢值或变形**:\n %s\n"+
|
||||
"(修法:在 shmcodec.go 的 captureLocal/writeLocal/readLocal 三处接线)",
|
||||
strings.Join(lost, "\n "))
|
||||
}
|
||||
|
||||
// Extra 的四类具名键 + bag 必须都保住。
|
||||
for _, k := range []string{
|
||||
ExtraKeyMediaBlocks, ExtraKeyMediaType, ExtraKeyInputSource, ExtraKeyOutputChannel,
|
||||
} {
|
||||
if !reflect.DeepEqual(src.Extra[k], dst.Extra[k]) {
|
||||
t.Errorf("Extra[%s] 未往返:want=%v got=%v", k, src.Extra[k], dst.Extra[k])
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(src.Extra["qq_auth"], dst.Extra["qq_auth"]) {
|
||||
t.Errorf("Extra 的自建键(bag)未往返:want=%v got=%v",
|
||||
src.Extra["qq_auth"], dst.Extra["qq_auth"])
|
||||
}
|
||||
}
|
||||
|
||||
// fullStageContext 构造一个**所有导出字段都非零**的 StageContext。
|
||||
//
|
||||
// ★ 它自身带防腐蚀:反射断言每个导出字段都非零。新增 SDK 字段而没在这里
|
||||
// 赋值时,本函数会直接失败 —— 否则那条新字段永远不会被上面那条判据覆盖,
|
||||
// 判据看起来全绿却罩不住新字段("假绿")。
|
||||
func fullStageContext(t *testing.T) *pubsdk.StageContext {
|
||||
t.Helper()
|
||||
resp := "resp"
|
||||
sc := &pubsdk.StageContext{
|
||||
RawMessage: "raw-输入",
|
||||
UserID: "u1",
|
||||
GroupID: "g1",
|
||||
LLMText: "llm-输出",
|
||||
ReasoningContent: "think",
|
||||
FinalText: "final",
|
||||
Response: &resp,
|
||||
Phase: pubsdk.StageAfterToolcall,
|
||||
NoMemory: true,
|
||||
ContextMsgs: []map[string]interface{}{{"role": "user", "content": "hi"}},
|
||||
ToolCalls: []pubsdk.ToolCall{{ID: "c1", Name: "t1", Plugin: "p"}},
|
||||
ToolResults: []pubsdk.ToolResult{{CallID: "c1", Name: "t1", Success: true, Result: "o"}},
|
||||
Memory: []pubsdk.MemItem{{Role: "user", Content: "m", Score: 0.5}},
|
||||
TokenUsage: map[string]int{"prompt": 1},
|
||||
Errors: []string{"e1"},
|
||||
Extra: map[string]interface{}{
|
||||
ExtraKeyMediaBlocks: []interface{}{map[string]interface{}{"type": "text"}},
|
||||
ExtraKeyMediaType: "image",
|
||||
ExtraKeyInputSource: "qq",
|
||||
ExtraKeyOutputChannel: "qq",
|
||||
"qq_auth": "self-key",
|
||||
},
|
||||
}
|
||||
|
||||
// 防腐蚀:每个导出字段都必须非零。
|
||||
v := reflect.ValueOf(sc).Elem()
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
f := v.Type().Field(i)
|
||||
if !f.IsExported() {
|
||||
continue
|
||||
}
|
||||
if v.Field(i).IsZero() {
|
||||
t.Fatalf("StageContext.%s 在 fullStageContext 里没赋值(仍是零值)—— "+
|
||||
"全字段往返判据覆盖不到它。请给它一个非零值。", f.Name)
|
||||
}
|
||||
}
|
||||
return sc
|
||||
}
|
||||
|
||||
// nil Response 与空字符串 Response 必须可区分(短路语义依赖此)。
|
||||
func TestSegment_ResponseNilVsEmpty(t *testing.T) {
|
||||
seg := newTestSegment(t, 8192)
|
||||
|
||||
Reference in New Issue
Block a user