From 46fabdd341b44012eff9d53f7d926a306a350005 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 3 Nov 2026 10:25:09 +0800 Subject: [PATCH 01/15] =?UTF-8?q?feat(obs):=20M1=20native=20identity=20obs?= =?UTF-8?q?ervation=20layer=20(#5571)=20=E2=80=94=20one=20choke=20point,?= =?UTF-8?q?=20five=20client=20profiles,=20digest-only=20session=20ext,=20d?= =?UTF-8?q?efault=20off?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CONFIGURATION.md | 2 + CONFIGURATION.zh-CN.md | 2 + TECHNICAL-NOTES.md | 15 + TECHNICAL-NOTES.zh-CN.md | 15 + src/rollout.ts | 9 + src/server/handle.ts | 7 + src/server/native-identity-obs.ts | 158 ++++++++++ src/server/native-identity-profiles.ts | 302 ++++++++++++++++++++ tests/issue5571-native-identity-obs.test.ts | 194 +++++++++++++ website/config-reference/rollout.yaml | 8 + 10 files changed, 712 insertions(+) create mode 100644 src/server/native-identity-obs.ts create mode 100644 src/server/native-identity-profiles.ts create mode 100644 tests/issue5571-native-identity-obs.test.ts diff --git a/CONFIGURATION.md b/CONFIGURATION.md index e244c36ae0..b0094abc72 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -102,6 +102,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `rollout.features.salt` | string | the feature name | — | Hash salt for bucketing. Changing it re-randomizes the whole cohort (the only way to reshuffle; raising percent alone never reshuffles). | | `rollout.features.base` | string | unset (roll out over everyone) | — | Nested rollout: evaluate this feature only inside the named feature's enabled cohort, so the percent is relative to that population (roll B out to A's users; chains allowed, cycles fail closed). | | `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.nativeIdentityObservation` | boolean \| number | false (off) | BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION | Native identity observation (#5571 M1, observational layer): on every model-API request bili recognizes which client family it came from (WorkBuddy / codex / Claude Code / opencode / Gemini) and records that client's NATIVE identity surface — session ids, per-message host ids, explicit compaction headers or summary-turn prefixes — into session ext key `nidv:obs` as sha1-8 DIGESTS only (raw id values never leave request memory; unknown clients write nothing). Pure collection at the single relay choke point: zero forwarded-byte changes, zero decisions, fail-open by construction. It exists to turn the #5571 client-collection table from static forensics into live measured data ahead of the M2 binding table and M3 re-baseline work. Default OFF (0%) — enable with `true` or `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION=1`. See TECHNICAL-NOTES.md "Native identity observation layer". | | `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”. | | `maskHosts` | boolean | true | BILI_LOG_MASK_HOSTS | Mask non-public target hosts in logs as ; 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. | @@ -1913,6 +1914,7 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_RESIGN_PASSTHROUGH` | `resign` | {} (armed; built-in scheme sdk-hmac-sha256) | | `BILI_RESUME_INHERITANCE` | `resumeInheritance` | true | | `BILI_ROLLOUT_` | `rollout.features.enabled` | unset (bucket math decides) | +| `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION` | `rollout.features.nativeIdentityObservation` | false (off) | | `BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK` | `rollout.features.pluginFullResendWatermark` | 5 (experimental grey) | | `BILI_ROLLOUT_PLUGIN_LANE_SERVER_HISTORY` | `rollout.features.pluginLaneServerHistory` | 0 (off) | | `BILI_SESSION_CONTENT_STORE_PIN` | `sessions.contentStorePin` | false | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index a5853ccbf0..c09241bddb 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -102,6 +102,7 @@ | `rollout.features.salt` | string | the feature name | — | 分桶哈希盐。修改它会重新随机整个分组(唯一的洗牌方式;仅上调 percent 永不洗牌)。 | | `rollout.features.base` | string | unset (roll out over everyone) | — | 嵌套灰度:仅在所指特性的已入组人群内评估本特性,percent 相对该人群(B 只放量给 A 的用户;允许链式,环路判为关)。 | | `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.nativeIdentityObservation` | boolean \| number | false(关) | BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION | 原生身份观测层(#5571 M1):每条模型 API 请求到达时,bili 识别它来自哪个客户端家族(WorkBuddy / codex / Claude Code / opencode / Gemini),并把该客户端的原生身份面——session id、逐条消息宿主 id、显式压缩头或摘要轮前缀——以 sha1-8 摘要形式记入 session ext 键 `nidv:obs`(原始 id 值不落盘、不出请求内存;unknown 客户端不写任何值)。纯采集,位于 relay 单点咽喉:零转发字节改动、零决策、结构性 fail-open。目的是在 M2 绑定表与 M3 re-baseline 开工前,把 #5571 客户端采集表从静态取证变成实测数据。默认关(0%),`true` 或 `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION=1` 开启。见 TECHNICAL-NOTES.zh-CN.md「原生身份观测层」。 | | `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「全量重发水位快路径」。 | | `maskHosts` | boolean | true | BILI_LOG_MASK_HOSTS | 日志中把非公开目标主机遮成 ;凭据头无论此开关如何总是遮盖。 | | `security.adminRelay` | boolean | false | — | 允许宿主(当前为 dsh web)把它自己入口域名下的整个 /__bili/ 管理面中继到本机代理,使远程浏览器能打开面板(#3373)。默认关闭、仅配置文件。中继跳到达代理时是本机非浏览器客户端(回环源地址 + 回环 Host、无 Origin 头),管理端门槛不变;开启后,凡能访问宿主 web 入口的人都能改配置、写凭据——请先给入口加鉴权/反代。 | @@ -1896,6 +1897,7 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 | `BILI_RESIGN_PASSTHROUGH` | `resign` | {} (armed; built-in scheme sdk-hmac-sha256) | | `BILI_RESUME_INHERITANCE` | `resumeInheritance` | true | | `BILI_ROLLOUT_` | `rollout.features.enabled` | unset (bucket math decides) | +| `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION` | `rollout.features.nativeIdentityObservation` | false (off) | | `BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK` | `rollout.features.pluginFullResendWatermark` | 5 (experimental grey) | | `BILI_ROLLOUT_PLUGIN_LANE_SERVER_HISTORY` | `rollout.features.pluginLaneServerHistory` | 0 (off) | | `BILI_SESSION_CONTENT_STORE_PIN` | `sessions.contentStorePin` | false | diff --git a/TECHNICAL-NOTES.md b/TECHNICAL-NOTES.md index 29b4d98feb..10b3e2c342 100644 --- a/TECHNICAL-NOTES.md +++ b/TECHNICAL-NOTES.md @@ -587,3 +587,18 @@ 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). + +## Native identity observation layer (#5571 M1) + +Every model-API request passing bili carries its client's NATIVE identity surface — session ids, per-message host ids, compaction markers — as plain headers/body fields, visible at the relay before any rewrite. The observation layer turns that static forensics (issue #5571 collection table) into live per-session data so the M2 binding table and M3 re-baseline work start from measured facts instead of binary strings. + +**One call site, one profile table.** `observeNativeIdentity()` is invoked exactly once per request, at `src/server/handle.ts` right after session-id binding (`enterSessionContext`). Client families are pinned in `src/server/native-identity-profiles.ts` (WorkBuddy / codex / Claude Code / opencode / Gemini rows: session/message/request headers, dual-channel body paths, compaction prefixes, shape assertions). Compaction wording is a client-version surface — when it drifts upstream, fix the row + tests there, never hard-code literals elsewhere. + +**Invariants (the red lines):** +- Zero forwarded-byte changes — the module only READS; nothing downstream may gate on this data until M2/M3 decide otherwise. +- Privacy: session ext (`nidv:obs`) stores sha1-8 DIGESTS of id values only; raw values live in request memory for microseconds; logs print digests/truncations. +- Unknown clients write NOTHING (privacy redline: we do not fingerprint arbitrary strangers' traffic into storage). +- Default OFF: `rollout.features.nativeIdentityObservation`, percent 0 (env `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION=1|0`, config `true/false`). Off ⇒ zero ext writes, byte-identical pipeline — pinned by golden-suite neutrality (feature absent for existing cohorts) plus explicit off-test in `tests/issue5571-native-identity-obs.test.ts`. +- Fail-open by construction: the whole collection sits in one try/catch inside the function; any broken profile row degrades to "no observation", never to a failed or slowed request (constant-cost lookups + bounded body walks only — `USER_TEXT_SCAN_CAP=3`, `TOOL_ANCHOR_CAP=4096`). + +**State shape** (`nidv:obs`, JSON ≤4KB hard cap via FIFO-trimmed events): `{v:1, client, firstSeen, lastSeen, reqs, sessH?, sessStable, msgN?, msgLastH?, events:[{t,k,e≤64}]}`. Event kinds: `compaction` (three signal classes — explicit header > dedicated `/responses/compact` endpoint > summary-turn PREFIX anchored at text START, mid-text copies must not fire), `id_change`, `profile_flip`, `dual_mismatch` (cc header vs metadata channel disagree), `shape_assert_fail` (opencode wire shape drift). Consecutive identical events dedupe; max 32 kept. diff --git a/TECHNICAL-NOTES.zh-CN.md b/TECHNICAL-NOTES.zh-CN.md index d5ea5b5d97..1238f933a2 100644 --- a/TECHNICAL-NOTES.zh-CN.md +++ b/TECHNICAL-NOTES.zh-CN.md @@ -164,3 +164,18 @@ 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`(门矩阵,双向)。 + +## 原生身份观测层(#5571 M1) + +每条经过 bili 的模型 API 请求都自带其客户端的**原生身份面**——session id、逐条消息宿主 id、压缩标记——以普通头/正文字段形式,在 relay 任何改写之前就可读。观测层把这份静态取证(issue #5571 采集表)变成按会话的实测数据,让 M2 绑定表与 M3 re-baseline 建立在测量事实而非二进制字符串之上。 + +**单采集点,单张模式表。** `observeNativeIdentity()` 每请求恰好调用一次,位于 `src/server/handle.ts` 会话 id 绑定(`enterSessionContext`)之后。客户端家族钉在 `src/server/native-identity-profiles.ts`(WorkBuddy / codex / Claude Code / opencode / Gemini 五行:session/msg/request 头、双通道 body 路径、压缩前缀、形状断言)。压缩文案是客户端版本面——上游漂移时改这张表+测试,禁止在别处硬编码字面量。 + +**不变量(红线):** +- 零转发字节改动——本模块只读;M2/M3 决定之前,下游任何逻辑不得基于这些数据做 gate。 +- 隐私:session ext 键 `nidv:obs` 只存 id 值的 sha1-8 **摘要**;原始值只在请求内存里活几微秒;日志打摘要/截断。 +- unknown 客户端**不写任何东西**(隐私红线:不把陌生流量的指纹存进存储)。 +- 默认关:`rollout.features.nativeIdentityObservation`,percent 0(env `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION=1|0`;配置 `true/false`)。关 = 零 ext 写入、管线字节一致——由既有 golden 套件的无感中性(对现有队列特性缺席)加 `tests/issue5571-native-identity-obs.test.ts` 显式 off 用例共同钉住。 +- 结构性 fail-open:全部采集在函数内一个 try/catch 里;任何坏行降级为「无观测」,绝不会失败或拖慢请求(常数成本查找 + 有界正文扫描——`USER_TEXT_SCAN_CAP=3`、`TOOL_ANCHOR_CAP=4096`)。 + +**状态形状**(`nidv:obs`,JSON ≤4KB 硬上限,事件 FIFO 裁剪):`{v:1, client, firstSeen, lastSeen, reqs, sessH?, sessStable, msgN?, msgLastH?, events:[{t,k,e≤64}]}`。事件类型:`compaction`(三级信号——显式头 > 专用 `/responses/compact` 端点 > 摘要轮前缀[锚定在文本开头,中段嵌入不得命中])、`id_change`、`profile_flip`、`dual_mismatch`(cc 头 vs metadata 通道不一致)、`shape_assert_fail`(opencode wire 形状漂移)。连续相同事件去重,最多保 32 条。 diff --git a/src/rollout.ts b/src/rollout.ts index adb1a85157..3621170274 100644 --- a/src/rollout.ts +++ b/src/rollout.ts @@ -97,6 +97,15 @@ export const ROLLOUT_FEATURES: Record = { // cohorts (compressed vs deleted) and detects generation switches. // Default 0% — force on with `BILI_ROLLOUT_PLUGIN_LANE_SERVER_HISTORY=1`. pluginLaneServerHistory: { percent: 0 }, + // #5571 M1 native identity observation: collect each model-API client's + // native identity surface (session/message ids as headers/body fields) and + // its re-baseline signals into session ext "nidv:obs" (sha1-8 digests + // only), behind one choke point in handle.ts. PURE OBSERVATION — zero + // forwarded-byte changes, zero decisions, fail-open, default OFF. + // Feeds M2 binding table / M3 re-baseline. Force on with + // `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION=1` or + // `rollout.features.nativeIdentityObservation: true`. + nativeIdentityObservation: { percent: 0 }, }; export const BP_MAX = 10_000; diff --git a/src/server/handle.ts b/src/server/handle.ts index 44a5c738df..f318bf2ed9 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -64,6 +64,7 @@ import { prepareOpenai } from "./prepare-openai.js"; import { prepareGoogle, prepareGoogleCountTokens } from "./prepare-google.js"; import { DUMP_PLAINTEXT_BANNER } from "../dump-banner.js"; import { prepareResponses, prepareResponsesCompact } from "./prepare-responses.js"; +import { observeNativeIdentity } from "./native-identity-obs.js"; import { bodyDumpEnabled, isModelDiscoveryPath, isV1InternalControlPlanePath, logDumpFailure, logUnrecognizedPath } from "./observability.js"; import { yieldToEventLoop } from "../yield-loop.js"; import { adminGateDenial, handleAdminRoute, isManagementPath } from "./admin.js"; @@ -1355,6 +1356,12 @@ async function handleRequest( // embed the id manually. One statement, runs in this request's own // async context, so concurrent requests never cross-contaminate. enterSessionContext(sessionId); + // #5571 M1: native identity observation — pure collection (profiles in + // src/server/native-identity-profiles.ts), fail-open inside, default + // OFF (rollout.features.nativeIdentityObservation / percent 0). + // Zero forwarded-byte changes; persists only digests under ext key + // "nidv:obs". Must never affect the request below. + observeNativeIdentity({ sessionId, headers: req.headers, urlPath, protocol, bodyText, parsedBody: parsed, log }); // #1086/#1357: content-fallback chain observation, now that identity is known. // Artifacts + processed local state ⇒ self-produced: process normally. // Artifacts + NO local state ⇒ ADVISORY observation (#1357 Phase 1): the diff --git a/src/server/native-identity-obs.ts b/src/server/native-identity-obs.ts new file mode 100644 index 0000000000..567cfc2a95 --- /dev/null +++ b/src/server/native-identity-obs.ts @@ -0,0 +1,158 @@ +// #5571 M1 (observation layer): per-session native identity state + the +// fail-open collection call. +// +// Red lines (see issue #5571 M1 design): +// - zero forwarded-byte changes: this module reads only; +// - zero decisions: nothing downstream may gate on this data until M2/M3; +// - privacy: session ext stores sha1-8 digests of id values, never raw ids; +// logs print digests/truncations only; +// - default OFF (rollout.features.nativeIdentityObservation, percent 0); +// - unknown clients leave NO ext values at all (count-only, see profiles); +// - size hygiene: the whole ext blob is hard-capped (events FIFO-trimmed), +// same discipline as the gc-vacuum era. +import crypto from "node:crypto"; +import { featureEnabled } from "../rollout.js"; +import { getStore } from "../persist.js"; +import { detectNativeProfile, extractNativeIdentity, type NidvObservation, type NidvClientId } from "./native-identity-profiles.js"; + +export const NIDV_EXT_KEY = "nidv:obs"; +const MAX_JSON_BYTES = 4096; +const MAX_EVENTS = 32; +const EV_TEXT_CAP = 64; + +export interface NidvEvent { + t: number; + /** compaction | id_change | profile_flip | dual_mismatch | shape_assert_fail */ + k: string; + /** ≤64 chars of evidence (prefix text / header name / marker). */ + e: string; +} + +export interface NidvState { + v: 1; + client: NidvClientId; + firstSeen: number; + lastSeen: number; + reqs: number; + sessH?: string; + sessStable: "unknown" | "yes" | "no"; + msgN?: number; + msgLastH?: string; + events: NidvEvent[]; +} + +/** sha1 first 8 hex — digest form stored in ext / printed in logs. */ +export function nidvH8(value: string): string { + return crypto.createHash("sha1").update(value, "utf8").digest("hex").slice(0, 8); +} + +/** Pure state transition: fold one request observation into prior state. + * Unit-tested directly (stability matrix incl. restart continuity). */ +export function mergeNidvState(prev: NidvState | null, obs: NidvObservation, now: number): NidvState { + const next: NidvState = prev + ? { ...prev, events: [...prev.events] } + : { v: 1, client: obs.profileId, firstSeen: now, lastSeen: now, reqs: 0, sessStable: "unknown", events: [] }; + next.lastSeen = now; + next.reqs += 1; + const pushEvent = (k: string, e: string) => { + const ev: NidvEvent = { t: now, k, e: e.slice(0, EV_TEXT_CAP) }; + const last = next.events[next.events.length - 1]; + if (last && last.k === k && last.e === ev.e) return; // consecutive dedupe + next.events.push(ev); + while (next.events.length > MAX_EVENTS) next.events.shift(); + }; + + if (obs.profileId !== next.client) { + // Client family changed under one bili session id — incident class. + pushEvent("profile_flip", `${next.client}->${obs.profileId}`); + next.client = obs.profileId; + } + + // Session channel stability (same-value repeats → yes, any change → no). + if (typeof obs.sessVal === "string") { + const h = nidvH8(obs.sessVal); + if (next.sessH === undefined) { + next.sessH = h; + next.sessStable = "yes"; // single sighting: assume stable until proven otherwise + } else if (h !== next.sessH) { + next.sessH = h; + next.sessStable = "no"; + pushEvent("id_change", `sess ${h}`); + } + } + // Cross-channel verification (cc metadata vs header). + if (typeof obs.dualBodySessVal === "string" && typeof obs.sessVal === "string") { + if (nidvH8(obs.dualBodySessVal) !== nidvH8(obs.sessVal)) pushEvent("dual_mismatch", obs.dualBodySessVal.slice(0, EV_TEXT_CAP)); + } + // Message-level host id (wb today): per-request id changes every turn by + // design — we track LAST value + sighting count; M2's binding table turns + // this into the tail slot. + if (typeof obs.msgVal === "string") { + const h = nidvH8(obs.msgVal); + next.msgN = (next.msgN ?? 0) + 1; + next.msgLastH = h; + } + // Re-baseline signals — the core M3 data asset starts here. + if (obs.compactionSignal) pushEvent("compaction", `${obs.compactionSignal}:${obs.compactionEvidence ?? ""}`); + if (obs.shapeAssertFail) pushEvent("shape_assert_fail", obs.shapeAssertFail); + + // Hard size budget: trim oldest events until the blob fits. + while (JSON.stringify(next).length > MAX_JSON_BYTES && next.events.length > 1) next.events.shift(); + return next; +} + +/** Minimal structural store view — production callers pass nothing (module + * singleton via getStore()); tests inject a duck to exercise the write path + * without a real sidecar. */ +export interface NidvStoreView { + replicasAvailable(): boolean; + getSessionExt(sessionId: string, key: string): unknown; + setSessionExt(sessionId: string, key: string, value: unknown): void; +} + +export interface ObserveNativeIdentityArgs { + sessionId: string; + headers: Record; + urlPath: string; + protocol: string | null; + bodyText?: string; + parsedBody?: unknown; + log: (level: string, msg: string) => void; + /** Test seam: force on/off regardless of rollout (undefined = read flag). */ + enabled?: boolean; + /** Test seam: storage view override (undefined = module singleton). */ + store?: NidvStoreView; +} + +/** Single observation call site target (wired at src/server/handle.ts after + * sessionId binding). Synchronous, fail-open, default off. Must never throw + * into the request path. */ +export function observeNativeIdentity(args: ObserveNativeIdentityArgs): void { + try { + if (!args.sessionId) return; + const enabled = args.enabled ?? featureEnabled("nativeIdentityObservation"); + if (!enabled) return; // off = ZERO writes, byte-identical pipeline + const store = args.store ?? getStore(); + if (!store.replicasAvailable()) return; + const profile = detectNativeProfile(args.headers, args.urlPath, args.protocol); + const obs = extractNativeIdentity(profile, args.headers, args.urlPath, args.protocol, args.parsedBody, args.bodyText); + if (profile.id === "unknown") return; // privacy redline: no values for unknown clients + const prevRaw = store.getSessionExt(args.sessionId, NIDV_EXT_KEY); + let prev: NidvState | null = null; + if (typeof prevRaw === "string" && prevRaw.length > 0) { + try { + const p = JSON.parse(prevRaw) as NidvState; + if (p && p.v === 1 && Array.isArray(p.events)) prev = p; + } catch { /* corrupt prev: rebuild fresh */ } + } + const next = mergeNidvState(prev, obs, Date.now()); + store.setSessionExt(args.sessionId, NIDV_EXT_KEY, JSON.stringify(next)); + const evtPart = obs.compactionSignal ? ` evt=compaction(${obs.compactionSignal}:${obs.compactionEvidence ?? ""})` : ""; + args.log( + obs.compactionSignal ? "warn" : "debug", + `nidv: client=${next.client} sess=${next.sessH ?? "-"} reqs=${next.reqs}${evtPart}`, + ); + } catch { + /* fail-open: observation must never affect the request below it */ + } +} diff --git a/src/server/native-identity-profiles.ts b/src/server/native-identity-profiles.ts new file mode 100644 index 0000000000..4a93cbc399 --- /dev/null +++ b/src/server/native-identity-profiles.ts @@ -0,0 +1,302 @@ +// #5571 M1 (observation layer): native identity profile table for model-API +// clients. +// +// bili relays traffic from heterogeneous agent clients. Each client exposes +// its own native identity surface (session/message ids as headers or body +// fields) and its re-baseline signals (explicit compaction headers vs summary +// user-turn prefixes) on the wire. This table pins those facts per client so +// the observation layer (#5571 M1), the binding layer (M2 tail slot) and the +// re-baseline layer (M3) share ONE source instead of ad-hoc string checks. +// +// Provenance: binary forensics + local sample capture 2026-11-02/03 — issue +// #5571 collection table (WorkBuddy dsh / codex 0.147.0 / Claude Code / +// opencode 1.14.42 / Gemini CLI 0.3.66). The compaction prefix WORDING is a +// client-version surface: it may drift upstream. When that happens, fix the +// row here (+ unit tests) — do not hard-code literals anywhere else. +export type NidvClientId = "wb" | "codex" | "cc" | "opencode" | "gemini" | "unknown"; + +export interface NidvProfile { + readonly id: NidvClientId; + /** Header carrying the SESSION id (lowercase name). */ + readonly sessHeader?: string; + /** Header carrying a PER-MESSAGE host id (strongest future tail-slot signal). */ + readonly msgHeader?: string; + /** Header carrying a PER-REQUEST id. */ + readonly reqHeader?: string; + /** Fork/lineage header. */ + readonly parentHeader?: string; + /** Additional headers to capture — dynamic-capture items, spelling TBC. */ + readonly extraHeaders?: readonly string[]; + /** Body JSON paths for session-id cross-channel verification. */ + readonly bodySessPaths?: ReadonlyArray; + /** User-turn text prefixes marking a client-side re-baseline (compaction). */ + readonly compactionPrefixes?: readonly string[]; + /** Explicit compaction indicator headers (presence = signal, strongest class). */ + readonly compactionHeaders?: readonly string[]; + /** URL path suffixes naming a dedicated compaction endpoint. */ + readonly compactPathSuffixes?: readonly string[]; + /** Marker substrings that must NOT appear in the request body + * (shape assertion; presence = protocol-drift event, never fatal here). */ + readonly shapeAssertAbsent?: readonly string[]; +} + +export type NidvCompactionSignal = "explicit-header" | "prefix-match" | "compact-endpoint" | null; + +/** Per-request extraction result. Raw values live in MEMORY ONLY for the + * lifetime of this call — persistence stores sha1 digests (h8), logs never + * print full values. */ +export interface NidvObservation { + profileId: NidvClientId; + /** Session id as seen on the primary channel (header or body path). */ + sessVal?: string; + /** Cross-channel session value (e.g. cc metadata.user_id.session_id). */ + dualBodySessVal?: string; + /** Per-message host id (wb only today). */ + msgVal?: string; + /** Per-request id. */ + reqVal?: string; + /** Fork/lineage marker (opencode x-parent-session-id, codex x-codex-parent-thread-id). */ + parentVal?: string; + /** Count of intra-message tool anchors (cc `toolu_` occurrences; capped). */ + toolAnchorCount?: number; + compactionSignal: NidvCompactionSignal; + /** Which rule fired (header name / prefix text / suffix) — ≤64 chars. */ + compactionEvidence?: string; + /** Shape assertion failure: marker that wrongly appeared in the body. */ + shapeAssertFail?: string; +} + +const WB: NidvProfile = { + id: "wb", + sessHeader: "x-conversation-id", + msgHeader: "x-conversation-message-id", + reqHeader: "x-request-id", + // Strongest re-baseline class in the fleet: explicit headers. + compactionHeaders: ["x-compacted", "x-context-compacted"], +}; + +const CODEX: NidvProfile = { + id: "codex", + // Installation id is stable per machine (file ~/.codex/installation_id); + // the thread/window header spellings are FORENSIC GUESSES pending a live + // capture — capture them all when present, do not filter on them yet. + extraHeaders: [ + "x-codex-installation-id", + "x-client-request-id", + "x-codex-window-id", + "x-codex-turn-metadata", + "x-codex-parent-thread-id", + "x-openai-subagent", + ], + parentHeader: "x-codex-parent-thread-id", + // Re-baseline: fixed lead sentence prepended after a local compact, plus + // the dedicated server endpoint POST /responses/compact. + compactionPrefixes: ["Another language model started to solve this problem"], + compactPathSuffixes: ["/responses/compact"], +}; + +const CC: NidvProfile = { + id: "cc", + sessHeader: "x-claude-code-session-id", + // Dual channel: metadata.user_id carries the same session id — encoded + // either as a JSON STRING ("{\"session_id\":...}") or as a plain object, + // depending on dialect/version. Path stops at user_id; extraction below + // handles both encodings. Disagreement with the header is an incident + // event, not a fallback. + bodySessPaths: [["metadata", "user_id"]], + compactionPrefixes: ["This session is being continued from a previous conversation"], +}; + +const OPENCODE: NidvProfile = { + id: "opencode", + sessHeader: "x-session-affinity", + parentHeader: "x-parent-session-id", + compactionPrefixes: ["What did we do so far?", ""], + // Research asserts ZERO message ids on the OpenAI-compatible wire; a + // non-zero count means upstream changed its wire shape. + shapeAssertAbsent: ["ses_", "msg_", "prt_"], +}; + +const GEMINI: NidvProfile = { + // Generic path exposes no ids at all — the observation IS the absence. + id: "gemini", + compactionPrefixes: [""], +}; + +const UNKNOWN: NidvProfile = { id: "unknown" }; + +function firstHeader(headers: Record, name: string): string | undefined { + const raw = headers[name]; + if (typeof raw === "string") return raw.length > 0 ? raw : undefined; + if (Array.isArray(raw) && typeof raw[0] === "string" && (raw[0] as string).length > 0) return raw[0] as string; + return undefined; +} + +/** Deterministic profile detection. Order matters and is pinned by tests: + * explicit per-client session headers outrank family markers, which outrank + * protocol inference. Never throws on odd inputs. */ +export function detectNativeProfile( + headers: Record, + urlPath: string, + protocol: string | null, +): NidvProfile { + void urlPath; // reserved for path-based markers (none needed at launch) + if (WB.sessHeader && firstHeader(headers, WB.sessHeader)) return WB; + if (CC.sessHeader && firstHeader(headers, CC.sessHeader)) return CC; + if (OPENCODE.sessHeader && firstHeader(headers, OPENCODE.sessHeader)) return OPENCODE; + if (firstHeader(headers, "x-codex-installation-id")) return CODEX; + if (protocol === "responses" && firstHeader(headers, "x-client-request-id")) return CODEX; + if (protocol === "google") return GEMINI; + return UNKNOWN; +} + +function walkPath(body: unknown, path: readonly (string | number)[]): unknown { + let cur: unknown = body; + for (const key of path) { + if (cur === null || typeof cur !== "object") return undefined; + cur = (cur as Record)[key]; + } + return cur; +} + +/** Up to this many leading user texts are scanned for compaction prefixes — + * bounds cost on megabyte bodies while covering the real shape (the summary + * turn always sits near the head after a re-baseline). */ +const USER_TEXT_SCAN_CAP = 3; +/** Max counted `toolu_` occurrences before we stop counting (value is an + * observation, not a ledger — capping is harmless). */ +const TOOL_ANCHOR_CAP = 4096; + +function extractUserTexts(parsedBody: unknown, protocol: string | null, cap: number): string[] { + const out: string[] = []; + if (!parsedBody || typeof parsedBody !== "object") return out; + const b = parsedBody as Record; + const arr = protocol === "responses" ? b.input : b.messages; + if (!Array.isArray(arr)) return out; + for (const el of arr) { + if (!el || typeof el !== "object") continue; + const m = el as Record; + let text: unknown; + if (protocol === "responses") { + if (m.type !== "message" || m.role !== "user" || !Array.isArray(m.content)) continue; + text = (m.content as Record[]).map((c) => (typeof c?.text === "string" ? c.text : "")).join(""); + } else { + if (m.role !== "user") continue; + if (typeof m.content === "string") text = m.content; + else if (Array.isArray(m.content)) text = (m.content as Record[]).map((c) => (typeof c?.text === "string" ? c.text : "")).join(""); + else continue; + } + out.push(typeof text === "string" ? text : ""); + if (out.length >= cap) break; + } + return out; +} + +function countOccurrences(haystack: string, needle: string, cap: number): number { + let n = 0; + let i = haystack.indexOf(needle); + while (i !== -1 && n < cap) { + n += 1; + i = haystack.indexOf(needle, i + needle.length); + } + return n; +} + +/** Pure per-request extraction. Total cost: a constant number of header + * lookups + bounded body walks; on a 1MB body well under a millisecond. + * Never throws. */ +export function extractNativeIdentity( + profile: NidvProfile, + headers: Record, + urlPath: string, + protocol: string | null, + parsedBody: unknown, + bodyText: string | undefined, +): NidvObservation { + const obs: NidvObservation = { profileId: profile.id, compactionSignal: null }; + try { + if (profile.id !== "unknown") { + if (profile.sessHeader) obs.sessVal = firstHeader(headers, profile.sessHeader); + if (profile.msgHeader) obs.msgVal = firstHeader(headers, profile.msgHeader); + if (profile.reqHeader) obs.reqVal = firstHeader(headers, profile.reqHeader); + if (profile.parentHeader) obs.parentVal = firstHeader(headers, profile.parentHeader); + for (const p of profile.bodySessPaths ?? []) { + const v = walkPath(parsedBody, p); + if (typeof v === "string" && v.length > 0) { + if (v.startsWith("{")) { + try { + const inner = (JSON.parse(v) as Record)?.session_id; + if (typeof inner === "string" && inner) obs.dualBodySessVal = inner; + } catch { /* malformed dual channel: ignore, header stands alone */ } + } else { + obs.dualBodySessVal = v; + } + break; + } + if (v !== null && typeof v === "object") { + const sid = (v as Record).session_id; + if (typeof sid === "string" && sid.length > 0) { obs.dualBodySessVal = sid; break; } + } + } + } + + // Re-baseline signal class 1 (strongest): explicit compaction header. + for (const h of profile.compactionHeaders ?? []) { + if (firstHeader(headers, h)) { + obs.compactionSignal = "explicit-header"; + obs.compactionEvidence = h; + return obs; + } + } + // Class 2: dedicated compaction endpoint on the path. + if (obs.compactionSignal === null) { + for (const suf of profile.compactPathSuffixes ?? []) { + if (urlPath.toLowerCase().endsWith(suf)) { + obs.compactionSignal = "compact-endpoint"; + obs.compactionEvidence = suf; + return obs; + } + } + } + // Class 3: summary user-turn PREFIX — anchored at text START only. A + // copy of the wording embedded mid-text must NOT fire (adversarial + // case pinned by tests). + if (obs.compactionSignal === null && profile.compactionPrefixes && profile.compactionPrefixes.length > 0) { + for (const text of extractUserTexts(parsedBody, protocol, USER_TEXT_SCAN_CAP)) { + if (!text) continue; + for (const pref of profile.compactionPrefixes) { + if (text.startsWith(pref)) { + obs.compactionSignal = "prefix-match"; + obs.compactionEvidence = pref.slice(0, 64); + break; + } + } + if (obs.compactionSignal !== null) break; + } + } + + // Client-specific assertions/counters. + if (profile.id === "cc" && typeof bodyText === "string") { + obs.toolAnchorCount = countOccurrences(bodyText, '"toolu_', TOOL_ANCHOR_CAP); + } + if (profile.shapeAssertAbsent && typeof bodyText === "string") { + for (const marker of profile.shapeAssertAbsent) { + if (bodyText.includes(marker)) { + obs.shapeAssertFail = marker; + break; + } + } + } + } catch { + // Fail-open by construction: a broken profile row degrades to "no + // observation", never to a failed request. + obs.profileId = profile.id === "unknown" ? "unknown" : obs.profileId; + obs.compactionSignal = obs.compactionSignal ?? null; + } + return obs; +} + +/** Header view kept intentionally structural (not node:http-typed) so tests + * can feed plain objects and handle.ts can pass req.headers directly — + * IncomingHttpHeaders is structurally assignable to Record. */ +export type NidvHeaders = Record; diff --git a/tests/issue5571-native-identity-obs.test.ts b/tests/issue5571-native-identity-obs.test.ts new file mode 100644 index 0000000000..db6a056228 --- /dev/null +++ b/tests/issue5571-native-identity-obs.test.ts @@ -0,0 +1,194 @@ +// #5571 M1 — native identity observation layer: profiles table extraction, +// stability state machine, and the fail-open collection call. +import assert from "node:assert/strict"; +import test from "node:test"; +import { detectNativeProfile, extractNativeIdentity } from "../src/server/native-identity-profiles.ts"; +import { mergeNidvState, nidvH8, observeNativeIdentity, NIDV_EXT_KEY } from "../src/server/native-identity-obs.ts"; + +const NOOP_LOG = () => { }; +type Logged = { level: string; msg: string }; +function spyLog(): { log: (level: string, msg: string) => void; lines: Logged[] } { + const lines: Logged[] = []; + return { log: (level, msg) => lines.push({ level, msg }), lines }; +} + +interface DuckStore { + replicas: boolean; + ext: Map; + reads: number; + writes: number; +} +function duckStore(replicas = true): DuckStore { + const d: DuckStore = { replicas, ext: new Map(), reads: 0, writes: 0 }; + return d; +} +function toView(d: DuckStore): Parameters[0]["store"] { + return { + replicasAvailable: () => d.replicas, + getSessionExt: (sid, key) => { d.reads += 1; return d.ext.get(`${sid}\x00${key}`) ?? null; }, + setSessionExt: (sid, key, value) => { d.writes += 1; d.ext.set(`${sid}\x00${key}`, String(value)); }, + }; +} + +const WB_HDRS = { "x-conversation-id": "conv-abc", "x-conversation-message-id": "m-42", "x-request-id": "r-7" }; +const CODEX_BODY_PREFIX = { input: [{ type: "message", role: "user", content: [{ text: "Another language model started to solve this problem and produced a summary. Here it is…" }] }] }; +const CC_BODY_MATCH = { metadata: { user_id: JSON.stringify({ session_id: "cc-sess-1" }) }, messages: [] }; +const CC_BODY_MISMATCH = { metadata: { user_id: JSON.stringify({ session_id: "cc-sess-OTHER" }) }, messages: [] }; +const CC_BODY_OBJECT_DIALECT = { metadata: { user_id: { session_id: "cc-sess-1" } }, messages: [] }; + +test("profile detection: order pinned (wb > cc > opencode > codex > gemini > unknown)", () => { + assert.equal(detectNativeProfile(WB_HDRS, "/v1/chat/completions", "openai").id, "wb"); + assert.equal(detectNativeProfile({ "x-claude-code-session-id": "s" }, "/v1/messages", "anthropic").id, "cc"); + assert.equal(detectNativeProfile({ "x-session-affinity": "ses_1" }, "/v1/chat/completions", "openai").id, "opencode"); + assert.equal(detectNativeProfile({ "x-codex-installation-id": "i" }, "/v1/responses", "responses").id, "codex"); + // codex fallback rule: responses protocol + x-client-request-id alone + assert.equal(detectNativeProfile({ "x-client-request-id": "x" }, "/v1/responses", "responses").id, "codex"); + assert.equal(detectNativeProfile({}, "/v1beta/models/m:generateContent", "google").id, "gemini"); + assert.equal(detectNativeProfile({ "x-random": "1" }, "/v1/chat/completions", "openai").id, "unknown"); + // a header that only matters on the responses wire must NOT leak to cc traffic + assert.equal(detectNativeProfile({ "x-client-request-id": "x" }, "/v1/messages", "anthropic").id, "unknown"); +}); + +test("wb: header ids extracted + explicit compaction header is strongest signal", () => { + const p = detectNativeProfile(WB_HDRS, "/v1/chat/completions", "openai"); + let obs = extractNativeIdentity(p, WB_HDRS, "/v1/chat/completions", "openai", {}, undefined); + assert.equal(obs.sessVal, "conv-abc"); + assert.equal(obs.msgVal, "m-42"); + assert.equal(obs.reqVal, "r-7"); + assert.equal(obs.compactionSignal, null); + obs = extractNativeIdentity(p, { ...WB_HDRS, "x-context-compacted": "1" }, "/v1/chat/completions", "openai", {}, undefined); + assert.equal(obs.compactionSignal, "explicit-header"); + assert.equal(obs.compactionEvidence, "x-context-compacted"); +}); + +test("codex: prefix anchored at user-text START; mid-text copy must NOT fire", () => { + const p = { id: "codex" as const, extraHeaders: ["x-codex-installation-id"], compactionPrefixes: ["Another language model started to solve this problem"], compactPathSuffixes: ["/responses/compact"] }; + const hit = extractNativeIdentity(p, {}, "/v1/responses", "responses", CODEX_BODY_PREFIX, undefined); + assert.equal(hit.compactionSignal, "prefix-match"); + const midText = { input: [{ type: "message", role: "user", content: [{ text: "hello\nAnother language model started to solve this problem — quoted in passing." }] }] }; + const miss = extractNativeIdentity(p, {}, "/v1/responses", "responses", midText, undefined); + assert.equal(miss.compactionSignal, null); + // dedicated endpoint class beats absence of everything else + const ep = extractNativeIdentity(p, {}, "https://up/bili/https://x/v1/responses/compact", "responses", {}, undefined); + assert.equal(ep.compactionSignal, "compact-endpoint"); +}); + +test("cc: dual-channel verification + toolu anchor count; malformed dual channel swallowed", () => { + const p = detectNativeProfile({ "x-claude-code-session-id": "cc-sess-1" }, "/v1/messages", "anthropic"); + let obs = extractNativeIdentity(p, { "x-claude-code-session-id": "cc-sess-1" }, "/v1/messages", "anthropic", CC_BODY_MATCH, '"toolu_a" "toolu_b"'); + assert.equal(obs.sessVal, "cc-sess-1"); + assert.equal(obs.dualBodySessVal, "cc-sess-1"); + assert.equal(obs.toolAnchorCount, 2); + obs = extractNativeIdentity(p, { "x-claude-code-session-id": "cc-sess-1" }, "/v1/messages", "anthropic", CC_BODY_MISMATCH, undefined); + assert.equal(obs.dualBodySessVal, "cc-sess-OTHER"); + // object-encoded dialect + const objObs = extractNativeIdentity(p, { "x-claude-code-session-id": "cc-sess-1" }, "/v1/messages", "anthropic", CC_BODY_OBJECT_DIALECT, undefined); + assert.equal(objObs.dualBodySessVal, "cc-sess-1"); + obs = extractNativeIdentity(p, { "x-claude-code-session-id": "cc-sess-1" }, "/v1/messages", "anthropic", { metadata: { user_id: "{not-json" } }, undefined); + assert.equal(obs.dualBodySessVal, undefined); // malformed: ignored, no throw +}); + +test("opencode: shape assertion fires on foreign wire markers only", () => { + const p = detectNativeProfile({ "x-session-affinity": "ses_z" }, "/v1/chat/completions", "openai"); + assert.equal(p.id, "opencode"); + const clean = extractNativeIdentity(p, { "x-session-affinity": "ses_z" }, "/v1/chat/completions", "openai", { messages: [{ role: "user", content: "plain" }] }, '{"messages":[{"content":"plain"}]}'); + assert.equal(clean.shapeAssertFail, undefined); + assert.equal(clean.sessVal, "ses_z"); + const drifted = extractNativeIdentity(p, { "x-session-affinity": "ses_z" }, "/v1/chat/completions", "openai", { messages: [{ role: "user", content: "plain" }] }, '{"messages":[{"id":"msg_leak","content":"plain"}]}'); + assert.equal(drifted.shapeAssertFail, "msg_"); +}); + +test("stability matrix: fresh / repeat / change / restart continuity / flip / mismatch", () => { + const wbObs = (): ReturnType => extractNativeIdentity( + detectNativeProfile(WB_HDRS, "/v1/chat/completions", "openai"), WB_HDRS, "/v1/chat/completions", "openai", {}, undefined); + let st = mergeNidvState(null, wbObs(), 1000); + assert.equal(st.client, "wb"); + assert.equal(st.reqs, 1); + assert.equal(st.sessH, nidvH8("conv-abc")); + assert.equal(st.sessStable, "yes"); + assert.deepEqual(st.events, []); + // raw value never stored: digest != raw + assert.notEqual(st.sessH, "conv-abc"); + st = mergeNidvState(st, wbObs(), 2000); + assert.equal(st.sessStable, "yes"); + assert.deepEqual(st.events, []); + // changed session value → stable=no + id_change event + const changed = { ...WB_HDRS, "x-conversation-id": "conv-XYZ" }; + st = mergeNidvState(st, extractNativeIdentity(detectNativeProfile(changed, "", "openai"), changed, "", "openai", {}, undefined), 3000); + assert.equal(st.sessStable, "no"); + assert.equal(st.events.at(-1)?.k, "id_change"); + // restart continuity: feed a state deserialized from a previous blob + const fromDisk = JSON.parse(JSON.stringify(st)) as typeof st; + const after = mergeNidvState(fromDisk, wbObs(), 9000); + assert.equal(after.reqs, st.reqs + 1); + assert.equal(after.firstSeen, st.firstSeen); + assert.equal(after.sessStable, "no"); // prior break persists across restart + // profile flip under one bili session id + const flipped = mergeNidvState(after, extractNativeIdentity(detectNativeProfile({ "x-claude-code-session-id": "s2" }, "/v1/messages", "anthropic"), { "x-claude-code-session-id": "s2" }, "/v1/messages", "anthropic", {}, undefined), 10000); + assert.equal(flipped.client, "cc"); + assert.ok(flipped.events.some((e) => e.k === "profile_flip")); + // dual mismatch event + const mm = mergeNidvState(null, extractNativeIdentity(detectNativeProfile({ "x-claude-code-session-id": "cc-sess-1" }, "", "anthropic"), { "x-claude-code-session-id": "cc-sess-1" }, "/v1/messages", "anthropic", CC_BODY_MISMATCH, undefined), 11000); + assert.ok(mm.events.some((e) => e.k === "dual_mismatch")); +}); + +test("event FIFO cap 32 + ≤4KB hard budget survive heavy churn", () => { + const mk = (n: number, ev: string): ReturnType => { + let st: ReturnType | null = null; + for (let i = 0; i < n; i++) { + st = mergeNidvState(st, { profileId: "codex", compactionSignal: "prefix-match", compactionEvidence: ev + "-" + i, sessVal: "s-" + i }, i); + } + return st!; + }; + const st = mk(200, "another-language-model-started-to-solve-this-problem-and-produced-a-summar"); + assert.ok(st!.events.length <= 32); + assert.ok(JSON.stringify(st!).length <= 4096); + // evidence capped at 64 chars + assert.ok(st!.events.every((e) => e.e.length <= 64)); +}); + +test("observeNativeIdentity: off ⇒ zero store traffic + zero logs", () => { + const d = duckStore(); + const { log, lines } = spyLog(); + observeNativeIdentity({ sessionId: "s1", headers: WB_HDRS, urlPath: "/v1/chat/completions", protocol: "openai", log, enabled: false, store: toView(d) }); + assert.equal(d.reads, 0); + assert.equal(d.writes, 0); + assert.equal(lines.length, 0); +}); + +test("observeNativeIdentity: on ⇒ digest write, privacy-held logs, fail-open on corrupt prev", () => { + const d = duckStore(); + const { log, lines } = spyLog(); + observeNativeIdentity({ sessionId: "s1", headers: WB_HDRS, urlPath: "/v1/chat/completions", protocol: "openai", log, enabled: true, store: toView(d) }); + assert.equal(d.writes, 1); + const blob = d.ext.get(`s1\x00${NIDV_EXT_KEY}`)!; + const parsed = JSON.parse(blob) as Record; + assert.equal(parsed.v, 1); + assert.equal(parsed.client, "wb"); + assert.ok(!blob.includes("conv-abc")); // raw id must not be persisted + assert.equal(lines.length, 1); + assert.equal(lines[0].level, "debug"); + assert.ok(!lines[0].msg.includes("conv-abc")); // and not logged either + // corrupt prev blob → rebuild fresh, no throw + d.ext.set(`s1\x00${NIDV_EXT_KEY}`, "{corrupt!"); + observeNativeIdentity({ sessionId: "s1", headers: WB_HDRS, urlPath: "/v1/chat/completions", protocol: "openai", log, enabled: true, store: toView(d) }); + assert.equal(JSON.parse(d.ext.get(`s1\x00${NIDV_EXT_KEY}`)!).reqs, 1); + // replicas unavailable → graceful inertness + const down = duckStore(false); + observeNativeIdentity({ sessionId: "s1", headers: WB_HDRS, urlPath: "/v1/chat/completions", protocol: "openai", log, enabled: true, store: toView(down) }); + assert.equal(down.reads + down.writes, 0); + // unknown client with storage available → NOTHING written (privacy redline) + const unk = duckStore(); + observeNativeIdentity({ sessionId: "s2", headers: { "x-whatever": "1" }, urlPath: "/v1/chat/completions", protocol: "openai", log, enabled: true, store: toView(unk) }); + assert.equal(unk.ext.size, 0); + // empty sessionId → inert + const es = duckStore(); + observeNativeIdentity({ sessionId: "", headers: WB_HDRS, urlPath: "/v1/chat/completions", protocol: "openai", log, enabled: true, store: toView(es) }); + assert.equal(es.writes, 0); + // compaction escalates the log line to warn + const cw = duckStore(); + const clog = spyLog(); + observeNativeIdentity({ sessionId: "s3", headers: { ...WB_HDRS, "x-compacted": "1" }, urlPath: "/v1/chat/completions", protocol: "openai", log: clog.log, enabled: true, store: toView(cw) }); + assert.equal(clog.lines[0].level, "warn"); + assert.match(clog.lines[0].msg, /compaction/); +}); diff --git a/website/config-reference/rollout.yaml b/website/config-reference/rollout.yaml index b01da282e7..70b013aa26 100644 --- a/website/config-reference/rollout.yaml +++ b/website/config-reference/rollout.yaml @@ -57,6 +57,14 @@ entries: group: behavior desc_en: "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." desc_zh: "插件车道服务端正史(#4491):对已放量的安装,(a) 插件车道请求可携带与 `messages` 平行的内部字段 `biliMsgIds`,把消息身份钉在客户端提供的 id 上(转发上游前一律剥掉;格式错误的数组告警后忽略,身份投毒形态在增量车道直接硬失败);(b) 仅回环可达的 `POST /__bili/plugin/render` 端点从统一存储渲染出站前缀(折叠区收敛为摘要锚点;任何失步都返回非 2xx,shim 退回本地历史);(c) 增量车道探测响应通告 `serverHistory`。默认 0%,放量前无行为变化。" + - key: rollout.features.nativeIdentityObservation + type: "boolean | number" + default: "false (off)" + default_zh: "false(关)" + env: BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION + group: behavior + desc_en: "Native identity observation (#5571 M1, observational layer): on every model-API request bili recognizes which client family it came from (WorkBuddy / codex / Claude Code / opencode / Gemini) and records that client's NATIVE identity surface — session ids, per-message host ids, explicit compaction headers or summary-turn prefixes — into session ext key `nidv:obs` as sha1-8 DIGESTS only (raw id values never leave request memory; unknown clients write nothing). Pure collection at the single relay choke point: zero forwarded-byte changes, zero decisions, fail-open by construction. It exists to turn the #5571 client-collection table from static forensics into live measured data ahead of the M2 binding table and M3 re-baseline work. Default OFF (0%) — enable with `true` or `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION=1`. See TECHNICAL-NOTES.md \"Native identity observation layer\"." + desc_zh: "原生身份观测层(#5571 M1):每条模型 API 请求到达时,bili 识别它来自哪个客户端家族(WorkBuddy / codex / Claude Code / opencode / Gemini),并把该客户端的原生身份面——session id、逐条消息宿主 id、显式压缩头或摘要轮前缀——以 sha1-8 摘要形式记入 session ext 键 `nidv:obs`(原始 id 值不落盘、不出请求内存;unknown 客户端不写任何值)。纯采集,位于 relay 单点咽喉:零转发字节改动、零决策、结构性 fail-open。目的是在 M2 绑定表与 M3 re-baseline 开工前,把 #5571 客户端采集表从静态取证变成实测数据。默认关(0%),`true` 或 `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION=1` 开启。见 TECHNICAL-NOTES.zh-CN.md「原生身份观测层」。" - key: rollout.features.pluginFullResendWatermark type: "boolean | number" default: "5 (experimental grey)" From a978523a7af597b838527aa1ea480c1e956a4c1c Mon Sep 17 00:00:00 2001 From: ci-check Date: Tue, 3 Nov 2026 10:49:52 +0800 Subject: [PATCH 02/15] fix(obs): dual_mismatch event stores digests of both channels, never raw ids (#5571 M1) Review of the M1 PR: the dual-channel mismatch event carried up to 64 chars of the raw client session id (cc metadata.user_id.session_id) into the persisted ext blob, breaking the stated privacy redline that only sha1-8 digests ever reach storage or logs. Evidence is now hdr= body=, and the stability-matrix test pins that neither raw channel value appears in the serialized state. --- src/server/native-identity-obs.ts | 7 +++++-- tests/issue5571-native-identity-obs.test.ts | 7 ++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/server/native-identity-obs.ts b/src/server/native-identity-obs.ts index 567cfc2a95..87abac6f2e 100644 --- a/src/server/native-identity-obs.ts +++ b/src/server/native-identity-obs.ts @@ -80,9 +80,12 @@ export function mergeNidvState(prev: NidvState | null, obs: NidvObservation, now pushEvent("id_change", `sess ${h}`); } } - // Cross-channel verification (cc metadata vs header). + // Cross-channel verification (cc metadata vs header). Evidence carries + // DIGESTS of both channels — a raw id must never reach the persisted blob. if (typeof obs.dualBodySessVal === "string" && typeof obs.sessVal === "string") { - if (nidvH8(obs.dualBodySessVal) !== nidvH8(obs.sessVal)) pushEvent("dual_mismatch", obs.dualBodySessVal.slice(0, EV_TEXT_CAP)); + const hHdr = nidvH8(obs.sessVal); + const hBody = nidvH8(obs.dualBodySessVal); + if (hHdr !== hBody) pushEvent("dual_mismatch", `hdr=${hHdr} body=${hBody}`); } // Message-level host id (wb today): per-request id changes every turn by // design — we track LAST value + sighting count; M2's binding table turns diff --git a/tests/issue5571-native-identity-obs.test.ts b/tests/issue5571-native-identity-obs.test.ts index db6a056228..26d9d5de98 100644 --- a/tests/issue5571-native-identity-obs.test.ts +++ b/tests/issue5571-native-identity-obs.test.ts @@ -127,9 +127,14 @@ test("stability matrix: fresh / repeat / change / restart continuity / flip / mi const flipped = mergeNidvState(after, extractNativeIdentity(detectNativeProfile({ "x-claude-code-session-id": "s2" }, "/v1/messages", "anthropic"), { "x-claude-code-session-id": "s2" }, "/v1/messages", "anthropic", {}, undefined), 10000); assert.equal(flipped.client, "cc"); assert.ok(flipped.events.some((e) => e.k === "profile_flip")); - // dual mismatch event + // dual mismatch event — evidence must be digest-only: raw channel values + // never land in the persisted state (privacy redline, review of M1 PR) const mm = mergeNidvState(null, extractNativeIdentity(detectNativeProfile({ "x-claude-code-session-id": "cc-sess-1" }, "", "anthropic"), { "x-claude-code-session-id": "cc-sess-1" }, "/v1/messages", "anthropic", CC_BODY_MISMATCH, undefined), 11000); assert.ok(mm.events.some((e) => e.k === "dual_mismatch")); + const mmBlob = JSON.stringify(mm); + assert.ok(!mmBlob.includes("cc-sess-OTHER")); + assert.ok(!mmBlob.includes("cc-sess-1")); + assert.ok(mm.events.some((e) => e.k === "dual_mismatch" && /^hdr=[0-9a-f]{8} body=[0-9a-f]{8}$/.test(e.e))); }); test("event FIFO cap 32 + ≤4KB hard budget survive heavy churn", () => { From 870265dcf16b7ebb587a25c9e0522e43f4888112 Mon Sep 17 00:00:00 2001 From: ci-check Date: Tue, 3 Nov 2026 10:52:45 +0800 Subject: [PATCH 03/15] refactor(obs): satisfy unused-exports CI gate + drop no-op catch assignments (#5571 M1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI static gate check-unused-exports flagged seven exports of the new modules: six module-local types (NidvProfile, NidvCompactionSignal, NidvEvent, NidvState, NidvStoreView, ObserveNativeIdentityArgs) lose their leading export per the gate's own remedy, and NidvHeaders was dead code entirely — deleted, its structural-typing rationale folded into detectNativeProfile's doc. Also removes two self-assigning no-op statements from the fail-open catch in extractNativeIdentity. --- src/server/native-identity-obs.ts | 8 ++++---- src/server/native-identity-profiles.ts | 19 +++++++------------ 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/server/native-identity-obs.ts b/src/server/native-identity-obs.ts index 87abac6f2e..ac97a201c4 100644 --- a/src/server/native-identity-obs.ts +++ b/src/server/native-identity-obs.ts @@ -20,7 +20,7 @@ const MAX_JSON_BYTES = 4096; const MAX_EVENTS = 32; const EV_TEXT_CAP = 64; -export interface NidvEvent { +interface NidvEvent { t: number; /** compaction | id_change | profile_flip | dual_mismatch | shape_assert_fail */ k: string; @@ -28,7 +28,7 @@ export interface NidvEvent { e: string; } -export interface NidvState { +interface NidvState { v: 1; client: NidvClientId; firstSeen: number; @@ -107,13 +107,13 @@ export function mergeNidvState(prev: NidvState | null, obs: NidvObservation, now /** Minimal structural store view — production callers pass nothing (module * singleton via getStore()); tests inject a duck to exercise the write path * without a real sidecar. */ -export interface NidvStoreView { +interface NidvStoreView { replicasAvailable(): boolean; getSessionExt(sessionId: string, key: string): unknown; setSessionExt(sessionId: string, key: string, value: unknown): void; } -export interface ObserveNativeIdentityArgs { +interface ObserveNativeIdentityArgs { sessionId: string; headers: Record; urlPath: string; diff --git a/src/server/native-identity-profiles.ts b/src/server/native-identity-profiles.ts index 4a93cbc399..4b55e1324d 100644 --- a/src/server/native-identity-profiles.ts +++ b/src/server/native-identity-profiles.ts @@ -15,7 +15,7 @@ // row here (+ unit tests) — do not hard-code literals anywhere else. export type NidvClientId = "wb" | "codex" | "cc" | "opencode" | "gemini" | "unknown"; -export interface NidvProfile { +interface NidvProfile { readonly id: NidvClientId; /** Header carrying the SESSION id (lowercase name). */ readonly sessHeader?: string; @@ -40,7 +40,7 @@ export interface NidvProfile { readonly shapeAssertAbsent?: readonly string[]; } -export type NidvCompactionSignal = "explicit-header" | "prefix-match" | "compact-endpoint" | null; +type NidvCompactionSignal = "explicit-header" | "prefix-match" | "compact-endpoint" | null; /** Per-request extraction result. Raw values live in MEMORY ONLY for the * lifetime of this call — persistence stores sha1 digests (h8), logs never @@ -134,7 +134,9 @@ function firstHeader(headers: Record, name: string): string | u /** Deterministic profile detection. Order matters and is pinned by tests: * explicit per-client session headers outrank family markers, which outrank - * protocol inference. Never throws on odd inputs. */ + * protocol inference. Headers stay structural (Record) so + * tests feed plain objects and handle.ts passes req.headers directly — + * IncomingHttpHeaders is structurally assignable. Never throws on odd inputs. */ export function detectNativeProfile( headers: Record, urlPath: string, @@ -288,15 +290,8 @@ export function extractNativeIdentity( } } } catch { - // Fail-open by construction: a broken profile row degrades to "no - // observation", never to a failed request. - obs.profileId = profile.id === "unknown" ? "unknown" : obs.profileId; - obs.compactionSignal = obs.compactionSignal ?? null; + // Fail-open by construction: a broken profile row degrades to a + // partial/no observation, never to a failed request. } return obs; } - -/** Header view kept intentionally structural (not node:http-typed) so tests - * can feed plain objects and handle.ts can pass req.headers directly — - * IncomingHttpHeaders is structurally assignable to Record. */ -export type NidvHeaders = Record; From f6968ee9f2028b755b394111781593243160ea0e Mon Sep 17 00:00:00 2001 From: ci-check Date: Tue, 3 Nov 2026 11:49:51 +0800 Subject: [PATCH 04/15] fix(obs): drop dead extraHeaders field never consumed by extraction NidvProfile.extraHeaders was declared and populated in the codex row but no code path reads it: detection keys x-codex-installation-id directly, extraction has no storage slot for extra headers, and no test asserts them. Remove the field and the row entry; the pending live-capture spellings stay in issue #5571's collection table until M2 decides what to actually capture. --- src/server/native-identity-profiles.ts | 16 +++------------- tests/issue5571-native-identity-obs.test.ts | 2 +- 2 files changed, 4 insertions(+), 14 deletions(-) diff --git a/src/server/native-identity-profiles.ts b/src/server/native-identity-profiles.ts index 4b55e1324d..89805b89a5 100644 --- a/src/server/native-identity-profiles.ts +++ b/src/server/native-identity-profiles.ts @@ -25,8 +25,6 @@ interface NidvProfile { readonly reqHeader?: string; /** Fork/lineage header. */ readonly parentHeader?: string; - /** Additional headers to capture — dynamic-capture items, spelling TBC. */ - readonly extraHeaders?: readonly string[]; /** Body JSON paths for session-id cross-channel verification. */ readonly bodySessPaths?: ReadonlyArray; /** User-turn text prefixes marking a client-side re-baseline (compaction). */ @@ -77,17 +75,9 @@ const WB: NidvProfile = { const CODEX: NidvProfile = { id: "codex", - // Installation id is stable per machine (file ~/.codex/installation_id); - // the thread/window header spellings are FORENSIC GUESSES pending a live - // capture — capture them all when present, do not filter on them yet. - extraHeaders: [ - "x-codex-installation-id", - "x-client-request-id", - "x-codex-window-id", - "x-codex-turn-metadata", - "x-codex-parent-thread-id", - "x-openai-subagent", - ], + // Installation id is stable per machine (file ~/.codex/installation_id) — + // the reliable detector; the other thread/window header spellings are + // forensic guesses pending live capture (issue #5571 collection table). parentHeader: "x-codex-parent-thread-id", // Re-baseline: fixed lead sentence prepended after a local compact, plus // the dedicated server endpoint POST /responses/compact. diff --git a/tests/issue5571-native-identity-obs.test.ts b/tests/issue5571-native-identity-obs.test.ts index 26d9d5de98..f26ae3a839 100644 --- a/tests/issue5571-native-identity-obs.test.ts +++ b/tests/issue5571-native-identity-obs.test.ts @@ -62,7 +62,7 @@ test("wb: header ids extracted + explicit compaction header is strongest signal" }); test("codex: prefix anchored at user-text START; mid-text copy must NOT fire", () => { - const p = { id: "codex" as const, extraHeaders: ["x-codex-installation-id"], compactionPrefixes: ["Another language model started to solve this problem"], compactPathSuffixes: ["/responses/compact"] }; + const p = { id: "codex" as const, compactionPrefixes: ["Another language model started to solve this problem"], compactPathSuffixes: ["/responses/compact"] }; const hit = extractNativeIdentity(p, {}, "/v1/responses", "responses", CODEX_BODY_PREFIX, undefined); assert.equal(hit.compactionSignal, "prefix-match"); const midText = { input: [{ type: "message", role: "user", content: [{ text: "hello\nAnother language model started to solve this problem — quoted in passing." }] }] }; From 0e83b21e44c4bdcbbe08870a03a68251fe30d433 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 3 Nov 2026 10:55:24 +0800 Subject: [PATCH 05/15] feat(fastpath): v5 identity-only head verification per owner ruling 2026-11-03 Owner directive (issue #5571 thread): drop byte-stability from the hit gate; verify on sessionid + msgid only, count stays diagnostic (already so since v4). - Head element loop: under a shape-valid host msgid list, id/byte inequality demotes to a diagnostic warn stream (feeds M3 re-seeding signals); pure-count clients keep the pre-v5 byte gate unchanged (their ids carry no proof). - Session continuity gate: new state field cs (h8 digest of the client-native session header: wb x-conversation-id / cc x-claude-code-session-id / opencode x-session-affinity); an identity swap riding one bili session is a sess-change miss; recorded identity follows the traffic, swaps always cost a legacy pass. readSaved whitelist extended for cs. - System text has no msgid (flagged deviation in the ruling): head-drift stays gating in both modes. --- src/server/fastpath.ts | 104 ++++++++++++++++++++++++++++++++--------- tests/fastpath.test.ts | 55 ++++++++++++++++++++++ 2 files changed, 136 insertions(+), 23 deletions(-) diff --git a/src/server/fastpath.ts b/src/server/fastpath.ts index 161d05d7c4..eaa654fb99 100644 --- a/src/server/fastpath.ts +++ b/src/server/fastpath.ts @@ -35,6 +35,7 @@ import type { CoreMessage } from "acp-kernel"; import type { OpenAIRequestBody } from "acp-kernel/wire"; import { openaiToCore } from "acp-kernel/wire"; import type http from "node:http"; +import { createHash } from "node:crypto"; import { featureEnabled } from "../rollout.js"; import { getStore } from "../persist.js"; import type { Session } from "../session.js"; @@ -46,6 +47,23 @@ 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"; + +// #5571 v5 (owner ruling 2026-11-03): identity-only verification takes the +// client's NATIVE session id as an identity input alongside host msgids. +// Canonical table lives in #5571's native-identity-profiles; these three +// spellings are byte-duplicated here (#3482 precedent) so this module stays +// dependency-free of the observation layer. +const CLIENT_SESS_HEADERS = ["x-conversation-id", "x-claude-code-session-id", "x-session-affinity"] as const; + +/** h8 digest of whichever known client session header carries a value + * (first hit wins); undefined when none does — absence claims nothing. */ +function clientSessDigest(req: http.IncomingMessage): string | undefined { + for (const h of CLIENT_SESS_HEADERS) { + const v = req.headers[h]; + if (typeof v === "string" && v.length > 0) return createHash("sha1").update(v).digest("hex").slice(0, 8); + } + return undefined; +} // #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). @@ -63,6 +81,9 @@ interface PFSavedState { /** Last received tail-id list (#5418 v2) — survives restarts so the * prevId continuity check is live on the first turn back. */ l?: string[]; + /** #5571 v5: client-native session id digest recorded with this state + * (h8, never raw — privacy parity with #5571); sess-change gate input. */ + cs?: string; } interface PFSeed { @@ -123,6 +144,10 @@ export interface FastpathOutcome { * into the (re)seeded state either way so continuity holds across both. * Absent (undefined) for count-only turns or shape-invalid lists. */ readonly receivedTailIds?: string[]; + /** #5571 v5: client-native session id digest of THIS request + * (undefined when no known header carried a value). Persisted by + * finalize as state `cs`; feeds the sess-change identity gate. */ + readonly clientSess?: string; } /** #5418 v2: decode the shim's x-bili-pf-tail-ids value. @@ -173,6 +198,7 @@ function readSaved(sessionId: string): PFSavedState | null { l: Array.isArray(o.l) && o.l.length > 0 && o.l.length <= 2048 && (o.l as unknown[]).every((x): x is string => typeof x === "string" && x.length > 0 && x.length <= 512) ? (o.l as string[]) : undefined, + cs: typeof o.cs === "string" && o.cs.length === 8 ? o.cs : undefined, }; } catch { return null; @@ -232,10 +258,13 @@ export function evaluateWatermarkFastpath( const T = scan.total; const rawStamp = req.headers[PF_COUNT_HEADER]; const stamped = typeof rawStamp === "string" && /^\d+$/.test(rawStamp.trim()) ? parseInt(rawStamp.trim(), 10) : NaN; + // #5571 v5: captured ONCE per evaluated turn — feeds the sess-change gate + // below and rides the outcome so finalize persists it as state `cs`. + const nowCs = clientSessDigest(req); const miss = (decision: string, credited: boolean, receivedTailIds?: string[]): FastpathOutcome => { if (credited) noteCreditedMiss(session.id, decision, log); log("info", `[${session.id}] watermark fastpath miss (${decision}) — legacy full-parse this turn`); - return { hit: null, measuredT: T, decision, creditedMiss: credited, receivedTailIds }; + return { hit: null, measuredT: T, decision, creditedMiss: credited, receivedTailIds, clientSess: nowCs }; }; const seed = seeds.get(session); const rawTailIds = req.headers[PF_TAIL_IDS_HEADER]; @@ -289,6 +318,17 @@ export function evaluateWatermarkFastpath( if (prevKnown !== undefined && prevKnown !== PF_SLOT_UNKNOWN && tailIds[0] !== prevKnown) return miss("tail-ids-prev", false); } } + // #5571 v5 (owner ruling 2026-11-03): session continuity joins the + // identity proof. State carrying a client-native session id digest + // means an earlier turn claimed an identity; this request must keep + // claiming the SAME one — a swapped conversation riding one bili + // session is an identity event, not a byte question. Neutral when + // either side claims nothing (header-less clients unchanged); + // asserted only when both sides do. Id mode only (no valid list + // reached here without one). + if (tailIds !== undefined && saved?.cs !== undefined) { + if (nowCs !== undefined && nowCs !== saved.cs) return miss("sess-change", false, tailIds); + } if (seed.multimodal) return miss("seeded-multimodal", false, tailIds); const headEnd = Math.min(HEAD_CHECK_ELEMENTS, T); const headFragment: { messages: unknown } = { messages: [] }; @@ -300,23 +340,35 @@ export function evaluateWatermarkFastpath( const windowCounts = stripRawStage(windowFragment, "openai"); const headCores = openaiToCore(headFragment as OpenAIRequestBody); if (headCores.systemText !== seed.systemText) return miss("head-drift", true, tailIds); - // In-place head EDIT detection. The system-text check alone would miss - // an in-place rewrite of any non-system head element (dsh message-edit - // flows): counts stay equal, the stamp stays honest, and the stale - // seed byte would ride the outbound again — the costliest divergence - // class. Compare every stashed prefix core against its freshly parsed - // counterpart: openaiToCore is deterministic per element bytes, so - // structural inequality (cluster id / role / content) marks a rewrite. - // Uncredited: a genuine client edit is not a lying stamp, so the - // breaker must not arm on it; finalizeWatermarkTurn reseeds from the - // legacy full parse of THIS turn, so the very next turn hits against - // the new baseline (self-healing). Shape mismatch covers small - // histories where the head fragment reaches past seed coverage — - // those turns legitimately go legacy. - // Compare ONLY the part of the head still under seed coverage: on small - // histories the 8-element head fragment legitimately reaches INTO the - // fresh tail region, whose content differs from nothing stashed yet — - // positions >= coverage are verified by the window conversion itself. + // In-place head EDIT detection (pre-v5 history): the system-text + // check alone misses an in-place rewrite of any non-system head + // element (dsh message-edit flows) — counts stay equal, stamp stays + // honest, stale seed byte rides outbound again. Pre-v5 that + // comparison GATED: openaiToCore is deterministic per element bytes, + // structural inequality marked a rewrite, uncredited self-healing + // legacy turn (a genuine client edit is not a lying stamp). + // v5 (owner ruling 2026-11-03, identity-only verification): with a + // shape-valid HOST msgid list the identity chain IS the proof — + // width arithmetic re-derives the count SERVER-side (never from a + // client echo), the prevId chain pins the window origin, sess-change + // rules out conversation swaps, model equality rules out cross-model + // reuse. Bili INTERNAL core ids are content-derived + // (deriveCanonicalMessageId(role,text)) — they carry no identity + // beyond the byte check itself. So under id mode BOTH the id- + // equality and byte-equality loops demote to a diagnostic warn: host + // rewrites ride the stashed prefix cores; the warn stream feeds M3 + // smart re-seeding should the rides ever prove harmful. Pure-COUNT + // clients have no ids at all — their byte check remains the sole + // truth and behaves exactly as pre-v5. System text has no msgid + // (flagged deviation in the ruling thread): head-drift above STAYS + // gating in both modes — serving a stale prompt beats saving one + // parse. Compare ONLY the part of the head still under seed coverage: + // on small histories the 8-element head fragment legitimately reaches + // INTO the fresh tail region, whose content differs from nothing + // stashed yet — positions >= coverage are verified by the window + // conversion itself. + let contentDrifts = 0; + let driftTotal = 0; const headElements = Array.isArray((headFragment as { messages?: unknown }).messages) ? ((headFragment as { messages: unknown[] }).messages.filter((m): m is { role?: unknown } => typeof m === "object" && m !== null && (m as { role?: unknown }).role !== "system")).length : -1; @@ -324,12 +376,17 @@ export function evaluateWatermarkFastpath( const compareUpTo = Math.min(headElements, headCores.msgs.length, seed.cores.length); const seedHead = seed.cores.slice(0, compareUpTo); if (headCores.msgs.length < seedHead.length) return miss("head-shape", false, tailIds); + driftTotal = seedHead.length; for (let hi = 0; hi < seedHead.length; hi++) { const a = headCores.msgs[hi]; const b = seedHead[hi]; - if (a.id !== b.id || JSON.stringify(a) !== JSON.stringify(b)) return miss("head-prefix-drift", false, tailIds); + if (a.id !== b.id || JSON.stringify(a) !== JSON.stringify(b)) { + if (tailIds === undefined) return miss("head-prefix-drift", false, tailIds); + contentDrifts += 1; + } } } + if (contentDrifts > 0) log("warn", `[${session.id}] watermark v5: ${contentDrifts}/${driftTotal} head element(s) differ from the seed under stable host ids — riding the stashed prefix per owner ruling 2026-11-03 (diagnostic only; feeds M3 re-seeding signals)`); const windowRaw = openaiToCore(windowFragment as OpenAIRequestBody); if (windowRaw.systemText.trim() !== "") return miss("window-system-head", true, tailIds); const rekeyedWindow = rekeyWindowCores(windowRaw.msgs, K, seed.cores); @@ -352,6 +409,7 @@ export function evaluateWatermarkFastpath( decision: hitDecision, creditedMiss: false, receivedTailIds: tailIds, + clientSess: nowCs, }; } return miss(seed === undefined ? "unseeded" : "seed-stale", false); @@ -439,14 +497,14 @@ function addStripCounts(a: RawStripCounts, b: RawStripCounts): RawStripCounts { } function noteCreditedMiss(sessionId: string, decision: string, log: (level: string, msg: string) => void): void { - const cur = readSaved(sessionId) ?? { t: 0, m: "", misses: 0 }; + const cur = readSaved(sessionId) ?? ({ t: 0, m: "", misses: 0 } as PFSavedState); // an EXPIRED hold has already paid its penalty — count fresh from zero, // or the very first verified miss after the TTL would instantly re-arm // (the persisted counter sits at PF_BREAKER_MISSES from the original trip). const staleHold = cur.disabledAt !== undefined && Date.now() - cur.disabledAt >= PF_DISABLED_TTL_MS; const misses = (staleHold ? 0 : cur.misses) + 1; if (misses >= PF_BREAKER_MISSES) { - writeSaved(sessionId, { t: cur.t, m: cur.m, misses, disabledAt: Date.now() }); + writeSaved(sessionId, { t: cur.t, m: cur.m, misses, disabledAt: Date.now(), cs: cur.cs }); log("warn", `[${sessionId}] watermark fastpath disabled for ${Math.round(PF_DISABLED_TTL_MS / 60000)}m after ${misses} consecutive verified misses (last: ${decision}) — legacy full-parse continues`); } else { writeSaved(sessionId, { ...cur, misses, disabledAt: staleHold ? undefined : cur.disabledAt }); @@ -483,7 +541,7 @@ export function finalizeWatermarkTurn( lastTailIds: outcome.receivedTailIds, multimodal: outcome.hit.seedMultimodal, }); - writeSaved(session.id, { t: T, m: input.model, misses: 0, l: outcome.receivedTailIds }); + writeSaved(session.id, { t: T, m: input.model, misses: 0, l: outcome.receivedTailIds, cs: outcome.clientSess ?? saved?.cs }); headers[PF_SEQ_HEADER] = String(T); return headers; } @@ -500,7 +558,7 @@ export function finalizeWatermarkTurn( } // Held (breaker-armed) turns flow through here too and DO restamp: the // stamp is how a client converges on truth while the lane stays hit-less. - writeSaved(session.id, { t: T, m: input.model, misses: saved?.misses ?? 0, disabledAt: saved?.disabledAt, l: outcome.receivedTailIds }); + writeSaved(session.id, { t: T, m: input.model, misses: saved?.misses ?? 0, disabledAt: saved?.disabledAt, l: outcome.receivedTailIds, cs: outcome.clientSess ?? saved?.cs }); headers[PF_SEQ_HEADER] = String(T); return headers; } diff --git a/tests/fastpath.test.ts b/tests/fastpath.test.ts index 8965a7b9f6..e8a3a91c41 100644 --- a/tests/fastpath.test.ts +++ b/tests/fastpath.test.ts @@ -464,3 +464,58 @@ test("clearWatermarkSeed forces the next turn back through verification", () => const { out } = runTurn(session, { [PF_COUNT_HEADER]: "3" }, b2); assert.equal(out.decision, "unseeded"); }); + +// --------------------------------------------------------------------------- +// #5571 v5 (owner ruling 2026-11-03): identity-only head verification +// --------------------------------------------------------------------------- + +test("v5 id mode: head rewrite under stable host msgids RIDES the stashed prefix and warns", () => { + LOGS.length = 0; + makeStubStore(); + const session = freshSession("pf-v5-ride"); + const b1 = bodyOf([SYS("s"), USR("a"), USR("b")]); + assert.equal(runTurn(session, {}, b1).out.decision, "no-stamp"); + // rewrite "b" IN PLACE and append one user turn; the shim echoes the window host ids. + // Pre-v5 this was an uncredited head-prefix-drift miss; under v5 the host + // msgid chain (shape + width + prevId) IS the proof — it rides. + const b2 = bodyOf([SYS("s"), USR("a"), USR("b-E"), USR("c")]); + const { out } = runTurn(session, TAIL(["h-bE", "h-c"]), b2); + assert.equal(out.decision, "hit(no-count)", LOGS.join("\n")); + // the diagnostic stream must record the drift (feeds M3 re-seeding signals) + assert.ok(LOGS.some((l) => l.startsWith("warn") && l.includes("watermark v5")), LOGS.join("\n")); +}); + +test("v5: system-text change STILL misses under stable host msgids (pinned deviation — a prompt has no msgid)", () => { + LOGS.length = 0; + makeStubStore(); + const session = freshSession("pf-v5-sys"); + const b1 = bodyOf([SYS("s"), USR("a"), USR("b")]); + runTurn(session, {}, b1); + const b2 = bodyOf([SYS("CHANGED"), USR("a"), USR("b"), USR("c")]); + const { out } = runTurn(session, TAIL(["x1", "x2"]), b2); + assert.equal(out.decision, "head-drift", LOGS.join("\n")); + assert.equal(out.creditedMiss, true); +}); + +test("v5: client session-id swap under stable host msgids misses sess-change, recovers when the conversation returns", () => { + LOGS.length = 0; + makeStubStore(); + const session = freshSession("pf-v5-sess"); + const A: Record = { "x-conversation-id": "conv-A" }; + const b1 = bodyOf([SYS("s"), USR("a"), USR("b")]); + runTurn(session, A, b1); // no-stamp; cs captured + const b2 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c")]); + const bad = runTurn(session, { ...A, "x-conversation-id": "conv-B", ...TAIL(["p1", "p2"]) }, b2); + assert.equal(bad.out.decision, "sess-change", LOGS.join("\n")); + // The missed turn went legacy AND the recorded identity follows the + // traffic: state now belongs to conv-B, so B's continuous growth RIDES + // (window ids open on the swapped turn's last slot) ... + const b3 = bodyOf([...JSON.parse(b2).messages, USR("d")]); + const contB = runTurn(session, { ...A, "x-conversation-id": "conv-B", ...TAIL(["p2", "q2"]) }, b3); + assert.equal(contB.out.decision, "hit(no-count)", LOGS.join("\n")); + // ...while the ORIGINAL conversation A returning is ANOTHER identity + // event — it pays one more legacy pass (no silent ride across swaps). + const b4 = bodyOf([...JSON.parse(b3).messages, USR("e")]); + const backA = runTurn(session, { ...A, ...TAIL(["q2", "r2"]) }, b4); + assert.equal(backA.out.decision, "sess-change", LOGS.join("\n")); +}); From 50feb191a308c6c5b5293a5eb0d455545f6be5c7 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 3 Nov 2026 13:41:31 +0800 Subject: [PATCH 06/15] v6: add watermarkCompactionPassthrough rollout knob (R4) + docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #5403/#5418 v6 canonical-ledger unification. The knob governs what the watermark hit decision does with a client structural rewrite whose shape survived the width + origin gates: ON (default) takes one conservative legacy pass and rides the increment passthrough-as-new-message from the next turn (fresh ids append to the cumulative host-id ledger, no suppression logic — contract R4/O3); OFF restores pre-v6 ride-with- diagnostic for those turns. Nested under pluginFullResendWatermark so it is dead weight outside the watermark cohort; count-only turns stay byte-identical either way. Docs follow the sibling-knob convention: CONFIGURATION(.zh-CN) feature + env tables, website/config-reference/rollout.yaml entry (en+zh), and a v6 paragraph in the Full-resend watermark fastpath TECHNICAL-NOTES section (en+zh). --- CONFIGURATION.md | 2 ++ CONFIGURATION.zh-CN.md | 2 ++ TECHNICAL-NOTES.md | 2 ++ TECHNICAL-NOTES.zh-CN.md | 2 ++ src/rollout.ts | 12 ++++++++++++ website/config-reference/rollout.yaml | 8 ++++++++ 6 files changed, 28 insertions(+) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index b0094abc72..4a37fc5e8a 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -104,6 +104,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `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.nativeIdentityObservation` | boolean \| number | false (off) | BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION | Native identity observation (#5571 M1, observational layer): on every model-API request bili recognizes which client family it came from (WorkBuddy / codex / Claude Code / opencode / Gemini) and records that client's NATIVE identity surface — session ids, per-message host ids, explicit compaction headers or summary-turn prefixes — into session ext key `nidv:obs` as sha1-8 DIGESTS only (raw id values never leave request memory; unknown clients write nothing). Pure collection at the single relay choke point: zero forwarded-byte changes, zero decisions, fail-open by construction. It exists to turn the #5571 client-collection table from static forensics into live measured data ahead of the M2 binding table and M3 re-baseline work. Default OFF (0%) — enable with `true` or `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION=1`. See TECHNICAL-NOTES.md "Native identity observation layer". | | `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.watermarkCompactionPassthrough` | boolean \| number | 100 (on, nested under pluginFullResendWatermark) | BILI_ROLLOUT_WATERMARK_COMPACTION_PASSTHROUGH | Watermark v6 canonical-ledger unification (#5403/#5418 v6): when the plugin-lane watermark turn carries a shape-valid host-id list AND a mid-history unknown id sits before a still-known one — a client structural rewrite (compaction/insertion) that changed what the stashed prefix cores describe — this knob decides the verdict: ON (default) pays ONE conservative legacy pass for that turn (credited miss, self-healing re-stamp) so the increment rides through as new messages from the next turn with its fresh ids appended to the session's cumulative host-id ledger (`pf:state.lg`, FIFO-capped) — no suppression logic, never speculative rebuilds; OFF restores the pre-v6 behavior for those turns (the rewrite rides the stashed prefix under the identity-only ruling, byte-compare demoted to diagnostic). Only matters for id-list turns inside an already-enabled watermark cohort; count-only turns are byte-identical either way. Force off with `false` / env = 0. See TECHNICAL-NOTES.md “Full-resend watermark fastpath”. | | `maskHosts` | boolean | true | BILI_LOG_MASK_HOSTS | Mask non-public target hosts in logs as ; 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 (\|sub:) instead of queueing behind the main session. | @@ -1917,6 +1918,7 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION` | `rollout.features.nativeIdentityObservation` | false (off) | | `BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK` | `rollout.features.pluginFullResendWatermark` | 5 (experimental grey) | | `BILI_ROLLOUT_PLUGIN_LANE_SERVER_HISTORY` | `rollout.features.pluginLaneServerHistory` | 0 (off) | +| `BILI_ROLLOUT_WATERMARK_COMPACTION_PASSTHROUGH` | `rollout.features.watermarkCompactionPassthrough` | 100 (on; nested under BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK) | | `BILI_SESSION_CONTENT_STORE_PIN` | `sessions.contentStorePin` | false | | `BILI_SESSION_GC` | `sessions.gc.enabled` | false | | `BILI_SESSION_GC_INTERVAL_MS` | `sessions.gc.intervalMs` | 3600000 | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index c09241bddb..d2167d4100 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -104,6 +104,7 @@ | `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.nativeIdentityObservation` | boolean \| number | false(关) | BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION | 原生身份观测层(#5571 M1):每条模型 API 请求到达时,bili 识别它来自哪个客户端家族(WorkBuddy / codex / Claude Code / opencode / Gemini),并把该客户端的原生身份面——session id、逐条消息宿主 id、显式压缩头或摘要轮前缀——以 sha1-8 摘要形式记入 session ext 键 `nidv:obs`(原始 id 值不落盘、不出请求内存;unknown 客户端不写任何值)。纯采集,位于 relay 单点咽喉:零转发字节改动、零决策、结构性 fail-open。目的是在 M2 绑定表与 M3 re-baseline 开工前,把 #5571 客户端采集表从静态取证变成实测数据。默认关(0%),`true` 或 `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION=1` 开启。见 TECHNICAL-NOTES.zh-CN.md「原生身份观测层」。 | | `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.watermarkCompactionPassthrough` | boolean \| number | 100(开,嵌套于 pluginFullResendWatermark) | BILI_ROLLOUT_WATERMARK_COMPACTION_PASSTHROUGH | 水位 v6 标准账本统一(#5403/#5418 v6):当插件车道水位回合携带形状合格的宿主 id 列表,且已验证范围内出现「已知 id 之前还有未知真实 id」——客户端结构性改写(压缩/插入)已经改变了钉存前缀核所描述的内容——本旋钮决定判决:开(默认)为该回合付一次保守的 legacy 全量解析(计名 miss,自愈重盖戳),增量从下一轮起以新消息形态透出、其新 id 追加进会话累计宿主 id 账本(`pf:state.lg`,FIFO 上限)——无抑制逻辑、永不做猜测式重建;关 = 这些回合回退 pre-v6 行为(改写在身份-only 裁定下骑钉存前缀,字节比对降为诊断)。仅影响 id 列表回合且限已启用水位队列内;纯计数回合两种取值逐字节相同。`false` / env = 0 强制关。见 TECHNICAL-NOTES.zh-CN.md「全量重发水位快路径」。 | | `maskHosts` | boolean | true | BILI_LOG_MASK_HOSTS | 日志中把非公开目标主机遮成 ;凭据头无论此开关如何总是遮盖。 | | `security.adminRelay` | boolean | false | — | 允许宿主(当前为 dsh web)把它自己入口域名下的整个 /__bili/ 管理面中继到本机代理,使远程浏览器能打开面板(#3373)。默认关闭、仅配置文件。中继跳到达代理时是本机非浏览器客户端(回环源地址 + 回环 Host、无 Origin 头),管理端门槛不变;开启后,凡能访问宿主 web 入口的人都能改配置、写凭据——请先给入口加鉴权/反代。 | | `subagentSplit` | boolean | true | BILI_SUBAGENT_SPLIT | Claude 子代理拥有独立会话命名空间(\|sub:),不再排队在主会话锁后。 | @@ -1900,6 +1901,7 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 | `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION` | `rollout.features.nativeIdentityObservation` | false (off) | | `BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK` | `rollout.features.pluginFullResendWatermark` | 5 (experimental grey) | | `BILI_ROLLOUT_PLUGIN_LANE_SERVER_HISTORY` | `rollout.features.pluginLaneServerHistory` | 0 (off) | +| `BILI_ROLLOUT_WATERMARK_COMPACTION_PASSTHROUGH` | `rollout.features.watermarkCompactionPassthrough` | 100 (on; nested under BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK) | | `BILI_SESSION_CONTENT_STORE_PIN` | `sessions.contentStorePin` | false | | `BILI_SESSION_GC` | `sessions.gc.enabled` | false | | `BILI_SESSION_GC_INTERVAL_MS` | `sessions.gc.intervalMs` | 3600000 | diff --git a/TECHNICAL-NOTES.md b/TECHNICAL-NOTES.md index 10b3e2c342..9f17f4dbf0 100644 --- a/TECHNICAL-NOTES.md +++ b/TECHNICAL-NOTES.md @@ -584,6 +584,8 @@ Fail-soft discipline (anti-deviation lock): the legacy pipeline code is UNTOUCHE Declared trust boundary (§7.4 — human review required, no auto-merge): a client that edits PREFIX BYTES while keeping the element count constant is NOT detected — except at the anchor, where v2 compares the carried prevId against the stored one and a re-minted id costs one uncredited miss plus self-heal. That trade is the entire price of skipping byte-level re-verification; it cleared the §7.4 human review and therefore ships as an EXPERIMENTAL grey rollout — ON by default for roughly 5% of installs (owner ruling 2026-11-02: small cohort before GA, one-time web intro notice visible to every install until closed, plus a tri-state quick switch) — with the A/B golden pinning outbound byte-equality and a per-install opt-in/opt-out (`rollout.features.pluginFullResendWatermark: true|false` / `BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK=1|0`). Destructive rewrites (announced compaction, truncation, reorders) change the count and are caught before any stale core could feed the kernel — under v4 the catch moves from the client echo to the width arithmetic itself: a shrunken prefix demands a non-positive width no id list can satisfy, so the credited `ahead` / `seed-stale` verdicts fire exactly as pre-v4. +**v6 canonical-ledger unification (owner rulings 2026-11-03, contract R1–R8):** the hit decision now derives from the CANONICAL transcript alignment instead of the fastpath's own parallel byte gates. Mechanically, the alignment's id fast-path is exactly what the shim's tail-ids encode — host msgids are unique forever, so a list that is a pure append to the session's cumulative host-id ledger (`pf:state.lg`, FIFO-capped at 2048 real ids; `?` slots never recorded) is equivalent to the backward id-chain anchored on the transcript succeeding. Consuming snapshot-render's full walk on the hit path would pay the very O(N) parse this fastpath exists to avoid (guidance item 2), so the set-diff fronts the SAME semantic contract as the primary cheap gate, and snapshot-render serves as the confirmation layer where it is free: on a watermark MISS turn the full parse is already paid, so a light identity-row-only probe (`probeTranscriptAlignment`, identity rows only, no content bytes) cross-checks the ledger view against the unified transcript and logs the verdict once per session (dormant unless `snapshotRender` rollout is also on). What remains of the old stack, and why: width arithmetic is kept as SHIM PROTOCOL shape validity (it locates the window origin K server-side); the origin pin (`tail-ids-prev`) is kept because gap-tolerant alignment would ride a re-minted origin slot the client no longer claims; the head SYSTEM-text gate stays gating in both modes (a prompt has no msgid — flagged deviation, serving a stale prompt beats saving one parse); model switching keeps its physical projection partition (R6: one derived projection per (model × wire format) sharing ONE logical ledger — the first request for a new model pays one full legacy pass building that projection, subsequent turns are pure incremental appends; the `m` field demotes from world-partition to projection-cache key). NEW in v6: (a) a mid-history unknown-real id inside the verified range — a structural rewrite whose shape survived the width+origin gates (client compaction/insertion) — takes ONE conservative credited legacy pass and rides passthrough-as-new-message from the next turn (`watermarkCompactionPassthrough` knob, default ON; OFF restores pre-v6 ride-with-diagnostic for those turns): the summary block carries fresh ids, the set-diff appends them naturally, NO suppression logic (R4/O3); (b) an UNIDENTIFIABLE increment (body grew but the increment carries no host id at all) hits normally but logs a structured diagnostic and appends nothing to the ledger — never speculative rebuilds (R5); (c) a client session-header digest swap (cs gate, R7) now ALSO holds the ledger — the swapped conversation's ids never fold into this session's cumulative ledger. Count-only turns are byte-identical to pre-v6 in every branch. + 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). diff --git a/TECHNICAL-NOTES.zh-CN.md b/TECHNICAL-NOTES.zh-CN.md index 1238f933a2..e3dac0a848 100644 --- a/TECHNICAL-NOTES.zh-CN.md +++ b/TECHNICAL-NOTES.zh-CN.md @@ -161,6 +161,8 @@ chat wire 上 bili 自己 vs 客户端自带:插件车道上,请求体里等于 声明的信任边界(§7.4——必须人工评审,禁止自动合并):**保元素数不变的前缀字节改写不可检测**——锚点除外:v2 在锚点比对 carried prevId 与存锚,id 重铸 = 一次 UNcredited miss + 下一轮自愈。这就是跳过逐条字节复核的全部代价;该代价已过 §7.4 人工评审,故以**实验性灰度**出厂——默认仅约 5% 的安装开启(owner 裁定 2026-11-02:先小流量,web 面板对全部安装显示一次性公告直到关闭、快速配置提供三态开关),A/B 黄金测试钉死出站字节逐字一致,并提供 per-install 开/关(`rollout.features.pluginFullResendWatermark: true|false` / `BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK=1|0`)。破坏性改写(通告 compaction、截断、重排)都会改变 count,在任何陈旧 core 喂给内核之前就被判掉——在 v4 下这道拦截从客户端回显移到宽度算式本身:前缀收缩要求一个非正宽度,任何 id 列表都不可能满足,credited `ahead` / `seed-stale` 判决与 pre-v4 完全一致地触发。 +**v6 标准账本统一(owner 裁定 2026-11-03,契约 R1–R8):** 命中判决现在派生自标准(transcript)对齐而非快路径自己的并行字节门。机制上,对齐的 id 快速路径恰好就是 shim tail-ids 所编码的东西——宿主 msgid 永世唯一,所以「对会话累计宿主 id 账本(`pf:state.lg`,FIFO 上限 2048 真实 id;`?` 槽永不记录)纯追加的列表」等价于「锚在 transcript 上的向后 id 链成功」。若命中路径直接消费 snapshot-render 的完整走查,就会付上本快路径专为避免的 O(N) 解析(指导项 2),因此集合差作为同一语义契约的首要廉价门前置,而 snapshot-render 担任免费时的确认层:水位 MISS 回合全量解析本已付出,此时一个只读身份行的轻量探针(`probeTranscriptAlignment`,仅身份行、无内容字节)将账本视图与 unified transcript 交叉核对并每会话记一条日志(除非 `snapshotRender` rollout 同时开启,否则休眠)。旧栈保留的部分及理由:宽度算术保留为 SHIM 协议形状有效性(服务端定位窗口起点 K);起点钉(`tail-ids-prev`)保留,因为容隙对齐会骑在客户端已不再声明的重铸起点槽上;头部 SYSTEM 文本门两种模式下都保留生效(prompt 没有 msgid——flagged 偏差:宁可省一次解析也不能服务陈旧 prompt);模型切换保留物理投影分区(R6:每 (model × wire format) 一份派生投影、共享一份逻辑账本——某新模型的首个请求付一次全量 legacy pass 建立该投影,后续回合纯增量追加;`m` 字段从世界分区降格为投影缓存键)。v6 新增:(a) 已验证范围内出现中历史未知真实 id——形状存活于宽度+起点门之后的结构性改写(客户端压缩/插入)——付一次保守的计名 legacy pass,下一轮起按新消息透出(`watermarkCompactionPassthrough` 旋钮,默认开;关 = 这些回合恢复 pre-v6 骑存+诊断):摘要块带新 id,集合差自然追加,无抑制逻辑(R4/O3);(b) 不可辨识增量(正文变大但增量完全不带宿主 id)正常命中但记结构化诊断、不向账本追加——永不做猜测式重建(R5);(c) 客户端会话头摘要切换(cs 门,R7)现在同时扣住账本——换入会话的 id 绝不折入本会话累计账本。纯计数回合在所有分支上与 pre-v6 逐字节相同。 + 诚实边界:(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`(门矩阵,双向)。 diff --git a/src/rollout.ts b/src/rollout.ts index 3621170274..f2776bc43c 100644 --- a/src/rollout.ts +++ b/src/rollout.ts @@ -106,6 +106,18 @@ export const ROLLOUT_FEATURES: Record = { // `BILI_ROLLOUT_NATIVE_IDENTITY_OBSERVATION=1` or // `rollout.features.nativeIdentityObservation: true`. nativeIdentityObservation: { percent: 0 }, + // #5403/#5418 v6 canonical-ledger unification (contract R4): client-side + // structural rewrites — the compaction/insertion shapes that survive the + // width + origin gates with a shape-valid tail-id list — take ONE + // conservative legacy pass and ride PASSTHROUGH-AS-NEW-MESSAGE from the + // next turn: the rewritten/summary elements carry fresh host ids that + // the incremental ledger appends (R2), no suppression logic, never a + // speculative rebuild (O3). Nested under pluginFullResendWatermark — + // dead weight outside the watermark cohort. Default ON (percent 100 + // inside base) = passthrough; OFF = pre-v6 behavior for rewrite-shaped + // turns only. Force off with `rollout.features.watermarkCompactionPassthrough: + // false` or `BILI_ROLLOUT_WATERMARK_COMPACTION_PASSTHROUGH=0`. + watermarkCompactionPassthrough: { percent: 100, base: "pluginFullResendWatermark" }, }; export const BP_MAX = 10_000; diff --git a/website/config-reference/rollout.yaml b/website/config-reference/rollout.yaml index 70b013aa26..4d67c98dcd 100644 --- a/website/config-reference/rollout.yaml +++ b/website/config-reference/rollout.yaml @@ -73,3 +73,11 @@ entries: group: behavior desc_en: "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”." desc_zh: "全量重发水位快路径(#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「全量重发水位快路径」。" + - key: rollout.features.watermarkCompactionPassthrough + type: "boolean | number" + default: "100 (on, nested under pluginFullResendWatermark)" + default_zh: "100(开,嵌套于 pluginFullResendWatermark)" + env: BILI_ROLLOUT_WATERMARK_COMPACTION_PASSTHROUGH + group: behavior + desc_en: "Watermark v6 canonical-ledger unification (#5403/#5418 v6): when the plugin-lane watermark turn carries a shape-valid host-id list AND a mid-history unknown id sits before a still-known one — a client structural rewrite (compaction/insertion) that changed what the stashed prefix cores describe — this knob decides the verdict: ON (default) pays ONE conservative legacy pass for that turn (credited miss, self-healing re-stamp) so the increment rides through as new messages from the next turn with its fresh ids appended to the session's cumulative host-id ledger (pf:state.lg, FIFO-capped) — no suppression logic, never speculative rebuilds; OFF restores the pre-v6 behavior for those turns (the rewrite rides the stashed prefix under the identity-only ruling, byte-compare demoted to diagnostic). Only matters for id-list turns inside an already-enabled watermark cohort; count-only turns are byte-identical either way. Force off with false / env = 0. See TECHNICAL-NOTES.md \"Full-resend watermark fastpath\"." + desc_zh: "水位 v6 标准账本统一(#5403/#5418 v6):当插件车道水位回合携带形状合格的宿主 id 列表,且已验证范围内出现「已知 id 之前还有未知真实 id」——客户端结构性改写(压缩/插入)已经改变了钉存前缀核所描述的内容——本旋钮决定判决:开(默认)为该回合付一次保守的 legacy 全量解析(计名 miss,自愈重盖戳),增量从下一轮起以新消息形态透出、其新 id 追加进会话累计宿主 id 账本(pf:state.lg,FIFO 上限)——无抑制逻辑、永不做猜测式重建;关 = 这些回合回退 pre-v6 行为(改写在身份-only 裁定下骑钉存前缀,字节比对降为诊断)。仅影响 id 列表回合且限已启用水位队列内;纯计数回合两种取值逐字节相同。false / env = 0 强制关。见 TECHNICAL-NOTES.zh-CN.md「全量重发水位快路径」。" From 26c8fa8a8767c25426aea8298ca32d4e0d055165 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 3 Nov 2026 13:43:06 +0800 Subject: [PATCH 07/15] v6: persist cumulative host-id ledger pf:state.lg (R2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The watermark identity channel already carried the per-turn tail-id list; this commit adds the CUMULATIVE ledger it needs — the set-diff baseline for the canonical-ledger hit decision (contract R1/R2, owner rulings 2026-11-03): - PFSavedState.lg: ordered real host ids ever observed on this session's channel, FIFO-capped (PF_LEDGER_CAP 2048 entries / PF_LEDGER_MAX_BYTES 48KB serialized, oldest dropped first). '?' slots never recorded. MODEL-INDEPENDENT by design (R6): projections partition on (model × wire format), the logical ledger does not. - Sole growth site is finalizeWatermarkTurn: grow only when the turn delivered a shape-valid list AND the new watermarkCompactionPassthrough knob is on AND the conversation did not swap (ledgerHold, contract R7 — a cs-gated turn's ids describe a DIFFERENT conversation and must not fold into this session's baseline). Non-grow turns carry the stored ledger forward unchanged. Bootstrap/migration falls back to l. - Append-only: no server-authored text ever enters (R2); entries are the client's own screened id surface (parseTailIds all-or-nothing). - Fixes noteCreditedMiss arm-path dropping l on breaker trip — the breaker firing would have wiped exactly the ledger state rewrite-heavy clients rely on (l is now preserved alongside lg). - FastpathOutcome gains optional ledgerHold (additive, consumed by finalize; produced in the next commit). --- src/server/fastpath.ts | 77 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 3 deletions(-) diff --git a/src/server/fastpath.ts b/src/server/fastpath.ts index eaa654fb99..6d19f97d3a 100644 --- a/src/server/fastpath.ts +++ b/src/server/fastpath.ts @@ -72,6 +72,12 @@ const HEAD_CHECK_ELEMENTS = 8; const PF_BREAKER_MISSES = 5; const PF_DISABLED_TTL_MS = 60 * 60 * 1000; const PF_EXT_KEY = "pf:state"; +// #5403/#5418 v6 (contract R2): bounds for the cumulative host-id ledger +// (`lg`). Entry shape mirrors parseTailIds screening (len 1..512, no '?'); +// the FIFO drop and serialized-size guard follow the obs layer's ≤4KB-style +// discipline scaled to the watermark cohort's realistic history depth. +const PF_LEDGER_CAP = 2048; +const PF_LEDGER_MAX_BYTES = 48 * 1024; interface PFSavedState { t: number; @@ -81,6 +87,17 @@ interface PFSavedState { /** Last received tail-id list (#5418 v2) — survives restarts so the * prevId continuity check is live on the first turn back. */ l?: string[]; + /** #5403/#5418 v6 (contract R2): CUMULATIVE host-id ledger for THIS + * session — every real id ever observed on the channel, in order, + * FIFO-capped (oldest dropped past PF_LEDGER_CAP / serialized-size + * guard); '?' slots never recorded. MODEL-INDEPENDENT by design (R6): + * projections partition on (model × wire format), the logical ledger + * does not — a model flip rebuilds the projection but inherits the + * id bookkeeping. Grown ONLY in finalizeWatermarkTurn from this + * turn's shape-valid list (no server-authored text ever enters); + * consumed as the set-diff baseline for the v6 rewrite classification. + * Bootstrap/migration: sessions predating v6 fall back to `l`. */ + lg?: string[]; /** #5571 v5: client-native session id digest recorded with this state * (h8, never raw — privacy parity with #5571); sess-change gate input. */ cs?: string; @@ -148,6 +165,12 @@ export interface FastpathOutcome { * (undefined when no known header carried a value). Persisted by * finalize as state `cs`; feeds the sess-change identity gate. */ readonly clientSess?: string; + /** #5403/#5418 v6 (contract R7): set when the cs (sess-change) gate + * fired — the incoming conversation SWAPPED. finalize honors it by + * holding the cumulative ledger: a swapped-in conversation's ids must + * never fold into this session's ledger (they describe different + * clients' history and would poison the set-diff baseline). */ + readonly ledgerHold?: boolean; } /** #5418 v2: decode the shim's x-bili-pf-tail-ids value. @@ -198,6 +221,9 @@ function readSaved(sessionId: string): PFSavedState | null { l: Array.isArray(o.l) && o.l.length > 0 && o.l.length <= 2048 && (o.l as unknown[]).every((x): x is string => typeof x === "string" && x.length > 0 && x.length <= 512) ? (o.l as string[]) : undefined, + lg: Array.isArray(o.lg) && o.lg.length > 0 && o.lg.length <= PF_LEDGER_CAP + && (o.lg as unknown[]).every((x): x is string => typeof x === "string" && x.length > 0 && x.length <= 512) + ? (o.lg as string[]) : undefined, cs: typeof o.cs === "string" && o.cs.length === 8 ? o.cs : undefined, }; } catch { @@ -213,6 +239,43 @@ function writeSaved(sessionId: string, state: PFSavedState): void { } catch { /* state is advisory — losing it degrades to verify-next-turn */ } } +/** #5403/#5418 v6 (contract R2): grow the cumulative host-id ledger from + * one shape-valid tail-id list. Real ids append in list order, deduped; + * '?' slots never enter (unknown identity claims nothing); the result is + * FIFO-trimmed to PF_LEDGER_CAP entries / PF_LEDGER_MAX_BYTES serialized + * (oldest dropped first). Append-only — server-authored text is NEVER + * injected here (R2), the list is the client's own id surface as screened + * by parseTailIds. No-op turns (nothing new) return the previous ledger so + * the persisted state is untouched. */ +function growPfLedger( + saved: PFSavedState | null, + list: readonly string[], +): string[] | undefined { + // Bootstrap/migration: pre-v6 sessions carry only `l` (last list). + const base = saved?.lg ?? saved?.l ?? []; + const known = new Set(base); + const out: string[] = []; + for (const id of base) { + if (!known.has(id)) known.add(id); // defensive dedupe of hand-edited state + out.push(id); + } + for (const id of list) { + if (id === PF_SLOT_UNKNOWN || known.has(id)) continue; + known.add(id); + out.push(id); + } + // Serialized-size estimate: two quotes + one separator per entry + // (JSON escapes in exotic id alphabets only inflate a little; the + // per-entry len cap bounds the worst case). + const jsonLen = (arr: string[]): number => arr.reduce((n, s) => n + s.length + 3, 1); + while (out.length > PF_LEDGER_CAP || jsonLen(out) > PF_LEDGER_MAX_BYTES) { + const dropped = out.shift(); + if (dropped !== undefined) known.delete(dropped); + if (out.length === 0) return undefined; // pathological — start fresh next list + } + return out.length > 0 ? out : undefined; +} + function breakerArmed(saved: PFSavedState | null): boolean { return saved?.disabledAt !== undefined && Date.now() - saved.disabledAt < PF_DISABLED_TTL_MS; } @@ -504,7 +567,7 @@ function noteCreditedMiss(sessionId: string, decision: string, log: (level: stri const staleHold = cur.disabledAt !== undefined && Date.now() - cur.disabledAt >= PF_DISABLED_TTL_MS; const misses = (staleHold ? 0 : cur.misses) + 1; if (misses >= PF_BREAKER_MISSES) { - writeSaved(sessionId, { t: cur.t, m: cur.m, misses, disabledAt: Date.now(), cs: cur.cs }); + writeSaved(sessionId, { t: cur.t, m: cur.m, misses, disabledAt: Date.now(), l: cur.l, lg: cur.lg, cs: cur.cs }); log("warn", `[${sessionId}] watermark fastpath disabled for ${Math.round(PF_DISABLED_TTL_MS / 60000)}m after ${misses} consecutive verified misses (last: ${decision}) — legacy full-parse continues`); } else { writeSaved(sessionId, { ...cur, misses, disabledAt: staleHold ? undefined : cur.disabledAt }); @@ -531,6 +594,14 @@ export function finalizeWatermarkTurn( if (outcome.measuredT === undefined) return headers; const T = outcome.measuredT; const saved = readSaved(session.id); + // #5403/#5418 v6 (R2/R7): sole ledger growth site. Grow when this turn + // delivered a shape-valid list, the v6 knob is on, and the conversation + // did not swap (cs gate fired ⇒ ledgerHold — a swapped-in conversation's + // ids must not fold into this session's baseline). Non-grow turns carry + // the stored ledger forward unchanged (never wipe). + const lg = outcome.receivedTailIds !== undefined && !outcome.ledgerHold && featureEnabled("watermarkCompactionPassthrough") + ? growPfLedger(saved, outcome.receivedTailIds) + : saved?.lg; if (outcome.hit) { seeds.set(session, { cores: outcome.hit.view, @@ -541,7 +612,7 @@ export function finalizeWatermarkTurn( lastTailIds: outcome.receivedTailIds, multimodal: outcome.hit.seedMultimodal, }); - writeSaved(session.id, { t: T, m: input.model, misses: 0, l: outcome.receivedTailIds, cs: outcome.clientSess ?? saved?.cs }); + writeSaved(session.id, { t: T, m: input.model, misses: 0, l: outcome.receivedTailIds, lg, cs: outcome.clientSess ?? saved?.cs }); headers[PF_SEQ_HEADER] = String(T); return headers; } @@ -558,7 +629,7 @@ export function finalizeWatermarkTurn( } // Held (breaker-armed) turns flow through here too and DO restamp: the // stamp is how a client converges on truth while the lane stays hit-less. - writeSaved(session.id, { t: T, m: input.model, misses: saved?.misses ?? 0, disabledAt: saved?.disabledAt, l: outcome.receivedTailIds, cs: outcome.clientSess ?? saved?.cs }); + writeSaved(session.id, { t: T, m: input.model, misses: saved?.misses ?? 0, disabledAt: saved?.disabledAt, l: outcome.receivedTailIds, lg, cs: outcome.clientSess ?? saved?.cs }); headers[PF_SEQ_HEADER] = String(T); return headers; } From abace8c4853c0fa351c8305ebc6ecbc7cfa07abb Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 3 Nov 2026 13:44:32 +0800 Subject: [PATCH 08/15] =?UTF-8?q?v6:=20canonical-ledger=20hit=20decision?= =?UTF-8?q?=20=E2=80=94=20rewrite-passthrough,=20R5=20diagnostics=20(R1/R4?= =?UTF-8?q?/R5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The watermark HIT DECISION now derives from the canonical ledger instead of the fastpath's own parallel byte gates. Consuming snapshot-render's full walk on the hit path would pay the O(N) parse this lane exists to avoid, so the shim tail-ids SET-DIFF against pf:state.lg fronts the same semantic contract as the primary cheap gate — host msgids are unique forever, so a pure-append list is equivalent to the backward id-chain anchored on the transcript succeeding (snapshot-render's id fast-path). - New layer after the cs gate (R7 placement), id mode only, knob-gated: a REAL id arriving mid-list before a still-known id proves in-range structural mutation (client compaction/insertion); verdict = ONE conservative CREDITED legacy pass ('rewrite-passthrough'), then the increment rides passthrough-as-new-message from the next turn — fresh ids append naturally via finalize set-diff, NO suppression logic, never speculative rebuilds (R4/O3). Knob OFF skips the layer entirely: pre-v6 ride-with-diagnostic semantics. - Ids OUTSIDE [K-1..T-1] legitimately never reappear in traffic, so 'vanishing from the list' is not a signal — only mid-list unknowns are. Index 0 (window origin) stays with the origin pin, which explicitly neutralizes an unknown no-claim origin (#5418 v3/#5571 v5). - R5: body grew (T > K) but the increment carries no host id at all ⇒ hit proceeds on the stashed snapshot (every verifiable gate agreed) + structured diagnostic, ledger append stays a natural no-op; model- switch/fork id-space questions deferred to research holds O1/O2. - tail-ids-prev miss now carries the shape-valid list so its observed ids still enter the ledger (R2 completeness; count-only turns unaffected). - cs-gate miss sets ledgerHold=true (finalize then holds lg — a swapped-in conversation's ids never fold into this session's baseline, R7). - Header doctrine + PFSeed.model comment updated: m demoted from world-partition to projection-cache key over ONE logical ledger (R6); kept gates documented where alignment cannot cover them (width = shim-protocol shape/origin K; origin pin = gap-tolerant alignment would ride a reminted origin; head system-text = prompt has no msgid). --- src/server/fastpath.ts | 108 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 98 insertions(+), 10 deletions(-) diff --git a/src/server/fastpath.ts b/src/server/fastpath.ts index 6d19f97d3a..bcdd90ca89 100644 --- a/src/server/fastpath.ts +++ b/src/server/fastpath.ts @@ -11,10 +11,26 @@ // * the tail fragment [k..T) — the only genuinely new content // * each remaining top-level field individually (scalars + tools) // Prefix CORES come from the in-memory seed: the previous turn's canonical -// openaiToCore output. Reuse is sound because wire identity is deterministic +// openaiToCore output, SHARED across model projections (contract R6): one +// logical ledger (`pf:state.lg`) per session, one derived projection per +// (model × wire format) — the first request for a new model pays one full +// legacy pass building that projection, subsequent turns are pure +// incremental appends. Reuse is sound because wire identity is deterministic // (content-hash canonical ids, #3642): the legacy re-parse would mint exactly // the same cores for unchanged bytes. // +// v6 canonical-ledger unification (owner rulings 2026-11-03, contract +// R1–R8): the HIT DECISION derives from the canonical transcript ALIGNMENT, +// not from parallel byte gates. Mechanically, snapshot-render's id fast-path +// IS this channel's set-diff: host msgids are unique forever, so a list that +// is a PURE APPEND to the session's cumulative ledger (`pf:state.lg`) is +// equivalent to the backward id-chain anchored on the transcript succeeding. +// Consuming snapshot-render's full walk here would pay the very O(N) parse +// this lane exists to avoid (guidance item 2) — the set-diff fronts the same +// semantic contract as the primary cheap gate; snapshot-render confirms on +// the free turns (miss turns already pay the full parse; see +// probeTranscriptAlignment). +// // Fail-soft contract (anti-deviation lock): the legacy pipeline is UNTOUCHED // code — this module only swaps the inputs the caller feeds it when EVERY // gate agrees. Any doubt (missing/garbage stamp — UNLESS a ledger-proven @@ -26,11 +42,20 @@ // // Declared trust boundary (§7.4 human review required): a client that edits // prefix bytes while keeping the element count constant is NOT detected (the -// cost of skipping byte-level re-verification). Destructive rewrites — -// announced compaction, truncation, reorders that add/remove elements — -// change the count and are caught by the k-behind/k-ahead verdicts before -// any stale core could feed the kernel; under v4 (count relaxation below) -// the catch moves from the client echo to the ledger width arithmetic itself. +// cost of skipping byte-level re-verification). v6: the verdict rides the +// CANONICAL LEDGER instead of byte comparison — the list must be a pure +// append to pf:state.lg (host msgids unique forever); a structural rewrite +// that survives the shape gates takes ONE conservative credited legacy pass +// and the increment rides passthrough-as-new-message from the next turn +// (watermarkCompactionPassthrough knob, default ON; R4/O3), never a +// speculative rebuild. The remaining pre-v6 gates survive WHERE ALIGNMENT +// CANNOT COVER THEM: width arithmetic = shim-protocol shape validity + +// server-side window-origin K (it re-verifies the exact width the ids assert); +// the origin pin = a gap-tolerant alignment would ride a re-minted origin +// slot the client no longer claims; the head SYSTEM-text gate = a prompt has +// no msgid (flagged deviation: serving a stale prompt beats saving one +// parse); model switch = physical projection partition (R6) over ONE logical +// ledger. Count-only turns stay byte-identical to pre-v6 in every branch. import type { CoreMessage } from "acp-kernel"; import type { OpenAIRequestBody } from "acp-kernel/wire"; import { openaiToCore } from "acp-kernel/wire"; @@ -108,6 +133,9 @@ interface PFSeed { /** Verified head system run the stash was built under (real bytes). */ readonly systemText: string; readonly stampT: number; + /** Projection-cache key (v6/R6): the seed is ONE (model × wire-format) + * projection over the shared logical ledger — a model flip rebuilds the + * projection via one legacy pass but keeps the id bookkeeping (`lg`). */ readonly model: string; /** Full-body marker-strip ledger carried from the seed turn — the middle * region is never re-scanned, so its stripped-marker accounting rides @@ -324,10 +352,10 @@ export function evaluateWatermarkFastpath( // #5571 v5: captured ONCE per evaluated turn — feeds the sess-change gate // below and rides the outcome so finalize persists it as state `cs`. const nowCs = clientSessDigest(req); - const miss = (decision: string, credited: boolean, receivedTailIds?: string[]): FastpathOutcome => { + const miss = (decision: string, credited: boolean, receivedTailIds?: string[], ledgerHold?: boolean): FastpathOutcome => { if (credited) noteCreditedMiss(session.id, decision, log); log("info", `[${session.id}] watermark fastpath miss (${decision}) — legacy full-parse this turn`); - return { hit: null, measuredT: T, decision, creditedMiss: credited, receivedTailIds, clientSess: nowCs }; + return { hit: null, measuredT: T, decision, creditedMiss: credited, receivedTailIds, clientSess: nowCs, ...(ledgerHold !== undefined ? { ledgerHold } : {}) }; }; const seed = seeds.get(session); const rawTailIds = req.headers[PF_TAIL_IDS_HEADER]; @@ -378,7 +406,7 @@ export function evaluateWatermarkFastpath( const prevKnown = seed.lastTailIds !== undefined && seed.lastTailIds.length > 0 ? seed.lastTailIds[seed.lastTailIds.length - 1] : undefined; // "?" on EITHER side = no identity claim — no penalty; the // byte-level head checks below remain the boundary truth - if (prevKnown !== undefined && prevKnown !== PF_SLOT_UNKNOWN && tailIds[0] !== prevKnown) return miss("tail-ids-prev", false); + if (prevKnown !== undefined && prevKnown !== PF_SLOT_UNKNOWN && tailIds[0] !== prevKnown) return miss("tail-ids-prev", false, tailIds); } } // #5571 v5 (owner ruling 2026-11-03): session continuity joins the @@ -390,7 +418,59 @@ export function evaluateWatermarkFastpath( // asserted only when both sides do. Id mode only (no valid list // reached here without one). if (tailIds !== undefined && saved?.cs !== undefined) { - if (nowCs !== undefined && nowCs !== saved.cs) return miss("sess-change", false, tailIds); + if (nowCs !== undefined && nowCs !== saved.cs) return miss("sess-change", false, tailIds, true); + } + // --- v6 canonical-ledger classification (contract R1/R2/R4/R5) ----- + // Runs LAST among identity gates: width (shape/origin K) and the + // origin pin above have already proven the window anchors on the + // verified range, and the cs gate has ruled out conversation swaps. + // The list spans slots [K-1 .. T-1], so every REAL id in it is either + // (a) the window origin — pinned above, neutralized there when the + // client re-mints it with no claim (#5418 v3) — or (b) inside the + // verified range [K .. T-1]. Ids OUTSIDE [K-1..] legitimately never + // reappear (pure-append traffic), so "vanishing from traffic" is NOT + // a signal — the only thing detectable HERE is a REAL id that arrived + // MID-LIST before a still-known id: history was structurally mutated + // (client compaction summary inserted between two ids this session + // already saw, or rows inserted/reordered) — the stashed prefix cores + // describe a world the client no longer resends. With + // watermarkCompactionPassthrough ON (default, R4/O3): ONE conservative + // legacy pass (CREDITED — parity with the pre-v6 credited `ahead`/ + // head-drift catches; bounded by the 1h breaker on pathological + // cycles), then the increment rides PASSTHROUGH-AS-NEW-MESSAGE from + // the next turn — the summary block carries fresh host ids, the + // finalize set-diff appends them naturally, NO suppression logic, and + // never a speculative rebuild. OFF: skipped entirely — pre-v6 + // semantics (such a list passes everything below and rides the + // stashed prefix under the v5 identity-only ruling, byte-compare + // demoted to the diagnostic warn further down). + let v6UnidentifiableIncrement = false; + if (tailIds !== undefined && featureEnabled("watermarkCompactionPassthrough")) { + const baseline = saved?.lg ?? saved?.l ?? []; + const known = new Set(baseline); + // Trailing region = maximal suffix holding NO known real id: + // exactly the fresh increment ('?' counts as trailing-neutral; + // an unknown real id claims NEWNESS, a known one ends the region). + let cursor = tailIds.length; + let newRealCount = 0; + while (cursor > 0) { + const s = tailIds[cursor - 1]; + if (s !== PF_SLOT_UNKNOWN && known.has(s)) break; + if (s !== PF_SLOT_UNKNOWN) newRealCount += 1; + cursor -= 1; + } + // Mid-list check over indices [1, cursor): index 0 is the window + // ORIGIN — handled by the origin pin above (an unknown origin is + // explicitly neutralized there, #5418 v3/#5571 v5). + let midInsertion = false; + for (let i = 1; i < cursor; i++) { + if (tailIds[i] !== PF_SLOT_UNKNOWN && !known.has(tailIds[i])) { midInsertion = true; break; } + } + if (!midInsertion) v6UnidentifiableIncrement = T > K && newRealCount === 0; + if (midInsertion) { + return miss("rewrite-passthrough", true, tailIds); + } + log("debug", `[${session.id}] [pf-v6] set-diff ok: ${newRealCount} new real id(s), trailing region ${tailIds.length - cursor}/${tailIds.length} slots, ledger ${baseline.length}`); } if (seed.multimodal) return miss("seeded-multimodal", false, tailIds); const headEnd = Math.min(HEAD_CHECK_ELEMENTS, T); @@ -452,6 +532,14 @@ export function evaluateWatermarkFastpath( if (contentDrifts > 0) log("warn", `[${session.id}] watermark v5: ${contentDrifts}/${driftTotal} head element(s) differ from the seed under stable host ids — riding the stashed prefix per owner ruling 2026-11-03 (diagnostic only; feeds M3 re-seeding signals)`); const windowRaw = openaiToCore(windowFragment as OpenAIRequestBody); if (windowRaw.systemText.trim() !== "") return miss("window-system-head", true, tailIds); + // R5: the body GREW (T > K) yet the increment carries NO host id — + // an unidentifiable delta. We do NOT speculate: replay the stashed + // snapshot (hit proceeds normally — every verifiable gate agreed) + // and leave the ledger untouched (growth below is a natural no-op); + // the structured diagnostic marks the gap for M3. Model-switch / fork + // id-space questions live in research holds O1/O2 (contract) — no + // speculative rebuild behavior may land ahead of them. + if (v6UnidentifiableIncrement) log("warn", `[${session.id}] [pf-v6] unidentifiable-increment: T=${T} K=${K} — body grew but the increment carries no host id; replaying the stashed snapshot WITHOUT ledger append (R5; model-switch/fork id behavior pending research holds O1/O2)`); const rekeyedWindow = rekeyWindowCores(windowRaw.msgs, K, seed.cores); // v4 diagnostics ride the decision string (the debug/panel surfaces // already print it): pure count mode stays byte-identical "hit" — From bcf0cf752cbe879af018816a1c3fe50dbdf83e21 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 3 Nov 2026 13:45:59 +0800 Subject: [PATCH 09/15] v6: transcript-alignment confirmation probe on watermark miss turns (R1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cheap set-diff gate is the id fast-path of the canonical alignment — this adds the confirmation layer where it costs nothing: on a watermark MISS turn the full O(N) parse is already paid, so prepare-openai runs a light backward id-chain over store.unifiedMessageIdRows (identity rows ONLY — no content bytes loaded) and logs whether the client's live tail anchors into the unified transcript. One log per session at most (metadata latch); dormant unless the snapshotRender rollout cohort is active with ≥1 active block — outside that cohort it is a blocks check. probeTranscriptAlignment is deliberately standalone rather than extracted from buildView: this module is render authority (#3812/#4241), and an observability probe must not couple doctrine-critical walk code to a diagnostics path. Strict-contiguous walk + MIN_SEAM_RUN floor mirror the alignment's gap discipline; it reports reasons (no-active-blocks / store-unavailable / transcript-error / transcript-empty / chain-not-started / seam-too-short) for M3 ledger-vs-transcript cross-checks. --- src/server/prepare-openai.ts | 13 +++++++- src/server/snapshot-render.ts | 61 +++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index ab8f430473..582d092c8d 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -13,7 +13,7 @@ import { yieldToEventLoop } from "../yield-loop.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; -import { maybeSnapshotView } from "./snapshot-render.js"; +import { maybeSnapshotView, probeTranscriptAlignment } from "./snapshot-render.js"; import { storedMessagesFor, storedRowLookupFor } from "../fold-decomposition-lookup.js"; import { nudgeSuppressed } from "../session-self-heal.js"; import { compressBreakerArmed } from "../stream.js"; @@ -164,6 +164,17 @@ export async function prepareOpenai( openaiSystemText = outcome.outbound; } originalMessages = msgs; + // #5403/#5418 v6 (R1) confirmation layer: on a watermark MISS turn + // the full parse is already paid — let the CANONICAL transcript + // confirm/contradict the ledger's view with a light identity-rows-only + // probe (no content bytes), one log per session at most. + if (wpOutcome !== null && wpHit === undefined && featureEnabled("snapshotRender") + && session.state.blocks.some((b) => b.active) + && session.metadata["pfV6ConfirmLogged"] !== true) { + session.metadata["pfV6ConfirmLogged"] = true; + const probe = probeTranscriptAlignment(session, originalMessages); + log("debug", `[${session.id}] [pf-v6] transcript-alignment confirmation after watermark miss (${wpOutcome.decision}): ${probe.anchored ? `anchored (join row ${probe.joinRow})` : `not anchored (${probe.reason ?? "unknown"})`}`); + } // #3756 snapshot render: the outbound prefix renders from the unified // transcript (server-authoritative, fold-time ids — immune to identity // re-mints #3752); only the live tail keeps the client's bytes. diff --git a/src/server/snapshot-render.ts b/src/server/snapshot-render.ts index 6cedbcf677..ef6a829d1f 100644 --- a/src/server/snapshot-render.ts +++ b/src/server/snapshot-render.ts @@ -85,6 +85,67 @@ export function identitySigForTest(m: BiliMessage): string { return identitySig(m); } +// #5403/#5418 v6 (contract R1): observability-only confirmation layer. The +// watermark lane's cheap gate is the shim tail-ids SET-DIFF against its +// cumulative ledger — equivalent to this chain's ID FAST-PATH (host msgids +// unique forever ⇒ pure-append list ⟺ backward id-chain from client end), +// minus the signature fallback, which by definition never fires for an id- +// carried request. Running buildView's full walk on watermark hit turns would +// pay the O(N) parse the fastpath exists to avoid; on MISS turns the parse is +// already paid, so a light probe (identity rows ONLY — no content bytes) lets +// the canonical transcript confirm or contradict the ledger's view. One log +// per session at most (latch lives in session.metadata). Deliberately NOT +// reused from buildView: this module is render authority (#3812/#4241) — the +// probe must not couple doctrine-critical walk code to a diagnostics path. +export interface TranscriptProbeResult { + readonly anchored: boolean; + /** Human-readable reason when not anchored. */ + readonly reason?: string; + /** Unified-transcript row where the client tail joins, when anchored. */ + readonly joinRow?: number; +} + +/** Backward STRICT-contiguous id chain over unifiedMessageIdRows — the same + * proof snapshot-render's anchor alignment produces for id-carried tails, + * without rendering anything. See TranscriptProbeResult for placement. */ +export function probeTranscriptAlignment( + session: Session, + clientMsgs: readonly { readonly id: string }[], +): TranscriptProbeResult { + if (!session.state.blocks.some((b) => b.active)) return { anchored: false, reason: "no-active-blocks" }; + const store = getStore(); + if (!store.replicasAvailable()) return { anchored: false, reason: "store-unavailable" }; + let rows: Array<{ seq: number; msgId: string }> | null; + try { + rows = store.unifiedMessageIdRows(session.id); + } catch { return { anchored: false, reason: "transcript-error" }; } + if (!rows || rows.length === 0) return { anchored: false, reason: "transcript-empty" }; + const indexById = new Map(); + for (let i = rows.length - 1; i >= 0; i--) { + const r = rows[i]; + if (r && typeof r.msgId === "string" && r.msgId.length > 0 && !indexById.has(r.msgId)) indexById.set(r.msgId, i); + } + // Contiguous backward walk: any skip between matches breaks the run + // (the transcript has rows the client no longer sends ⇒ structural + // divergence, same discipline as buildView's gap handling). + let prevRow = Infinity; + let started = false; + let run = 0; + let joinRow: number | undefined; + for (let i = clientMsgs.length - 1; i >= 0; i--) { + const row = indexById.get(clientMsgs[i].id); + if (row === undefined) { break; } + if (started && row !== prevRow - 1) break; + started = true; + run += 1; + joinRow = row; + prevRow = row; + } + if (!started) return { anchored: false, reason: "chain-not-started" }; + if (run < MIN_SEAM_RUN) return { anchored: false, reason: "seam-too-short", joinRow }; + return { anchored: true, joinRow }; +} + interface ViewRow { seq: number; msgId: string; From 2267337c8e845758c7129c93519243ddfdf9e729 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 3 Nov 2026 14:02:54 +0800 Subject: [PATCH 10/15] v6: document the mid-insertion proof requirement of rewrite-passthrough (R4/O3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The structural-rewrite layer fires only on "unknown real id BEFORE a still-known slot". Spell out WHY that is the sole id-provable mutation shape: - lists span elements [K-1..T-1], so old ledger ids legitimately never reappear; "vanishing from traffic" is not a signal; - an unknown at index 0 (the ORIGIN slot) can never reach this layer — the origin pin above has already verified or missed it (#5418 v3 / #5571 v5); - a pure trailing run of fresh ids — incl. a full-history compaction summary minting fresh ids — is indistinguishable from ordinary appends, so it rides by DEFAULT per R4/O3 (passthrough-as-new-message; fresh ids enter the ledger via finalize; NO suppression logic). Docs-only: the loop already implements cursor > i. Closes the review question "which rewrites does v6 catch, which ride?" in the code where the answer lives. Ref contract R4/R5 + O3 hold; #5403/#5418 v6 canonical-ledger unification. --- src/server/fastpath.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/server/fastpath.ts b/src/server/fastpath.ts index bcdd90ca89..ca57c4e531 100644 --- a/src/server/fastpath.ts +++ b/src/server/fastpath.ts @@ -461,7 +461,14 @@ export function evaluateWatermarkFastpath( } // Mid-list check over indices [1, cursor): index 0 is the window // ORIGIN — handled by the origin pin above (an unknown origin is - // explicitly neutralized there, #5418 v3/#5571 v5). + // explicitly neutralized there, #5418 v3/#5571 v5). PROOF REQUIREMENT: + // an unknown real id must be FOLLOWED by at least one still-known + // slot (cursor > i) — "unknown before known" is the only shape + // that proves in-range mutation from ids alone. A pure trailing run + // of fresh ids (incl. a full-history compaction summary with fresh + // ids) is NOT distinguishable from ordinary appends ⇒ rides by + // default per R4/O3: the summary passes THROUGH AS A NEW MESSAGE, + // its fresh ids enter the ledger via finalize, no suppression. let midInsertion = false; for (let i = 1; i < cursor; i++) { if (tailIds[i] !== PF_SLOT_UNKNOWN && !known.has(tailIds[i])) { midInsertion = true; break; } From 7e910aae4a1bb57c3bec6fe3862fd6c2f54f4f42 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 3 Nov 2026 14:03:05 +0800 Subject: [PATCH 11/15] =?UTF-8?q?v6:=20pin=20the=20canonical-ledger=20verd?= =?UTF-8?q?icts=20=E2=80=94=20rewrite-passthrough,=20knob-off,=20R5=20no-a?= =?UTF-8?q?ppend,=20R6=20projections,=20FIFO=20cap?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five new cases in tests/fastpath.test.ts (suite now 27), encoding the v6 contract face in host-id space (#5403/#5418 v6; contract R4/R5/R6 + O1–O3 holds): 1. rewrite-passthrough (R4/O3): seed a world [s,a,b,c] with a hit whose list [h-b,h-c] grows the ledger, then send T=6 with slots ["h-c","X1","h-b"] — unknown real id BEFORE a still-known one. Width law len===T-K+1 still holds and slot K-1 keeps its id, so every cheap gate passes; the mid-list proof fires: ONE conservative legacy pass, CREDITED (parity with the pre-v6 credited catches so pathological cycles stay breaker-bounded), ids still enter the ledger. The next turn rides clean on the grown ledger → hit(no-count). Convergence in one pass, no speculative rebuild. 2. Same turn with BILI_ROLLOUT_WATERMARK_COMPACTION_PASSTHROUGH=0: the v6 layer is skipped entirely, the byte-compare covers only unchanged prefix positions ⇒ no warns, plain "hit" — exact pre-v6 behavior for that turn. 3. unidentifiable increment (R5): body grows but the increment slot is "?" (host minted no id) ⇒ hit WITHOUT ledger append + structured diagnostic "[pf-v6] unidentifiable-increment ... O1/O2"; the anonymous content still rides the replayed snapshot. 4. per-model projections share ONE logical ledger (R6): m-one hits, flip to m-two ⇒ ONE "seed-stale" legacy pass builds m-two's projection, then pure incremental; flipping back is symmetric. The ledger itself is model-independent. 5. FIFO cap: inflate the persisted lg to PF_LEDGER_CAP=2048 via ext, append one honest id ⇒ exactly the single oldest entry drops (oldest-first trim, newest kept) — bounded like the obs ≤4KB discipline. Geometry notes (cost hours to derive, kept here for the next maintainer): - shim lists span elements [K-1..T-1]; shape gate demands length T-K+1 where K = seed.stampT; slot[0] is the origin anchor (origin-pin vs last id of the previous turn's list, '?' neutral either side); - parseTailIds REJECTS duplicate real ids within one list ('?' may repeat), so a mid-insertion case needs TWO distinct known ids in play; - known-id re-emergence must sit at index ≥ 1 — index 0 can never be an unknown at this layer (the pin settles it first). Ref contract R4/R5/R6, owner rulings 2026-11-03 (m02699/m02725/m02730 line); #3756/#3658 alignment doctrine consumed as the id-fast-path domain per implementation guidance item 2. --- tests/fastpath.test.ts | 131 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) diff --git a/tests/fastpath.test.ts b/tests/fastpath.test.ts index e8a3a91c41..c260966437 100644 --- a/tests/fastpath.test.ts +++ b/tests/fastpath.test.ts @@ -519,3 +519,134 @@ test("v5: client session-id swap under stable host msgids misses sess-change, re const backA = runTurn(session, { ...A, ...TAIL(["q2", "r2"]) }, b4); assert.equal(backA.out.decision, "sess-change", LOGS.join("\n")); }); + +// --------------------------------------------------------------------------- +// #5403/#5418 v6 canonical-ledger unification (owner rulings 2026-11-03) +// --------------------------------------------------------------------------- + +test("v6: a mid-history structural mutation pays ONE conservative legacy pass, then rides passthrough-as-new-message (R4/O3)", () => { + LOGS.length = 0; + const stub = makeStubStore(); + const session = freshSession("pf-v6-rewrite"); + const b1 = bodyOf([SYS("s"), USR("a"), USR("b")]); + assert.equal(runTurn(session, {}, b1).out.decision, "no-stamp"); // K=3 + const b2 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c")]); + const h2 = runTurn(session, { [PF_COUNT_HEADER]: "3", ...TAIL(["h-b", "h-c"]) }, b2); + assert.equal(h2.out.decision, "hit", LOGS.join("\n")); // K=4, ledger [h-b,h-c] + // Structural mutation INSIDE the increment: the verified prefix + // [s,a,b,c] is intact (slot K-1 keeps its id h-c), but fresh material X1 + // arrives BEFORE the still-known id h-b re-sent at the window tail — + // "unknown before known" proves rows were inserted/reordered/merged + // between two ids this session already saw; pure-append traffic can + // never produce it. Verdict (R4/O3): ONE conservative legacy pass. + const b3 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c"), USR("X1"), USR("b")]); + const m3 = runTurn(session, { [PF_COUNT_HEADER]: "4", ...TAIL(["h-c", "X1", "h-b"]) }, b3); + assert.equal(m3.out.decision, "rewrite-passthrough", LOGS.join("\n")); + assert.equal(m3.out.creditedMiss, true, "parity with the pre-v6 credited catches (breaker bounds pathological cycles)"); + assert.deepEqual(m3.out.receivedTailIds, ["h-c", "X1", "h-b"], "the observed ids still enter the ledger"); + let lg = readSaved(stub, "pf-v6-rewrite").lg as string[] | undefined; + assert.ok(lg && lg.includes("X1") && lg.includes("h-c") && lg.includes("h-b"), `ledger must absorb the rewritten world: ${JSON.stringify(lg)}`); + // the NEXT turn rides: same mutated world + one ordinary append — a + // clean pure-append to the grown ledger (origin anchored on the re-sent + // h-b row): no suppression, no speculative rebuild, convergence in one + // pass (count-less echo → hit(no-count)). + const b4 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c"), USR("X1"), USR("b"), USR("e")]); + const h4 = runTurn(session, { ...TAIL(["h-b", "h-e"]) }, b4); + assert.equal(h4.out.decision, "hit(no-count)", LOGS.join("\n")); + assert.ok(h4.headers[PF_SEQ_HEADER] === "7"); +}); + +test("v6 knob OFF: rewrite-shaped turns fall back to the pre-v6 identity-only ride (diagnostic warn, no ledger verdict)", () => { + LOGS.length = 0; + makeStubStore(); + const session = freshSession("pf-v6-knoboff"); + process.env.BILI_ROLLOUT_WATERMARK_COMPACTION_PASSTHROUGH = "0"; + try { + const b1 = bodyOf([SYS("s"), USR("a"), USR("b")]); + assert.equal(runTurn(session, {}, b1).out.decision, "no-stamp"); + const b2 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c")]); + assert.equal(runTurn(session, { [PF_COUNT_HEADER]: "3", ...TAIL(["h-b", "h-c"]) }, b2).out.decision, "hit", LOGS.join("\n")); + // same rewrite shape as the knob-on case — OFF means the v6 layer is + // skipped entirely and pre-v6 semantics decide: the list survives + // every remaining gate (width, origin pin, head check, id-mode + // ride) and HITs — no v6 verdict at all. + const b3 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c"), USR("X1"), USR("b")]); + const r3 = runTurn(session, { [PF_COUNT_HEADER]: "4", ...TAIL(["h-c", "X1", "h-b"]) }, b3); + assert.equal(r3.out.decision, "hit", LOGS.join("\n")); + assert.ok(!LOGS.some((l) => l.includes("rewrite-passthrough")), LOGS.join("\n")); + assert.ok(!LOGS.some((l) => l.startsWith("warn")), `no v6 diagnostics may leak when the layer is off:\n${LOGS.join("\n")}`); + } finally { + delete process.env.BILI_ROLLOUT_WATERMARK_COMPACTION_PASSTHROUGH; + } +}); + +test("v6: an unidentifiable increment (body grew, no host id in it) hits WITHOUT ledger append and logs R5 (O1/O2 holds)", () => { + LOGS.length = 0; + makeStubStore(); + const session = freshSession("pf-v6-unident"); + const U = PF_SLOT_UNKNOWN; + const b1 = bodyOf([SYS("s"), USR("a"), USR("b")]); + assert.equal(runTurn(session, {}, b1).out.decision, "no-stamp"); + const b2 = bodyOf([SYS("s"), USR("a"), USR("b"), ASST("ok")]); + const h2 = runTurn(session, { [PF_COUNT_HEADER]: "3", ...TAIL([U, "h-ok"]) }, b2); + assert.equal(h2.out.decision, "hit", LOGS.join("\n")); // K=4; ledger [h-ok] + // one growth, but the new element carries NO host id at all ("?"): every + // verifiable gate agrees, so we replay the stashed snapshot + the new + // bytes — never a speculative rebuild — and mark the gap for M3. + const b3 = bodyOf([SYS("s"), USR("a"), USR("b"), ASST("ok"), USR("anon")]); + const h3 = runTurn(session, { [PF_COUNT_HEADER]: "4", ...TAIL(["h-ok", U]) }, b3); + assert.equal(h3.out.decision, "hit", LOGS.join("\n")); + assert.ok(JSON.stringify(h3.out.hit?.view ?? []).includes("anon"), "the anonymous increment must still ride"); + assert.ok(LOGS.some((l) => l.startsWith("warn") && l.includes("[pf-v6] unidentifiable-increment")), LOGS.join("\n")); +}); + +test("v6: per-model projections share ONE logical ledger (R6) — one legacy pass builds each model's projection", () => { + makeStubStore(); + const session = freshSession("pf-v6-models"); + const b1 = bodyOf([SYS("s"), USR("a"), USR("b")], "m-one"); + assert.equal(runTurn(session, {}, b1).out.decision, "no-stamp"); // K=3 @m-one + // model flip: the physical partition rebuilds m-two's projection from the + // FULL legacy parse of this turn (count mode — id mode requires model + // equality, and the cross-model echo desync self-heals via restamp). + const b2 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c")], "m-two"); + const r2 = runTurn(session, { [PF_COUNT_HEADER]: "3" }, b2); + assert.equal(r2.out.decision, "seed-stale", LOGS.join("\n")); + assert.equal(watermarkDebugState(session).model, "m-two"); + // m-two's projection is now pure incremental appends + const b3 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c"), USR("d")], "m-two"); + const r3 = runTurn(session, { [PF_COUNT_HEADER]: "4" }, b3); + assert.equal(r3.out.decision, "hit", LOGS.join("\n")); + // flipping BACK costs exactly one more legacy pass — then m-one resumes + // incremental service from the rebuilt projection (its own stale-watermark + // semantics untouched). + const b4 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c"), USR("d"), USR("e")], "m-one"); + const r4 = runTurn(session, { [PF_COUNT_HEADER]: "5" }, b4); + assert.equal(r4.out.decision, "seed-stale", LOGS.join("\n")); + const b5 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c"), USR("d"), USR("e"), USR("f")], "m-one"); + const r5 = runTurn(session, { [PF_COUNT_HEADER]: "6" }, b5); + assert.equal(r5.out.decision, "hit", LOGS.join("\n")); +}); + +test("v6: ledger FIFO cap — the cumulative host-id table stays bounded while appends continue (obs ≤4KB discipline scaled)", () => { + const stub = makeStubStore(); + const session = freshSession("pf-v6-cap"); + // two honest turns build a small REAL ledger [h-b,h-c,h-d] under K=4; + // simulating a long-lived history means hand-growing the PERSISTED table + // to its full 2048-entry capacity (oldest synthetic ids first), which is + // exactly the shape readSaved validates back in. + const b1 = bodyOf([SYS("s"), USR("a"), USR("b")]); + assert.equal(runTurn(session, {}, b1).out.decision, "no-stamp"); + const b2 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c")]); + assert.equal(runTurn(session, { [PF_COUNT_HEADER]: "3", ...TAIL(["h-b", "h-c"]) }, b2).out.decision, "hit", LOGS.join("\n")); + const b3 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c"), USR("d")]); + assert.equal(runTurn(session, { [PF_COUNT_HEADER]: "4", ...TAIL(["h-c", "h-d"]) }, b3).out.decision, "hit", LOGS.join("\n")); + const padIds = Array.from({ length: 2045 }, (_, i) => `old-${i}`); + stub.ext.set(savedKey("pf-v6-cap"), JSON.stringify({ t: 4, m: "m1", misses: 0, l: ["h-c", "h-d"], lg: [...padIds, "h-b", "h-c", "h-d"] })); + const b4 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c"), USR("d"), USR("e")]); + const r4 = runTurn(session, { [PF_COUNT_HEADER]: "5", ...TAIL(["h-d", "h-e"]) }, b4); + assert.equal(r4.out.decision, "hit", LOGS.join("\n")); + const lg = readSaved(stub, "pf-v6-cap").lg as string[]; + assert.equal(lg.length, 2048, "cap must hold exactly (FIFO drop oldest)"); + assert.equal(lg[0], padIds[1], "exactly one oldest drops per single append"); + assert.deepEqual(lg.slice(-2), ["h-d", "h-e"], "newest appends survive at the tail"); +}); From 37cbd311e528f3c54d4015946de05f2224571649 Mon Sep 17 00:00:00 2001 From: ci-check Date: Wed, 11 Nov 2026 09:28:04 +0800 Subject: [PATCH 12/15] fix(ci): pass architecture-docs + unused-exports gates after master merge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - reference/architecture.md: list src/server/native-identity-obs.ts and native-identity-profiles.ts in the src/server/ tree (guard requires full src/ coverage; the map predates these modules from the #5571 M1 PR) - src/server/snapshot-render.ts: TranscriptProbeResult is used only inside snapshot-render.ts (probeTranscriptAlignment return annotation) — drop the leading export per the unused-exports gate (INTERNAL_ONLY) --- reference/architecture.md | 2 ++ src/server/snapshot-render.ts | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/reference/architecture.md b/reference/architecture.md index cf232d6f07..84de431dc1 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -22,6 +22,8 @@ billion-context/ │ │ ├── handoff-response.ts # Retains parsed assistant output for handoff export without changing request snapshots │ │ ├── headers.ts # Client-provided id sanitization for dump filenames (#286) │ │ ├── inject.ts # Per-wire tool-injection wrappers + FORCE_TEXT_PROTOCOL switch (#1440) +│ │ ├── native-identity-obs.ts # Native identity observation layer: live measurement of the #5571 collection table (default off) (#5571) +│ │ ├── native-identity-profiles.ts # Per-host native identity profiles feeding the observation layer (#5571) │ │ ├── observability.ts # Body dumps (dumps/req-*.json, raw/*), unrecognized-path stats │ │ ├── prepare-anthropic.ts # Anthropic request preparation (fold → rebuild → system/nudge injection) (#1440) │ │ ├── prepare-google.ts # Gemini request preparation incl. :countTokens twin (#1440) diff --git a/src/server/snapshot-render.ts b/src/server/snapshot-render.ts index ef6a829d1f..dd9c0f4e82 100644 --- a/src/server/snapshot-render.ts +++ b/src/server/snapshot-render.ts @@ -97,7 +97,7 @@ export function identitySigForTest(m: BiliMessage): string { // per session at most (latch lives in session.metadata). Deliberately NOT // reused from buildView: this module is render authority (#3812/#4241) — the // probe must not couple doctrine-critical walk code to a diagnostics path. -export interface TranscriptProbeResult { +interface TranscriptProbeResult { readonly anchored: boolean; /** Human-readable reason when not anchored. */ readonly reason?: string; From f8458a30f3fdbecf1a19e8348656e5edcd85250e Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 22 Nov 2026 08:09:22 +0800 Subject: [PATCH 13/15] =?UTF-8?q?fix:=20growPfLedger=20=E2=80=94=20make=20?= =?UTF-8?q?the=20defensive=20dedupe=20of=20hand-edited=20ledger=20state=20?= =?UTF-8?q?actually=20collapse=20duplicates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pre-v6 bootstrap loop seeded the known set from base itself, so the membership guard never fired and duplicate ids in a hand-edited or corrupted persisted ledger were carried through forever (wasting FIFO budget). Start from an empty set and skip already-seen ids. Regression test pins a pre-seeded duplicate ledger collapsing on the first growth. --- src/server/fastpath.ts | 5 +++-- tests/fastpath.test.ts | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/server/fastpath.ts b/src/server/fastpath.ts index 40a2a51865..2d0e2794e9 100644 --- a/src/server/fastpath.ts +++ b/src/server/fastpath.ts @@ -286,10 +286,11 @@ function growPfLedger( ): string[] | undefined { // Bootstrap/migration: pre-v6 sessions carry only `l` (last list). const base = saved?.lg ?? saved?.l ?? []; - const known = new Set(base); + const known = new Set(); const out: string[] = []; for (const id of base) { - if (!known.has(id)) known.add(id); // defensive dedupe of hand-edited state + if (known.has(id)) continue; // defensive dedupe of hand-edited state + known.add(id); out.push(id); } for (const id of list) { diff --git a/tests/fastpath.test.ts b/tests/fastpath.test.ts index 31611b6544..26db2e8d3d 100644 --- a/tests/fastpath.test.ts +++ b/tests/fastpath.test.ts @@ -598,6 +598,21 @@ test("v6: a mid-history structural mutation pays ONE conservative legacy pass, t assert.ok(h4.headers[PF_SEQ_HEADER] === "7"); }); +test("v6: a hand-edited ledger with duplicate ids is deduped when it first grows (R2 defensive)", () => { + LOGS.length = 0; + const stub = makeStubStore(); + const session = freshSession("pf-v6-dedupe"); + // a hand-edited/corrupted persisted ledger carries a duplicate id + stub.ext.set(savedKey("pf-v6-dedupe"), JSON.stringify({ t: 3, m: "m1", misses: 0, lg: ["h-b", "h-b", "h-c"] })); + const b1 = bodyOf([SYS("s"), USR("a"), USR("b")]); + assert.equal(runTurn(session, {}, b1).out.decision, "no-stamp"); + const b2 = bodyOf([SYS("s"), USR("a"), USR("b"), USR("c")]); + const r2 = runTurn(session, { [PF_COUNT_HEADER]: "3", ...TAIL(["h-c", "h-d"]) }, b2); + assert.equal(r2.out.decision, "hit", LOGS.join("\n")); + const lg = readSaved(stub, "pf-v6-dedupe").lg as string[]; + assert.deepEqual(lg, ["h-b", "h-c", "h-d"], "the duplicate must be collapsed on first growth"); +}); + test("v6 knob OFF: rewrite-shaped turns fall back to the pre-v6 identity-only ride (diagnostic warn, no ledger verdict)", () => { LOGS.length = 0; makeStubStore(); From 888167fa3e47c9342e9bf19b325e3a6ec048f3ef Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 22 Nov 2026 08:12:02 +0800 Subject: [PATCH 14/15] fix: drop the redundant PFSavedState cast in the noteCreditedMiss fallback The object literal already satisfies the interface (t/m/misses are the only required fields), so the cast adds nothing. --- src/server/fastpath.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/fastpath.ts b/src/server/fastpath.ts index 2d0e2794e9..9e43d987b0 100644 --- a/src/server/fastpath.ts +++ b/src/server/fastpath.ts @@ -678,7 +678,7 @@ function addStripCounts(a: RawStripCounts, b: RawStripCounts): RawStripCounts { } function noteCreditedMiss(sessionId: string, decision: string, log: (level: string, msg: string) => void): void { - const cur = readSaved(sessionId) ?? ({ t: 0, m: "", misses: 0 } as PFSavedState); + const cur = readSaved(sessionId) ?? { t: 0, m: "", misses: 0 }; // an EXPIRED hold has already paid its penalty — count fresh from zero, // or the very first verified miss after the TTL would instantly re-arm // (the persisted counter sits at PF_BREAKER_MISSES from the original trip). From de087a919a4e6cf440cdee6205c6cc74fece7e00 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 22 Nov 2026 08:12:10 +0800 Subject: [PATCH 15/15] =?UTF-8?q?fix:=20correct=20the=20R7=20ledgerHold=20?= =?UTF-8?q?wording=20=E2=80=94=20the=20swap=20turn=20holds=20ledger=20grow?= =?UTF-8?q?th=20only?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The docstring, the finalize comment, and the EN/ZH technical-notes clause (c) claimed a swapped-in conversation's ids "never fold" into the session ledger. But finalize converges cs to the incoming conversation on the same turn (identity follows the traffic, pinned by the sess-change test), so from the NEXT turn its ids grow the ledger as usual. Reword all three places to state the actual one-turn hold and note the mixed ledger is inert bloat under host-msgid uniqueness, bounded by the FIFO cap. --- docs/technical-notes.md | 2 +- docs/technical-notes.zh-CN.md | 2 +- src/server/fastpath.ts | 16 ++++++++++------ 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/technical-notes.md b/docs/technical-notes.md index b42c5da0b6..63aa12b953 100644 --- a/docs/technical-notes.md +++ b/docs/technical-notes.md @@ -600,7 +600,7 @@ Fail-soft discipline (anti-deviation lock): the legacy pipeline code is UNTOUCHE Declared trust boundary (§7.4 — human review required, no auto-merge): a client that edits PREFIX BYTES while keeping the element count constant is NOT detected — except at the anchor, where v2 compares the carried prevId against the stored one and a re-minted id costs one uncredited miss plus self-heal. That trade is the entire price of skipping byte-level re-verification; it cleared the §7.4 human review and therefore ships as an EXPERIMENTAL grey rollout — ON by default for roughly 5% of installs (owner ruling 2026-11-02: small cohort before GA, one-time web intro notice visible to every install until closed, plus a tri-state quick switch) — with the A/B golden pinning outbound byte-equality and a per-install opt-in/opt-out (`rollout.features.pluginFullResendWatermark: true|false` / `BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK=1|0`). Destructive rewrites (announced compaction, truncation, reorders) change the count and are caught before any stale core could feed the kernel — under v4 the catch moves from the client echo to the width arithmetic itself: a shrunken prefix demands a non-positive width no id list can satisfy, so the credited `ahead` / `seed-stale` verdicts fire exactly as pre-v4. -**v6 canonical-ledger unification (owner rulings 2026-11-03, contract R1–R8):** the hit decision now derives from the CANONICAL transcript alignment instead of the fastpath's own parallel byte gates. Mechanically, the alignment's id fast-path is exactly what the shim's tail-ids encode — host msgids are unique forever, so a list that is a pure append to the session's cumulative host-id ledger (`pf:state.lg`, FIFO-capped at 2048 real ids; `?` slots never recorded) is equivalent to the backward id-chain anchored on the transcript succeeding. Consuming snapshot-render's full walk on the hit path would pay the very O(N) parse this fastpath exists to avoid (guidance item 2), so the set-diff fronts the SAME semantic contract as the primary cheap gate, and snapshot-render serves as the confirmation layer where it is free: on a watermark MISS turn the full parse is already paid, so a light identity-row-only probe (`probeTranscriptAlignment`, identity rows only, no content bytes) cross-checks the ledger view against the unified transcript and logs the verdict once per session (dormant unless `snapshotRender` rollout is also on). What remains of the old stack, and why: width arithmetic is kept as SHIM PROTOCOL shape validity (it locates the window origin K server-side); the origin pin (`tail-ids-prev`) is kept because gap-tolerant alignment would ride a re-minted origin slot the client no longer claims; the head SYSTEM-text gate stays gating in both modes (a prompt has no msgid — flagged deviation, serving a stale prompt beats saving one parse); model switching keeps its physical projection partition (R6: one derived projection per (model × wire format) sharing ONE logical ledger — the first request for a new model pays one full legacy pass building that projection, subsequent turns are pure incremental appends; the `m` field demotes from world-partition to projection-cache key). NEW in v6: (a) a mid-history unknown-real id inside the verified range — a structural rewrite whose shape survived the width+origin gates (client compaction/insertion) — takes ONE conservative credited legacy pass and rides passthrough-as-new-message from the next turn (`watermarkCompactionPassthrough` knob, default ON; OFF restores pre-v6 ride-with-diagnostic for those turns): the summary block carries fresh ids, the set-diff appends them naturally, NO suppression logic (R4/O3); (b) an UNIDENTIFIABLE increment (body grew but the increment carries no host id at all) hits normally but logs a structured diagnostic and appends nothing to the ledger — never speculative rebuilds (R5); (c) a client session-header digest swap (cs gate, R7) now ALSO holds the ledger — the swapped conversation's ids never fold into this session's cumulative ledger. Count-only turns are byte-identical to pre-v6 in every branch. +**v6 canonical-ledger unification (owner rulings 2026-11-03, contract R1–R8):** the hit decision now derives from the CANONICAL transcript alignment instead of the fastpath's own parallel byte gates. Mechanically, the alignment's id fast-path is exactly what the shim's tail-ids encode — host msgids are unique forever, so a list that is a pure append to the session's cumulative host-id ledger (`pf:state.lg`, FIFO-capped at 2048 real ids; `?` slots never recorded) is equivalent to the backward id-chain anchored on the transcript succeeding. Consuming snapshot-render's full walk on the hit path would pay the very O(N) parse this fastpath exists to avoid (guidance item 2), so the set-diff fronts the SAME semantic contract as the primary cheap gate, and snapshot-render serves as the confirmation layer where it is free: on a watermark MISS turn the full parse is already paid, so a light identity-row-only probe (`probeTranscriptAlignment`, identity rows only, no content bytes) cross-checks the ledger view against the unified transcript and logs the verdict once per session (dormant unless `snapshotRender` rollout is also on). What remains of the old stack, and why: width arithmetic is kept as SHIM PROTOCOL shape validity (it locates the window origin K server-side); the origin pin (`tail-ids-prev`) is kept because gap-tolerant alignment would ride a re-minted origin slot the client no longer claims; the head SYSTEM-text gate stays gating in both modes (a prompt has no msgid — flagged deviation, serving a stale prompt beats saving one parse); model switching keeps its physical projection partition (R6: one derived projection per (model × wire format) sharing ONE logical ledger — the first request for a new model pays one full legacy pass building that projection, subsequent turns are pure incremental appends; the `m` field demotes from world-partition to projection-cache key). NEW in v6: (a) a mid-history unknown-real id inside the verified range — a structural rewrite whose shape survived the width+origin gates (client compaction/insertion) — takes ONE conservative credited legacy pass and rides passthrough-as-new-message from the next turn (`watermarkCompactionPassthrough` knob, default ON; OFF restores pre-v6 ride-with-diagnostic for those turns): the summary block carries fresh ids, the set-diff appends them naturally, NO suppression logic (R4/O3); (b) an UNIDENTIFIABLE increment (body grew but the increment carries no host id at all) hits normally but logs a structured diagnostic and appends nothing to the ledger — never speculative rebuilds (R5); (c) a client session-header digest swap (cs gate, R7) now ALSO holds ledger growth for the swap turn itself — the turn goes legacy and re-seeds, and identity follows the traffic (cs converges to the incoming conversation on the same turn), so from the next turn the incoming conversation's ids grow the ledger as usual (a mixed ledger is inert bloat under host-msgid uniqueness, bounded by the FIFO cap). Count-only turns are byte-identical to pre-v6 in every branch. 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. diff --git a/docs/technical-notes.zh-CN.md b/docs/technical-notes.zh-CN.md index 504a78a716..c76ce074ce 100644 --- a/docs/technical-notes.zh-CN.md +++ b/docs/technical-notes.zh-CN.md @@ -177,7 +177,7 @@ chat wire 上 bili 自己 vs 客户端自带:插件车道上,请求体里等于 声明的信任边界(§7.4——必须人工评审,禁止自动合并):**保元素数不变的前缀字节改写不可检测**——锚点除外:v2 在锚点比对 carried prevId 与存锚,id 重铸 = 一次 UNcredited miss + 下一轮自愈。这就是跳过逐条字节复核的全部代价;该代价已过 §7.4 人工评审,故以**实验性灰度**出厂——默认仅约 5% 的安装开启(owner 裁定 2026-11-02:先小流量,web 面板对全部安装显示一次性公告直到关闭、快速配置提供三态开关),A/B 黄金测试钉死出站字节逐字一致,并提供 per-install 开/关(`rollout.features.pluginFullResendWatermark: true|false` / `BILI_ROLLOUT_PLUGIN_FULL_RESEND_WATERMARK=1|0`)。破坏性改写(通告 compaction、截断、重排)都会改变 count,在任何陈旧 core 喂给内核之前就被判掉——在 v4 下这道拦截从客户端回显移到宽度算式本身:前缀收缩要求一个非正宽度,任何 id 列表都不可能满足,credited `ahead` / `seed-stale` 判决与 pre-v4 完全一致地触发。 -**v6 标准账本统一(owner 裁定 2026-11-03,契约 R1–R8):** 命中判决现在派生自标准(transcript)对齐而非快路径自己的并行字节门。机制上,对齐的 id 快速路径恰好就是 shim tail-ids 所编码的东西——宿主 msgid 永世唯一,所以「对会话累计宿主 id 账本(`pf:state.lg`,FIFO 上限 2048 真实 id;`?` 槽永不记录)纯追加的列表」等价于「锚在 transcript 上的向后 id 链成功」。若命中路径直接消费 snapshot-render 的完整走查,就会付上本快路径专为避免的 O(N) 解析(指导项 2),因此集合差作为同一语义契约的首要廉价门前置,而 snapshot-render 担任免费时的确认层:水位 MISS 回合全量解析本已付出,此时一个只读身份行的轻量探针(`probeTranscriptAlignment`,仅身份行、无内容字节)将账本视图与 unified transcript 交叉核对并每会话记一条日志(除非 `snapshotRender` rollout 同时开启,否则休眠)。旧栈保留的部分及理由:宽度算术保留为 SHIM 协议形状有效性(服务端定位窗口起点 K);起点钉(`tail-ids-prev`)保留,因为容隙对齐会骑在客户端已不再声明的重铸起点槽上;头部 SYSTEM 文本门两种模式下都保留生效(prompt 没有 msgid——flagged 偏差:宁可省一次解析也不能服务陈旧 prompt);模型切换保留物理投影分区(R6:每 (model × wire format) 一份派生投影、共享一份逻辑账本——某新模型的首个请求付一次全量 legacy pass 建立该投影,后续回合纯增量追加;`m` 字段从世界分区降格为投影缓存键)。v6 新增:(a) 已验证范围内出现中历史未知真实 id——形状存活于宽度+起点门之后的结构性改写(客户端压缩/插入)——付一次保守的计名 legacy pass,下一轮起按新消息透出(`watermarkCompactionPassthrough` 旋钮,默认开;关 = 这些回合恢复 pre-v6 骑存+诊断):摘要块带新 id,集合差自然追加,无抑制逻辑(R4/O3);(b) 不可辨识增量(正文变大但增量完全不带宿主 id)正常命中但记结构化诊断、不向账本追加——永不做猜测式重建(R5);(c) 客户端会话头摘要切换(cs 门,R7)现在同时扣住账本——换入会话的 id 绝不折入本会话累计账本。纯计数回合在所有分支上与 pre-v6 逐字节相同。 +**v6 标准账本统一(owner 裁定 2026-11-03,契约 R1–R8):** 命中判决现在派生自标准(transcript)对齐而非快路径自己的并行字节门。机制上,对齐的 id 快速路径恰好就是 shim tail-ids 所编码的东西——宿主 msgid 永世唯一,所以「对会话累计宿主 id 账本(`pf:state.lg`,FIFO 上限 2048 真实 id;`?` 槽永不记录)纯追加的列表」等价于「锚在 transcript 上的向后 id 链成功」。若命中路径直接消费 snapshot-render 的完整走查,就会付上本快路径专为避免的 O(N) 解析(指导项 2),因此集合差作为同一语义契约的首要廉价门前置,而 snapshot-render 担任免费时的确认层:水位 MISS 回合全量解析本已付出,此时一个只读身份行的轻量探针(`probeTranscriptAlignment`,仅身份行、无内容字节)将账本视图与 unified transcript 交叉核对并每会话记一条日志(除非 `snapshotRender` rollout 同时开启,否则休眠)。旧栈保留的部分及理由:宽度算术保留为 SHIM 协议形状有效性(服务端定位窗口起点 K);起点钉(`tail-ids-prev`)保留,因为容隙对齐会骑在客户端已不再声明的重铸起点槽上;头部 SYSTEM 文本门两种模式下都保留生效(prompt 没有 msgid——flagged 偏差:宁可省一次解析也不能服务陈旧 prompt);模型切换保留物理投影分区(R6:每 (model × wire format) 一份派生投影、共享一份逻辑账本——某新模型的首个请求付一次全量 legacy pass 建立该投影,后续回合纯增量追加;`m` 字段从世界分区降格为投影缓存键)。v6 新增:(a) 已验证范围内出现中历史未知真实 id——形状存活于宽度+起点门之后的结构性改写(客户端压缩/插入)——付一次保守的计名 legacy pass,下一轮起按新消息透出(`watermarkCompactionPassthrough` 旋钮,默认开;关 = 这些回合恢复 pre-v6 骑存+诊断):摘要块带新 id,集合差自然追加,无抑制逻辑(R4/O3);(b) 不可辨识增量(正文变大但增量完全不带宿主 id)正常命中但记结构化诊断、不向账本追加——永不做猜测式重建(R5);(c) 客户端会话头摘要切换(cs 门,R7)现在同时扣住本切换轮的账本增长——该轮走 legacy 重播种,身份跟随流量(同一轮 cs 收敛到换入会话),次轮起换入会话的 id 照常进入账本(宿主 msgid 唯一性下混合账本只是受 FIFO 上限约束的惰性膨胀)。纯计数回合在所有分支上与 pre-v6 逐字节相同。 诚实边界:(1) 一旦多模态尾部(含 `image_url` 的 content array)进入缓存,该段历史此后整段降级回 legacy 全量轮——kernel 按位置区分 user 图片消息在尾部与在历史中部的渲染,冻结缓存无法做到位置无关地复现 legacy 字节;纯文本工作负载(#5403 报告者的形态)不受影响。(2) 每次命中会现解析头部 8 个元素,只为做 system-run 校验。(3) 两个 `x-bili-pf-*` 头都在转发上游前剥掉(`UPSTREAM_HOP_HEADERS`)——协议头绝不漏进模型流量。 diff --git a/src/server/fastpath.ts b/src/server/fastpath.ts index 9e43d987b0..0f15c67083 100644 --- a/src/server/fastpath.ts +++ b/src/server/fastpath.ts @@ -195,9 +195,12 @@ export interface FastpathOutcome { readonly clientSess?: string; /** #5403/#5418 v6 (contract R7): set when the cs (sess-change) gate * fired — the incoming conversation SWAPPED. finalize honors it by - * holding the cumulative ledger: a swapped-in conversation's ids must - * never fold into this session's ledger (they describe different - * clients' history and would poison the set-diff baseline). */ + * holding ledger growth for the swap turn itself: the turn goes + * legacy and re-seeds, and identity follows the traffic (cs + * converges to the incoming conversation on the same turn), so from + * the NEXT turn the incoming conversation's ids grow the ledger as + * usual — a mixed ledger is inert bloat under host-msgid uniqueness, + * bounded by the FIFO cap. */ readonly ledgerHold?: boolean; } @@ -714,9 +717,10 @@ export function finalizeWatermarkTurn( const saved = readSaved(session.id); // #5403/#5418 v6 (R2/R7): sole ledger growth site. Grow when this turn // delivered a shape-valid list, the v6 knob is on, and the conversation - // did not swap (cs gate fired ⇒ ledgerHold — a swapped-in conversation's - // ids must not fold into this session's baseline). Non-grow turns carry - // the stored ledger forward unchanged (never wipe). + // did not swap (cs gate fired ⇒ ledgerHold — the swap turn itself goes + // legacy and re-seeds; identity follows the traffic, so from the next + // turn the incoming conversation's ids grow the ledger as usual). + // Non-grow turns carry the stored ledger forward unchanged (never wipe). const lg = outcome.receivedTailIds !== undefined && !outcome.ledgerHold && featureEnabled("watermarkCompactionPassthrough") ? growPfLedger(saved, outcome.receivedTailIds) : saved?.lg;