tokencostguard / docs /openhands-benchmark-plan.md
lixiaowww
CSP: allow huggingface.co frame-ancestors
249c849
|
Raw
History Blame Contribute Delete
17.4 kB
# OpenHands × SWE-bench 外部基准规划
**Status:** Draft(团队内部,可执行)
**Horizon:** 本周 PoC → 2 周子集报告 → 1–3 月案例与 Pro 证据链
**Related:** [`strategy-memo.md`](./strategy-memo.md), [`load-baseline.md`](./load-baseline.md), [`v1-optimized-messages-spec.md`](./v1-optimized-messages-spec.md), [`case-study-template.md`](./case-study-template.md)
---
## 1. 背景与问题陈述
公开 Agent 成本研究(见附录)指出三类与 TCG 产品叙事直接相关的现象:
| 现象 | 对 TCG 的含义 |
|------|----------------|
| **输入 token 主导**(多步 Agent 中 prompt ≫ completion) | Option A/B 的价值在「减输入、排布 cache」,而非只盯 completion |
| **逆缩放 / 能力–成本非单调** | Speculative routing 需用 outcome 校准,不能单靠模型档位 |
| **无效探索**(重复读文件、Explore→Fix 长环、低信息 ACK) | `analyzer.ts``duplicate_context``reflection_loop``chatter``infrastructure_pivot` 需在真实 coding agent 轨迹上验证 |
**OpenHands + SWE-bench Verified** 是业界可复现的 coding-agent 基准:有标准任务集、resolve 判定、公开 eval 管线。TCG 当前 `bench:baseline` 仅压测 **API 延迟与可用性**(合成 `LogEntry``/api/v1/optimize`),**不能**证明对真实 Agent 的 ROI。本规划补齐 **外部轨迹 → TCG API → 任务成功率 / 美元成本** 的闭环。
**非目标(本阶段):**
- 在 OpenHands 运行时内嵌 TCG 代理(透明 gateway,见 strategy-memo Option C)
- 宣称「TCG 提升 SWE-bench resolve%」——除非实验设计为 **post-flight 建议 + 人工/脚本应用** 且对照清晰
- 用单次 bench 报告替代 provider 账单对账
---
## 2. 目标与成功标准(可度量)
### 2.1 北极星
**固定 SWE-bench Verified 子集** 上,证明 TCG 能在 **不显著损害 resolve 率** 的前提下,降低 **每 resolved issue 的 input tokens 与 USD**,并形成可写入 case study 的 **帕累托证据**(saved vs success)。
### 2.2 分阶段成功标准
| 阶段 | 时间盒 | 成功标准(全部满足才算过线) |
|------|--------|------------------------------|
| **P0 PoC** | 本周 | ≥10 条 OpenHands 轨迹成功映射为 `LogEntry[]``POST /api/v1/optimize``mode=fast`)p95 < 2s;至少 1 条轨迹 `patterns``duplicate_context``context_bloat` |
| **P1 子集对照** | 2 周 | Verified **子集 N=30**(可复现 seed);3 组对照各跑通;输出 CSV:tokens、USD、success、latency、重复读文件率;帕累托图:saved% vs resolve% |
| **P2 产品证据** | 1–3 月 | ≥1 篇按 [`case-study-template.md`](./case-study-template.md) 填写的案例;Pro 组 `optimize/messages` 在 ≥5 条轨迹上 `cached_tokens_if_repeat` 估计 ≥ 基线 15%;`/api/v1/feedback` 回填率 ≥ 50% 于已分析 trace |
### 2.3 与 strategy-memo 对齐的 Kill / Go
- **Go:** 子集上 TCG **fast** 组 estimated savings ≥ 15%,且 resolve 率相对 Control 下降 **< 3 个百分点**(绝对值)
- **Kill / 改向:** savings 主要来自「建议未应用」的模拟图;或 resolve 下降 ≥ 5pp 且无法归因于模型路由误配
---
## 3. 实验设计
### 3.1 基准栈
```
OpenHands (固定 commit / Docker 镜像)
→ SWE-bench Verified 子集 (N=30, 分层抽样: 易/中/难各 ~10)
→ 轨迹导出 (JSONL / event log)
→ tcg-adapter (离线) → LogEntry[] + optional messages[]
→ TCG API (staging/prod)
→ 指标聚合 + feedback 回填
```
**子集选择原则:**
- 使用 [SWE-bench Verified](https://www.swebench.com/) 官方列表的子集,固定 `instance_id` 列表入仓(`artifacts/swe-subset-30.json`
- 记录 OpenHands 版本、默认 model、max iterations、temperature(写入 `artifacts/run-manifest.json`
### 3.2 对照组(四臂)
| 臂 ID | 名称 | Agent 侧 | TCG 侧 | 目的 |
|-------|------|----------|--------|------|
| **C0** | Control | 原生 OpenHands,不改 prompt | 无调用 | 成本/成功率基线 |
| **C1** | Post-flight fast | 同上(跑完后分析) | `POST /api/v1/optimize``mode=fast`**不**改运行时 | 验证 Option A:归因与 estimated savings |
| **C2** | Post-flight deep | 同上 | `optimize``mode=deep``auto` | 测量决策引擎 + 压缩路径延迟与建议差异 |
| **C3** | Pro layout | 下一 run 应用 `optimized_messages`(脚本合并) | `POST /api/v1/optimize/messages``provider=anthropic`(或 OpenHands 实际 provider) | 验证 Option B:cache-friendly layout |
**重要:** C1/C2 默认 **不改变** 第一次 OpenHands run(避免混淆因果)。C3 需要 **第二次 run**(同 instance、同 seed 策略),在 system/tool 块上应用 layout,仅变前缀结构。
**可选 C4(1–3 月):** 在 turn 边界调用 `optimize` 并应用 `optimized_logs` 建议——仅当 adapter 与 OpenHands 集成方案评审通过。
### 3.3 运行纪律
- 每个 instance 最多 2 次「计费 run」(C0/C1 一次;C3 第二次),防止 token 预算失控
- 所有 run 写入 `trace_id`(OpenHands session id)并在结束时 `POST /api/v1/feedback`
- 原始轨迹 **不入 Git**;仅存 `artifacts/`(gitignore)或加密对象存储
---
## 4. 指标定义
### 4.1 主指标
| 指标 | 定义 | 数据源 |
|------|------|--------|
| **Total tokens** | Σ(prompt_tokens + completion_tokens) | OpenHands log / provider usage |
| **Input / output split** | 分别汇总 prompt vs completion | 同上 |
| **USD** | `calcCost(model, prompt, completion)` 或 provider 账单 | TCG `pricing.ts` 与发票交叉抽查 |
| **Success (resolve)** | SWE-bench 官方 apply + tests pass | Eval harness 输出 |
| **Latency** | 单 issue wall-clock;TCG API p95 | OpenHands;`bench:baseline` 仅服务 API |
| **重复读文件率** | 含 `read`/`cat`/`view` 且 path 相同的 tool 调用 / 总 tool 调用 | adapter 从轨迹统计 |
| **Explore+Fix 占比** | agent 标签或 phase 含 explore/fix 的 token / 总 token | adapter 启发式(见 §6) |
| **TCG estimated savings %** | `optimization_plan.savings_percentage` | `/api/v1/optimize` 响应 |
| **Realized savings %** | (C0 USD − C3 USD) / C0 USD | 两次 run 对比;case study 必填 |
### 4.2 帕累托(saved vs success)
对每个 instance 画点:
- x:USD 或 input tokens 节省率(相对 C0)
- y:resolve 是否成功(0/1)或 partial score
**聚合:** 报告 **前沿曲线**——是否存在臂在 **success 不降** 的前提下 **saved 严格占优**;避免只报平均 savings(会被少数超大轨迹 skew)。
### 4.3 与 `analyzer.ts` pattern 的映射验收
| 论文/视频信号 | 期望触发的 pattern |
|---------------|-------------------|
| 重复读同一文件 | `duplicate_context` |
| Explore→Fix 长链 | `reflection_loop` / `agent_redundancy` |
| 短 ACK 回合 | `chatter` |
| prompt_tokens 高、input 文本短 | `context_bloat` |
| 多次 file tool | `infrastructure_pivot` |
验收:P1 结束时,子集中 **≥40%** 的 C1 轨迹至少命中上表 2 类 pattern(按 `patterns[].type` 去重)。
---
## 5. 与现有 `bench:baseline` / `bench:gate` 的关系
### 5.1 现状([`load-baseline.md`](./load-baseline.md))
- `npm run bench:baseline`:并发 POST `/api/v1/optimize`,合成 1 条 `LogEntry`,测 **success rate / avg / p95 latency**
- `npm run bench:gate`:对 `artifacts/bench-report.json` 做阈值门禁(默认 p95 ≤ 1200ms,success ≥ 99%)
- `.github/workflows/benchmark.yml`:CI 手动 workflow,**不**含 OpenHands
### 5.2 扩展点(规划,非本文件实现)
| 扩展 | 说明 | 优先级 |
|------|------|--------|
| `bench:openhands` | 读 `*.jsonl` → 批量 optimize → `artifacts/openhands-bench-report.json` | **Done** |
| `bench:openhands:gate` | p95 / success / pattern_hit_rate 门禁 | **Done** |
| `bench:gate` 增参 | 合成 baseline 仍用 `bench:gate`;OpenHands 用 `bench:openhands:gate` | P1 |
| 样本日志 | `scripts/fixtures/openhands-sample-trace.jsonl` + `openhands-sample-logs.json` | **Done** |
| CI | `.github/workflows/openhands-benchmark.yml`(fixtures demo,**不**阻塞主 CI) | **Done** |
**原则:** 现有 `bench:baseline` 继续作为 **API SLO 守门**;OpenHands 基准 **独立 artifact**,避免把合成延迟门禁误用于 ROI 宣称。
---
## 6. 轨迹 → TCG API 适配器(字段映射草图)
### 6.1 OpenHands / 通用事件 → `LogEntry`
| OpenHands / 轨迹字段(示意) | `LogEntry` 字段 | 规则 |
|-----------------------------|-----------------|------|
| `event.action` / `tool_name` | `step` | 取 `str_replace_editor.view``view_file` 等短名,max 50 |
| `agent.name` / `source` | `agent` | 如 `CodeActAgent``BrowsingAgent` |
| `llm_metrics.prompt_tokens` | `prompt_tokens` | 无则估:chars/4 并标注 `_estimated` |
| `llm_metrics.completion_tokens` | `completion_tokens` | 同上 |
| `model` / `litellm.model` | `model` | 规范化到 `MODEL_PRICES` 键 |
| 发给 LLM 的 messages 拼接或 `args.command` | `input` | 截断 8k 字符;PII 预脱敏 |
| `observation` / `message.content` | `output` | 截断 8k |
| `timestamp` | `timestamp` | Unix ms,可选 |
**顺序:** 按时间排序;每个 **LLM 调用** 一条 `LogEntry`;tool-only 步可合并进相邻 LLM 的 `input`/`output` 或跳过(adapter 配置 `merge_tool_steps: boolean`)。
### 6.2 Explore+Fix 占比(adapter 侧)
```
phase = classify(step, agent, input) // explore | fix | other
explore_fix_tokens = sum(tokens where phase in (explore, fix))
ratio = explore_fix_tokens / total_tokens
```
启发式:`edit`/`write`/`test` → fix;`view`/`find`/`grep` 且无 patch → explore。
### 6.3 重复读文件率
维护 `Set<canonical_path>` 于单次 issue run:
```
repeat_read_rate = (read_calls where path seen before) / (total read_calls)
```
path 规范化:resolve relative path、去重 symlink。
### 6.4 `POST /api/v1/optimize`
```json
{
"logs": [ "... LogEntry[] ..." ],
"mode": "fast",
"decision": { "mode": "recommend" }
}
```
响应关注点:`patterns[]``optimization_plan``trace_id`(响应头或 body)、`_decision``_guard`(若有)。
### 6.5 `POST /api/v1/optimize/messages`(C3)
从 OpenHands **最后一轮** 发给模型的 `messages[]` 导出:
```json
{
"messages": [ { "role": "system", "content": "..." }, ... ],
"provider": "anthropic",
"pinned_memory": []
}
```
应用方式:脚本将 `optimized_messages` 写回 OpenHands 配置或 prompt 模板,**仅**改 stable prefix 顺序与 `cache_control`,不改 task 指令语义。
### 6.6 `POST /api/v1/feedback`(HERMES)
| 轨迹字段 | `feedback` 字段 |
|----------|-----------------|
| `session_id` / `trace_id` | `trace_id` |
| SWE-bench resolved | `success` |
| tests pass fraction | `score` |
| `instance_id`, arm, savings | `metadata` |
在 optimize 响应后 **同一 trace_id** 提交,供 `HermesEvolver` 关联 decision audit 与 outcome。
---
## 7. 分阶段任务清单
### 7.1 本周(P0 / S 档)
- [x] 锁定 SWE-bench Verified 子集清单(30 ids)→ `artifacts/swe-subset-30.json`
- [x] **S 档** 10 issue 子集 → `artifacts/swe-subset-10.json`(4 易 / 3 中 / 3 难)
- [x] S 档 fixture 轨迹(10×C0/C1)+ `npm run openhands:s:fixtures` / `openhands:s:demo`
- [x] S 档执行手册 → [`openhands-s-tier-runbook.md`](./openhands-s-tier-runbook.md)
- [ ] 跑通 1 个 instance 的 **OpenHands 真跑** → JSONL 导出(需 OpenHands eval + LLM API key)
- [x] 实现 `tcg-adapter`(`src/benchmark/openhands-adapter.ts` + `npm run openhands:adapt`)
- [x] 脱敏样本轨迹 `scripts/fixtures/openhands-sample-trace.jsonl` + `openhands-sample-logs.json`
- [x] 对样本调用 `optimize`(fast)— 本地 `npm run dev` + `bench:openhands` 10/10 成功(p95≈3.7s,超 P0 2s 门槛;pattern 待真轨迹验证);staging 需 `BENCH_API_KEY`
- [x] run manifest 模板 → `artifacts/run-manifest.example.json`
- [x] 评估 token 档位(§8)草案 → [`openhands-token-budget.md`](./openhands-token-budget.md)(S 档用户已口头批准;正式签字待填)
- [x] `npm run bench:openhands` + [`openhands-benchmark-runbook.md`](./openhands-benchmark-runbook.md)
- [x] S 档 Go/Kill 离线演示 → `artifacts/openhands-p1-summary-s-tier.json`(`npm run openhands:s:demo`)
### 7.2 2 周(P1)
- [ ] 完成 C0/C1/C2 各 30 instances(可分批 10+10+10)— **需 OpenHands 真跑**
- [x] 统计 §4 主指标 + 帕累托:`npm run openhands:aggregate` → CSV + SVG
- [x] 重复读文件率、Explore+Fix、pattern 命中率(bench 报告 + aggregate summary)
- [x] `bench:openhands` 多臂(C0/C1/C2)、`SWE_RESULTS_FILE`、`SUBMIT_FEEDBACK`
- [x] P1 Go/Kill:`npm run openhands:p1:evaluate`;本地演示 `npm run openhands:p1:demo`
- [ ] 内部 30min 复盘:真跑 30 条后对照 §2.2
- [ ] 决定 C3 是否进入第二轮 run
### 7.3 1–3 月(P2)
- [ ] C3:`optimize/messages` 二跑子集(≥15 instances)
- [ ] 按 case study 模板发布 1 篇(可匿名)
- [ ] HERMES:feedback 回填链接 decision audit,检查 `successRate` 校准
- [ ] 评估 C4(inline 应用)技术评审
- [ ] 可选:对外博客「方法论」而非 raw 数据
- [ ] 将稳定 fixture 接入 `bench:baseline` 回归(合成 + 真实各 1)
---
## 8. 风险与成本预算
### 8.1 风险
| 风险 | 影响 | 缓解 |
|------|------|------|
| OpenHands run 成本超预期 | 预算击穿 | 子集化、固定 max iterations、先 10 条试点 |
| 轨迹不含 token 计数 | USD 不可信 | 标注 estimated;抽查 provider dashboard |
| Post-flight 无因果 | 高估 TCG 价值 | C3 二跑 + realized savings;文案区分 estimated vs realized |
| 日志含仓库路径/PII | 合规 | `sanitizeLogContent`、不入 Git、DPA 引用 [`data-processing-notice.md`](./data-processing-notice.md) |
| SWE-bench 环境 flaky | success 方差大 | 固定 Docker;每 instance 记录 flake retry |
| `optimize` deep 模式慢 | 阻塞批量 | P1 以 fast 为主;deep 抽 5 条样本 |
### 8.2 Token 消耗粗估档位(非精确报价)
假设:每 issue **平均 15–40 次 LLM 调用**,模型档 **$3–15 / M input tokens**(Claude/GPT-4 类)。
| 档位 | 规模 | 粗估 OpenHands LLM 成本 | TCG API 成本 |
|------|------|-------------------------|--------------|
| **S** | 10 issues × 1 run | 低三位数 USD | &lt; $5(fast optimize) |
| **M** | 30 issues × 3 臂(C0/C1/C2 各 1 run) | 中四位数 USD | &lt; $50 |
| **L** | 30 issues × 2 run(含 C3)+ deep 抽样 | 高四位数 USD | &lt; $200 |
**TCG 侧控费:** `mode=fast`、批量离线、staging quota、`BENCH_REQUESTS` 式限流;DeepSeek 压缩仅在 deep/auto 启用。
**决策门:** 超过 **M 档** 需书面批准;未达 P1 Go 标准不进入 L 档。
---
## 9. 与 HERMES、`/api/v1/feedback`、Pro 卖点的对齐
### 9.1 HERMES 闭环
1. `optimize` 产生 `trace_id` 与 decision audit(`source=optimize`
2. SWE-bench 判定后 `feedback` 写入 `trace_outcomes`
3. `HermesEvolver.analyzePerformance()``successRate` / `avgRoi` 校准策略(见 `src/domain/policy/hermes.ts`
**本基准贡献:** 提供 **高噪声、真实 coding** 的 outcome 分布,避免仅合成日志导致 `successRate` 虚高。
### 9.2 Pro(Option B)卖点
- **证据句:** 在 coding agent 长轨迹上,`optimize/messages` 将 stable system/tool 前缀前移并标注 `cache_control`,提升 **重复读文件场景** 下的 **cached input** 比例,且不改变 SWE-bench 任务文本。
- **不宣称:** TCG 自动修复 issue;或替代 OpenHands 规划器。
### 9.3 与 Beta Option A 的分工
- **免费层:** C1 `fast` 报告 + pattern 归因(投信任)
- **付费层:** C3 layout + case study 中的 realized metrics
---
## 10. 交付物
| 交付物 | 路径(建议) |
|--------|----------------|
| 子集清单 | `artifacts/swe-subset-30.json` |
| Run manifest | `artifacts/run-manifest.json` |
| 指标 CSV | `artifacts/openhands-metrics.csv` |
| 帕累托图 | `artifacts/figures/pareto-saved-vs-success.png` |
| Bench 报告 | `artifacts/openhands-bench-report.json` |
| Case study | `artifacts/case-studies/YYYY-MM-openhands-swe.md` |
---
## 11. 附录:参考链接
| 资源 | URL |
|------|-----|
| 视频(Agent 成本启示,输入主导 / 无效探索) | https://www.youtube.com/watch?v=dvWfeexfa1s |
| SWE-bench 官方 | https://www.swebench.com/ |
| SWE-bench Verified 说明 | https://www.swebench.com/verified.html |
| OpenHands 文档 | https://docs.all-hands.dev/ |
| OpenHands 评估 / benchmark 相关 | https://github.com/All-Hands-AI/OpenHands/tree/main/evaluation |
| Agent 成本与规模(arXiv,按视频引用核对具体篇目) | https://arxiv.org/search/?query=LLM+agent+token+cost&searchtype=all |
| TCG 内部:负载基准 | [`load-baseline.md`](./load-baseline.md) |
| TCG 内部:v1 Pro spec | [`v1-optimized-messages-spec.md`](./v1-optimized-messages-spec.md) |
---
**Next review:** P0 完成后 48h 内,或 P1 指标出齐后召开 Go/Kill 评审。
**Owner(待填):** 工程 ___ / 基准 ___ / 文案 ___