Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions docs/egress-block-flow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Egress block flow/state: block canonical history + checkpoint retirement

> #7577 (follow-up to #7439 / #6785). 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).

## Tables

| Table | Role | PK |
|---|---|---|
| `egress_block_flow` | Append-only block canonical history (I/U/B rows) | `(session_id, op_seq)` |
| `egress_block_state` | Read replica: latest snapshot per block | `(session_id, block_id)` |

**Dual clocks** (owner ruling 2026-11-24 — the original shared-clock design was
rejected because it 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
would start two op_seqs past the last flow row and every egress read's
`op_seq === prevSeq + 1` check would throw):

- The block tables number **themselves**: `egress_block_flow.op_seq` is dense
within its own table, issued from `MAX(egress_block_flow) + 1`. What the
block table does internally (compress, transform, renumber) is
self-contained; it never touches the flow number pool.
- `egress_flow` keeps its **exclusive** number pool and its density invariant,
untouched.
- Every block row carries **`flow_op_seq`** — a pointer to the flow clock:
`egress_flow`'s `MAX(op_seq)` at the moment the row was written (it never
decreases, so the rows with `flow_op_seq <= X` form 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 message view with the block set at
that moment.

### Row types

| row_type | Meaning |
|---|---|
| `I` | Block born (one fold). Payload = full snapshot. |
| `U` | State change (superseded / reaped / content revision). Payload = full snapshot (no diff). |
| `B` | Compaction base. Payload = `{entries: [{blockId, snapshot}], watermark}`. |

### Snapshot shape

```json
{
"tier": 1,
"startMsgid": "m00001",
"startSeq": 1,
"endMsgid": "m00005",
"endSeq": 5,
"supersedesBlockId": null,
"active": true,
"reaped": false,
"one": "{\"text\":\"...\",\"count\":3}",
"full": "{\"text\":\"...\",\"count\":5}"
}
```

Self-contained bytes (D2): zero content-CAS refs in both tables.

## kstate sidecar

Every I/U/B row carries a `kstate_json` column: the bounded residual snapshot at write time (<2KB). The 13 residual fields: `viewLatches`, `emergencyTruncateLatch`, `absorbed`, `rules`, `nudge`, `stats`, `terminalStreak`, `nextRuleId`, `deadRefs`, `sweptOrphanCallIds`, `renderDeferredRefs`, `refLedgerAligned`, `timestampsHighWaterRefSeq`. `lastPassIds` is excluded (self-heal field).

Replay takes the last sidecar at or before the watermark (else fresh default).

## Checkpoint retirement (D5)

For egress-on sessions:
- `maybeCutForkBaseAsync` / `createReplica` skip (no fork_base/replica/auto rows).
- Admin `POST /__bili/replicas` takes the point-fork path for an egress-on parent: `201 {ok, pointFork, sessionId, opSeq, restoredFrom}` — a fresh, independent child session (the parent is never mutated, and the child is a snapshot, not a live alias). Egress-off parents keep the checkpoint behavior; a below-high-water `opSeq` is rejected (400) because it needs the point-reconstruction materializer (follow-up).
- `persistForkSession` / `cloneSessionRows` use `egressPointFork` (the four tables `egress_state`, `egress_flow`, `egress_block_state`, `egress_block_flow`). The watermark is the **flow clock** (`egressStateMaxSeq` — the reference clock under dual clocks). Fork-to-now (`wm` >= flow high water) copies all four directly (SQL `INSERT…SELECT`); a true point fork (`wm` < flow high water) copies flow rows filtered by `op_seq <= wm` and block rows filtered by `flow_op_seq <= wm`, then rebuilds the state replicas by replaying those rows (a direct copy filtered by the block clock would align two unrelated clocks).

## kstate trim (D4)

For egress-on sessions, `tsStamps`, `tokenSnapshot`, and `lastPassIds` are excluded from the `sessions.kstate_json` column (derivable from the egress log). The legacy path is byte-identical.

On load, the store re-derives `tsStamps` for an egress-on session whose column has no value: each I row's `msgid` is the kernel raw id (the `tsStamps` key) and its `ts` is the first-seen wall clock. A persisted value always wins — the derive only fills the gap the trim left.

## Gating

Everything is under the `egressPlane` master switch. Zero new config items. The egress dual tables were never shipped (dev-DB DROP-recreate precedent); the block tables follow the same pattern. The shipped tables (`blocks`, `orphan_blocks`, `checkpoints`) get write-stop + read-path switch only (no DROP; physical DROP is a follow-up with version bump + 100% rollout).
66 changes: 66 additions & 0 deletions docs/egress-block-flow.zh-CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Egress 块流/状态:块正史 + checkpoint 退役

> #7577(#7439 / #6785 后续)。新增两张表(`egress_block_flow`、`egress_block_state`),使块集合成为与消息视图(`egress_flow`/`egress_state`)平级的一等 op-log 公民。对 egress-on 会话退役 checkpoint(fork_base/replica/auto),改用点位 fork(4 表拷贝)。对 egress-on 会话裁剪 kstate 列(tsStamps/tokenSnapshot/lastPassIds 可从 flow 回放推导)。

## 表

| 表 | 角色 | 主键 |
|---|---|---|
| `egress_block_flow` | 追加式块正史(I/U/B 行) | `(session_id, op_seq)` |
| `egress_block_state` | 读副本:每块最新快照 | `(session_id, block_id)` |

**双时钟**(owner 裁定 2026-11-24——原“共享时钟”设计被否:折叠轮的块行在 SAVE 时落盘,晚于同轮的消息行,下一条消息会从“最后一条 flow 行 +2”处开始,导致每次 egress 读的 `op_seq === prevSeq + 1` 稠密校验全部报错):

- 块表**自己发号**:`egress_block_flow.op_seq` 在表内稠密,从 `MAX(egress_block_flow) + 1` 发出。块表内部怎么压缩、变换、重编号都是自成体系,不碰 flow 的号池。
- `egress_flow` 保留**独占**号池与稠密不变量,零改动。
- 每条块行携带 **`flow_op_seq`**——指向 flow 时钟的指针:写入时刻 `egress_flow` 的 `MAX(op_seq)`(只增不减,故 `flow_op_seq <= X` 的行构成前缀)。点位 fork 在 flow 水位 `X` 处:拷贝 `op_seq <= X` 的 flow 行 + `flow_op_seq <= X` 的块行,消息视图与块集合在该时刻对齐。

### 行类型

| row_type | 含义 |
|---|---|
| `I` | 块诞生(一次折叠)。payload = 完整快照。 |
| `U` | 状态变更(被取代 / 收割 / 内容修订)。payload = 完整快照(无 diff)。 |
| `B` | 压缩基线。payload = `{entries: [{blockId, snapshot}], watermark}`。 |

### 快照形状

```json
{
"tier": 1,
"startMsgid": "m00001",
"startSeq": 1,
"endMsgid": "m00005",
"endSeq": 5,
"supersedesBlockId": null,
"active": true,
"reaped": false,
"one": "{\"text\":\"...\",\"count\":3}",
"full": "{\"text\":\"...\",\"count\":5}"
}
```

自包含字节(D2):两表中零 content-CAS 引用。

## kstate 边车

每个 I/U/B 行携带 `kstate_json` 列:写入时刻的有界残差快照(<2KB)。13 个残差字段:`viewLatches`、`emergencyTruncateLatch`、`absorbed`、`rules`、`nudge`、`stats`、`terminalStreak`、`nextRuleId`、`deadRefs`、`sweptOrphanCallIds`、`renderDeferredRefs`、`refLedgerAligned`、`timestampsHighWaterRefSeq`。`lastPassIds` 被排除(自愈字段)。

回放取水线之前(含)最后一个边车(否则用全新默认值)。

## Checkpoint 退役(D5)

对 egress-on 会话:
- `maybeCutForkBaseAsync` / `createReplica` 跳过(不建 fork_base/replica/auto 行)。
- Admin `POST /__bili/replicas` 对 egress-on 父会话走点 fork:`201 {ok, pointFork, sessionId, opSeq, restoredFrom}` —— 生成一个全新的独立子会话(父会话永不被改,子会话是快照而非活别名)。egress-off 父保留 checkpoint 行为;低于高水位的 `opSeq` 被拒绝(400),因为它需要点位重构物化器(后续项)。
- `persistForkSession` / `cloneSessionRows` 使用 `egressPointFork`(四张表 `egress_state`、`egress_flow`、`egress_block_state`、`egress_block_flow`)。水位是 **flow 时钟**(`egressStateMaxSeq`——双时钟下的参考时钟)。fork-to-now(`wm` >= flow 高水位)直接拷贝全部四表(SQL `INSERT…SELECT`);真点位 fork(`wm` < flow 高水位)按 `op_seq <= wm` 拷 flow 行、按 `flow_op_seq <= wm` 拷块行,再回放重建状态副本(直接按块表自己的 op_seq 过滤会把两个无关时钟对齐)。

## kstate 裁剪(D4)

对 egress-on 会话,`tsStamps`、`tokenSnapshot`、`lastPassIds` 从 `sessions.kstate_json` 列中排除(可从 egress 日志推导)。legacy 路径字节级不变。

加载时,store 为「列里无值」的 egress-on 会话重新推导 `tsStamps`:每个 I 行的 `msgid` 就是内核 raw id(`tsStamps` 的键),其 `ts` 是首见墙钟。已持久化的值永远优先 —— 推导只补裁剪留下的缺口。

## 门控

全部在 `egressPlane` 主开关下。零新增配置项。egress 双表从未发布(dev-DB DROP-recreate 先例);块表遵循同一模式。已发布的表(`blocks`、`orphan_blocks`、`checkpoints`)只做停写 + 读路径切换(不 DROP;物理 DROP 是后续工作,需版本 bump + 100% 灰度)。
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@
| [auto-merge-guardrails](auto-merge-guardrails.md) | Evidence appendix behind §7 of `AGENTS.md` (AI auto-dev review history) |
| [unified-loop-spec](unified-loop-spec.md) | Historical design: unified compress-loop spec (implemented; code is the source of truth) |
| [PR #6785 in depth](pr-6785-unified-storage-and-flows.md) / [中文](pr-6785-unified-storage-and-flows.zh-CN.md) | Review-grade walkthrough of PR #6785: unified-storage tables (schema v12) / implementation logic / per-turn data flow / full switch ledger + measured validation (#5874/#7064/#7398/#4491) + round 2: op-log canonical numbering, lazy projection, window re-anchor, resident perf gate (KDD #23) |
| [egress block flow](egress-block-flow.md) / [中文](egress-block-flow.zh-CN.md) | Block canonical history + checkpoint retirement (#7577): `egress_block_flow`/`egress_block_state` tables, kstate sidecar, point-fork, kstate trim |
1 change: 1 addition & 0 deletions docs/index.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@
| [auto-merge-guardrails](auto-merge-guardrails.md) | `AGENTS.md` §7 背后的证据附录(AI 自动开发评审史) |
| [unified-loop-spec](unified-loop-spec.md) | 历史设计:统一压缩循环规格(已落地,以代码为准) |
| [PR #6785 详尽梳理](pr-6785-unified-storage-and-flows.zh-CN.md) / [EN](pr-6785-unified-storage-and-flows.md) | PR #6785 审查级梳理:统一存储表结构(schema v12)/ 实现逻辑 / 逐轮数据流转 / 开关总账 + 实测验证(#5874/#7064/#7398/#4491)+ 第 2 轮:op log 正史编号、惰性投影、窗口 re-anchor、常驻性能门(KDD #23) |
| [egress 块流/状态](egress-block-flow.zh-CN.md) / [EN](egress-block-flow.md) | 块正史 + checkpoint 退役(#7577):`egress_block_flow`/`egress_block_state` 表、kstate 边车、点位 fork、kstate 裁剪 |
1 change: 1 addition & 0 deletions reference/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ billion-context/
│ │ ├── engine-bootstrap.ts # Self-downloads pinned better-sqlite3 prebuilt when no engine exists
│ │ ├── identity.ts # messages-table identity hash: strips position metadata (#4390)
│ │ ├── egress-state.ts # Egress op-log outbound view: dual-table state+flow, replay, compaction, any-seq rollback (#7398)
│ │ ├── egress-block.ts # Egress block op-log: dual-table block state+flow, replay, compaction, point-fork, kstate sidecar (#7577, rollout egressPlane)
│ │ ├── egress-record.ts # Egress op-log RECORDING: build the outbound view rows, diff vs prev, append sparse ops, fold-triggered compaction (#7398, rollout egressPlane)
│ │ ├── egress-serve.ts # Egress op-log SERVE: rebuild the outbound elements from the self-contained op-log rows (byte-identity chain, ladder recovery, whole-turn degrade) + shadow byte comparison (#7398, rollout egressPlane)
│ │ ├── ingest.ts # Legacy → unified row mapping + legacy view rebuild (#2671)
Expand Down
67 changes: 67 additions & 0 deletions src/persist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2805,6 +2805,9 @@ export class SessionStore {
* backend queue. Fire-and-forget from the save paths. */
private async maybeCutForkBaseAsync(session: Session): Promise<void> {
if (!this.shadow || this.shadow.stats.disabled) return;
// #7577 D5: egress-on sessions fork via point copy (egressPointFork),
// not a fork_base checkpoint — skip the checkpoint cut entirely.
if (session.metadata["egressAuthority"] === true) return;
const retained = session.metadata.publicForkReceipt !== undefined
|| session.metadata.publicSnapshotRetained === true;
if (!retained || !Array.isArray(session.pluginSnapshot) || session.pluginSnapshot.length === 0) return;
Expand Down Expand Up @@ -2850,6 +2853,14 @@ export class SessionStore {
if (!view) throw new Error(`[storage] session ${sessionId} is not in the unified index (unknown, or never persisted under this mode)`);
record = viewToRecord(view);
}
// #7577 D5: egress-on sessions do not use checkpoints — the admin
// API does a point copy (egressPointFork) instead. Guard on the
// PERSISTED record's metadata (resident build or unified view, both
// carry it) so a stray call cannot create a checkpoint for an
// egress-on session whether or not it is currently loaded.
if (record.metadata?.["egressAuthority"] === true) {
throw new Error(`[storage] createReplica: session ${sessionId} is egress-on — use the point-fork path instead`);
}
// CCR originals must survive the rollback the replica exists for:
// the live content-store sidecar (not just what the unified index
// captured) is the authoritative envelope — stamp it into the frozen
Expand Down Expand Up @@ -2878,6 +2889,62 @@ export class SessionStore {
return row;
}

/** #7577 D5 / review (c): egress-on sessions have no checkpoint substrate
* (checkpoints are retired for them), so the admin "create replica" path
* FORKS THE SESSION TO NOW instead — a full copy as of the current
* flow high water (the FLOW clock is the reference clock — dual clocks,
* owner ruling 2026-11-24): the four egress op-log tables (the content
* authority; block rows align via their flow_op_seq pointer) plus the
* unified kernel-state rows. The child is a new, loadable session; the
* parent is never mutated. Forking at an EARLIER op_seq is deliberately
* NOT supported: the unified kernel-state rows only exist at *now*, so a
* point below the high water would pair content-at-X with
* kernel-state-at-now (inconsistent). That needs the point-reconstruction
* materializer — a follow-up, not this PR. */
async forkEgressSnapshot(sessionId: string, childId?: string): Promise<{ childId: string; opSeq: number }> {
await this.ready();
// Resident if it is actively loaded; otherwise load the persisted
// (idle) session — a point-fork of an egress-on session does not need
// the parent to be in-flight, only present.
const parent = peekSession(sessionId) ?? (await this.loadAsync(sessionId));
if (!parent) throw new Error(`[storage] forkEgressSnapshot: session ${sessionId} does not exist`);
if (parent.metadata["egressAuthority"] !== true) throw new Error(`[storage] forkEgressSnapshot: session ${sessionId} is not an egress-on session`);
const cid = childId ?? `fork-${randomUUID()}`;
if (peekSession(cid) !== undefined || (await this.loadAsync(cid))) throw new Error(`[storage] forkEgressSnapshot: child ${cid} already exists`);
// Deep-copy the mutable fields: persistForkSession mutates the child
// (fork-base receipt, tail fold, resident drops), so the child must
// not alias the parent's state/metadata/lock chain. `transient` is
// in-flight request state — never carried into a fork child. The
// contentStore is shared by design: saveContentStore snapshots it to
// disk under the child's id, and dropResidentContentStore reassigns
// the CHILD's field only (the parent keeps its own handle).
const child: Session = {
...parent,
id: cid,
meta: structuredClone(parent.meta),
stats: structuredClone(parent.stats),
metadata: { ...parent.metadata, derivedFromSessionId: sessionId },
state: structuredClone(parent.state),
blockContents: new Map([...(parent.blockContents ?? new Map()).entries()].map(([k, v]) => [k, structuredClone(v)])),
lastMessages: parent.lastMessages ? structuredClone(parent.lastMessages) : undefined,
pluginSnapshot: parent.pluginSnapshot ? structuredClone(parent.pluginSnapshot) : undefined,
decompositionLog: parent.decompositionLog ? structuredClone(parent.decompositionLog) : undefined,
transient: undefined,
lockChain: undefined,
persisted: false,
inFlight: 0,
pendingRetrievals: [],
};
await this.persistForkSession(sessionId, child);
// #7577 (dual clocks, owner ruling 2026-11-24): report the FLOW high
// water (egress_flow's MAX) — the reference clock for point forks.
// Block rows align to it via their flow_op_seq pointer; the block
// table's own op_seq space is self-contained and not part of the
// watermark.
const opSeq = this.egressOpLogStore()?.egressStateMaxSeq(cid) ?? 0;
return { childId: cid, opSeq };
}

async listReplicas(sessionId?: string): Promise<CheckpointRow[]> {
await this.ready();
return this.liveShadow().listCheckpointsAsync(sessionId);
Expand Down
Loading
Loading