Skip to content

[PR] feat: async compression for Pi and Claude bridge - #3001

Closed
RodrigoHamuy wants to merge 3 commits into
ranxianglei:masterfrom
RodrigoHamuy:2026-10-13_async-background-compress
Closed

RodrigoHamuy wants to merge 3 commits into
ranxianglei:masterfrom
RodrigoHamuy:2026-10-13_async-background-compress

Conversation

@RodrigoHamuy

@RodrigoHamuy RodrigoHamuy commented Oct 13, 2026 •

Copy link
Copy Markdown

🚨 Blocked pending approval: add compress.async (default: off) using the existing global/provider/model settings. For now, tests enable it through an internal, default-off switch (configureAsyncCompress).

Closes #3000.

✨ What this does

  • 🧵 Compresses in the background. When the agent asks for background compression, a separate request on the same model does the work while the main conversation keeps going.
  • ♻️ Reuses cached conversation history where available to reduce the extra request's input cost.
  • ✅ Applies the summary on a later request. Normal compression works exactly as before.

Safety: summaries are checked before applying. If a summary is no longer valid or a request can't be copied safely, background compression is skipped and the agent gets a short note.

⚙️ Config surface

No public settings added yet; the proposed compress.async key is the approval request above.

Notes: automatic Claude-bridge setup is still unfinished. Usage stats don't include these background requests, as they already don't for external-summary requests. A pending background summary is lost if bili restarts; the original conversation is preserved.

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到。这是外部贡献的 draft PR(明确标注 Not merge-ready),我按 PR Review 规范走完整审查:先核对原 issue #3000 的方向与三个 owner 决策点,再在分支头验证 pre-flight 声明(typecheck/build/定向测试;全量套件交给 CI),然后逐文件审代码、审测试有效性、审回归面。结论会按结构化八问回复在本线程。审查期间不动分支代码——这是 draft,等 owner 对 enablement/bridge/credential 三问拍板。

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Full review of #3001 complete (draft kept as-is — no merge/approve; human tier per §7.4).

What I did

  • Read the full diff (13 files, +2747/−33 @ 01e470918, single commit ✓): all of src/async-compress.ts, every hook site (handle/relay/inject/plugin/loop/core/external-summary-compress/fetch-transport), and the 1847-line test file.
  • Verified pre-flight locally: typecheck ✓, build ✓, tests/async-compress.test.ts 48/48 pass. Full suite left to CI per local-testing discipline.
  • Two CI gates are red, and since test/static-gates needs: them, your full-suite claim ("12 failures identical to unmodified master") is currently unverifiable in CI. Both failures are mechanical, neither touches semantics. I fixed both on a scratch branch (verified green) — I have pull-only on your fork, so please apply the patch below (or grant push access and I'll push it as two labeled commits):
diff --git a/src/async-compress.ts b/src/async-compress.ts
--- a/src/async-compress.ts
+++ b/src/async-compress.ts
@@ -25,7 +25,7 @@ import type { WireProtocol } from "./util.js";
 export const ASYNC_COMPRESS_CALL_ID_PREFIX = "async_compress_";
 
-export interface AsyncCompressPolicy {
+interface AsyncCompressPolicy {
     captureTimeoutMs: number;
@@ -73,7 +73,7 @@ interface Note {
-export interface OutboundSend {
+interface OutboundSend {
     url: string;
@@ -104,6 +104,12 @@ export function asyncCompressEnabled(): boolean {
     return policy !== undefined;
 }
 
+/** Request-level eligibility shared by the apply and note hooks: plain model POSTs only —
+ *  not count-tokens, not codex compact-forge, and never side-lane traffic (side requests do not own compression). */
+export function asyncRequestGate(countTokens: boolean, responsesCompact: boolean, prepared: { sidePassthrough?: boolean } | null | undefined): boolean {
+    return policy !== undefined && !countTokens && !responsesCompact && prepared !== null && prepared !== undefined && prepared.sidePassthrough !== true;
+}
+
 export function disposeAsyncCompress(reason = "disposed"): void {
@@ -371,12 +377,12 @@ function activeBlockKeys(session: Session): string[] {
-export interface FoldHint {
+interface FoldHint {
     startRef: string;
     endRef: string;
 }
 
-export type FoldSuggestion = { hint: FoldHint; reason?: undefined } | { hint?: undefined; reason: "no-offer" | "stale-offer" | "none-offered" };
+type FoldSuggestion = { hint: FoldHint; reason?: undefined } | { hint?: undefined; reason: "no-offer" | "stale-offer" | "none-offered" };
@@ -495,7 +501,7 @@ function modelOf(protocol: WireProtocol, body: Record<string, unknown>, url: str
-export interface ForkCall { name: string; arguments: string }
+interface ForkCall { name: string; arguments: string }
@@ -608,10 +614,10 @@ export function mediaTypeClass(header: string | null): string {
-export type ReplyFraming = "sse" | "json" | "html" | "empty" | "other";
+type ReplyFraming = "sse" | "json" | "html" | "empty" | "other";
 
 /** Classifies a decoded reply by its first non-blank characters (a BOM is already removed by TextDecoder). */
-export function replyFraming(text: string): ReplyFraming {
+function replyFraming(text: string): ReplyFraming {
@@ -730,7 +736,7 @@ function staleReason(capture: Capture, session: Session, messages: readonly Core
-export interface AsyncApplyContext {
+interface AsyncApplyContext {
     core: CompressionCore;
diff --git a/src/server/handle.ts b/src/server/handle.ts
--- a/src/server/handle.ts
+++ b/src/server/handle.ts
@@ -64,7 +64,7 @@
-import { applyReadyAsyncCompress, asyncCompressEnabled, attachAsyncNote } from "../async-compress.js";
+import { applyReadyAsyncCompress, attachAsyncNote, asyncRequestGate } from "../async-compress.js";
@@ -2024,7 +2024,7 @@
                 prepared = await runPrepare();
-                if (asyncCompressEnabled() && !countTokens && !responsesCompact && prepared && !prepared.sidePassthrough && applyReadyAsyncCompress(session, {
+                if (prepared && asyncRequestGate(countTokens, responsesCompact, prepared) && applyReadyAsyncCompress(session, {
                     core, config: reqConfig, protocol: prepared.protocol, upstreamUrl: forwardUpstreamUrl(req, opts, route), model: requestModel,
@@ -2141,7 +2141,7 @@
-                if (asyncCompressEnabled() && !countTokens && !responsesCompact && !prepared!.sidePassthrough) prepared!.body = attachAsyncNote(prepared!, session, prepared!.protocol, prepared!.body);
+                if (asyncRequestGate(countTokens, responsesCompact, prepared)) prepared!.body = attachAsyncNote(prepared!, session, prepared!.protocol, prepared!.body);
                 logRequestCost(log, session.id, inboundMsgs, inboundBytes, reqT0, prepared!.body);

Why each fix is right:

  1. unused-exports: those 8 types/functions have zero references outside their own file (tests included — verified by grep). Dropping export is exactly what the gate prescribes for INTERNAL_ONLY; re-export later when enablement wiring needs them.
  2. lane-guard: the gate greps src/server/handle.ts diff lines for side-lane symbols (sidePassthrough, …). Your new lines merely read prepared.sidePassthrough as an eligibility condition — no side-lane logic changed, so updating the side-lane suites would be theater. Moving the predicate into asyncRequestGate() in async-compress.ts keeps the gate honest and unweakened: identical semantics (policy set && !countTokens && !responsesCompact && !sidePassthrough), and the handle.ts diff no longer contains lane symbols. Re-verified after the change: both gate scripts clean, typecheck ✓, 48/48 ✓, build ✓.

Structured eight questions (结构化八问)

  1. 是什么问题: Async compression for Pi without blocking the main turn #3000 — synchronous compression stalls the active turn, and idle sessions never converge ([Feature] fold toward autoFoldTargetTokens while the session is idle — folding only happens on the request path, so idle sessions never converge and active ones stall every ~4.5 min #2670). This adds background async compression: the model calls compress({"content":[]}) to queue a job; the proxy forks a background request (templated on the next outbound send) that performs the fold, applied to a later turn.
  2. 什么原因导致的: inherent tension of the sync pipeline with long turns; feat: external-summary autoFold — growth folding with zero model involvement + observable external blocks #2571's externalSummary.autoFold uses a different model and doesn't cover the same-model case. Capability addition, not defect repair.
  3. 影响范围与严重程度: disabled = zero impact (code-verified inert-by-default: configureAsyncCompress() has no production caller; withAsyncCompressTools returns tools unchanged, triggerAsyncCompress/observeOutboundSend bail out when no policy; the two verbatim-move files keep re-export identity). Enabled = one extra background request per trigger plus possibly one note message. Severity: N/A (feature).
  4. 怎么修复的: six-phase state machine trigger→capture→fork→validate→ready→apply. Deny-by-default capture list (signed bodies, server-state keys, hosted capabilities, forced tool_choice, …), byte-preserved existing items, bounded reads with cancel, enum-only diagnostics (never echoing raw values), one job/session, supersede-on-direct-fold, stale detection honoring KDD#11 (ids never reused; ref rebinding ⇒ stale), dry-run validation + net-benefit check before commit under the session lock. Defense-in-depth quality is high.
  5. 是否有回归问题: none found. Audited existing behaviors on every touched path: prepare/forward main path (all new branches policy-gated; off ⇒ byte-identical old path), relay forward() observation/settle (same), tool injection wrappers (no-op disabled), external-summary-compress routing/supersede (no-ops without policy), loop-round observation (gated), google/plugin-fold-callid moves (re-exports unchanged). CI e2e suites green at head (codex fake both modes, opencode native, dsh, pi WS, registry hermetic, image billing). No past behavior/threshold/default/output-format drift: feature off ≡ current release.
  6. 是否破坏缓存: existing prefix-cache behavior untouched (off ⇒ unchanged path). When enabled: the fork is fresh traffic; the failure note is a one-shot trailing user message that never enters client history (no echo desync); the acp_summary carrier follows standard compression cache-invalidation semantics, same as today's sync folds.
  7. 是否改了设计方向: no pivot — a background lane inside the proxy (module-local job queue), complementary to feat: external-summary autoFold — growth folding with zero model involvement + observable external blocks #2571/[Feature] fold toward autoFoldTargetTokens while the session is idle — folding only happens on the request path, so idle sessions never converge and active ones stall every ~4.5 min #2670; dual-mode carrier choice consistent with KDD#7 (both modes use acp_summary).
  8. 是否引入了新的配置: none — enablement deliberately deferred to the owner decision (§3 config-surface discipline respected). My recommendation: a key inside the existing compress hierarchy resolved via knobs (env > file > default), default off; wire configureAsyncCompress only after you approve the exact field name.

Clear recommendations on the three owner questions (not a menu):

  1. Enablement surface: new key inside the compress hierarchy, default off, no new top-level shape.
  2. Bridge routing: do NOT let bili silently auto-set the Claude Code route when launching Pi — compression ownership must stay single-writer; allow it only with explicit coordination via compactionOptIn/bind. A silent route switch is a silent ownership swap.
  3. Credential reuse: keep replaying captured auth headers for now (the fork must authenticate to the same upstream), but cost accounting must land before any default-on — background requests bill against the same account and users must see them (you already listed this).

Remaining gaps before merge (your open checklist is honest; confirmed still needed):

  • apply the two gate fixes above → full-suite CI actually runs green (currently skipped behind the failed gates)
  • net-benefit refusal path (dropJob + note, 手动 compress 仍接受零/负净收益折叠,先改写缓存再提示上下文增长 #2748) — handled but untested
  • reconciliation-interaction test (cell re-rendered/re-claimed between capture and apply)
  • codex e2e run
  • real-client acceptance against THIS head (currently only prototype base 9972ff2d)
  • Claude bridge routing + compaction coordination (awaiting owner call)
  • background-request usage/cost accounting

Verdict: code quality is high, the feature is provably inert until enabled, and I found no regressions. Keep draft status: resolve the three owner decisions + the checklist above, then undraft for human review (wire-shape feat ⇒ auto-merge N/A; merge stays human-only regardless).

@RodrigoHamuy

Copy link
Copy Markdown
Author

@ranxianglei you mind if I add a new setting compress.async, defaulting to false in this draft PR as part of the proof of concept? Thanks!

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Adding a config field is owner territory (AGENTS.md §3 Configuration Surface Discipline — a new key needs explicit owner sign-off in-thread BEFORE implementation), so I can't give that yes/no for you — @ranxianglei has to rule on compress.async.

As reviewer though: the shape you propose matches exactly what I recommended in the review (a key inside the existing compress hierarchy, default off), so I endorse it pending the owner's call. If approved, these are the requirements:

  1. Knob discipline (彻底整治环境变了滥用,除非必要都走配置文件 #2030): define it in src/knobs.ts as env > file > default, following the file's pattern (e.g. BILI_COMPRESS_ASYNC > compress.async > false). No raw process.env reads elsewhere.
  2. Wiring gotcha: configureAsyncCompress() calls disposeAsyncCompress() on EVERY invocation — it drops live jobs/notes. Knobs resolve on every call, so wire it with change-detection (apply only when the resolved value differs from the last-applied state, i.e. boot-time or on actual change), never per-request — otherwise you'd kill in-flight background jobs.
  3. PoC scope: keep it boolean-only for now; keep the internal timing constants (capture/fork/TTL/backoff) as module defaults until there's evidence someone needs to tune them.
  4. Docs: CONFIGURATION.md en+zh entry ("document or don't ship").
  5. PR body: add a "config surface" section — what's added (compress.async, default false), why the existing surface can't express it (no current key controls background async folding), alternatives considered, compat story (default false ⇒ zero behavior change).

@ranxianglei — over to you: approve or decline compress.async (plus the two remaining open questions in #3000: bridge routing and credential reuse)?

…fault off)

An empty compress({"content": []}) queues a background job. The next
outbound request is captured and replayed once as a background request
(existing message content and tool declarations preserved, plus a
directive asking for exactly one compress call). The validated result is
applied through the existing atomic apply path at a later request; stale
or invalid results are dropped with a one-time note.

Default off: reachable only through the internal configureAsyncCompress
hook. No config key, env var or CLI flag. Enablement, Claude-bridge
routing, background-request accounting and credential policy await
owner decisions in the tracking issue.
@RodrigoHamuy
RodrigoHamuy force-pushed the 2026-10-13_async-background-compress branch from 107007c to 0b9f84f Compare October 13, 2026 12:19
@ranxianglei

Copy link
Copy Markdown
Owner

8问

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 当前状态的结构化八问(代码 @ 01e470918,含我提供的两个 CI 门禁修复补丁):

  1. 是什么问题:Async compression for Pi without blocking the main turn #3000 — 同步压缩让当前轮次卡住、空闲会话永不收敛([Feature] fold toward autoFoldTargetTokens while the session is idle — folding only happens on the request path, so idle sessions never converge and active ones stall every ~4.5 min #2670)。本 PR 加「后台异步压缩」:模型调 compress({"content":[]}) 触发作业,代理 fork 一个后台请求执行折叠,应用到后续轮次。
  2. 什么原因导致的:同步管线与长轮次延迟的固有矛盾;feat: external-summary autoFold — growth folding with zero model involvement + observable external blocks #2571 externalSummary.autoFold 用另一模型,覆盖不了同模型场景。是能力新增,不是缺陷修复。
  3. 影响范围与严重程度:关闭时零影响(已代码级验证 inert-by-default:configureAsyncCompress() 无生产调用点,所有钩子在 policy 缺省时短路,两个 verbatim-move 文件 re-export 不变);启用后每次触发多一个后台请求 + 可能一条 note 消息。功能类,严重程度 N/A。
  4. 怎么修复的:trigger→capture→fork→validate→ready→apply 六相状态机;deny-by-default 捕获清单(signed body、server-state keys、hosted capabilities、forced tool_choice…);会话锁内 apply + stale 检测(KDD#11:id 永不复用、ref 重绑即 stale)+ dry-run 校验 + net-benefit 检查;失败每会话一条 note。防御纵深质量高。
  5. 是否有回归问题:无。逐项审过所有触碰路径的既有行为(prepare/forward 主链、relay forward()、工具注入 wrapper、external-summary-compress 路由/supersede、loop 轮观察、google/plugin-fold-callid 移动)——关闭时字节级等同旧路径;CI 全部 e2e 套件绿(codex fake 双模式、opencode native、dsh、pi WS、registry hermetic、image billing)。无历史行为/阈值/默认值/输出格式漂移。
  6. 是否破坏缓存:否。关闭 = 路径不变;启用后 fork 请求是全新增流量,失败 note 是一次性尾随 user 消息(不进客户端历史、无 echo 失步),acp_summary carrier 走标准压缩缓存失效语义,与现有同步折叠一致。
  7. 是否改了设计方向:无转向。代理内部新增后台 lane(模块内 job 队列),与 feat: external-summary autoFold — growth folding with zero model involvement + observable external blocks #2571/[Feature] fold toward autoFoldTargetTokens while the session is idle — folding only happens on the request path, so idle sessions never converge and active ones stall every ~4.5 min #2670 互补;双模式(proxy/pluginMode)carrier 策略符合 KDD#7(都用 acp_summary)。
  8. 是否引入了新的配置:尚未。作者提议 compress.async(默认 false),等你拍板;若批准须走 src/knobs.ts(env > file > default)+ CONFIGURATION.md en/zh + PR 正文 config-surface 小节,且接线要做变更检测(configureAsyncCompress() 每次调用都会 dispose 在途作业,不能按请求调用)。

待办三项:

  • 两个 CI 门禁红(unused-exports、lane-guard 误报):补丁已在上一条回复给出,作者应用后全量套件 CI 才能真正跑起来(当前被跳过);
  • 作者剩余清单:net-benefit 拒绝路径测试、reconciliation 交互测试、codex e2e、本 head 上的真客户端验收、bridge 路由完善、成本核算;
  • 你的三个决定:compress.async 批不批、bridge 路由策略、凭证复用。

判定:代码质量高、可证明默认惰性、未发现回归;维持 draft,上述清完再出 draft 走人审(wire-shape feat ⇒ auto-merge 不适用,合并始终人工)。

Resolve the src/server/relay.ts conflict with ranxianglei#3148's upstream circuit
breaker: the breaker check runs before the async capture hook, so an open
circuit fails fast without capturing a queued background job; a transport
failure settles the async job, then throws master's failureDetail.

Add a regression test: with the circuit open the queued job is neither
captured nor left running, and it captures once the circuit closes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Async compression for Pi without blocking the main turn

2 participants