Skip to content

perf(ai-statistics): sort existing tool call indexes - #5435

Open
zhihao-yuan wants to merge 3 commits into
higress-group:mainfrom
zhihao-yuan:fix/ai-statistics-sparse-index
Open

zhihao-yuan wants to merge 3 commits into
higress-group:mainfrom
zhihao-yuan:fix/ai-statistics-sparse-index

Conversation

@zhihao-yuan

@zhihao-yuan zhihao-yuan commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

I. Summary

工具调用按实际存在的非负索引升序返回,避免扫描到最大索引。单工具直接返回,连续索引保留一次结果分配;稀疏索引用 slices.Sort 排序。回归直接检查连续、乱序、稀疏输入的完整工具信息。

II. Related issue

Fixes #5425

Design: #5474;需求:SPEC-5425001。

III. Change type

  • Bug fix
  • Feature or enhancement
  • Documentation or configuration only
  • Refactoring, tests, or maintenance

IV. Agent participation and issue-spec gate

  • No agent participation: This PR is human-only.

  • Trivial agent-use exception: Agent use was limited to spelling, punctuation, whitespace, or formatting with no substantive choice or behavioral effect.

  • Verified maintainer/administrator exception: Material participation occurred and the canonical repository role and PR author were verified.

  • Material agent participation: An AI or coding agent materially participated in analysis, design, implementation, testing, or PR preparation.

  • Before implementation began: A Higress maintainer had approved the Proposal and Design Issues, and authorized implementation TASKs linked the work to the applicable SPECs.

  • Before verification began: The Design contained a concrete Verification Plan.

  • Before requesting maintainer review or acceptance: Applicable implementation and verification TASKs were done with exact commands, results, evidence links, and hashes.

  • Complete: all three timed obligations above were satisfied.

  • Noncompliant: one or more obligations were not satisfied; explain below.

  • Verified exception: material participation used the verified-maintainer/administrator exception.

  • N/A because the PR is human-only or qualifies for the trivial exception.

Proposal 已获批准,SPEC 和 Design 已补交,待 Design 确认后登记 TASK。实现和既有验证早于本次补交,相关时间项保持未勾选。

Trivial-exception explanation: N/A,包含实质代码修改。

Verified maintainer/administrator exception evidence: N/A,未使用此例外;该项身份、角色、作者匹配、令牌覆盖检查及例外理由字段均不适用。

Approved Proposal Issue URL: #5425 (已批准)

Approved Design Issue URL: #5474 (已提交,待确认)

Maintainer approval link(s): Proposal:批准评论;Design:待确认。

Authorized implementation TASK link(s): 待 Design 确认后登记;当前实现已提交在本 PR。

Verification Plan and verification TASK/evidence link(s): Design 中的验证安排;已有验证记录;验证 TASK 待 Design 确认后登记。

V. Testing and verification

在插件模块目录,Go 1.24.4:

GOTOOLCHAIN=local GOWORK=off go test -mod=readonly -run '/go$' -timeout=2m ./...
GOTOOLCHAIN=local GOWORK=off go test -mod=readonly -run '^TestToolCall(Order|MaxIndex)$' -count=1 -v
GOTOOLCHAIN=local GOWORK=off GOOS=wasip1 GOARCH=wasm go build -mod=readonly -buildvcs=false -trimpath -buildmode=c-shared -o plugin.wasm .

本次验证记录包含复跑脚本、配置、输入输出、原始日志和校验和。另提供独立压缩包与 SHA-256,可下载留存。

  • 原版:c4c537f37175befc375e65ba059e8df477dc52a4
  • 修复:50932c40b7b616c3ce464a2e1d53ae41c4b5c449
  • 网关:higress-registry.cn-hangzhou.cr.aliyuncs.com/higress/gateway@sha256:a82de493902012ce6b555ecb2244156f3c73824474d67549144a7efa334d0299
  • 环境:macOS/amd64,Go 1.24.4;真实 Envoy/V8,单 worker、1 CPU、768 MiB、fail_open=false;固定本地 HTTP 上游,没有调用真实模型。
  • 原版和修复版均按上述完整源码 SHA 重建,哈希与受测模块一致;修复提交后还做了逐字节比较。具体 Wasm SHA-256 见记录中的 manifest.json。

Go 原生/宿主套件及直接回归通过。

12 月 1 日在 b8f4bcd796df84e8ea419b6a55c9c943198ceacf 补充 single_negative(单条负索引)回归,断言返回空的非 nil 切片。Go 1.24.4 下直接回归和 Go 宿主套件通过,getToolCallsFromBuffer 的语句覆盖率达到 100%。该提交重建出的 Wasm 与下述网关受测模块逐字节相同。

11 月 30 日真实网关 72 次 = 原版 36 + 修复版 36,覆盖单工具索引 0/1/10000000,以及多工具 0/1/2、2/0/1、0/2/10000000。全部 HTTP 200;响应正文逐字节一致,日志中的顺序、ID、类型、函数名和参数正确。Wasm crash/rebuild/fail-open skip 为 0,清理通过。

原版/修复版原生辅助函数基准串行运行,GOMAXPROCS=1、-benchtime=200ms -count=5 -cpu=1,以下为中位数(ns/op):

索引 原版 修复 allocs/op 原版 → 修复
单工具 0 167.8 125.4 1 → 1
单工具 1 156.4 129.2 1 → 1
单工具 10000000 55,209,394 122.0 1 → 1
多工具 0/1/2 298.8 148.9 1 → 1
多工具 0/2/10000000 64,743,995 323.9 1 → 2

以上耗时和分配数字均以 Go 1.24.4 实测为准;不同 Go 版本的逃逸分析和分配结果可能不同。

原始五次样本、B/op 和复跑命令均在验证记录中。稀疏三工具的额外索引切片使分配从 224 增至 248 B/op;普通单工具和连续索引不增加分配。

VI. Special notes for reviewers

高索引属于合成边界输入,不声称常见模型会这样返回。原生短基准受宿主调度影响,仅用于检查辅助函数的扫描和分配行为,不外推生产 QPS、CPU 或计费成本,也未测试同 worker 并发影响。

此前整个 SDK Wazero 套件超时,没有将其列为通过项;本轮 Go 模式和真实 Envoy/V8 验证分别通过。不相关注释已恢复,排序使用 slices.Sort。

VII. AI coding disclosure

Tool(s) used: AI 编码助手,以及 Git、Go/Rust 和真实网关测试工具。

Prompts or instructions

修复关联 issue,保持官方风格和已有兼容性,补回归与真实网关原版/修复对照;一项问题对应一个 PR。

AI-assisted work summary

参与实现、回归和验证整理。改动及范围见 I,测试结果和未通过项见 V/VI;审批缺项见 IV。

Issue-spec managed closing links:
Closes #5425
Closes #5474

Signed-off-by: zhihao-yuan <341868981+zhihao-yuan@users.noreply.github.com>
@codecov-commenter

codecov-commenter commented Nov 25, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (main@c4c537f). Learn more about missing BASE report.
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #5435   +/-   ##
=======================================
  Coverage        ?   55.21%           
=======================================
  Files           ?       93           
  Lines           ?    14924           
  Branches        ?        0           
=======================================
  Hits            ?     8240           
  Misses          ?     6124           
  Partials        ?      560           
Flag Coverage Δ
wasm-go-plugin-ai-statistics 90.22% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
plugins/wasm-go/extensions/ai-statistics/main.go 89.34% <100.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zhihao-yuan

zhihao-yuan commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

@johnlanni @jizhuozhi 辛苦帮忙看下,对应 #5425(按最大工具索引逐个扫描空位的性能问题),改动带验证,谢谢。


@johnlanni @jizhuozhi Thank you for your help. It corresponds to #5425 (performance issue of scanning vacancies one by one according to the maximum tool index). The changes will be verified. Thank you.

func BenchmarkToolCallSparseOrder(b *testing.B) {
for _, index := range []int{0, 10000000} {
buffer := &StreamingToolCallsBuffer{ToolCalls: map[int]*ToolCall{index: {Index: index}}}
b.Run(map[bool]string{true: "sparse", false: "dense"}[index > 0], func(b *testing.B) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Benchmark 命名与语义不符,且无法体现本次修复的收益

修复之后,index=0 与 index=10000000 的工作量已经完全相同(都与索引值无关),但子基准仍命名为 dense / sparse,容易让人误以为两者存在数量级差异。

另外 map[bool]string{true: "sparse", false: "dense"}[index > 0] 这种取巧写法可读性也偏弱。

建议:

  1. 直接按索引值命名,例如 b.Run(fmt.Sprintf("index-%d", index), ...);
  2. 补充「修复前 vs 修复后」的对照基准,或至少在 PR 描述中给出 Go 层的 before/after 数据 —— issue Proposal: ai-statistics 避免按最大工具索引逐个扫描空位 || Proposal: ai-statistics avoids scanning gaps one by one by maximum tool index #5425 明确要求「确认常见小索引不会因额外排序、分配而退化」,目前 PR 描述只有网关级中位耗时,缺少这一层证据。

)

func TestToolCallSparseOrder(t *testing.T) {
buffer := &StreamingToolCallsBuffer{ToolCalls: map[int]*ToolCall{10000000: {Index: 10000000}, 2: {Index: 2}, 0: {Index: 0}, -1: {Index: -1}}}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 回归覆盖未完全对齐 issue #5425 提出的范围

issue 明确列出的回归点是:空 buffer、常见连续索引、稀疏索引、多个工具、负索引的现有处理方式。

当前用例覆盖了稀疏索引、负索引(-1 被跳过)、nil buffer 与空 map;但「多个工具 / 常见连续索引」只由既有的 main_test.go 间接覆盖,没有针对 getToolCallsFromBuffer 的直接断言。

建议补一个多工具连续索引的用例,并显式断言「输出顺序 == index 升序,且与 map 的迭代顺序无关」——后者正是本次改动的核心契约(旧实现依赖 maxIndex 扫描,新实现改为显式排序,契约需要被测试钉住)。

// Handles both raw JSON and SSE "data: " prefixed chunks, including multi-event
// streaming buffers.
// 2. HTTP status code >= 400 as fallback when body is empty.
// 1. Response body contains non-null "error" field at root level (OpenAI/Anthropic format).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 夹带了与本次改动无关的 gofmt 注释重排

isErrorResponse 的这段注释被 gofmt 重排,与 perf 改动没有任何关联。plugins/wasm-go/extensions/ai-statistics 是独立 Go module,不在仓库根 module 的 golangci-lint 覆盖范围内,因此这不是 CI 强制项。

建议还原这一段,让 diff 只保留 getToolCallsFromBuffer 的改动,降低 review 噪音和后续冲突风险。

indexes = append(indexes, index)
}
}
sort.Ints(indexes)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 可以考虑 slices.Sort

本模块 go.mod 声明 go 1.24.1,slices.Sort 比 sort.Ints 更现代,且避免了 sort.Interface 的接口调用开销。当前典型场景只有 1~3 个元素,实际收益极小,仅作建议,不阻塞。

Signed-off-by: zhihao-yuan <341868981+zhihao-yuan@users.noreply.github.com>
@zhihao-yuan

zhihao-yuan commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

@CH3CHO 感谢建议,已在 50932c4 调整:基准直接按索引命名,去掉 map[bool]string;补了连续、乱序多工具的直接断言,检查顺序及完整工具信息;无关注释恢复原样,排序也换成 slices.Sort。

补跑原版/修复版基准后,加了单工具和连续索引的处理,常见输入仍是一次分配。五次样本中位数见正文;稀疏三工具会多一个索引切片,分配从 224 到 248 B/op,也一并列明了。真实网关另跑了 72 次,正文、工具顺序和参数均一致。

本次验证记录附原始样本和复跑方法。麻烦您再看下,谢谢!


@CH3CHO Thanks for the suggestion, it has been adjusted in 50932c4: the benchmark is directly named according to the index, and the map[bool]string is removed; the direct assertion of continuous and disordered multi-tools is added, the order and complete tool information are checked; the irrelevant comments are restored to the original, and the sorting is replaced by slices.Sort.

After re-running the original/repaired version of the benchmark, single tool and continuous index processing were added, and common inputs are still allocated once. The five-time sample median is shown in the text; the sparse three tool will have one more index slice, and the allocation will be from 224 to 248 B/op, which is also listed. The real gateway was run another 72 times, and the text, tool sequence, and parameters were consistent.

This verification record Attached is the original sample and rerun method. Please take a look again, thank you!

return []ToolCall{*tc}
}
}
return []ToolCall{}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 单条负索引分支仍未覆盖 —— codecov 报的 "1 line missing" 就是这一行

return []ToolCall{} 的触发条件是:buffer 里恰好只有 1 个工具调用,且它的 index 为负。

当前测试表里 negative_only 用的是 {-1, -2} 两个条目,走的是稀疏路径,覆盖不到这条单条快路径;TestToolCallMaxIndex 用的是正的极大 index,同样覆盖不到。

建议在表里补一行即可:

{"single_negative", []int{-1}, []int{}},

want 写成 []int{}(非 nil)时会被构造成空非 nil 切片,与 []ToolCall{} 的 reflect.DeepEqual 一致,不会误判。

补完后 getToolCallsFromBuffer 的语句覆盖即可补齐,codecov 的 patch coverage 也会随之回到 100%。

return result
}
result = result[:0]
indexes := make([]int, 0, len(buffer.ToolCalls))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 分配数字与 Go 版本相关,建议在正文标注口径

正文里「稀疏三工具 224 → 248 B/op、1 → 2 allocs」是 Go 1.24.4 上的实测值。对本仓库锁定的工具链(go.mod toolchain go1.24.4、CI 用 Go 1.24.0)这个数字是准确的,不是错误。

但在 Go 1.26.x 上跑同一个基准,稀疏三工具是 224 B/op、1 alloc/op,与连续三工具完全相同 —— 逃逸分析输出 make([]int, 0, len(buffer.ToolCalls)) does not escape,新版本把这个索引切片栈分配了。

也就是说这「多一次分配」是工具链实现细节,而不是本仓库工具链下的稳定契约。建议正文补一句「分配数字以 go1.24.4 为准」,避免复现者用较新 Go 时得到相反结论而误判为数据不一致。

Signed-off-by: zhihao-yuan <341868981+zhihao-yuan@users.noreply.github.com>
@zhihao-yuan

zhihao-yuan commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

@CH3CHO 已在 b8f4bcd 补上 single_negative,断言返回空的非 nil 切片。本地直接回归和 Go 宿主套件通过,getToolCallsFromBuffer 的语句覆盖率补到了 100%。

正文也注明了耗时、分配数字以 Go 1.24.4 实测为准,不同 Go 版本的结果可能不同。麻烦再看下,谢谢!


@CH3CHO has added single_negative in b8f4bcd, asserting that an empty non-nil slice is returned. Local direct regression and Go host suite passed, and the statement coverage of getToolCallsFromBuffer reached 100%.

The text also states that the time consumption and allocation figures are subject to actual measurements on Go 1.24.4. The results of different Go versions may be different. Please take a look again, thank you!

@zhihao-yuan

zhihao-yuan commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

@CH3CHO 已补上 SPEC-5425001 和 Design #5474,改法、具体测试命令、固定版本证据和清理记录都整理进去了,PR 的批准状态和链接也已同步更新。

实现先于 Design 这一点按实际情况保留,相关时间项仍未勾选。麻烦确认下设计,确认后我再补实现、验证 TASK,谢谢!


@CH3CHO has added SPEC-5425001 and Design #5474. The revised method, specific test commands, fixed version evidence and cleanup records have been compiled. The approval status and link of the PR have also been updated simultaneously.

The fact that implementation precedes design is retained according to the actual situation, and the relevant time items are still unchecked. Please confirm the design. After confirmation, I will implement and verify the TASK. Thank you!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants