Skip to content

[PR] feat: egress block flow/state — block canonical history + checkpoint retirement (#7577) - #7581

Merged
ranxianglei merged 11 commits into
masterfrom
2026-11-23_egress-block-flow-checkpoint-retire
Nov 24, 2026
Merged

ranxianglei merged 11 commits into
masterfrom
2026-11-23_egress-block-flow-checkpoint-retire

Conversation

@ranxianglei

@ranxianglei ranxianglei commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner

这个 PR 干什么

把「块」(压缩块,block)的生命周期变成和「消息视图」(egress_flow/egress_state)平级的一等 op-log 公民,并借此:

  1. 退役 checkpoint:egress-on 会话不再写 fork_base/replica/auto 检查点行,改由点位 fork(四张表拷贝)提供独立子会话;
  2. 瘦身 kstate 列:egress-on 会话的 sessions.kstate_json 不再存 tsStamps/tokenSnapshot/lastPassIds(可从 flow 日志重放派生),legacy 路径字节不变。

背景与设计提案

egress 平面(#7398/#7439,egressPlane 总开关)已经把出站消息视图记成稀疏 op 日志(I 插入 / D 删除 / U 更新),出站内容从日志回放、字节恒定。但块——折叠产生的摘要对象、覆盖范围、superseded/reaped 生命周期——之前只活在内存和 kstate 里,崩溃重启后没有可回放的权威来源。

本 PR 的设计决策(评审记录见 PR 评论,2026-11-24):

  • D1/D2 自包含:两张块表每行携带完整快照 + one/full 原文字节,零内容 CAS 引用,读不依赖 messages 表;
  • D3 kstate sidecar:每个块行捎带 <2KB 的 kstate 残余快照(13 个字段),replay 取水位点最后一个;
  • D4 kstate 列裁剪:见上;加载时对 egress-on 会话从 I 行 msgid+ts 重派生 tsStamps(持久值永远优先);
  • D5 checkpoint 退役:见上;admin POST /__bili/replicas 对 egress-on 父会话走点位 fork(201),非驻留 503,低于高水位 400(点位重建 materializer 是后续项);
  • D6 reap 语义:活块离开集合发终止 U(reaped=true),不删行——历史永远可回放;
  • 双时钟(评审后定稿):消息流表和块表各发各的号(op_seq 各自在表内稠密),块行另带一列 flow_op_seq = 写入那一刻 egress_flow 的 MAX(op_seq),作为跨表对齐指针。
    • 为什么不用共享号池:生产交错序是「消息 op(prepare 时写)→ 块 I 行(SAVE 时写)」,共享号池会让下一条消息跳过块占用的号,flow 表出现空洞,密度校验每次读都炸(E2E 复现过,已按此方案修复,见 fix(egress): block tables get their own op_seq clock);
    • flow_op_seq 只增不减,「指针 ≤ X」的块行恰为前缀,点位 fork 用它对齐。

建表(仅 unified store,从未随版本发布,dev 库 DROP 重建迁移)

CREATE TABLE egress_block_flow (          -- 追加式生命周期日志(B/I/U),自有编号
    session_id TEXT NOT NULL,
    op_seq INTEGER NOT NULL,              -- 块表自己的号池,表内稠密
    flow_op_seq INTEGER NOT NULL DEFAULT 0, -- 指针:写入时刻 egress_flow 的 MAX(op_seq)
    row_type TEXT NOT NULL CHECK (row_type IN ('B','I','U')),
    block_id TEXT,
    payload TEXT NOT NULL,                -- I/U:完整快照 JSON;B:{entries:[{blockId,snapshot}],watermark}
    kstate_json TEXT,                     -- <2KB 残余快照 sidecar
    created_at INTEGER NOT NULL,
    PRIMARY KEY (session_id, op_seq)
);
CREATE INDEX idx_egress_block_flow_block ON egress_block_flow (session_id, block_id);

CREATE TABLE egress_block_state (         -- 读副本:每块最新快照
    session_id TEXT NOT NULL,
    block_id TEXT NOT NULL,
    op_seq INTEGER NOT NULL,
    flow_op_seq INTEGER NOT NULL DEFAULT 0,
    payload TEXT NOT NULL,
    created_at INTEGER NOT NULL,
    PRIMARY KEY (session_id, block_id)
);

快照 shape:{tier, startMsgid, startSeq, endMsgid, endSeq, supersedesBlockId, active, reaped, one, full}。两个已钉死的行为:折叠自己的块坐标是 null(SAVE 时覆盖消息已被同轮 D op 移出 live 视图,内容在 one/full 与 flow 的摘要行里,不丢);保留地板(折叠的 D 批同事务写 B 基点并删基点以下行,低于最新基点的点位 fork 拷不到历史)。

配置:如何开启 / 关闭

无新增配置项,全部挂在既有 egressPlane 总开关下,且以 unified store 为前提:

步骤 配置
1. 前置:统一存储 配置文件 storage.unified: full(或 shadow),或环境变量 BILI_STORAGE_UNIFIED=full
2. 打开 egress 平面(含本 PR 全部行为) 配置文件 rollout.features.egressPlane: true,或环境变量 BILI_ROLLOUT_EGRESS_PLANE=1
关闭 不设/置回 egressPlane: false(BILI_ROLLOUT_EGRESS_PLANE=0)。OFF = 老链路:零行、零新代码路径,字节级等同 feature 之前

块表、点位 fork、kstate 裁剪都只在 egress-on 会话发生;egress-off 会话(含 egress-off 父会话的 fork,拷四张空表)行为不变。迁移纪律:探测式 DDL,新库直接建,老 dev 库缺列则整表 DROP 重建(表未发布过,可丢)。

变更点

  • src/storage/schema.ts:上述 DDL + 探测式迁移;
  • src/storage/egress-block.ts:I/U/B 读写、egressBlockAppend/Compact/Replay(replay 带自编号密度校验)、egressPointFork(wm = flow 时钟;块行按 flow_op_seq <= wm 拷)、diffBlockSet;
  • src/storage/egress-state.ts:flow 号池独占(块表不再参与发号),EgressViewRow/op 带首见墙钟 ts;
  • src/storage/store.ts + src/persist/ingest.ts:ingest 缝上的逐轮块记录器(egress-on 门控),点位 fork 接线,tsStamps 加载派生;
  • src/server/admin.ts:POST /__bili/replicas egress-on 走点位 fork;createReplica/maybeCutForkBaseAsync 对 egress-on 跳过;
  • 文档:docs/egress-block-flow.md + 中文 egress-block-flow.zh-CN.md + 索引与文件地图。

测试

遗留(不阻塞合并)

  1. egressBlockCompact/egressBlockReplay 暂无生产调用方——块日志当前无界增长,压缩接线是后续项;
  2. 点位重建 materializer(低于最新基点的点位 fork)是后续项,admin 端点已按 400 明确拒绝。

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-11-23_egress-block-flow-checkpoint-retire (eaad533)

Latest build — install this exact version

npm install -g billion-context@0.0.11747-pr.7581.847cf74

This exact version is immutable and reproducible. The rolling pr tag tracks the newest test build across all PRs.

Recent builds (commit → version)

commit version build
eaad533 billion-context@0.0.11747-pr.7581.847cf74 build
1e2c6bd billion-context@0.0.11743-pr.7581.37691fb build
770735a billion-context@0.0.11739-pr.7581.1b2b0f8 build
500e74e billion-context@0.0.11738-pr.7581.7f820e0 build
247af1f billion-context@0.0.11722-pr.7581.82e02e7 build
890e26a billion-context@0.0.11699-pr.7581.80415de build
6299764 billion-context@0.0.11648-pr.7581.6080cde build
b2563da billion-context@0.0.11645-pr.7581.3197fbe build
ff13c16 billion-context@0.0.11601-pr.7581.993511d build

Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr7581.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei ranxianglei changed the title feat: egress block flow/state — block canonical history + checkpoint retirement (#7579) [PR] feat: egress block flow/state — block canonical history + checkpoint retirement (#7579) Nov 23, 2026
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

查重: 不重复。本 PR 是块生命周期正史 + checkpoint 退役设计提案(mirror #7579)的实现,无其他 PR 覆盖同一主题。

PR #7581 review — egress block flow/state + checkpoint retirement

Read the full diff (14 files, +951/-3) and the new test suite. CI is green on the pushed head — all test shards (ubuntu/windows × node 22/24) + static-gates pass; the e2e lanes are gated/skipped for this file list. The core block flow/state machinery is clean, well-documented, and the tests pin the contract with real assertions (replay determinism, B-row compaction, reap semantics, point fork, kstate sidecar, corrupt paths).

Concrete findings (priority order):

  1. [CRITICAL — fix before merge] PR body Closes #7579 will auto-close the WRONG GitHub issue. GitHub decision request: extend measured-wire-body fix to truncate + add symmetric calibration/divergence guard (#7578) #7579 is "decision request: extend measured-wire-body fix to truncate + add symmetric calibration/divergence guard ([Bug] Under-reported upstream prompt_tokens + k̂=0.25 freeze blinds preflight/nudge/truncate until 413 egress_window_fuse deadlock #7578)" — an unrelated open p1 decision request. The egress-block design proposal (mirror decision request: extend measured-wire-body fix to truncate + add symmetric calibration/divergence guard (#7578) #7579) has no GitHub counterpart (searched egress_block_flow; only this PR matches). On merge, Closes #7579 closes the truncate decision request. Fix: remove or correct that line in the PR body (the PR title also carries the (#7579) suffix — same collision). Code comments also cite mirror numbers decision request: extend measured-wire-body fix to truncate + add symmetric calibration/divergence guard (#7578) #7579/新提案:egress 流水表成为会话内容唯一权威(存储解耦 + 服务端快照权威) #7439/块生命周期正史 + checkpoint 退役(egress_block_flow / egress_block_state)——#7439 后续项设计提案 #7577 that 404 on GitHub — a pre-existing pattern in master — but the PR-body auto-close is the actionable one.

  2. [MINOR] Fork egress_state rebuild drift. New egressPointFork rebuilds the child's egress_state by replaying the full egress_flow (untrimmed); the old egressFork copied the parent's trimmed egress_state. The child's current VIEW is identical (the B base row resets the replay), so this is not a correctness bug — but the child's egress_state starts untrimmed (larger) until its own compaction. Minor storage/perf drift.

  3. [VERIFY] kstate trim has no restore-path derivation in this PR. For egress-on sessions, ingest.ts finishPlan excludes tsStamps/tokenSnapshot/lastPassIds from the persisted kstate (both the column and the state_fields rows). The design says these are "derivable from flow replay", but neither this PR nor master contains the restore path that derives them. If the egress-on restore path doesn't derive them, they're lost on restart. Gated on egress-on (experimental), so not a blocker — please confirm the derivation path exists or is a tracked follow-up.

  4. [BEHAVIOR CHANGE] Checkpoint retirement for egress-on sessions. maybeCutForkBaseAsync skips egress-on; createReplica throws; admin /__bili/replicas returns 400 for egress-on. There is no replacement admin endpoint for point-fork (it's internal-only via cloneSessionRows). Please confirm this is the intended UX.

Test gaps: the new suite covers the block flow/state primitives only. Not covered: the ingest.ts finishPlan kstate trim, the checkpoint-retirement guards (persist.ts / admin.ts), the fork egress_state-rebuild-drift, and any e2e through recordEgressTurn + ingestSession together.


八问(中文):

  1. 是什么问题: 把块集合提升为 op-log 一等公民——新增 egress_block_flow(追加 I/U/B 行)+ egress_block_state(读副本),与消息视图共享 op_seq 时钟;对 egress-on 会话退役 checkpoint,改用点分叉(4 表拷贝);并为 egress-on 会话裁剪 kstate 列。
  2. 什么原因导致的: 块集合此前只是消息视图的派生物,没有自己的正史;checkpoint 是点快照,无法精确到任意 op_seq。块集合有了追加式正史后,分叉可精确到任意水位,checkpoint 因此冗余。
  3. 影响范围与严重程度: 仅 egress-on 会话(egressPlane 主开关,metadata.egressAuthority===true);legacy 会话字节级不变。功能新增,非缺陷修复;对现有用户无影响(egress-on 是实验特性)。
  4. 怎么修复的: 两张新表 + 共享 op_seq 时钟;块记录器在 ingest 缝做每轮 egress-on 门控,diff 前后块集合 → I/U op + block_state upsert + kstate sidecar;重放 + 点分叉(WHERE op_seq<=wm);checkpoint 三入口对 egress-on 短路/抛错/400;kstate 裁剪在 finishPlan 对 egress-on 排除三字段。
  5. 是否有回归问题: 审了既有行为——(a) 分叉:新路径从完整 flow 重建子 egress_state,当前视图不变(B 基行重置),仅存储/性能漂移,非正确性 bug;(b) kstate 裁剪:egress-on 持久化 kstate 不再含三字段,但本 PR 与 master 均未见恢复路径从 flow 导出——若恢复路径不导出则重启丢失,需确认;(c) checkpoint 退役:egress-on 不能再建 checkpoint/replica,admin 端点 400 且无替代——需确认 UX。高危模式:语义漂移(kstate 裁剪)已点出;阈值/时序/输出格式不涉及。
  6. 是否破坏缓存: 不涉及。不触碰 prompt cache / 重试 / 增量游标 / 去重键。
  7. 是否改了设计方向: 是——块集合从"消息视图派生物"转向"独立 op-log 正史",分叉从"checkpoint 点快照"转向"任意 op_seq 水位的点分叉"。owner D 裁定(D1-D6),方向明确。
  8. 是否引入了新的配置: 不涉及。全部在既有 egressPlane 主开关之下,无新 env/config/默认值。

结论: 核心块 flow/state 机制扎实(代码干净、测试钉契约、CI 绿)。合并前必须修 #1(PR 正文/标题 Closes #7579 会误关无关的 GitHub #7579 truncate 决策请求);#2 为轻微漂移可接受;#3/#4 为 owner 设计层确认项。修掉 #1 后可合。

@ranxianglei
ranxianglei force-pushed the 2026-11-23_egress-block-flow-checkpoint-retire branch from ff13c16 to b2563da Compare November 23, 2026 16:02
@ranxianglei ranxianglei changed the title [PR] feat: egress block flow/state — block canonical history + checkpoint retirement (#7579) [PR] feat: egress block flow/state — block canonical history + checkpoint retirement (#7577) Nov 23, 2026
@ranxianglei

Copy link
Copy Markdown
Owner Author

(ai: sglang-gpu0/qwen3.8-27b)

评审三点修复留档(对应讨论 #7577)

本 PR 在初版之外,针对评审提的三个关注点各追加了一个 commit,均已推送到 head 6299764,CI 全绿(38 success / 14 skip / 0 fail)。

(a) fork-to-now 快路径 — commit 8b62ffb

问题:父会话压实后 egress_state 是一张 B 基行(~8MB / 10w 行)。fork 到当前点位若按真点位逻辑逐行 JS 重放 flow,单事务会把这个大 B 行反复过一遍,慢。

修复:egressBlockFork/点 fork 里加判断——目标点位 wm >= 父高水位(即 fork-to-now)时,四张表直接 SQL INSERT…SELECT 整体直拷;只有真点位(wm 低于高水位)才回放 flow 行重建状态副本。

(b) tsStamps 从 egress 视图派生 — commit 4483e3f

问题:egress-on 会话的 tsStamps/tokenSnapshot/lastPassIds 若继续落 kstate 列,每轮都写、随会话增长;且这些字段本质可由 egress 日志重放推导,落库是冗余。

修复:这三项不再落 kstate 列。加载 egress-on 会话时,store 从 egress I 行重新推导 tsStamps(I 行 msgid 就是内核 raw id,ts 是首见墙钟)。已持久化的值永远优先,推导只补列里被裁剪留下的缺口。初版曾引入一个多余的 rawId 字段 + rawIds map,本版已删除(msgid 本身即 raw id)。

(c) 点 fork 端点 — commit b2563da

问题:checkpoint 退役后,POST /__bili/replicas 对 egress-on 父会话原本直接 400/501,没有替代的快照/fork 入口。

修复:该端点对 egress-on 父会话改走点 fork,返回 201 {ok, pointFork, sessionId, opSeq, restoredFrom},生成一个全新的独立子会话(父永不被改,子是快照而非活别名)。egress-off 父保留原 checkpoint 行为;opSeq 低于高水位的请求诚实 400(需要点位重构物化器,已登记为后续项,见讨论 #7577)。

文档

docs/egress-block-flow.md(中英)+ 索引 + 架构文件地图已同步 (a)/(c) 的实际行为;并把误写的 tracker 引用 #7579 全部更正为 #7577(commit 6299764)。

@ranxianglei ranxianglei left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

结论:先别合并。共享 op_seq 时钟和消息日志已有的"严格连续"校验互相矛盾——egress-on 会话从第一次压缩(fold)之后,出站 op 日志每轮都被判损坏,恢复梯子每轮回退删行,日志永久冻结在 fold 点。这是数据底座级的缺陷,不是边角 bug。

1. 这是啥问题

egress-on 会话只要发生过一次压缩(生成 compression block),从 fold 后第二轮起,每一轮的出站日志(egress_flow/egress_state)读取都抛 op_seq jumps from X to Y;恢复路径每轮回退一步、删掉上一轮刚写入的行,日志永远停在 fold 那一刻。伴随现象:

  • 每轮一条 error 日志("the outbound log did not replay … 1 row(s) after op_seq X were removed")、degraded=true 常态化;
  • 对该会话做 point-fork 只能拿到 fold 之前的状态(fold 之后每轮的记录下一轮就被删了);
  • 重启后 <acp time> 时间戳丢失:shadow 的 tsStamps 重走 egressStateView,抛异常后被 catch 成 null。

2. 根本原因(代码级)

本 PR 让 block 行(egress_block_flow)与消息行(egress_flow)共用一个 op_seq 时钟,但消息日志有一个"op_seq 严格连续"的硬校验,共享时钟必然在它中间打出空洞:

  1. src/storage/egress-state.ts:596-601 — applyOps 断言 row.op_seq === prevSeq + 1,否则抛 EgressStateCorruptError("op_seq jumps from X to Y")。它支撑全部 egress 读(egressStateView/Read/At),是 #7574 特意加的强信号。
  2. 生产写序决定空洞必然出现:fold 轮的 recordEgressTurn 在请求前执行(src/server/prepare-openai.ts:702/960),写完消息 ops(含 B base,设消息 max=M);block recorder 在 save 时才跑(UnifiedStore.ingestSession,src/storage/store.ts:1227,recorder 在 ~1835-1876)→ block I 行占 M+1;下一轮消息 ops 从 nextSeqs(两表 MAX)+1 = M+2 开始 → egress_flow 变成 [..M, M+2],中间空一格。
  3. 本地复现已验证:turn1 消息 I@1、I@2 → block I@3 → turn2 消息 I@4 → egress_flow=[1,2,4];egressStateView/egressStateRead/egressStateAt 全部抛 op_seq jumps from 2 to 4。PR 自带测试没覆盖"消息 ops → block ops → 再消息 ops"这个生产写序,所以全绿。
  4. 稳态机制(src/server/egress-lane-io.ts:193 → src/storage/egress-record.ts:191-235 recoverEgressBase):每轮读抛异常 → 梯子回退到 fold 点(那里仍连续)→ egressStateTruncateAfter 删掉该轮刚写的行(truncated=1)→ 本轮以 degraded 视图继续 → 下一轮同 seq 重写、再被删。死循环。

3. 怎么解决(方向留给作者,此处未动手)

  • 方案 a(最小):把连续性校验放宽为"严格单调递增"(允许空洞)。锚点按 msgid 引用而非 seq,真丢行仍会被 anchor-missing 类错误抓住;需同步更新 tests/issue7574-egress-log-integrity.test.ts:182 对 op_seq jumps from 1 to 3 的断言。
  • 方案 b:两个日志各自计时(放弃 #7577 的对齐收益,改动大)。
  • 方案 c:egress_flow 写 no-op 占位行保持稠密(污染消息日志,不推荐)。
  • 无论哪个方案,都要补一个"生产写序交错"的回归测试:消息 ops → block ops → 消息 ops → 全量读成功 + 恢复梯子不触发。

4. 其他发现(报告,不动手)

  • egressBlockCompact/egressBlockReplay 没有生产调用方:egress_block_flow 的 B 行压缩永不触发,表无界增长;egress_block_state 永久保留 reaped 块行。若属有意留 follow-up,建议在 docs/egress-block-flow.md 写明。
  • recoverEgressBase 的截断(egressStateTruncateAfter,src/storage/store.ts:2280-2289)只截 egress_state/egress_flow,不截 egress_block_flow → 恢复后 block 日志领先消息日志(与主问题同源,共享时钟要整体处理)。
  • PR body "Closes #7577":该号在 issue 和 PR API 下都 404,建议核对。

5. 已直接修的小问题(commit 247af1f0,已推到 PR 分支)

  • admin POST /__bili/replicas 的 egress-on point-fork 高位水位用错了时钟:egressStateMaxSeq 只看 egress_flow,一个落在"消息 max 与共享 max 之间"的 opSeq 会被静默 fork-to-now 而不是 400 拒绝 → 改用 egressBlockMaxSeq(src/server/admin.ts 该 handler 内)。
  • forkEgressSnapshot 的 201 响应 opSeq 同源低估 → 同样改用共享水位(src/persist.ts)。
  • egressBlockAppend/egressBlockCompact:state 副本校验读 + blockNextSeq 原来在写事务外,违反 #7574 立的"next seq 必须事务内读"纪律(src/storage/egress-block.ts)→ 移入事务内。
  • tests/issue7577-fork-endpoint.test.ts 的水位 oracle 同步到共享时钟(fixture 无 block 行,值不变,语义正确)。
  • 相关 20 个测试(egress-block / issue7577-fork-endpoint / issue7577-kstate-derive / storage-replicas)本地全绿。

6. CI 红项归因(run 45307407370,4 个失败 job 均非本 PR 回归)

  • #6770 compaction-coverage-text 断言失败(expected preset-dsh-go-companion×2,got unnamed-entry×2):在 merge base a59a638(master 现状)本地复现,ubuntu22/24 + windows22 三个 shard 挂的是同一处 → master 本来就红。
  • #1365 dsh-native:listen EADDRINUSE 127.0.0.1:42819,runner 端口占用噪音。
  • e2e-anthropic:Unexpected end of JSON input(ubuntu24 shard);PR 分支本地 11/11 通过。
  • 其余 job(build/tsc/lint/其余 shard/windows)全绿。

7. 已验证无问题的部分

  • ts 字段:recordEgressTurn 在 I 行盖章;U 行经对象 spread 保留(egressReplay/applyOps 两处);B base 行带 ts。
  • kstate sidecar 有界:recorder 读到的是 finishPlan 已按 KSTATE_TRIM_FIELDS 裁剪后的 kstateJson(src/storage/ingest.ts:587-599),652KB 的 lastPassIds 进不了 sidecar。
  • fork-to-now 快路径(四表 SQL 拷贝)与 true point fork(flow 拷贝 + state 重放重建)逻辑正确;egress-off 父会话得到四个空表拷贝,等价旧 egressForkSession 的 no-op。
  • kstate trim 对 legacy 路径字节级不变;D6 的 live→gone 终态 U reaped=true 由 ingest 的全量 state.blocks diff 正确得出。

8. 能否合并

不能(在 §1 的设计级缺陷修掉之前)。建议:定下修复方向(倾向方案 a)+ 补交错回归测试,重新过 CI 后再合。

URL: #7581

@ranxianglei

Copy link
Copy Markdown
Owner Author

更新(2026-11-24 12:55):阻断项已修复,已推送到本分支

上一条评论指出的阻断问题(共享 op_seq 号池破坏 egress_flow 稠密不变量 → 每次 egress 读抛错、会话日志从第一次折叠起冻结)已按裁定修复:双时钟。

改动(commit 770735a3)

  1. egress_flow 零改动——独占号池,PR #6785 review conclusions: 10 issues (e.g., 502 on large requests with handshake headers, data loss on rollback to the | PR #6785 review 结论:大请求带握手头会 502、回退旧版会丢数据等 10 项问题及修复计划 #7574 的密度校验原样保留,生产交错(消息行→SAVE 时块行→消息行)下现在真正成立;
  2. 块表自己发号——egress_block_flow.op_seq 从 MAX(egress_block_flow)+1 发出、表内稠密;egressBlockReplay 增加块表自身的密度自检(块日志是纯追加的,空洞即缺行,必报);
  3. 指针列对齐两表——每条块行(flow 与 state 副本)新增 flow_op_seq = 写入时刻 flow 时钟的 MAX(op_seq);水位只增不减,flow_op_seq <= X 构成前缀。点位 fork 在 flow 水位 X:拷 op_seq <= X 的消息行 + flow_op_seq <= X 的块行,两表在该时刻对齐;
  4. 参考时钟统一为 flow 时钟——管理员端点、forkEgressSnapshot、forkSessionUnified 的水位都用 egressStateMaxSeq;egressBlockMaxSeq 退化为块表自身位置的诊断值;
  5. schema 探针——已建过旧形状块表的 dev 库走 DROP + 重建(未发版的表,沿用既有先例);
  6. 回归测试——新增"消息→块→消息"交错用例:断言 flow 保持稠密且 egressStateView/egressStateAt 可读,即原 bug 的最小复现,现已翻绿。点位 fork 用例按指针语义重写;fork-to-now 仍为四表字节一致;
  7. 文档(英/中)重写为双时钟,并记录了否掉共享时钟的原因。

验证

遗留(不阻断,follow-up)

  • egressBlockCompact / egressBlockReplay 目前无生产调用方 → 块日志只增不减,长期会话无界增长,需要接一个压缩调用点;
  • PR 正文 Closes #7577 引用的 issue 不存在(404),建议改掉或补 issue。

结论从"不能合并"更新为:修复已就位,待 CI 绿后可由人合并(按惯例合并留给维护者)。

@ranxianglei

Copy link
Copy Markdown
Owner Author

补充一个 E2E 测试(commit 8395c3b1):tests/issue7577-block-flow-e2e.test.ts。

之前评审指出单测从未复现过生产交错序(消息 op → 块 I → 消息 op),这个测试把真正的内核压缩(applyRanges + processTurn,和 compress 工具同一套机制,80 条消息折掉 31 条)在隔离的生产形 DB 上跑了一遍完整的 recordEgressTurn(prepare 时)+ store.writeNow(SAVE 时,块记录器在 ingestSession 里),然后重启 + fork。结论:

双时钟机制在真实压缩下完全正确:

  • flow 表原样稠密(原始行 op_seq 严格 +1),折叠后、重启后视图都可读(原来卡死的位置不卡了);
  • 块行自编号(op 1)+ flow_op_seq 指针正好指向折叠自己写的那个 B 基点;
  • 重启后视图字节相等、tsStamps 从日志派生、块表 replay 回活块集;
  • fork-to-now 四张表字节相等;点位 fork 在基点位上拿到"折叠后 51 行 + 块",而 fork-to-now 是 52 行——点位语义在保留范围内是真的。

测试还顺带钉死了两个设计如此的行为(之前文档没写明白,现在测试里有注释):

  1. 折叠自己的块行坐标是 null(startMsgid/endMsgid):SAVE 时该折叠覆盖的 31 条消息已经被同一轮的 D op 从 live 视图删掉,snapEgressPinLiveIds 按 live 视图解析坐标,解析不到就诚实降 null。内容不丢——one/full 存覆盖原文,摘要文本在 flow 里(这正是设计的分工)。
  2. 保留地板:折叠的 D 批在同一事务里写 B 基点并删掉基点以下所有行,所以低于最新基点的点位 fork 拷不到任何历史(admin 端点对这种点位回 400,"point-reconstruction materializer (follow-up)"就是给这个用的)。E2E 把这个现状契约钉住了:低于基点 → 零拷贝,基点位上 → 折叠后视图。

没有发现新的代码 bug,核心套件 57/57 + E2E 稳定通过。

ci-check and others added 10 commits November 24, 2026 13:16
…retirement (#7579)

Adds two new tables (egress_block_flow, egress_block_state) that make the
block set a first-class op-log citizen alongside the message view
(egress_flow/egress_state). Retires checkpoints (fork_base/replica/auto)
for egress-on sessions in favor of point-fork (4-table copy). Trims the
kstate column for egress-on sessions (tsStamps/tokenSnapshot/lastPassIds
derivable from flow replay).

- DDL: egress_block_flow (append-only I/U/B rows) + egress_block_state
  (read replica, latest snapshot per block). Shared op_seq clock with
  egress_flow.
- ts: EgressViewRow / InsertOp / B-entries carry first-observed wall
  clock (epoch ms), stamped at recordEgressTurn.
- Block recorder: per-turn egress-on gate at the ingest seam; diff prev
  block set → I/U ops + block_state upsert + kstate sidecar.
- Replay + point fork: egressBlockReplay / egressPointFork (4-table copy
  WHERE op_seq <= wm; state replicas rebuilt by flow replay).
- Checkpoint stop: maybeCutForkBaseAsync / createReplica skip egress-on;
  admin /__bili/replicas returns 400.
- kstate trim: tsStamps/tokenSnapshot/lastPassIds excluded from
  sessions.kstate_json for egress-on sessions (legacy byte-identical).
- Tests: replay determinism, point fork, kstate sidecar, B-row
  compaction, reap semantics, corrupt paths.
- Docs: bilingual egress-block-flow.md + index entries + architecture
  file map.

Closes #7579
The point fork rebuilt both STATE replicas with a JS row-by-row replay of
the flow tables. At wm = the parent's high water (the only call site today),
the parent's STATE tables ARE already the correct child state (egress_state
compacted as base + window, block state one row per live block), so the replay
materialized the child's egress_state as the full uncompacted flow (every
historical B base row is a whole-view snapshot — ~8MB at 100k messages),
making the fork O(total history) and every later turn's prev-read a
full-history JS replay until the child's first fold.

The fast path copies all four tables straight by SQL when wm covers the
parent's shared high water; only a true point fork (wm < high water) replays.
The child still inherits the shared op clock verbatim.
egress-on sessions trim tsStamps on write (ingest.ts KSTATE_TRIM_FIELDS keeps
the kstate column bounded), so a restarted session loaded a missing stamp map
and the kernel re-rendered <acp time=> attributes as honest NULL. The I row's
msgid IS the kernel raw message id and its ts is the first-observed wall clock,
so the stamp map is derivable from the live egress view — no extra column.

store.egressTsStamps reads the live view and returns the msgid→ts map (null for
egress-off sessions and corrupt logs — it never throws into the load path);
shadow.viewFor re-derives it only when the persisted value is absent, so an
older build that still persists tsStamps keeps its value. The async (MySQL) leg
is untouched: the egress plane is the SQLite lane only.
An egress-on session has no checkpoints to snapshot/restore — its
content authority is the egress op-log. The admin replicas endpoint
therefore routes egress-on sessions to a point-fork instead of the
checkpoint path:

- SessionStore.forkEgressSnapshot(sessionId, childId?): deep-copies a
  resident-or-loadable egress-on parent into a fresh child and persists
  it via the proven fork machinery (cloneSessionRows + the four egress
  op-log tables at the shared high water). The child is an independent
  snapshot — mutating + re-persisting the parent afterwards does not
  reach it. Fork-to-now only: an earlier op_seq would pair
  content-at-X with kernel-state-at-now (the unified rows exist only at
  now), which needs the point-reconstruction materializer (follow-up),
  so a below-high-water opSeq is rejected with a clear 400.
- POST /__bili/replicas: egress-on parents return 201 {ok, pointFork,
  sessionId, opSeq, restoredFrom}; egress-off parents keep the
  checkpoint behavior; non-resident egress-on sessions get a 503 telling
  the client to load the session first.

tests/issue7577-fork-endpoint.test.ts covers the primitive end to end:
content byte-equality, kernel-state snapshot independence, and both
rejection directions (#3617).
The original slice referenced #7579 in code comments and docs, but the
block-flow design discussion is #7577 (the D-rulings live there); #7579
is an unrelated open issue. Corrected every reference.

Also updated the egress-block-flow doc (EN + zh) to match what (a) and
(c) actually do:
- fork-to-now copies all four tables directly (SQL), a true point fork
  replays the flow rows to rebuild the state replicas;
- POST /__bili/replicas takes the point-fork path for an egress-on parent
  (201 {ok, pointFork, ...}) instead of returning 400;
- on load, tsStamps is re-derived from the egress view for egress-on
  sessions whose trimmed column has no value (persisted value always wins).
…ons (#7577)

The D5 guard only fired when the caller passed the resident session
(opts.resident && ...), but the admin endpoint passes `resident` only
when the session is already loaded — a NON-resident egress-on session
bypassed the guard and createReplica wrote a checkpoint row for it,
violating the invariant the guard exists for. The endpoint's 503
mapping for the guard's error was dead code, and the commit-(c) intent
("non-resident egress-on sessions get a 503 telling the client to load
the session first") was not delivered.

Guard on the persisted record's metadata instead (the resident build
and the unified view both carry it): the same error now fires for
resident AND non-resident egress-on sessions, making the existing 503
"load the session first" mapping reachable as intended.

Behavior change (intended, per commit c): POST /__bili/replicas on a
NON-resident egress-on session was silently creating a checkpoint row;
it now returns 503 with "load the session first, then POST again".

Regression test: non-resident egress-on → createReplica rejects with
"use the point-fork path" and no checkpoint row is created;
non-resident egress-off still checkpoints (both directions #3617).
…mputed by the kernel render pass, not derived from the flow replay (#7577)
…k writes read inside the transaction (#7577)

Review follow-ups (small, mechanical — the shared-clock design question is
reported separately and NOT changed here):

- admin POST /__bili/replicas: the egress-on point-fork high-water check read
  egressStateMaxSeq (egress_flow only). A fold turn writes block rows AFTER
  the message rows of the same turn, so an opSeq between the message max and
  the shared max was silently forked to now instead of rejected 400. Now
  egressBlockMaxSeq (MAX over egress_flow + egress_block_flow).
- forkEgressSnapshot: the 201 response's opSeq had the same message-only
  under-report. Now the shared high water (child's true clock).
- egressBlockAppend / egressBlockCompact: the state-replica validation read
  and blockNextSeq ran OUTSIDE the write transaction, breaking the #7574
  discipline the message log established (next seq must be read inside the
  append transaction). Moved inside.
- issue7577-fork-endpoint test oracle: parentHighWater now egressBlockMaxSeq
  (identical value — the fixture parent has no blocks — but the oracle now
  states the intended semantics).
…pointer to the flow clock (#7577)

The shared-clock design broke egress_flow's density invariant: a fold's
block rows land at SAVE time (after the same turn's message rows), so the
next message append starts two op_seqs past the last flow row and
applyOps' op_seq === prevSeq + 1 check throws on every egress read — the
session log is frozen from the first fold, and walk-back recovery
truncates each turn's own row. CI never saw it because the tests never
reproduce the production write order (message ops, then block ops, then
message ops).

Fix (owner ruling): dual clocks.

- egress_flow keeps its exclusive number pool; the #7574 density check
  is untouched and now actually holds in production.
- egress_block_flow numbers itself (MAX(egress_block_flow) + 1, dense
  within its own table); egressBlockReplay gains the matching density
  check (the block log is append-only, so a gap is a missing row).
- every block row (flow and state replica) carries flow_op_seq = the
  flow clock's MAX(op_seq) at write time. The watermark never
  decreases, so flow_op_seq <= X is a prefix: a point fork at flow
  watermark X copies flow rows with op_seq <= X and block rows with
  flow_op_seq <= X, aligning the two clocks at that moment.
- the reference clock for fork water marks (admin endpoint,
  forkEgressSnapshot, forkSessionUnified) is the flow clock
  (egressStateMaxSeq); egressBlockMaxSeq is a diagnostic of the block
  table's own position only.
- schema probe: a dev DB that already created the old-shape block
  tables is dropped + recreated (never-shipped tables, same
  DROP-recreate precedent).

Tests: the interleave regression (message -> block -> message) now
asserts the flow stays dense and readable — the minimal repro of the
review-critical bug, green. Point-fork tests rewritten for the pointer
semantics; fork-to-now stays byte-identical over all four tables.
Docs (en/zh) rewritten for the dual clocks.
Drives a REAL kernel fold (applyRanges + processTurn, the same machinery
the compress tool uses) through the production seams — recordEgressTurn at
prepare, store.writeNow (block recorder inside ingestSession) at save — on
an isolated SessionStore DB, then restarts and forks. The interleaving the
unit tests never reproduced: message ops, block I, more message ops.

Pinned:
- egress_flow stays DENSE (raw-row op_seq strictly +1) across the
  interleaving; egressStateView/At never throw at the original freeze
  point or after a restart;
- the block row's dual clocks: own op 1, flow_op_seq pointer == the fold's
  own compaction-base point;
- the fold's own block coordinates are honestly NULL (covered rows left
  the live view in the same turn) while one/full keep the covered
  originals and the summary text lives in the flow — the designed split;
- fork-to-now copies all four tables byte-equal;
- the retention floor: the fold's D batch writes a B base and deletes the
  rows below it IN the same transaction, so a point fork below the base
  copies nothing (admin.ts documents this: 400 until the point-
  reconstruction materializer lands); a point fork AT the base watermark
  yields the folded view plus the block while fork-to-now has one more row.

57/57 on the egress/storage core suite.
@ranxianglei
ranxianglei force-pushed the 2026-11-23_egress-block-flow-checkpoint-retire branch from 8395c3b to 1e2c6bd Compare November 24, 2026 05:17
…ates typecheck)

The lazy vd() closure assigned dbv inside a nested function, so TS kept the
null narrowing at the finally-close and rejected dbv?.close() with
TS2339 (Property 'close' does not exist on type 'never') — red static-gates
on both legs. index.db exists once the unified store is open, so the handle
opens straight-line after waitForReplicas; behavior unchanged (same handle,
same lazy-open point in practice, all 12 call sites identical).
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

查重:本轮是本 PR 评审的延续(首轮已查重,无重复),核实对象为双时钟修复(rebase 后 d1a6bd82e60,即原 770735a3)与新增 E2E 测试(1e2c6bd),并处理了 CI 红。

双时钟修复核实(逐条过 diff)

  1. egress_flow 零改动,PR #6785 review conclusions: 10 issues (e.g., 502 on large requests with handshake headers, data loss on rollback to the | PR #6785 review 结论:大请求带握手头会 502、回退旧版会丢数据等 10 项问题及修复计划 #7574 密度校验原样保留;
  2. 块表自编号 MAX(egress_block_flow)+1 表内稠密,egressBlockReplay 带密度自检(纯追加表空洞即缺行,必报);
  3. 每条块行(flow 与 state 副本)带 flow_op_seq = 写入时刻 flow 时钟 MAX,水位只增不减,flow_op_seq <= X 构成前缀——点位 fork 在 flow 水位 X 两表对齐,语义成立;
  4. 参考时钟统一为 flow 时钟(admin 端点 / forkEgressSnapshot / forkSessionUnified),egressBlockMaxSeq 退化为诊断值——全仓 grep 确认无残留以它做水位消费的调用点;
  5. schema 探针 DROP + 重建旧形状 dev 表(未发版表,沿用既有先例);
  6. rebase 干净:双时钟内容与 rebase 前逐字节一致,唯一 delta 是 rebase 带入的无关 master 修复(block-archive 提交顺序)。

测试与回归测试有效性

冲突:origin/master 已是当前 head 的祖先——floor 14 的脏冲突态已被作者的 rebase 清掉。

CI 修复(本轮)

head 1e2c6bd 的 static-gates 红(ubuntu 24 + windows 22 两腿)= 本 PR 自己的问题,非继承:新增 E2E 测试有 typecheck 错误——tests/issue7577-block-flow-e2e.test.ts:275 TS2339(懒加载 vd() 闭包在嵌套函数内给 dbv 赋值,TS 保持 null 收窄,finally 的 dbv?.close() 落到 never 分支)。本地复现后按几行级小修修掉:验证句柄改为 waitForReplicas 成功后直开(index.db 此时已存在),12 处调用点不变,行为不变。本地 typecheck 干净 + 67 项定向 + E2E 全绿。已推 final head eaad5339844,等 CI 重跑。

遗留(不阻断,作者已列出)

  1. egressBlockCompact / egressBlockReplay 无生产调用方 → 块日志只增不减,长期会话无界增长,需要接一个压缩调用点(follow-up);
  2. PR 正文 Closes #7577 引用 404(块生命周期正史 + checkpoint 退役(egress_block_flow / egress_block_state)——#7439 后续项设计提案 #7577 是设计讨论的镜像号,不是 GitHub issue)——建议改 PR 正文或补 issue。

八问

  1. 是什么问题:共享 op_seq 号池破坏 egress_flow 稠密不变量——块行在 SAVE 时消费 flow 号,第一次折叠后每次 egress 读都抛错,会话日志冻结(首轮评审指出的阻断项)。
  2. 什么原因导致的:块表与 flow 表共用一个号池,但生产写入顺序是交错的(消息行 → SAVE 时块行 → 消息行),flow 表的密度校验 op_seq === prevSeq + 1 必然被打破;单测从未复现这个交错顺序,所以 CI 抓不到。
  3. 影响范围与严重程度:egress-on 会话(egressPlane 开关下)——会话日志从第一次折叠起冻结、walk-back 恢复截断当前轮行,p1 级缺陷;但表未发版(dev-only),无生产用户影响。
  4. 怎么修复的:双时钟(owner 裁定)——egress_flow 独占号池;块表自编号 + 密度自检;每条块行带 flow_op_seq 指针,点位 fork 用指针对齐两表;参考时钟统一为 flow 时钟。
  5. 是否有回归问题:逐项审过——PR #6785 review conclusions: 10 issues (e.g., 502 on large requests with handshake headers, data loss on rollback to the | PR #6785 review 结论:大请求带握手头会 502、回退旧版会丢数据等 10 项问题及修复计划 #7574 完整性/恢复/回滚套件全绿(密度校验未动,现在生产交错下真正成立);点位 fork 水位语义从「共享时钟」变为「flow 时钟 + 指针对齐」(PR 已披露,表未发版);admin 端点 highWater 从共享 MAX 变为 flow MAX(同上,无外部影响);fork-to-now 四表字节一致有测试钉住;schema 探针 DROP 重建旧形状 dev 库(未发版表,先例)。未发现无意回归。
  6. 是否破坏缓存:不涉及——存储/oplog 层,非提示缓存;egress 水位只增不减,语义未变。
  7. 是否改了设计方向:没有——是对本 PR 首版共享时钟设计的修正(owner 裁定),「块集作为一等 oplog 公民」的方向不变。
  8. 是否引入新配置:不涉及——全部在既有 egressPlane 总开关之下。

结论

修复已就位,CI 红(static-gates typecheck)已修并推送(eaad5339844)。CI 绿后可由人合并(按惯例合并留给维护者)。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

CI 状态更新:final head eaad5339844 全绿——16 success / 14 skipped / 0 failure(static-gates 两腿 + 11 个 test 分片全过,其余为按 scope 跳过的 e2e 车道)。mergeable_state: blocked 是分支保护(需人工 review/批准),不是红 check。

CI 绿,可由人合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

本次唤醒报告的失败是陈旧事件:所报 head 247af1f07b 在分支上不存在,所引 run 45317161480 早于当前 head。已 live 复核——分支 head 仍为 eaad5339844(我上轮推的 final head),镜像缓存显示 16 success / 14 skipped / 0 failure,全绿。无需任何操作,CI 绿,可由人合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

本次唤醒报告的「dirty 冲突」是陈旧事件,已 live 复核:分支 head eaad5339844 与 master head fc7ddee4f95 的 merge-base 就是 master head 本身,即分支已包含 master 全部提交(master..branch 为空),不存在冲突。镜像缓存 mergeable 为 blocked(分支保护/待人工 review),不是 dirty;check 矩阵 16 success / 14 skipped / 0 failure,全绿。无需 rebase,CI 绿,可由人合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

本次唤醒报告的 static-gates 红在旧 head 1e2c6bdde9(run 45332234344),已被我上轮推的 eaad5339844 修掉(typecheck TS2339,验证句柄改直开)。live 复核:分支 head 现为 eaad5339844,check 矩阵 16 success / 14 skipped / 0 failure,全绿。属陈旧事件,无需操作。

@ranxianglei
ranxianglei merged commit 64516a4 into master Nov 24, 2026
52 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.1315-master.64516a4 (rolling master tag).

npm install -g billion-context@0.0.1315-master.64516a4  # this exact build
npm install -g billion-context@master  # always the newest merged build

npm view billion-context@master prints the current version at any time.

ranxianglei added a commit that referenced this pull request Nov 24, 2026
…e rmSync, and never let a cleanup failure fail the test

CI red (windows-latest 22/3): all six E2E tests died with
EBUSY on unlink of index.db in closeStore — Windows releases a
SQLite handle asynchronously, so rmSync raced it (and the test's
own read-only verification handle was never closed at all).

The #7581 E2E precedent simply leaves the tmpdir; this version
closes the handle, then makes the rm best-effort: cleanup is
hygiene, a failure to clean must not turn a passing test red.
ranxianglei added a commit that referenced this pull request Nov 24, 2026
…e rmSync, and never let a cleanup failure fail the test

CI red (windows-latest 22/3): all six E2E tests died with
EBUSY on unlink of index.db in closeStore — Windows releases a
SQLite handle asynchronously, so rmSync raced it (and the test's
own read-only verification handle was never closed at all).

The #7581 E2E precedent simply leaves the tmpdir; this version
closes the handle, then makes the rm best-effort: cleanup is
hygiene, a failure to clean must not turn a passing test red.
ranxianglei added a commit that referenced this pull request Nov 24, 2026
…s docs, storage page refresh, KDD #24

- rollout: egressPlane percent 0 -> 100 (GA; opt-out kept per #5469 precedent)
- tests: 5 sites relying on 'unset = off' now set '0' explicitly; egress-record direction test rewritten to 'GA default ON, explicit 0 closes'
- docs/egress-plane.{md,zh-CN.md}: one-stop egress doc (lineage #7439->#7581->#7617, dual clocks, identity consolidation, flag dependency, on/off resolution order, runbook, timeline)
- docs/deprecations.{md,zh-CN.md}: retirement register (l1 placeholder, conversations, D-lane triggers, msgid switch removals, DROP batch)
- docs/architecture/storage{,.zh-CN}.md refresh; AGENTS.md + design-decisions.md KDD #24; docs index x2
- CHANGELOG + generated config docs
ranxianglei pushed a commit to mariopasquali/billion-context that referenced this pull request Nov 25, 2026
…ranxianglei#7678 wal-reclaim-passive (walJournalSizeLimitBytes default 0, ranxianglei#7674) + ranxianglei#7617 identity-tables-consolidate + ranxianglei#7581 egress block-flow checkpoint retire + ranxianglei#7659 eg-GA docs wrapup + ranxianglei#7671 degenerate-retry + ranxianglei#7676 megaturn-bridge + ranxianglei#7677 doom-prompt-mass + ranxianglei#7632 pure-echo latch + dsh batch (ranxianglei#7161/ranxianglei#7159/ranxianglei#7158/ranxianglei#7129/ranxianglei#7127)

Only manual conflict: docs/configuration{,.zh-CN}.md env table — union of intent,
original line order: master's walJournalSizeLimitBytes row (default 0, ranxianglei#7674)
+ PR's archiveAfterDays row (with the bili storage migrate ranxianglei#5599 clause).
All code (src/persist.ts, src/storage/shadow.ts, src/storage/store.ts,
tests/storage-unified.test.ts) auto-merged; local typecheck clean and the
targeted storage suites (storage-unified/-ccr/-state-fields/
-batched-verification) pass 38/38 on the merged tree.

(ranxianglei#6773)
XcluEzy7 added a commit to Nebuless/billion-context that referenced this pull request Nov 30, 2026
* docs(egress): correct tracker ref #7579→#7577; document (a)/(c) behavior

The original slice referenced #7579 in code comments and docs, but the
block-flow design discussion is #7577 (the D-rulings live there); #7579
is an unrelated open issue. Corrected every reference.

Also updated the egress-block-flow doc (EN + zh) to match what (a) and
(c) actually do:
- fork-to-now copies all four tables directly (SQL), a true point fork
  replays the flow rows to rebuild the state replicas;
- POST /__bili/replicas takes the point-fork path for an egress-on parent
  (201 {ok, pointFork, ...}) instead of returning 400;
- on load, tsStamps is re-derived from the egress view for egress-on
  sessions whose trimmed column has no value (persisted value always wins).

* fix(egress): guard createReplica against NON-resident egress-on sessions (#7577)

The D5 guard only fired when the caller passed the resident session
(opts.resident && ...), but the admin endpoint passes `resident` only
when the session is already loaded — a NON-resident egress-on session
bypassed the guard and createReplica wrote a checkpoint row for it,
violating the invariant the guard exists for. The endpoint's 503
mapping for the guard's error was dead code, and the commit-(c) intent
("non-resident egress-on sessions get a 503 telling the client to load
the session first") was not delivered.

Guard on the persisted record's metadata instead (the resident build
and the unified view both carry it): the same error now fires for
resident AND non-resident egress-on sessions, making the existing 503
"load the session first" mapping reachable as intended.

Behavior change (intended, per commit c): POST /__bili/replicas on a
NON-resident egress-on session was silently creating a checkpoint row;
it now returns 503 with "load the session first, then POST again".

Regression test: non-resident egress-on → createReplica rejects with
"use the point-fork path" and no checkpoint row is created;
non-resident egress-off still checkpoints (both directions #3617).

* docs(egress): correct the kstate-trim comment — tokenSnapshot is recomputed by the kernel render pass, not derived from the flow replay (#7577)

* fix(egress): point-fork high water uses the shared op_seq clock; block writes read inside the transaction (#7577)

Review follow-ups (small, mechanical — the shared-clock design question is
reported separately and NOT changed here):

- admin POST /__bili/replicas: the egress-on point-fork high-water check read
  egressStateMaxSeq (egress_flow only). A fold turn writes block rows AFTER
  the message rows of the same turn, so an opSeq between the message max and
  the shared max was silently forked to now instead of rejected 400. Now
  egressBlockMaxSeq (MAX over egress_flow + egress_block_flow).
- forkEgressSnapshot: the 201 response's opSeq had the same message-only
  under-report. Now the shared high water (child's true clock).
- egressBlockAppend / egressBlockCompact: the state-replica validation read
  and blockNextSeq ran OUTSIDE the write transaction, breaking the #7574
  discipline the message log established (next seq must be read inside the
  append transaction). Moved inside.
- issue7577-fork-endpoint test oracle: parentHighWater now egressBlockMaxSeq
  (identical value — the fixture parent has no blocks — but the oracle now
  states the intended semantics).

* fix(egress): block tables get their own op_seq clock + a flow_op_seq pointer to the flow clock (#7577)

The shared-clock design broke egress_flow's density invariant: a fold's
block rows land at SAVE time (after the same turn's message rows), so the
next message append starts two op_seqs past the last flow row and
applyOps' op_seq === prevSeq + 1 check throws on every egress read — the
session log is frozen from the first fold, and walk-back recovery
truncates each turn's own row. CI never saw it because the tests never
reproduce the production write order (message ops, then block ops, then
message ops).

Fix (owner ruling): dual clocks.

- egress_flow keeps its exclusive number pool; the #7574 density check
  is untouched and now actually holds in production.
- egress_block_flow numbers itself (MAX(egress_block_flow) + 1, dense
  within its own table); egressBlockReplay gains the matching density
  check (the block log is append-only, so a gap is a missing row).
- every block row (flow and state replica) carries flow_op_seq = the
  flow clock's MAX(op_seq) at write time. The watermark never
  decreases, so flow_op_seq <= X is a prefix: a point fork at flow
  watermark X copies flow rows with op_seq <= X and block rows with
  flow_op_seq <= X, aligning the two clocks at that moment.
- the reference clock for fork water marks (admin endpoint,
  forkEgressSnapshot, forkSessionUnified) is the flow clock
  (egressStateMaxSeq); egressBlockMaxSeq is a diagnostic of the block
  table's own position only.
- schema probe: a dev DB that already created the old-shape block
  tables is dropped + recreated (never-shipped tables, same
  DROP-recreate precedent).

Tests: the interleave regression (message -> block -> message) now
asserts the flow stays dense and readable — the minimal repro of the
review-critical bug, green. Point-fork tests rewritten for the pointer
semantics; fork-to-now stays byte-identical over all four tables.
Docs (en/zh) rewritten for the dual clocks.

* test(#7577): dual-clock E2E — a real fold on an isolated production DB

Drives a REAL kernel fold (applyRanges + processTurn, the same machinery
the compress tool uses) through the production seams — recordEgressTurn at
prepare, store.writeNow (block recorder inside ingestSession) at save — on
an isolated SessionStore DB, then restarts and forks. The interleaving the
unit tests never reproduced: message ops, block I, more message ops.

Pinned:
- egress_flow stays DENSE (raw-row op_seq strictly +1) across the
  interleaving; egressStateView/At never throw at the original freeze
  point or after a restart;
- the block row's dual clocks: own op 1, flow_op_seq pointer == the fold's
  own compaction-base point;
- the fold's own block coordinates are honestly NULL (covered rows left
  the live view in the same turn) while one/full keep the covered
  originals and the summary text lives in the flow — the designed split;
- fork-to-now copies all four tables byte-equal;
- the retention floor: the fold's D batch writes a B base and deletes the
  rows below it IN the same transaction, so a point fork below the base
  copies nothing (admin.ts documents this: 400 until the point-
  reconstruction materializer lands); a point fork AT the base watermark
  yields the folded view plus the block while fork-to-now has one more row.

57/57 on the egress/storage core suite.

* test(#7577): open the E2E verification handle straight-line (static-gates typecheck)

The lazy vd() closure assigned dbv inside a nested function, so TS kept the
null narrowing at the finally-close and rejected dbv?.close() with
TS2339 (Property 'close' does not exist on type 'never') — red static-gates
on both legs. index.db exists once the unified store is open, so the handle
opens straight-line after waitForReplicas; behavior unchanged (same handle,
same lazy-open point in practice, all 12 call sites identical).

* 身份表收拢:egress-on 退役 l1_world/conversations 写入,R3 latch 收进 sessions (discussions/7591)

- S1 sessions 表加 r3_latched_at 列(SQLite probe-first + MySQL 同构,无版本 bump)
- S2 R3 breaker latch 改写 sessions 行(最小 upsert,无占位行),l1 只读回退
- S3 egress-on 会话 stage-0 无状态化:echo/anchor 重放对 op log,不读写 l1;
  位置基准取 MAX(log_seq)(review L1)
- S4 egress-on 的 convBound 由内存 metadata.pluginAgent 派生(lane 传给 runStage0),
  不再查 conversations 行;legacy 保持 SQL sticky 语义
- S5 GC 新鲜度 egress 感知(max(updated_at, 最近 op log 行)),egress-on 排除归档
- review 二轮:M1 双载体 unlatch 无条件清两个载体;L2 arm 轮窗口文档化;
  L3 convBound 翻转集成测试;死代码 snapR3LatchWrite 标 @deprecated

新增 tests/identity-tables-consolidate.test.ts(10 测试);
issue5874-2x2-p3 M3.2 改契约 + legacy guard。egress-off 会话三表写入字节不变。

* fix(tests): CI 两红修复 — egress-on 测试补 egressPlane 旗标 + text-safe 家族门放行数组切片

CI(0564284d)两个失败都是本 PR 引入的测试层问题,非产品代码:

1. S3 egress-on stage-0 测试 'anchor' !== 'echo':master #7583 给
   snapPinLiveIds 加了 featureEnabled('egressPlane') 门 — 旗标未开时回退
   messages ledger(新 egress-on 会话为空)→ 恒 anchor。测试需强制
   BILI_ROLLOUT_EGRESS_PLANE=1 才能确定性走 op-log 无状态分支。
   (此前该旗标只在工作树、误把加旗标前的 commit 推上去了。)

2. text-safe 家族门(#816/#1615)报 src/storage/store.ts 的
   incoming.slice(-64) — 这是 msgid 字符串数组的数组切片(码元安全),
   非字符串切片。按既有约定加入 allowlist(数组接收方,带 #7591 注释)。

本地:text-safe 18/18、identity-consolidate 10/10、typecheck 绿。

* identity: gate the R3 latch carrier migration behind egressPlane (owner ruling)

Per owner ruling (discussions/7591): the R3 breaker latch carrier migration
(l1_world -> sessions.r3_latched_at) was the only UNCONDITIONAL behavior change
in this PR. It now branches on featureEnabled("egressPlane"):

- ON  -> new latches land on the sessions row (of record);
- OFF -> legacy l1_world carrier (placeholder row, keyed by
         snapSessRawOf(sid)), byte-identical to pre-migration.

Read / clear / list stay dual-carrier (a superset, always correct), so an
ON->OFF rollback loses nothing. DDL stays unconditional (probe-first,
forward-compatible).

Tests: a new flag-off case in identity-tables-consolidate (now 11) pins the
legacy carrier + conv-bound keying + zero sessions write; p3 M3.2's
new-contract half now runs with egressPlane ON.

* fix(identity): refuse manual archive of egress-on sessions; mirror the convBound predicate verbatim on the lane side

Review follow-ups (2026-11-24):
- archiveSession is the shared chokepoint of the GC age-sweep AND the
  manual paths (unifiedArchiveSession / 'bili sessions archive'). The
  sweep gained the egress-on exclusion, but a manual archive of an
  egress-on session still exported the arm-frozen projection while the
  egress op log (sole content authority) was neither exported nor
  re-imported by restoreSession — data loss. Refuse with a reason until
  the archive format carries the op log (follow-up, same batch as the
  l1/conversations physical DROP). Test pins the refusal + untouched rows.
- S4 lane predicate: the row write is 'pluginAgent when a non-empty
  string, else proxy' (ingest.ts); the lane passed '!= null'. Identical
  today (headerValue normalizes empties), mirror it verbatim so the two
  cannot drift.

* fix(stage0): the position frontier reads the base highWater once compaction removed the I rows

The stateless egress-on branch computed the message frontier as raw
MAX(log_seq). The #7574 compaction physically deletes every I row the
fold's base subsumes, so right after a fold the flow holds the B base
row only and raw MAX(log_seq) is 0: the first turn after every fold
echoed maxPos 0 / anchored at pos 1..k, and every persisted witness
from that session on would have lied about where the world's positions
live. nextSeqs already had the fallback rule (base payload highWater);
the stateless branch didn't. Extract it as egressMessageHighWater and
use it in both.

tests/identity-consolidate-e2e.test.ts pins the whole PR on real seams:
a real SessionStore on an isolated DB, a REAL kernel fold (applyRanges
+ processTurn, not hand-built D batches), runStage0 with real strike
counting and restarts. Pinned: the legacy path is byte-identical; the
stateless verdict across a restart (and the fact that an egress-on
session lands no sessions row on this branch — #7474 P2); the fold
frontier is the base highWater 82, not 0 (this bug) and not 50 (the
live count); the R3 latch lands on the sessions row and the clear
releases it; one clear releases a double-latched migration session
(M1); the GC exclusion + the manual-archive refusal for egress-on.

* retrigger CI against master containing the #6770 fix (no code change)

* fix(tests): E2E cleanup on Windows — close the read-only handle before rmSync, and never let a cleanup failure fail the test

CI red (windows-latest 22/3): all six E2E tests died with
EBUSY on unlink of index.db in closeStore — Windows releases a
SQLite handle asynchronously, so rmSync raced it (and the test's
own read-only verification handle was never closed at all).

The #7581 E2E precedent simply leaves the tmpdir; this version
closes the handle, then makes the rm best-effort: cleanup is
hygiene, a failure to clean must not turn a passing test red.

* Protect mid-session workspace instruction revisions from folding (#2447 follow-up)

The baseline re-emits only when baselineIdentity changes, so a mid-session
edit rides its own message alone: classify Updated/Additional/removed
revision shapes first and project them to per-path durable/agents-md-update
identities. Merged with #7153's system-reminder frame guard, which the
revision classifier already enforces for its own leading-frame forms.

Co-authored-by: IcyDate <44359334+IcyDate@users.noreply.github.com>
Source-PR: #4922
(cherry picked from commit 7d1d57a162e0d3ab1355b376a22d04692af3e845)
(cherry picked from commit 7ea71690b14bc0e161fe31b09d55c68472555a09)

* [PR] feat(dsh): detect dsh-go host and log once | feat(dsh): 识别 dsh-go 宿主并打一次日志

One-shot [dsh-client] detection log for dsh-go hosts; pure probe, fail-open, zero behavior change; decision-table tests.

Co-authored-by: 山海学社OMSociety <85862362+OMSociety@users.noreply.github.com>
Source-PR: #6591
(cherry picked from commit 95894e7ec9ec214cb74aa40e6d320ae10ca5ce2d)
(cherry picked from commit 2dc562cd7d1af0b16f408e12479902265513ff47)

* [PR] fix(external-summary): stop repeated total failures and recover after repair

Wire all-external-summary-failure / invalid-config paths into the existing consecutive-failure guard (3-strike fuse, config-fingerprint or 10-minute decay recovery, success reset); credentials stay in the fingerprint hash only. NOTE: model-facing receipt text changes (flagged in original PR body).

Co-authored-by: xwc2020-2 <232002243+xwc2020-2@users.noreply.github.com>
Source-PR: #6905
(cherry picked from commit 8fca35a5addf12da28a06bde121108091a243f31)
(cherry picked from commit 8e207d1f9dd0fb724eb1166948a28284f23c632c)

* [PR] perf(storage): complete block views once per ingest plan

completeBlockContents: build once outside the per-block loop (n^2 -> n; 16k blocks 22.7s -> 114ms).

Co-authored-by: mariopasquali <46114603+mariopasquali@users.noreply.github.com>
Source-PR: #6914
(cherry picked from commit 418580613982d80289608438b911cc2ffdd4dc67)
(cherry picked from commit 31ebe898e538f63c8dc21719e0169c6d96897971)

* [PR] fix(claude): stop force-exiting the SessionStart hook (Windows libuv abort)

Claude SessionStart hook: route through runSessionStartHook instead of process.exit on the same tick, fixing the Windows libuv abort. CI reds are unrelated base noise (#5844/#7013/#7189).

Co-authored-by: Sentryea <100594650+Sentryea@users.noreply.github.com>
Source-PR: #7094
(cherry picked from commit 327f1911a51f557c4c2b07c3eee6a7b6b27a2dc5)
(cherry picked from commit 03564d4e501093cc99ee58a2b8c3b479d39d0852)

* [PR] feat(compress): protect host-marked current-task prompts from folding

Opt-in compress.protectedUserPatterns (literal substring protection for host-marked current-task prompts against folding); default off, byte-identical when unconfigured; includes the plugin tool path restore fix.

Co-authored-by: 赵瑞哲 <229347043+zhaoruizhe81@users.noreply.github.com>
Source-PR: #7559
(cherry picked from commit 0380d0c11a31dc3203e9abd82ab79aecec1045b6)
(cherry picked from commit c1177b7771065f80dc06fb0efc03d425ecfd4e2f)

* [PR] feat(web): add Korean (ko) locale to the web UI

Fixed a machine-translation truncation in the same pass: ko
summary.key_invalid ended with '너무 김' (cut mid-word); corrected to '너무
깁니다' to match en 'too long'.

Co-authored-by: nockaeo <129250402+nokiexow@users.noreply.github.com>
Source-PR: #7552
(cherry picked from commit 156e1dbea41f6134127b401d5022ed2b507edc1f)
(cherry picked from commit fc6f0cd113fb49c2ee24391902914aa3ec7e323b)

* fix(pack): clear compress streak directly on config repair; add ko parity keys

- src/stream.ts: #7300 reworked clearCompressLoopStreak into a success gate
  with a substantial-fold guard. A config repair is not a compression
  success, so #6905's repair path erases the streak directly via
  writeCompressLoopStreak(session, undefined), preserving its original
  semantics.
- src/web/i18n.ts: the ko catalog from the #7552 pick predates #7594;
  add the six parity keys (ses.badge_child{,_tip},
  ses.filter_kind_{all,child,tip,top}) required by tests/web-i18n.test.ts.

* docs+rollout: egressPlane GA (default 100) + egress-plane/deprecations docs, storage page refresh, KDD #24

- rollout: egressPlane percent 0 -> 100 (GA; opt-out kept per #5469 precedent)
- tests: 5 sites relying on 'unset = off' now set '0' explicitly; egress-record direction test rewritten to 'GA default ON, explicit 0 closes'
- docs/egress-plane.{md,zh-CN.md}: one-stop egress doc (lineage #7439->#7581->#7617, dual clocks, identity consolidation, flag dependency, on/off resolution order, runbook, timeline)
- docs/deprecations.{md,zh-CN.md}: retirement register (l1 placeholder, conversations, D-lane triggers, msgid switch removals, DROP batch)
- docs/architecture/storage{,.zh-CN}.md refresh; AGENTS.md + design-decisions.md KDD #24; docs index x2
- CHANGELOG + generated config docs

* docs(egress): full doc wrap-up per owner review — dedicated egress-plane doc with diagrams, retirement register, storage/identity figure refresh, doc fact fixes

Owner: '现在的文档太简单了 和预期差太远了' + '很多文档应该会因此退役 需要直接退役或者重写'.

- egress-plane.{md,zh-CN.md}: rewritten as the real one-stop doc — inbound vs
  outbound, design-decision table (incl. dual-clock rejection reason), all
  four tables with PKs/retention, 7-step turn lifecycle, before/after
  performance table (KDD #23 numbers), fork & rollback semantics, switch
  family + arm rule, operator runbook, PR timeline. Fact-checked against
  code; fixed egress_state PK misstatement ((session_id, log_seq) ->
  (session_id, op_seq)) in en+zh.
- 3 new diagram pairs (egress-turns / egress-tables / egress-fork, en+zh-CN,
  svg+png): the turn lifecycle, the table map with the flow_op_seq pointer,
  and fork/rollback with the retention floor.
- deprecations.{md,zh-CN.md}: retirement register (l1 placeholder,
  conversations, D-lane trigger conditions, msgid switch removals, retired
  rollout keys) — retire-by-note, nothing deleted (l1/D-lane still serve
  non-egress paths).
- architecture/storage.{md,zh-CN,ja}: egress section completed in zh+ja
  (was en-only), l1_world marked degraded, index links.
- assets/identity.{en,zh-CN}.svg(+png): new egress-plane box (pin resolves
  flow I rows, stateless stage-0, latch in sessions), P8 note updated to
  'l1_world was the planned home, now degraded'.
- assets/storage.{en,zh-CN}.svg(+png): egress table chips (4 + l1 placeholder)
  in the DB band, egress-on note.
- pr-6785 doc (en+zh): retirement note at top (l1/conversations/fold_journal
  status, pointer to current table list).
- AGENTS.md: standing egress pointer in the orientation line.
- src: two stale comments fixed (egress-lane-io 'default 0', schema.ts
  block-DDL 'shared clock' — the pre-dual-clock wording).

* fix(docs): sync egressPlane GA wording into the config-docs seed

The GA commit hand-edited the generated docs/configuration*.md blocks
but left website/config-reference/rollout.yaml at the pre-GA seed
(default "0 (off)" + old desc), so the docs-sync gate's
regeneration reverted those lines and failed on the PR head.

The seed now carries the GA default ("100 (on, GA)" / "100(开,已 GA)",
matching the sibling GA keys pluginLaneServerHistory /
pluginMsgIdIncremental) and the GA desc wording. The generator feeds
BOTH the features table and the env table from the single e.default
string, so the two hand-edited variants ("100 (on)" vs
"100 (on, GA 2026-11-24)") collapse to the convention string — the
GA date + owner ruling stay in the desc text.

* test: scope 6 legacy-path suites to egressPlane off after the GA default flip

The egressPlane GA (default 100) makes egress-on the default, so these
6 suites — which verify the watermark/msgid-pin/render/incremental-lane
behavior by reading the unified messages table — now run egress-on by
accident. For egress-on sessions the messages table is a lazy projection
(no per-turn ingest), so the unified tail view / ledger reads return
empty and the assertions fail (0 rows).

Force BILI_ROLLOUT_EGRESS_PLANE=0 in each harness/setup, consistent with
the 5 egress test files the GA commit already scoped to off. The
egress-on path itself is covered by the 12 egress core suites.

* test: scope 3 egress-fork/lane suites to egressPlane off after the GA default flip

The egressPlane GA (default 100) switches the persistence path to
egress-on (lazy projection: no per-turn ingest into the unified
messages table). These 3 suites exercise the store-level fork
primitive (forkEgressSnapshot, egress-on by metadata.egressAuthority)
and the seq-interval / splice lanes through the unified index, so the
GA flip makes loadAsync / the debounced settle see an empty unified
table and the assertions fail.

Force BILI_ROLLOUT_EGRESS_PLANE=0 in each, consistent with the 5 egress
test files the GA commit already scoped to off and the 6 legacy-path
suites scoped in the prior commit. The egress-on path itself is covered
by the 12 egress core suites.

* revert: egressPlane default stays 0 (owner ruling) — the PR is docs-only now

Owner: '我们没有说要改成100 现在还是需要0'. The default-100 GA flip was
proposed in this series (per the #5469 precedent) and declined.

- src/rollout.ts: reverted to percent 0 (+ original comment).
- tests: the 'unset means off' semantics are restored; three tests that now
  force the off direction use env "0" (wins over both the default and any
  local config file), incl. a hermeticity fix in issue7574-egress-seam
  (delete-env only meant 'off' on machines whose config does not force the
  plane on).
- egress-record direction test rewritten back to 'default 0 — unset env/
  config resolves OFF; explicit 1 opens the gate'.
- docs (en/zh/ja + KDD #24 + CHANGELOG + config docs): every 'GA/default
  100' statement rewritten to 'stays 0, opt-in; a default-100 flip was
  proposed and declined'; the deprecations register's GA gates now read
  'the default-100 flip, pending owner decision'; the flip is listed as the
  first tracked follow-up.

* revert: egressPlane config-docs seed back to 0 (off) — the GA flip was declined (owner ruling 2026-11-24)

* regenerate config docs from the rebased seed (egressPlane back to 0 off; master's newer entries included)

* fix(egress diagrams): the six new arrows had no arrowheads (review m02806)

The generator emitted plain <line> elements with no <marker> definition, so
every arrow in egress-turns/tables/fork (en+zh) rendered as a bare line.
Added the marker def (userSpaceOnUse, matching the original storage/identity
figures' approach) + marker-end on all 11 arrows; re-rendered the 6 PNGs and
pixel-verified the arrowhead zones.

* fix(egress diagrams): pointer arrow was a self-loop; remove double arrowheads

- egress-tables: the flow_op_seq pointer ran from egress_block_flow's
  top-right corner back into its OWN top-left corner (both endpoints on the
  same box, riding its border) — it was meant to point at egress_flow.
  Rerouted as a polyline: up from the block table's top, across the gap,
  down into egress_flow's top edge; labels moved above the line.
- turns/fork/tables: the generator had already drawn hand-made polygon
  arrowheads; the previous marker fix added marker-end on top of them, so
  every arrow wore two heads. Polygons removed — the shared <marker> is now
  the only arrowhead source (matching the original storage/identity figures).
- re-rendered all 6 PNGs, visually re-checked.

* degenerate retry: configurable attempt budget + nudge rotation (compress.degenerateRetry)

#7666 follow-up. The degenerate-terminal retry (empty/draft-tail turn ->
re-issue with a transient continuation nudge) was hard-wired to one attempt
per turn, shared with the #2171 truncation re-issue budget. This makes the
budget and the nudge sentences configurable per the existing three compress
levels (global -> provider -> model), merged sub-field-wise like absorb:

- compress.degenerateRetry.maxAttempts: integer 0..5, default 1 (pre-#7666
  behavior); 0 disables the retry entirely (the #5897 opt-out, now
  per-config instead of an env switch).
- compress.degenerateRetry.nudges: 1..8 custom sentences, one per attempt
  (cycling); default is a built-in three-sentence rotation whose first entry
  is the historical DEGENERATE_RETRY_NUDGE, so attempt 1 is unchanged.
- The budget is independent of the #2171 truncation re-issue: a turn may
  spend one degenerate and one truncation re-issue.
- Chat lane keeps the in-band terminal error when the budget is exhausted
  (#870; plural wording names the attempt count when > 1). The responses
  lane keeps passing an exhausted empty turn through (no #870 there).
- Nudges stay transient: appended to the retry body only, never persisted,
  never replayed on the client's next request. Cost per extra attempt is
  near zero on a warm prefix cache (the append is at the body tail).

Local evidence (#7666, 7 days, qwen3.8-27b): 85 degenerate arms, 79 rescued
(93%), 6 fatal #870s; empty stops are an independent sampling-tail event
(3/30 replayed at baseline), so a fresh nudge sentence genuinely re-draws
the tail instead of re-issuing a byte-identical prompt.

Web quick-config: 'degenerate retry attempts' (0-5) + one-nudge-per-line
textarea, with i18n (zh/en). Docs updated in all three languages.

Tests: 20 new (parse bounds, block-rejection on bad values, sub-field merge,
nudge rotation via a recording server, both pipe lanes' budget behavior
including the off switch); full related regression green; tsc green.

* config surface: seed compress.degenerateRetry in website/config-reference, regenerate docs

Fixes config-surface-guard + docs-sync CI failures: the docs index tables
are generated from website/config-reference/*.yaml (tools/gen-config-docs.mjs
generate), not hand-edited. Adds the compress.degenerateRetry object entry
(co.degenerateRetry) plus the two leaf seeds (maxAttempts, nudges) with
en/zh/ja descriptions, and regenerates all generated artifacts (docs tables
in all three languages, website nav).

* [PR] kernel: bridge span-safe gaps at the merge gate so mega-turn islands …

Retarget the kernel version bump from 0.0.207 to 0.0.209: master has moved
to 0.0.208 (0.0.207 was consumed by an unrelated kernel release), and the
code does not depend on the number.

Co-authored-by: guowenjie1992 <52691423+guowenjie1992@users.noreply.github.com>
Source-PR: #6345
(cherry picked from commit bd4548a4d346b363c8fdb06b6e2602fb8184b9e9)
(cherry picked from commit 6ac84b74b3250ead06c5013a6742e3f03b43cb62)

* [PR] fix(agent): price the client-local doom gate by prompt mass, not raw body bytes (#7106)

Client local doom gate: price by prompt mass instead of raw bytes, fixing false rejects from the 8MiB dsh_session_log transport field; two-tier contract kept, 8 tests.

Co-authored-by: ZzXxYy1234 <104406571+ZzXxYy1234@users.noreply.github.com>
Source-PR: #7119
(cherry picked from commit 18939eba8855e6bb9fd163b4b12c04280a3fa13c)
(cherry picked from commit 4c50854e5b9116846832a7cd928a9130e2273c37)

* fix: ko i18n parity for the degenerate-retry keys; label+mount the nudge textarea; update #2171 budget tests to the independent-budget contract

- web-i18n #1024 parity: the ko locale (landed on master via the PR-branch
  merge) needs the four cfg.q_degen_retry_* keys too.
- web-i18n dead-key: cfg.q_degen_retry_nudges was unreferenced because the
  textarea had no label — and it was never appended to the DOM (qCtrls is
  only the disable-target list), so the control was invisible. Wrap it in a
  labelled row and mount it like every other quick-config control.
- #2171 tests pinned the old SHARED re-issue budget; the owner ruled the
  degenerate retry gets its own budget (#7666), so a healed stream may now
  still spend one degenerate re-issue: chat refetches twice and raises the
  #870 terminal, responses refetches twice and passes through (no in-band
  error on that lane). 75/75 local, WEB_CLIENT syntax checked, tsc clean.

* fix(web): reject non-integer degenerateRetry.maxAttempts in the quick-config page

The degenMax handler floored the input (Math.floor(Number(v))), so typing
"2.5" silently became 2. The server requires an integer 0-5 and rejects
2.5; the UI should reject it too (clear the field) rather than silently
floor it to a different value. Number(v) + the existing Number.isInteger
check now rejects non-integers, matching the server's validation.

* fix: stop the engine-truncated WAL reclamation that corrupted the shared index (default journal_size_limit -> 0; reclaim via PASSIVE checkpoints)

#7674 — the corruption producer, per the source comparison with
opencode-stable (13 concurrent writers, 9.55 GB db, zero damage):
opencode never asks SQLite to shrink the WAL; the old 8 MiB default made
the engine truncate index.db-wal internally after EVERY completed
checkpoint — an implicit floor-reclaim that no JS-side guard covers,
pulling the WAL out from under live peer connections sharing the
sessions dir (#2671 five-daemon topology, kill-9 handovers). Damage
shape = #7156 (pages double-allocated in the tail, index pages corrupt
first); three field events 2026-11-19/21/23 plus the #7156 incident.

- storage.walJournalSizeLimitBytes default 8388608 -> 0: 0 = the engine
  does not truncate (file sits at its bounded historical high-water
  mark; field ~55 MiB steady); a POSITIVE value keeps the legacy
  truncate-to-N behavior for anyone who wants it.
- open/close reclaim: TRUNCATE -> PASSIVE (frames still converge at
  lane boot / daemon stop; the WAL file is never truncated behind live
  peers). The #7156 activeForeignWriter guard around those two call
  sites is dead code now and is removed; the #4175 lock file itself
  stays (the integrity-cache invalidation still consumes it).
- gc/vacuum operator-requested reclaim: TRUNCATE kept there
  (explicit, infrequent, logged).
- docs en/zh/ja + website config reference + config.ts comment.

* fix: a live manual (lane-less) daemon on the lane's target port now blocks the launch instead of drifting a silent second writer

#7675 — field state on the corruption host (2026-11-24): three manual
'bili start' daemons on 18873/4/5 plus two pi-lane daemons drifted to
18876/18877 by the port ladder — five live writers over one index.db.
The pre-spawn second-writer gate (#7156) only matched instances whose
lane EQUALS the launching lane, so a manual daemon (no lane) was
invisible: the lane found the port occupied, laddered to +1, and
spawned a full second proxy on the shared sessions dir.

quiesceSameLanePredecessor now counts live LANE-LESS instances on the
target port as predecessors. They are neither attachable (unless
armed — that cell attaches and spawns nothing) nor takeover-eligible
(the user's own process), so the gate REFUSES with an actionable
error: pid + 'manual launch with no lane' + the two remedies (give it
its own -p / BILI_PORT_ZONE, or kill <pid>).

Rows updated for the deliberate behavior change (spawn-behind ->
refusal): launcher.test.ts #2877 row, issue5955 user-zone row (the
holder is still untouched — no kills; only the launch outcome moved).
New suite issue7675-nolane-second-writer-gate.test.ts: refusal rows
(armed-vetoed, health-silent) + does-NOT-trigger rows (armed attach,
dead pid, foreign port, same-lane healthy, lane-less launch).

* docs: apply gen-config-docs output for the #7674 walJournalSizeLimitBytes re-default (docs-sync lane)

* test: #3544 user-zone row follows the #7675 gate semantics (rotation still never touches it; the launch now refuses instead of spawning behind it)

* fix: gate refusal wording — 'no lane declared' instead of 'manual launch'

The second-writer refusal described the lane-less holder as a 'manual
launch', which mislabels host-spawned lane-less proxies (they carry a
launch token, not a manual start). 'no lane declared' is accurate for
both shapes; the remedies (own port zone / kill) are unchanged.

Review fix-up on #7678 (second-writer gate, #7675).

* fix(storage): fork of an egress-on parent with no unified sessions row

#7658 step 1 — e2e pins + the clone fix

An egress-on session's unified leg is frozen (egressProjectionFrozen),
so a session that armed from turn 1 has NO sessions row at all — the
normal creation site is the ingestSession upsert, and ingests are
frozen. The host fork then hit cloneSessionRows' legacy-only early
branch: no egress table copy, no lineage pair, child silently
re-bootstraps from client bytes (msgid track survives, so it 'works',
but the R-B whole-table-copy ruling is broken: number space
re-issued, retired/fold marks lost, parent_session_id absent).

cloneSessionRows now treats a parent with egress rows but no sessions
row as forkable: the skeleton parent row is inserted in the same
transaction (the #7591 R3-latch pattern) and the clone proceeds —
egressPointForkSession copies all four tables verbatim, the child
row carries parent_session_id + fork_point_seq, and the initial
ingest finalizes the projection.

tests/egress-fork-host-e2e.test.ts pins the surface end to end:
T1 fork-to-now verbatim copy, T2 mid-history fork D-run + number
continuation + parent isolation + second-turn probe, T3 cold parent
reconstruction fork, T4 (RED pin) capped egress-on parent → 409
until the op-log snapshot source lands.

* feat(storage): inherit egressAuthority across fork + record the egress fork point

#7658 step 2 — wiring 1 + wiring 3

Wiring 1 (host face): the fork metadata whitelist now carries
egressAuthority, so a child of an egress-on parent is served from its
own copied flow on turn 1 instead of re-bootstrapping from client
bytes. The admin face (forkEgressSnapshot) strips egressFlowUnreadable
from the copied metadata: the unreadable latch is a per-session
failure state of the PARENT's log; the child's health is decided by
the child's own first recovery walk.

Wiring 3 (storage face): sessions gains fork_egress_watermark — the
FLOW-clock watermark (MAX op_seq of the parent's egress_flow) the four
egress tables were copied at. fork_point_seq cannot carry it: for an
egress-on parent the unified leg is frozen, so the clone's
through-seq is -1 while the egress copy is whole-table. Probe-first
ALTER, SQLite writes the value, MySQL mirrors the column (NULL —
egress tables are SQLite-only). T1 pins the lineage pair + watermark
on the child row; T2 pins the latch inheritance.

* feat(plugin): fork snapshot source falls back to the egress op log

#7658 step 3 — wiring 2

An egress-on session's unified leg is frozen, so once the in-memory raw
snapshot is gone (dropOverCap under BILI_PUBLIC_SNAPSHOT_CAP_BYTES, or a
cold process whose raw-tail reconstruction only sees frozen rows) the
fork and the snapshot route 409'd SNAPSHOT_UNAVAILABLE even though the
egress flow — the content authority by ruling 7439-5 — still holds the
full canonical history.

forkSnapshot's source chain gains egressOpLogSource (rebuildCoreFromLog
over the parent's flow) as the last resort after the raw snapshot and
the raw-tail reconstruction, so sessions where those still work keep
today's behavior. The source chain is extracted to forkSourceOf and
shared with the child-construction path, which used to recompute the
first two links on its own and null-slice when only the op-log fallback
had a source.

T4 pins the end-to-end surface: capped egress-on parent → snapshot 200
from the op log; a client still holding the PRE-cap snapshot gets 409
BRANCH_POINT_CONFLICT (identity-stable byte drift on the stamped cells
— the #6262 drift track, follow-up); the real host flow (re-snapshot,
fork with fresh cells) gets 201 and the verbatim whole-table copy.

* docs(storage): correct the skeleton-row comment — an egress-on parent never full-ingests

The comment claimed a later full ingest fills the skeleton row's JSON
columns, but an egress-on parent's unified leg is frozen
(egressProjectionFrozen), so no full ingest ever runs — the columns keep
their DDL defaults and the egress op log is the parent's authority. The
skeleton row is a lineage anchor only.

* test(#7658) T5: fork-then-compress — child's client-side fold books in its own flow

Host-side compress (pi folds locally, re-sends folded history): the
child's first post-fold turn books one D-run over the covered cells +
a summary I row numbered strictly above the parent high water, the
D-bearing batch compacts (B row), the next turn advances by exactly
one flow number, and the parent flow stays isolated.

* test(egress-fork): real-client adoption, block fork + both-side isolation, fork-after-fork, block-ledger gap pin

T6 tryForkAdoption end to end (the #2399 client half — snapshot →
text/msgid prefix → fork POST) against an egress-on parent.
T7 compression blocks ride the fork (kernel block set byte-identical);
parent and child fold AFTER the fork on their own flows — each fold
books in its own session only (D-run + fresh summary number above the
inherited watermark), neither flow nor block set leaks across.
T8 fork-after-fork: p8 folds, c8 forks the folded state (the compressed
summary row survives byte for byte; the consumed kernel block is not
inherited because its covered cells left the live prefix), c8 turns,
g8 forks c8 mid-history — two lineage levels in SQL, watermarks at
each fork, g8's first turn D-runs the dropped tail and continues the
number space strictly above c8's high water.
T9 gap pin (RED by design of this PR): a fully armed egress-on session
(plane ON + egressAuthority latch) NEVER writes the #7577 block ledger
(egress_block_state/flow stay empty) because the only writer sits in
the unified ingestSession, which egressProjectionFrozen skips — the
R-B four-table fork therefore copies two empty tables. The kernel
block set still forks correctly (T7); the fix direction (move the
block-ledger write into recordAuthorityTurn's transaction) is a
follow-up this test pins.

gate: Lane B gains the fork-then-compress legs the old fork check
stopped before — (1) adopted block count == the parent's active block
count after the parent's own fold (块一致), (2) the forked session
re-reads the corpus and must fold on its own (fork 后能压缩), (3) the
child's post-fold recall must hit BOTH generations: S07 from the
adopted parent block + S40 from the child's new fold.

* fix(storage): write the egress block ledger on the egress record path (the #7577 second leg)

The #7577 block ledger (egress_block_state / egress_block_flow) was
promised to rebuild the block set from the op log alone — but its only
writer sat in the unified ingestSession, gated on the save-envelope
metadata.egressAuthority. A fully armed egress-on session skips the
unified record entirely (egressProjectionFrozen), so the ledger tables
stayed EMPTY and the R-B four-table fork copied two empty tables.

Fix: the egress record path (recordEgressTurn — the single funnel of all
five egress record points) now carries the in-memory block set
(egressBlockLedgerFor, gated on the egressAuthority latch). Each turn
diffs the ledger view vs the live kernel blocks (diffBlockSet) and
appends self-contained I/U rows with the kstate residual sidecar.
Best-effort by design: a failed ledger append never blocks the turn and
self-heals on the next one (idempotent diff on a fresh view).

T7 now asserts the ledger rows ride the fork verbatim; T9 flips from
red-pin to green: the I row carries the block's full bytes, the
coordinate/msgid range, the sidecar, and egressBlockReplay rebuilds the
block set from the ledger alone.

Refs #7658, #7577, #7439 (R-B).

* feat(storage): retire egress-on kstate to the op log (PR-B of #7658)

The unified legs are frozen for fully armed egress-on sessions, so
sessions.kstate_json never tracks their live state — a folded session
that restarts cold loads with an EMPTY block set (the #3573 shape) and
a fork of that cold parent inherits nothing. The op log was always the
intended authoritative store; this commit completes the rebuild side:

- egress-block.ts: block ledger rows now carry the full kernel block
  shape (summary/runId/effectiveMessageIds/directMessageIds/direct-
  BlockIds/compressedTokens/createdAt/survivedCount/generation/expanded)
  so the block set is reconstructable from the ledger alone; new
  rebuildEgressKstateOverlay maps (block replay + sidecar + live flow
  view) to kstate: blocks + messageRefs + tsStamps + the 13-field
  residual sidecar. lastPassIds stays deliberately out (self-heals).
- shadow.ts (viewFor): egress-on cold loads apply the overlay under the
  egressKstateRebuild flag; any replay corruption keeps the stored
  state verbatim (no fuzzy guessing — same discipline as the message-
  log degrade ladder). The egress-on gate now also accepts 'flow rows
  exist', which the skeleton row a fork materializes for an armed
  parent has no metadata_json to carry the latch on (fixes the same
  latent gap in the tsStamps fallback).
- ingest.ts: under egressKstateRetireWrites, non-residual kstate fields
  stop being double-written for armed sessions.
- rollout.ts: both flags default 0; rollback order = RetireWrites off
  first, then Rebuild off.

Tests: T10 (cold fold -> cold load rebuilds block/refs/tsStamps from
the op log; flag off pins the empty legacy load); T7's block-ledger
assertions now pin the real two-writer shape (parent books on its next
egress turn, child self-heals at clone time, ledgers stay isolated).
Full file 10/10, tsc clean.

* chore(storage): drop the export from three internal-only symbols (CI unused-exports)

* fix(gate): Lane B fork-compress assertions — parse the true block count, survive the async log race, retry the model flake

Two real-model gate runs exposed three gate-side bugs (the product
behaviour was right in all cases):

1. parentActiveBlocks was parsed from the t2 slice only — Lane A folds
   several times in its small-window phase, so the check compared the
   FIRST fold's count against the adopted count (flake: parent=1 vs
   adopted=4). Now: the last 'N active blocks' line in the whole
   evidence file before the fork-adoption line.
2. The child fold check sliced from a mark taken before the turn; the
   proxy logs the shrink line asynchronously and it can land after the
   slice is cut (flake: the fold demonstrably happened — the
   two-generation recall, which needs it, still passed). Now: fall back
   to searching the whole evidence file for a shrink line tagged with
   the forked pfa (any shrink under the child pfa is post-fork by
   definition).
3. The two-generation recall can get a single model flake (the child's
   fold surfaces as an ACP compress-receipt line instead of the TITLE
   markers — seen once on the glm relay). One identical-prompt retry.

Result: A 9/9, B 10/10 in 297s (billion-context@0.1.216 from this
branch, real model lanes).

* test(egress-fork): best-effort temp cleanup — EPERM on the Windows runner's still-locked temp tree (CI hookFailed)

The after-hook's plain rmSync threw EPERM on windows-latest node 24
(the SQLite handle on the same tree is only released by Defender/GC
after the last test; the 10 tests themselves all passed). Bounded
retries + swallow, same pattern as tests/issue3397-durability-before-
render.test.ts (rmBestEffort).

* fix(plugin): the fork source link must not leak a damaged flow as FORK_FAILED

egressOpLogSource read the view (a flow replay — it throws
EgressStateCorruptError on a damaged log) in the fork route OUTSIDE its
structured-error try. A snapshot-capped egress-on parent with a damaged op
log therefore 503'd with the raw DB error text in the response body instead
of the diagnosable 409 SNAPSHOT_UNAVAILABLE (and the client-visible error
leaked storage internals). The source link now degrades to "no source"
(warn-logged — a damaged log is a support incident) and the route's own
try produces the structured 409; the child's recovery walk decides the
copied log's health. T11 pins both directions (red pre-fix: 503 FORK_FAILED
with the raw EgressStateCorruptError in the body).

(review follow-up on the egress fork completion)

* rollout: egress family defaults to 100 — ci:full verification branch (NOT for merge)

Owner directive (2026-11-25): the merged egress work should get a full CI
pass with the plane ON by default. This branch flips the three egress
rollout defaults (egressPlane, egressKstateRetireWrites,
egressKstateRebuild) from 0 to 100 so every ci:full lane runs the whole
egress path out of the box; rollback is still per-install via
rollout.features.* = false or the BILI_ROLLOUT_* env ("0" always wins
over the baked-in percent).

Accompanying:
- config docs regenerated from the seed (docs/configuration.{md,zh-CN,ja})
- two tests that read "unset env" as "plane off" now force "0"
  (identity-tables-consolidate S5 latch test; egress-record #3617
  negative-direction test — renamed: the rollback path is the forced 0)

Verification branch: close after the ci:full evidence is collected, do
not merge.

* test(ci-full): scope legacy-wire suites off the egress plane

With the branch's egressPlane default of 100, the openai lane serves the
outbound conversation from the op log for EVERY session (egress-serve.ts
seg 4b, recorded bytes replayed verbatim). Measured on all four golden
wires: after fold + restart, a folded summary carrier keeps its <acp> tag
in the log-served leg while the legacy restart re-renders it without one
(turn 13 drift). Kstate pair and storage tier alone stay byte-equal
(isolated both ways), so this is egress-serve behavior, pinned by the
egress suites — not storage-tier invisibility, which is the contract of
storage-engine-proofs (goldens pre-date the plane), plugin-fork and
issue3769-upgrade-compat (legacy fork/orphan pins).

* test(ci-full): scope the real pi/dsh e2e lanes off the egress plane

The plane default (100 on this branch) ARMS these real plugin lanes
(x-bili-plugin pi/dsh, pinned): egress-on sessions freeze the legacy JSON
persistence surface — the op log + index.db are the transcript authority —
so the legacy-persistence assertions (session files on disk, compressed
blocks in the envelope, parent+child files) fail by design of the plane,
not of the lanes. Scope the plane off in the spawned env (cleanEnv strips
BILI* inherited vars, so the pin rides inside cleanEnv); armed behavior is
pinned by the egress suites.

* docs(egress): lock the renumber design — log_seq IS the citation number

Owner ruling 2026-11-25 (closes the refs-table / op-log split behind the
wire token-tag bug): the kernel citation number and the op log's log_seq
are ONE number.

- egress-plane.md §10 (+ zh): the six rules — citation-aligned log_seq
  (MAX+1 survives only as fallback for uncited rows); the system row is
  number 0, outside the citation space (the 'filter out the system row'
  problem disappears by construction); arm-time one-shot SELF-HEALING
  backfill (marker row, fork-safe, state-based detection); refs table
  write-retired for egress-on with read fallback until the physical DROP
  batch; the kstate overlay ref rebuild becomes the legitimate path;
  client raw system A lives in egress_state (fixed msgid, num 0, U on
  change) while the flow keeps the assembled A+B transcript.
- deprecations register (+ zh): refs write path + session_ext inc:system
  (egress-on) entries with removal gates.
- architecture/storage.{md,zh}: pointer into the egress paragraph.

* feat(egress): renumber — the op log's log_seq IS the kernel citation number (owner ruling 2026-11-25)

The kstate-rebuild overlay minted m00001 = egress-system (the op log
numbered rows densely from 1, system row first) and shifted every real
citation by one on cold load; the stored tokenSnapshot (keyed by kernel
ref) then misattributed wire tags after restart. Ruling: no second
number space — log_seq is the kernel citation number.

- egress-state: InsertOp.num/sysIn, UpdateOp.sysIn; replay + writeOps
  keep a cited number even below the batch high water (retired slot);
  collision is refused only against a row LIVE at the op position;
  uncited rows (kernel fold-summary ids have no refs entry) take the
  dense fallback ABOVE every number the batch cites; the system row is
  number 0 (outside the citation space) in both store and replay.
- egress-record: citationNumber (byRaw, then mNNNNN parse), refMap
  through recordEgressTurn; sysIn (the client raw system) stamped on
  the system I/U ops; EgressOpLogStore.egressSystemInput.
- lanes: openai/anthropic/google/responses pass session.state.messageRefs
  to the record pass (recordAuthorityTurn gained the param).
- store: egressSystemInput reads the system row's sysIn from
  egress_state; the incremental lane prefers it over the sticky
  session_ext copy for egress-on sessions (legacy untouched).
- tests: T6/T7/T10 oracles re-based on the new numbering; the
  acp_summary_b2 collision found in T7 (a fork-child fold books a
  kernel summary id with no refs entry BETWEEN cited numbers) pinned;
  NEW tests/egress-load-refs-overlay.test.ts — the regression oracle
  (RED on baseline: system row claimed m00001; GREEN here);
  storage-engine-proofs keeps its plane scope, comment rewritten:
  after the renumber the tags AGREE and the only residual turn-13
  delta is egress-serve's logged-bytes transcript (the fold carrier
  keeps the tag it was served under; legacy re-renders untagged) —
  pinned by the egress suites, not the storage-tier oracle.
- docs/egress-plane.md (+zh) §10 amended: collision rules + the
  marker-row claim dropped (the natural first record pass IS the
  backfill — idempotent by construction, self-heals truncated logs).

* fix(ci-full): close the two red gates from 6842c71

- unused-exports: citationNumber is only consumed by buildEgressViewRows
  in the same file — drop the file-scope export (the gate rejects it).
- e2e-native-dsh-persona: scope the suite off the egress plane, the same
  discipline as e2e-native-dsh / e2e-native-pi / e2e-delegate-notify
  (5c73de3). With the plane ON these real dsh lanes arm and the legacy
  JSON persistence surface freezes (index-only) while egress-serve
  replays the recorded transcript across the mid-session
  model/protocol switches — the two failures were exactly that
  (no session under the raw key; compress re-called on the switched
  wire). Verified 2/2 green locally with the scope.

* fix(verif): translate the `in` operator and String.lastIndexOf (two inherited master reds)

Two inherited master reds in the verif judge suites, both translator
gaps exposed by master evolution (KDD #14: teach the translator first):

1. verif-snapshot-render: 5404d9c27b (#4804) added `if ("reason" in
   base)` to snapshot-render.ts buildView; the translator had no `in`
   support — evalBinary fell through to any → "if condition degraded"
   → the judge's degradations === [] assertion failed.

2. verif-bug3769: ce781e54af2 (#7521) rewired quotedRangeKeys onto
   parseCompressArgs, inlining parse-compress-input.ts into hide-consumed's
   call graph; stripFence's `s.lastIndexOf("```")` hit the
   unmodeled-method degrade → any → `raw.length` in normalizeSingleQuotes
   threw "member on any".

Fixes:
- `in` operator: obj SymVal gains an optional presence map (per-field
  liveness guards built at the merge/literal/delete/write rebuild sites);
  InKeyword resolves const-string keys against it. No entry ≡ definitely
  present; a const-false entry = deleted. Sound direction:
  over-approximating presence can only yield spurious SAT (caught by the
  replay lock), never false UNSAT.
- String.lastIndexOf: exact const fold; symbolic receiver → fresh Int in
  [-1, len(recv) - len(a0)] (the JS result range).
- terms.ts indexOf: the 2-arg str.indexof form built a 2-child SMT-LIB
  term the solver rejects — default start to 0 (the 3-ary form).

Full verif matrix: 77/77 green (master had 2 inherited reds); typecheck
clean.

* kernel: cross-lane egress rendering — degrade explicitly, never drop

Egress-plane follow-up (discussion #7439): when a pinned session switches
wire lane, the flow rows were recorded in the original lane's shape and
the serving lane's raw sidecars are foreign. The coreTo* converters then
had no policy for the canonical-fields-only path:

- coreToAnthropic emitted an UNSIGNED thinking block (rejected upstream)
  for any reasoning core without its own signature, and rendered image
  cores as the literal "[image]" text (imageBase64 never read);
- coreToResponses dropped external reasoning cores entirely (raw item
  required, no else) and rendered cross-lane images as text;
- coreToGoogle emitted an unsigned {thought:true} part (Gemini 3 rejects
  the whole request).

Align with pi-stable's degradation policy (packages/ai/src/api/*):
unsigned thinking -> visible plain text; images rebuild natively from the
imageBase64/imageMediaType sidecars. Same-lane behavior is byte-unchanged
(raw/sidecar verbatim paths keep priority; new branches fire only when
the sidecar is absent/foreign).

Tests-first: kernel/tests/crosslane-egress-fidelity.test.ts pins the
openai-recorded agentic conversation across all three target lanes plus
same-lane signed/unsigned thinking regressions (failed on main before).

Ref: #7439 (egress plane), #6781, #7102, #6957, #4920

* server+agents: wire-granularity msg-id pinning for cross-lane model/protocol switching (#7439 follow-up)

Hosts stamp one id per PROTOCOL ELEMENT; the kernel splits one element
into N cores (assistant text+tool_call, user text+image) sharing a
wireIndex. The per-core length check rejected such lists, degrading the
session to content-derived ids: the switched turn re-rendered from
scratch (full history resend #6781, permanent oversize refusals #7102,
消息错位 on lane switch).

- msgid-pin.ts: wirePinGroups/validateWireMsgIds/applyWireMsgIdPin —
  group cores by their already-stamped wireIndex (continuity-checked);
  group head takes the host id, siblings derive deterministic
  <base>#p<k> ids inside the 7439-1 self-contained row bytes (zero
  schema change). Dual-mode is unambiguous: a split form always has
  fewer ids than cores, so 1:1 lists keep the original per-core path
  byte-for-byte (old hosts unchanged).
- stage0 (openai/responses) + prepare-anthropic + prepare-google:
  dual-mode dispatch; the R3 identity fault path is untouched.
- coreAlignEnvelopeIds (pi + dsh shared): returns the element-aligned
  list; drops only what breaks the wire<->entry pairing proof.
  opencode-v2 needs no change (its header ids were already
  per-element and now validate).
- tests: msgid-pin-wire-form (8 unit), crosslane-wire-pin (e2e:
  split-core bootstrap + next-turn Anthropic wire of the same session
  serves from the op-log with correct placement; neither-form degrades
  to 200), issue6525 split-bail cases flip to per-element ids.

Proposal: discussions/7439#discussioncomment-19862991

* fix(lint): drop unused export on WirePinGroups (unused-exports gate)

WirePinGroups is referenced only inside src/msgid-pin.ts (return/param type of wirePinGroups/validateWireMsgIds/applyWireMsgIdPin); no other module imports it, so the export is INTERNAL_ONLY. Dropping the keyword satisfies the gate without changing behavior. typecheck + msgid-pin/crosslane/msgid-rule-parity suites green locally.

* server: rethrow EgressAuthorityRejectError on every wire lane (ruling 7439-5)

The openai lane already failed loudly when a pinned session's op-log had no
healthy point (500 + x-bili-egress: unreadable); the anthropic, responses
and google seams swallowed the same error in their catch and forwarded the
CLIENT'S bytes to the upstream — the exact degrade ruling 7439-5 forbids.

All four lanes now rethrow EgressAuthorityRejectError from the prepare
catch to the server funnel, which answers 500 + the unreadable marker and
latches the session until the operator resets the log (POST
/__bili/egress/reset). Other kernel failures keep the existing
forward-unchanged degrade on every lane.

Test: tests/egress-authority-rethrow.test.ts — a pinned session bootstrapped
on the openai wire, its log rows damaged, then hit on each of the four
wires: the turn 500s with x-bili-egress: unreadable and the upstream
receives no request (client bytes never leave the proxy). Red before the
fix on anthropic/responses/google (they returned 200).

* server: window ratchet — a model judged on the anonymous default rides it until billing proves the window bigger (C4, PR #7684)

Models with no declared window anywhere (no plugin/launcher/operator/registry/
table evidence) were sized against the anonymous base.modelContextLimit default
forever. If the upstream's real window was bigger than that default, every turn
that legitimately billed past the default left the next turn's preflight judging
the same anchor against the too-small default — force-folds, window fuses and
the '#6957/#7102 switched-model-now-over-window' symptom half.

Ruling (owner, 2026-11-25): the first request is not judged against a smaller
guess — it runs on the default; if the turn SUCCEEDS and the upstream BILLS
input beyond the window the request was judged on, that is the proof the
upstream window is bigger: raise the session-local window to 2× the observation,
monotonically (never down, never below a previous raise).

  * src/server/handle.ts: requests that judged the model on the anonymous
    default (no declaration of any kind; an operator-tuned window never counts
    as the default) record metadata.windowFallbackModels[model] = judged window;
    a session-raised number (metadata.windowRatchet) re-resolves the request
    config so preflight/nudge judge against it (logged once as
    source=ratchet). Declared / registry / operator windows are untouched.
  * src/cache-ledger.ts settleUsageReport: a real usage report (the non-foreign
    branch only) that billed past the judged window raises the ratchet to
    2× the observation with a loud [window-ratchet] line.
  * tests/c4-window-ratchet.test.ts: full-chain e2e — default ride → over-
    default billing → single 2× raise → post-raise turn judges against the
    raised window → monotonic (no second raise) → declared-window control
    model never ratchets. Red before the fix (the over-default bill settles
    but the window stays put).

* server: make a session's wire-lane switch explicit — loud line with the per-turn loss list (C5, PR #7684)

A conversation that moves to another wire dialect (openai -> anthropic ->
responses) silently had its dialect-neutral cores re-rendered on the new
lane: no log line, no counter, no loss list. The re-render has bounded
losses (thinking signatures degrade to plain text, redacted placeholders,
tool-error flags, mid-system placement), and the user/ops never saw the
switch happen.

- src/server/session-lane.ts (new): noteSessionLaneSwitch(session, protocol,
  inbound, log) — session metadata tracks lastLaneKey + switch counter +
  accumulated evidence (signed thinking / redacted / images / tool errors /
  mid-system, Math.max-merged because hosts re-resend history every turn).
  First observed lane: baseline only, silent. Same lane: silent. Lane change:
  one warn line with the loss list for THIS conversation's content.
- handle.ts runPrepare: calls it after the prepare (all four wire lanes).
- tests/c5-lane-switch.test.ts: openai -> anthropic -> responses on one
  session asserts the two switch lines (switch #1/#2, direction, loss list
  mentions thinking after a signed block was observed), steady-state
  silence on same-lane turns, and silence on the first observed lane.

Ruling 7439-1 is untouched: the flow rows stay dialect-neutral; this is a
session-level OBSERVATION of the serving lane, not storage.

* server: make the egress flow the seq authority for egress-on sessions (C6, PR #7684)

An egress-on session's legacy messages projection is FROZEN at the arm
turn (#7474 P2, ruling 7439), but block coordinates still resolved
through that frozen table (store.ts boundsForCovered) and kernel-input
cores carried no ledgerSeq at all on egress traffic — so seq-based
coverage in the kernel (prune / sync / fold interval recording) silently
did nothing for exactly the sessions the plane exists for, and blocks
folded after arming bound to stale table space or [-1,-1] no-claim.

- stampEgressSeqs (egress-lane-io): each lane now stamps the
  kernel-input cores with ledgerSeq = egress_flow.log_seq (1-based; the
  system row holds 1, matching the plugin-lane row.seq+1 convention).
  Per-turn view only: the recorded flow bytes strip the field (the
  identity hash already ignores it).
- store.ts: for egress-on sessions the block coords come from the flow
  (live ids -> their flow numbers) or from the block's own
  kernel-attested interval (ingest.ts now carries provenStartSeq/EndSeq
  from the envelope) — covered ids are already gone from the live view,
  so the attestation is the only source. egress-off is byte-identical.
- tryIncrementalPin now maps at WIRE-ELEMENT granularity: a split core
  (one element, several cores, #pN siblings) counts as one element, so
  the steady-state tail pin stops degrading in the agentic shape that
  is normal traffic. Prefix drift still degrades (never rejects, never
  mis-maps); 1:1 sessions keep the legacy per-core mapping.

Tests: c6-egress-seq-authority (A: real kernel fold attests [11,41] in
flow number space; B: rollback re-ingest rebinds to the flow, kernel
attestation beats a vanished look-up; C: stamps never land in the flow
bytes; D: element-granularity tail pin). Regression: kernel 1678/1678,
seq/block/egress/msgid/pin families all green.

* test: the 12-cell switch matrix — {model, wire, both} × {bootstrap, steady, fold, fork} end-to-end (C7, PR #7684)

The egress plane had ZERO coverage for a session changing model and/or
wire lane mid-life: all 21 plane-ON tests are single-model single-wire,
and no gate lane does a protocol switch. Every symptom issue in the
#7439 background (#6781 43MB unfolded resend, #7102 permanent 422,
#6957 window-fuse refusal, #4920 fold-coverage mismatch) is a session
that switched.

This file drives a live proxy (plane ON) with a fake upstream answering
three wire dialects, and runs all twelve combinations:

  model (A->B, same wire)     × bootstrap | steady-state | fold-active | fork
  wire   (openai -> anthropic)× bootstrap | steady-state | fold-active | fork
  both   (wire + model)       × bootstrap | steady-state | fold-active | fork

Fold-active cells first force a REAL kernel fold (8K window, 300
messages, verified the flow shrank) and switch on top of the fold;
fork cells fork the egress snapshot and drive the child's first turn
on the target wire with the parent's host ids.

Every cell asserts the contract a switching host relies on: 200 (never
500/unreadable), a shaped response, the upstream saw the target wire,
no pin rejection, and the op log stayed alive (pinned ids + live view
non-empty).

* gate: Lane W — mid-session wire switch against the real model (C8, PR #7684)

The gate had zero lanes that switch a session's wire lane mid-life: the
egress plane was built on the single-model single-wire assumption, and
every symptom issue in the #7439 background (#6781, #7102, #6957, #4920)
is a session that switched. C7's 12-cell matrix proves the combinations
against a fake upstream; Lane W proves the switch against the REAL model.

wire-lanes.mjs drives the installed candidate exactly like a switching
host — plugin mode, wire-aligned biliMsgIds, per-request context window
— and runs one conversation through:

  t1  @ chat wire, big window   : 12-marker corpus, must echo
  t2  @ chat wire, small window : fold pressure, no 500/422
  t3  SWITCH /v1/messages       : markers recalled THROUGH the switch
  t4  SWITCH /v1/responses      : switch #2, same contract

Hard assertions: 200 only, the upstream recorder saw the target wire's
POST (wire truth, not bili's log — #3401's lesson), the [lane-switch]
line fired with the right from->to pair, no pin-rejection/unreadable.
A missing upstream door degrades that one switch to env-blocked (the
established dsh-wire-variant rule, #3461). The egress plane rides
GATE_SNAPBASE like the P/R lanes — off = legacy-switch baseline (C3-C6
are plane-gated no-op…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant