WuKongIM 插件迁移基准测试基线:NoPersist 实时投递与 HTTP Forward Fanout 延迟分支的 Go Benchmark 实践

原创2026-10-15 13:29:571,401 阅读
文章标签:即时通讯后端

WuKongIM 插件迁移基准测试基线:NoPersist 实时投递与 HTTP Forward Fanout 延迟分支的 Go Benchmark 实践

本文以 internalv2 Plugin Benchmark Baseline 实现计划 与其配套设计文档为主体,结合 WuKongIM 仓库中 internal/runtime/channelappend(channel append 运行时)与 internal/usecase/plugin(插件用例层)的真实源码与测试,讲解如何为两条"迁移期高风险路径"建立可量化的 Go 微基准基线:一是 command 风格 NoPersist 实时投递的全链路 submit 路径,二是插件 /plugin/httpForward toNodeId=-1 的 fanout 延迟(deferred)分支。读完本文,你将掌握这两个基准的完整代码、执行命令、底层调用链,以及如何在不改动生产代码的前提下为运行时行为建立回归护栏。

背景:为什么需要这两条基准基线

在 WuKongIM 的插件能力向新版运行时(文档中称为 internalv2 迁移路径)演进的过程中,插件基准测试覆盖已经包含了不少路径:send hook 候选选择与 BeforeSend、PersistAfter 事件克隆与消息批量映射、插件 host RPC 的 message / channel messages / cluster / conversation / HTTP forward 本地与远程调用映射、插件 hook worker 入队压力,以及 channelappend 的持久化 submit、post-commit 插件入队、recipient 投递 worker 入队。

但设计文档指出还有两条高风险的迁移边缘没有被直接钉住(pinned):

  1. command 风格的 NoPersist 实时投递——它要走真实的本地 channelappend submit 路径(Group.SubmitLocal),而不是只测纯粹的 realtimeEffect 辅助函数;
  2. /plugin/httpForward toNodeId=-1 的 fanout 延迟分支——这是一个常量时间(constant-time)的分支,需要断言它返回类型化的延迟错误,并且不产生任何本地/远程转发副作用。

这两条路径在后续迁移步骤中最容易被意外回归,因此需要把它们的性能特征以基准形式固定下来。设计文档明确说明了本次改造的边界:不做生产代码优化、不改变运行时行为、不新增指标、不跑大规模黑盒 wkbench 场景,纯粹是"加基准、钉基线"。

从仓库结构看,计划中提到的 internalv2/ 目录对应当前仓库实际的 internal/ 目录(即 internal/runtime/channelappend 与 internal/usecase/plugin)。两个基准均已落地在包内 _test.go 文件中,这样可以直接复用现有测试端口(test ports)与接收器(sink),无需任何生产代码改动。

基准一:command 风格 NoPersist 实时投递基准

待测路径的语义

在讲解基准代码前,先看这条路径在 channelappend 运行时 中的真实语义。NoPersist 发送与普通持久化发送走同一套 authority 路由与 recipient 机制,但不会创建任何 Channel 日志或 membership 状态:

NoPersist sends use the same authority and recipient machinery but create no Channel log or membership state. Ordinary sends retain the source Channel; command-style sends retain the command Channel. Both allocate a transient message ID and enter online delivery with sequence zero, preserving the sender's complete setting bitset, topic, and expiration just as durable envelopes do.

—— FLOW.md

也就是说:持久化消息保留源 Channel,command 风格消息保留 command Channel;两者都分配一个瞬态消息 ID,以 sequence 0 进入在线投递,并且像持久化信封一样保留发送者的完整 setting 位集合、topic 与过期时间。

设计文档给出的数据流如下:

command-style NoPersist SEND
  -> Group.SubmitLocal
  -> prepareNoPersistRealtimeSend
  -> realtimeEffect
  -> dispatchCommittedRecipientsForTarget
  -> RecipientDeliveryEnqueuer.EnqueueRecipientBatch
  -> SENDACK success

在真实源码中,这条链路的实现分布在三处:

  • prepare.go:prepareNoPersistSend 先用 FromCommandChannel 还原源 Channel,若 SyncOnce 为真或原本就是 command Channel,则再经 ToCommandChannel 转回 command Channel;随后进入 prepareNoPersistRealtimeSend 完成校验、分配消息 ID,并标记为 realtime,从而在 prepareBatch 中被归入 realtime 分组;
  • realtime.go:realtimeEffect.run 对每个条目调用 runItem,以 onlinedelivery.ModeTransient(瞬态模式)执行 dispatchRecipientsForTarget,信封中的 MessageSeq 为 0,成功后返回 ReasonSuccess;
  • recipient.go:dispatchRecipientsForTarget 优先处理 MessageScopedUIDs(免去订阅者扫描),再处理单人(person)Channel 解码,最后按 target.Large || command 决定走订阅者分页还是快照。

基准代码

基准位于 internal/runtime/channelappend/benchmark_test.go,已经与 BenchmarkSubmitLocalHotChannel 等既有 submit 基准并排存在:

func BenchmarkSubmitLocalNoPersistRealtimeScoped(b *testing.B) {
	group := newBenchmarkChannelAppendGroup(b, Options{
		LocalNodeID:                1,
		AuthorityShardCount:        1,
		EffectPoolSize:             4,
		AdmissionCapacityPerShard:  4096,
		InboxCoalesceWindow:        -time.Nanosecond,
		RecipientAuthorityResolver: staticRecipientAuthorityResolverForRecipientTest{nodeID: 1},
		OnlineDeliveryEnqueuer:     &benchmarkRealtimeDeliveryEnqueuer{},
	})
	item := benchmarkSendItem("bench-nopersist-realtime")
	target := benchmarkAuthorityTarget(runtimechannelid.ToCommandChannel(item.Command.ChannelID))
	item.Command.NoPersist = true
	item.Command.SyncOnce = true
	item.Command.MessageScopedUIDs = []string{"u1"}
	startGoroutines := runtime.NumGoroutine()

	b.ReportAllocs()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		results, err := submitAndWaitBenchmark(group, target, item)
		if err != nil {
			b.Fatalf("submit/wait error = %v", err)
		}
		if len(results) != 1 || results[0].Err != nil || results[0].Result.Reason != ReasonSuccess {
			b.Fatalf("results = %#v, want one successful realtime result", results)
		}
	}
	b.StopTimer()
	b.ReportMetric(float64(runtime.NumGoroutine()-startGoroutines), "goroutine-delta")
}

配置参数逐项说明(对应 Options 结构 中的定义):

参数 基准取值 语义
LocalNodeID 1 允许持有本地 Channel authority 状态的节点 ID
AuthorityShardCount 1 Channel key 查找分片数,<=0 时使用单分片
EffectPoolSize 4 直接 ants 池大小,分别用于阻塞 append 调用与 append 后 recipient 效应
AdmissionCapacityPerShard 4096 每个分片允许"已准入但未完成"的条目上限
InboxCoalesceWindow -time.Nanosecond 负值表示禁用合并(coalescing),让每条消息独立进入实时路径
RecipientAuthorityResolver 静态解析器(nodeID=1) 把每个 recipient UID 解析到其 authority 节点
OnlineDeliveryEnqueuer benchmarkRealtimeDeliveryEnqueuer 把有界 plan 转交给在线投递的端口

关键点:

  • item.Command.NoPersist = true 让消息走瞬态实时投递;
  • item.Command.SyncOnce = true 使 command 风格语义生效(保留 command Channel);
  • item.Command.MessageScopedUIDs = []string{"u1"} 走消息级作用域 UID 投递,避免订阅者扫描,从而精确测量实时投递核心路径;
  • 注意 target 使用 runtimechannelid.ToCommandChannel(...) 把 Channel ID 转换为 command Channel——这正是"command 风格"的关键;
  • 循环内每次迭代都通过 submitAndWaitBenchmark 提交并等待,断言恰好一个成功结果;
  • 基准结束前用 b.StopTimer() 停止计时,并通过 b.ReportMetric(..., "goroutine-delta") 报告基准前后 goroutine 数量差,用于发现 goroutine 泄漏回归。

计划文档中给出的入队辅助器签名为 EnqueueRecipientBatch,而仓库落地版本按 OnlineDeliveryEnqueuer 接口 实现为 EnqueueRecipientDeliveryPlan(见 benchmark_test.go):

type benchmarkRealtimeDeliveryEnqueuer struct {
	count atomic.Uint64
}

func (e *benchmarkRealtimeDeliveryEnqueuer) EnqueueRecipientDeliveryPlan(context.Context, onlinedelivery.RecipientDeliveryPlan) error {
	e.count.Add(1)
	return nil
}

它只做一次原子计数并返回 nil,把投递端口压到最低成本,从而让基准聚焦于 submit/准备/实时效应/收件人规划本身的 CPU 与分配开销。在真实链路中,最终由 dispatchRecipientPlans 按 RecipientBatchSize 分批调用该端口,批次边界由 defaultRecipientBatchSize 约束。

执行命令

计划要求先做 1x 冒烟(-benchtime=1x 表示每个基准只迭代一次,用于验证编译与正确性):

go test ./internal/runtime/channelappend -run '^$' -bench '^BenchmarkSubmitLocalNoPersistRealtimeScoped$' -benchtime=1x

-run '^$' 跳过所有单元测试,只执行匹配的基准。期望输出:PASS,且包含一条基准结果与分配数据(因为调用了 b.ReportAllocs())。

基准二:插件 HTTP Forward fanout 延迟分支基准

待测路径的语义

第二条基准针对插件 host RPC 的 /plugin/httpForward。真实实现在 internal/usecase/plugin/host_rpc_http.go 中,HTTPForward 的判定逻辑非常清晰:

switch {
case normalized.GetToNodeId() == -1:
	return nil, ErrHTTPForwardFanoutDeferred
case normalized.GetToNodeId() > 0:
	// 远程转发:需要 HTTPForwarder 端口
	resp, err := a.httpForwarder.ForwardPluginHTTP(ctx, uint64(normalized.GetToNodeId()), normalized)
	...
default:
	// 本地路由:走插件 Route
	return a.Route(ctx, normalized.GetPluginNo(), normalized.GetRequest())
}

ToNodeId == -1 代表广播/fanout 语义(向所有节点转发),而错误类型在 types.go 中定义为:

// ErrHTTPForwardFanoutDeferred reports that broadcast HTTP forward is not implemented in phase 1.
ErrHTTPForwardFanoutDeferred = errors.New("plugin http forward fanout deferred")

即:广播式 HTTP forward 在阶段一尚未实现,返回延迟(deferred)错误。这条分支是常量时间的——不发起任何远程调用、不触碰本地路由,因此把它做成基准基线,就能把"兼容性决策保持为一个廉价分支"这件事量化地钉住,避免未来做集群级插件转发时悄悄引入开销或副作用。

在进入 HTTPForward 之前,请求还会经过 normalizeHTTPForwardRequest:补全 PluginNo(空则取 caller UID)、克隆请求、剥离 hop-by-hop 头(Connection、Keep-Alive、Transfer-Encoding 等)、校验 body 与 header 大小。默认限制见 host_rpc_http.go:defaultHTTPForwardMaxBodyBytes = 10 << 20(10 MiB)、defaultHTTPForwardMaxHeaderBytes = 64 << 10(64 KiB)。

对应单元测试在 host_rpc_http_test.go 中通过 require.ErrorIs(t, err, ErrHTTPForwardFanoutDeferred) 断言错误身份,与基准的 errors.Is 校验方式一致。

设计文档给出的数据流:

plugin /plugin/httpForward toNodeId=-1
  -> App.HTTPForward
  -> ErrHTTPForwardFanoutDeferred

基准代码

基准位于 internal/usecase/plugin/benchmark_test.go,紧邻既有的 BenchmarkHTTPForward:

func BenchmarkHTTPForwardFanoutDeferred(b *testing.B) {
	app, err := NewApp(Options{Runtime: &recordingRuntime{}, Invoker: &recordingHTTPRouteInvoker{}, HTTPForwarder: &recordingHTTPForwarder{}})
	require.NoError(b, err)
	req := &pluginproto.ForwardHttpReq{
		PluginNo: "bench.plugin",
		ToNodeId: -1,
		Request: &pluginproto.HttpRequest{
			Method: http.MethodPost,
			Path:   "/fanout",
			Body:   []byte("fanout"),
		},
	}
	b.ReportAllocs()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		resp, err := app.HTTPForward(context.Background(), req, "bench.plugin")
		if !errors.Is(err, ErrHTTPForwardFanoutDeferred) {
			b.Fatalf("HTTPForward() error = %v, want ErrHTTPForwardFanoutDeferred", err)
		}
		if resp != nil {
			b.Fatalf("HTTPForward() response = %#v, want nil", resp)
		}
	}
}

要点:

  • ToNodeId: -1 精确命中 fanout 延迟分支;pluginproto 是 PDK 兼容的协议包(pkg/plugin/pluginproto 由仓库的 pkg/plugin 提供);
  • 通过 recordingRuntime、recordingHTTPRouteInvoker、recordingHTTPForwarder 三个 recording 桩注入端口,从代码层面证明该分支不会调用本地 Route、也不会调用远程 ForwardPluginHTTP(否则会缺少桩或产生副作用);
  • 每次迭代断言 errors.Is(err, ErrHTTPForwardFanoutDeferred) 且响应为 nil——既校验错误身份,也确认"无转发副作用"的契约;
  • 与既有 BenchmarkHTTPForward 的 local/remote 正路径形成对照:正路径测转发吞吐,此基准测延迟分支的常量时间成本。

计划要求给导入块补充 errors 包(用于 errors.Is),落地版本中已包含。

执行命令

go test ./internal/usecase/plugin -run '^$' -bench '^BenchmarkHTTPForwardFanoutDeferred$' -benchtime=1x

期望输出:PASS,且包含一条基准结果与分配数据。

验证与合入:把两条基线跑在一起

计划的任务三要求把两条基准合在一起冒烟,再跑包内完整测试,最后提交。两个命令可以直接照搬到当前仓库(把 internalv2/ 换成实际的 internal/):

go test ./internal/runtime/channelappend ./internal/usecase/plugin -run '^$' -bench 'Benchmark(SubmitLocalNoPersistRealtimeScoped|HTTPForwardFanoutDeferred)$' -benchtime=1x

期望:PASS,输出中同时出现两个基准名,且通过 b.ReportAllocs() 报告分配数据。

go test ./internal/runtime/channelappend ./internal/usecase/plugin -count=1

期望:PASS——确保新增的基准辅助类型与既有测试(例如 recipient_test.go 中的 TestNoPersistSyncOnceDispatchesRealtimeWithoutAppend、commit_test.go 中的 TestNoPersistRealtimeDoesNotEnqueuePersistAfter)共存无冲突。

计划的合入清单(以当前仓库路径表达):

提交信息建议沿用计划中的 test: add plugin benchmark baselines。

设计原则与边界(Non-Goals)

设计文档与本计划反复强调的边界,值得迁移期工程实践参考:

  • 零生产代码改动:两条基准全部落在 _test.go 文件内,直接复用既有测试端口与接收器;计划的架构说明明确 "No production code should change"。
  • 不做优化:本次只是把高风险的迁移边缘"钉"成可测量的基线,不做生产优化、不加指标、不跑黑盒场景。
  • 不设阈值门槛:基准基线用于人工对比与回归观察,本计划不引入基准阈值强制(benchmark threshold enforcement)。
  • 不做 e2e/集成基准:两条都是包内微基准。
  • 不实现 fanout:ErrHTTPForwardFanoutDeferred 明确声明阶段一不实现广播转发,后续集群级插件工作才可能落地该分支。
  • 不改 PDK/protobuf:pluginproto 保持兼容。

此外,从 realtime.go 可以看到一条重要的运行时契约:如果 deliveryEnqueuer == nil,实时投递会返回 ErrRealtimeDeliveryRequired——这说明基准中注入 benchmarkRealtimeDeliveryEnqueuer 是必须的,否则路径会失败而不是测量真实投递。这也是"用真实本地 authority 路径而非纯 helper"这一设计决策的落地证据。

小结

BenchmarkSubmitLocalNoPersistRealtimeScoped 与 BenchmarkHTTPForwardFanoutDeferred 两条基线,分别从"正向全链路"与"负向延迟分支"两个角度,把 internalv2 插件迁移中最容易被回归的两条边缘路径变成可重复执行、可对比、可报警的 Go 基准。阅读本文后,你可以:

  1. 直接用文中命令跑通两条基准的 1x 冒烟与完整包测试;
  2. 结合 prepare.go、realtime.go、recipient.go 理解 NoPersist 实时投递的准备、效应与收件人分发三段链路;
  3. 结合 host_rpc_http.go 与 types.go 理解 /plugin/httpForward toNodeId=-1 延迟分支的常量时间语义与契约;
  4. 在后续迁移工作中,用同样的"计划 + 设计 + 包内 _test.go 基准 + 冒烟/完整测试"模式为其他高风险路径建立基线。
登录后查看全文
WuKongIM