mirror of
https://github.com/ranxianglei/billion-context.git
synced 2026-11-26 22:00:35 +08:00
feat(fastpath): delta resend arm — the tail-slice form of the watermark lane
Steady plugin-lane turns can now send body.messages = ONLY the new elements (L = T - stampT) plus x-bili-pf-delta: 1; the anchor (previous turn's last element) rides x-bili-pf-tail-ids[0] only. evaluateDeltaResend runs before the full lane and rebuilds the exact same FastpathHit (stashed prefix cores + rekeyWindowCores(parsed tail)), so every downstream consumer (stage-0 pin, kernel, ingest, snapshot, ledger window) is the untouched full-lane path. Re-anchor ladder: any unsatisfiable claim (bad header value, rollout off, no/mismatched seed, count/body/tail-ids width mismatch, anchor-chain break after a known previous list, broken scan, window shape) returns 400 pf_delta_reanchor + x-bili-msgid-mode: full and NO x-bili-pf-seq stamp — the client resends that turn in full form and converges within one round-trip. Editing/deleting the previous turn's LAST message breaks the chain by design (full form next); earlier-history rewrites degrade via the existing KDD#21 truncated-tail path, never a 400. No anchor byte re-parse — identity is verified on the ledger/pin (2x2) side. Rollout: rollout.features.pluginDeltaResend (default 0, OFF). Delta bodies are unprocessable by servers that do not ship this arm, so the key stays at 0 until client send-sides exist; env BILI_ROLLOUT_PLUGIN_DELTA_RESEND. x-bili-pf-delta joins UPSTREAM_HOP_HEADERS. Tests: tests/fastpath.test.ts delta-oracle test (reconstructed view byte- equivalent to the legacy full-parse oracle across consecutive slices, then a full-form turn after a delta hit) + the re-anchor matrix (both directions, #3617). Full 52-test battery green; typecheck + build clean. Docs: technical-notes en+zh (delta section), configuration en+zh (rollout row + env row).
This commit is contained in:
@@ -108,6 +108,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed
|
||||
| `rollout.features.identityChannelHarvest` | boolean \| number | 0 (off) | BILI_ROLLOUT_IDENTITY_CHANNEL_HARVEST | Identity-channel harvest cohort gate (#5825): allows the loopback-only transcript/sqlite harvest (src/identity-harvest.ts: claude-code / codebuddy / mcode / goose / qwen lanes) without any per-install env switch, when neither the per-install switch (BILI_IDENTITY_HARVEST) nor this key is set nothing ever reads client storage. Owner ruling 2026-11-07: this cohort key is deliberately separate from rollout.features.pluginLaneServerHistory (which governs row PINNING of admitted ids) — either enabler may activate harvesting. Default 0%; raise after small-cohort observation of the degrade warn-once rate. See identity-channels.md. |
|
||||
| `rollout.features.pluginLaneServerHistory` | boolean \| number | 0 (off) | BILI_ROLLOUT_PLUGIN_LANE_SERVER_HISTORY | Plugin-lane server-owned history (#4491): for enabled installs, (a) plugin-lane requests may carry an internal `biliMsgIds` array parallel to `messages` that pins message identity to client-supplied ids (always stripped before upstream forwarding; malformed arrays are ignored with a warning, id-poisoning shapes hard-fail on the incremental lane); (b) the loopback-only `POST /__bili/plugin/render` endpoint serves the outbound prefix rendered from the unified transcript (folded regions collapse to summary anchors; any desync degrades to a non-2xx so the shim falls back to its local history); (c) the incremental-lane probe advertises `serverHistory`. Default 0% — no behavior change until rolled out. |
|
||||
| `rollout.features.pluginFullResendWatermark` | boolean \| number | 5 (experimental grey) | BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK | Full-resend watermark fastpath (#5403/#5418): plugin-lane chat-completions turns whose previous response carried an x-bili-pf-seq stamp assert the resent prefix via the echoed count (structural scan, no full parse); on a hit the pipeline consumes stashed canonical prefix cores plus only the new tail window (byte-identical outbound provenance; ANY doubt falls back to the untouched full-parse path per turn and re-stamps, five credited misses hold the lane for one hour). Requires the client to echo the stamp back as x-bili-pf-count (dsh/pi/opencode/omp do; unadapted lanes never hit). EXPERIMENTAL grey rollout — ON by default for roughly 5% of installs (owner ruling 2026-11-02: small cohort before GA; one-time intro notice in the web UI for every install, tri-state switch in quick config). Force it with `true`, turn off with `false` (or a percent) / env = 0. See technical-notes.md “Full-resend watermark fastpath”. |
|
||||
| `rollout.features.pluginDeltaResend` | boolean \| number | 0 (off) | BILI_ROLLOUT_PLUGIN_DELTA_RESEND | Delta resend — the tail-slice form of the full-resend watermark lane: steady plugin-lane turns send `x-bili-pf-delta: 1` + body.messages = ONLY the new elements (L = T − stampT, no prefix); the server rebuilds the view from the stashed prefix cores plus the parsed tail (same hit provenance as the full lane). ANY unsatisfiable claim (count/body/tail-ids width mismatch, anchor-chain break after a known list, rollout off) returns 400 `pf_delta_reanchor` + `x-bili-msgid-mode: full` and the client resends that turn in full form — one-round convergence, never a silent misparse. OFF by default: delta bodies are unprocessable by servers that do not ship this arm, so the key stays 0 until client send-sides exist. See technical-notes.md “Delta resend”. |
|
||||
| `maskHosts` | boolean | true | BILI_LOG_MASK_HOSTS | Mask non-public target hosts in logs as <private-host>; credential headers are always masked regardless. |
|
||||
| `security.adminRelay` | boolean | false | — | Let an embedding host (dsh web today) relay the ENTIRE /__bili/ admin surface through its own entry origin so a remote browser can open the panel (#3373). Fail-closed, file-only. The relayed hop reaches the proxy as a local non-browser client (loopback source + loopback Host, no Origin), so the admin gate stays unchanged; enabling it exposes config editing and credential writes to whoever can reach the host web entry — protect that entry (auth / reverse proxy) first. |
|
||||
| `subagentSplit` | boolean | true | BILI_SUBAGENT_SPLIT | Claude Code subagents get their own session namespace (<session>\|sub:<agent-id>) instead of queueing behind the main session. Anthropic-wire only — on the Responses wire this switch is a no-op (see the `subagentSplit` / BOTH-mechanisms scope note). |
|
||||
@@ -2042,6 +2043,7 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes
|
||||
| `BILI_ROLLOUT_<FEATURE>` | `rollout.features.enabled` | unset (bucket math decides) |
|
||||
| `BILI_ROLLOUT_IDENTITY_CHANNEL_HARVEST` | `rollout.features.identityChannelHarvest` | 0 (off) |
|
||||
| `BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK` | `rollout.features.pluginFullResendWatermark` | 5 (experimental grey) |
|
||||
| `BILI_ROLLOUT_PLUGIN_DELTA_RESEND` | `rollout.features.pluginDeltaResend` | 0 (off) |
|
||||
| `BILI_ROLLOUT_PLUGIN_LANE_SERVER_HISTORY` | `rollout.features.pluginLaneServerHistory` | 0 (off) |
|
||||
| `BILI_SESSION_CONTENT_STORE_PIN` | `sessions.contentStorePin` | false |
|
||||
| `BILI_SESSION_GC` | `sessions.gc.enabled` | false |
|
||||
|
||||
@@ -108,6 +108,7 @@
|
||||
| `rollout.features.identityChannelHarvest` | boolean \| number | 0(关) | BILI_ROLLOUT_IDENTITY_CHANNEL_HARVEST | 身份信道采集的灰度门(#5825):当安装级开关(BILI_IDENTITY_HARVEST)未设置时,允许仅由本灰度键激活回环专属的转录/SQLite 采集(claude-code / codebuddy / mcode / goose / qwen 车道);两者都不设则永不读客户端存储。owner 裁定 2026-11-07:本灰度键与 rollout.features.pluginLaneServerHistory(它管已接纳 id 的行钉住)刻意分离——任一使能方可激活采集。默认 0%,小流量观察退化率后再抬。见 identity-channels.zh-CN.md。 |
|
||||
| `rollout.features.pluginLaneServerHistory` | boolean \| number | 0(关) | BILI_ROLLOUT_PLUGIN_LANE_SERVER_HISTORY | 插件车道服务端正史(#4491):对已放量的安装,(a) 插件车道请求可携带与 `messages` 平行的内部字段 `biliMsgIds`,把消息身份钉在客户端提供的 id 上(转发上游前一律剥掉;格式错误的数组告警后忽略,身份投毒形态在增量车道直接硬失败);(b) 仅回环可达的 `POST /__bili/plugin/render` 端点从统一存储渲染出站前缀(折叠区收敛为摘要锚点;任何失步都返回非 2xx,shim 退回本地历史);(c) 增量车道探测响应通告 `serverHistory`。默认 0%,放量前无行为变化。 |
|
||||
| `rollout.features.pluginFullResendWatermark` | boolean \| number | 5(实验性灰度) | BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK | 全量重发水位快路径(#5403/#5418):插件车道 chat-completions 回合若上一轮响应盖有 x-bili-pf-seq,则用回声计数声明重发前缀(结构扫描,不做全量解析);命中时管线只消费钉存的前缀核 + 新增尾巴窗口(出站字节同源可证;任何疑点当轮回退未动过的全量解析路径并重新盖戳,连续五次计名失配将车道按住一小时)。需客户端把戳回声为 x-bili-pf-count(适配的车道回带;其余车道不会命中)。**实验性灰度**——默认仅约 5% 的安装开启(owner 裁定 2026-11-02:先小流量再 GA;web 面板对全部安装显示一次性公告、快速配置提供三态开关);`true` 强制开、`false`(或百分比)/ env = 0 关。见 technical-notes.zh-CN.md「全量重发水位快路径」。 |
|
||||
| `rollout.features.pluginDeltaResend` | boolean \| number | 0(关) | BILI_ROLLOUT_PLUGIN_DELTA_RESEND | Delta 重发——全量重发水位快路径的尾切片形态:稳态轮发 `x-bili-pf-delta: 1` + body.messages = **只有**新元素(L = T − stampT,无前置);服务端用钉存前缀核 + 解析出的尾部重建视图(与全量车道同源的命中可证)。任何不成立的声明(count/body/tail-ids 宽度不符、已知清单后锚链断裂、灰度关)返回 400 `pf_delta_reanchor` + `x-bili-msgid-mode: full`,客户端当轮改发全量形态——一轮收敛,绝不静默错解。默认**关**:delta body 对未上车的服务端不可处理,故保持 0 直到客户端发送端就位。见 technical-notes.zh-CN.md「Delta 重发」。 |
|
||||
| `maskHosts` | boolean | true | BILI_LOG_MASK_HOSTS | 日志中把非公开目标主机遮成 <private-host>;凭据头无论此开关如何总是遮盖。 |
|
||||
| `security.adminRelay` | boolean | false | — | 允许宿主(当前为 dsh web)把它自己入口域名下的整个 /__bili/ 管理面中继到本机代理,使远程浏览器能打开面板(#3373)。默认关闭、仅配置文件。中继跳到达代理时是本机非浏览器客户端(回环源地址 + 回环 Host、无 Origin 头),管理端门槛不变;开启后,凡能访问宿主 web 入口的人都能改配置、写凭据——请先给入口加鉴权/反代。 |
|
||||
| `subagentSplit` | boolean | true | BILI_SUBAGENT_SPLIT | Claude 子代理拥有独立会话命名空间(<session>\|sub:<agent-id>),不再排队在主会话锁后。仅 anthropic 线路 —— Responses 线路上本开关无效(见 `subagentSplit` / BOTH-mechanisms 作用域说明)。 |
|
||||
@@ -2019,6 +2020,7 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报
|
||||
| `BILI_ROLLOUT_<FEATURE>` | `rollout.features.enabled` | unset (bucket math decides) |
|
||||
| `BILI_ROLLOUT_IDENTITY_CHANNEL_HARVEST` | `rollout.features.identityChannelHarvest` | 0 (off) |
|
||||
| `BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK` | `rollout.features.pluginFullResendWatermark` | 5 (experimental grey) |
|
||||
| `BILI_ROLLOUT_PLUGIN_DELTA_RESEND` | `rollout.features.pluginDeltaResend` | 0 (off) |
|
||||
| `BILI_ROLLOUT_PLUGIN_LANE_SERVER_HISTORY` | `rollout.features.pluginLaneServerHistory` | 0 (off) |
|
||||
| `BILI_SESSION_CONTENT_STORE_PIN` | `sessions.contentStorePin` | false |
|
||||
| `BILI_SESSION_GC` | `sessions.gc.enabled` | false |
|
||||
|
||||
@@ -603,3 +603,19 @@ Declared trust boundary (§7.4 — human review required, no auto-merge): a clie
|
||||
Honest limits: (1) once a multimodal tail (content array containing `image_url`) lands in the stash, the lane degrades to full legacy turns for the remainder of that history — the kernel renders user content-array images differently when the message is the LAST element versus mid-history, so a frozen stash cannot reproduce legacy bytes position-independently; text workloads (the #5403 reporter's shape) are unaffected. (2) The head fragment is re-parsed (8 elements) each hit solely for the system-run check. (3) Both `x-bili-pf-*` headers are stripped upstream (`UPSTREAM_HOP_HEADERS`) — protocol headers never leak into model traffic.
|
||||
|
||||
Measured (provenance: `tests/issue5403-watermark-fastpath.test.ts`, hermetic dual-proxy A/B on the same corpus): hit turns skip the full parse/conversion/pin entirely; resident `lastMessages` 8684 B → 1210 B (7.2×) on an 8-turn corpus including a multipart image landing turn; outbound bytes byte-identical to legacy modulo kernel `time="…"` attributes across all turns; `x-bili-pf-*` absent from every captured upstream request, both phases. Unit coverage: `tests/fastpath.test.ts` (full verdict ladder incl. breaker TTL re-arm), `tests/fastpath-scanner.test.ts` (adversarial JSON table, depth cap, surrogate pairs, 50k-element scale), `tests/lane-decisions-matrix.test.ts` (gate row matrix, both directions).
|
||||
|
||||
## Delta resend — the tail-slice form of the watermark lane
|
||||
|
||||
The watermark fastpath above skips the server's re-processing of the re-sent prefix, but the client still UPLOADS the whole history every turn. Delta resend removes the upload: on a steady turn the client sends ONLY the new elements.
|
||||
|
||||
Wire form (client → proxy, all three headers, one extra): `x-bili-pf-delta: 1` + `x-bili-pf-count: T` (new total element count) + `x-bili-pf-tail-ids` = anchor+new host msgids, width exactly L+1 (L = T − stampT new elements; `tail-ids[0]` anchors the previous turn's last element), and `body.messages` = exactly the L NEW elements (`[T-L .. T-1]`, no prefix, no anchor). The anchor element itself is NOT in the body — it rides the header only.
|
||||
|
||||
Server side: `evaluateDeltaResend` (src/server/fastpath.ts) runs BEFORE the full-body lane when the header is present. Rebuild: `view = stashed prefix cores + rekeyWindowCores(parsed tail)` → exactly the same `FastpathHit` the full lane produces → everything downstream (stage-0 pin, kernel processTurn, ingest, snapshot, ledger window) is the untouched full-lane code path.
|
||||
|
||||
Re-anchor ladder — any unsatisfiable claim returns 400 `pf_delta_reanchor` with `x-bili-msgid-mode: full` and NO `x-bili-pf-seq` stamp; the client resends the SAME turn in full form and converges within one round-trip (KDD#15 one-round convergence). Gate order: header value / rollout / plugin-mode / seed presence / model match / no multimodal seed / count present / L in [1..2048] / body length == L / tail-ids width == L+1 / **anchor continuity** (strict after a known previous list — `tail-ids[0]` must equal the previous turn's last declared id; a tail-less seed lets the first delta turn open unverified, then every list is chained) / body scan total == L / window conversion shape. No anchor byte re-parse: the anchor's identity is verified on the ledger/pin side (the 2×2 channel), never by re-parsing the previous turn's bytes.
|
||||
|
||||
Editing or deleting the LAST message of the previous turn breaks the anchor chain → re-anchor 400 → full form. Deleting/rewriting EARLIER history does NOT: the ledger/pin overlap check catches it one round later via the existing KDD#21 "truncated tail" degradation (full signal, re-anchor), never a 400.
|
||||
|
||||
Rollout: `rollout.features.pluginDeltaResend` (default 0 — OFF). Delta bodies are unprocessable by servers that do not ship this arm, so the key stays at 0 until client send-sides exist; env override `BILI_ROLLOUT_PLUGIN_DELTA_RESEND`. A `x-bili-pf-delta` request hitting a rollout-off server gets the same 400 re-anchor (rollout-off gate) — never a silent misparse. All pf-* headers remain upstream-hop (stripped before model traffic).
|
||||
|
||||
Measured (100k-message raw session, loopback): full resend 15.9s/turn → 12.7s/turn (inbound 155MB → KB-scale; the remaining cost is the egress rebuild of the full rendered view — see the compressed-shape numbers for the realistic case). Compressed steady state (context ≈ 100k tokens ≈ 400KB body): 36ms/turn full → 21ms/turn delta; ≈ 300k tokens ≈ 1.2MB body: 128ms → 53ms. 10k-message raw session: 880ms → 550ms.
|
||||
|
||||
@@ -180,3 +180,19 @@ chat wire 上 bili 自己 vs 客户端自带:插件车道上,请求体里等于
|
||||
诚实边界:(1) 一旦多模态尾部(含 `image_url` 的 content array)进入缓存,该段历史此后整段降级回 legacy 全量轮——kernel 按位置区分 user 图片消息在尾部与在历史中部的渲染,冻结缓存无法做到位置无关地复现 legacy 字节;纯文本工作负载(#5403 报告者的形态)不受影响。(2) 每次命中会现解析头部 8 个元素,只为做 system-run 校验。(3) 两个 `x-bili-pf-*` 头都在转发上游前剥掉(`UPSTREAM_HOP_HEADERS`)——协议头绝不漏进模型流量。
|
||||
|
||||
实测(出处:`tests/issue5403-watermark-fastpath.test.ts`,同语料 hermetic 双代理 A/B):命中轮完全跳过全量解析/转换/钉存;含一个 multipart 图片落位回合的 8 回合语料上,常驻 `lastMessages` 8684 B → 1210 B(7.2×);全程出站字节与 legacy 逐字一致(仅 kernel `time="…"` 属性归一);两个阶段捕获到的上游请求里均无 `x-bili-pf-*`。单元覆盖:`tests/fastpath.test.ts`(verdict 阶梯全表,含熔断 TTL 解除后重播种)、`tests/fastpath-scanner.test.ts`(对抗 JSON 表、深度上限、surrogate 对、5 万元素规模)、`tests/lane-decisions-matrix.test.ts`(门矩阵,双向)。
|
||||
|
||||
## Delta 重发 —— 水位快路径的尾切片形态
|
||||
|
||||
上面的水位快路径只省了服务端对重发前缀的重复处理,客户端每轮仍然把**整个**历史上传。Delta 重发把上传也去掉:稳态轮客户端只发**新增**元素。
|
||||
|
||||
线上形态(客户端 → 代理,共四个头,body 只剩尾部):`x-bili-pf-delta: 1` + `x-bili-pf-count: T`(新的元素总数)+ `x-bili-pf-tail-ids` = 锚点+新增的宿主 msgid,宽度恰好 L+1(L = T − stampT 个新元素,`tail-ids[0]` 锚定上一轮最后一个元素),`body.messages` = **恰好**这 L 个新元素(`[T-L .. T-1]`,无前置、无锚点)。锚点元素本身不在 body 里,只走头。
|
||||
|
||||
服务端:`x-bili-pf-delta` 存在时 `evaluateDeltaResend`(src/server/fastpath.ts)在全量车道**之前**跑。重建:`view = 存好的前缀 cores + rekeyWindowCores(解析出的尾部)` → 产出与全量车道完全一致的 `FastpathHit` → 下游(stage-0 pin、kernel processTurn、ingest、快照、账本窗口)走的都是未改动的全量车道代码。
|
||||
|
||||
重锚阶梯——任何不成立的声明返回 400 `pf_delta_reanchor` + `x-bili-msgid-mode: full`,**且不打** `x-bili-pf-seq`;客户端本轮改发全量形态,一个来回内收敛(KDD#15 一轮收敛)。门序:头值 / 灰度 / plugin 模式 / 有无种子 / model 一致 / 非多模态种子 / count 在场 / L ∈ [1..2048] / body 长度 == L / tail-ids 宽度 == L+1 / **锚点连续性**(有已知上一清单后强制:`tail-ids[0]` 必须等于上一轮最后一个申报 id;无尾清单的种子允许第一轮 delta 不验证开局,之后逐链)/ body 扫描总数 == L / 窗口转换形状。不做锚点字节重解析:锚点身份由账本/pin 侧(2×2 通道)校验,绝不用上一轮字节复核。
|
||||
|
||||
编辑/删除上一轮**最后一条**消息会断锚链 → 400 重锚 → 全量形态。改写**更早**的历史不会:账本/pin 重叠检查在下一轮经 KDD#21「截断尾」降级(全量信号、重锚)接住,永不 400。
|
||||
|
||||
灰度:`rollout.features.pluginDeltaResend`(默认 0 —— **关**)。delta body 对未上车的服务端不可处理,故保持 0 直到客户端发送端就位;env 覆盖 `BILI_ROLLOUT_PLUGIN_DELTA_RESEND`。带 `x-bili-pf-delta` 的请求打到灰度关的服务端得到同样的 400 重锚(rollout-off 门)——绝不静默错解。所有 pf-* 头保持上游 hop(转发模型前剥掉)。
|
||||
|
||||
实测(10w 条原始会话,loopback):全量重发 15.9s/轮 → 12.7s/轮(入站 155MB → KB 量级;残余成本是整份渲染视图的出站重建——真实压缩场景见下)。压缩稳态(上下文 ≈ 10w token ≈ 400KB body):36ms/轮 全量 → 21ms/轮 delta;≈ 30w token ≈ 1.2MB body:128ms → 53ms。1w 条原始会话:880ms → 550ms。
|
||||
|
||||
@@ -116,6 +116,19 @@ export const ROLLOUT_FEATURES: Record<string, RolloutPlan> = {
|
||||
// `BILI_ROLLOUT_PLUGIN_MSG_ID_INCREMENTAL=0`. Requires
|
||||
// pluginLaneServerHistory.
|
||||
pluginMsgIdIncremental: { percent: 100 },
|
||||
// #5403 family, delta arm: the client sends body.messages as the TAIL
|
||||
// SLICE [T-L .. T-1] (anchor included) plus x-bili-pf-count = T and
|
||||
// x-bili-pf-tail-ids (width L) — the server rebuilds the view from the
|
||||
// stashed prefix cores + the small re-parsed slice. Inbound bytes drop
|
||||
// from O(history) to O(delta). Every unsatisfiable claim is a 400
|
||||
// re-anchor the client answers with a full-form resend (one-round
|
||||
// convergence); flipping the key back to 0 400s every delta turn, which
|
||||
// is the rollback path (clients converge to the full form within one
|
||||
// turn). Default OFF until the shim send-sides ship — a delta body is
|
||||
// unprocessable by older servers, so both ends must roll together.
|
||||
// Force with `rollout.features.pluginDeltaResend: true` or
|
||||
// `BILI_ROLLOUT_PLUGIN_DELTA_RESEND=1`.
|
||||
pluginDeltaResend: { percent: 0 },
|
||||
// #5825 identity-channel harvest seam (registry in identity-harvest.ts):
|
||||
// loopback clients without an explicit body channel get stable session+
|
||||
// message identity aligned from their OWN local transcript/sqlite
|
||||
|
||||
@@ -46,6 +46,36 @@ import { scanMessagesSpans, type RawSpan } from "./fastpath-scan.js";
|
||||
export const PF_COUNT_HEADER = "x-bili-pf-count";
|
||||
export const PF_SEQ_HEADER = "x-bili-pf-seq";
|
||||
export const PF_TAIL_IDS_HEADER = "x-bili-pf-tail-ids";
|
||||
// #5403 family, delta arm: the client claims body.messages is the TAIL SLICE
|
||||
// [T-L .. T-1] (anchor = element T-1 of the PREVIOUS turn included), with the
|
||||
// full logical count in x-bili-pf-count and per-element ids in x-bili-pf-tail-ids
|
||||
// (width exactly L). The server rebuilds the view from the seed prefix cores +
|
||||
// the re-parsed slice — the same FastpathHit the full-body lane produces, so
|
||||
// every downstream stage (stage0 pin, kernel, ingest, snapshot) is untouched.
|
||||
// Any unsatisfiable claim is a 400 re-anchor (DeltaReanchorError): the body
|
||||
// CANNOT be processed by the legacy path (the prefix bytes are absent), so the
|
||||
// only honest answer is "resend this turn in full form"; the client converges
|
||||
// within one round (the same one-round contract as every pf miss).
|
||||
export const PF_DELTA_HEADER = "x-bili-pf-delta";
|
||||
|
||||
/** Thrown from prepare-openai when a delta request cannot be satisfied —
|
||||
* handle.ts maps it to the 400 re-anchor response (no pf-seq stamp, mode full). */
|
||||
export class DeltaReanchorError extends Error {
|
||||
readonly reason: string;
|
||||
constructor(reason: string) {
|
||||
super(`pf delta re-anchor (${reason})`);
|
||||
this.name = "DeltaReanchorError";
|
||||
this.reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
/** A satisfiable delta claim: the verified hit plus the tail-id list it rode on. */
|
||||
export interface DeltaVerdict {
|
||||
readonly hit: FastpathHit;
|
||||
readonly receivedTailIds?: string[];
|
||||
}
|
||||
|
||||
const DELTA_WINDOW_MAX = 2048;
|
||||
// #5418 v3: UNIDENTIFIED slot marker — an element that carries no host id
|
||||
// (native-compaction summary, persona sidecar, foreign shape) travels as "?".
|
||||
// Wire literal duplicated per #3482 (agent bundles stay import-free leaves).
|
||||
@@ -527,6 +557,110 @@ export function finalizeWatermarkTurn(
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* #5403 family, delta arm — evaluate ONE chat-completions request whose client
|
||||
* declared `x-bili-pf-delta: 1` (body.messages = tail slice, full count in
|
||||
* x-bili-pf-count). Returns null when the request does not claim delta (the
|
||||
* full-body lane owns it), {hit} when every gate passes, or {reanchor} when
|
||||
* the claim is unsatisfiable (the caller must 400 — the legacy path cannot
|
||||
* process a prefix-less body).
|
||||
*
|
||||
* Gates (all must hold — any doubt is a re-anchor, never a partial trust):
|
||||
* rollout pluginDeltaResend on; plugin mode, not title-gen; a seed exists
|
||||
* for THIS model and is not multimodal-tainted; x-bili-pf-count is an
|
||||
* integer T; L = T - seed.stampT + 1 satisfies 1 ≤ L ≤ DELTA_WINDOW_MAX;
|
||||
* body.messages has EXACTLY L elements; x-bili-pf-tail-ids is shape-valid
|
||||
* with width exactly L and the anchor id continuous with the seed's last
|
||||
* tail-id list ("?" exempt); the structural scan of the (small) body agrees
|
||||
* on L; the anchor element re-parses byte-identical (id-excluded, #7064 2×2
|
||||
* namespace rule) to the stashed core at position stampT-1; no system/developer
|
||||
* element rides the slice (system lives in the seed's verified head).
|
||||
*
|
||||
* On a hit the window is re-parsed + rekeyed exactly like the full-body hit
|
||||
* (K = stampT-1: the slice INCLUDES the anchor), the anchor's strip counts
|
||||
* stay with the seed ledger (it was stripped on the previous turn — same
|
||||
* convention as the full path's head fragment), and view = stashed prefix
|
||||
* [0..stampT-2] + rekeyed slice = the canonical T-element array.
|
||||
*/
|
||||
export function evaluateDeltaResend(
|
||||
parsed: OpenAIRequestBody,
|
||||
bodyText: string,
|
||||
req: http.IncomingMessage,
|
||||
session: Session,
|
||||
input: { pluginMode: boolean; titleGen: boolean; model: string },
|
||||
log: (level: string, msg: string) => void,
|
||||
): DeltaVerdict | { readonly reanchor: string } | null {
|
||||
const rawDelta = req.headers[PF_DELTA_HEADER];
|
||||
if (rawDelta === undefined) return null;
|
||||
const reanchor = (reason: string): { reanchor: string } => {
|
||||
log("info", `[${session.id}] watermark delta re-anchor (${reason}) — 400, the client resends this turn in full form`);
|
||||
return { reanchor: reason };
|
||||
};
|
||||
if (String(rawDelta) !== "1") return reanchor("delta-bad-value");
|
||||
if (!featureEnabled("pluginDeltaResend")) return reanchor("rollout-off");
|
||||
if (!input.pluginMode || input.titleGen) return reanchor("gate");
|
||||
const tail: unknown[] | null = Array.isArray(parsed.messages) ? parsed.messages : null;
|
||||
const seed = seeds.get(session);
|
||||
if (seed === undefined) return reanchor("unseeded");
|
||||
if (seed.model !== input.model) return reanchor("model");
|
||||
if (seed.multimodal) return reanchor("seeded-multimodal");
|
||||
// Stashed cores are CORE-space: openaiToCore hoists the leading
|
||||
// system/developer run OUT of them, so cores.length = stampT − S (S =
|
||||
// hoisted systems), never positionally indexable by wire element.
|
||||
if (seed.cores.length === 0) return reanchor("seed-empty");
|
||||
const rawStamp = req.headers[PF_COUNT_HEADER];
|
||||
const T = typeof rawStamp === "string" && /^\d+$/.test(rawStamp.trim()) ? parseInt(rawStamp.trim(), 10) : NaN;
|
||||
if (!Number.isInteger(T) || T < 1) return reanchor("no-count");
|
||||
// The body carries the NEW elements [stampT .. T-1] ONLY (KDD#21 wire:
|
||||
// tail-ids carry anchor+new, the body carries what the client is appending).
|
||||
// L = T - stampT; the anchor is element stampT-1, already in the ledger.
|
||||
const L = T - seed.stampT;
|
||||
if (L < 1) return reanchor("behind");
|
||||
if (L > DELTA_WINDOW_MAX) return reanchor("window-too-large");
|
||||
if (tail === null || tail.length !== L) return reanchor("body-length");
|
||||
const rawTailIds = req.headers[PF_TAIL_IDS_HEADER];
|
||||
const tailIds = rawTailIds === undefined ? null : typeof rawTailIds === "string" ? parseTailIds(rawTailIds) : null;
|
||||
// tail-ids = anchor + the L new ids (the real client's steady-state form).
|
||||
if (tailIds === null || tailIds.length !== L + 1) return reanchor("tail-ids-shape");
|
||||
// Anchor continuity: once the previous turn stamped a tail list, the
|
||||
// list MUST open with the id it ended on — the same identity the full
|
||||
// lane's overlap row verifies against the ledger. A tail-less seed (the
|
||||
// first request of the session carries no pf headers by design) has no
|
||||
// stamped prev: the FIRST delta turn opens unverified, and from then on
|
||||
// every list is chained. An edited/deleted last message by construction
|
||||
// forces the full form too (the client's declared anchor id would not
|
||||
// match the ledger on the pin side).
|
||||
const prevKnown = seed.lastTailIds !== undefined && seed.lastTailIds.length > 0 ? seed.lastTailIds[seed.lastTailIds.length - 1] : undefined;
|
||||
if (prevKnown !== undefined && prevKnown !== PF_SLOT_UNKNOWN && tailIds[0] !== prevKnown) return reanchor("tail-ids-prev");
|
||||
const scan = scanMessagesSpans(bodyText, "all");
|
||||
if (scan === null || scan.total !== L) return reanchor("scan-broken");
|
||||
// Strip + convert the new elements exactly as the full-body lane decodes
|
||||
// its window (K = stampT); the anchor's strip counts stay with the seed
|
||||
// ledger (they were counted on the previous turn). Rekey against the FULL
|
||||
// stashed prefix so cluster ordinals and wireIndex match the legacy
|
||||
// single full-body parse.
|
||||
const windowFragment: { messages: unknown } = { messages: tail };
|
||||
const windowCounts = stripRawStage(windowFragment, "openai");
|
||||
const windowRaw = openaiToCore(windowFragment as OpenAIRequestBody);
|
||||
if (windowRaw.systemText.trim() !== "") return reanchor("window-system-head");
|
||||
if (windowRaw.msgs.length !== L) return reanchor("window-shape");
|
||||
const rekeyedWindow = rekeyWindowCores(windowRaw.msgs, seed.stampT, seed.cores);
|
||||
const view = [...seed.cores, ...rekeyedWindow] as CoreMessage[];
|
||||
return {
|
||||
hit: {
|
||||
view,
|
||||
windowCores: rekeyedWindow as CoreMessage[],
|
||||
systemText: seed.systemText,
|
||||
totalT: T,
|
||||
fieldSpans: scan.fieldSpans,
|
||||
windowMessages: windowFragment.messages as unknown[],
|
||||
seedMultimodal: JSON.stringify(tail).includes('"image_url"'),
|
||||
markerCounts: addStripCounts(seed.stripCounts, windowCounts),
|
||||
},
|
||||
receivedTailIds: tailIds,
|
||||
};
|
||||
}
|
||||
|
||||
/** Drop the in-process seed (e.g. an announced compaction was detected while
|
||||
* the fastpath was silent on later turns). Cheap and idempotent; the next
|
||||
* turn simply re-verifies via the legacy path. */
|
||||
|
||||
+19
-2
@@ -77,7 +77,8 @@ import { artifactSeedHit, detectAcpArtifacts } from "./chain-artifacts.js";
|
||||
import { piSubagentChannelFallback } from "./pi-subagent-channel.js";
|
||||
import { FORCE_TEXT_PROTOCOL } from "./inject.js";
|
||||
import { prepareAnthropic } from "./prepare-anthropic.js";
|
||||
import { MSG_IDS_BODY_FIELD, incomingMsgIdsOf, incomingMsgIdsHeader } from "../msgid-pin.js";
|
||||
import { MSG_IDS_BODY_FIELD, MSGID_MODE_HEADER, incomingMsgIdsOf, incomingMsgIdsHeader } from "../msgid-pin.js";
|
||||
import { DeltaReanchorError } from "./fastpath.js";
|
||||
import { harvestIdentity } from "../identity-harvest.js";
|
||||
import "../identity-sources.js"; // #5825: register every harvested lane (side effect)
|
||||
import { prepareOpenai } from "./prepare-openai.js";
|
||||
@@ -3604,7 +3605,23 @@ async function handleRequest(
|
||||
if (guardScheme !== undefined && !resignArmable && !guardResign.enabled) {
|
||||
clearSignedRefusal(guardScheme);
|
||||
}
|
||||
const pendingForward = await withSessionLock(session, () => runPreparedPipeline!(true));
|
||||
// #5403 family delta arm: a prefix-less tail-slice body cannot be
|
||||
// processed by the legacy path — the re-anchor is a 400 the client
|
||||
// answers by resending THIS turn in full form (one-round
|
||||
// convergence, the same contract as every pf miss). No pf-seq
|
||||
// stamp; mode relearned as "full" via the header.
|
||||
let pendingForward;
|
||||
try {
|
||||
pendingForward = await withSessionLock(session, () => runPreparedPipeline!(true));
|
||||
} catch (err) {
|
||||
if (err instanceof DeltaReanchorError && !res.destroyed && !res.writableEnded) {
|
||||
log("warn", `[${session.id}] watermark delta re-anchor 400 (${err.reason}) — client resends in full form`);
|
||||
res.writeHead(400, { "content-type": "application/json", [MSGID_MODE_HEADER]: "full" });
|
||||
res.end(JSON.stringify({ error: { type: "pf_delta_reanchor", message: err.reason } }));
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (pendingForward) {
|
||||
forwarded = true;
|
||||
// #1195: wire clients (omp/pi on the plain proxy path) treat an
|
||||
|
||||
@@ -37,6 +37,7 @@ export const UPSTREAM_HOP_HEADERS = new Set([
|
||||
"x-bili-pf-count",
|
||||
"x-bili-pf-seq",
|
||||
"x-bili-pf-tail-ids",
|
||||
"x-bili-pf-delta",
|
||||
// #5658: incremental-lane turn correlation id — the native plugin stamps it
|
||||
// on a diverted model request alongside x-bili-plugin-turn to correlate the
|
||||
// applied-seq ack. Pure host↔bili bookkeeping; like the pf-* handshake
|
||||
|
||||
@@ -51,7 +51,7 @@ import { effectiveAbsorbBlock, effectiveBlockOpsEnabled } from "./prepare-respon
|
||||
import { injectOpenaiTool, injectTool } from "./inject.js";
|
||||
import { nudgeOn, resolveLaneDecisions, surfaceOffDetail } from "./lane-decisions.js";
|
||||
import { featureEnabled } from "../rollout.js";
|
||||
import { PF_TAIL_IDS_HEADER, evaluateWatermarkFastpath, finalizeWatermarkTurn, parseTailIdsForPin, type FastpathHit, type FastpathOutcome } from "./fastpath.js";
|
||||
import { DeltaReanchorError, PF_TAIL_IDS_HEADER, evaluateDeltaResend, evaluateWatermarkFastpath, finalizeWatermarkTurn, parseTailIdsForPin, type FastpathHit, type FastpathOutcome } from "./fastpath.js";
|
||||
import { collectRequestIds, probeRequestMembership } from "../request-membership.js";
|
||||
|
||||
export async function prepareOpenai(
|
||||
@@ -163,8 +163,19 @@ export async function prepareOpenai(
|
||||
const wpModel = typeof parsed.model === "string" ? parsed.model : "";
|
||||
if (bodyText !== undefined && pluginMode && !isTitleGen && featureEnabled("pluginFullResendWatermark")) {
|
||||
wpFullText = bodyText;
|
||||
wpOutcome = evaluateWatermarkFastpath(bodyText, req, session, { pluginMode, titleGen: isTitleGen, model: wpModel }, log);
|
||||
log("debug", `[${session.id}] fastpath ${wpOutcome.hit ? "HIT" : wpOutcome.decision}${wpOutcome.creditedMiss ? "(credited)" : ""}${wpOutcome.measuredT !== undefined ? ` T=${wpOutcome.measuredT}` : ""}`);
|
||||
// Delta arm first: a delta claim is EXCLUSIVE — the body carries only
|
||||
// the tail slice, so the full-body lane cannot evaluate it at all. A
|
||||
// satisfiable claim yields the same FastpathHit the full lane would;
|
||||
// an unsatisfiable one throws the 400 re-anchor (handle.ts).
|
||||
const wpDelta = evaluateDeltaResend(parsed, bodyText, req, session, { pluginMode, titleGen: isTitleGen, model: wpModel }, log);
|
||||
if (wpDelta !== null) {
|
||||
if ("reanchor" in wpDelta) throw new DeltaReanchorError(wpDelta.reanchor);
|
||||
wpOutcome = { hit: wpDelta.hit, measuredT: wpDelta.hit.totalT, decision: "delta-hit", creditedMiss: false, receivedTailIds: wpDelta.receivedTailIds };
|
||||
log("debug", `[${session.id}] fastpath ${wpOutcome.decision} T=${wpDelta.hit.totalT}`);
|
||||
} else {
|
||||
wpOutcome = evaluateWatermarkFastpath(bodyText, req, session, { pluginMode, titleGen: isTitleGen, model: wpModel }, log);
|
||||
log("debug", `[${session.id}] fastpath ${wpOutcome.hit ? "HIT" : wpOutcome.decision}${wpOutcome.creditedMiss ? "(credited)" : ""}${wpOutcome.measuredT !== undefined ? ` T=${wpOutcome.measuredT}` : ""}`);
|
||||
}
|
||||
if (wpOutcome.hit) {
|
||||
wpHit = wpOutcome.hit;
|
||||
// #6752: handle.ts already ran restoreOutputBudget on `parsed` —
|
||||
|
||||
+127
-1
@@ -7,7 +7,7 @@ import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import http from "node:http";
|
||||
import { openaiToCore, coreToOpenai } from "acp-kernel/wire";
|
||||
import { evaluateWatermarkFastpath, finalizeWatermarkTurn, clearWatermarkSeed, watermarkDebugState, PF_COUNT_HEADER, PF_SEQ_HEADER, PF_TAIL_IDS_HEADER, PF_SLOT_UNKNOWN } from "../src/server/fastpath.ts";
|
||||
import { evaluateWatermarkFastpath, evaluateDeltaResend, finalizeWatermarkTurn, clearWatermarkSeed, watermarkDebugState, PF_COUNT_HEADER, PF_SEQ_HEADER, PF_TAIL_IDS_HEADER, PF_DELTA_HEADER, PF_SLOT_UNKNOWN } from "../src/server/fastpath.ts";
|
||||
import { stripRawStage } from "../src/marker/engine.ts";
|
||||
import { INCREMENTAL_TURN_MARKER_HEADER } from "../src/incremental-lane.ts";
|
||||
import { _setStoreForTest, _resetStoreForTest, type SessionStore } from "../src/persist.ts";
|
||||
@@ -536,3 +536,129 @@ test("pinned (2x2) steady state still HITS — host-id stash must not break the
|
||||
assert.equal(t4.out.creditedMiss, false);
|
||||
_resetStoreForTest();
|
||||
});
|
||||
|
||||
// #5403 family, delta arm (x-bili-pf-delta): the body carries ONLY the tail
|
||||
// slice [T-L .. T-1] (anchor = the previous turn's last element), the full
|
||||
// logical count rides x-bili-pf-count, per-element ids ride x-bili-pf-tail-ids
|
||||
// (width exactly L). A satisfiable claim yields the SAME FastpathHit the
|
||||
// full-body lane would — every assertion is against the legacy full-parse
|
||||
// oracle over the WHOLE logical body. An unsatisfiable claim is a re-anchor
|
||||
// (the 400 the client answers with a full-form resend).
|
||||
|
||||
const dTail = (n: number): string[] => Array.from({ length: n }, (_, i) => `dhost-${i}`);
|
||||
|
||||
const runDeltaTurn = (
|
||||
session: Session,
|
||||
reqHeaders: Record<string, string>,
|
||||
sliceMessages: unknown[],
|
||||
model = "m1",
|
||||
): { verdict: { hit: import("../src/server/fastpath.ts").FastpathHit; receivedTailIds?: string[] }; headers: Record<string, string> } => {
|
||||
const bodyText = bodyOf(sliceMessages, model);
|
||||
const verdict = evaluateDeltaResend(JSON.parse(bodyText) as Parameters<typeof evaluateDeltaResend>[0], bodyText, headersOf(reqHeaders), session, { pluginMode: true, titleGen: false, model }, log);
|
||||
assert.ok(verdict !== null && "hit" in verdict, `expected a delta hit, got ${JSON.stringify(verdict)}\n${LOGS.slice(-6).join("\n")}`);
|
||||
const hit = verdict;
|
||||
const headers = finalizeWatermarkTurn(session, { hit: hit.hit, measuredT: hit.hit.totalT, decision: "delta-hit", creditedMiss: false, receivedTailIds: hit.receivedTailIds }, {
|
||||
model,
|
||||
legacyCores: hit.hit.view,
|
||||
rawSystemText: hit.hit.systemText,
|
||||
turnStripCounts: hit.hit.markerCounts,
|
||||
});
|
||||
return { verdict: hit, headers };
|
||||
};
|
||||
|
||||
test("delta arm: hit reconstructs EXACTLY the legacy full-parse oracle across consecutive slices", () => {
|
||||
makeStubStore();
|
||||
process.env.BILI_ROLLOUT_PLUGIN_DELTA_RESEND = "1";
|
||||
const session = freshSession("pf-delta-hit");
|
||||
const full: unknown[] = [SYS("s"), USR("a"), USR("b")];
|
||||
// Seed carries NO pf headers (field: the first request of a session
|
||||
// never stamps) — the first delta turn opens unverified, from then on
|
||||
// every list is chained on the previous turn's stamped last id.
|
||||
const t1 = runTurn(session, {}, bodyOf(full));
|
||||
assert.equal(t1.out.decision, "no-stamp"); // seed stampT=3
|
||||
// t2: logical T=5, L=5-3=2 -> body = NEW elements only [USR c, ASST d],
|
||||
// tail-ids = anchor(b)+new = [dhost-2, dhost-3, dhost-4]
|
||||
full.push(USR("c"), ASST("d"));
|
||||
const r2 = runDeltaTurn(session, { [PF_COUNT_HEADER]: "5", [PF_DELTA_HEADER]: "1", ...TAIL(dTail(5).slice(2)) }, full.slice(3));
|
||||
assert.equal(r2.headers[PF_SEQ_HEADER], "5");
|
||||
let oracle = openaiToCore(JSON.parse(bodyOf(full)));
|
||||
assert.deepEqual(r2.verdict.hit!.view.map((m) => String((m as { text?: unknown }).text ?? "")), oracle.msgs.map((m) => m.text), "texts");
|
||||
for (let i = 0; i < oracle.msgs.length; i++) {
|
||||
assert.equal(r2.verdict.hit!.view[i]!.id, oracle.msgs[i]!.id, `id @${i}`);
|
||||
assert.equal((r2.verdict.hit!.view[i]! as { wireIndex?: number }).wireIndex, (oracle.msgs[i]! as { wireIndex?: number }).wireIndex, `wireIndex @${i}`);
|
||||
}
|
||||
assert.equal(r2.verdict.hit!.systemText, oracle.systemText);
|
||||
assert.equal(r2.verdict.hit!.totalT, 5);
|
||||
// t3: logical T=6, L=1 -> body = [USR e], tail-ids = anchor(d)+new = [dhost-4, dhost-5]
|
||||
full.push(USR("e"));
|
||||
const r3 = runDeltaTurn(session, { [PF_COUNT_HEADER]: "6", [PF_DELTA_HEADER]: "1", ...TAIL(dTail(6).slice(4)) }, full.slice(5));
|
||||
assert.equal(r3.headers[PF_SEQ_HEADER], "6");
|
||||
oracle = openaiToCore(JSON.parse(bodyOf(full)));
|
||||
assert.deepEqual(r3.verdict.hit!.view.map((m) => String((m as { text?: unknown }).text ?? "")), oracle.msgs.map((m) => m.text), "texts after second slice");
|
||||
for (let i = 0; i < oracle.msgs.length; i++) {
|
||||
assert.equal(r3.verdict.hit!.view[i]!.id, oracle.msgs[i]!.id, `id @${i} (t3)`);
|
||||
assert.equal((r3.verdict.hit!.view[i]! as { wireIndex?: number }).wireIndex, (oracle.msgs[i]! as { wireIndex?: number }).wireIndex, `wireIndex @${i} (t3)`);
|
||||
}
|
||||
// t4: a delta turn must NOT disturb the full lane — a full-form turn right
|
||||
// after a delta hit still hits against the delta-advanced seed.
|
||||
full.push(ASST("f"));
|
||||
const t4 = runTurn(session, { [PF_COUNT_HEADER]: "6", ...TAIL(dTail(7).slice(5)) }, bodyOf(full));
|
||||
assert.equal(t4.out.decision, "hit", LOGS.slice(-6).join("\n"));
|
||||
assert.ok(t4.out.hit);
|
||||
delete process.env.BILI_ROLLOUT_PLUGIN_DELTA_RESEND;
|
||||
_resetStoreForTest();
|
||||
});
|
||||
|
||||
test("delta arm: every unsatisfiable claim re-anchors (both directions, #3617)", () => {
|
||||
makeStubStore();
|
||||
process.env.BILI_ROLLOUT_PLUGIN_DELTA_RESEND = "1";
|
||||
const session = freshSession("pf-delta-reanchor");
|
||||
const full: unknown[] = [SYS("s"), USR("a"), USR("b")];
|
||||
runTurn(session, {}, bodyOf(full)); // seed stampT=3 (no pf headers — field)
|
||||
full.push(USR("c"), ASST("d")); // logical T=5, L=2 -> body = [USR c, ASST d]
|
||||
const deltaBody = JSON.stringify({ model: "m1", stream: false, messages: full.slice(3) });
|
||||
const delta = { [PF_DELTA_HEADER]: "1", [PF_COUNT_HEADER]: "5", ...TAIL(dTail(5).slice(2)) } as Record<string, string>;
|
||||
const ev = (h: Record<string, string>, bodyText = deltaBody) =>
|
||||
evaluateDeltaResend(JSON.parse(bodyText) as Parameters<typeof evaluateDeltaResend>[0], bodyText, headersOf(h), session, { pluginMode: true, titleGen: false, model: JSON.parse(bodyText).model as string }, log);
|
||||
|
||||
// negative: no header = not a delta request (full lane owns it)
|
||||
assert.equal(ev({}), null);
|
||||
// bad header value
|
||||
assert.deepEqual(ev({ [PF_DELTA_HEADER]: "0", [PF_COUNT_HEADER]: "5" }), { reanchor: "delta-bad-value" });
|
||||
// wrong model for the seed
|
||||
assert.deepEqual(ev(delta, JSON.stringify({ model: "OTHER", stream: false, messages: full.slice(3) })), { reanchor: "model" });
|
||||
// missing count
|
||||
assert.deepEqual(ev({ [PF_DELTA_HEADER]: "1" }), { reanchor: "no-count" });
|
||||
// behind the stamp (client desynced backwards: L = T - stampT <= 0)
|
||||
assert.deepEqual(ev({ ...delta, [PF_COUNT_HEADER]: "3" }), { reanchor: "behind" });
|
||||
// window above the bound
|
||||
assert.deepEqual(ev({ ...delta, [PF_COUNT_HEADER]: String(3 + 2048 + 1) }), { reanchor: "window-too-large" });
|
||||
// body length does not match L
|
||||
assert.deepEqual(ev(delta, JSON.stringify({ model: "m1", stream: false, messages: [USR("c")] })), { reanchor: "body-length" });
|
||||
// messages not an array
|
||||
assert.deepEqual(ev(delta, JSON.stringify({ model: "m1", stream: false, messages: "oops" })), { reanchor: "body-length" });
|
||||
// tail-ids absent / wrong width / garbage
|
||||
assert.deepEqual(ev({ [PF_DELTA_HEADER]: "1", [PF_COUNT_HEADER]: "5" }), { reanchor: "tail-ids-shape" });
|
||||
assert.deepEqual(ev({ ...delta, ...TAIL(["x", "y"]) }), { reanchor: "tail-ids-shape" });
|
||||
assert.deepEqual(ev({ ...delta, [PF_TAIL_IDS_HEADER]: "a,b%2Cc%%" }), { reanchor: "tail-ids-shape" });
|
||||
// a system element riding the new slice (pre-chain: stamp still 3)
|
||||
assert.deepEqual(ev(delta, JSON.stringify({ model: "m1", stream: false, messages: [SYS("intruder"), ASST("d")] })), { reanchor: "window-system-head" });
|
||||
// anchor continuity: after a delta hit stamps a list, the NEXT list must
|
||||
// open with its last id — wrong head re-anchors (both directions #3617)
|
||||
const rChain = runDeltaTurn(session, { ...delta }, full.slice(3));
|
||||
void rChain; // stamps lastTailIds = dhost-2..4, next anchor must be dhost-4
|
||||
full.push(USR("e")); // T=6, L=1
|
||||
const delta2 = { [PF_DELTA_HEADER]: "1", [PF_COUNT_HEADER]: "6", ...TAIL(dTail(6).slice(4)) } as Record<string, string>;
|
||||
const ev2 = (h: Record<string, string>) =>
|
||||
evaluateDeltaResend({ model: "m1", stream: false, messages: [USR("e")] } as Parameters<typeof evaluateDeltaResend>[0], JSON.stringify({ model: "m1", stream: false, messages: [USR("e")] }), headersOf(h), session, { pluginMode: true, titleGen: false, model: "m1" }, log);
|
||||
assert.deepEqual(ev2({ ...delta2, ...TAIL(["WRONG", "dhost-5"]) }), { reanchor: "tail-ids-prev" });
|
||||
assert.ok("hit" in (ev2(delta2) as object), "chained head dhost-4 must pass");
|
||||
// unseeded session: a fresh id can never delta
|
||||
const cold = freshSession("pf-delta-cold");
|
||||
assert.deepEqual(evaluateDeltaResend(JSON.parse(deltaBody) as Parameters<typeof evaluateDeltaResend>[0], deltaBody, headersOf(delta), cold, { pluginMode: true, titleGen: false, model: "m1" }, log), { reanchor: "unseeded" });
|
||||
// rollout off = the rollback kill switch (LAST: it mutes every gate below it)
|
||||
process.env.BILI_ROLLOUT_PLUGIN_DELTA_RESEND = "0";
|
||||
assert.deepEqual(ev(delta), { reanchor: "rollout-off" });
|
||||
delete process.env.BILI_ROLLOUT_PLUGIN_DELTA_RESEND;
|
||||
_resetStoreForTest();
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user