From 0fcff3d0e4d13967cf82525bdb1e48f182f42eab Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 20 Oct 2026 00:14:56 +0800 Subject: [PATCH 1/2] snapshot-render shadow observability: compute the view, never emit it (#3756 follow-up) - snapshot-render.ts: buildView/maybeSnapshotView split; shadow lane classifies the would-be view against the legacy outbound (lost-tail / duplicate / unstable-prefix = mechanical error classes; degrade reasons = known costs, never errors), per-session snapshotShadow blob, snapshotShadowStatusWire - knobs.ts resolveSnapshotShadow + config.ts snapshot.shadow (env BILI_SNAPSHOT_SHADOW > file > default ON) - admin status JSON snapshotShadow aggregate; sessions list per-session counters; snapshot-shadow diagnostics topic; web banner with report buttons (i18n en/zh); docs seeds + generated reference Fixes the rollout flip precondition: error rate ~0 across a full version. --- CHANGELOG.md | 8 + CONFIGURATION.md | 4 +- CONFIGURATION.zh-CN.md | 4 +- src/config.ts | 4 + src/knobs.ts | 19 ++ src/log-mask.ts | 2 +- src/server/admin.ts | 3 +- src/server/snapshot-render.ts | 208 +++++++++++++-- src/web/client.ts | 19 ++ src/web/diagnostics.ts | 32 +++ src/web/i18n.ts | 4 + src/web/page.ts | 1 + src/web/sessions-data.ts | 19 ++ tests/snapshot-shadow.test.ts | 350 +++++++++++++++++++++++++ website/config-reference/env-only.yaml | 8 + website/config-reference/process.yaml | 8 + 16 files changed, 670 insertions(+), 23 deletions(-) create mode 100644 tests/snapshot-shadow.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c30988878e..63a5d0bf84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ## [Unreleased] +### 快照渲染影子对账(#3756 后续,默认开启) + +- 新增影子车道:灰度仍为 0% 的出站快照引擎在每轮已折叠会话上现算视图,与 legacy 实际出站比对后丢弃 —— 出站字节零变化,纯观测。 +- 三级分类:预期差异只计数(覆盖压制/锚);已知降级记原因不报警(seam-too-short/block-unanchored/storage-off 等);机械可证的错误才计数报警(lost-tail=非覆盖客户端消息从视图消失 / duplicate=非锚消息重复 / unstable-prefix=同输入异视图)。 +- 暴露面:`/__bili/status` 的 `snapshotShadow` 汇总(enabled/watching/errors/worst)、web 会话列表逐会话计数(`snapshotShadow` 字段)、`snapshot-shadow` 诊断主题(GitHub 一键上报)、面板 banner(仅 error>0 时出现,附复制诊断/报 issue 按钮)。 +- 配置:环境变量 `BILI_SNAPSHOT_SHADOW` 优先,配置文件 `snapshot.shadow` 布尔次之,缺省开启(`false`/`0`/`off` 关闭)。这是灰度翻转前的全舰队干跑 —— error 率连续一版本≈0 才翻 rollout。 + + ### Fixed - **快照渲染接缝加固(#3812)**:身份签名没有 id 分量,重复短文本("继续"/yes/1)会让单次签名命中伪装成接缝,静默截断两点之间的全部历史。现在接缝要求至少 2 条连续匹配(`MIN_SEAM_RUN`,fold-reconcile `MIN_RESYNC_RUN` 同款纪律),单次命中一律降级走 legacy(`seam-too-short`),绝不猜测;同时容忍接缝中恰好一条未观测消息(上一轮回复的观察滞后——重发/重试轮的常态),第二条未命中即断链。块覆盖的签名传播被整体移除:它无法区分升级孪生与真实重复消息,会把未折叠的同文消息静默并入覆盖集(丢真消息);折叠期 id 在视图中完全失锚的块现在降级(`block-unanchored`)而不是把摘要锚点放在裸历史顶端。插件车道整体旁路(插件契约本就客户端权威)。影响面:灰度 0% 下零暴露,属开闸前必修。 diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 09e953c4c5..50c76e97d6 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -174,8 +174,6 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `persist.epermAlertRepeatMs` | number | 0 (no repeats) | BILI_PERSIST_EPERM_ALERT_REPEAT_MS | Repeat interval for the EPERM alert; 0 logs it once. | | `storage` | object | {} (all defaults) | — | Unified SQLite storage sidecar settings (#2671). | | `storage.unified` | legacy\|shadow\|full | unset (full) | BILI_STORAGE_UNIFIED | Tiered storage-migration switch (#2671): shadow = unified SQLite double-write dry-run with digest reconciliation; full = drop-in read path (unified-first loads with organic import, legacy fallback). Absent everywhere now defaults to FULL (#3818 flip - the shadow dry-run reconciled cleanly since #2815, so the index is the load path; JSON envelopes keep being written, and legacy remains the one-line escape hatch). File tier is strict legacy/shadow/full; the env tier also accepts 1/true (=shadow) and unified (=full) and wins over the file. Resolved once per lane boot - hot edits need a restart. Encryption (BILI_ENCRYPTION_KEY) hard-blocks the sidecar. | -| `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | Gate for the one-time SQLite engine self-download (#2833): when no engine is available in-process (no built-in node:sqlite, no host-installed better-sqlite3) and the unified sidecar is wanted on this platform, bili downloads the pinned better-sqlite3 prebuilt tarball from the npm registry once (~11 MB, sha512-verified) into the cache dir and reuses it on every later start. Engine resolution order: built-in node:sqlite (Node >= 22.5) -> host-provided better-sqlite3 -> cached self-download -> self-download (gated by this switch) -> none (legacy-only, the #2825 degrade contract). The switch gates only the network fetch - a cached copy is used even when it is false; unsupported platforms never download. The tarball download walks a builtin mirror list (#3338): the configured registry (BILI_UPDATE_REGISTRY / update.registry) is tried first, then https://registry.npmjs.org, then https://registry.npmmirror.com - the first mirror that yields a sha512-verified tarball wins; a Node < 22.5 with no engine gets an explicit Node upgrade hint in the degrade reason (#3385). | -| `storage.unified` | legacy\|shadow\|full | unset (shadow) | BILI_STORAGE_UNIFIED | Tiered storage-migration switch (#2671): shadow = unified SQLite double-write dry-run with digest reconciliation; full = drop-in read path (unified-first loads with organic import, legacy fallback). Absent everywhere now defaults to shadow (JSON stays the sole source of truth; the index is digest-reconciled telemetry - set legacy to opt out). File tier is strict legacy/shadow/full; the env tier also accepts 1/true (=shadow) and unified (=full) and wins over the file. Resolved once per lane boot - hot edits need a restart. Encryption (BILI_ENCRYPTION_KEY) hard-blocks the sidecar. | | `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | Gate for the one-time SQLite engine self-download (#2833): when no engine is available in-process (no built-in node:sqlite, no host-installed better-sqlite3) and the unified sidecar is wanted on this platform, bili downloads the pinned better-sqlite3 prebuilt tarball from the npm registry once (~11 MB, sha512-verified) into the cache dir and reuses it on every later start. Engine resolution order: built-in node:sqlite (Node >= 22.5) -> host-provided better-sqlite3 -> cached self-download -> self-download (gated by this switch) -> none (legacy-only, the #2825 degrade contract). The switch gates only the network fetch - a cached copy is used even when it is false; unsupported platforms never download. The tarball download walks a builtin mirror list (#3338): the configured registry (BILI_UPDATE_REGISTRY / update.registry) is tried first, then https://registry.npmjs.org, then https://registry.npmmirror.com - the first mirror that yields a sha512-verified tarball wins; a Node < 22.5 with no engine gets an explicit Node upgrade hint in the degrade reason (#3385). A failed download arms a 6-hour retry cooldown persisted as a marker file under the cache dir (billion-context/sqlite/.bootstrap-failed.json); the storage diagnostics blob shows the marker's absolute expiry time and path - delete that file and restart bili to force an immediate retry instead of waiting out the whole window (#3788). | | `storage.jsonWriter` | on\|off | on | BILI_STORAGE_JSON_WRITER | Phase 3 envelope switch (#2960): off stops writing the legacy JSON session envelope while storage.unified is full - the SQLite index becomes the only persistent copy (reads are already unified-first; boot enumerates the index union, so index-only sessions load normally). Only honored in effective-full mode: under shadow/legacy (or with encryption active) the request is ignored with a one-time warning because the JSON file remains the sole source of truth. Env tier 0/false/off = off and 1/true/on = on wins over the strict file spellings. Fail-safe: if the sidecar disables itself mid-run, envelope writes resume on the next save. Rollback: unset the knob - writing resumes, index-only sessions keep loading via the boot union, and replicas/restore re-materialize portable JSON envelopes. Downgrading the binary (or losing the SQLite engine) makes index-only sessions invisible to v0.1.196 and older until a >=v0.1.197 binary runs again - the data stays intact in index.db, it is just not read by the older code. The per-session content-store sidecar keeps being written either way. A jsonWriter=off lane must be the SOLE writer of its sessions directory: an off lane reads unified-first and never falls back to the file, so any peer instance running legacy/shadow against the same directory diverges silently (its JSON copy stops receiving updates, and the off lane never sees the peer's writes). | | `storage.walJournalSizeLimitBytes` | number | 8388608 | BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES | WAL reclamation cap for index.db-wal (#3250), in bytes: every completed checkpoint truncates the WAL file back to this size, bounding disk use and crash-recovery replay in long-lived processes. NOT a per-session data quota - data lands in index.db as it is written and the WAL only stages frames between checkpoints, so session count/size does not scale this; a large burst can overshoot temporarily until the next completed checkpoint truncates back. Higher = rarer truncate IO but more steady disk use and a longer crash-replay tail. Env tier (positive integer) wins over the file tier; a garbage or non-positive env value falls through to the file/default tier instead of failing boot. Applied when the store opens at lane boot - hot edits need a restart. The effective value appears on the unified-enable log line and in the storage diagnostics blob. | @@ -189,6 +187,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `sessions.gc.maxTokens` | number | 1000000 | BILI_SESSION_GC_MAX_TOKENS | GC token-size threshold per session record. | | `sessions.gc.intervalMs` | number | 3600000 | BILI_SESSION_GC_INTERVAL_MS | GC sweep interval. | | `plugin.snapshotCapBytes` | number | 104857600 (0 disables snapshots) | BILI_PUBLIC_SNAPSHOT_CAP_BYTES | Size cap for fork-API public snapshots served to native plugins. | +| `snapshot.shadow` | boolean | true (on) | — | Snapshot-render shadow observability (#3756 follow-up): with the render lane still rollout-gated, every armed turn computes the would-be snapshot view, classifies the diff against the legacy outbound, and records per-session counters (web panel rows + /__bili/status snapshotShadow aggregate + the snapshot-shadow diagnostics topic). Default ON - it is the fleet-wide dry run whose error rate gates the rollout flip. Env BILI_SNAPSHOT_SHADOW wins. Turn off with false/0/off if you do not want the extra per-turn computation. | **Updates & advisories** @@ -332,6 +331,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | Key | Type | Default | Env | Description | |-----|------|---------|-----|-------------| | `BILI_DSH_AUTHORED_COMPACTION` | boolean | false | — | Let bili ANSWER dsh compaction summarize calls locally with the folded snapshot instead of refusing (#3733): identity header + kernel-rendered block summaries, zero egress; replay recognized via the #2432 rebase. | +| `BILI_SNAPSHOT_SHADOW` | boolean | true (on) | — | Snapshot-render shadow observability (#3756 follow-up): compute the outbound snapshot view on every armed turn WITHOUT using it, classify the diff against the legacy outbound, and surface per-session counters in the web panel + the snapshot-shadow diagnostics topic. 0/false/off disables; 1/true/on enables; otherwise the config-file snapshot.shadow boolean applies (default on). The render lane itself stays rollout-gated (BILI_ROLLOUT_SNAPSHOT_RENDER), so the shadow lane never changes outbound bytes - it is the dry-run evidence that flips the rollout later. | | `BILI_CONFIG_FILE` | string | unset (XDG config path) | — | Override the config file path (path relocation). | | `BILI_SESSIONS_DIR` | string | unset (XDG state path) | — | Where session records are stored (path relocation). | | `BILI_ENCRYPTION_KEY` | string | unset | — | Key material for encrypted persisted payloads (secret). | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 758505a848..4305644f89 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -174,8 +174,6 @@ | `persist.epermAlertRepeatMs` | number | 0 (no repeats) | BILI_PERSIST_EPERM_ALERT_REPEAT_MS | EPERM 告警的重复间隔;0 只记录一次。 | | `storage` | object | {} (all defaults) | — | 统一 SQLite 存储边车设置(#2671)。 | | `storage.unified` | legacy\|shadow\|full | unset (full) | BILI_STORAGE_UNIFIED | 分层存储迁移开关(#2671):shadow = 统一 SQLite 双写干跑 + digest 对账;full = 平替读路径(unified-first 加载 + 有机导入 + legacy 兜底)。两处均未设置时默认 full(#3818 翻转 —— shadow 干跑自 #2815 起对账一直干净,索引因此成为默认加载路径;JSON 信封照写,legacy 仍是一行逃生口)。文件层只接受 legacy/shadow/full;环境变量层还接受 1/true(=shadow)与 unified(=full)并优先于文件。每个 lane 启动时解析一次 —— 热改动需重启生效。加密(BILI_ENCRYPTION_KEY)会硬阻断边车。 | -| `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | SQLite 引擎一次性自下载的闸门(#2833):进程内没有可用引擎(无内置 node:sqlite、宿主未装 better-sqlite3)且本平台希望启用统一边车时,bili 从 npm registry 一次性下载钉死的 better-sqlite3 预编译 tarball(约 11 MB,sha512 校验)到缓存目录,之后每次启动复用。引擎解析顺序:内置 node:sqlite(Node >= 22.5)-> 宿主机已装的 better-sqlite3 -> 缓存的自下载副本 -> 自下载(本开关控制)-> 无引擎(仅 legacy,即 #2825 降级契约)。开关只控制网络下载 —— 为 false 时缓存副本仍会使用;不支持的平台永不下载。 tarball 下载内置镜像列表兜底(#3338):先试配置的 registry(BILI_UPDATE_REGISTRY / update.registry),再试 https://registry.npmjs.org、https://registry.npmmirror.com —— 第一个通过 sha512 校验的镜像生效;Node < 22.5 且无引擎时,降级原因会给出明确的 Node 升级提示(#3385)。 | -| `storage.unified` | legacy\|shadow\|full | unset (shadow) | BILI_STORAGE_UNIFIED | 分层存储迁移开关(#2671):shadow = 统一 SQLite 双写干跑 + digest 对账;full = 平替读路径(unified-first 加载 + 有机导入 + legacy 兜底)。两处均未设置时默认 shadow(JSON 仍是唯一事实源,索引只做对账遥测 —— 设 legacy 可退出)。文件层只接受 legacy/shadow/full;环境变量层还接受 1/true(=shadow)与 unified(=full)并优先于文件。每个 lane 启动时解析一次 —— 热改动需重启生效。加密(BILI_ENCRYPTION_KEY)会硬阻断边车。 | | `storage.sqliteAutoDownload` | boolean | true | BILI_SQLITE_AUTO_DOWNLOAD | SQLite 引擎一次性自下载的闸门(#2833):进程内没有可用引擎(无内置 node:sqlite、宿主未装 better-sqlite3)且本平台希望启用统一边车时,bili 从 npm registry 一次性下载钉死的 better-sqlite3 预编译 tarball(约 11 MB,sha512 校验)到缓存目录,之后每次启动复用。引擎解析顺序:内置 node:sqlite(Node >= 22.5)-> 宿主机已装的 better-sqlite3 -> 缓存的自下载副本 -> 自下载(本开关控制)-> 无引擎(仅 legacy,即 #2825 降级契约)。开关只控制网络下载 —— 为 false 时缓存副本仍会使用;不支持的平台永不下载。 tarball 下载内置镜像列表兜底(#3338):先试配置的 registry(BILI_UPDATE_REGISTRY / update.registry),再试 https://registry.npmjs.org、https://registry.npmmirror.com —— 第一个通过 sha512 校验的镜像生效;Node < 22.5 且无引擎时,降级原因会给出明确的 Node 升级提示(#3385)。下载失败会置一个 6 小时的重试冷却,以标记文件形式持久化在缓存目录下(billion-context/sqlite/.bootstrap-failed.json);storage 诊断块会显示该标记的绝对到期时间与路径 —— 删除该文件并重启 bili 即可强制立即重试,不必等完整个冷却窗口(#3788)。 | | `storage.jsonWriter` | on\|off | on | BILI_STORAGE_JSON_WRITER | Phase 3 信封开关(#2960):off 时若 storage.unified 为 full 则不再写 legacy JSON 会话信封 —— SQLite 索引成为唯一持久化副本(读路径本就 unified-first;boot 枚举索引并集,纯索引会话可正常加载)。仅在有效 full 模式下生效:shadow/legacy(或加密激活)下请求会被忽略并警告一次,因为 JSON 文件仍是唯一事实源。环境变量层 0/false/off = off、1/true/on = on,优先于严格拼写的文件层。失败安全:若边车运行中自禁用,下次保存即恢复信封写入。回滚:去掉该开关 —— 写入恢复,纯索引会话经 boot 并集继续可加载,replicas/restore 可重新物化可移植的 JSON 信封。降级二进制(或丢失 SQLite 引擎)会让纯索引会话在 v0.1.196 及更早版本上不可见,直到重新运行 >=v0.1.197 —— 数据在 index.db 中完好无损,只是旧代码不读它。每会话的 content-store 边车无论开关如何都照写。jsonWriter=off 的 lane 必须是其会话目录的唯一写者:off lane 读路径 unified-first、永不回退到文件,因此同一目录上跑 legacy/shadow 的对等实例会静默分叉(它的 JSON 副本收不到更新,off lane 也看不到对等实例的写入)。 | | `storage.walJournalSizeLimitBytes` | number | 8388608 | BILI_STORAGE_WAL_JOURNAL_SIZE_LIMIT_BYTES | index.db-wal 的 WAL 回收上限(#3250),单位字节:每次完成的 checkpoint 把 WAL 文件截回该大小,约束长驻进程的磁盘占用与崩溃恢复重放。不是每会话数据配额 —— 数据写入时就已落进 index.db,WAL 只是两次 checkpoint 之间的帧暂存区,会话数量/大小不会放大它;大 burst 可能暂时超出,直到下一次完成的 checkpoint 截回。调大 = truncate IO 更稀疏,但稳态磁盘占用更多、崩溃恢复重放尾更长。环境变量层(正整数)优先于配置文件层;env 值非法或非正数时静默落到文件/默认层,boot 不崩。lane 启动、store open 时生效 —— 热改动需重启。实际取值会出现在 unified-enable 日志行与 storage 诊断块中。 | @@ -189,6 +187,7 @@ | `sessions.gc.maxTokens` | number | 1000000 | BILI_SESSION_GC_MAX_TOKENS | GC 单会话记录的 token 大小阈值。 | | `sessions.gc.intervalMs` | number | 3600000 | BILI_SESSION_GC_INTERVAL_MS | GC 清扫间隔。 | | `plugin.snapshotCapBytes` | number | 104857600 (0 disables snapshots) | BILI_PUBLIC_SNAPSHOT_CAP_BYTES | 提供给原生插件的 fork API 公共快照大小上限。 | +| `snapshot.shadow` | boolean | true (on) | — | 快照渲染影子对账(#3756 后续):渲染车道仍处灰度关闭时,每轮已折叠会话都现算一次快照视图,与 legacy 实际出站比对分类,逐会话记账(web 面板行 + /__bili/status snapshotShadow 汇总 + snapshot-shadow 诊断主题)。默认开 —— 这是全舰队干跑,其错误率决定灰度翻转。环境变量 BILI_SNAPSHOT_SHADOW 优先。不想要每轮额外计算可用 false/0/off 关闭。 | **更新与公告** @@ -332,6 +331,7 @@ | Key | Type | Default | Env | Description | |-----|------|---------|-----|-------------| | `BILI_DSH_AUTHORED_COMPACTION` | boolean | false | — | 让 bili 本地应答 dsh 压缩摘要请求(返回折叠快照而非拒绝,#3733):身份头 + 内核渲染格式的块摘要,零出口流量;重放经 #2432 再基线识别。 | +| `BILI_SNAPSHOT_SHADOW` | boolean | true (on) | — | 快照渲染影子对账(#3756 后续):每轮已折叠会话都用引擎现算一次出站快照视图但不使用,与 legacy 实际出站比对分类,逐会话计数进 web 面板与 snapshot-shadow 诊断主题。0/false/off 关闭;1/true/on 开启;否则读配置文件 snapshot.shadow 布尔(默认开)。渲染车道本身仍受灰度开关控制(BILI_ROLLOUT_SNAPSHOT_RENDER),影子车道绝不改变出站字节 —— 它是后续翻转灰度的干跑证据。 | | `BILI_CONFIG_FILE` | string | unset (XDG config path) | — | 覆盖配置文件路径(路径重定位)。 | | `BILI_SESSIONS_DIR` | string | unset (XDG state path) | — | 会话记录的存放目录(路径重定位)。 | | `BILI_ENCRYPTION_KEY` | string | unset | — | 加密持久化载荷的密钥材料(机密)。 | diff --git a/src/config.ts b/src/config.ts index 4218ab0fc1..0819018246 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1649,6 +1649,10 @@ type FileConfig = { promptCache?: { routing?: string }; /** MITM block (#2030: + handshakeTimeoutMs, was env BILI_MITM_HANDSHAKE_TIMEOUT_MS only). */ mitm?: { enabled?: boolean; domains?: string[]; handshakeTimeoutMs?: number }; + /** Snapshot-render observability block. `shadow` (boolean, default true) + * computes the snapshot view on armed turns without using it — counters + * surface in the web panel; env BILI_SNAPSHOT_SHADOW wins (#3756). */ + snapshot?: { shadow?: boolean }; /** Re-sign block (#1884), scheme-keyed: the key is the lowercase * Authorization scheme (built-in: "sdk-hmac-sha256" — CodeArts APIG). * `enabled: false` unloads the arm for that scheme (pre-resign rewrite diff --git a/src/knobs.ts b/src/knobs.ts index 1e45c259c7..974a1b896e 100644 --- a/src/knobs.ts +++ b/src/knobs.ts @@ -750,6 +750,25 @@ export function resolveJsonWriterOff(env: NodeJS.ProcessEnv = process.env, fileV return fileValue?.trim().toLowerCase() === "off"; } +/** Snapshot-render SHADOW observability switch (#3756 follow-up): compute the + * snapshot view on every armed proxy turn WITHOUT using it (outbound bytes + * stay the legacy path), classify the diff against what was actually sent, + * and record per-session counters surfaced by the web panel + the + * `snapshot-shadow` diagnostics topic. This is how the fleet proves the + * render engine healthy BEFORE the rollout flip — the same dry-run-then-flip + * discipline storage used (#2815 shadow → #3818 full default). + * Env BILI_SNAPSHOT_SHADOW (0/false/off = off; 1/true/on = on) wins over the + * config-file `snapshot.shadow` boolean; absent everywhere = ON (the render + * lane itself stays rollout-gated at 0%, so the shadow lane is pure + * observation). Garbage spellings fall through to the file/default tier. + * Pure: env + file value in, decision out (never throws). */ +export function resolveSnapshotShadow(env: NodeJS.ProcessEnv = process.env, fileShadow?: boolean): boolean { + const raw = env.BILI_SNAPSHOT_SHADOW?.trim().toLowerCase(); + if (raw === "1" || raw === "true" || raw === "on") return true; + if (raw === "0" || raw === "false" || raw === "off") return false; + return typeof fileShadow === "boolean" ? fileShadow : true; +} + /** SQLite engine self-download switch (#2833): env BILI_SQLITE_AUTO_DOWNLOAD * (1/true vs 0/false, strict) wins over config-file `storage.sqliteAutoDownload` * (strict boolean); absent = true (enabled). Garbage env values fall through to diff --git a/src/log-mask.ts b/src/log-mask.ts index ac2440b279..d34a619b1b 100644 --- a/src/log-mask.ts +++ b/src/log-mask.ts @@ -118,7 +118,7 @@ export function maskUrlsInText(text: string): string { * preference must not weaken the publish boundary (same stance as * redactSecretsInText, which is never gated by the switch). Userinfo, query * and hash are dropped exactly as in maskUrlForLog; the path is kept. */ -export function maskUrlForPublish(url: string): string { +function maskUrlForPublish(url: string): string { let u: URL; try { u = new URL(url); diff --git a/src/server/admin.ts b/src/server/admin.ts index 60a9783370..159ad7023a 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -35,6 +35,7 @@ import { buildSessionReportMd, buildSessionReportSvg } from "../web/report.js"; import { queryLogLines } from "../web/logs-query.js"; import { buildDiagnostics } from "../web/diagnostics.js"; import { storageStatusWire } from "../storage/runtime-status.js"; +import { snapshotShadowStatusWire } from "../server/snapshot-render.js"; import { attributionStatusWire } from "./attribution-status.js"; interface AdminCtx { @@ -953,7 +954,7 @@ async function sendStatus(res: http.ServerResponse, opts: ProxyOptions): Promise loggerLog("warn", `split-session canary (#2170): conversation ${w.base} has live traffic under multiple session keys (design persona forks are excluded): ${w.sessions.map((s) => `${s.id} (requests=${s.requests})`).join("; ")}. For a non-persona host this is the #2165 failure shape (stolen anchor / never-compressing split) — investigate if unexpected.`); } } - res.end(JSON.stringify({ version: VERSION, commit: BUILD_COMMIT, diskVersion, stale, lastInstall, updateReady: updateReadyPayload(), autoRestartOnUpdate: opts.autoRestartOnUpdate, advisory: currentAdvisoryPayload(), updatePolicy: updatePolicyPayload(), pluginAdvisories: detectCostAdvisories(process.env), inFlight: totalInFlight(), splitSessions: splitWarnings, conflicts: summarizeConflicts(listSessions()), storage: storageStatusWire(), attribution: attributionStatusWire() }, null, 2)); + res.end(JSON.stringify({ version: VERSION, commit: BUILD_COMMIT, diskVersion, stale, lastInstall, updateReady: updateReadyPayload(), autoRestartOnUpdate: opts.autoRestartOnUpdate, advisory: currentAdvisoryPayload(), updatePolicy: updatePolicyPayload(), pluginAdvisories: detectCostAdvisories(process.env), inFlight: totalInFlight(), splitSessions: splitWarnings, conflicts: summarizeConflicts(listSessions()), storage: storageStatusWire(), snapshotShadow: snapshotShadowStatusWire(), attribution: attributionStatusWire() }, null, 2)); } // #2090 plan A — read-only view backing the web UI's "Signed upstreams" card: diff --git a/src/server/snapshot-render.ts b/src/server/snapshot-render.ts index f89b9ce2c4..ba7014ce26 100644 --- a/src/server/snapshot-render.ts +++ b/src/server/snapshot-render.ts @@ -1,7 +1,10 @@ import type { BiliMessage } from "acp-kernel/wire"; import { getStore } from "../persist.js"; import { featureEnabled } from "../rollout.js"; -import type { Session } from "../session.js"; +import { listSessions, type Session } from "../session.js"; +import { loadConfigFile } from "../config.js"; +import { resolveSnapshotShadow } from "../knobs.js"; +import { createHash } from "node:crypto"; /** * #3756 snapshot render: assemble the outbound message view for a proxy @@ -118,33 +121,33 @@ function parseRow(content: string, seq: number): BiliMessage | null { * are two observability fields on `session.metadata` (the render latch and the * last post-arm degrade reason) — neither touches outbound bytes. */ -export function maybeSnapshotView(session: Session, clientMsgs: BiliMessage[], deps: SnapshotRenderDeps): BiliMessage[] { - if (!featureEnabled("snapshotRender")) return clientMsgs; - if (deps.pluginMode) return clientMsgs; // plugin lane: client-authoritative by design, not a degradation +type ViewResult = { ok: true; view: BiliMessage[] } | { ok: false; reason: string }; + +function buildView(session: Session, clientMsgs: BiliMessage[]): ViewResult { const activeBlocks = session.state.blocks.filter((b) => b.active); - if (activeBlocks.length === 0) return clientMsgs; + if (activeBlocks.length === 0) return { ok: false, reason: "no-active-blocks" }; const store = getStore(); - if (!store) return legacyFor(session, deps, clientMsgs, "store-unavailable"); + if (!store) return { ok: false, reason: "store-unavailable" }; let rows: ViewRow[] = []; try { const rawRows = store.unifiedTailViewRows(session.id); const seqs = store.unifiedTailSeqs(session.id); - if (!rawRows || rawRows.length === 0 || !seqs || seqs.length === 0) return legacyFor(session, deps, clientMsgs, "transcript-empty"); + if (!rawRows || rawRows.length === 0 || !seqs || seqs.length === 0) return { ok: false, reason: "transcript-empty" }; const bySeq = new Map(); for (const row of rawRows) { const msg = parseRow(row.content, row.seq); - if (!msg) return legacyFor(session, deps, clientMsgs, "row-unparsable"); // untrustworthy transcript: degrade, never guess + if (!msg) return { ok: false, reason: "row-unparsable" }; // untrustworthy transcript: degrade, never guess bySeq.set(row.seq, { seq: row.seq, msg }); } for (const seq of seqs) { const v = bySeq.get(seq); - if (!v) return legacyFor(session, deps, clientMsgs, "view-pointer-missing-row"); // view pointer to a missing row: degrade + if (!v) return { ok: false, reason: "view-pointer-missing-row" }; // view pointer to a missing row: degrade rows.push(v); } } catch { - return legacyFor(session, deps, clientMsgs, "transcript-error"); + return { ok: false, reason: "transcript-error" }; } - if (rows.length === 0) return legacyFor(session, deps, clientMsgs, "transcript-empty"); + if (rows.length === 0) return { ok: false, reason: "transcript-empty" }; // Backward chain: from the client's end, match view rows (id fast path, // then identity signature). The chain must be contiguous; the first @@ -208,13 +211,13 @@ export function maybeSnapshotView(session: Session, clientMsgs: BiliMessage[], d run++; cursor = hit; } - if (!started) return legacyFor(session, deps, clientMsgs, "chain-not-started"); // nothing chains: epoch-like rewrite, legacy + if (!started) return { ok: false, reason: "chain-not-started" }; // nothing chains: epoch-like rewrite, legacy // #3812: a lone match — however it matched — is not a seam. The classic // shape: the client's new "继续" chains by signature against an old // "继续" row while the true history sits above the old row's position; // accepting it renders only the ancient prefix + the one tail message // and silently drops everything between. Degrade instead: never guess. - if (run < MIN_SEAM_RUN) return legacyFor(session, deps, clientMsgs, "seam-too-short"); + if (run < MIN_SEAM_RUN) return { ok: false, reason: "seam-too-short" }; } const d = joinRow + 1; // prefix = rows[0..d) — everything up to the join; rows beyond (rewound-away tails) never render @@ -240,7 +243,7 @@ export function maybeSnapshotView(session: Session, clientMsgs: BiliMessage[], d // it at the top (the old behavior) renders the summary above raw // history the engine can no longer suppress. Degrade to the legacy // path, which renders the client view untouched. - if (blockSeqs.size === 0) return legacyFor(session, deps, clientMsgs, "block-unanchored"); + if (blockSeqs.size === 0) return { ok: false, reason: "block-unanchored" }; // NOTE: upgrade twins (ids re-minted, same content) are anchored by // reconcile's re-key of effectiveMessageIds, NOT by signature // propagation here: the old sig sweep could not distinguish an @@ -281,7 +284,178 @@ export function maybeSnapshotView(session: Session, clientMsgs: BiliMessage[], d while (ai < anchors.length) merged.push(anchors[ai++].msg); for (let k = clientJoin; k < clientMsgs.length; k++) merged.push(clientMsgs[k]); - delete session.metadata["snapshotRenderDegradeReason"]; - noteRender(session, deps); - return merged; + return { ok: true, view: merged }; +} + +export function maybeSnapshotView(session: Session, clientMsgs: BiliMessage[], deps: SnapshotRenderDeps): BiliMessage[] { + if (deps.pluginMode) return clientMsgs; // plugin lane: client-authoritative by design, not a degradation + const live = featureEnabled("snapshotRender"); + const shadow = !live && shadowLaneEnabled(); + if (!live && !shadow) return clientMsgs; + // Pre-arm (no folded block yet) is not observable and not a degrade: skip. + if (!session.state.blocks.some((b) => b.active)) return clientMsgs; + const r = buildView(session, clientMsgs); + if (live) { + if (!r.ok) return legacyFor(session, deps, clientMsgs, r.reason); + delete session.metadata["snapshotRenderDegradeReason"]; + noteRender(session, deps); + return r.view; + } + noteShadow(session, deps, r, clientMsgs); + return clientMsgs; // shadow NEVER changes outbound bytes +} + +// --------------------------------------------------------------------------- +// Shadow observability (#3756 follow-up): classify the would-be view against +// what the legacy path actually sends. The classes are MECHANICAL — no +// heuristics; every error class is a provable set/logic violation. +// --------------------------------------------------------------------------- + +function shadowLaneEnabled(): boolean { + return resolveSnapshotShadow(process.env, loadConfigFile().snapshot?.shadow); +} + +interface ShadowClassifyInput { + view: BiliMessage[]; + clientMsgs: BiliMessage[]; + coveredClientIds: ReadonlySet; + prev?: { inputDigest?: string; viewDigest?: string }; +} + +interface ShadowClassify { + lostTail: number; + duplicateIds: string[]; + unstablePrefix: boolean; + suppressed: number; + inputDigest: string; + viewDigest: string; +} + +export function classifyShadowForTest(x: ShadowClassifyInput): ShadowClassify { + const digest = (msgs: BiliMessage[]): string => + createHash("sha256").update(msgs.map((m) => `${m.id}\u0000${identitySig(m)}`).join("\u0001")).digest("hex").slice(0, 16); + const isAnchor = (m: BiliMessage): boolean => typeof m.id === "string" && m.id.startsWith("acp_summary_"); + const viewIds = new Set(); + const viewSigCount = new Map(); + const idCount = new Map(); + for (const m of x.view) { + if (isAnchor(m)) continue; + viewIds.add(m.id); + idCount.set(m.id, (idCount.get(m.id) ?? 0) + 1); + const sig = identitySig(m); + viewSigCount.set(sig, (viewSigCount.get(sig) ?? 0) + 1); + } + let lostTail = 0; + let suppressed = 0; + for (const m of x.clientMsgs) { + const inView = viewIds.has(m.id) || (viewSigCount.get(identitySig(m)) ?? 0) > 0; + if (x.coveredClientIds.has(m.id)) { + if (!inView) suppressed++; // expected fold suppression: info, never an error + continue; + } + if (!inView) lostTail++; // a non-covered client message vanished from the would-be view + } + const duplicateIds = [...idCount.entries()].filter(([, c]) => c > 1).map(([id]) => id); + const inputDigest = digest(x.clientMsgs); + const viewDigest = digest(x.view); + const unstablePrefix = + x.prev?.inputDigest !== undefined && x.prev.inputDigest === inputDigest && x.prev.viewDigest !== undefined && x.prev.viewDigest !== viewDigest; + return { lostTail, duplicateIds, unstablePrefix, suppressed, inputDigest, viewDigest }; +} + +interface ShadowBlob { + turns: number; + errors: number; + lastClass: "watch" | "degraded" | "error"; + lastReason?: string; + lastErrors?: string[]; + inputDigest?: string; + viewDigest?: string; + lastLogged?: string; +} + +function noteShadow(session: Session, deps: SnapshotRenderDeps, result: ViewResult, clientMsgs: BiliMessage[]): void { + const prior = session.metadata["snapshotShadow"]; + const blob: ShadowBlob = + prior && typeof prior === "object" && typeof (prior as ShadowBlob).turns === "number" + ? (prior as ShadowBlob) + : { turns: 0, errors: 0, lastClass: "watch" }; + blob.turns++; + if (!result.ok) { + // Degrade classes (storage-off, seam-too-short, …) are KNOWN costs of + // the conservative gates — the legacy outbound is what shipped, so + // there is no would-be view to diff. Record the reason, never an error. + blob.lastClass = "degraded"; + blob.lastReason = result.reason; + delete blob.lastErrors; + delete blob.inputDigest; + delete blob.viewDigest; + if (blob.lastLogged !== result.reason) { + deps.log?.("warn", `[snapshot-shadow] view degraded on ${session.id} (${result.reason}) — legacy outbound kept`); + blob.lastLogged = result.reason; + } + session.metadata["snapshotShadow"] = blob; + return; + } + const covered = new Set(); + for (const b of session.state.blocks) { + if (!b.active) continue; + for (const id of b.effectiveMessageIds) covered.add(id); + } + const c = classifyShadowForTest({ + view: result.view, + clientMsgs, + coveredClientIds: covered, + prev: { inputDigest: blob.inputDigest, viewDigest: blob.viewDigest }, + }); + blob.inputDigest = c.inputDigest; + blob.viewDigest = c.viewDigest; + const errors: string[] = []; + if (c.lostTail > 0) errors.push(`lost-tail:${c.lostTail}`); + if (c.duplicateIds.length > 0) errors.push(`duplicate:${c.duplicateIds.length}`); + if (c.unstablePrefix) errors.push("unstable-prefix"); + const signature = errors.length > 0 ? errors.join(",") : "ok"; + if (errors.length > 0) { + blob.errors += errors.length; + blob.lastClass = "error"; + blob.lastErrors = errors; + delete blob.lastReason; + if (blob.lastLogged !== signature) { + deps.log?.("error", `[snapshot-shadow] mechanical mismatch on ${session.id} (${errors.join("; ")}) — diagnostics: /__bili/diagnostics?topic=snapshot-shadow`); + blob.lastLogged = signature; + } + } else { + blob.lastClass = "watch"; + delete blob.lastReason; + delete blob.lastErrors; + } + session.metadata["snapshotShadow"] = blob; +} + +interface SnapshotShadowWire { + enabled: boolean; + watching: number; + errors: number; + worst?: { sessionId: string; label?: string; lastErrors: string[] }; } + +/** Aggregate across the live session pool for /__bili/status + the banner. */ +export function snapshotShadowStatusWire(): SnapshotShadowWire { + const enabled = shadowLaneEnabled(); + let watching = 0; + let errors = 0; + let worst: { sessionId: string; label?: string; lastErrors: string[]; n: number } | undefined; + for (const s of listSessions()) { + const blob = s.metadata["snapshotShadow"] as ShadowBlob | undefined; + if (!blob || typeof blob !== "object" || !(blob.turns > 0)) continue; + watching++; + errors += blob.errors ?? 0; + if ((blob.errors ?? 0) > 0 && (!worst || (blob.errors ?? 0) > worst.n)) { + worst = { sessionId: s.id, label: s.meta.label !== s.id ? s.meta.label : undefined, lastErrors: blob.lastErrors ?? [], n: blob.errors ?? 0 }; + } + } + return enabled + ? { enabled, watching, errors, ...(worst ? { worst: { sessionId: worst.sessionId, label: worst.label, lastErrors: worst.lastErrors } } : {}) } + : { enabled, watching, errors }; +} + diff --git a/src/web/client.ts b/src/web/client.ts index 812697de32..3de7709226 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -794,6 +794,25 @@ export const WEB_CLIENT = `(function () { sb.innerHTML = ""; } } + const sh = $("snapshot-shadow-banner"); + if (sh) { + const sw = d.snapshotShadow; + if (sw && sw.enabled && sw.errors > 0) { + sh.hidden = false; + sh.classList.add("show"); + const worstTxt = sw.worst ? "(" + (sw.worst.label ?? sw.worst.sessionId) + ")" : ""; + sh.innerHTML = "" + t("sys.snapshot_shadow_title") + " " + escapeHtml(t("sys.snapshot_shadow", { n: String(sw.errors), worst: worstTxt })) + + '
' + + '" + + '' + t("sys.report_issue") + "" + + "
"; + attachReportButtons("snapshot-shadow", sh); + } else { + sh.hidden = true; + sh.classList.remove("show"); + sh.innerHTML = ""; + } + } const pt = $("passthrough-banner"); if (d.passthrough && d.passthrough.enabled) { pt.hidden = false; diff --git a/src/web/diagnostics.ts b/src/web/diagnostics.ts index 450d7bbf5d..90e8420382 100644 --- a/src/web/diagnostics.ts +++ b/src/web/diagnostics.ts @@ -33,6 +33,7 @@ import { readFileSync, statSync } from "node:fs"; import os from "node:os"; import * as path from "node:path"; import { summarizeConflicts } from "../conflict-watch.js"; +import { snapshotShadowStatusWire } from "../server/snapshot-render.js"; import { dshProfileDirs } from "../dsh-channel.js"; import { resolveDshHome } from "../client-config.js"; import { safeReadJson } from "../config.js"; @@ -278,6 +279,10 @@ const TOPICS: Record = { // "copy diagnostics / report on GitHub" buttons straight on the banner. // #3611: the ledger section alone was not diagnosable (no client version, // no config, no log evidence) — the matching log signatures ride along. + "snapshot-shadow": { + title: () => `Snapshot-render shadow mismatch (bili v${VERSION}, node ${process.version}, ${process.platform}-${process.arch})`, + section: () => snapshotShadowDiagnosticsLines(), + }, "conflict-banner": { title: () => `Compression conflict banner (bili v${VERSION}, node ${process.version}, ${process.platform}-${process.arch})`, section: (ctx) => [ @@ -296,6 +301,33 @@ interface DiagnosticsReport { url: string; } +/** #3756 follow-up: snapshot-render shadow lane — the engine computes the + * would-be view on every armed turn and classifies the diff against the + * legacy outbound. This section lists the watching sessions and the worst + * offenders so a user can attach it to a report with one click. */ +function snapshotShadowDiagnosticsLines(): string[] { + const wire = snapshotShadowStatusWire(); + const lines = [ + `snapshot-shadow: enabled=${wire.enabled} watching=${wire.watching} totalErrors=${wire.errors}`, + ]; + if (wire.worst) { + lines.push(`worst: ${wire.worst.sessionId}${wire.worst.label ? ` (${wire.worst.label})` : ""} lastErrors=${wire.worst.lastErrors.join("; ") || "(none recorded)"}`); + } else { + lines.push("worst: (no session with error-class entries)"); + } + lines.push("--- per-session shadow blobs ---"); + let listed = 0; + for (const s of listSessions()) { + const b = s.metadata["snapshotShadow"] as { turns?: number; errors?: number; lastClass?: string; lastReason?: string; lastErrors?: string[] } | undefined; + if (!b || typeof b !== "object" || !((b.turns ?? 0) > 0)) continue; + lines.push(`${s.id}${s.meta.label !== s.id ? ` (${s.meta.label})` : ""}: turns=${b.turns} errors=${b.errors ?? 0} lastClass=${b.lastClass ?? "watch"}${b.lastReason ? ` reason=${b.lastReason}` : ""}${b.lastErrors?.length ? ` lastErrors=${b.lastErrors.join(";")}` : ""}`); + listed++; + if (listed >= 40) { lines.push("(…more sessions truncated)"); break; } + } + if (listed === 0) lines.push("(no watching sessions in the live pool)"); + return lines; +} + export function buildDiagnostics(topic?: string): DiagnosticsReport { const t = topic?.trim().slice(0, 64) ?? ""; const def = t ? TOPICS[t] : undefined; diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 375020e434..4bbcb7c5ba 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -118,6 +118,8 @@ export const MESSAGES: Record> = { "sys.pt_file": "配置文件 passthrough: true", "sys.storage_degraded_title": "SQLite 存储降级:", "sys.storage_degraded": "未来几个版本将默认开启 SQLite 统一存储,但你的系统因 {reason} 暂不支持(已自动回退 JSON 存储,当前不受影响)。请点击下方按钮反馈,帮助我们在默认开启前覆盖你的环境。", + "sys.snapshot_shadow_title": "快照渲染对账发现异常", + "sys.snapshot_shadow": "出站快照引擎(尚未启用,仅对账)在 {n} 处发现与实际发送不一致{worst}。当前发送内容完全不受影响——这是灰度前的健康巡检报警。请点击下方按钮反馈诊断,帮助我们在正式启用前修复。", "sys.report_copy": "复制诊断信息", "sys.report_issue": "在 GitHub 反馈", "conflict.on": "检测到压缩冲突", @@ -612,6 +614,8 @@ export const MESSAGES: Record> = { "sys.pt_file": "config file passthrough: true", "sys.storage_degraded_title": "SQLite storage degraded:", "sys.storage_degraded": "Unified SQLite storage becomes the default in an upcoming release, but this system cannot run it ({reason}). You have been automatically rolled back to JSON storage — nothing is affected today. Please report this so your environment is covered before the flip.", + "sys.snapshot_shadow_title": "Snapshot render shadow found mismatches", + "sys.snapshot_shadow": "The outbound snapshot engine (not enabled yet — shadow-compare only) found {n} mismatches against what was actually sent{worst}. Nothing you send is affected today — this is a pre-rollout health check alarm. Please report the diagnostics so it can be fixed before the flip.", "sys.report_copy": "Copy diagnostics", "sys.report_issue": "Report on GitHub", "conflict.on": "Compression conflict detected", diff --git a/src/web/page.ts b/src/web/page.ts index d6ece0eda6..bdb77c0a6e 100644 --- a/src/web/page.ts +++ b/src/web/page.ts @@ -25,6 +25,7 @@ export function renderPage(origin: string, version: string, embed = false, theme + diff --git a/src/web/sessions-data.ts b/src/web/sessions-data.ts index 9b9290c1ad..237ce9c60d 100644 --- a/src/web/sessions-data.ts +++ b/src/web/sessions-data.ts @@ -39,6 +39,9 @@ interface WebSessionSummary { /** #1839: provenance of contextTokens — "usage" = last real usage report, * "estimate" = bounded local estimate (display should mark it as such). */ contextTokensSource?: "usage" | "estimate"; + /** #3756 follow-up: snapshot-render shadow counters (view computed, never + * emitted). Present only for sessions with at least one armed turn. */ + snapshotShadow?: { turns: number; errors: number; lastClass: "watch" | "degraded" | "error"; lastReason?: string }; /** #2117: the honest best reading of "how full is this context right now", * picked by provenance (usage > calibrated estimate > char-count upper * bound). Display surfaces drive their main bar from this so one value @@ -625,6 +628,10 @@ function summaryOf(s: SummarySource, live: boolean): WebSessionSummary { // covered ids are now entirely off the wire. Live state: self-heals when // the host resends the originals again. const covAll = s.metadata[METADATA_FOLD_COVERAGE] as Record | undefined; + // #3756 follow-up: snapshot-render shadow counters (view computed, never + // emitted) — surfaced on the list row so the panel can watch the render + // engine's health across the fleet before the rollout flip. + const shadowBlob = s.metadata["snapshotShadow"] as { turns?: number; errors?: number; lastClass?: string; lastReason?: string } | undefined; const agg = led; const requests = Math.max(s.stats.requests ?? 0, agg?.agg?.requests ?? 0); const inputTokens = Math.max(s.stats.inputTokens ?? 0, agg?.agg?.input ?? 0); @@ -700,6 +707,9 @@ function summaryOf(s: SummarySource, live: boolean): WebSessionSummary { ...(s.meta.label && s.meta.label !== s.id ? { label: s.meta.label } : {}), ...(s.meta.protocol ? { protocol: s.meta.protocol } : {}), ...(s.meta.upstreamOrigin ? { upstreamOrigin: s.meta.upstreamOrigin } : {}), + ...(shadowBlob && (shadowBlob.turns ?? 0) > 0 + ? { snapshotShadow: { turns: shadowBlob.turns as number, errors: shadowBlob.errors ?? 0, lastClass: (shadowBlob.lastClass as "watch" | "degraded" | "error") ?? "watch", ...(shadowBlob.lastReason ? { lastReason: shadowBlob.lastReason } : {}) } } + : {}), live, requests, contextTokens: s.stats.contextTokens, @@ -991,6 +1001,15 @@ function renderDetail(session: Session, live: boolean): WebSessionDetail { ...(clientHint ? { clientHint } : {}), ...(typeof session.metadata["biliVersion"] === "string" ? { biliVersion: session.metadata["biliVersion"] as string } : {}), ...(typeof session.metadata["storageMode"] === "string" ? { storageMode: session.metadata["storageMode"] as string } : {}), + // #3756 follow-up: snapshot-render shadow observability (compute the + // view, never emit it) — surfaced so the panel can prove the render + // engine healthy across the fleet before the rollout flip. + ...(() => { + const b = session.metadata["snapshotShadow"] as { turns?: number; errors?: number; lastClass?: string; lastReason?: string } | undefined; + return b && typeof b.turns === "number" && b.turns > 0 + ? { snapshotShadow: { turns: b.turns, errors: b.errors ?? 0, lastClass: (b.lastClass as "watch" | "degraded" | "error") ?? "watch", ...(b.lastReason ? { lastReason: b.lastReason } : {}) } } + : {}; + })(), // #2904: no-ceiling output-budget degraded state (written by restoreOutputBudget). ...(typeof (session.metadata["outputBudgetDegraded"] as { model?: unknown } | undefined)?.model === "string" ? { outputBudgetDegraded: session.metadata["outputBudgetDegraded"] as { model: string; value: number; ts: number } } diff --git a/tests/snapshot-shadow.test.ts b/tests/snapshot-shadow.test.ts new file mode 100644 index 0000000000..4314d1f651 --- /dev/null +++ b/tests/snapshot-shadow.test.ts @@ -0,0 +1,350 @@ +// #3756 follow-up: snapshot render SHADOW mode — default-on observability lane. +// +// The render engine ships inactive (rollout 0%). Shadow flips the default the +// OTHER way: every proxy turn with an armed fold ALSO computes the snapshot +// view, classifies the diff against the legacy outbound, records counters in +// session metadata — and DISCARDS the view (outbound bytes untouched). +// +// Contract staked BEFORE the implementation (打桩): +// +// 1. knob resolution: env BILI_SNAPSHOT_SHADOW > file `snapshot.shadow` > +// default ON; garbage spellings fall back, never throw. +// 2. shadow observes without emitting: with shadow on + rollout off, the +// outbound bytes are IDENTICAL to a shadow-off baseline run; the session +// gains metadata.snapshotShadow with turns counted and zero errors. +// 3. classifier (pure): the #3812 misjoin shape (view drops non-covered +// client messages) reports lostTail errors; duplicated non-anchor ids +// report; same-input/different-view reports unstablePrefix; the clean +// shape reports none of them. +// 4. degrade accounting: a seam-too-short session records lastClass +// "degraded" + reason, with ZERO error-class entries (known cost, not a +// bug — the alert bar must NOT light up for it). +// 5. surfacing: /__bili/status aggregates snapshotShadow {enabled, watching, +// errors}; /__bili/sessions entries carry the per-session counters; the +// `snapshot-shadow` diagnostics topic names erroring sessions. +// 6. opt-out: BILI_SNAPSHOT_SHADOW=0 writes no shadow metadata at all. +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +process.env.NODE_ENV = "test"; +process.env.BILI_PERSIST_ZSTD = "0"; +process.env.BILI_STORAGE_UNIFIED = "shadow"; +process.env.BILI_CONFIG_FILE = path.join(mkdtempSync(path.join(tmpdir(), "bili-shadow-hermetic-")), "no-config.json"); +delete process.env.BILI_ROLLOUT_SNAPSHOT_RENDER; // render stays OFF — shadow must observe via the legacy outbound + +import { defaultConfig } from "acp-kernel"; +import type { BiliMessage } from "acp-kernel/wire"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { listSessions, _resetSessionsForTest } from "../src/session.ts"; +import { resolveSnapshotShadow } from "../src/knobs.ts"; +import { classifyShadowForTest } from "../src/server/snapshot-render.ts"; +import { rmrf } from "./tmp-rm.ts"; + +const SUMMARY = "MAIN-SUMMARY-SETUP-CONTEXT-FOLDED-BY-COMPRESSION-LONG-ENOUGH-FOR-KERNEL-MIN-LENGTH-CHECK"; + +function sse(obj: unknown): string { + return `data: ${JSON.stringify(obj)}\n\n`; +} + +function conversation(tail: { role: string; content: string }[] = []): { role: string; content: string }[] { + const out: { role: string; content: string }[] = []; + for (let i = 0; i < 23; i++) { + out.push({ role: i % 2 === 0 ? "user" : "assistant", content: `Message ${i} of the working session. ` + `WORK_${i}_content_`.repeat(88) }); + } + return [...out, ...tail]; +} + +type Harness = { + proxy: http.Server; + upstream: http.Server; + bodies: string[]; + url: string; + statusUrl: string; + sessionsUrl: string; + diagUrl: (topic: string) => string; + store: { unifiedTailSeqs(sessionId: string): number[] | null } | null; + sessionOf: (label: string) => { meta: { label: string }; state: { blocks: { id: string; active: boolean }[] }; metadata: Record } | undefined; +}; + +async function withHarness(fn: (h: Harness) => Promise, storeEnabled: boolean): Promise { + const bodies: string[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + bodies.push(Buffer.concat(chunks).toString("utf8")); + const n = bodies.length; + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + if (n === 1) { + const args = JSON.stringify({ content: [{ startId: "m00001", endId: "m00008", topic: "setup", summary: SUMMARY }] }); + res.write(sse({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: null, tool_calls: [{ index: 0, id: "call_p", type: "function", function: { name: "compress", arguments: args } }] } }] })); + res.write(sse({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] })); + } else { + const text = n === 2 ? "done compressing" : `ok ${n}`; + res.write(sse({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: text } }] })); + res.write(sse({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })); + } + res.end(); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + const dir = mkdtempSync(path.join(tmpdir(), "bili-shadow-store-")); + const store = storeEnabled ? new SessionStore({ enabled: true, dir, debounceMs: 0 }) : new SessionStore({ enabled: false }); + _setStoreForTest(store); + _resetSessionsForTest(); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "gpt-test": { context: 15_000 } } } }, + modelContextLimit: 15_000, + kernelConfig: defaultConfig(15_000), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: Boolean(process.env.SNAP_DEBUG), + debug: Boolean(process.env.SNAP_DEBUG), + passthrough: false, + passthroughSource: null, + autoUpdate: false, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: true, + releaseNotesCheck: true, + compat: { roles: {} }, + streamErrorShape: "protocol", + mitm: { enabled: false, domains: [] }, + } as unknown as ProxyOptions); + await once(proxy, "listening"); + const port = (proxy.address() as { port: number }).port; + const h: Harness = { + proxy, + upstream, + bodies, + url: `http://127.0.0.1:${port}/bili/http://127.0.0.1:${upstreamPort}/v1/chat/completions`, + statusUrl: `http://127.0.0.1:${port}/__bili/status`, + sessionsUrl: `http://127.0.0.1:${port}/__bili/sessions`, + diagUrl: (topic) => `http://127.0.0.1:${port}/__bili/diagnostics?topic=${topic}`, + store: storeEnabled ? store : null, + sessionOf: (label) => listSessions().find((x) => x.meta.label === label) as never, + }; + try { + await fn(h); + } finally { + proxy.close(); + proxy.closeIdleConnections?.(); + await once(proxy, "close"); + upstream.close(); + upstream.closeIdleConnections?.(); + await once(upstream, "close"); + delete process.env.BILI_SNAPSHOT_SHADOW; + delete process.env.BILI_ROLLOUT_SNAPSHOT_RENDER; + store.closeQuietly(); + void rmrf(dir); + } +} + +const rowsSeen = new Map(); +async function settleRows(h: Harness, label: string): Promise { + if (!h.store) { + await new Promise((res) => setTimeout(res, 60)); + return; + } + const prev = rowsSeen.get(label) ?? 0; + for (let i = 0; i < 200; i++) { + const n = h.store.unifiedTailSeqs(label)?.length ?? 0; + if (n !== prev && n > 0) { + rowsSeen.set(label, n); + return; + } + await new Promise((res) => setTimeout(res, 25)); + } + throw new Error(`settleRows: store tail view never changed for ${label}`); +} + +type Msg = { role: string; content: string }; + +async function turn(h: Harness, label: string, messages: unknown[], history: Msg[] | null = null): Promise<{ status: number; body: string; idx: number }> { + const r = await fetch(h.url, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": label }, + body: JSON.stringify({ model: "gpt-test", messages, stream: true }), + }); + const body = await r.text(); + await settleRows(h, label); + if (history) { + const t = body; + const matches = [...t.matchAll(/"content":"((?:[^"\\]|\\.)*)"/g)].reverse(); + if (matches.length > 0) { + const raw = JSON.parse(`"${matches[0][1]}"`); + if (raw) history.push({ role: "assistant", content: String(raw) }); + } + } + return { status: r.status ?? 0, body, idx: h.bodies.length - 1 }; +} + +function sentMessages(h: Harness, i: number): { role: string; content: unknown }[] { + return JSON.parse(h.bodies[i]).messages; +} + +/** stake 1 — knob resolution matrix. */ +test("snapshot shadow knob: env > file > default-on, garbage never throws", () => { + assert.equal(resolveSnapshotShadow({} as NodeJS.ProcessEnv, undefined), true, "default on"); + assert.equal(resolveSnapshotShadow({} as NodeJS.ProcessEnv, false), false, "file false honored"); + assert.equal(resolveSnapshotShadow({} as NodeJS.ProcessEnv, true), true, "file true honored"); + assert.equal(resolveSnapshotShadow({ BILI_SNAPSHOT_SHADOW: "0" } as NodeJS.ProcessEnv, true), false, "env off wins over file on"); + assert.equal(resolveSnapshotShadow({ BILI_SNAPSHOT_SHADOW: "false" } as NodeJS.ProcessEnv, undefined), false, "env false"); + assert.equal(resolveSnapshotShadow({ BILI_SNAPSHOT_SHADOW: "off" } as NodeJS.ProcessEnv, undefined), false, "env off"); + assert.equal(resolveSnapshotShadow({ BILI_SNAPSHOT_SHADOW: "1" } as NodeJS.ProcessEnv, false), true, "env on wins over file off"); + assert.equal(resolveSnapshotShadow({ BILI_SNAPSHOT_SHADOW: "on" } as NodeJS.ProcessEnv, undefined), true, "env on"); + assert.equal(resolveSnapshotShadow({ BILI_SNAPSHOT_SHADOW: "garbage" } as NodeJS.ProcessEnv, false), false, "garbage env degrades to file value"); +}); + +/** stake 3 — pure classifier: mechanical error classes. */ +test("snapshot shadow classifier: misjoin/duplicate/unstable are mechanical errors", () => { + const row = (id: string, text: string): BiliMessage => ({ id, role: "user", contentType: "text", text } as BiliMessage); + // #3812 misjoin shape: the view chains against an OLD "继续" row and drops + // the middle of the conversation. Covered = the two ids the block owns. + { + const view = [row("h_r1", "old question"), row("h_r2", "old answer")]; + const clientMsgs = [row("h_r1", "old question"), row("h_r2", "old answer"), row("h_m1", "middle 1"), row("h_m2", "middle 2"), row("h_t1", "final question")]; + const r = classifyShadowForTest({ view, clientMsgs, coveredClientIds: new Set(["h_r1", "h_r2"]) }); + assert.equal(r.lostTail, 3, "three non-covered client messages vanish from the view"); + assert.deepEqual(r.duplicateIds, []); + assert.equal(r.unstablePrefix, false); + } + // duplicate: the same non-anchor id renders twice (upgrade twin misrender). + { + const view = [row("h_a", "x"), row("h_a", "x"), row("h_t1", "t")]; + const clientMsgs = [row("h_a", "x"), row("h_t1", "t")]; + const r = classifyShadowForTest({ view, clientMsgs, coveredClientIds: new Set() }); + assert.deepEqual(r.duplicateIds, ["h_a"]); + assert.equal(r.lostTail, 0); + } + // unstable: identical resent input, different view prefix. + { + const base = { inputDigest: undefined as string | undefined, viewDigest: undefined as string | undefined }; + const first = classifyShadowForTest({ view: [row("h_a", "stable"), row("h_t1", "t")], clientMsgs: [row("h_a", "stable"), row("h_t1", "t")], coveredClientIds: new Set() }); + const second = classifyShadowForTest({ view: [row("h_a", "CHANGED"), row("h_t1", "t")], clientMsgs: [row("h_a", "stable"), row("h_t1", "t")], coveredClientIds: new Set(), prev: { inputDigest: first.inputDigest, viewDigest: first.viewDigest } }); + void base; + assert.equal(second.unstablePrefix, true, "same input must yield the same view"); + const stable = classifyShadowForTest({ view: [row("h_a", "stable"), row("h_t1", "t")], clientMsgs: [row("h_a", "stable"), row("h_t1", "t")], coveredClientIds: new Set(), prev: { inputDigest: first.inputDigest, viewDigest: first.viewDigest } }); + assert.equal(stable.unstablePrefix, false); + } + // clean shape: suppression of covered messages is NOT an error. + { + const view = [row("h_new", "fresh tail")]; + const clientMsgs = [row("h_old1", "folded"), row("h_old2", "folded"), row("h_new", "fresh tail")]; + const r = classifyShadowForTest({ view, clientMsgs, coveredClientIds: new Set(["h_old1", "h_old2"]) }); + assert.equal(r.lostTail, 0); + assert.deepEqual(r.duplicateIds, []); + assert.equal(r.unstablePrefix, false); + assert.equal(r.suppressed, 2, "covered messages the view drops are counted as info"); + } +}); + +/** stakes 2+5 — observe-without-emit + surfacing. */ +test("snapshot shadow: observes armed folds, outbound identical to baseline, surfaces counters", async (t) => { + // baseline FIRST (shadow off) so the comparison lives in one process. + let baseline: string[] = []; + await withHarness(async (h) => { + process.env.BILI_SNAPSHOT_SHADOW = "0"; + const history = conversation(); + await turn(h, "s-base", history.map((m) => ({ ...m }))); + await turn(h, "s-base", [...history.map((m) => ({ ...m })), { role: "user", content: "TAIL_A follow up question about the work" }]); + baseline = [...h.bodies]; + const s = h.sessionOf("s-base"); + assert.equal(s?.metadata.snapshotShadow, undefined, "opt-out writes no shadow metadata"); + }, true); + assert.ok(baseline.length >= 3, "baseline captured both requests"); + + await withHarness(async (h) => { + delete process.env.BILI_SNAPSHOT_SHADOW; // default ON + const history = conversation(); + await turn(h, "s-obs", history.map((m) => ({ ...m }))); + await turn(h, "s-obs", [...history.map((m) => ({ ...m })), { role: "user", content: "TAIL_A follow up question about the work" }]); + // outbound identical to the shadow-off baseline (same deterministic turns) + assert.equal(h.bodies.length, baseline.length); + for (let i = 0; i < baseline.length; i++) { + assert.equal(h.bodies[i], baseline[i], `upstream body ${i} must be byte-identical with shadow on`); + } + const s = h.sessionOf("s-obs"); + const meta = s?.metadata.snapshotShadow as { turns: number; errors: number; lastClass: string } | undefined; + assert.ok(meta, "shadow metadata recorded"); + assert.ok((meta.turns ?? 0) >= 1, "at least one turn observed"); + assert.equal(meta.errors, 0, "healthy session reports zero errors"); + assert.equal(s?.metadata.snapshotRenderTurns, undefined, "render latch stays off (rollout 0%)"); + + // surfacing: status aggregate + const st = await (await fetch(h.statusUrl)).json() as { snapshotShadow?: { enabled: boolean; watching: number; errors: number } }; + assert.equal(st.snapshotShadow?.enabled, true); + assert.ok((st.snapshotShadow?.watching ?? 0) >= 1, "one session under watch"); + assert.equal(st.snapshotShadow?.errors, 0, "no error sessions"); + + // surfacing: sessions list carries per-session counters + const list = await (await fetch(h.sessionsUrl)).json() as { sessions: { id: string; snapshotShadow?: { turns: number; errors: number } }[] }; + const entry = list.sessions.find((x) => x.snapshotShadow && x.snapshotShadow.turns > 0); + assert.ok(entry, "sessions list exposes snapshotShadow counters"); + + // surfacing: diagnostics topic names watching sessions + const diag = await (await fetch(h.diagUrl("snapshot-shadow"))).json() as { blob: string }; + assert.match(diag.blob, /snapshot-shadow/); + }, true); +}); + +/** stake 4 — degrade accounting: known costs never light the error bar. */ +test("snapshot shadow: seam-too-short degrades without error-class entries", async () => { + await withHarness(async (h) => { + const history = conversation(); + history[2] = { role: "user", content: "继续" }; + await turn(h, "s-seam", history.map((m) => ({ ...m }))); + const seen = [...history]; + // make the resent history contain ANOTHER "继续" — the classic #3812 shape + seen.push({ role: "assistant", content: "done compressing" }); + seen.push({ role: "user", content: "继续" }); + await turn(h, "s-seam", seen.map((m) => ({ ...m }))); + const s = h.sessionOf("s-seam"); + const meta = s?.metadata.snapshotShadow as { turns: number; errors: number; lastClass: string; lastReason?: string } | undefined; + assert.ok(meta, "shadow metadata recorded on the degrade session"); + assert.equal(meta.errors, 0, "degrade is a known cost, not an error"); + assert.equal(meta.lastClass, "degraded"); + assert.equal(meta.lastReason, "seam-too-short"); + }, true); +}); + +/** stake 6 — status/errors: an erroring session drives the aggregate up. */ +test("snapshot shadow: error sessions drive the status aggregate and diagnostics", async () => { + await withHarness(async (h) => { + const history = conversation(); + await turn(h, "s-ok", history.map((m) => ({ ...m }))); + await turn(h, "s-ok", [...history.map((m) => ({ ...m })), { role: "user", content: "TAIL_A follow up question" }]); + // synthesize the error state the classifier would produce (unit-tested + // above): the aggregate/wire layer must surface whatever the engine + // recorded — here we inject to prove the surfacing path. + const s = h.sessionOf("s-ok"); + assert.ok(s); + (listSessions().find((x) => x.meta.label === "s-ok") as unknown as { metadata: Record }).metadata.snapshotShadow = { + turns: 3, + errors: 2, + lastClass: "error", + lastErrors: ["lost-tail:1", "unstable-prefix"], + }; + const st = await (await fetch(h.statusUrl)).json() as { snapshotShadow?: { enabled: boolean; watching: number; errors: number; worst?: { sessionId: string } } }; + assert.equal(st.snapshotShadow?.errors, 2); + assert.ok(typeof st.snapshotShadow?.worst?.sessionId === "string" && st.snapshotShadow.worst.sessionId.length > 0, "worst session surfaced"); + const diag = await (await fetch(h.diagUrl("snapshot-shadow"))).json() as { blob: string }; + assert.match(diag.blob, /lost-tail/); + }, true); +}); diff --git a/website/config-reference/env-only.yaml b/website/config-reference/env-only.yaml index 69125481bb..271e5b9b4a 100644 --- a/website/config-reference/env-only.yaml +++ b/website/config-reference/env-only.yaml @@ -10,6 +10,14 @@ entries: group: envonly desc_en: "Let bili ANSWER dsh compaction summarize calls locally with the folded snapshot instead of refusing (#3733): identity header + kernel-rendered block summaries, zero egress; replay recognized via the #2432 rebase." desc_zh: "让 bili 本地应答 dsh 压缩摘要请求(返回折叠快照而非拒绝,#3733):身份头 + 内核渲染格式的块摘要,零出口流量;重放经 #2432 再基线识别。" + - key: BILI_SNAPSHOT_SHADOW + type: boolean + default: "true (on)" + kind: env-only + audience: user + group: envonly + desc_en: "Snapshot-render shadow observability (#3756 follow-up): compute the outbound snapshot view on every armed turn WITHOUT using it, classify the diff against the legacy outbound, and surface per-session counters in the web panel + the snapshot-shadow diagnostics topic. 0/false/off disables; 1/true/on enables; otherwise the config-file snapshot.shadow boolean applies (default on). The render lane itself stays rollout-gated (BILI_ROLLOUT_SNAPSHOT_RENDER), so the shadow lane never changes outbound bytes - it is the dry-run evidence that flips the rollout later." + desc_zh: "快照渲染影子对账(#3756 后续):每轮已折叠会话都用引擎现算一次出站快照视图但不使用,与 legacy 实际出站比对分类,逐会话计数进 web 面板与 snapshot-shadow 诊断主题。0/false/off 关闭;1/true/on 开启;否则读配置文件 snapshot.shadow 布尔(默认开)。渲染车道本身仍受灰度开关控制(BILI_ROLLOUT_SNAPSHOT_RENDER),影子车道绝不改变出站字节 —— 它是后续翻转灰度的干跑证据。" - key: BILI_CONFIG_FILE type: string default: "unset (XDG config path)" diff --git a/website/config-reference/process.yaml b/website/config-reference/process.yaml index 87de90477f..c1bc97d057 100644 --- a/website/config-reference/process.yaml +++ b/website/config-reference/process.yaml @@ -350,3 +350,11 @@ entries: desc_zh: "提供给原生插件的 fork API 公共快照大小上限。" site_en: "plugin.snapshotCapBytes — fork API snapshot cap (default 100 MiB; 0 disables snapshots)." site_zh: "plugin.snapshotCapBytes —— fork API 快照上限(默认 100 MiB;0 禁用快照)。" + - key: snapshot.shadow + type: boolean + default: "true (on)" + kind: file-only + audience: user + group: process + desc_en: "Snapshot-render shadow observability (#3756 follow-up): with the render lane still rollout-gated, every armed turn computes the would-be snapshot view, classifies the diff against the legacy outbound, and records per-session counters (web panel rows + /__bili/status snapshotShadow aggregate + the snapshot-shadow diagnostics topic). Default ON - it is the fleet-wide dry run whose error rate gates the rollout flip. Env BILI_SNAPSHOT_SHADOW wins. Turn off with false/0/off if you do not want the extra per-turn computation." + desc_zh: "快照渲染影子对账(#3756 后续):渲染车道仍处灰度关闭时,每轮已折叠会话都现算一次快照视图,与 legacy 实际出站比对分类,逐会话记账(web 面板行 + /__bili/status snapshotShadow 汇总 + snapshot-shadow 诊断主题)。默认开 —— 这是全舰队干跑,其错误率决定灰度翻转。环境变量 BILI_SNAPSHOT_SHADOW 优先。不想要每轮额外计算可用 false/0/off 关闭。" From 05e9b1a5db4aa0591372cc75a5ef185619d0dd5e Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 20 Oct 2026 01:22:26 +0800 Subject: [PATCH 2/2] tests: pin BILI_SNAPSHOT_SHADOW=0 in the two golden suites (#3756 follow-up) Goldens pin wire+state bytes for the render/storage shape; the shadow observability blob is orthogonal and covered by its own suite. --- tests/golden-storage-render.test.ts | 6 ++++++ tests/storage-engine-proofs.test.ts | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/tests/golden-storage-render.test.ts b/tests/golden-storage-render.test.ts index 6e02999dde..29458cefc6 100644 --- a/tests/golden-storage-render.test.ts +++ b/tests/golden-storage-render.test.ts @@ -21,6 +21,12 @@ import { driveWire, WIRES } from "./golden-storage-drive.ts"; // these digests by design (its own suite covers it); this suite proves // render/storage fidelity against committed references. process.env.BILI_IMAGE_RESCALE = "0"; +// #3756 follow-up: the shadow observability lane writes a snapshotShadow blob +// into session.metadata on armed turns; goldens pin wire+state bytes for the +// RENDER/STORAGE shape, not observability — keep them free of the new field +// (the shadow lane has its own suite, tests/snapshot-shadow.test.ts). +process.env.BILI_SNAPSHOT_SHADOW = "0"; + const GOLDEN_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "golden", "storage-render"); diff --git a/tests/storage-engine-proofs.test.ts b/tests/storage-engine-proofs.test.ts index f323110c97..97b02837b0 100644 --- a/tests/storage-engine-proofs.test.ts +++ b/tests/storage-engine-proofs.test.ts @@ -52,6 +52,12 @@ process.env.BILI_PERSIST_ZSTD = "0"; // image rescale (#3400) changes those digests by design and is covered by its // own suite (tests/issue3400-image-rescale.test.ts) — keep the two concerns apart. process.env.BILI_IMAGE_RESCALE = "0"; +// #3756 follow-up: the shadow observability lane writes a snapshotShadow blob +// into session.metadata on armed turns; goldens pin wire+state bytes for the +// RENDER/STORAGE shape, not observability — keep them free of the new field +// (the shadow lane has its own suite, tests/snapshot-shadow.test.ts). +process.env.BILI_SNAPSHOT_SHADOW = "0"; + // Same hermeticity contract as the corpus suites: a developer machine with // storage.unified in its real config must not leak a tier into these tests.