Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag

### Changes

- **Fork 子会话不再因前缀漂移永久 409(#3741,owner 决策:门降 advisory)**:dsh/客户端 fork 出的子会话,其首个请求如果与继承的有序前缀不匹配(升级换代重排消息 id、宿主改写 body 等),过去直接 409 且被拒请求不计数——重试永远撞同一扇门,子会话确定性卡死、无任何自愈或清除路径。现在改为**照常收养**:session-id 绑定本来就是真正的唤醒路由,折叠覆盖差异由 reconcile(#3641 order-over-hash)兜底修复;漂移首请求付出一次性未折叠 token 峰,正确性无损。每次收养打一条带分类的 warn(reason 沿用 #3743 诊断:id-drift / hash-drift-under-same-id / prefix-longer-than-incoming 等),`publicForkPrefix` 在漂移时保持 false,side-lane 降级启发照常发言。测试:三种漂移形态全部 200+转发+父会话不动+恰一条 warn(one-shot:首请求后 stats.requests>0 绕过检查)。
- **快照渲染:proxy 车道的出站前缀改由服务端正史渲染,存量会话对内核升级免疫(#3756,根治 #3752/#3751)。** 折叠覆盖此前锚定在"客户端本轮重发的字节"上——消息 id 由内容哈希现算,身份函数一变(协议切换 #3640、#3642 的一次性 re-key、dsh 图片 offload #3588、宿主自查点)覆盖名单就与历史失联:轻则整段历史因 MAX_ANCHORS=16384 封顶失锚(#3752),重则图片族 `_N` 后缀全体位移重铸、每轮 fold 断缓存(#3751)。新引擎 `src/server/snapshot-render.ts`(灰度开关 `BILI_ROLLOUT_SNAPSHOT_RENDER`,默认 0%):当会话有活跃折叠块且统一存储可读时,prepare 层的出站消息序列 = 服务端快照行前缀(覆盖区由块的 seq/signature 覆盖集自拥抑制 + `acp_summary_*` 锚原位重渲,身份跟随块而非客户端字节)+ 客户端尾巴(分歧点 join 之上逐字保留,rewind 裁剪不复活)。链回溯用 id 快路径 + 内容签名兜底(#3658 canonical 种子同构,升级后同内容仍可链上);任何环节失步整轮降级回 legacy 路径,零行为面风险。验收:身份函数原地翻盐后出站前缀逐字节不变(老病当场钉死)、协议中途切换会话不分叉、客户端任意删/checkpoint 覆盖区不复活(一轮采用滞后,模块头有注释)、稳态轮轮前缀字节稳。观测闩 `metadata.snapshotRenderTurns`;kernel 加 `__setMessageIdSaltForTests` 测试缝(kernel 0.0.134,仅测试可达,生产零调用)。

- **Automatic upgrades now stagger across a window instead of landing within minutes; a public policy file controls the window fleet-wide (#3619).** Every bili instance that discovers a new version draws ONE random moment inside a delay window (built-in default **15 min – 48 h**), persists it, and upgrades when it arrives — restarts never re-roll. Before this, a release hit every auto-updating install within ~15–30 minutes, leaving no time to stop a bad one mid-rollout (#3401/#3600/#3394 were all shipped-too-fast incidents). The window and the emergency controls live in `auto-update-policy.json` in this repo, fetched anonymously (plain GET + ETag, zero telemetry, fail-open — an unreachable or malformed file falls back to local defaults): `hold` freezes automatic upgrades fleet-wide, `blocked` skips listed versions, `pinned` sets an upgrade ceiling, and per-version `overrides` tune the window (`{ "range": ">=0.1.200", "maxDelay": "1h" }`). Delay fields take human-readable durations — `"15m"`, `"2d"`, `"1d12h"` (units s/m/h/d/w, combinable; plain numbers still mean raw ms); malformed values are ignored with a warning, never guessed. The file steers timing/skip/pin only — it can never control what gets installed (no URLs, no commands; target versions must exist in the npm packument). Exits: manual `bili update` bypasses `hold`/stagger (still respects `blocked`/`pinned`), `update.staggerMinDelayMs: 0` + `update.staggerMaxDelayMs: 0` (or the `BILI_UPDATE_STAGGER_*_MS` twins) restore legacy immediate upgrades on one machine, `ACP_AUTO_UPDATE=0` disables auto-updates entirely. The update-driven e2e suites pin stagger 0/0 + an unroutable policy URL — they test periodic-update mechanics, not rollout timing.
Expand Down
11 changes: 7 additions & 4 deletions src/agent/fork-adopt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@ import { ACP_NAME_ALT } from "../loop/tag-echo-filter.js";
* HASH PARITY CONTRACT: forkStableJson/forkIdentityHashOf/forkOrderHashOf
* below are byte-for-byte replicas of src/plugin.ts stableJson/
* forkMessageIdentityHash/forkOrderHash. The server's publicForkInputCheck
* rejects the child's first request (409 FORK_PREFIX_CONFLICT) when the
* replayed prefix does not hash-match the receipt, so any drift here poisons
* the child conversation permanently. The parity is pinned by
* tests/dsh-fork-adopt.test.ts against the exported plugin.ts hash.
* compares the replayed prefix against the receipt on the child's first
* request: a mismatch no longer rejects — it adopts with a classified warn
* and fold reconcile settles the inherited folds (#3741) — but the child
* loses the verified-prefix fast path (publicForkPrefix stays false, so the
* side-lane heuristics keep their say) and pays one unfolded first request.
* The parity is pinned by tests/dsh-fork-adopt.test.ts against the exported
* plugin.ts hash.
*
* RESPONSES PIPELINE PARITY CONTRACT: the forkResponses* functions below are
* byte-for-byte replicas of the server's responses pre-projection pipeline
Expand Down
34 changes: 24 additions & 10 deletions src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1334,13 +1334,27 @@ async function handleRequest(
publicForkPrefix = true;
return true;
}
// #3741: the 409 used to be a total blind spot — classify the
// mismatch server-side and echo the detail back so the client
// log alone points at the cause (id drift vs flag drift vs shape).
loggerLog("warn", `[fork-prefix] ${sessionId}: first child request rejected — ${verdict.reason} (protocol=${protocol})`);
res.writeHead(409, { "content-type": "application/json" });
res.end(JSON.stringify({ ok: false, code: "FORK_PREFIX_CONFLICT", error: "first child request does not match its inherited ordered prefix", detail: verdict.reason }));
return false;
// #3741 resolution (owner decision): the ordered-prefix gate is
// now ADVISORY, not blocking. The session-id binding above is
// what actually wakes the fork child (client conversation id →
// registered child session), and fold reconcile — #3641's
// order-over-hash doctrine — repairs coverage drift on resent
// history, so a byte-exact pre-gate adds no correctness the
// pipeline below doesn't already enforce. What it DID add was a
// permanent 409 dead-end: any drift the gate couldn't tolerate
// (in-place proxy upgrade re-keying message ids — #3741's field
// report, host body rewrite, legacy-hash adoption) stuck the
// child conversation forever, because the rejected first request
// never increments stats.requests, so every retry re-hit the same
// gate with no clear or TTL path. Adopt with a classified warn
// (reason taxonomy from the #3743 diagnostics) and let reconcile
// settle the inherited folds; a divergent child's first request
// goes out unfolded — a one-time token spike, never corruption.
// publicForkPrefix stays false on mismatch: the side-lane
// heuristics below keep their normal say instead of trusting an
// unverified inherited prefix to veto demotion.
loggerLog("warn", `[fork-prefix] ${sessionId}: inherited prefix mismatch — adopting anyway (${verdict.reason}; protocol=${protocol})`);
return true;
});
if (!accepted) return;
} finally {
Expand Down Expand Up @@ -1907,9 +1921,9 @@ async function handleRequest(
const dshTitleSidecar = pluginAgentHeader(req.headers) === "dsh" && requestAgent !== "main" && isDshTitleRequest(parsed);
const sideIntent = isSideRequest(parsed, requestAgent) || dshTitleSidecar;
// #388/#2157 follow-up: side requests must not touch kernel state under
// a public-fork receipt either. The receipt's first-request 409
// discipline above has already accepted this request (inherited prefix
// matched, or the child has live traffic), and a side request reads
// a public-fork receipt either. The receipt's first-request check above
// has already accepted this request (inherited prefix matched, or live
// traffic, or an advisory adoption per #3741), and a side request reads
// none of the kernel state fork adoption maintains — so the historical
// !publicForkPrefix veto here only had the effect of running
// full-history-replaying side calls (dsh title-gen under a forked
Expand Down
39 changes: 39 additions & 0 deletions tests/fork-side-request-lane.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,42 @@ test("fork-child title-gen rides the #388 passthrough and never pollutes the chi
await h.close();
}
});

test("an advisory-adopted first request that is a declared side request still rides the #388 passthrough (#3741)", async () => {
const h = await harness();
try {
// 1. fork parent -> child at the full 3-message prefix
const snapshot = (await h.request("/__bili/plugin/snapshot?conversationId=parent")).body as { status: string; parentRevision: string; orderedMessages: unknown[] };
assert.ok(snapshot.status !== "error");
const orderedMessages = snapshot.orderedMessages.slice(0, 3);
const fork = await h.request("/__bili/plugin/fork", { protocolVersion: 1, parentConversationId: "parent", childConversationId: "forkchild", parentRevision: snapshot.parentRevision, branchPoint: { messageCount: 3, orderHash: hash(orderedMessages) }, orderedMessages, idempotencyKey: "fork-title-adopted" });
assert.equal(fork.status, 201, JSON.stringify(fork.body));
const revBefore = ((await h.request("/__bili/plugin/snapshot?conversationId=forkchild")).body as { parentRevision: string }).parentRevision;

// 2. FIRST child request is a dsh title-gen shape (agent=title) whose replayed history
// DRIFTS from the inherited prefix. Pre-#3757 this 409'd forever; now the advisory gate
// adopts it — and declared side intent must STILL divert it to the #388 passthrough
// (publicForkPrefix stays false on mismatch, so the lane heuristics keep their say).
const driftedHistory = h.messages.map((m, i) => i === 0 ? { ...m, content: "drifted first message" } : m);
const titleMessages = [...driftedHistory, { role: "assistant", content: "child continuation" }, { role: "user", content: "Generate a title." }];
const upstreamHitsBefore = h.forwarded.length;
await h.dshSend("forkchild", titleMessages, "title", "You generate short titles.", 1024);
assert.equal(h.forwarded.length, upstreamHitsBefore + 1, "adopted side request still reaches the upstream");

const session = resolveConversation("forkchild").session!;
assert.ok(session.metadata.publicForkReceipt !== undefined, "fork receipt recorded on the child session");
assert.equal(session.stats.requests, 0, "a declared side request never counts as a fork-child main request, even when adopted");
const revAfter = ((await h.request("/__bili/plugin/snapshot?conversationId=forkchild")).body as { parentRevision: string }).parentRevision;
assert.equal(revAfter, revBefore, "adopted title-gen must not grow the fork-child session snapshot");
assert.ok(!JSON.stringify(session.pluginSnapshot).includes("Generate a title."), "title instruction never lands in the child's kernel session");
const titleForward = h.forwarded.at(-1)! as { messages?: { content: unknown }[] };
assert.ok(titleForward.messages?.some((m) => JSON.stringify(m.content).includes("Generate a title.")), "the forwarded title request carries the title instruction");

// 3. the child's first MAIN turn afterwards still runs the full pipeline normally:
// the adoption was one-shot advisory signal, not a lane reclassification.
await h.dshSend("forkchild", [...titleMessages, { role: "assistant", content: "A Title" }, { role: "user", content: "continue working" }], "main", "MAIN OPERATING SYSTEM", 256);
assert.equal(session.stats.requests, 1, "the next main turn counts as a fork-child main request");
} finally {
await h.close();
}
});
Loading
Loading