Skip to content

Architecture debt: cross-cutting concerns lack a unified chokepoint across the 5 wire exits (plugin.ts dual paths, remembered-snapshot pattern) #588

Closed

Description

@ranxianglei

问题

Proxy 有 5 条 wire 出口,而横切关注点(usage / abort / timer / role 兼容)各自需要在每条出口过一遍,形成 N×M touchpoint 矩阵——漏掉一格就是一类 bug。近期 bug 史几乎全是这个症状:

Issue 关注点 漏掉的格子
#411 timer 生命周期 侧请求/abort 路径的 timer 未清理
#546 side-request 判定 预算收缩后误判主请求
#408 usage 回填 SSE/JSON/plugin 各出口数字不一
#387 status/nudge remembered snapshot 过期
#552 role 兼容 fetch-util timer race(同 #411 类)

根因(刻意取舍,不是烂代码)

核心约束:raw passthrough 保字节稳定 = 保上游 prefix cache(#377 教训:头部 system 逐字节稳定 SGLang 才命中)。"优雅"的全量解析重建会杀缓存 + 踩严格后端。所以修复被迫走流式逐块原地补丁,天然散在多出口。

已收敛的部分

剩余债务

  1. src/plugin.ts SSE/JSON 双路径(代理压缩不上报改写量,宿主上下文会计塌缩至 ~0(omps recordAnchoredHistoryRewrite 零调用);且持久化 lastInputTokens 恢复无钳制,旧版负值升级后复活 #408 中 +91 行)—— plugin 透传没有收编进 loop 体系,是最大的重复面
  2. remembered-snapshot vs live-state 模式(acp_status 缝合报告:Compressible ranges/Nudge 读冻结的 ctx.nudge,压缩成功后旧区间与新块同框并存 #387/sessions 存储三重膨胀:叶块 blockContents 逐字节重复 50%、零 GC、每次启动两遍全量同步解析(实测 387MB/+60MB 每天/2s 起步) #401 都栽在这):prepare 时冻结的快照与后续 state 变更不同步

建议方向(非紧急,收益递减时停手)

  • 把 plugin 透传收编进 src/loop/ 适配器体系,消灭 plugin.ts 双路径
  • 每个横切关注点建"出口枚举测试矩阵"(tests/host-usage-backfill.test.ts 的 19 测试协议矩阵就是模板):新增出口时测试强制补格
  • 可选:exit registry 抽象——每个关注点按出口注册 handler,新出口编译期可见漏注册

明确的非目标

全量解析重建(杀 prefix cache、破严格后端兼容)——本 issue 只记录债务与渐进收敛路线,不要求大重构。

Activity

  1. ranxianglei commented on Sep 6, 2026

    @ranxianglei
    OwnerAuthor

    🤖 ework agent · qwen3.8-27b

    [bot] 🏷 ## 审核结论:issue 判断成立,已在当前 master(e8ef2cb,含 PR #425)逐项核验

    查重:全仓库 issue/PR(含已关闭)检索 wire exit / chokepoint / passthrough absorb / snapshot staleness / test matrix 均无重复项,#588 是此架构债务的唯一跟踪条目。引用的 #408/#387/#411/#546/#552/#401/#377 全部 closed。

    一、出口精确清单(比 issue 的"5 条"更细:5 条承载出口 + 1 条裸中继)

    forward()(src/server.ts:2833)内的响应路径:

    # 出口 位置
    E1 compress-loop 流式(proxy mode SSE) src/server.ts:3369-3443 → runCompressLoop + 3 个 adapter
    E2 compress-loop JSON(proxy mode 非流式) src/server.ts:3444-3518
    E3 passthrough chat/anthropic SSE src/plugin.ts:607 pipePluginChatWithStrip
    E4 passthrough responses SSE src/plugin.ts:862 pipePluginResponsesWithStrip
    E5 passthrough JSON src/plugin.ts:1032 pipePluginJson
    E0 裸字节中继 src/server.ts:3631 pipeThrough(设计上零关注点,正确)

    新发现 ①:E3/E4/E5 不只服务 plugin mode——proxy mode 的非注入分支(title-gen 排除、ACP_NO_INJECT_TOOL、classifier bypass、native-compact 轮)也复用这三条 pipe(src/server.ts:3307-3359,session=undefined)。所以剩余债务 1 的真实规模是 6 条 wire 出口的共享实现,不只是"plugin 透传"。且 plugin.ts 实际是三路径(SSE×2 + JSON×1,~490 行),不是 issue 写的双路径——重复面比我预期还大一格:SSE framing 循环 ×2、usage sniff/settle ×3、tag-echo 状态机 ×3、#408 backfill 补丁 ×3、weak-overflow note ×2、abort-safe settle ×3。已共享的只有 rebuildEvent、usageFromSseEvent、applyUsageSample 和 tag-echo-filter 原语。

    新发现 ②:矩阵漏洞不是理论风险,有现成事故标本——#425 的 ac2b75e:credit 原本只在 prepareAnthropic arm,prepareOpenai/prepareResponses 漏了,导致 E1/E2 的 backfill 对 openai/responses 两个协议静默失效(credit 恒 0,所有补丁代码都在跑但什么都不改)。这正是"漏一格 = 一类 bug",而且是最阴险的形态:不报错,只是数字不对。

    二、各关注点当前矩阵状态(核验后)

    关注点 状态 证据
    usage(#408) ✅ 数值语义已收敛 backfillHostUsage/promptInputTotal/usageTotals(src/util.ts:64-140),5 出口全是薄壳调用(loop/core.ts:169,177,363;server.ts:3477,3498;plugin.ts:570,797,958,1077)。但**"在哪打补丁、何时打"的决策逻辑仍是每出口一份**——#425 arm-gap 就漏在这一层
    timer(#411/#552) ⚠️ 半收敛 创建侧收敛于 src/fetch-util.ts ✓;但清理侧在 forward() 里是 4 层嵌套 finally(server.ts:3270 / 3283 / 3436 / 3512 / 3520 共 5 处 clearUpstreamTimer()),靠注释维持"为什么不能合并"的知识。新增出口必须记得加自己的 finally——和 usage 同构的债务,只是格子小
    tag-echo strip(#206/#460) ⚠️ 原语共享、编排重复 原语在 src/loop/tag-echo-filter.ts ✓;但流式编排(per-field filter map、tail flush、合成 tail 事件、rebuild)在 E3/E4 各写一遍,JSON 侧又在 rewrite*JsonResponse 第三遍
    role 兼容(#552) ✅ 请求侧,不在出口矩阵内 rewrite 发生在 prepare 阶段,与出口无关——issue 表格里把它列进 N 维其实高估了矩阵宽度,真实 N=3(usage/timer/tag-echo)+ abort-settle
    remembered-snapshot(#387) ⚠️ 事故格已补,结构风险仍在 PR #397 后 status/nudge 全部 live 重算(plugin.ts:388-409 注释、acp_status live-state)✓。handlePluginTool 仍对 mem.processed 快照执行(plugin.ts:489-490)——我审过,这是有意语义而非 bug:工具 ref(mNNNNN)必须解析到模型当时看到的视图,事后 state 变更不应改写 ref 空间。真正的残留是:没有任何机制强制消费者声明"我要 live 还是 snapshot",下一个读 remembered 的人还会踩一次 #387

    三、方向建议(明确推荐,非选择题)

    P0 — 出口枚举测试矩阵扩到 abort/settle 与 tag-echo(建议做,纯测试)
    模板就是 tests/host-usage-backfill.test.ts(19 测试覆盖 5 出口×backfill,已核验)。补两个矩阵:(a) mid-stream 客户端断开 → 每出口断言 usage settle + timer clear + stream 干净终止(#411/#552 全是 abort 路径漏格,现有 issue411-abort-usage.test.ts 只盖了部分格);(b) tag-echo 注入 → 每出口断言剥离+tail 不丢字。零管线改动,直接给"漏格"上保险,是三个方向里唯一无回归风险的。

    P1 — 抽共享 SSE event pump + 关注点 hook(有时间再做,单独分支)
    从 E3/E4 抽出 framing 层(\n\n 切分、data: 提取、parse 容错、write 背压,~80 行重复),出口变成声明 {onEvent, onSettle, onAbort} hook。不建议按 issue 原话"收编进 src/loop/ 适配器体系":loop adapter 的接口是为 compress-loop 的往返语义设计的(tool-call buffering、marker emit、多轮重试),passthrough 必须 verbatim——强行塞进同一接口是过度抽象,会威胁"字节稳定"这个本 issue 自己列的非目标。轻量 pump 应该放在 adapter 层之下,两者共用而不互相污染。

    P2 — exit registry 编译期穷尽检查(建议停手)
    出口集合已稳定(5+E0),可预见的第 6 条出口不存在;TS 做注册穷尽需要引入 ExitId discriminated union,收益递减——符合 issue 自己"收益递减时停手"的原则。如果哪天真出现新出口,P1 的 pump 已经让"漏 hook"变成显式缺省而不是复制粘贴遗漏。

    四、请拍板

    按 AGENTS.md 功能类 triage,多方案先讨论再动手。我的推荐:P0 立即做(测试-only PR,低风险快合);P1 排后;P2 不做。 你确认范围后我就开工——回复"P0"或"P0+P1"即可。

  2. ranxianglei commented on Sep 6, 2026

    @ranxianglei
    OwnerAuthor

    🤖 ework agent · qwen3.8-27b

    [bot] 🏷 更正上一条的 timer 计数(本 issue 的主题就是精确数格子,不能含糊):forward() 内 clearUpstreamTimer() 实际共 6 处——成功区域 4 个 finally(src/server.ts:3271 plugin 分支、3437 流式 rewriter、3513 JSON、3526 最外层 safety net)+ 非 2xx 错误路径 1 处(3223)+ 无 body 早退 1 处(3230)。我上条把 3283(那是外层 try { 的起始行,不是清理点)误列入。结论不变且更强:清理点 = 出口路径数 × 1,每加一条路径必须记得放一个,这正是 N×M 债务在 timer 维上的形态。

  3. ranxianglei commented on Sep 7, 2026

    @ranxianglei
    OwnerAuthor

    Reviewed against current master (56d0484, after the #575/#571/#572/#558 merge wave). The debt inventory still reads accurate, with one small addition and one positive signal.

    Verified on master

    Remaining debt 1 — plugin.ts dual/triple path: confirmed, still the largest duplicate surface. pipePluginChatWithStrip ≈ 255 lines, pipePluginResponsesWithStrip ≈ 170 lines, pipePluginJson separate (1113 lines total). Churn is the tell: 19 commits since 2026-09-01 touched plugin.ts — #408/#411/#387/#389/#532 all had to patch the paths in parallel. That is the N×M matrix cost, measured.

    Remaining debt 2 — remembered-snapshot: the RememberedMessages map is still prepare-time frozen; #387/#389 mitigations (recompute nudge/status from live state under the session lock, src/plugin.ts:386-388, :494-495) are patches on top, not a removal of the pattern.

    New cell since the issue was filed

    #571 added emitPreflightError in src/stream-error.ts — a second per-protocol emitter next to emitStreamError (openai inline error+[DONE] / anthropic+responses event: error). It lives in the right module, but the error-delivery concern now has two hand-rolled variants instead of one. If a future protocol or exit is added, both need touching. Worth folding into one emitter with a reason parameter when next touched.

    Positive signal: the convergence direction held

    None of the last six merged fix PRs added a scattered cell — every new cross-cutting concern went through a single chokepoint: #572 confirmed/speculative window channels → src/weak-overflow.ts resolvers (one read site in server.ts); #558 char-upper-bound sizing → estimateCoreMessagesUpper in src/preflight.ts shared by trigger/nudge/preflight; usage stayed on backfillHostUsage. The rule "new concern = new module + thin shells at exits" is being followed in practice.

    Suggested next step (cheapest, no design change)

    The exit-enumeration test matrix is the only item actionable without a design change: extend the tests/host-usage-backfill.test.ts 19-test protocol-matrix pattern to (a) error delivery (SSE per protocol × JSON × post-early-commit in-band) and (b) abort propagation across the 5 exits. That converts "漏掉一格就是一类 bug" into a compile/test-time failure for future exits. The plugin.ts fold-in and the snapshot-pattern removal both change design and stay deferred until a bug forces them, per the issue's own diminishing-returns guidance.

  4. ranxianglei commented on Sep 7, 2026

    @ranxianglei
    OwnerAuthor

    🤖 ework agent · qwen3.8-27b

    [bot] 🏷 收到,按你圈定的范围执行:只加测试矩阵,不动设计。

    • (a) 错误投递矩阵:单元层覆盖 3 协议 × 2 emitter(emitStreamError / emitPreflightError,含客户端已断连时 write 抛错的健壮性),集成层补 preflight-hold.test.ts 没盖的格子——openai in-band preflight error 形状、非流式 early-commit 后的 JSON 错误体、early-commit 后上游 4xx(流式 → emitStreamError / 非流式 → verbatim body under 200)。
    • (b) abort 传播矩阵:数据驱动枚举 E1–E5 + raw relay 六个出口 × 客户端中途断开,统一断言 usage 落账(可断言时)/ _liveUpstreamTimersForTest() === 0 / 无裸 AbortError error 日志 / 断开后服务仍健康。其中 E1(compress-loop 流式)是现有 客户端取消 = 无主 AbortError ×260/天 + 已计费 usage 丢弃(lastInputTokens 冻结)+ 透传路径漏 10min timer(无 finally) #411 测试没覆盖的格子,会重点加。
    • emitPreflightError 与 emitStreamError 合并成单 emitter + reason 参数:按你的"下次动它时再折"留待将来,本次不碰。

    两个新测试文件,零 src 改动。完成后带 PR 链接回复。

  5. ranxianglei commented on Sep 7, 2026

    @ranxianglei
    OwnerAuthor

    补丁层已交付

    彻底方案(提案,供讨论;均未实施)

    目标:把 N×M touchpoint 收敛为「一条字节中继核心 + 每出口一个 adapter + 每关注点一个横切模块」,同时不破坏 raw passthrough 的字节稳定(prefix cache #377 红线)。

    1. plugin 透传收编进 src/loop/:三个 pipe(pipePluginChatWithStrip/pipePluginResponsesWithStrip/pipePluginJson)与 proxy 侧的差异只有三点——不重建消息体、tag-echo 过滤、usage 嗅探。把这三点抽成可组合的 stream transform(tagEchoFilter()、usageSniffer(protocol)),plugin 管道变成 byteRelay + transforms 的薄壳,与 proxy 路径共享同一套 transform。预计 plugin.ts 1113 行可减一半以上,且 代理压缩不上报改写量,宿主上下文会计塌缩至 ~0(omps recordAnchoredHistoryRewrite 零调用);且持久化 lastInputTokens 恢复无钳制,旧版负值升级后复活 #408/客户端取消 = 无主 AbortError ×260/天 + 已计费 usage 丢弃(lastInputTokens 冻结)+ 透传路径漏 10min timer(无 finally) #411 类修复从“改 N 处”变“改 1 处”。
    2. 错误发射器合一:emitStreamError + emitPreflightError → 单一 emitWireError(res, protocol, { reason, stage }),stage 决定 openai 是 error delta 还是 top-level error。本次矩阵测试已把两种形态都钉死,合并时契约不丢。
    3. remembered-snapshot → live-state:快照只保留不可变的 original;processed/nudge 在会话锁内使用时重算(acp_status 缝合报告:Compressible ranges/Nudge 读冻结的 ctx.nudge,压缩成功后旧区间与新块同框并存 #387/compress 批量门报错 "a prior compress renumbered the remaining refs" 为事实性错误——内核不存在任何 ref 重编号(首压会话即被谎称有前科) #389 的补丁模式转正为唯一模式),消除快照过期类 bug 的整类来源。
    4. 注册表升级为真接口(可选,收益最大也最重):WireExit 接口 = { usage, error, abort } 三个 hook 的实现;exit-matrix.ts 从纯数据变成该接口的 type-level 证明(satisfies Record<WireExitId, WireExit>),漏 hook 从测试失败升格为编译失败。

    顺序建议:2(最小、零风险)→ 1(最大收益)→ 3 → 4。每步独立成 PR、以现有矩阵测试做护栏。全部满足 issue 的非目标约束:不做全量解析重建,字节中继保持逐块原地补丁。

  6. added a commit that references this issue on Sep 7, 2026
  7. ranxianglei commented on Sep 7, 2026

    @ranxianglei
    OwnerAuthor

    🤖 ework agent · qwen3.8-27b

    先更正:E0/raw-relay 无 timer 泄漏

    之前说的「E0 泄漏调查中」是我的测量方法误报,更正记录:

    • 采样探针(t+0 与 t+600 双采样):自然完成 timers=0@t+0 & 0@t+600;客户端中断 timers=1@t+0 → 0@t+600。是有界的传播窗口(undici 把本地 cancel 送达 body stream 需要时间),自愈,不是泄漏。最初只采了 t+0 单点,被误导。
    • 机制:src/server.ts:3519-3523 的外层 try 包住所有 body-consuming 路径,:3760-3767 的 finally(客户端取消 = 无主 AbortError ×260/天 + 已计费 usage 丢弃(lastInputTokens 冻结)+ 透传路径漏 10min timer(无 finally) #411 安全网)注释明确「must sit at the very end so clearing never happens while a live stream still needs the external-abort listener」——包括非 rewriter relay 在内的所有出口都覆盖。无需服务端改动。
    • 教训已固化进测试:storm 断言必须轮询两个可观测量(proxy 侧 timer 收敛 + 上游 socket close 到达),不能同步断言——同步断言恰好会 race 这个窗口。

    补格 PR:#612

    逐格核对 #608(把 coveredBy 引用的每个文件都读完),确认 5 个真·未覆盖格子,tests/wire-exit-gap-cells.test.ts 补齐(5/5 绿):

    1. emitPreflightError 单元形态矩阵 × 3 协议 × retryable{true,false}——proxy-stream-error.test.ts 只钉了 emitStreamError,preflight emitter 此前零钉死(含只有 openai 带 retryable 的不对称)
    2. non-stream preflight 失败 post-commit → 200 上 {error} JSON——preflight-hold.test.ts 的 non-stream 格只断言成功路径,注册表行声称的失败形态覆盖实际不存在
    3. upstream non-2xx post-commit(non-stream)→ 200 上逐字节透传上游错误体——全仓库零断言
    4. proxy-openai-sse ×3 重复中断收敛 storm(轮询 timer 收敛 + socket close 双观测量)
    5. client-gone 健壮性:write 抛错时三协议均不得 throw

    另在 src/exit-matrix.ts 的 5 行 coveredBy 追加注册新文件(纯增量)。预检:typecheck 干净;全套 1182/1183,唯一红是 launcher.test.ts resolveClientCommand 的环境依赖既有问题(在安装了 codex 的环境里 resolver 返回绝对路径,clean master 上同样红,与本 diff 无关)。

    彻底方案意见(顺序 2→1→3→4)

    同意顺序,两点细化:

    • Item 2(发射器合一):完全同意,零风险。两种形态现在被矩阵双钉死(含 retryable 不对称),合并时契约不丢。实现注意:stage 保持必填参数、不要默认推断——显式是合一的全部意义。
    • Item 1(plugin 收编):最大收益,同意。建议拆成 2 个 PR:先抽 tagEchoFilter() / usageSniffer(protocol) 为纯可组合 transform + 单测(零行为变化),再把三个 pipe 切到 byteRelay+transforms。一个必须保留的差异:plugin-responses verbatim 变体按设计跳过 usage 记账(注册表契约写明),transform 组合要保留这种按出口差异,不能统一开 sniffer。
    • Item 3(snapshot→live-state):方向同意,先标成本:status panel 轮询意味着每次读取都在会话锁内重算 processed/nudge,热路径上加 kernel 工作。建议先量一下 compress 批量门报错 "a prior compress renumbered the remaining refs" 为事实性错误——内核不存在任何 ref 重编号(首压会话即被谎称有前科) #389 定点重算模式的开销,再决定是否全面转正。
    • Item 4(WireExit 接口):建议放到 item 1 落地后再做——hook 形状取决于 transform 架构的最终形态,现在定义接口有返工风险。

    另记一条观察(不提议动作):pipeThrough 的反压等待(src/server.ts:3878)只等 drain,缺 rewriter 路径(:3666-3669)处理的 drain-vs-close race——反压期间客户端断连理论上可挂起,暂无证据,留作观察项。

  8. ranxianglei commented on Sep 7, 2026

    @ranxianglei
    OwnerAuthor

    Closing — the actionable parts shipped:

    • PR#608 (v0.1.90): wire-exit enumeration matrix — compile-time registry of all 5 exits × cross-cutting concerns (usage/abort/timer/role), with coveredBy annotations enforced by a self-consistency test.
    • PR#612 (v0.1.90): the 5 surveyed gap cells now have tests — preflight-emitter shapes per protocol, client-gone-mid-write, post-commit structured-vs-verbatim JSON, abort-storm → timers converge to zero.

    Remaining residue (plugin.ts SSE/JSON dual paths + remembered-snapshot pattern) is documented in the PR#612 review thread; if it ever bites in practice, file a focused issue against the specific cell — the matrix now makes the surface enumerable.

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions