Skip to content

[PR] Host fork completion for egress-on sessions: full table copy actually executed + authority inheritance + forkable beyond | egress-on 会话的宿主 fork 补全:整表拷贝真正执行 + 权威继承 + 超 cap 可 fork + 块账本与 kstate 归位 op log - #7664

Merged
ranxianglei merged 12 commits into
masterfrom
egress-fork-wiring
Nov 25, 2026

Conversation

@ranxianglei

@ranxianglei ranxianglei commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

egress-on 会话的宿主 fork 补全:能整表拷贝了,能继承权威了,cap 之后也能 fork 了

配套提案:discussions/7658。本 PR 只做 egress 体系(egressPlane on)下的宿主侧 fork(pi /fork → POST /__bili/plugin/fork),不碰 legacy 路径语义。

背景

egress 裁定 R-B(#7439,owner 2026-11-21)说 fork = 四表(egress_state / egress_flow / egress_block_state / egress_block_flow)整表复制、编号空间构造性自洽。存储层 egressPointForkSession 也确实这么拷——但生产主场景下这段代码根本不会被执行:egress-on 会话的 unified 腿被 egressProjectionFrozen 冻掉,sessions 行的唯一正常创建点在 ingest upsert,而被冻了。第一轮就 pin 的会话(即所有新会话)没有 sessions 行,cloneSessionRows 走进 legacy-only 早退分支,子会话靠客户端字节重新 bootstrap「能活」,但 R-B 实际被破坏:编号空间重发、retired/折叠标记丢失、血缘对(parent_session_id/fork_point_seq)不落库。悄悄降级,无日志。

三个改动

1. 让 fork 真的能走整表拷贝(src/storage/store.ts cloneSessionRows)
父会话有 egress 行但没有 sessions 行时,在同一事务内补一个父骨架行(仿 #7591 的 R3-latch 模式),然后走完整克隆流:四表 verbatim 拷贝、子行带 parent_session_id + fork_point_seq、初始 ingest 收尾统一投影。真 legacy 父(无任何 egress 行)行为不变。

2. 继承 egressAuthority + 记录 egress fork 点

  • 宿主 fork 的 metadata 白名单加入 egressAuthority(plugin.ts),子首轮从自己的流水被 serve,而不是重新 bootstrap;
  • admin 面 forkEgressSnapshot 剥掉 egressFlowUnreadable:不可读 latch 是父会话日志的失败状态,子的健康由子自己的首次恢复走查决定;
  • sessions 表新增 fork_egress_watermark(probe-first ALTER,SQLite 写值 = 拷贝时父 egress_flow 的 MAX(op_seq);MySQL 镜像列恒 NULL,该车道没有 egress 表)。fork_point_seq 装不下这个值:egress-on 父的统一腿冻着,克隆的 through-seq 是 -1 而 egress 拷贝是整表的。

3. 超 cap 的 egress-on 父重新可 fork(src/plugin.ts forkSnapshot)
原始快照被 dropOverCap 丢掉、或冷进程只能重建到冻结行时,fork 和 snapshot 路由以前一律 409 SNAPSHOT_UNAVAILABLE——尽管 egress 流水(裁定 7439-5 的内容权威)还攥着全量字节。源链末尾加 egressOpLogSource(rebuildCoreFromLog 过父流水)兜底;源链抽成 forkSourceOf 与子构造共用(原来子构造自己重算前两级、只有流水兜底时有源时 null-slice 崩 503)。

4. 块账本真正被写进 egress 记录路径(PR-A,src/storage/egress-record.ts + egress-lane-io.ts + 四条车道)
上面的「三个改动」让消息流水的 R-B 整表拷贝生效了,但 R-B 四表里还有两张块账本表(egress_block_state/flow,#7577)——它们的唯一写入点在统一 ingestSession,而 egress-on 的整体跳过统一记录,所以全武装 egress-on 会话从不写块账本,四表 fork 拷的是两张空表。修复:块账本记录挪进 recordEgressTurn(egress 车道的每轮事务里,用同一份 live 视图算块 diff,与消息流水同事务落库),四条车道(OpenAI/Anthropic/Google/responses)全部接上。账本行同时变成自包含的:摘要文本、runId、覆盖/直接消息 id、代次等直接进 payload(老行缺字段照读)。

5. egress-on 的 kstate 退役到 op log(PR-B,两个默认关的旗标,src/storage/shadow.ts + ingest.ts + egress-block.ts)
#7577 的重建公式「kstate = 消息流水 + 块流水 + 13 字段 sidecar」现在有了消费方:

  • egressKstateRetireWrites(默认 0):开之后,egress-on 会话的每轮保存不再把非残余字段(块集/messageRefs/tsStamps 等)序列化进 kstate_json——这些信息已经在块账本行和消息流水里;13 个残余字段照旧随块行走。
  • egressKstateRebuild(默认 0):开之后,冷加载时从 op log 重建块集/messageRefs/tsStamps 叠在存储 kstate 之上(缺字段以存储值为兜底,重建失败保留存储 kstate 并告警)。
  • 顺带修了一个潜在缺口:fork 骨架行没有 metadata_json,原来「egress-on」判定只看 metadata,骨架行会话冷加载会漏掉 tsStamps 派生和重建——现在「有流水行」也算 egress-on。
    回滚顺序:先回 0 RetireWrites(恢复双写),再回 0 Rebuild。

测试

新增 tests/egress-fork-host-e2e.test.ts(全链 harness,真实 HTTP + 真实 SQLite):

  • T1 fork-to-now:子流水 = 父流水 verbatim,血缘对 + fork_egress_watermark 落库;
  • T2 中点 fork:子首轮收敛一条 D-run、新尾领父高水位之后的新号、零重号、父流水不受影响、第二轮 probe 走自己的流水无降级;
  • T3 冷父:重启后 snapshot 重建 + fork 201;
  • T4 超 cap:cap 化后 snapshot 路由 200(来自流水);还攥着 pre-cap 旧快照的客户端 409 BRANCH_POINT_CONFLICT(身份稳定的字节漂移——提案:fork 继承四原则(msgid 身份轨 / lineage 编号 / 无状态账本 / 纯块拷贝) #6262 drift track 的延伸,follow-up);真实宿主流程(重新 snapshot 再 fork)201 + verbatim 拷贝;
  • T5 fork 后压缩:plugin 车道的折叠是宿主本地执行(pi 自己 fold、下轮重发折叠后的历史),T5 模拟这个真实行为——子首轮即带折叠:被覆盖格退役成一条 D-run、摘要领父高水位之后的新号、D 批触发压实(B 行)、二轮续流水高水位 +1、父流水隔离;
  • T6 真实客户端 adoption 端到端:不走手工 POST,走 tryForkAdoption(src/agent/fork-adopt.ts,dsh 扩展接入 fork 协议(stage 1/#2394 L0):fork 子会话首请求前 snapshot→match→fork 收养 #2399 客户端半段)——snapshot → (role,text) 前缀 + msgid 身份轨 → fork POST——对 egress-on 父会话,断言 adopted + 子流水 verbatim + 权威继承 + 血缘/水位落库,子首轮由自己的流水服务(一个号,零降级);
  • T7 压缩块随 fork + 双向独立折叠:父经真实工具通道(/__bili/plugin/tool compress)折自己的中段,子 fork 时内核块集逐字节继承(b1 整拷、原内容在子可取),块账本也随行:子账本在 clone 时自愈(新子会话的初始 ingest 把继承来的块集记入账本),父账本在父的下一个 egress 轮补记,两边收敛成同一行;fork 之后父再折(原会话能正常压缩)只动父流水+父账本——子流水/子块集/子账本纹丝不动;子自己再折(新会话能正常压缩、不影响原会话)只动子流水+子账本——父无泄漏(b2 不进父的块集,也不进父的账本);
  • T8 fork 后再 fork:p8 先折叠 → c8 fork 折叠态(压缩内容=摘要行,逐字节过 fork;被消费的 b1 块不继承,因为它的覆盖格已不在活前缀里——摘要行就是压缩块了)→ c8 自己一轮 → g8 在 c8 历史中点 fork。SQL 断言两级血缘链(c8←p8,g8←c8)、两级水位、g8 首轮对丢掉的尾段收 D-run、新号严格接在 c8 高水位之上、双祖先流水均不被后代触碰;
  • T9 块账本随 egress 轮落库(改动 4 的钉):全武装 egress-on 会话(plane ON + egressAuthority latch)折叠后,块账本行出现(I 行、覆盖坐标、payload 自带摘要原文)、sidecar 非空、egressBlockReplay 能从流水重建块集。修前此测试 RED(四表 fork 拷空表),修复后翻绿;
  • T10 kstate 退役闭环(改动 5 的钉,旗标门控):默认关 = 冷加载照旧用存储 kstate(现状不变);egressKstateRebuild 开 = 冷进程从 op log 逐字段重建块集/messageRefs/tsStamps,与存储值一致(骨架行会话同样命中——上面那个潜在缺口)。

gate 面(scripts/release-gate-local.mjs Lane B)+ 真模型实跑

旧 fork 车道只查「fork 后能运行」,现在追加三段:

  1. 压缩块一致:fork 行 adoptable 块数 == 父会话 fork 时刻的 active 块数(全证据文件 fork 行前最后一次 N active blocks);
  2. fork 后能压缩:fork 会话重读 corpus 触发子自己的 fold(断言 fork 子 pfa 名下出现新 acp-compress-obs shrink 行);
  3. 两代召回:子 fold 后同轮答 S07(来自 adopt 的父块)+ S40(来自子新 fold),单次模型 flake 自动重试一次。

本机真模型 gate 实跑(A/B 双车道,真推理):A 9/9,B 10/10,297s。B 车道关键行:

✅ same lineage across switch + proxy restart — pfa-… -> pfa-… (forked + adopted)
✅ forked session adopts the parent's compressed blocks 1:1 — parent=1 adopted=1
✅ forked turn completes
✅ forked session folds its own context (fork 后能压缩) — shrink …%
✅ forked fold recalls BOTH generations (S07 from parent block + S40 from new fold)

(前两轮真跑各红 1 项,均为 gate 断言自身 bug——异步日志切片竞态、父块数只解析第一块、单次模型 flake——已修,行为本身三轮全部正确。)

回归

  • fork/6262/7577 系 245 项、egress 系 128 项(1 跳)、统一存储系 73 项(2 跳)全绿 + 本文件 10/10;PR-A/PR-B 的旗标默认关,存量行为零变化;
  • bounded-storage.test.ts 6 红为环境噪音(base 3afa915 上同红,本地 /tmp 文件系统行为,非本 PR 引入)。

明确不做(提案同款边界)

  • 真点 fork(below-high-water point-reconstruction materializer)维持 deferred,本 PR 只记水位、不建点;
  • egress 平面 SQLite-only,MySQL 车道 fork_egress_watermark 恒 NULL;
  • pre-cap 旧快照 + identity drift 的 409 是钉住的现状,drift track 到 branch point 的延伸另立;
  • PR-B 两个旗标保持默认关(观察期):gate 真模型臂验证 kstate 退役行为后再谈默认值。

@ranxianglei ranxianglei changed the title egress-on 会话的宿主 fork 补全:整表拷贝真正执行 + 权威继承 + 超 cap 可 fork [PR] Host fork completion for egress-on sessions: full table copy actually executed + authority inheritance + forkable beyond | egress-on 会话的宿主 fork 补全:整表拷贝真正执行 + 权威继承 + 超 cap 可 fork Nov 24, 2026
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: egress-fork-wiring (6618014)

Latest build — install this exact version

npm install -g billion-context@0.0.11907-pr.7664.d15e11f

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
6618014 billion-context@0.0.11907-pr.7664.d15e11f build
b2b196b billion-context@0.0.11902-pr.7664.1e55b92 build
0c984d2 billion-context@0.0.11900-pr.7664.c648c6d build
b1516d4 billion-context@0.0.11898-pr.7664.e35a98f build
d6dce99 billion-context@0.0.11897-pr.7664.44f8f93 build
d36ed2f billion-context@0.0.11834-pr.7664.7def257 build
a02d24d billion-context@0.0.11822-pr.7664.3ab58e1 build
7f1eead billion-context@0.0.11809-pr.7664.3ea8c85 build
15e0b4c billion-context@0.0.11806-pr.7664.702676b build
6a01adc billion-context@0.0.11798-pr.7664.947e03f build

Download artifact

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

Install instructions are refreshed on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

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

查重: 不重复 — 镜像 open [PR] 行里无同主题(egress-on 宿主 fork)的并行 PR;#7661(egressPlane GA + 文档)是不同主题。

标签: bug + pi + scope/storage + p1(宿主 fork 是 pi 车道;根因在存储层 cloneSessionRows;fork 继承被静默破坏 = 数据完整性类 p1)。已打上,保留原 pr 标签。

结构化八问

  1. 是什么问题:egress-on 会话(第一轮就 pin 的新会话,GA 后是全部新会话)做宿主 fork 时,egress 四表的整表拷贝根本不会执行——父会话没有 sessions 行,cloneSessionRows 走进 legacy-only 早退分支,子会话靠客户端字节重新 bootstrap。后果:编号空间重发(违反 Kernel Contract)、retired/折叠标记丢失、血缘对(parent_session_id/fork_point_seq)不落库。静默降级,无日志。

  2. 什么原因导致的:egress-on 会话的 unified 腿被 egressProjectionFrozen 冻掉,sessions 行失去正常创建点;而 cloneSessionRows 的早退分支只覆盖了「有 sessions 行」的父,漏掉了「有 egress 行但无 sessions 行」的 egress-on 父。存储层的 egressPointForkSession(本应执行 R-B 整表拷贝)因此从未被调用。

  3. 影响范围与严重程度:所有 egress-on 会话的宿主 fork(pi /fork + admin forkEgressSnapshot)。GA 后 egressPlane 默认 100%,即所有新会话。严重程度 p1:子会话「能活」(靠客户端字节 bootstrap),不是完全不可用,但 R-B 裁定被破坏——编号空间重发是数据完整性缺陷(模型引用父历史 ref 可能在子会话被错误归因),且静默无日志,难以发现。

  4. 怎么修复的:三处改动,让 R-B 整表拷贝真正执行:

    • cloneSessionRows 检测到 egress-on 父(有 egress 行无 sessions 行)→ 同事务补父骨架行 → 走完整克隆流(四表 verbatim 拷贝 + 血缘对 + fork_egress_watermark + 初始 ingest);legacy-only 父(无 egress 行)行为不变。
    • 子继承 egressAuthority(首轮从自己的流水被 serve,不重新 bootstrap);fork 源链抽成 forkSourceOf 共用,末尾加 egressOpLogSource 兜底(超 cap / 冷进程可 fork)。
    • 新增 fork_egress_watermark 列(probe-first ALTER,SQLite 写父 egress_flow 的 MAX(op_seq),MySQL 恒 NULL)记录 egress fork 点。
  5. 是否有回归问题:审了 fork/6262/7577 系、egress 系、统一存储系、identity-tables 系的既有行为。本地定向跑:新 e2e 4/4 绿、egress 系 42/42 绿、统一存储系 9/9 绿。fork 系 6 红在 base 3afa915 上同样红(「parent must have folded a block」断言,本地文件系统行为),非本 PR 引入。高危模式逐项过:语义漂移——无(legacy-only 父早退分支保留);fail-fast 变吞错——无;阈值/时序/输出格式——无;缓存/重试——无。

  6. 是否破坏缓存:不涉及。不触碰缓存/重试/增量游标/去重键。fork_egress_watermark 是新的血缘记录列,不影响任何缓存失效策略。

  7. 是否改了设计方向:不涉及架构转向。本 PR 补全 egress 体系下宿主 fork 的既有设计(R-B 裁定:fork = 四表整表复制),让存储层的 egressPointForkSession 真正被执行。egress 平面的数据流与边界不变。

  8. 是否引入了新的配置:不涉及。无新 env/config/默认值。fork_egress_watermark 是存储 schema 列,不是配置项。

顺手修(独立 commit,已推 PR 分支)

  • docs(storage) 15e0b4c:骨架行注释与事实不符——原注释称「A later full ingest of the parent fills the remaining columns」,但 egress-on 父的 unified 腿冻着,永远不会 full ingest,JSON 列恒为 DDL 默认 '{}',egress op log 才是父的权威。已改为准确表述(骨架行只是血缘锚点)。

CI 状态

14 完成(4 success: docs-coverage / lane-guard / lock-sync / mysql-contract;10 skipped e2e lanes),16 进行中/排队(test shards + static-gates),0 失败。test lanes 还在跑,最终判定以 CI 为准。

合并判定

可合。本地定向测试全绿(新 e2e + egress + 统一存储),fork 系 6 红为 base 同红的环境噪音,CI 无失败。测试有牙(T1–T4 真实断言:flow verbatim 拷贝、血缘 + watermark 落库、编号零重发、父隔离、超 cap 流水兜底、pre-cap drift 409 钉住),设计符合 R-B 裁定,边界清晰(真点 fork 维持 deferred、MySQL 恒 NULL、pre-cap identity drift 409 留作 drift track follow-up)。

@ranxianglei ranxianglei added bug Something isn't working p1 pi scope/storage labels Nov 24, 2026
@ranxianglei ranxianglei changed the title [PR] Host fork completion for egress-on sessions: full table copy actually executed + authority inheritance + forkable beyond | egress-on 会话的宿主 fork 补全:整表拷贝真正执行 + 权威继承 + 超 cap 可 fork egress-on 会话的宿主 fork 补全:整表拷贝真正执行 + 权威继承 + 超 cap 可 fork + 块账本与 kstate 归位 op log Nov 24, 2026
@ranxianglei ranxianglei changed the title egress-on 会话的宿主 fork 补全:整表拷贝真正执行 + 权威继承 + 超 cap 可 fork + 块账本与 kstate 归位 op log [PR] Host fork completion for egress-on sessions: full table copy actually executed + authority inheritance + forkable beyond | egress-on 会话的宿主 fork 补全:整表拷贝真正执行 + 权威继承 + 超 cap 可 fork + 块账本与 kstate 归位 op log Nov 24, 2026
@ranxianglei ranxianglei added the ci:full Run the FULL CI matrix (all e2e lanes + 12-leg test matrix) on this PR label Nov 25, 2026
ranxianglei and others added 10 commits November 25, 2026 08:56
#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.
…s 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.
#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.
… 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.
…n 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.
…tion, 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.
… (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).
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.
…nt, 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).
…nner'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).
…K_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)

@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.

结论:可以合并(CI 绿后人合)

基于现有 egress 体系(#7439 裁定 + #7581 双时钟 + #7617 身份收拢)逐项审了这个 fork 实现,设计和机制都对齐,发现并已修 1 个小问题(commit 6618014)。

这是啥(PR 干了什么)

egress-on 会话的 fork 之前只有「表结构上会拷」,主机端链路实际走不通:

  1. full table copy 真正被执行——cloneSessionRows 现在把四张 egress 表按 flow 高水位(egressStateMaxSeq)逐字节拷给子会话,和会话克隆同一事务;无 sessions 行的 egress-on 父会话先落一行骨架锚点;子会话 fork_egress_watermark 记录拷贝水位。
  2. 超快照上限也能 fork——fork/snapshot 源链新增第三环 egressOpLogSource:client 侧 raw snapshot 丢了(cap 丢弃/冷启动)时从 op log 重建。
  3. 权限继承——子会话继承 egressAuthority,父会话的 egressFlowUnreadable 故障 latch 不继承(子会话自己的 recovery walk 判定)。
  4. 附带同一分支的两个独立小件:#7577 第二腿(egress 记录路径真正写块账本)+ #7658 kstate 归位(两个 0 默认 gate)。

根因(为什么之前走不通)

forkSnapshot 的源链只有两环:pluginSnapshot ?? reconstructRawTailForFork。egress-on 会话的 unified leg 是冻结的(persist 层 egressProjectionFrozen 早退),reconstructRawTailForFork 依赖 unified tail 行 → 恒 null;raw snapshot 一旦被 cap 丢掉,源链断掉 → 409,尽管 op log(内容权威,7439 裁定 5)里就是完整字节。fork 侧的表拷贝代码(#7439 R-B)本身早就在 cloneSessionRows 里,缺的是主机端把 egress-on 父会话送到它跟前。

设计对齐核查(基于现有 eg 体系)

  • 子会话形状 = 中途 arm 的会话形状:fork 时刻冻结的 unified leg + 逐字节 flow 拷贝(编号/退役标记不变),和「历史会话中途开 egress」的形态完全一致,不是新物种。
  • 双时钟:拷贝水位只认 flow 时钟(egressStateMaxSeq),块行按自身编号随表走——和 7581 的双时钟裁定一致;fork_egress_watermark 记录的是 flow 水位,注释写清了。
  • 源链第三环取 egressStateView(flow 重放):和 lane 每次请求读的是同一个权威源,fork 拿到的字节和会话下次出站渲染的字节同源。
  • 骨架父行 GC 安全:isEgressOnSession 有 flow 探针兜底(metadata 缺失也认 egress-on),不会被年龄清扫归档。
  • MySQL 轨:watermark 列留 NULL(egress 表只在 SQLite),克隆双生写 NULL,一致。

已修的小问题(6618014,已在分支上)

fork 路由会把损坏的 flow 漏成 503 FORK_FAILED + 原始 DB 报错。egressOpLogSource 在路由的结构化 try 外面读 view——view 是 flow 重放,日志损坏时抛 EgressStateCorruptError。复现:snapshot-capped 的 egress-on 父会话 + 删掉 flow 中间一行 → fork 返回 {"code":"FORK_FAILED","error":"EgressStateCorruptError: … op_seq jumps from 4 to 6"}(DB 内部细节直接进响应体)。修法:源链接降级为「无源」(warn 记日志——日志损坏本就是支持事故)→ 路由自己的 try 给出可诊断的 409 SNAPSHOT_UNAVAILABLE。新增 T11 端到端钉住双方向(修复前 503、修复后 409)。

非阻塞备注

  • fork_egress_watermark 目前无读取方(血缘记账,留给未来的 lazy projection)。
  • 骨架父行会出现在会话列表里(无标签行),纯观感。
  • 块账本写入是 best-effort(flow 已进账、块失败只 warn,下一轮自愈)——顺序刻意如此。

验证

  • 本机 e2e 11/11(T1–T10 原有 + T11 新增;含 T4 capped 父会话走 op log、T2 log_seq 永不重发、T6 真客户端 adoption、T9 块账本、T10 kstate 冷载重建)。
  • egress 核心批 57/57;fork 相关批 97/101——4 个红(#2408 折叠场景)在 master 23841da 原样复现,pre-existing 非回归(本机无真模型,属环境依赖)。
  • tsc 干净(除本分支之前就有的 workspace 噪音)。

CI 绿后人合即可。

@ranxianglei
ranxianglei merged commit 64b578b into master Nov 25, 2026
27 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.1326-master.64b578b (rolling master tag).

npm install -g billion-context@0.0.1326-master.64b578b  # 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 pushed a commit that referenced this pull request Nov 25, 2026
…n type (master born-red inherited from #7664)

static-gates typecheck fails on master HEAD (64b578b) itself: the #7664 T11
test declared wdb as { db: node:sqlite DatabaseSync }, but openSqliteDatabase
returns OpenedDatabase whose db is the multi-engine SqliteDatabase interface
(node:sqlite / better-sqlite3 / bun:sqlite, #57f2d554a66). The master push
workflow does not run static-gates, so the merge landed born-red for every
PR based on it.

One-line mechanical fix: type wdb as ReturnType<typeof openSqliteDatabase>.
No behavior change (types only). Verified locally: typecheck green,
tests/egress-fork-host-e2e.test.ts + tests/issue7689-incremental-egress-gate.test.ts 14/14 pass.

Inherited master red — the same fix must converge to ci-fixes/master (flagged
in the PR thread for the sentinel).
ranxianglei pushed a commit that referenced this pull request Nov 25, 2026
…iteDatabase>, not node:sqlite DatabaseSync

Inherited master born-red (static-gates typecheck): master 64b578b (#7664 egress-fork-wiring) shipped tests/egress-fork-host-e2e.test.ts:863 declaring wdb as { db: node:sqlite DatabaseSync } while openSqliteDatabase (src/storage/driver.ts:473) returns the multi-engine OpenedDatabase wrapper since the bun:sqlite storage refactor (57f2d55). tsc TS2322/TS18047 at 884/885/887 on every PR head rebased past that merge; reproduced on clean master 9c8307c worktree. Same one-line fix as landed in PR #7690 (5c269ad) and #5311 (2c6d193); requested sentinel convergence into ci-fixes in #4599.
ranxianglei pushed a commit to Maziar123/billion-context that referenced this pull request Nov 25, 2026
…ted master red)

tests/egress-fork-host-e2e.test.ts:863 annotated wdb as
{ db: DatabaseSync } | null, but openSqliteDatabase returns
OpenedDatabase (db: SqliteDatabase) — TS2322 at :884 plus the two
TS18047 cascades at :885/:887. File is byte-identical to origin/master:
master is born-red on typecheck since 6618014 (ranxianglei#7664 merge,
2026-11-25 09:41 +0800), tracked in ranxianglei#4599. One-line annotation fix,
same as the sibling PRs (ranxianglei#5284/ranxianglei#7690/ranxianglei#6347/ranxianglei#5398/ranxianglei#5477); sentinel
should converge this into ci-fixes/master.
ranxianglei pushed a commit that referenced this pull request Nov 25, 2026
…ter-born-red since #7664)

tests/egress-fork-host-e2e.test.ts:863 declares wdb as raw node:sqlite
DatabaseSync, but openSqliteDatabase returns OpenedDatabase (db is the
multi-engine SqliteDatabase wrapper) — TS2322 + 2x TS18047 on every
static-gates leg. The file is byte-identical to master (not in this PR's
delta); reproduced on a clean upstream/master worktree. Same signature as
the inherited reds reported in #4599 (floors 1697-1711); ci-fixes
(f013a82) is 107 commits behind master and lacks this fix, so per the
2026-10-13 few-line-fix policy the annotation is fixed here on the PR
branch. Type-only change, zero runtime effect; typecheck exit 0 +
egress-fork 11/11. Sentinel: please converge the same line into
ci-fixes/master.
ranxianglei pushed a commit that referenced this pull request Nov 25, 2026
…turn (master born-red typecheck)

wdb was declared { db: DatabaseSync } but openSqliteDatabase returns
OpenedDatabase (db + engine + source): TS2322 at :884, TS18047 at :885/:887.
Red on master since 6618014 (#7664), breaking static-gates on every PR
merge ref (CI master control #4599). Same fix shape as the #5477 branch
(f931c86).
ranxianglei pushed a commit that referenced this pull request Nov 25, 2026
Master moved 0.0.207 -> 0.0.210 (egress log_seq renumber to kernel citation #7691, egress-fork wiring #7664, egress-on kstate retirement #7658 PR-B, ci-full gates). Resolved kernel version to 0.0.211 (master's 0.0.210 + 1 for this PR's kernel/src change, per Kernel Boundary rule 2). hide-consumed.ts and its tests auto-merged cleanly — master has not touched them since the merge-base. Verified locally on the merged head: kernel suite 1679/1679 green (incl. hide-consumed-stub + truncate-surrogates), host stub-resubmission-guard 5/5 green.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working ci:full Run the FULL CI matrix (all e2e lanes + 12-leg test matrix) on this PR p1 pi scope/storage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant