From 6c233cf91517eb518cca83f364ad928d1985df44 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Fri, 27 Nov 2026 14:04:25 +0800 Subject: [PATCH 1/3] fix: egress row addressing moves from msgid to self-issued rids (#7773 follow-up, owner ruling 2026-11-27) D-row payloads carried msgid endpoints ({"start":"h_...","end":"b6ab..."}): content-hash ids when the host id was unavailable, potentially-colliding client ids, and ambiguous after fold re-homing (one msgid can occupy a slot twice in history). The persistent log must address rows by an id we issue ourselves: dense per session (MAX(rid)+1), append-only flow never deletes, so a retired rid can never be re-issued. - egress_state PK (session_id, msgid) -> (session_id, rid) + msgid index - egress_flow gains a rid column (I/U rows carry it, D rows NULL); payload addressing: I {after: rid|null}, D {start: rid, end: rid}, U +rid (the target msgid stays as a cross-check) - invariant 5 (invariants suite + per-write assert): log addressing is rid, never msgid; the state<->flow twin check joins on (rid, log_seq) - the diff (prev<->next view match) still keys on msgid: that is the kernel identity seam (KDD contract) and only the persistent layer de-msgid-ifies. New case: a colliding msgid gets a fresh rid and MAX(rid)+1 stays unambiguous - frontier/high-water = egressRowHighWater = MAX(rid) over the flow (U rows carry a rid, D rows NULL). log_seq cannot serve as the row id: retired-slot re-homing legitimately re-cites an old log_seq - fork (to-now full copy / point-in-time prefix) copies rid verbatim; the migrate probe adds the rid-less shape (never shipped: first-open rebuild, docs/egress-plane.md section 7) - docs: egress-plane en/zh (tables, invariants, ruling ledger, handover manual), architecture/storage en/zh/ja, deprecations en/zh register the change with the rebuild handoff --- docs/architecture/storage.ja.md | 2 +- docs/architecture/storage.md | 2 +- docs/architecture/storage.zh-CN.md | 2 +- docs/deprecations.md | 5 +- docs/deprecations.zh-CN.md | 5 +- docs/egress-plane.md | 9 +- docs/egress-plane.zh-CN.md | 11 +- src/storage/egress-block.ts | 12 +- src/storage/egress-record.ts | 8 +- src/storage/egress-state.ts | 280 ++++++++++++------ src/storage/schema.ts | 15 +- src/storage/store.ts | 7 + tests/eg-sweep-egress-identity.test.ts | 2 +- tests/egress-authority-ladder.test.ts | 2 +- tests/egress-block.test.ts | 26 +- tests/egress-invariants-7773.test.ts | 10 +- tests/egress-lazy-projection.test.ts | 2 +- tests/egress-oplog-lifecycle.test.ts | 8 +- tests/egress-state.test.ts | 214 +++++++------ tests/identity-tables-consolidate.test.ts | 10 +- tests/issue7574-egress-log-integrity.test.ts | 10 +- ...issue7574-storage-schema-followups.test.ts | 2 +- tests/issue7577-egress-kstate-derive.test.ts | 16 +- 23 files changed, 402 insertions(+), 258 deletions(-) diff --git a/docs/architecture/storage.ja.md b/docs/architecture/storage.ja.md index de9ce3f7b1..7ff7dda7ca 100644 --- a/docs/architecture/storage.ja.md +++ b/docs/architecture/storage.ja.md @@ -26,7 +26,7 @@ **整合性。** チェックポイントフレーム署名 + S4 行ごとのチェックサム; 判定はチェーンを信頼し、コンテンツの類似性を決して信頼しない。任意の静止時エンコーディング: AES-256-GCM (#708) + zstd (#1080)。`src/storage/mysql.ts` 配下の mysql ダイアレクトはテストミラーのみである(mysql-contract CI レーン) — SQLite が本番ストレージであり続ける。 -**egress プレーン(KDD #23/#24、#7439/#7577/#7591/#7773 — 出向会話 op log)。** `egress_flow`(SQLite レーンのみ、ゲート `rollout.features.egressPlane`)は各セッションの出向ビューの **append-only** I/D/U op log を保持し、行は自己完結(バイトは行に乗る、content CAS 不要)。flow のキーは `(session_id, op_seq)`(稠密な行カーソル、復旧/切り詰め鍵)、I 行はさらに `log_seq`(正規メッセージ番号、再発行なし)を持つ;フロンティアは flow 上の `MAX(log_seq)`(退役した `B` ベース行の `highWater` payload は消滅、#7773)。**`egress_state` は物化ライブビュー**(#7773):PK `(session_id, msgid)`、`pos` 順;各 append は同一トランザクション内で op を行に適用(I 挿入+シフト、U その場更新、D 物理削除+シフト)、サービスコピーは構造上ライブビューの大きさに有界 — ベース行も圧縮も op ミラーもない。egress-on セッションでは op log が**唯一の**正規メッセージ権威:出向バイトはそこから配信、pin チャネルは messages レジャーではなく物化 state を読む、ターンごとの統一 ingest は停止(messages は**遅延射影**に格下げ、ロールバック/web 読み取り/復元時に一括再構築)、セッション JSON エンベロープは bootstrap で凍結。復旧:state コピーが損傷したら**全履歴リプレイで再構築**しそのまま配信(flow が権威);flow 自体がリプレイ不能なら `recoverEgressBase` が全履歴 walk を 1 度だけ実行(`egressFlowWalkBack`)— 最新健全プレフィックスまで尾を切り詰め;健全な点が皆無 ⇒ ターンはハード失敗(裁定 7439-5)で、クライアントバイトに劣化することはない。裁定 7439-2 は読み書き側を blocks テーブル本体に置く:`summary_bytes` がブロック要約をインライン化(読取り側はこれを優先、content CAS は legacy フォールバックのみ)、`start_msgid`/`end_msgid` は折りたたみ時にフローの msgid 座標へ一度だけ整列 — フロー記録セッションのみ、他は NULL。**#7581 がブロックライフサイクルログ**(`egress_block_flow`/`egress_block_state`)**を二重クロックで追加** — ブロックテーブルは自分自身を番号付けし、各行は `flow_op_seq` でフロークロックを指す;reap はそのブロックの最終スナップショットを携えた `D` 行で、state 行は物理削除(#7773);フロークローク W の定点 fork:フロー行 `op_seq <= W`・ブロック行 `flow_op_seq <= W` をコピーし、**両 state テーブルを W までリプレイして物化**(任意のポイント可 — 「最新ベース未満」ゲートは廃止);egress-on の checkpoint はこの定点 fork に退役。**#7617 は ID を統合**:egress-on の stage-0 は状態なし(`MAX(op_seq)`/flow の `MAX(log_seq)` からの境界、l1 カーソルも resync もない)、R3 故障 latch は `sessions.r3_latched_at`(legacy l1 列との二重キャリアで読替/クリア)、egress-on セッションは年齢 GC から除外され手動 archive は拒否(アーカイブ形式が op log を載せるまで)。**番号付け(2026-11-25、[egress-plane.md](../egress-plane.md) §10)**:`log_seq` がカーネル引用番号そのもの(`mNNNNN` = m + log_seq、system 行 = 0);arm 時の一括 backfill で op log が完全履歴になり、`refs` 書き込み経路は egress-on で退役、kstate overlay の refs 再構築が正当経路に。**構造不変条件(#7773 §6、毎回の書き込み後にアサート、両プレーン)**:flow 行数は減少しない・state 行数 == ライブビュー長さ・最大 value == 歴史上の最大単一行・行文字列はちょうど I/D/U(メッセージ)/ I/U/D(ブロック)— スイート `tests/egress-invariants-7773.test.ts`。全体:[PR #6785 ドキュメント §6](../pr-6785-unified-storage-and-flows.md#6-round-2) ・ブロック:[egress-block-flow.md](../egress-block-flow.md) ・一箇所:[egress-plane.md](../egress-plane.md)。 +**egress プレーン(KDD #23/#24、#7439/#7577/#7591/#7773 — 出向会話 op log)。** `egress_flow`(SQLite レーンのみ、ゲート `rollout.features.egressPlane`)は各セッションの出向ビューの **append-only** I/D/U op log を保持し、行は自己完結(バイトは行に乗る、content CAS 不要)。flow のキーは `(session_id, op_seq)`(稠密な行カーソル、復旧/切り詰め鍵)、I 行はさらに `log_seq`(正規メッセージ番号、再発行なし)を持つ;フロンティアは flow 上の `MAX(log_seq)`(退役した `B` ベース行の `highWater` payload は消滅、#7773)。**`egress_state` は物化ライブビュー**(#7773):PK `(session_id, rid)`、`pos` 順;各 append は同一トランザクション内で op を行に適用(I 挿入+シフト、U その場更新、D 物理削除+シフト)、サービスコピーは構造上ライブビューの大きさに有界 — ベース行も圧縮も op ミラーもない。ログと state キーの行アドレスは再発行されない稠密な `rid` で、msgid ではない(owner 裁定 2026-11-27、#7773 続行:msgid はカーネル同一性 — content-hash 代理・衝突可能・折りたたみ後にどの発生を指すか曖昧 — 、rid は自発行。D 端点 / U 目標 / I アンカーは全て rid を参照し、`idx_egress_state_msgid` が msgid 検索に供される)。egress-on セッションでは op log が**唯一の**正規メッセージ権威:出向バイトはそこから配信、pin チャネルは messages レジャーではなく物化 state を読む、ターンごとの統一 ingest は停止(messages は**遅延射影**に格下げ、ロールバック/web 読み取り/復元時に一括再構築)、セッション JSON エンベロープは bootstrap で凍結。復旧:state コピーが損傷したら**全履歴リプレイで再構築**しそのまま配信(flow が権威);flow 自体がリプレイ不能なら `recoverEgressBase` が全履歴 walk を 1 度だけ実行(`egressFlowWalkBack`)— 最新健全プレフィックスまで尾を切り詰め;健全な点が皆無 ⇒ ターンはハード失敗(裁定 7439-5)で、クライアントバイトに劣化することはない。裁定 7439-2 は読み書き側を blocks テーブル本体に置く:`summary_bytes` がブロック要約をインライン化(読取り側はこれを優先、content CAS は legacy フォールバックのみ)、`start_msgid`/`end_msgid` は折りたたみ時にフローの msgid 座標へ一度だけ整列 — フロー記録セッションのみ、他は NULL。**#7581 がブロックライフサイクルログ**(`egress_block_flow`/`egress_block_state`)**を二重クロックで追加** — ブロックテーブルは自分自身を番号付けし、各行は `flow_op_seq` でフロークロックを指す;reap はそのブロックの最終スナップショットを携えた `D` 行で、state 行は物理削除(#7773);フロークローク W の定点 fork:フロー行 `op_seq <= W`・ブロック行 `flow_op_seq <= W` をコピーし、**両 state テーブルを W までリプレイして物化**(任意のポイント可 — 「最新ベース未満」ゲートは廃止);egress-on の checkpoint はこの定点 fork に退役。**#7617 は ID を統合**:egress-on の stage-0 は状態なし(`MAX(op_seq)`/flow の `MAX(log_seq)` からの境界、l1 カーソルも resync もない)、R3 故障 latch は `sessions.r3_latched_at`(legacy l1 列との二重キャリアで読替/クリア)、egress-on セッションは年齢 GC から除外され手動 archive は拒否(アーカイブ形式が op log を載せるまで)。**番号付け(2026-11-25、[egress-plane.md](../egress-plane.md) §10)**:`log_seq` がカーネル引用番号そのもの(`mNNNNN` = m + log_seq、system 行 = 0);arm 時の一括 backfill で op log が完全履歴になり、`refs` 書き込み経路は egress-on で退役、kstate overlay の refs 再構築が正当経路に。**構造不変条件(#7773 §6、毎回の書き込み後にアサート、両プレーン)**:flow 行数は減少しない・state 行数 == ライブビュー長さ・最大 value == 歴史上の最大単一行・行文字列はちょうど I/D/U(メッセージ)/ I/U/D(ブロック)— スイート `tests/egress-invariants-7773.test.ts`。全体:[PR #6785 ドキュメント §6](../pr-6785-unified-storage-and-flows.md#6-round-2) ・ブロック:[egress-block-flow.md](../egress-block-flow.md) ・一箇所:[egress-plane.md](../egress-plane.md)。 ## 厳格な不変条件(これに触れる前に AGENTS.md を参照すること) diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index c1f542a4a0..32f3e9274b 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -26,7 +26,7 @@ Everything that must survive a process restart lands in ONE SQLite file: session **Consistency.** Checkpoint frame signatures + S4 per-row checksums; verdicts trust the chain, never content similarity. Optional at-rest encoding: AES-256-GCM (#708) + zstd (#1080). The mysql dialect under `src/storage/mysql.ts` is a TEST MIRROR only (the mysql-contract CI lane) — SQLite remains the production store. -**Egress plane (KDD #23/#24, discussions #7439/#7577/#7591/#7773 — the outbound conversation op log).** `egress_flow` (SQLite lane only, gate `rollout.features.egressPlane`) holds the **append-only** I/D/U op log of each session's outbound view; rows are self-contained (bytes ride the row, no content CAS). The flow keys on `(session_id, op_seq)` (dense row cursor, recovery/truncation key) and I rows additionally carry `log_seq` — the canonical, never-reissued message number; the frontier is `MAX(log_seq)` on the flow (the retired `B` base row's `highWater` payload is gone, #7773). **`egress_state` is the MATERIALIZED live view** (#7773): PK `(session_id, msgid)`, `pos`-ordered; every append applies its ops to the rows in the same transaction (I inserts + shifts, U in-place, D physically deletes + shifts), so the serving copy is bounded by the live view's size by construction — there is no base row, no compaction, no op mirror. For egress-on sessions the op log is the SOLE canonical message authority: outbound bytes are served from it, the pin channel reads the materialized state instead of the messages ledger, the per-turn unified ingest stops (messages demoted to a LAZY projection, rebuilt one-time on rollback/web-read/restore) and the session JSON envelope freezes at bootstrap. Recovery: a damaged state copy is **rebuilt by full-history replay** and served as-is (the flow is the authority); if the flow itself does not replay, `recoverEgressBase` does ONE full-history walk (`egressFlowWalkBack`) — the newest healthy prefix truncates the tail; no healthy point ⇒ the turn hard-fails (ruling 7439-5), never degrades to client bytes. Ruling 7439-2 lands the read/write side on the blocks table itself: `summary_bytes` inlines the block summary (readers prefer it, the content CAS keeps its role only as the legacy fallback), and `start_msgid`/`end_msgid` align the block to the flow's msgid coordinates once at fold time — for flow-recorded sessions, NULL otherwise. **#7581 added the block lifecycle log** (`egress_block_flow`/`egress_block_state`) on **dual clocks** — the block tables number themselves, each row pointing at the flow clock via `flow_op_seq`; reap is a `D` row carrying the block's full terminal snapshot with the state row physically deleted (#7773); a point fork at flow watermark W copies flow rows `op_seq <= W` and block rows `flow_op_seq <= W`, then **materializes both state tables by replay to W** (any point — the "below the newest base" gate is gone); checkpoints for egress-on retired in favor of this point-fork. **#7617 consolidated identity**: egress-on stage-0 is stateless (frontiers from `MAX(op_seq)` / the flow's `MAX(log_seq)`, no l1 cursor, no resync), the R3 fault latch lives in `sessions.r3_latched_at` (dual-carrier read/clear with the legacy l1 column), and egress-on sessions are excluded from age GC and refused on manual archive until the archive format carries the op log. **Renumber (2026-11-25, [egress-plane.md](../egress-plane.md) §10):** `log_seq` IS the kernel citation number (`mNNNNN` = m + log_seq, system row = 0); the arm-time one-shot backfill makes the op log the complete history, so the `refs` write path retires for egress-on and the kstate overlay's ref rebuild is the legitimate path. **Structural invariants after every write, both planes (#7773 §6):** flow row count never shrinks · state row count == live view length · largest value == historical max SINGLE row · row alphabet exactly I/D/U (message) / I/U/D (block) — suite `tests/egress-invariants-7773.test.ts`. **Usage stream (owner ruling 2026-11-27):** `egress_usage` (5th egress table, own clock) records the in-memory cache ledger's mutations as an append-only M/S/F event stream so an egress-on session rebuilds its ledger by replay after a restart (detail: [egress-plane.md](../egress-plane.md) §12). Full walkthrough: [PR #6785 doc §6](../pr-6785-unified-storage-and-flows.md#6-round-2) · blocks: [egress-block-flow.md](../egress-block-flow.md) · one-stop: [egress-plane.md](../egress-plane.md). +**Egress plane (KDD #23/#24, discussions #7439/#7577/#7591/#7773 — the outbound conversation op log).** `egress_flow` (SQLite lane only, gate `rollout.features.egressPlane`) holds the **append-only** I/D/U op log of each session's outbound view; rows are self-contained (bytes ride the row, no content CAS). The flow keys on `(session_id, op_seq)` (dense row cursor, recovery/truncation key) and I rows additionally carry `log_seq` — the canonical, never-reissued message number; the frontier is `MAX(log_seq)` on the flow (the retired `B` base row's `highWater` payload is gone, #7773). **`egress_state` is the MATERIALIZED live view** (#7773): PK `(session_id, rid)`, `pos`-ordered; every append applies its ops to the rows in the same transaction (I inserts + shifts, U in-place, D physically deletes + shifts), so the serving copy is bounded by the live view's size by construction — there is no base row, no compaction, no op mirror. Row addressing in the log and the state key is the dense, never-reissued `rid`, never a msgid (owner ruling 2026-11-27, #7773 follow-up: msgids are kernel identities — content-hash-proxied, collision-prone, occurrence-ambiguous after folds — while rids are ours; D endpoints / U targets / I anchors all reference rids, `idx_egress_state_msgid` serves the msgid lookups). For egress-on sessions the op log is the SOLE canonical message authority: outbound bytes are served from it, the pin channel reads the materialized state instead of the messages ledger, the per-turn unified ingest stops (messages demoted to a LAZY projection, rebuilt one-time on rollback/web-read/restore) and the session JSON envelope freezes at bootstrap. Recovery: a damaged state copy is **rebuilt by full-history replay** and served as-is (the flow is the authority); if the flow itself does not replay, `recoverEgressBase` does ONE full-history walk (`egressFlowWalkBack`) — the newest healthy prefix truncates the tail; no healthy point ⇒ the turn hard-fails (ruling 7439-5), never degrades to client bytes. Ruling 7439-2 lands the read/write side on the blocks table itself: `summary_bytes` inlines the block summary (readers prefer it, the content CAS keeps its role only as the legacy fallback), and `start_msgid`/`end_msgid` align the block to the flow's msgid coordinates once at fold time — for flow-recorded sessions, NULL otherwise. **#7581 added the block lifecycle log** (`egress_block_flow`/`egress_block_state`) on **dual clocks** — the block tables number themselves, each row pointing at the flow clock via `flow_op_seq`; reap is a `D` row carrying the block's full terminal snapshot with the state row physically deleted (#7773); a point fork at flow watermark W copies flow rows `op_seq <= W` and block rows `flow_op_seq <= W`, then **materializes both state tables by replay to W** (any point — the "below the newest base" gate is gone); checkpoints for egress-on retired in favor of this point-fork. **#7617 consolidated identity**: egress-on stage-0 is stateless (frontiers from `MAX(op_seq)` / the flow's `MAX(log_seq)`, no l1 cursor, no resync), the R3 fault latch lives in `sessions.r3_latched_at` (dual-carrier read/clear with the legacy l1 column), and egress-on sessions are excluded from age GC and refused on manual archive until the archive format carries the op log. **Renumber (2026-11-25, [egress-plane.md](../egress-plane.md) §10):** `log_seq` IS the kernel citation number (`mNNNNN` = m + log_seq, system row = 0); the arm-time one-shot backfill makes the op log the complete history, so the `refs` write path retires for egress-on and the kstate overlay's ref rebuild is the legitimate path. **Structural invariants after every write, both planes (#7773 §6):** flow row count never shrinks · state row count == live view length · largest value == historical max SINGLE row · row alphabet exactly I/D/U (message) / I/U/D (block) — suite `tests/egress-invariants-7773.test.ts`. **Usage stream (owner ruling 2026-11-27):** `egress_usage` (5th egress table, own clock) records the in-memory cache ledger's mutations as an append-only M/S/F event stream so an egress-on session rebuilds its ledger by replay after a restart (detail: [egress-plane.md](../egress-plane.md) §12). Full walkthrough: [PR #6785 doc §6](../pr-6785-unified-storage-and-flows.md#6-round-2) · blocks: [egress-block-flow.md](../egress-block-flow.md) · one-stop: [egress-plane.md](../egress-plane.md). ## Hard invariants (see AGENTS.md before touching this) diff --git a/docs/architecture/storage.zh-CN.md b/docs/architecture/storage.zh-CN.md index 9d7d48b2be..a4a9f9a9d9 100644 --- a/docs/architecture/storage.zh-CN.md +++ b/docs/architecture/storage.zh-CN.md @@ -26,7 +26,7 @@ **一致性。** 检查点帧签名 + S4 逐行校验和;判决只信链、不信内容相似。可选静态加密:AES-256-GCM(#708)+ zstd(#1080)。`src/storage/mysql.ts` 的 mysql 方言只是**测试镜像**(mysql-contract CI 车道)——生产存储永远是 SQLite。 -**egress 平面(KDD #23/#24,#7439/#7577/#7591/#7773——出站会话 op log)。** `egress_flow`(仅 SQLite 车道,gate `rollout.features.egressPlane`)存每个会话出站视图的**append-only** I/D/U op log;行自包含(字节随行走,不经内容 CAS)。flow 以 `(session_id, op_seq)` 为主键(稠密行游标,恢复/截断键),I 行另带 `log_seq`——正史消息编号,永不重发;前沿 = flow 上的 `MAX(log_seq)`(退役 `B` base 行的 `highWater` payload 已不存在,#7773)。**`egress_state` 是物化 live 视图**(#7773):PK `(session_id, msgid)`、按 `pos` 排序;每次 append 在同一事务内把 op 应用到行上(I 插入 + 后移、U 就地改、D 物理删 + 前移),服务副本构造上以 live 视图大小为界——没有 base 行、没有压实、没有 op 镜像。对 egress-on 会话,op log 是**唯一**正史消息权威:出站字节从它 serve,pin 通道读物化 state 而非 messages 账本,逐轮统一 ingest 停止(messages 降级为**惰性投影**,回滚/web 读/恢复时一次性重建),会话 JSON 信封在 bootstrap 冻结。恢复:state 副本损坏时**全史重放重建**后照常服务(flow 是正史);flow 本身不可重放时,`recoverEgressBase` 走一趟全史 walk(`egressFlowWalkBack`)——最新健康前缀截掉尾部;无健康点 ⇒ 整轮硬失败(裁定 7439-5),绝不降级到客户端字节。裁定 7439-2 把读写侧落到 blocks 表自身:`summary_bytes` 内联压缩块摘要(读端优先用它,内容 CAS 只对遗留行保留回落),`start_msgid`/`end_msgid` 在折叠时一次性对齐到流水的 msgid 坐标——只有被流水记录的会话有值,其余保持 NULL。**#7581 增加块生命周期日志**(`egress_block_flow`/`egress_block_state`),**双时钟**——块表自己编号,每行经 `flow_op_seq` 指向流水时钟;reap = 一条 `D` 行带该块终态全量快照、state 行物理删除(#7773);流水水位 W 的点位 fork:流水行拷 `op_seq <= W`、块行拷 `flow_op_seq <= W`,然后**重放到 W 物化两张 state 表**(任意点位均可——「低于最新 base」门已废除);egress-on 的 checkpoint 退役,改用该点位 fork。**#7617 身份收拢**:egress-on 的 stage-0 无状态(前沿来自 `MAX(op_seq)`/flow 的 `MAX(log_seq)`,无 l1 游标、无 resync),R3 故障 latch 落 `sessions.r3_latched_at`(与 legacy l1 列双载体读/清),egress-on 会话整体排除出年龄 GC、手动 archive 被拒(直到归档格式携带 op log)。**重编号(2026-11-25,[egress-plane.zh-CN.md](../egress-plane.zh-CN.md) §10):**`log_seq` 就是内核引用号(`mNNNNN` = m + log_seq,system 行 = 0);arm 时一次性回填让 op log 成为完整历史,`refs` 写路径对 egress-on 退役,kstate overlay 的 refs 重建成为正当路径。**结构不变量(#7773 §6,每次写入后断言,两平面):** flow 行数只增 · state 行数 == live 视图长度 · 最大 value == 历史最大单行 · 行字母表恰为 I/D/U(消息)/ I/U/D(块)——套件 `tests/egress-invariants-7773.test.ts`。**用量事件流(owner 裁定 2026-11-27):** `egress_usage`(第 5 张 egress 表,独立时钟)把内存 cache ledger 的变更记成 append-only M/S/F 事件流,egress-on 会话重启后靠重放重建 ledger(详见 [egress-plane.zh-CN.md](../egress-plane.zh-CN.md) §12)。完整梳理:[PR #6785 文档 §6](../pr-6785-unified-storage-and-flows.zh-CN.md) · 块:[egress-block-flow.md](../egress-block-flow.zh-CN.md) · 一站式:[egress-plane.md](../egress-plane.zh-CN.md)。 +**egress 平面(KDD #23/#24,#7439/#7577/#7591/#7773——出站会话 op log)。** `egress_flow`(仅 SQLite 车道,gate `rollout.features.egressPlane`)存每个会话出站视图的**append-only** I/D/U op log;行自包含(字节随行走,不经内容 CAS)。flow 以 `(session_id, op_seq)` 为主键(稠密行游标,恢复/截断键),I 行另带 `log_seq`——正史消息编号,永不重发;前沿 = flow 上的 `MAX(log_seq)`(退役 `B` base 行的 `highWater` payload 已不存在,#7773)。**`egress_state` 是物化 live 视图**(#7773):PK `(session_id, rid)`、按 `pos` 排序;每次 append 在同一事务内把 op 应用到行上(I 插入 + 后移、U 就地改、D 物理删 + 前移),服务副本构造上以 live 视图大小为界——没有 base 行、没有压实、没有 op 镜像。日志与 state 主键的行寻址一律用稠密、永不重发的 `rid`,永不 msgid(owner 裁定 2026-11-27,#7773 后续:msgid 是内核身份——内容 hash 代理、可能冲突、折叠后分不清指哪一次;rid 是我们自己派的;D 端点 / U 目标 / I 锚点全引用 rid,`idx_egress_state_msgid` 负责 msgid 查找)。对 egress-on 会话,op log 是**唯一**正史消息权威:出站字节从它 serve,pin 通道读物化 state 而非 messages 账本,逐轮统一 ingest 停止(messages 降级为**惰性投影**,回滚/web 读/恢复时一次性重建),会话 JSON 信封在 bootstrap 冻结。恢复:state 副本损坏时**全史重放重建**后照常服务(flow 是正史);flow 本身不可重放时,`recoverEgressBase` 走一趟全史 walk(`egressFlowWalkBack`)——最新健康前缀截掉尾部;无健康点 ⇒ 整轮硬失败(裁定 7439-5),绝不降级到客户端字节。裁定 7439-2 把读写侧落到 blocks 表自身:`summary_bytes` 内联压缩块摘要(读端优先用它,内容 CAS 只对遗留行保留回落),`start_msgid`/`end_msgid` 在折叠时一次性对齐到流水的 msgid 坐标——只有被流水记录的会话有值,其余保持 NULL。**#7581 增加块生命周期日志**(`egress_block_flow`/`egress_block_state`),**双时钟**——块表自己编号,每行经 `flow_op_seq` 指向流水时钟;reap = 一条 `D` 行带该块终态全量快照、state 行物理删除(#7773);流水水位 W 的点位 fork:流水行拷 `op_seq <= W`、块行拷 `flow_op_seq <= W`,然后**重放到 W 物化两张 state 表**(任意点位均可——「低于最新 base」门已废除);egress-on 的 checkpoint 退役,改用该点位 fork。**#7617 身份收拢**:egress-on 的 stage-0 无状态(前沿来自 `MAX(op_seq)`/flow 的 `MAX(log_seq)`,无 l1 游标、无 resync),R3 故障 latch 落 `sessions.r3_latched_at`(与 legacy l1 列双载体读/清),egress-on 会话整体排除出年龄 GC、手动 archive 被拒(直到归档格式携带 op log)。**重编号(2026-11-25,[egress-plane.zh-CN.md](../egress-plane.zh-CN.md) §10):**`log_seq` 就是内核引用号(`mNNNNN` = m + log_seq,system 行 = 0);arm 时一次性回填让 op log 成为完整历史,`refs` 写路径对 egress-on 退役,kstate overlay 的 refs 重建成为正当路径。**结构不变量(#7773 §6,每次写入后断言,两平面):** flow 行数只增 · state 行数 == live 视图长度 · 最大 value == 历史最大单行 · 行字母表恰为 I/D/U(消息)/ I/U/D(块)——套件 `tests/egress-invariants-7773.test.ts`。**用量事件流(owner 裁定 2026-11-27):** `egress_usage`(第 5 张 egress 表,独立时钟)把内存 cache ledger 的变更记成 append-only M/S/F 事件流,egress-on 会话重启后靠重放重建 ledger(详见 [egress-plane.zh-CN.md](../egress-plane.zh-CN.md) §12)。完整梳理:[PR #6785 文档 §6](../pr-6785-unified-storage-and-flows.zh-CN.md) · 块:[egress-block-flow.md](../egress-block-flow.zh-CN.md) · 一站式:[egress-plane.md](../egress-plane.zh-CN.md)。 ## 硬不变量(动手前先读 AGENTS.md) diff --git a/docs/deprecations.md b/docs/deprecations.md index 8b664491d4..0a3918f3a2 100644 --- a/docs/deprecations.md +++ b/docs/deprecations.md @@ -16,8 +16,9 @@ Discipline: a surface is listed here **before** it goes default-off, and stays h | **kv_store value size** | **New hard cap 256 chars** (serialized) for ordinary keys on both backends, **`egressPlane`-on only** (legacy mode keeps the historical 4 MB byte budget — pre-existing keys may hold very large values; owner ruling 2026-11-26) (`KV_VALUE_MAX_CHARS`); the frozen whitelist (`KV_VALUE_WHITELIST`: `prefix-affinity\|v1`, `plugin-conversations\|table`) keeps the 4 MB ceiling — adding an entry is a review event and must be registered here | the cap itself is the replacement: kv_store is the small-config surface (install id, notices, host flags), not a blob store | none (removal would mean deleting the whitelist = all keys capped) | discussions/7735, 2026-11-25 | | **Legacy table creation** (12 tables) on eg-mode fresh databases | **Gated at creation** (KDD #25): an `egressPlane`-on instance's FRESH DB gets only `sessions`/`session_ext`/`kv_store` + the four egress tables; existing DBs are never stripped; probe-first convergence recreates the legacy group on any later open with the flag off | the gate itself — plus read-path guards (seven getters treat missing legacy tables as "no data") keep eg instances fully usable | none — turning the flag off converges any DB back to the full set; the 12-table physical DROP for egress-on carriers is still tracked above (l1_world row) | discussions/7735, 2026-11-25 | | **l1_world dead arm-turn placeholder rows** | **Auto-cleaned** by `UnifiedStore.ensureEgressIdentity()` (same tx as the identity upsert): rows with `armed_at IS NULL AND r3_latched_at IS NULL AND witness_probe <> ''` are deleted; armed/R3 rows survive | the identity row + stateless stage-0 (nothing reads the dead row) | none (the carrier table itself retires with the l1_world row above) | discussions/7735, 2026-11-25 | -| **egress `B` base row** (both planes: `row_type = 'B'` in `egress_flow` / `egress_block_flow`, payload `{entries, highWater}` / block base snapshot) | **Removed** (discussion #7773, 2026-11-26): no writer, no reader, no DDL `B` check remains; the frontier is `MAX(log_seq)` on the flow | the materialized state tables below — the base row's job (bounding the serving copy) is done by construction now | none left — the tables were never released with the `B` row in them: existing DBs **drop and rebuild** the four egress tables (owner runbook: delete `index.db*` + restart); the probe in `migrateSchema` does exactly that when it detects the old shape (`op_seq` column / missing `pos` column / `B` in the flow CHECK) | discussions/7773, 2026-11-26 | -| **`egress_state` as op-copy read replica** (PK `(session_id, op_seq)`, replayed from flow at every write) | **Removed** (discussion #7773): replaced by the **materialized live view** — PK `(session_id, msgid)`, `pos`-ordered, I inserts / U in-place / D physically deletes + shifts, same-transaction apply after the flow append | the materialized `egress_state` / `egress_block_state` + full-history replay (`egressStateAt`) as the rebuild path; serving read rebuilds a damaged copy by replay and serves (the flow is the authority) | none left — see the `B` base row row above (same never-released table, same drop-and-rebuild). `idx_egress_state_msgid` is gone too (the PK covers the msgid lookup) | discussions/7773, 2026-11-26 | +| **egress `B` base row** (both planes: `row_type = 'B'` in `egress_flow` / `egress_block_flow`, payload `{entries, highWater}` / block base snapshot) | **Removed** (discussion #7773, 2026-11-26): no writer, no reader, no DDL `B` check remains; the frontier is `MAX(log_seq)` on the flow | the materialized state tables below — the base row's job (bounding the serving copy) is done by construction now | none left — the tables were never released with the `B` row in them: existing DBs **drop and rebuild** the five egress tables (owner runbook: delete `index.db*` + restart); the probe in `migrateSchema` does exactly that when it detects the old shape (`op_seq` column / missing `pos` column / `B` in the flow CHECK / missing `rid` column) | discussions/7773, 2026-11-26 | +| **`egress_state` as op-copy read replica** (PK `(session_id, op_seq)`, replayed from flow at every write) | **Removed** (discussion #7773): replaced by the **materialized live view** — PK `(session_id, msgid)`, `pos`-ordered, I inserts / U in-place / D physically deletes + shifts, same-transaction apply after the flow append; the PK later moved to `(session_id, rid)` (next row, 2026-11-27) | the materialized `egress_state` / `egress_block_state` + full-history replay (`egressStateAt`) as the rebuild path; serving read rebuilds a damaged copy by replay and serves (the flow is the authority) | none left — see the `B` base row row above (same never-released table, same drop-and-rebuild). `idx_egress_state_msgid` is gone too (the PK covers the msgid lookup — superseded 2026-11-27: the index returned when the PK moved to `rid`, see next row) | discussions/7773, 2026-11-26 | +| **msgid-keyed log addressing in the egress tables** (D payload `{start, end}` = msgids, U payload `msgid` = target, I payload `after` = msgid, `egress_state` PK `(session_id, msgid)`) | **Removed** (owner ruling 2026-11-27, #7773 follow-up — the D-row audit in a field test): a msgid is a kernel identity the proxy may map from a content hash, can collide across hosts, and stops distinguishing occurrences after folds/re-homings — it cannot be a reliable PERSISTENT address. All addressing moves to `rid`, the dense per-session, append-only, never-reissued row id (the flow keeps every row, so `MAX(rid)+1` is always safe) | D payload `{start_rid, end_rid}` · U payload `rid` (+ the row's msgid as a cross-check) · I payload `after_rid` + `rid` column on `egress_flow` · `egress_state` PK `(session_id, rid)` with `idx_egress_state_msgid (session_id, msgid)` as the serving lookup. The kernel-identity seam (the prev↔next view diff) still matches on msgids — only the persistent layer changed. Suite: `tests/egress-state.test.ts` (incl. the msgid-collision row), `tests/egress-invariants-7773.test.ts` invariant ⑤ | none left — never released with msgid addressing: existing DBs drop and rebuild (the `migrateSchema` probe now treats a missing `rid` column as the old shape); dev DBs follow the destroy-&-rebuild runbook (egress-plane.md §7) | owner ruling 2026-11-27 (#7773 follow-up) | | **`egressStateCompact` / `egressBlockCompact`** (the compaction paths) | **Removed** (discussion #7773): no production caller existed for the block side; the message side's trim-below-base is replaced by physical D deletes on the materialized view | nothing — the state tables are bounded by the live view's size by construction; `tests/egress-invariants-7773.test.ts` pins the shape invariants after every write | none (functions deleted from `src/storage/egress-state.ts` / `src/storage/egress-block.ts`) | discussions/7773, 2026-11-26 | | **Bounded 16-step walk-back** (`EGRESS_HEALTHY_WALK_MAX`, `recoverEgressBase` one-step-at-a-time across bases) | **Removed** (discussion #7773): recovery is ONE full-history walk (`egressFlowWalkBack`) — the newest healthy prefix truncates the tail; no healthy point ⇒ null ⇒ latch + hard fail (7439-5) | `egressFlowWalkBack` in `src/storage/egress-state.ts` (O(n) single pass; density-checked) | none (constant deleted) | discussions/7773, 2026-11-26 | | **`egressMessageHighWater`'s B-payload fallback** (read `highWater` from the newest `B` row when the flow has no `log_seq`) | **Removed** (discussion #7773): the frontier is `MAX(log_seq)` on the flow only | `SELECT COALESCE(MAX(log_seq), 0) FROM egress_flow` | none | discussions/7773, 2026-11-26 | diff --git a/docs/deprecations.zh-CN.md b/docs/deprecations.zh-CN.md index b84839fbec..328839cc8f 100644 --- a/docs/deprecations.zh-CN.md +++ b/docs/deprecations.zh-CN.md @@ -16,8 +16,9 @@ | **kv_store 值大小** | **新增硬上限 256 字符**(序列化后)——普通键,sqlite/mysql 两后端,**仅 `egressPlane` 开时**(legacy 模式保持原有 4MB 字节预算——存量键可能存着非常大的值,不能把非 eg 部署炸掉;owner 裁定 2026-11-26)(`KV_VALUE_MAX_CHARS`);冻结白名单(`KV_VALUE_WHITELIST`:`prefix-affinity\|v1`、`plugin-conversations\|table`)保留 4MB 上限——加条目 = review 事件,须登记本表 | 上限本身就是替代:kv_store 是小配置面(install id、notices、host flags),不是 blob 库 | 无(移除 = 删白名单 = 全键带上限) | discussions/7735,2026-11-25 | | **legacy 表创建**(12 张)——eg 模式新建库 | **创建门**(KDD #25):`egressPlane` 开的实例**新建**库只建 `sessions`/`session_ext`/`kv_store` + 四张 egress 表;已有库绝不删表;probe-first 收敛在 flag 关闭后的任何一次打开补建 legacy 组 | 门本身 + 读路径守卫(7 个 getter 把缺失的 legacy 表当"无数据")保证 eg 实例完整可用 | 无——flag 关闭后任何库都收敛回全表;egress-on 载体的 12 表物理 DROP 仍按上方 l1_world 行跟踪 | discussions/7735,2026-11-25 | | **l1_world 死 arm-turn 占位行** | **自动清理**:`UnifiedStore.ensureEgressIdentity()` 同一事务删除 `armed_at IS NULL AND r3_latched_at IS NULL AND witness_probe <> ''` 的行;armed/R3 行保留 | 身份行 + 无状态 stage-0(无人读死行) | 无(载体表本身按上方 l1_world 行退役) | discussions/7735,2026-11-25 | -| **egress `B` base 行**(两平面:`egress_flow` / `egress_block_flow` 的 `row_type = 'B'`,payload `{entries, highWater}` / 块基线快照) | **移除**(discussion #7773,2026-11-26):不再有任何写入方、读取方、DDL `B` 检查;前沿 = flow 上的 `MAX(log_seq)` | 下方物化 state 表——base 行的职责(给服务副本封顶)现在由构造完成 | 无残留——这些表从未带 `B` 行随版本发布:已有库**drop 重建**四张 egress 表(owner 操作手册:删 `index.db*` + 重启);`migrateSchema` 探针检测到旧形态(`op_seq` 列 / 缺 `pos` 列 / flow CHECK 含 `B`)时正是这么做的 | discussions/7773,2026-11-26 | -| **`egress_state` 作为 op 副本读副本**(PK `(session_id, op_seq)`,每次写入从 flow 重放) | **移除**(discussion #7773):被**物化 live 视图**取代——PK `(session_id, msgid)`、`pos` 序、I 插入 / U 就地改 / D 物理删 + 前移、同事务在 flow append 之后应用 | 物化 `egress_state` / `egress_block_state` + 全史重放(`egressStateAt`)作为重建路径;serving 读发现副本损坏时重放重建后照常服务(flow 是正史) | 无残留——见上方 `B` base 行(同样的从未发布表,同样的 drop 重建)。`idx_egress_state_msgid` 也没了(PK 已覆盖 msgid 查找) | discussions/7773,2026-11-26 | +| **egress `B` base 行**(两平面:`egress_flow` / `egress_block_flow` 的 `row_type = 'B'`,payload `{entries, highWater}` / 块基线快照) | **移除**(discussion #7773,2026-11-26):不再有任何写入方、读取方、DDL `B` 检查;前沿 = flow 上的 `MAX(log_seq)` | 下方物化 state 表——base 行的职责(给服务副本封顶)现在由构造完成 | 无残留——这些表从未带 `B` 行随版本发布:已有库**drop 重建**五张 egress 表(owner 操作手册:删 `index.db*` + 重启);`migrateSchema` 探针检测到旧形态(`op_seq` 列 / 缺 `pos` 列 / flow CHECK 含 `B` / 缺 `rid` 列)时正是这么做的 | discussions/7773,2026-11-26 | +| **`egress_state` 作为 op 副本读副本**(PK `(session_id, op_seq)`,每次写入从 flow 重放) | **移除**(discussion #7773):被**物化 live 视图**取代——PK `(session_id, msgid)`、`pos` 序、I 插入 / U 就地改 / D 物理删 + 前移、同事务在 flow append 之后应用;PK 后来移到 `(session_id, rid)`(下一行,2026-11-27) | 物化 `egress_state` / `egress_block_state` + 全史重放(`egressStateAt`)作为重建路径;serving 读发现副本损坏时重放重建后照常服务(flow 是正史) | 无残留——见上方 `B` base 行(同样的从未发布表,同样的 drop 重建)。`idx_egress_state_msgid` 也没了(PK 已覆盖 msgid 查找——2026-11-27 被取代:PK 移到 `rid` 后该索引回来了,见下一行) | discussions/7773,2026-11-26 | +| **egress 表里用 msgid 做日志寻址**(D payload `{start, end}` = msgid、U payload `msgid` = 目标、I payload `after` = msgid、`egress_state` PK `(session_id, msgid)`) | **移除**(owner 裁定 2026-11-27,#7773 后续——实测 D 行审计):msgid 是内核身份,proxy 可能从内容 hash 映射而来、宿主间可能冲突、折叠/re-home 之后分不清指哪一次——不能当**持久地址**。一切寻址改用 `rid`:稠密、每会话、append-only、永不重发的行 id(flow 永不删,所以 `MAX(rid)+1` 永远安全) | D payload `{start_rid, end_rid}` · U payload `rid`(+ 该行 msgid 作交叉校验)· I payload `after_rid` + `egress_flow` 新增 `rid` 列 · `egress_state` PK `(session_id, rid)`,`idx_egress_state_msgid (session_id, msgid)` 只做 serving 查找。内核身份缝(prev↔next 视图 diff)继续按 msgid 匹配——只有**持久层**变了。套件:`tests/egress-state.test.ts`(含 msgid 冲突用例)、`tests/egress-invariants-7773.test.ts` 不变量 ⑤ | 无残留——从未以 msgid 寻址随版本发布:已有库 drop 重建(`migrateSchema` 探针把缺 `rid` 列也判为旧形态);开发库按 egress-plane.md §7 手册毁库重建 | owner 裁定 2026-11-27(#7773 后续) | | **`egressStateCompact` / `egressBlockCompact`**(压实路径) | **移除**(discussion #7773):块侧本无生产调用方;消息侧的 base 以下裁剪被物化视图上的物理 D 删除取代 | 无——state 表构造上以 live 视图大小为界;`tests/egress-invariants-7773.test.ts` 在每次写入后钉住形态不变量 | 无(函数已从 `src/storage/egress-state.ts` / `src/storage/egress-block.ts` 删除) | discussions/7773,2026-11-26 | | **有界 16 步回退**(`EGRESS_HEALTHY_WALK_MAX`,`recoverEgressBase` 跨过每个 base 逐步回退) | **移除**(discussion #7773):恢复 = **一趟全史 walk**(`egressFlowWalkBack`)——最新健康前缀截掉尾部;无健康点 ⇒ null ⇒ latch + 硬失败(7439-5) | `src/storage/egress-state.ts` 的 `egressFlowWalkBack`(O(n) 单趟,密度校验) | 无(常量已删) | discussions/7773,2026-11-26 | | **`egressMessageHighWater` 的 B-payload 回落**(flow 无 `log_seq` 时从最新 `B` 行读 `highWater`) | **移除**(discussion #7773):前沿 = flow 上的 `MAX(log_seq)`,仅此一种来源 | `SELECT COALESCE(MAX(log_seq), 0) FROM egress_flow` | 无 | discussions/7773,2026-11-26 | diff --git a/docs/egress-plane.md b/docs/egress-plane.md index f4bbbc2be5..1e9ac3ae70 100644 --- a/docs/egress-plane.md +++ b/docs/egress-plane.md @@ -34,8 +34,8 @@ Creation note (KDD #25): on an **egressPlane-on** instance a **fresh** database | Table | PK | Role | Key columns | |---|---|---|---| -| `egress_flow` | `(session_id, op_seq)` | **Message** op log. Dense within the table (#7574 invariant). **Append-only: nothing ever prunes it** (#7439); recovery = walk back to the newest healthy point; every point stays reconstructible (`egressStateAt`). | `row_type` I/D/U (the retired `B` base row is gone, #7773) · I: `msgid`, `log_seq` (canonical, never-reissued message number), `ref`, `tokens`, `bytes`, `role`, `type_tag` · D: range `(start_msgid, end_msgid)` + the terminal full snapshot · U: `msgid` + new bytes (+ `num` on re-citation) | -| `egress_state` | `(session_id, msgid)` | **Materialized live view** (7773): one row per LIVE message, ordered by `pos`. Every append applies its ops to the rows in the same transaction — `I` inserts (shifting `pos`), `U` updates in place, `D` physically deletes + shifts. Bounded by the live view's size by construction; there is no compaction, no base row, no op mirror. | `pos`, `log_seq` (the I-twin's flow number, immutable — the twin anchor), `num` (current kernel citation; 0 = uncited/retired), `msgid`, `ref`, `tokens`, `type`, `role`, `ts`, `sys_in`, `bytes`, `created_at`. This is what `snapPinLiveIds` / serving reads hit. | +| `egress_flow` | `(session_id, op_seq)` | **Message** op log. Dense within the table (#7574 invariant). **Append-only: nothing ever prunes it** (#7439); recovery = walk back to the newest healthy point; every point stays reconstructible (`egressStateAt`). | `row_type` I/D/U (the retired `B` base row is gone, #7773) · I: `rid` (the row id, below), `msgid`, `log_seq` (canonical, never-reissued message number), `ref`, `tokens`, `bytes`, `role`, `type_tag` · D: range `(start_rid, end_rid)` — addressed by row id, NEVER by msgid (2026-11-27 owner ruling) — + the terminal full snapshot · U: `rid` (the target row; the row's msgid is kept as a cross-check) + new bytes (+ `num` on re-citation) | +| `egress_state` | `(session_id, rid)` | **Materialized live view** (7773): one row per LIVE message, ordered by `pos`. Every append applies its ops to the rows in the same transaction — `I` inserts (shifting `pos`), `U` updates in place, `D` physically deletes + shifts. Bounded by the live view's size by construction; there is no compaction, no base row, no op mirror. A msgid MAY recur in the live view (a content-hash proxy can legitimately collide, or a re-homed slot can reappear); the `rid` cannot — that is why the key and every log anchor are `rid`, with `idx_egress_state_msgid` (session_id, msgid) as the serving lookup. | `rid` (dense, per-session, never re-issued — the flow keeps it forever, so `MAX(rid)+1` is always safe), `pos`, `log_seq` (the I-twin's flow number, immutable — the twin anchor), `num` (current kernel citation; 0 = uncited/retired), `msgid`, `ref`, `tokens`, `type`, `role`, `ts`, `sys_in`, `bytes`, `created_at`. This is what `snapPinLiveIds` / serving reads hit. | | `egress_block_flow` | `(session_id, op_seq)` | Append-only **block** history. **Own number pool** (dual clocks). | `row_type` I/U/D (reap = a `D` row carrying the block's **full terminal snapshot**, #7773; the retired `B` row is gone) · snapshot payload `{tier, startMsgid, startSeq, endMsgid, endSeq, supersedesBlockId, active, reaped, one, full}` · **`flow_op_seq`** = the flow's `MAX(op_seq)` at write time (the cross-table pointer) · kstate sidecar (residual field list) | | `egress_block_state` | `(session_id, block_id)` | **Materialized** live blocks: one row per non-reaped block, ordered by `pos`; reap physically deletes the row (the flow keeps the terminal `D` snapshot). | snapshot payload + `pos` + `op_seq`/`flow_op_seq` | | `egress_usage` | `(session_id, op_seq)` | Append-only **cache/usage event stream** (owner ruling 2026-11-27): the ledger's mutations as an op log, so the in-memory cache ledger is restart-reconstructible (§12). Third egress clock; own number pool. | `row_type` M/S/F · `at` (epoch ms — point-fork watermark) · `payload` = bounded JSON (S: the EXACT `recordCacheSample` arguments + model · F: the pristine fold row) | @@ -44,7 +44,7 @@ Creation note (KDD #25): on an **egressPlane-on** instance a **fresh** database Retention rules: **flow is append-only and never pruned** (#7439 — its growth is a deferred optimization, #7475, addressed elsewhere, never by retention); the **state** tables are the materialized live view — their size IS the live view's size, covered rows physically deleted at fold time (the base-row/compaction path, `egressStateCompact`/`egressBlockCompact`, is retired, #7773); block_flow is append-only like the message flow; **egress_usage** is append-only like its siblings (cleared only by session deletion / fork copy, §12). -**Structural invariants (7773 §6, asserted after EVERY write, both planes).** ① the flow's row count never shrinks (append-only); ② the state row count == the live view's row count (a materialization, never an aggregate and never an op mirror); ③ the largest value in flow/state equals the historical maximum SINGLE-row size — the regression defense against the retired `B` row's whole-view aggregate payload; ④ the row alphabet is exactly I/D/U (message plane) and I/U/D (block plane) — `B` never appears. Suite: `tests/egress-invariants-7773.test.ts`. +**Structural invariants (7773 §6, asserted after EVERY write, both planes).** ① the flow's row count never shrinks (append-only); ② the state row count == the live view's row count (a materialization, never an aggregate and never an op mirror); ③ the largest value in flow/state equals the historical maximum SINGLE-row size — the regression defense against the retired `B` row's whole-view aggregate payload; ④ the row alphabet is exactly I/D/U (message plane) and I/U/D (block plane) — `B` never appears; ⑤ **log addressing is by `rid`** — the dense, never-reissued per-session row id: D endpoints, U targets and I anchors in `egress_flow` payloads are rids, never msgids (a msgid is a kernel identity that the proxy may map from a content hash and that can legitimately recur; a rid is ours and cannot — owner ruling 2026-11-27, the follow-up to #7773). Suite: `tests/egress-invariants-7773.test.ts`. ## 4. One turn, step by step @@ -99,7 +99,7 @@ The invariant that pays for all of it: **every read the serving path needs is as - **R3 latch stuck:** `SELECT r3_latched_at FROM sessions WHERE session_id = ?` (old binaries: also check `l1_world`); clearing resets **both** carriers. - **GC / archive:** egress-on sessions are **excluded from age GC entirely** and **refused** on manual archive (`bili sessions archive`) — the archive format doesn't carry the op log yet (follow-up). - **Diagnosis:** `/__bili/status`; recovery events (walk-back truncations, degraded turns) are loud in the proxy log. -- **Handover — destroy & rebuild the dev database (7773 §7, owner executes):** the egress tables were never released with the old shape, so there is NO migration — a dev database holding the pre-#7773 egress tables is rebuilt by deleting the store files and restarting: stop bili, remove `/index.db`, `index.db-wal`, `index.db-shm` (default sessions dir: `~/.local/share/billion-context/sessions/`, i.e. `$XDG_DATA_HOME/billion-context/sessions/`), start bili again — the probe in `migrateSchema` detects the old shape (`op_seq` column / missing `pos` column / `B` in the flow CHECK) and drop-rebuilds the four egress tables on first open anyway; the manual delete is the clean path. egress-on session history in the old DB is discarded by design (dev data only — the plane never shipped to users). +- **Handover — destroy & rebuild the dev database (7773 §7, owner executes):** the egress tables were never released with the old shape, so there is NO migration — a dev database holding the pre-#7773 egress tables is rebuilt by deleting the store files and restarting: stop bili, remove `/index.db`, `index.db-wal`, `index.db-shm` (default sessions dir: `~/.local/share/billion-context/sessions/`, i.e. `$XDG_DATA_HOME/billion-context/sessions/`), start bili again — the probe in `migrateSchema` detects the old shape (`op_seq` column / missing `pos` column / `B` in the flow CHECK / missing `rid` column) and drop-rebuilds the five egress tables on first open anyway; the manual delete is the clean path. egress-on session history in the old DB is discarded by design (dev data only — the plane never shipped to users). ## 9. PR / proposal timeline @@ -113,6 +113,7 @@ The invariant that pays for all of it: **every read the serving path needs is as | **#7659 (this PR, 2026-11-24)** | Docs wrap-up: this doc; [deprecations.md](./deprecations.md); KDD #24; diagrams. The egressPlane default stays **0** per the owner ruling — a GA flip was proposed and declined. | | Discussion [#7735](https://github.com/ranxianglei/billion-context/discussions/7735) (2026-11-25) | **Sweep**: the arm-time identity row (§11), the 7-table creation gate, kv_store 256-char policy + big-blob retirement, l1 dead-row cleanup, and the flag-default correction back to 0. | | Discussion [#7773](https://github.com/ranxianglei/billion-context/discussions/7773) (2026-11-26) | **Shape re-ruling**: the `B` base row is retired on both planes; the state tables become the **materialized live view** (PK `(session_id, msgid)`, `pos`-ordered; D physically deletes, fold O(tail)); recovery becomes ONE full-history walk (`egressFlowWalkBack`); point forks materialize by replay to ANY point; structural invariants asserted after every write (§3). Legacy rows are NOT migrated — the tables were never released, so existing DBs drop and rebuild the four egress tables (owner runbook: delete `index.db*` + restart). | +| Owner ruling (2026-11-27, #7773 follow-up — the D-row audit in a field test) | **Row addressing moves to a self-issued row id (`rid`)**: msgids in log payloads are unreliable addresses — the proxy maps host ids to content hashes, a client id can collide, and after folds/re-homings a msgid no longer distinguishes which occurrence was meant. Every egress table addresses by the dense, append-only, never-reissued `rid` instead: `egress_state` PK `(session_id, rid)` (+ `idx_egress_state_msgid` for serving lookups), `egress_flow` I rows carry `rid` and D/U payloads reference rids. The kernel-identity seam (prev↔next diff matching) keeps msgids — only the PERSISTENT addressing changed. Never-shipped rule applies again: the old-shape probe (missing `rid`) drop-rebuilds on first open; dev DBs are destroyed & rebuilt by the §7 runbook. | **Open follow-ups** (tracked): the egressPlane default-100 flip when the owner says so; the archive format gaining the op log; the physical DROP batch for the retired identity carriers; flag removal (hardcode-on) per the retirement register. (The point-reconstruction materializer and the `egressBlockCompact` production caller are retired by #7773 — point forks materialize by replay, and block compaction no longer exists.) diff --git a/docs/egress-plane.zh-CN.md b/docs/egress-plane.zh-CN.md index 8291801cbe..642a4673f3 100644 --- a/docs/egress-plane.zh-CN.md +++ b/docs/egress-plane.zh-CN.md @@ -34,8 +34,8 @@ | 表 | 主键 | 作用 | 关键列 | |---|---|---|---| -| `egress_flow` | `(session_id, op_seq)` | **消息**操作日志。表内稠密(#7574 不变量)。**append-only:任何机制都不裁剪它**(#7439);恢复 = 回退到最新健康点;任意点位可完整重建(`egressStateAt`)。 | `row_type` I/D/U(退役的 `B` base 行已不存在,#7773)· I 行:`msgid`、`log_seq`(规范消息号,永不复用)、`ref`、`tokens`、`bytes`、`role`、`type_tag` · D 行:区间 `(start_msgid, end_msgid)` + 终态全量快照 · U 行:`msgid` + 新字节(再引用时带 `num`) | -| `egress_state` | `(session_id, msgid)` | **物化 live 视图**(7773):每条**存活**消息一行,按 `pos` 排序。每次 append 在同一事务内把 op 应用到行上——`I` 插入(`pos` 后移)、`U` 就地改、`D` 物理删 + 前移。构造上以 live 视图大小为界;没有压实、没有 base 行、没有 op 镜像。 | `pos`、`log_seq`(I 孪生在 flow 里的编号,不可变——孪生锚点)、`num`(当前内核引用号;0 = 无引用/已退役)、`msgid`、`ref`、`tokens`、`type`、`role`、`ts`、`sys_in`、`bytes`、`created_at`。`snapPinLiveIds`/serving 读命中它。 | +| `egress_flow` | `(session_id, op_seq)` | **消息**操作日志。表内稠密(#7574 不变量)。**append-only:任何机制都不裁剪它**(#7439);恢复 = 回退到最新健康点;任意点位可完整重建(`egressStateAt`)。 | `row_type` I/D/U(退役的 `B` base 行已不存在,#7773)· I 行:`rid`(行 id,见下)、`msgid`、`log_seq`(规范消息号,永不复用)、`ref`、`tokens`、`bytes`、`role`、`type_tag` · D 行:区间 `(start_rid, end_rid)`——用行 id 寻址,**永不**用 msgid(2026-11-27 owner 裁定)+ 终态全量快照 · U 行:`rid`(目标行;该行的 msgid 保留为交叉校验)+ 新字节(再引用时带 `num`) | +| `egress_state` | `(session_id, rid)` | **物化 live 视图**(7773):每条**存活**消息一行,按 `pos` 排序。每次 append 在同一事务内把 op 应用到行上——`I` 插入(`pos` 后移)、`U` 就地改、`D` 物理删 + 前移。构造上以 live 视图大小为界;没有压实、没有 base 行、没有 op 镜像。msgid **可以**在 live 视图里重现(内容 hash 代理可以合法冲突、re-home 可以重现同一 msgid);`rid` 不可以——所以主键与日志里的一切锚点都是 `rid`,`idx_egress_state_msgid`(session_id, msgid)只做 serving 查找。 | `rid`(稠密、每会话、永不重发——flow 永不删,所以 `MAX(rid)+1` 永远安全)、`pos`、`log_seq`(I 孪生在 flow 里的编号,不可变——孪生锚点)、`num`(当前内核引用号;0 = 无引用/已退役)、`msgid`、`ref`、`tokens`、`type`、`role`、`ts`、`sys_in`、`bytes`、`created_at`。`snapPinLiveIds`/serving 读命中它。 | | `egress_block_flow` | `(session_id, op_seq)` | 追加式**块**历史。**独立编号池**(双时钟)。 | `row_type` I/U/D(reap = 一条 `D` 行,带该块的**终态全量快照**,#7773;退役的 `B` 行已不存在)· 快照 payload `{tier, startMsgid, startSeq, endMsgid, endSeq, supersedesBlockId, active, reaped, one, full}` · **`flow_op_seq`** = 写入时刻 flow 的 `MAX(op_seq)`(跨表指针)· kstate 边车(残差字段清单) | | `egress_block_state` | `(session_id, block_id)` | **物化** live 块:每个未 reap 的块一行,按 `pos` 排序;reap 物理删行(flow 保留终态 `D` 快照)。 | 快照 payload + `pos` + `op_seq`/`flow_op_seq` | | `egress_usage` | `(session_id, op_seq)` | 追加式**缓存/用量事件流**(owner 裁定 2026-11-27):把内存 cache ledger 的变更记成 op log,进程重启后可重建(§12)。第三个 egress 时钟,独立编号池。 | `row_type` M/S/F · `at`(epoch ms——点位 fork 水位)· `payload` = 有界 JSON(S:`recordCacheSample` 的**精确**参数 + model · F:原始 fold 行) | @@ -44,7 +44,7 @@ 保留规则:**flow append-only、从不裁剪**(#7439——它的增长是已推迟的优化项 #7475,另行解决,绝不用裁剪解决);**state 表 = 物化 live 视图**——它的大小就是 live 视图的大小,被覆盖行在折叠时物理删除(base 行/压实路径 `egressStateCompact`/`egressBlockCompact` 已退役,#7773);block_flow 与消息 flow 一样 append-only;**egress_usage** 与它的兄弟们一样 append-only(只在会话删除 / fork 拷贝时清除,§12)。 -**结构不变量(7773 §6,每次写入后断言,两平面)。** ① flow 总行数只增(append-only);② state 行数 == live 视图行数(物化,不是聚合、不是 op 镜像);③ flow/state 里最大 value 大小 == 历史最大**单行**大小——针对退役 `B` 行全视图聚合 payload 的回归防线;④ 行字母表恰为 I/D/U(消息平面)与 I/U/D(块平面)——`B` 永不出现。套件:`tests/egress-invariants-7773.test.ts`。 +**结构不变量(7773 §6,每次写入后断言,两平面)。** ① flow 总行数只增(append-only);② state 行数 == live 视图行数(物化,不是聚合、不是 op 镜像);③ flow/state 里最大 value 大小 == 历史最大**单行**大小——针对退役 `B` 行全视图聚合 payload 的回归防线;④ 行字母表恰为 I/D/U(消息平面)与 I/U/D(块平面)——`B` 永不出现;⑤ **日志寻址一律用 `rid`**——稠密、永不重发的每会话行 id:`egress_flow` payload 里的 D 端点、U 目标、I 锚点都是 rid,永不 msgid(msgid 是内核身份,proxy 可能从内容 hash 映射而来、还可能合法重现;rid 是我们自己派的,不可能——owner 裁定 2026-11-27,#7773 后续)。套件:`tests/egress-invariants-7773.test.ts`。 ## 4. 一轮的生命周期 @@ -99,7 +99,7 @@ - **R3 latch 卡住**:`SELECT r3_latched_at FROM sessions WHERE session_id = ?`(旧二进制另查 `l1_world`);清除**两个载体都清**。 - **GC / 归档**:egress-on 会话**完全排除在按龄 GC 之外**,手动归档(`bili sessions archive`)**被拒绝**——归档格式尚未承载 op log(遗留项)。 - **诊断**:`/__bili/status`;恢复事件(回退截断、降级轮)在代理日志里响。 -- **交接——毁库重建开发库(7773 §7,owner 执行)**:egress 表从未以旧形态随版本发布,所以**没有迁移**——持有 #7773 前旧 egress 表的开发库靠删库文件 + 重启重建:停掉 bili,删 `/index.db`、`index.db-wal`、`index.db-shm`(默认 sessions 目录:`~/.local/share/billion-context/sessions/`,即 `$XDG_DATA_HOME/billion-context/sessions/`),再启动 bili——`migrateSchema` 探针本来就会检测到旧形态(`op_seq` 列 / 缺 `pos` 列 / flow CHECK 含 `B`)并在首次打开时 drop 重建四张 egress 表;手动删除只是干净路径。旧库里 egress-on 会话历史按设计丢弃(仅开发数据——平面从未发给过用户)。 +- **交接——毁库重建开发库(7773 §7,owner 执行)**:egress 表从未以旧形态随版本发布,所以**没有迁移**——持有 #7773 前旧 egress 表的开发库靠删库文件 + 重启重建:停掉 bili,删 `/index.db`、`index.db-wal`、`index.db-shm`(默认 sessions 目录:`~/.local/share/billion-context/sessions/`,即 `$XDG_DATA_HOME/billion-context/sessions/`),再启动 bili——`migrateSchema` 探针本来就会检测到旧形态(`op_seq` 列 / 缺 `pos` 列 / flow CHECK 含 `B` / 缺 `rid` 列)并在首次打开时 drop 重建五张 egress 表;手动删除只是干净路径。旧库里 egress-on 会话历史按设计丢弃(仅开发数据——平面从未发给过用户)。 ## 9. PR / 提案时间线 @@ -113,6 +113,7 @@ | **#7659(本 PR,2026-11-24)** | 文档收尾:本文档;[deprecations.zh-CN.md](./deprecations.zh-CN.md);KDD #24;图。egressPlane 默认按 owner 裁定保持 **0**——GA 翻转被提议后否决。 | | 讨论 [#7735](https://github.com/ranxianglei/billion-context/discussions/7735)(2026-11-25) | **扫尾**:arm 时身份行(§11)、7 表创建门、kv_store 256 字符策略 + 大 blob 退役、l1 死行清理、三个 flag 默认值修正回 0。 | | 讨论 [#7773](https://github.com/ranxianglei/billion-context/discussions/7773)(2026-11-26) | **形态再裁定**:两平面的 `B` base 行退役;state 表变为**物化 live 视图**(PK `(session_id, msgid)`、`pos` 序;D 物理删、折叠 O(尾长));恢复变为一趟全史 walk(`egressFlowWalkBack`);点位 fork 重放物化到**任意**点位;每次写入后断言结构不变量(§3)。存量不迁移——表从未随版本发布,已有库把四张 egress 表 drop 重建(owner 操作手册:删 `index.db*` + 重启)。 | +| Owner 裁定(2026-11-27,#7773 后续——实测 D 行审计) | **行寻址改用自派行 id(`rid`)**:日志 payload 里的 msgid 不是可靠地址——proxy 会把宿主 id 映射成内容 hash、客户端 id 可能冲突、折叠/re-home 之后同一个 msgid 分不清指哪一次。所有 egress 表改由稠密、append-only、永不重发的 `rid` 寻址:`egress_state` PK `(session_id, rid)`(+ `idx_egress_state_msgid` 供 serving 查找),`egress_flow` I 行带 `rid`、D/U payload 引用 rid。内核身份缝(prev↔next diff 匹配)继续用 msgid——只有**持久寻址层**变了。从未发布规则再次适用:旧形态探针(缺 `rid`)首开 drop 重建;开发库按 §7 手册毁库重建。 | **遗留**(已跟踪):egressPlane 默认翻 100(等 owner 点头);归档格式承载 op log;退役身份载体的物理 DROP 批次;按退役登记表删开关(硬编码开)。(point-reconstruction materializer 与 `egressBlockCompact` 生产调用方已被 #7773 退役——点位 fork 重放物化,块压实不复存在。) @@ -136,7 +137,7 @@ **身份行。** #7591 假设 egress-on 会话的 sessions 行在 arm turn 由首次 ingest 落地——不成立:`egressAuthority` latch 在该次保存**之前**就已打入(`src/server/egress-lane-io.ts`),第一次 ingest 就被 `egressProjectionFrozen` 冻结,行**永远落不了**。线上后果:重启后会话丢失(无行⇒不可 load、不可见、不进 GC 视野),metadata(pluginAgent/lastModel/title)只活在内存,血缘列永未持久化。修复:arm(latch 行)时 seam 调 `UnifiedStore.ensureEgressIdentity()`——一次性、幂等的 **13 列身份 upsert**(session_id、parent_session_id、protocol、label、title、host_title、namespace、origin、status、created_at、updated_at、meta_json、metadata_json;parent 用 `COALESCE(存量,新)` 与 ingest 同语义,第一个父赢;fork_point_seq 与全部 payload 列不碰)。每个 armed turn 都执行,删行下一轮自愈。同一事务里还删掉该会话的 **arm-turn 死 l1_world 占位行**(`armed_at IS NULL AND r3_latched_at IS NULL AND witness_probe <> ''`)——arm turn 的 stage-0 仍走 legacy(故意不预 latch),以前每个会话永久留一行死行。**该行的 metadata_json 只写身份键白名单**(`EGRESS_IDENTITY_METADATA_KEYS`:egressAuthority、pluginAgent、derivedFromSessionId、egressFlowUnreadable、lastModel),绝不写整个运行时袋:#6947 的 turn-final 回复暂存(handoffReply/handoffResponse,各最多 1.5MB 聊天内容)与每请求状态(effectiveConfig/cacheLedger/publicSnapshot*)只活在内存/op log(owner 2026-11-26:sessions 表放身份,不放聊天内容)。 -**表创建门。** eg 模式**新建**库只建:`sessions` + `session_ext` + `kv_store`(核心三件套)+ 四张 egress 表 = **7 张表**;12 张 legacy 表**不创建**(probe-first 收敛保证 flag 日后关闭时任何一次打开都会补建)。已有库保留全部现有表——门只管不建、从不删。`session_ext` 按 owner 裁定豁免(fastpath `pf:state` 熔断记忆住在里面)。直接调 `UnifiedStore.open` 的调用方默认建全表;开关判定在 `UnifiedShadow.maybeOpen`(`src/knobs.ts` 的 `egressPlaneGateOn()`——无副作用读法,现已是建表 DDL、kv256、affinity 退役与全部运行时行为的平面唯一门;`featureEnabled()` 在该平面任何位置都不可用,因为它的 install-id 引导会在 store open 中途做 wx 文件竞态写)。load/fork 路径对缺失的 legacy 表按"无数据"处理(7 个读 getter 短路),eg 模式实例完整可用。`BILI_TEST_FORCE_FULL_DDL=1` 是**测试专用**逃生口:断言 legacy 表形状而 flag 又开的套件(模拟门禁前的库)用它,生产永不设。 +**表创建门。** eg 模式**新建**库只建:`sessions` + `session_ext` + `kv_store`(核心三件套)+ 五张 egress 表(含 `egress_usage`,§12)= **8 张表(完整收敛 20)**;12 张 legacy 表**不创建**(probe-first 收敛保证 flag 日后关闭时任何一次打开都会补建)。已有库保留全部现有表——门只管不建、从不删。`session_ext` 按 owner 裁定豁免(fastpath `pf:state` 熔断记忆住在里面)。直接调 `UnifiedStore.open` 的调用方默认建全表;开关判定在 `UnifiedShadow.maybeOpen`(`src/knobs.ts` 的 `egressPlaneGateOn()`——无副作用读法,现已是建表 DDL、kv256、affinity 退役与全部运行时行为的平面唯一门;`featureEnabled()` 在该平面任何位置都不可用,因为它的 install-id 引导会在 store open 中途做 wx 文件竞态写)。load/fork 路径对缺失的 legacy 表按"无数据"处理(7 个读 getter 短路),eg 模式实例完整可用。`BILI_TEST_FORCE_FULL_DDL=1` 是**测试专用**逃生口:断言 legacy 表形状而 flag 又开的套件(模拟门禁前的库)用它,生产永不设。 **kv_store 策略。** `kv_store` 是小配置面(install id、notices、host flags),不是 blob 库:开启 `egressPlane` 时每个值 JSON 序列化后不得超过 **256 字符**(`KV_VALUE_MAX_CHARS`,sqlite/mysql 两后端 `setKv` 入口按调用时刻判定)。**legacy 模式保持原有 4MB 字节预算**——存量键可能已经存着非常大的值,上限不能把非 eg 部署炸掉(owner 裁定 2026-11-26)。冻结白名单(`KV_VALUE_WHITELIST`,加条目 = review 事件,须登记 [deprecations.zh-CN.md](./deprecations.zh-CN.md))给两个已知会长大的键保留 4MB 上限:`prefix-affinity|v1`、`plugin-conversations|table`。eg 模式下大 blob 在写入侧退役:`session-order` 早已退役(写入模块已被上游移除——孤儿行不再触碰,新库干净);`plugin-conversations` 不写(路由表纯内存;重启 miss 等下一个模型请求重建——既有 miss 语义);`prefix-affinity` 持久化在 eg 下整体退役(owner 裁定 2026-11-26):显式 ID 分支、file→kv 一次性迁移、kv/文件持久化路径全部加门——链表仍每轮计算、但 eg 模式下永不落盘(匿名客户端在 eg 下丢失跨重启链连续性,已接受),legacy JSON 文件降为只读 hydration 源,legacy 模式字节级不变。 diff --git a/src/storage/egress-block.ts b/src/storage/egress-block.ts index 2082f727f9..1661a4091e 100644 --- a/src/storage/egress-block.ts +++ b/src/storage/egress-block.ts @@ -630,16 +630,16 @@ export function egressPointFork(db: SqliteDatabase, fromSessionId: string, toSes } if (forkToNow) { db.prepare( - `INSERT INTO egress_flow (session_id, op_seq, log_seq, row_type, msgid, payload, bytes, created_at) - SELECT ?, op_seq, log_seq, row_type, msgid, payload, bytes, created_at FROM egress_flow WHERE session_id = ?`, + `INSERT INTO egress_flow (session_id, op_seq, log_seq, row_type, rid, msgid, payload, bytes, created_at) + SELECT ?, op_seq, log_seq, row_type, rid, msgid, payload, bytes, created_at FROM egress_flow WHERE session_id = ?`, ).run(toSessionId, fromSessionId); db.prepare( `INSERT INTO egress_block_flow (session_id, op_seq, flow_op_seq, row_type, block_id, payload, kstate_json, created_at) SELECT ?, op_seq, flow_op_seq, row_type, block_id, payload, kstate_json, created_at FROM egress_block_flow WHERE session_id = ?`, ).run(toSessionId, fromSessionId); db.prepare( - `INSERT INTO egress_state (session_id, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) - SELECT ?, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at FROM egress_state WHERE session_id = ?`, + `INSERT INTO egress_state (session_id, rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) + SELECT ?, rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at FROM egress_state WHERE session_id = ?`, ).run(toSessionId, fromSessionId); db.prepare( `INSERT INTO egress_block_state (session_id, block_id, pos, op_seq, flow_op_seq, payload, created_at) @@ -649,8 +649,8 @@ export function egressPointFork(db: SqliteDatabase, fromSessionId: string, toSes } // True point fork: copy the FLOW tables (append-only, op_seq <= wm). db.prepare( - `INSERT INTO egress_flow (session_id, op_seq, log_seq, row_type, msgid, payload, bytes, created_at) - SELECT ?, op_seq, log_seq, row_type, msgid, payload, bytes, created_at FROM egress_flow WHERE session_id = ? AND op_seq <= ?`, + `INSERT INTO egress_flow (session_id, op_seq, log_seq, row_type, rid, msgid, payload, bytes, created_at) + SELECT ?, op_seq, log_seq, row_type, rid, msgid, payload, bytes, created_at FROM egress_flow WHERE session_id = ? AND op_seq <= ?`, ).run(toSessionId, fromSessionId, wm); // Block rows align on the FLOW clock via their pointer column // (dual clocks: their own op_seq is unrelated to wm). diff --git a/src/storage/egress-record.ts b/src/storage/egress-record.ts index 0d8d8d29c4..bb69b647e6 100644 --- a/src/storage/egress-record.ts +++ b/src/storage/egress-record.ts @@ -157,6 +157,10 @@ export interface EgressOpLogStore { egressStateViewAt(sessionId: string, opSeq: number): EgressViewRow[]; /** Highest op_seq in the flow (0 = no rows). */ egressStateMaxSeq(sessionId: string): number; + /** 2026-11-27 (row ids): highest rid issued in the flow (0 = none) — + * the allocator a turn's diff continues from. Optional: a shim without + * rid support diffs from 0 (a single-writer test store). */ + egressStateMaxRid?(sessionId: string): number; /** 7773 walk-back: one O(n) pass over the flow's FULL history returning * the newest healthy NON-EMPTY prefix (seq + view), or null when no * non-empty healthy prefix exists (corruption reaching the floor). @@ -287,7 +291,9 @@ export function recordEgressTurn(args: { // trackNums: the next rows were stamped against the live refs ledger — // a spine row's num change is a kernel citation-fact change (demote / // re-cite / re-homing) and must reach the log as a +U carrying num. - const ops = diffEgressView(prev, next, refMap !== undefined); + // ridHighWater: row ids continue from the flow's MAX(rid) — ids never + // reuse (2026-11-27), a retired row's rid stays spent forever. + const ops = diffEgressView(prev, next, refMap !== undefined, store.egressStateMaxRid?.(sessionId) ?? 0); let stamped: EgressViewRow[]; if (ops.length === 0) { stamped = prev; diff --git a/src/storage/egress-state.ts b/src/storage/egress-state.ts index 6ef934a071..6f0f693f2a 100644 --- a/src/storage/egress-state.ts +++ b/src/storage/egress-state.ts @@ -7,22 +7,35 @@ * alphabet is I/U/D; the B base row never existed in the ruling and is * removed everywhere: not written, not read, no letter, no DDL CHECK). * - * THE ROW ALPHABET (7773 §2): - * I insert msgid required {"after": msgid|null, ref, tokens, + * THE ROW ALPHABET (7773 §2, addressing re-ruled 2026-11-27): + * I insert msgid required {"after": rid|null, ref, tokens, * type, role?} + bytes column; - * log_seq column = the canonical - * number (one number per message, - * session-scoped, never re-issued) + * rid column = the self-issued row id + * (see ROW ID below); log_seq column = + * the canonical number (one number + * per message, session-scoped) * U update-after msgid required {"role"?} + bytes column (the NEW * bytes; detected by byte inequality); + * rid column = the target row's rid; * an explicit num demotes/re-cites * (num→0 = demote: the number is * retired — permanently occupied by * the flow's I row, never re-issued) - * D delete-range msgid NULL {"start": msgid, "end": msgid} + * D delete-range msgid NULL {"start": rid, "end": rid} * inclusive view-order range * There is no -U letter: the flow is never pruned, so a before-image is - * always derivable from the msgid's earlier I/U rows. + * always derivable from the rid's earlier I/U rows. + * + * ROW ID (owner ruling 2026-11-27, follow-up to #7773): every log address + * is the self-issued `rid`, NEVER the msgid. The msgid is the CLIENT-facing + * identity (pin channel, kernel refs) — a content-hash mint on the proxy + * side, collidable in principle, and ambiguous across D/I churn. The rid is + * dense per session (1, 2, 3, …), issued at I from the flow's MAX(rid) + 1 + * (the flow is append-only and physically never deleted, so the frontier + * always sees every rid ever issued), and NEVER re-issued: a D retires the + * rid forever, an I takes a fresh one. log_seq stays the kernel CITATION + * number (mNNNNN) — a separate axis that a fold summary may re-cite after + * retirement, which is exactly why it cannot serve as a row id. * * THE TWO TABLES (7773 §2): * egress_flow — the record: EVERY I/U/D op in order, append-only, @@ -30,11 +43,13 @@ * separate, deferred project (#7475 family) — nothing * here ever prunes it. * egress_state — the MATERIALIZED live view: one row per live message - * (PK (session_id, msgid)), pos = the row's position in - * the current view. I inserts (suffix shifts), U edits in - * place, D physically deletes the range (suffix shifts). - * Serving reads are `ORDER BY pos` DIRECT reads — no - * replay, no compaction, no base concept. + * (PK (session_id, rid); msgid kept as an indexed column — + * the client-facing identity, read by the pin channel), + * pos = the row's position in the current view. I inserts + * (suffix shifts), U edits in place, D physically deletes + * the range (suffix shifts). Serving reads are `ORDER BY + * pos` DIRECT reads — no replay, no compaction, no base + * concept. * * SINGLE SOURCE OF TRUTH: every turn's batch of I/U/D is appended to the * flow AND applied in place to the state, in ONE transaction — the two @@ -68,7 +83,7 @@ * row (a U edits the state in place), so the serving read checks * STRUCTURAL invariants, cheaply: * - the state's pos sequence is dense 0..n-1; - * - every state row has its I twin in the flow (same msgid AND same + * - every state row has its I twin in the flow (same rid AND same * I-time log_seq); * a failed check = rebuild the state by replaying the flow's FULL * history (rare path — #7475 measured ~2.6s at 100k rows, one-shot, @@ -79,12 +94,13 @@ * the same ops in one transaction, and the state's row count is asserted * to equal the stamped view's length after the apply. * - * Anchors are MSGIDS, never display positions — positions shift under - * other ops, msgids do not (KDD#11: content may change, msgid does not). - * Any anchor/endpoint violation, missing update target, or duplicate - * msgid is a HARD ERROR (EgressStateCorruptError) — no fuzzy guessing, - * same discipline as every other lane's "any doubt, fall back whole- - * turn" rule. + * Anchors are RIDS, never display positions — positions shift under + * other ops, rids do not (self-issued, one-shot, never re-issued; the + * msgid is the client-facing identity and stays out of the log's + * addressing — owner ruling 2026-11-27). Any anchor/endpoint violation, + * missing update target, or duplicate rid is a HARD ERROR + * (EgressStateCorruptError) — no fuzzy guessing, same discipline as every + * other lane's "any doubt, fall back whole-turn" rule. */ import type { SqliteDatabase } from "./driver.js"; @@ -128,6 +144,11 @@ export const EGRESS_SYSTEM_MSGID = "egress-system"; * row it is the system text itself. The row is self-contained: replay + * serve need nothing beyond the flow table. */ export interface EgressViewRow { + /** Self-issued row id (dense per session, one-shot, never re-issued — + * the log's addressing key; 2026-11-27 owner ruling). Absent only on + * client-built diff inputs (buildEgressViewRows) — diffEgressView + * allocates it for every row that enters the log. */ + rid?: number; /** Current canonical session-scoped message number (0 = not cited). */ num: number; msgid: string; @@ -151,6 +172,7 @@ interface FlowRow { op_seq: number; log_seq: number | null; row_type: EgressOpType; + rid: number | null; msgid: string | null; payload: string; bytes: string | null; @@ -164,6 +186,7 @@ interface FlowRow { * outbound (A + server blocks); A's home inside the egress tables (the * 2026-11-25 renumber retires the session_ext inc:system copy). */ interface StateRow { + rid: number; msgid: string; pos: number; log_seq: number; @@ -177,9 +200,9 @@ interface StateRow { bytes: string; } -const INSERT_FLOW = `INSERT INTO egress_flow (session_id, op_seq, log_seq, row_type, msgid, payload, bytes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`; -const INSERT_STATE_ROW = `INSERT INTO egress_state (session_id, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`; -const SELECT_STATE_ROWS = `SELECT msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes FROM egress_state WHERE session_id = ? ORDER BY pos ASC`; +const INSERT_FLOW = `INSERT INTO egress_flow (session_id, op_seq, log_seq, row_type, rid, msgid, payload, bytes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`; +const INSERT_STATE_ROW = `INSERT INTO egress_state (session_id, rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`; +const SELECT_STATE_ROWS = `SELECT rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes FROM egress_state WHERE session_id = ? ORDER BY pos ASC`; /** The canonical message frontier: the highest number ever ISSUED * (retired messages included — I rows only advance it, D/U never do). @@ -195,6 +218,19 @@ export function egressMessageHighWater(db: SqliteDatabase, sessionId: string): n return Number(row?.n) || 0; } +/** The row-id frontier (2026-11-27): the highest rid ever ISSUED (retired + * rows included — rids are never re-issued, and the flow is append-only / + * never deleted, so MAX(rid) always sees every rid the session has used). + * U rows carry their target's rid (never a new one), D rows carry NULL, so + * the plain MAX over the table is the MAX over the I rows. diffEgressView + * allocates new rids strictly above it. */ +export function egressRowHighWater(db: SqliteDatabase, sessionId: string): number { + const row = db + .prepare("SELECT COALESCE(MAX(rid), 0) AS n FROM egress_flow WHERE session_id = ?") + .get(sessionId) as { n: number } | undefined; + return Number(row?.n) || 0; +} + function nextSeqs(db: SqliteDatabase, sessionId: string): { opSeq: number; num: number } { // egress_flow is the record and a superset of egress_state after every // turn, so the flow maxima ARE the session's high-waters: the op_seq @@ -219,7 +255,13 @@ function nextSeqs(db: SqliteDatabase, sessionId: string): { opSeq: number; num: interface InsertOp { type: "I"; msgid: string; - after: string | null; + /** The row's self-issued id — allocated by diffEgressView (dense, above + * the flow's rid frontier), REQUIRED (replay/apply hard-fail without + * it). 2026-11-27: the log's addressing key. */ + rid: number; + /** Anchor: the rid of the preceding row of the new view (null = the + * row goes to the FRONT — a replaced system prompt). */ + after: number | null; ref: string; tokens: number; typeTag: string; @@ -243,11 +285,13 @@ interface InsertOp { } interface DeleteOp { type: "D"; - start: string; - end: string; + start: number; + end: number; } interface UpdateOp { type: "U"; + /** The target row's self-issued id (2026-11-27: the addressing key). */ + rid: number; msgid: string; bytes: string; role?: string; @@ -279,7 +323,7 @@ function egressViewHighWater(view: EgressViewRow[]): number { * read from the flow, which includes numbers of rows a fold retired. */ export function egressReplay(prev: EgressViewRow[], ops: EgressOp[], startHigh?: number, sessionId = "diff"): EgressViewRow[] { const view: EgressViewRow[] = prev.map((r) => ({ ...r })); - const idxOf = (msgid: string): number => view.findIndex((r) => r.msgid === msgid); + const idxOf = (rid: number): number => view.findIndex((r) => r.rid === rid); let num = startHigh ?? egressViewHighWater(view); // Renumber (2026-11-25) — citation rules: // - the live set's numbers must stay UNIQUE; a cited number is @@ -294,6 +338,10 @@ export function egressReplay(prev: EgressViewRow[], ops: EgressOp[], startHigh?: // while the host's fold cell does — both land in one turn). const liveNums = new Set(); for (const r of view) if (r.num > 0) liveNums.add(r.num); + // Row ids (2026-11-27): unique among LIVE rows — a D retires its rids + // forever (the flow keeps them spent), an I reuses none of them. + const liveRids = new Set(); + for (const r of view) if (typeof r.rid === "number") liveRids.add(r.rid); let maxCited = 0; for (const op of ops) { if (op.type === "I" && op.msgid !== EGRESS_SYSTEM_MSGID && typeof op.num === "number" && op.num > 0) maxCited = Math.max(maxCited, op.num); @@ -301,13 +349,14 @@ export function egressReplay(prev: EgressViewRow[], ops: EgressOp[], startHigh?: } for (const op of ops) { if (op.type === "I") { - if (idxOf(op.msgid) >= 0) throw new EgressStateCorruptError(sessionId, `duplicate msgid ${op.msgid}`); + if (!Number.isInteger(op.rid) || op.rid < 1) throw new EgressStateCorruptError(sessionId, `insert ${op.msgid} has no row id`); + if (liveRids.has(op.rid)) throw new EgressStateCorruptError(sessionId, `duplicate row id ${op.rid} (msgid ${op.msgid})`); // `after: null` = the first row of the new view → the front. // #7574: idxOf answers -1 for a missing anchor, so the old // `at < -1` test could never fire and a missing anchor inserted // the row at index 0 in silence. const at = op.after === null ? -1 : idxOf(op.after); - if (at === -1 && op.after !== null) throw new EgressStateCorruptError(sessionId, `insert anchor ${op.after} missing`); + if (at === -1 && op.after !== null) throw new EgressStateCorruptError(sessionId, `insert anchor rid ${op.after} missing`); const isSystem = op.msgid === EGRESS_SYSTEM_MSGID; let assign = 0; if (isSystem) { @@ -326,25 +375,32 @@ export function egressReplay(prev: EgressViewRow[], ops: EgressOp[], startHigh?: assign = num; } } - const entry: EgressViewRow = { num: assign, msgid: op.msgid, ref: op.ref, tokens: op.tokens, type: op.typeTag, bytes: op.bytes }; + liveRids.add(op.rid); + const entry: EgressViewRow = { rid: op.rid, num: assign, msgid: op.msgid, ref: op.ref, tokens: op.tokens, type: op.typeTag, bytes: op.bytes }; if (op.role !== undefined) entry.role = op.role; if (op.ts !== undefined) entry.ts = op.ts; view.splice(at + 1, 0, entry); } else if (op.type === "D") { const s = idxOf(op.start); const e = idxOf(op.end); - if (s < 0) throw new EgressStateCorruptError(sessionId, `delete start ${op.start} missing`); - if (e < 0) throw new EgressStateCorruptError(sessionId, `delete end ${op.end} missing`); + if (s < 0) throw new EgressStateCorruptError(sessionId, `delete start rid ${op.start} missing`); + if (e < 0) throw new EgressStateCorruptError(sessionId, `delete end rid ${op.end} missing`); if (s > e) throw new EgressStateCorruptError(sessionId, "delete range inverted"); for (let i = s; i <= e; i++) { const r = view[i]; - if (r !== undefined && r.num > 0) liveNums.delete(r.num); + if (r !== undefined) { + if (r.num > 0) liveNums.delete(r.num); + if (typeof r.rid === "number") liveRids.delete(r.rid); + } } view.splice(s, e - s + 1); } else { - const i = idxOf(op.msgid); - if (i < 0) throw new EgressStateCorruptError(sessionId, `update target ${op.msgid} missing`); + const i = idxOf(op.rid); + if (i < 0) throw new EgressStateCorruptError(sessionId, `update target rid ${op.rid} missing`); const row = view[i]; + // Cross-check: the flow row's msgid column must name the same + // row the rid resolves to — a stale column is corruption. + if (row.msgid !== op.msgid) throw new EgressStateCorruptError(sessionId, `update rid ${op.rid} points at msgid ${row.msgid}, not ${op.msgid}`); if (typeof op.num === "number") { if (row.num > 0) liveNums.delete(row.num); if (op.num > 0) { @@ -389,7 +445,22 @@ export function egressReplay(prev: EgressViewRow[], ops: EgressOp[], startHigh?: * spine every turn — so num tracking is OFF and the diff keys on msgid + * bytes only, as before. */ -export function diffEgressView(prev: EgressViewRow[], next: EgressViewRow[], trackNums = false): EgressOp[] { +export function diffEgressView(prev: EgressViewRow[], next: EgressViewRow[], trackNums = false, ridHighWater = 0): EgressOp[] { + // RID ALLOCATION (2026-11-27): every row that ENTERS the log gets a + // fresh rid — dense, strictly above max(the flow's rid frontier, the + // max rid of prev), in `next` order. `ridHighWater` is the FLOW's + // MAX(rid) (includes retired rows — rids are never re-issued); prev + // rows keep their rids. Defensive: a prev row missing a rid (test + // shims) gets one from the same counter before it can anchor anything. + let rid = Math.max(ridHighWater, 0); + for (const r of prev) { + if (typeof r.rid !== "number" || r.rid < 1) { + rid += 1; + r.rid = rid; + } else if (r.rid > rid) { + rid = r.rid; + } + } const prevIdx = new Map(); prev.forEach((r, i) => { if (!prevIdx.has(r.msgid)) prevIdx.set(r.msgid, i); }); const prevByMsg = new Map(); @@ -404,51 +475,54 @@ export function diffEgressView(prev: EgressViewRow[], next: EgressViewRow[], tra } } const ops: EgressOp[] = []; - let runStart: string | null = null; - let runEnd: string | null = null; + let runStart: EgressViewRow | null = null; + let runEnd: EgressViewRow | null = null; for (const r of prev) { if (!spine.has(r.msgid)) { - if (runStart === null) runStart = r.msgid; - runEnd = r.msgid; + if (runStart === null) runStart = r; + runEnd = r; } else if (runStart !== null) { - ops.push({ type: "D", start: runStart, end: runEnd! }); + ops.push({ type: "D", start: runStart.rid!, end: runEnd!.rid! }); runStart = runEnd = null; } } - if (runStart !== null) ops.push({ type: "D", start: runStart, end: runEnd! }); + if (runStart !== null) ops.push({ type: "D", start: runStart.rid!, end: runEnd!.rid! }); for (const r of next) { if (spine.has(r.msgid)) { const old = prevByMsg.get(r.msgid)!; const oldNum = trackNums && typeof old.num === "number" && old.num > 0 ? old.num : 0; const newNum = trackNums && typeof r.num === "number" && r.num > 0 ? r.num : 0; if (old.bytes !== r.bytes || oldNum !== newNum) { - const u: UpdateOp = { type: "U", msgid: r.msgid, bytes: r.bytes }; + const u: UpdateOp = { type: "U", rid: old.rid!, msgid: r.msgid, bytes: r.bytes }; if (r.role !== undefined) u.role = r.role; if (oldNum !== newNum) u.num = newNum; ops.push(u); } } } - let last: string | null = null; + let last: number | null = null; for (const r of next) { - if (!spine.has(r.msgid)) { - const ins: InsertOp = { type: "I", msgid: r.msgid, after: last, ref: r.ref, tokens: r.tokens, typeTag: r.type, bytes: r.bytes }; + if (spine.has(r.msgid)) { + last = prevByMsg.get(r.msgid)!.rid!; + } else { + rid += 1; + const ins: InsertOp = { type: "I", rid, msgid: r.msgid, after: last, ref: r.ref, tokens: r.tokens, typeTag: r.type, bytes: r.bytes }; if (r.role !== undefined) ins.role = r.role; // Renumber (2026-11-25): a next-view row may already carry its // kernel citation number (recordEgressTurn stamps it from the // refs ledger); the I op preserves it. if (typeof r.num === "number" && r.num > 0) ins.num = r.num; ops.push(ins); + last = rid; } - last = r.msgid; } return ops; } /** Write one FLOW row (the record). The state table is applied separately * (materialized, 7773) — there is no twin-pair copy anymore. */ -function writeFlowRow(db: SqliteDatabase, sessionId: string, opSeq: number, logSeq: number | null, rowType: EgressOpType, msgid: string | null, payload: string, bytes: string | null, nowMs: number): void { - db.prepare(INSERT_FLOW).run(sessionId, opSeq, logSeq, rowType, msgid, payload, bytes, nowMs); +function writeFlowRow(db: SqliteDatabase, sessionId: string, opSeq: number, logSeq: number | null, rowType: EgressOpType, rid: number | null, msgid: string | null, payload: string, bytes: string | null, nowMs: number): void { + db.prepare(INSERT_FLOW).run(sessionId, opSeq, logSeq, rowType, rid, msgid, payload, bytes, nowMs); } /** Write a batch of ops to the FLOW. Every op gets the next op_seq; each I @@ -493,9 +567,11 @@ function writeFlowOps(db: SqliteDatabase, sessionId: string, ops: EgressOp[], fi if (op.sysIn !== undefined) payload["sysIn"] = op.sysIn; const citedLog = !isSystem && typeof op.num === "number" && op.num > 0 ? op.num : 0; const logSeq = isSystem ? 0 : (citedLog > 0 ? citedLog : num); - writeFlowRow(db, sessionId, opSeq, logSeq, "I", op.msgid, JSON.stringify(payload), op.bytes, nowMs); + writeFlowRow(db, sessionId, opSeq, logSeq, "I", op.rid, op.msgid, JSON.stringify(payload), op.bytes, nowMs); } else if (op.type === "D") { - writeFlowRow(db, sessionId, opSeq, null, "D", null, JSON.stringify({ start: op.start, end: op.end }), null, nowMs); + // 2026-11-27: the range endpoints are RIDS (self-issued, never + // re-issued) — the msgid never indexes the log again. + writeFlowRow(db, sessionId, opSeq, null, "D", null, null, JSON.stringify({ start: op.start, end: op.end }), null, nowMs); } else { const payload: Record = { role: op.role }; if (op.sysIn !== undefined) payload["sysIn"] = op.sysIn; @@ -503,7 +579,7 @@ function writeFlowOps(db: SqliteDatabase, sessionId: string, ops: EgressOp[], fi payload["num"] = op.num; num = Math.max(num, op.num); } - writeFlowRow(db, sessionId, opSeq, null, "U", op.msgid, JSON.stringify(payload), op.bytes, nowMs); + writeFlowRow(db, sessionId, opSeq, null, "U", op.rid, op.msgid, JSON.stringify(payload), op.bytes, nowMs); } } } @@ -519,12 +595,14 @@ function writeFlowOps(db: SqliteDatabase, sessionId: string, ops: EgressOp[], fi * serving read's twin check rejects) and throws. Runs inside the caller's * transaction. Returns the number of rows removed. */ export function egressMaterializeState(db: SqliteDatabase, sessionId: string, view: EgressViewRow[], nowMs: number): number { - const anchors = new Map(); + const anchors = new Map(); for (const r of db - .prepare("SELECT msgid, log_seq FROM egress_flow WHERE session_id = ? AND row_type = 'I' ORDER BY op_seq ASC") - .all(sessionId) as { msgid: string; log_seq: number | null }[]) { - if (typeof r.log_seq !== "number") throw new EgressStateCorruptError(sessionId, `I row for ${r.msgid} has no log_seq`); - anchors.set(r.msgid, r.log_seq); + .prepare("SELECT rid, log_seq FROM egress_flow WHERE session_id = ? AND row_type = 'I' ORDER BY op_seq ASC") + .all(sessionId) as { rid: number | null; log_seq: number | null }[]) { + if (typeof r.rid !== "number") throw new EgressStateCorruptError(sessionId, `I row has no rid`); + if (typeof r.log_seq !== "number") throw new EgressStateCorruptError(sessionId, `I row rid ${r.rid} has no log_seq`); + if (anchors.has(r.rid)) throw new EgressStateCorruptError(sessionId, `duplicate I row for rid ${r.rid}`); + anchors.set(r.rid, r.log_seq); } const removed = db .prepare("DELETE FROM egress_state WHERE session_id = ?") @@ -532,12 +610,15 @@ export function egressMaterializeState(db: SqliteDatabase, sessionId: string, vi for (let i = 0; i < view.length; i++) { const r = view[i]; const isSystem = r.msgid === EGRESS_SYSTEM_MSGID; - const anchor = anchors.get(r.msgid); + if (typeof r.rid !== "number" || r.rid < 1) { + throw new EgressStateCorruptError(sessionId, `materialized entry ${r.msgid} has no row id`); + } + const anchor = anchors.get(r.rid); if (typeof r.num !== "number" || r.num < 0 || anchor === undefined || (isSystem ? r.num !== 0 || anchor !== 0 : anchor < 1)) { throw new EgressStateCorruptError(sessionId, `materialized entry ${r.msgid} has no canonical number`); } db.prepare(INSERT_STATE_ROW).run( - sessionId, r.msgid, i, anchor, r.num, r.ref, r.tokens, r.type, + sessionId, r.rid, r.msgid, i, anchor, r.num, r.ref, r.tokens, r.type, r.role ?? null, r.ts ?? null, null, r.bytes, nowMs, ); } @@ -567,7 +648,7 @@ export function egressStateView(db: SqliteDatabase, sessionId: string): EgressVi if (r.num < 0 || (r.msgid === EGRESS_SYSTEM_MSGID && r.num !== 0)) { throw new EgressStateCorruptError(sessionId, `state row ${r.msgid} has an invalid current number (num ${r.num})`); } - const row: EgressViewRow = { num: r.num, msgid: r.msgid, ref: r.ref, tokens: r.tokens, type: r.type, bytes: r.bytes }; + const row: EgressViewRow = { rid: r.rid, num: r.num, msgid: r.msgid, ref: r.ref, tokens: r.tokens, type: r.type, bytes: r.bytes }; if (r.role !== null) row.role = r.role; if (r.ts !== null) row.ts = r.ts; view.push(row); @@ -577,7 +658,7 @@ export function egressStateView(db: SqliteDatabase, sessionId: string): EgressVi /** The STRUCTURAL integrity check (7773): state and flow are no longer * byte twins row-for-row (a U edits the state in place), so the check is - * (a) every state row has its I twin in the flow — same msgid AND same + * (a) every state row has its I twin in the flow — same rid AND same * I-time log_seq; (b) no state row exists for a session whose flow has no * rows. Cheap (index join), runs inside the caller's read transaction. * Throws EgressStateCorruptError on any stray row. */ @@ -585,7 +666,7 @@ function assertStateTwinOfFlow(db: SqliteDatabase, sessionId: string): void { const stray = db .prepare( `SELECT COUNT(*) AS c FROM egress_state s - LEFT JOIN egress_flow f ON f.session_id = s.session_id AND f.msgid = s.msgid AND f.log_seq = s.log_seq AND f.row_type = 'I' + LEFT JOIN egress_flow f ON f.session_id = s.session_id AND f.rid = s.rid AND f.log_seq = s.log_seq AND f.row_type = 'I' WHERE s.session_id = ? AND f.op_seq IS NULL`, ) .get(sessionId) as { c: number }; @@ -647,11 +728,11 @@ export function egressStateRead(db: SqliteDatabase, sessionId: string): EgressVi return rebuilt; } -/** msgid → pos over the session's materialized rows (the batch apply's +/** rid → pos over the session's materialized rows (the batch apply's * working index; a direct read replaces it after every transaction). */ -function posIndex(rows: StateRow[]): Map { - const posOf = new Map(); - for (const r of rows) posOf.set(r.msgid, r.pos); +function posIndex(rows: StateRow[]): Map { + const posOf = new Map(); + for (const r of rows) posOf.set(r.rid, r.pos); return posOf; } @@ -665,38 +746,38 @@ function posIndex(rows: StateRow[]): Map { * the caller's write transaction. */ function applyOpsToState(db: SqliteDatabase, sessionId: string, ops: EgressOp[], stamped: EgressViewRow[], nowMs: number): void { const posOf = posIndex(readStateRows(db, sessionId)); - const numOf = new Map(); - for (const r of stamped) numOf.set(r.msgid, r.num); + const numOf = new Map(); + for (const r of stamped) if (typeof r.rid === "number") numOf.set(r.rid, r.num); for (const op of ops) { if (op.type === "I") { - if (posOf.has(op.msgid)) throw new EgressStateCorruptError(sessionId, `state apply: insert ${op.msgid} already present`); + if (posOf.has(op.rid)) throw new EgressStateCorruptError(sessionId, `state apply: insert rid ${op.rid} already present`); const at = op.after === null ? -1 : posOf.get(op.after); - if (at === undefined && op.after !== null) throw new EgressStateCorruptError(sessionId, `state apply: insert anchor ${op.after} missing`); + if (at === undefined && op.after !== null) throw new EgressStateCorruptError(sessionId, `state apply: insert anchor rid ${op.after} missing`); const pos = (at ?? -1) + 1; - const assign = numOf.get(op.msgid) ?? 0; + const assign = numOf.get(op.rid) ?? 0; db.prepare("UPDATE egress_state SET pos = pos + 1 WHERE session_id = ? AND pos >= ?").run(sessionId, pos); db.prepare(INSERT_STATE_ROW).run( - sessionId, op.msgid, pos, assign, assign, op.ref, op.tokens, op.typeTag, + sessionId, op.rid, op.msgid, pos, assign, assign, op.ref, op.tokens, op.typeTag, op.role ?? null, op.ts ?? null, op.sysIn ?? null, op.bytes, nowMs, ); - for (const [m, p] of posOf) if (p >= pos) posOf.set(m, p + 1); - posOf.set(op.msgid, pos); + for (const [k, p] of posOf) if (p >= pos) posOf.set(k, p + 1); + posOf.set(op.rid, pos); } else if (op.type === "D") { const s = posOf.get(op.start); const e = posOf.get(op.end); - if (s === undefined) throw new EgressStateCorruptError(sessionId, `state apply: delete start ${op.start} missing`); - if (e === undefined) throw new EgressStateCorruptError(sessionId, `state apply: delete end ${op.end} missing`); + if (s === undefined) throw new EgressStateCorruptError(sessionId, `state apply: delete start rid ${op.start} missing`); + if (e === undefined) throw new EgressStateCorruptError(sessionId, `state apply: delete end rid ${op.end} missing`); if (s > e) throw new EgressStateCorruptError(sessionId, "state apply: delete range inverted"); const span = e - s + 1; db.prepare("DELETE FROM egress_state WHERE session_id = ? AND pos BETWEEN ? AND ?").run(sessionId, s, e); db.prepare("UPDATE egress_state SET pos = pos - ? WHERE session_id = ? AND pos > ?").run(span, sessionId, e); - for (const [m, p] of posOf) { - if (p >= s && p <= e) posOf.delete(m); - else if (p > e) posOf.set(m, p - span); + for (const [k, p] of posOf) { + if (p >= s && p <= e) posOf.delete(k); + else if (p > e) posOf.set(k, p - span); } } else { - const pos = posOf.get(op.msgid); - if (pos === undefined) throw new EgressStateCorruptError(sessionId, `state apply: update target ${op.msgid} missing`); + const pos = posOf.get(op.rid); + if (pos === undefined) throw new EgressStateCorruptError(sessionId, `state apply: update target rid ${op.rid} missing`); const sets = ["bytes = ?", "created_at = ?"]; const params: unknown[] = [op.bytes, nowMs]; if (op.role !== undefined) { @@ -711,7 +792,7 @@ function applyOpsToState(db: SqliteDatabase, sessionId: string, ops: EgressOp[], sets.push("num = ?"); params.push(op.num); } - db.prepare(`UPDATE egress_state SET ${sets.join(", ")} WHERE session_id = ? AND msgid = ?`).run(...params, sessionId, op.msgid); + db.prepare(`UPDATE egress_state SET ${sets.join(", ")} WHERE session_id = ? AND rid = ?`).run(...params, sessionId, op.rid); } } } @@ -789,7 +870,7 @@ export function egressAppendTurn( export function egressStateAt(db: SqliteDatabase, sessionId: string, x: number): EgressViewRow[] { const rows = db .prepare( - "SELECT op_seq, log_seq, row_type, msgid, payload, bytes FROM egress_flow WHERE session_id = ? AND op_seq <= ? ORDER BY op_seq ASC", + "SELECT op_seq, log_seq, row_type, rid, msgid, payload, bytes FROM egress_flow WHERE session_id = ? AND op_seq <= ? ORDER BY op_seq ASC", ) .all(sessionId, x) as unknown as FlowRow[]; return applyOps(sessionId, rows); @@ -815,12 +896,12 @@ export function egressFork(db: SqliteDatabase, fromSessionId: string, toSessionI db.prepare("DELETE FROM egress_state WHERE session_id = ?").run(toSessionId); db.prepare("DELETE FROM egress_flow WHERE session_id = ?").run(toSessionId); db.prepare( - `INSERT INTO egress_flow (session_id, op_seq, log_seq, row_type, msgid, payload, bytes, created_at) - SELECT ?, op_seq, log_seq, row_type, msgid, payload, bytes, created_at FROM egress_flow WHERE session_id = ?`, + `INSERT INTO egress_flow (session_id, op_seq, log_seq, row_type, rid, msgid, payload, bytes, created_at) + SELECT ?, op_seq, log_seq, row_type, rid, msgid, payload, bytes, created_at FROM egress_flow WHERE session_id = ?`, ).run(toSessionId, fromSessionId); db.prepare( - `INSERT INTO egress_state (session_id, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) - SELECT ?, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at FROM egress_state WHERE session_id = ?`, + `INSERT INTO egress_state (session_id, rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) + SELECT ?, rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at FROM egress_state WHERE session_id = ?`, ).run(toSessionId, fromSessionId); // The usage event stream rides with the whole copy (owner ruling: // one usage stream per session) — idempotent re-fork: replace. @@ -842,20 +923,22 @@ function applyRow(sessionId: string, view: EgressViewRow[], row: FlowRow): Egres throw new EgressStateCorruptError(sessionId, `payload at op_seq=${row.op_seq} is not an object`); } const p: Record = parsed; - const idxOf = (msgid: string): number => view.findIndex((e) => e.msgid === msgid); + const idxOf = (rid: number): number => view.findIndex((e) => e.rid === rid); if (row.row_type === "I") { if (typeof row.msgid !== "string") throw new EgressStateCorruptError(sessionId, `insert at op_seq=${row.op_seq} has no msgid`); + if (typeof row.rid !== "number" || row.rid < 1) throw new EgressStateCorruptError(sessionId, `insert at op_seq=${row.op_seq} has no row id`); + if (idxOf(row.rid) >= 0) throw new EgressStateCorruptError(sessionId, `duplicate row id ${row.rid} at op_seq=${row.op_seq}`); // Renumber (2026-11-25): 0 is the system row's number (outside the // citation space); every real message stores >= 1. const isSystem = row.msgid === EGRESS_SYSTEM_MSGID; if (typeof row.log_seq !== "number" || (isSystem ? row.log_seq !== 0 : row.log_seq < 1)) { throw new EgressStateCorruptError(sessionId, `insert at op_seq=${row.op_seq} has no canonical number`); } - if (idxOf(row.msgid) >= 0) throw new EgressStateCorruptError(sessionId, `duplicate msgid ${row.msgid} at op_seq=${row.op_seq}`); if (typeof p.ref !== "string" || typeof p.tokens !== "number" || typeof p.type !== "string" || typeof row.bytes !== "string") { throw new EgressStateCorruptError(sessionId, `insert at op_seq=${row.op_seq} has a malformed payload or missing bytes`); } const entry: EgressViewRow = { + rid: row.rid, num: row.log_seq, msgid: row.msgid, ref: p.ref as string, @@ -867,26 +950,31 @@ function applyRow(sessionId: string, view: EgressViewRow[], row: FlowRow): Egres if (typeof p.ts === "number") entry.ts = p.ts; // `after: null` = the row goes to the FRONT — it was the first // row of the view the diff described (a replaced system prompt). - const at = p.after == null ? -1 : typeof p.after === "string" ? idxOf(p.after) : -2; + // 2026-11-27: the anchor is a rid (never a msgid). + const at = p.after == null ? -1 : typeof p.after === "number" ? idxOf(p.after) : -2; if (at === -2) throw new EgressStateCorruptError(sessionId, `insert at op_seq=${row.op_seq} has a malformed anchor`); - if (at < 0 && p.after != null) throw new EgressStateCorruptError(sessionId, `insert anchor ${String(p.after)} missing at op_seq=${row.op_seq}`); + if (at < 0 && p.after != null) throw new EgressStateCorruptError(sessionId, `insert anchor rid ${String(p.after)} missing at op_seq=${row.op_seq}`); view.splice(at + 1, 0, entry); } else if (row.row_type === "D") { - if (typeof p.start !== "string" || typeof p.end !== "string") { + if (typeof p.start !== "number" || typeof p.end !== "number") { throw new EgressStateCorruptError(sessionId, `delete at op_seq=${row.op_seq} has a malformed payload`); } const s = idxOf(p.start); const e = idxOf(p.end); - if (s < 0) throw new EgressStateCorruptError(sessionId, `delete start ${p.start} missing at op_seq=${row.op_seq}`); - if (e < 0) throw new EgressStateCorruptError(sessionId, `delete end ${p.end} missing at op_seq=${row.op_seq}`); + if (s < 0) throw new EgressStateCorruptError(sessionId, `delete start rid ${p.start} missing at op_seq=${row.op_seq}`); + if (e < 0) throw new EgressStateCorruptError(sessionId, `delete end rid ${p.end} missing at op_seq=${row.op_seq}`); if (s > e) throw new EgressStateCorruptError(sessionId, `delete range inverted (start after end) at op_seq=${row.op_seq}`); view.splice(s, e - s + 1); } else if (row.row_type === "U") { + if (typeof row.rid !== "number" || row.rid < 1) { + throw new EgressStateCorruptError(sessionId, `update at op_seq=${row.op_seq} has no row id`); + } if (typeof row.msgid !== "string" || typeof row.bytes !== "string") { throw new EgressStateCorruptError(sessionId, `update at op_seq=${row.op_seq} has a malformed payload or missing bytes`); } - const i = idxOf(row.msgid); - if (i < 0) throw new EgressStateCorruptError(sessionId, `update target ${row.msgid} missing at op_seq=${row.op_seq}`); + const i = idxOf(row.rid); + if (i < 0) throw new EgressStateCorruptError(sessionId, `update target rid ${row.rid} missing at op_seq=${row.op_seq}`); + if (view[i].msgid !== row.msgid) throw new EgressStateCorruptError(sessionId, `update at op_seq=${row.op_seq}: rid ${row.rid} points at msgid ${view[i].msgid}, not ${row.msgid}`); view[i] = { ...view[i], bytes: row.bytes, @@ -931,7 +1019,7 @@ function applyOps(sessionId: string, rows: FlowRow[]): EgressViewRow[] { export function egressFlowWalkBack(db: SqliteDatabase, sessionId: string): { seq: number; view: EgressViewRow[] } | null { const rows = db .prepare( - "SELECT op_seq, log_seq, row_type, msgid, payload, bytes FROM egress_flow WHERE session_id = ? ORDER BY op_seq ASC", + "SELECT op_seq, log_seq, row_type, rid, msgid, payload, bytes FROM egress_flow WHERE session_id = ? ORDER BY op_seq ASC", ) .all(sessionId) as unknown as FlowRow[]; let view: EgressViewRow[] = []; diff --git a/src/storage/schema.ts b/src/storage/schema.ts index 99bd6aa865..bed0a0cbf0 100644 --- a/src/storage/schema.ts +++ b/src/storage/schema.ts @@ -485,6 +485,7 @@ CREATE TABLE IF NOT EXISTS state_fields ( const EGRESS_STATE_DDL = `-- #6785 perf (proposals discussions/7398 + 7439, materialized at 7773): op-log outbound view (flow record + materialized live state), self-contained bytes, canonical per-message numbers. CREATE TABLE IF NOT EXISTS egress_state ( session_id TEXT NOT NULL, + rid INTEGER NOT NULL, msgid TEXT NOT NULL, pos INTEGER NOT NULL, log_seq INTEGER NOT NULL, @@ -497,19 +498,22 @@ CREATE TABLE IF NOT EXISTS egress_state ( sys_in TEXT, bytes TEXT NOT NULL, created_at INTEGER NOT NULL, - PRIMARY KEY (session_id, msgid) + PRIMARY KEY (session_id, rid) ); CREATE TABLE IF NOT EXISTS egress_flow ( session_id TEXT NOT NULL, op_seq INTEGER NOT NULL, log_seq INTEGER, row_type TEXT NOT NULL CHECK (row_type IN ('I','D','U')), + rid INTEGER, msgid TEXT, payload TEXT NOT NULL, bytes TEXT, created_at INTEGER NOT NULL, PRIMARY KEY (session_id, op_seq) ); +CREATE INDEX IF NOT EXISTS idx_egress_state_msgid ON egress_state (session_id, msgid); +CREATE INDEX IF NOT EXISTS idx_egress_flow_rid ON egress_flow (session_id, rid); CREATE INDEX IF NOT EXISTS idx_egress_flow_msgid ON egress_flow (session_id, msgid); `; @@ -702,7 +706,14 @@ export function migrateSchema(db: { // check stays for a DB where only the flow row survived). The NEW shape // is recognized by the ABSENCE of op_seq plus the presence of pos — // that is the exact opposite of the old op-copy shape, never "old". - const egressOldShape = (egressCols.length > 0 && (egressCols.includes("op_seq") || !egressCols.includes("pos"))) + // 2026-11-27 (owner ruling, discussion follow-up to #7773): log + // addressing moved off msgid onto the self-issued row id `rid` (dense + // per-session, issued at I, NEVER re-issued — retired rows keep their + // rid forever; msgid stayed the CLIENT-facing identity but is no longer + // the state PK and no longer an op anchor). A state table without the + // rid column is an old-shape dev DB — same never-shipped rule, one-step + // drop + recreate (the owner's live DBs are rebuilt by the operator). + const egressOldShape = (egressCols.length > 0 && (egressCols.includes("op_seq") || !egressCols.includes("pos") || !egressCols.includes("rid"))) || egressFlowSql.includes("('B','I','D','U')"); if (egressOldShape) { // #7574 item 10: drop + recreate is one step (same transaction rule). diff --git a/src/storage/store.ts b/src/storage/store.ts index 01a0a26b2e..df1d2d0540 100644 --- a/src/storage/store.ts +++ b/src/storage/store.ts @@ -30,6 +30,7 @@ import { egressFlowWalkBack, egressStateRead, egressStateView, + egressRowHighWater, egressFork, egressMaterializeState, egressMessageHighWater, @@ -2648,6 +2649,12 @@ export class UnifiedStore { return Number(row.mx) || 0; } + /** 2026-11-27 (row ids): highest rid issued in the flow (0 = none) — + * the allocator for a session's next row ids. */ + egressStateMaxRid(sessionId: string): number { + return egressRowHighWater(this.db, sessionId); + } + /** 7773: truncate the flow past op_seq — and REBUILD the materialized * live state from the surviving flow, in ONE transaction (a crash * between a flow truncate and a state rebuild would leave the twin diff --git a/tests/eg-sweep-egress-identity.test.ts b/tests/eg-sweep-egress-identity.test.ts index df02ba2fc1..1ae15324ec 100644 --- a/tests/eg-sweep-egress-identity.test.ts +++ b/tests/eg-sweep-egress-identity.test.ts @@ -682,7 +682,7 @@ test("C5: a latched record-only turn still refreshes the identity row (title lan assert.equal(row.title, null, "title not derived yet on turn 1"); assert.equal(JSON.parse(row.metadata_json).egressAuthority, true, "the latch PERSISTS in the row (load restores it from metadata_json)"); // The turn-1 record (what recordAuthorityTurn appends for the lane). - store.egressAppendTurn(sid, [{ type: "I", msgid: "m1", after: null, ref: "m00001", tokens: 5, typeTag: "text", bytes: "hello" }], 0, Date.now()); + store.egressAppendTurn(sid, [{ type: "I", rid: 1, msgid: "m1", after: null, ref: "m00001", tokens: 5, typeTag: "text", bytes: "hello" }], 0, Date.now()); // Turn 2 — the pin FAILED this turn (host declared no ids): the lane // calls the seam with armed=false. The record-only path must STILL // refresh the identity row (meta.title now carries the lane's diff --git a/tests/egress-authority-ladder.test.ts b/tests/egress-authority-ladder.test.ts index 8546a6de73..02d695b972 100644 --- a/tests/egress-authority-ladder.test.ts +++ b/tests/egress-authority-ladder.test.ts @@ -62,7 +62,7 @@ test("recoverEgressBase: an unreplayable tail walks back to the newest healthy p // dense row order) gets a payload that does not parse, and a stray // state row without an I twin forces the read onto the rebuild path H.db.prepare(`UPDATE egress_flow SET payload = ? WHERE session_id = ? AND op_seq = 3`).run('{"x":1}', S); - H.db.prepare(`INSERT INTO egress_state (session_id, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 'ghost', 99, 7, 7, '', 0, 'text', 'user', 0, 0, 'x', 9)`).run(S); + H.db.prepare(`INSERT INTO egress_state (session_id, rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 99, 'ghost', 99, 7, 7, '', 0, 'text', 'user', 0, 0, 'x', 9)`).run(S); const got = recoverEgressBase(H.store, S); assert.ok(got !== null); assert.equal(got.degraded, true); diff --git a/tests/egress-block.test.ts b/tests/egress-block.test.ts index 079158a65b..cebc0061a4 100644 --- a/tests/egress-block.test.ts +++ b/tests/egress-block.test.ts @@ -139,7 +139,7 @@ test("point fork: the block set aligns to the FLOW watermark via flow_op_seq (du const P = "parent"; // flow point 1 egressAppendTurn(H.db, P, [ - { type: "I", msgid: "m00001", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "a" }, + { type: "I", rid: 1, msgid: "m00001", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "a" }, ], 1_000, { baseSeq: 0 }); // block born — its flow_op_seq pointer is 1 (flow's MAX at write time) egressBlockAppend(H.db, P, [ @@ -147,7 +147,7 @@ test("point fork: the block set aligns to the FLOW watermark via flow_op_seq (du ], null, 1_500); // flow point 2 egressAppendTurn(H.db, P, [ - { type: "I", msgid: "m00002", after: "m00001", ref: "m00002", tokens: 4, typeTag: "text", bytes: "b" }, + { type: "I", rid: 2, msgid: "m00002", after: 1, ref: "m00002", tokens: 4, typeTag: "text", bytes: "b" }, ], 2_000, { baseSeq: 1 }); // block updated at flow point 2 egressBlockAppend(H.db, P, [ @@ -180,16 +180,16 @@ test("fork-to-now: the child inherits the parent's four tables verbatim (a)", () const P = "parent-a"; // two message turns (flow ops 1, 2) egressAppendTurn(H.db, P, [ - { type: "I", msgid: "m00001", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "hello" }, + { type: "I", rid: 1, msgid: "m00001", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "hello" }, ], 1_000, { baseSeq: 0 }); egressAppendTurn(H.db, P, [ - { type: "I", msgid: "m00002", after: "m00001", ref: "m00002", tokens: 4, typeTag: "text", bytes: "there" }, + { type: "I", rid: 2, msgid: "m00002", after: 1, ref: "m00002", tokens: 4, typeTag: "text", bytes: "there" }, ], 2_000, { baseSeq: 1 }); // a block birth (block op 1 on the block's OWN clock; flow_op_seq 2) egressBlockAppend(H.db, P, [{ type: "I", blockId: "blk_1", snapshot: snap() }], null, 3_000); // a fold: delete both messages → compaction in the same write egressAppendTurn(H.db, P, [ - { type: "D", start: "m00001", end: "m00002" }, + { type: "D", start: 1, end: 2 }, ], 4_000, { baseSeq: 2 }); // The FLOW clock is the reference clock for fork watermarks (dual @@ -200,9 +200,9 @@ test("fork-to-now: the child inherits the parent's four tables verbatim (a)", () // every one of the four tables is byte-identical to the parent's for (const [table, cols] of [ - ["egress_flow", "op_seq, log_seq, row_type, msgid, payload, bytes, created_at"], + ["egress_flow", "op_seq, log_seq, row_type, rid, msgid, payload, bytes, created_at"], ["egress_block_flow", "op_seq, flow_op_seq, row_type, block_id, payload, kstate_json, created_at"], - ["egress_state", "msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at"], + ["egress_state", "rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at"], ["egress_block_state", "block_id, pos, op_seq, flow_op_seq, payload, created_at"], ] as const) { const q = (id: string) => H.db.prepare(`SELECT ${cols} FROM ${table} WHERE session_id = ? ORDER BY 1, 2`).all(id); @@ -210,7 +210,7 @@ test("fork-to-now: the child inherits the parent's four tables verbatim (a)", () } // the child continues the FLOW clock past the parent's high water egressAppendTurn(H.db, C, [ - { type: "I", msgid: "m00009", after: null, ref: "m00009", tokens: 2, typeTag: "text", bytes: "after fork" }, + { type: "I", rid: 3, msgid: "m00009", after: null, ref: "m00009", tokens: 2, typeTag: "text", bytes: "after fork" }, ], 9_000, { baseSeq: parentMax }); const childMax = (H.db.prepare("SELECT COALESCE(MAX(op_seq), 0) AS m FROM egress_flow WHERE session_id = ?").get(C) as { m: number }).m; assert.equal(childMax, parentMax + 1); @@ -222,10 +222,10 @@ test("fork-to-now: the child inherits the parent's four tables verbatim (a)", () // and the flow rows 1,2 are still the fork's source. const P2 = "parent-a2"; egressAppendTurn(H.db, P2, [ - { type: "I", msgid: "m00001", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "hello" }, + { type: "I", rid: 1, msgid: "m00001", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "hello" }, ], 1_000, { baseSeq: 0 }); egressAppendTurn(H.db, P2, [ - { type: "I", msgid: "m00002", after: "m00001", ref: "m00002", tokens: 4, typeTag: "text", bytes: "there" }, + { type: "I", rid: 2, msgid: "m00002", after: 1, ref: "m00002", tokens: 4, typeTag: "text", bytes: "there" }, ], 2_000, { baseSeq: 1 }); // blk_1's flow_op_seq pointer is 2 — it "exists at flow point 2" egressBlockAppend(H.db, P2, [{ type: "I", blockId: "blk_1", snapshot: snap() }], null, 3_000); @@ -246,8 +246,8 @@ test("interleave regression (the review-critical bug): flow stays DENSE when mes const S = "sess-interleave"; // turn 1: two messages egressAppendTurn(H.db, S, [ - { type: "I", msgid: "m00001", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "a" }, - { type: "I", msgid: "m00002", after: "m00001", ref: "m00002", tokens: 4, typeTag: "text", bytes: "b" }, + { type: "I", rid: 1, msgid: "m00001", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "a" }, + { type: "I", rid: 2, msgid: "m00002", after: 1, ref: "m00002", tokens: 4, typeTag: "text", bytes: "b" }, ], 1_000, { baseSeq: 0 }); // a fold turn lands a block at SAVE time (production write order: // message rows at prepare, block rows at save) @@ -257,7 +257,7 @@ test("interleave regression (the review-critical bug): flow stays DENSE when mes // applyOps' density check (`op_seq === prevSeq + 1`) threw "jumps // from 2 to 4" on every subsequent egress read. egressAppendTurn(H.db, S, [ - { type: "I", msgid: "m00003", after: "m00002", ref: "m00003", tokens: 5, typeTag: "text", bytes: "c" }, + { type: "I", rid: 3, msgid: "m00003", after: 2, ref: "m00003", tokens: 5, typeTag: "text", bytes: "c" }, ], 2_000, { baseSeq: 2 }); // ALL egress reads must work on the interleaved session — this is // exactly what broke in production (read threw, recoverEgressBase diff --git a/tests/egress-invariants-7773.test.ts b/tests/egress-invariants-7773.test.ts index f88e67e477..a859392cf8 100644 --- a/tests/egress-invariants-7773.test.ts +++ b/tests/egress-invariants-7773.test.ts @@ -69,7 +69,7 @@ let view: ReturnType | undefined; const t1 = [msg("a", 1), msg("b", 2), msg("c", 3), msg("d", 2), msg("e", 1)]; for (const m of t1) flowMaxBytes = Math.max(flowMaxBytes, JSON.stringify(m).length); for (const m of t1) stateMaxBytes = Math.max(stateMaxBytes, m.text.length); -view = egressAppendTurn(db, S, [{ type: "I", msgid: "sys", after: null, ref: "", tokens: 0, typeTag: "text", bytes: "" }, { type: "I", msgid: "a", after: "sys", ref: "m00001", tokens: 1, typeTag: "text", bytes: t1[0]!.text }, { type: "I", msgid: "b", after: "a", ref: "m00002", tokens: 2, typeTag: "text", bytes: t1[1]!.text }, { type: "I", msgid: "c", after: "b", ref: "m00003", tokens: 3, typeTag: "text", bytes: t1[2]!.text }, { type: "I", msgid: "d", after: "c", ref: "m00004", tokens: 2, typeTag: "text", bytes: t1[3]!.text }, { type: "I", msgid: "e", after: "d", ref: "m00005", tokens: 1, typeTag: "text", bytes: t1[4]!.text }], 1_000, { baseSeq: 0 }); +view = egressAppendTurn(db, S, [{ type: "I", rid: 1, msgid: "sys", after: null, ref: "", tokens: 0, typeTag: "text", bytes: "" }, { type: "I", rid: 2, msgid: "a", after: 1, ref: "m00001", tokens: 1, typeTag: "text", bytes: t1[0]!.text }, { type: "I", rid: 3, msgid: "b", after: 2, ref: "m00002", tokens: 2, typeTag: "text", bytes: t1[1]!.text }, { type: "I", rid: 4, msgid: "c", after: 3, ref: "m00003", tokens: 3, typeTag: "text", bytes: t1[2]!.text }, { type: "I", rid: 5, msgid: "d", after: 4, ref: "m00004", tokens: 2, typeTag: "text", bytes: t1[3]!.text }, { type: "I", rid: 6, msgid: "e", after: 5, ref: "m00005", tokens: 1, typeTag: "text", bytes: t1[4]!.text }], 1_000, { baseSeq: 0 }); checkMessagePlane("turn 1"); // the block plane lives alongside: two blocks, one reaped later @@ -104,8 +104,8 @@ const summaryText = `summary of ${"b".repeat(4)}`; flowMaxBytes = Math.max(flowMaxBytes, summaryText.length); stateMaxBytes = Math.max(stateMaxBytes, summaryText.length); view = egressAppendTurn(db, S, [ - { type: "D", start: "b", end: "d" }, - { type: "I", msgid: "sum", after: "a", ref: "m00006", tokens: 5, typeTag: "text", bytes: summaryText }, + { type: "D", start: 3, end: 5 }, + { type: "I", rid: 7, msgid: "sum", after: 2, ref: "m00006", tokens: 5, typeTag: "text", bytes: summaryText }, ], 2_000, { baseSeq: 6 }); checkMessagePlane("fold turn"); assert.deepEqual(egressStateView(db, S).map((r) => r.msgid), ["sys", "a", "sum", "e"]); @@ -123,11 +123,11 @@ checkBlockPlane("block fold turn"); assert.equal(egressBlockView(db, S).size, 0, "the reaped blocks are physically gone from the live view"); // turn 3: an in-place edit of a survivor — one U, state row count unchanged -view = egressAppendTurn(db, S, [{ type: "U", msgid: "e", bytes: t1[4]!.text + " (edited)", role: "user" }], 3_000, { baseSeq: 8 }); +view = egressAppendTurn(db, S, [{ type: "U", rid: 6, msgid: "e", bytes: t1[4]!.text + " (edited)", role: "user" }], 3_000, { baseSeq: 8 }); checkMessagePlane("edit turn"); // turn 4: delete the last survivor of a fold chain — the state plane shrinks -view = egressAppendTurn(db, S, [{ type: "D", start: "a", end: "a" }], 4_000, { baseSeq: 9 }); +view = egressAppendTurn(db, S, [{ type: "D", start: 2, end: 2 }], 4_000, { baseSeq: 9 }); checkMessagePlane("delete turn"); // the message plane's view must be what the ops say it is, to the end diff --git a/tests/egress-lazy-projection.test.ts b/tests/egress-lazy-projection.test.ts index 68d9a3b69a..bf6c99e46e 100644 --- a/tests/egress-lazy-projection.test.ts +++ b/tests/egress-lazy-projection.test.ts @@ -122,7 +122,7 @@ test("snapPinLiveIds: a damaged serving copy is copied again from the log; a cor // A ghost state row: pos density breaks, the serving read notices. const plantStateGhost = () => H.db - .prepare(`INSERT INTO egress_state (session_id, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 'ghost', 99, 0, 0, '', 0, 'text', 'user', 0, 0, 'x', 3)`) + .prepare(`INSERT INTO egress_state (session_id, rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 99, 'ghost', 99, 0, 0, '', 0, 'text', 'user', 0, 0, 'x', 3)`) .run("s3"); // 1. only the SERVING COPY is damaged, the log itself is intact: the // copy is rebuilt from the log and the session keeps its ids diff --git a/tests/egress-oplog-lifecycle.test.ts b/tests/egress-oplog-lifecycle.test.ts index e8003faeb9..f7cf8b5850 100644 --- a/tests/egress-oplog-lifecycle.test.ts +++ b/tests/egress-oplog-lifecycle.test.ts @@ -84,10 +84,10 @@ test("deleteSession cascades egress_state/egress_flow (plain rows, no CAS to rel const sid = "sess-egress-cascade"; egressStateAppend(db, sid, [ - { type: "I", msgid: "m1", after: null, ref: "", tokens: 5, typeTag: "text", bytes: '{"id":"m1","role":"user","text":"alpha"}', role: "user" }, - { type: "I", msgid: "m2", after: "m1", ref: "", tokens: 5, typeTag: "text", bytes: '{"id":"m2","role":"user","text":"beta"}', role: "user" }, - { type: "D", start: "m1", end: "m1" }, - { type: "U", msgid: "m2", bytes: '{"id":"m2","role":"user","text":"beta!"}', role: "user" }, + { type: "I", rid: 1, msgid: "m1", after: null, ref: "", tokens: 5, typeTag: "text", bytes: '{"id":"m1","role":"user","text":"alpha"}', role: "user" }, + { type: "I", rid: 2, msgid: "m2", after: 1, ref: "", tokens: 5, typeTag: "text", bytes: '{"id":"m2","role":"user","text":"beta"}', role: "user" }, + { type: "D", start: 1, end: 1 }, + { type: "U", rid: 2, msgid: "m2", bytes: '{"id":"m2","role":"user","text":"beta!"}', role: "user" }, ], Date.now()); const count = (t: string) => (db.prepare(`SELECT count(*) AS n FROM ${t}`).get() as { n: number }).n; assert.equal(count("egress_flow"), 4, "the flow keeps every op (append-only)"); diff --git a/tests/egress-state.test.ts b/tests/egress-state.test.ts index 64a01ad187..8ee358342e 100644 --- a/tests/egress-state.test.ts +++ b/tests/egress-state.test.ts @@ -8,7 +8,9 @@ * never existed in this form: not written, not read) and their payload * shapes; * - the hard-error paths (missing anchor / missing or inverted delete - * endpoints / update target missing) throw, never degrade fuzzy; + * endpoints / update target missing / duplicate row id) throw, never + * degrade fuzzy — and addressing is by row id (2026-11-27): a msgid may + * collide or churn, the log's anchors never do; * - egress_state is the MATERIALIZED live view: its row count == the * live row count (ORDER BY pos serving read, no replay); egress_flow * keeps every row forever (append-only, physically never deleted — @@ -72,7 +74,14 @@ const h = (m: string) => `h_${m}`; // The canonical `num` is assigned at append/replay time from the stored // high-water, so pure diff/replay fixtures carry num: 0 — comparisons ignore // it (norm); the db-backed tests assert the stamped numbers explicitly. -const norm = (rows: EgressViewRow[]) => rows.map(({ num, ...rest }) => rest); +const norm = (rows: EgressViewRow[]) => rows.map(({ num, rid, ...rest }) => rest); + +// Pure diff/replay fixtures build views without rids — diff assigns them +// defensively from its counter, but a REPLAY resolves rid anchors against +// the prev view, so tests stamp rids 1..n in view order (the same shape a +// DB-backed log holds). `next` views need none: diff reads only their +// content, and fresh rows get their rids from the diff's counter. +const stamped = (rows: EgressViewRow[]): EgressViewRow[] => rows.map((r, i) => (typeof r.rid === "number" ? r : { ...r, rid: i + 1 })); /** Total rows of a session in BOTH tables. */ @@ -98,12 +107,12 @@ function flowRows(h: Harness, S: string): number { function plant(h: Harness, S: string, op: EgressOp, opSeq: number, nowMs: number): void { const written = op.type === "I" - ? ["I", op.msgid, JSON.stringify({ after: op.after, ref: op.ref, tokens: op.tokens, type: op.typeTag, role: op.role }), 9, op.bytes] + ? ["I", op.rid, op.msgid, JSON.stringify({ after: op.after, ref: op.ref, tokens: op.tokens, type: op.typeTag, role: op.role }), 9, op.bytes] : op.type === "D" - ? ["D", null, JSON.stringify({ start: op.start, end: op.end }), null, null] - : ["U", op.msgid, JSON.stringify({ role: op.role }), null, op.bytes]; - const [rowType, msgid, payload, logSeq, bytes] = written; - h.db.prepare(`INSERT INTO egress_flow (session_id, op_seq, log_seq, row_type, msgid, payload, bytes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(S, opSeq, logSeq, rowType, msgid, payload, bytes, nowMs); + ? ["D", null, null, JSON.stringify({ start: op.start, end: op.end }), null, null] + : ["U", op.rid, op.msgid, JSON.stringify({ role: op.role }), null, op.bytes]; + const [rowType, rid, msgid, payload, logSeq, bytes] = written as [string, number | null, string | null, string, number | null, string | null]; + h.db.prepare(`INSERT INTO egress_flow (session_id, op_seq, log_seq, row_type, rid, msgid, payload, bytes, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(S, opSeq, logSeq, rowType, rid, msgid, payload, bytes, nowMs); } test("replay determinism: the five-op example from the proposal", () => { @@ -114,11 +123,11 @@ test("replay determinism: the five-op example from the proposal", () => { // names the row it follows (#7574: the stored replay now agrees with // the diff on this — it used to put an unanchored row at the end) egressStateAppend(H.db, S, [ - { type: "I", msgid: "a", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "h_a1" }, - { type: "I", msgid: "b", after: "a", ref: "m00002", tokens: 4, typeTag: "text", bytes: "h_b1" }, - { type: "I", msgid: "c", after: "b", ref: "m00003", tokens: 9, typeTag: "summary", bytes: "h_c1" }, - { type: "D", start: "a", end: "b" }, - { type: "U", msgid: "c", bytes: "h_c2" }, + { type: "I", rid: 1, msgid: "a", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "h_a1" }, + { type: "I", rid: 2, msgid: "b", after: 1, ref: "m00002", tokens: 4, typeTag: "text", bytes: "h_b1" }, + { type: "I", rid: 3, msgid: "c", after: 2, ref: "m00003", tokens: 9, typeTag: "summary", bytes: "h_c1" }, + { type: "D", start: 1, end: 2 }, + { type: "U", rid: 3, msgid: "c", bytes: "h_c2" }, ], 1_000); const view = egressStateView(H.db, S); assert.deepEqual(view.map((r) => r.msgid), ["c"]); @@ -142,25 +151,27 @@ test("+I anchored insert lands mid-history; an unanchored +I is the new first ro try { const S = "sess-2"; egressStateAppend(H.db, S, [ - { type: "I", msgid: "a", after: null, ref: "m00001", tokens: 1, typeTag: "text", bytes: "h_a" }, - { type: "I", msgid: "d", after: "a", ref: "m00002", tokens: 1, typeTag: "text", bytes: "h_d" }, - { type: "I", msgid: "e", after: "d", ref: "m00003", tokens: 1, typeTag: "text", bytes: "h_e" }, + { type: "I", rid: 1, msgid: "a", after: null, ref: "m00001", tokens: 1, typeTag: "text", bytes: "h_a" }, + { type: "I", rid: 2, msgid: "d", after: 1, ref: "m00002", tokens: 1, typeTag: "text", bytes: "h_d" }, + { type: "I", rid: 3, msgid: "e", after: 2, ref: "m00003", tokens: 1, typeTag: "text", bytes: "h_e" }, // mid-history insert anchored at a (positions of d/e shift) - { type: "I", msgid: "b", after: "a", ref: "m00004", tokens: 1, typeTag: "text", bytes: "h_b" }, - { type: "I", msgid: "c", after: "b", ref: "m00005", tokens: 1, typeTag: "text", bytes: "h_c" }, + { type: "I", rid: 4, msgid: "b", after: 1, ref: "m00004", tokens: 1, typeTag: "text", bytes: "h_b" }, + { type: "I", rid: 5, msgid: "c", after: 4, ref: "m00005", tokens: 1, typeTag: "text", bytes: "h_c" }, ], 1_000); assert.deepEqual(egressStateView(H.db, S).map((r) => r.msgid), ["a", "b", "c", "d", "e"]); + assert.deepEqual(egressStateView(H.db, S).map((r) => r.rid), [1, 4, 5, 2, 3], "the live view's rids follow the flow history, not the positions"); // a system prompt that shows up in a later turn becomes the FIRST row // (what the diff asks for; what the lane then serves) egressStateAppend(H.db, S, [ - { type: "I", msgid: "sys", after: null, ref: "m00006", tokens: 0, typeTag: "system", bytes: "h_sys" }, + { type: "I", rid: 6, msgid: "sys", after: null, ref: "m00006", tokens: 0, typeTag: "system", bytes: "h_sys" }, ], 1_500); assert.deepEqual(egressStateView(H.db, S).map((r) => r.msgid), ["sys", "a", "b", "c", "d", "e"]); - // a fold deletes b..d — sys, a and e survive in place - egressStateAppend(H.db, S, [{ type: "D", start: "b", end: "d" }], 2_000); + // a fold deletes b..d (rids 4,5,2 by position — b=4, c=5, d=2) — + // sys, a and e survive in place + egressStateAppend(H.db, S, [{ type: "D", start: 4, end: 2 }], 2_000); assert.deepEqual(egressStateView(H.db, S).map((r) => r.msgid), ["sys", "a", "e"]); // single-row delete (start == end) - egressStateAppend(H.db, S, [{ type: "D", start: "a", end: "a" }], 3_000); + egressStateAppend(H.db, S, [{ type: "D", start: 1, end: 1 }], 3_000); assert.deepEqual(egressStateView(H.db, S).map((r) => r.msgid), ["sys", "e"]); } finally { close(H); @@ -175,8 +186,8 @@ test("hard errors: missing anchor / missing or inverted endpoints / update targe // only ever surface the earliest one. const seed = (S: string) => { egressStateAppend(H.db, S, [ - { type: "I", msgid: "a", after: null, ref: "m00001", tokens: 1, typeTag: "text", bytes: "h_a" }, - { type: "I", msgid: "b", after: "a", ref: "m00002", tokens: 1, typeTag: "text", bytes: "h_b" }, + { type: "I", rid: 1, msgid: "a", after: null, ref: "m00001", tokens: 1, typeTag: "text", bytes: "h_a" }, + { type: "I", rid: 2, msgid: "b", after: 1, ref: "m00002", tokens: 1, typeTag: "text", bytes: "h_b" }, ], 1_000); }; const corrupt = (e: unknown, re: RegExp) => e instanceof EgressStateCorruptError && re.test(e.message); @@ -190,15 +201,24 @@ test("hard errors: missing anchor / missing or inverted endpoints / update targe assert.deepEqual(egressStateView(H.db, S).map((r) => r.msgid), ["a", "b"], `${S}: still on the healthy point`); }; refused("anchor-missing", [ - { type: "I", msgid: "x", after: "zz", ref: "m00003", tokens: 1, typeTag: "text", bytes: "h_x" }, - ], /anchor zz missing/); - refused("endpoint-missing", [{ type: "D", start: "a", end: "nope" }], /delete end nope missing/); - refused("start-missing", [{ type: "D", start: "nope", end: "b" }], /delete start nope missing/); - refused("inverted", [{ type: "D", start: "b", end: "a" }], /inverted/); - refused("update-missing", [{ type: "U", msgid: "ghost", bytes: "h_g" }], /update target ghost missing/); - refused("dup", [ - { type: "I", msgid: "a", after: null, ref: "m00009", tokens: 1, typeTag: "text", bytes: "h_a2" }, - ], /duplicate msgid a/); + { type: "I", rid: 3, msgid: "x", after: 99, ref: "m00003", tokens: 1, typeTag: "text", bytes: "h_x" }, + ], /anchor rid 99 missing/); + refused("endpoint-missing", [{ type: "D", start: 1, end: 99 }], /delete end rid 99 missing/); + refused("start-missing", [{ type: "D", start: 99, end: 2 }], /delete start rid 99 missing/); + refused("inverted", [{ type: "D", start: 2, end: 1 }], /inverted/); + refused("update-missing", [{ type: "U", rid: 99, msgid: "ghost", bytes: "h_g" }], /update target rid 99 missing/); + refused("dup-rid", [ + { type: "I", rid: 1, msgid: "x", after: null, ref: "m00009", tokens: 1, typeTag: "text", bytes: "h_x" }, + ], /duplicate row id 1/); + // 2026-11-27 (row ids): a COLLIDING msgid on a fresh row is legal at + // the log layer — addressing is by rid, so the two rows stay + // distinguishable (before/after an edit or a re-homing) where msgids + // cannot be. + seed("collide"); + egressStateAppend(H.db, "collide", [ + { type: "I", rid: 3, msgid: "a", after: 1, ref: "m00009", tokens: 1, typeTag: "text", bytes: "h_x" }, + ], 3_000); + assert.deepEqual(egressStateView(H.db, "collide").map((r) => r.rid), [1, 3, 2], "same msgid, fresh rid: both rows live and distinct"); // 7773: a bad row that got into the FLOW some other way (a library // edited by hand, a half-copied backup) must NOT break serving while // the materialized view is intact — the read is a consistent @@ -210,9 +230,9 @@ test("hard errors: missing anchor / missing or inverted endpoints / update targe assert.deepEqual(egressStateView(H.db, S).map((r) => r.msgid), ["a", "b"], `${S}: the intact view still serves`); assert.throws(() => egressStateAt(H.db, S, Number.MAX_SAFE_INTEGER), (e: unknown) => corrupt(e, re), `${S}: the full replay reports the planted bad row`); }; - planted("planted-anchor", { type: "I", msgid: "x", after: "zz", ref: "m00003", tokens: 1, typeTag: "text", bytes: "h_x" }, /anchor zz missing/); - planted("planted-end", { type: "D", start: "a", end: "nope" }, /delete end nope missing/); - planted("planted-dup", { type: "I", msgid: "a", after: "b", ref: "m00009", tokens: 1, typeTag: "text", bytes: "h_a2" }, /duplicate msgid a/); + planted("planted-anchor", { type: "I", rid: 3, msgid: "x", after: 99, ref: "m00003", tokens: 1, typeTag: "text", bytes: "h_x" }, /anchor rid 99 missing/); + planted("planted-end", { type: "D", start: 1, end: 99 }, /delete end rid 99 missing/); + planted("planted-dup", { type: "I", rid: 1, msgid: "a", after: 2, ref: "m00009", tokens: 1, typeTag: "text", bytes: "h_a2" }, /duplicate row id 1/); // and the healthy sessions in the same db still replay cleanly (no // cross-session leakage from the corrupt rows) seed("healthy"); @@ -232,12 +252,12 @@ test("materialized view: state row count == live row count, flow keeps its full const S = "sess-4"; // 10 tail appends, then a fold collapses 1..6 into one summary const ops: EgressOp[] = []; - ops.push({ type: "I", msgid: "m1", after: null, ref: "m00001", tokens: 1, typeTag: "text", bytes: "h_m1" }); + ops.push({ type: "I", rid: 1, msgid: "m1", after: null, ref: "m00001", tokens: 1, typeTag: "text", bytes: "h_m1" }); for (let i = 2; i <= 10; i++) { - ops.push({ type: "I", msgid: `m${i}`, after: `m${i - 1}`, ref: `m0000${i}`, tokens: i, typeTag: "text", bytes: `h_m${i}` }); + ops.push({ type: "I", rid: i, msgid: `m${i}`, after: i - 1, ref: `m0000${i}`, tokens: i, typeTag: "text", bytes: `h_m${i}` }); } - ops.push({ type: "I", msgid: "fold", after: "m6", ref: "m00011", tokens: 77, typeTag: "summary", bytes: "h_fold" }); - ops.push({ type: "D", start: "m1", end: "m6" }); + ops.push({ type: "I", rid: 11, msgid: "fold", after: 6, ref: "m00011", tokens: 77, typeTag: "summary", bytes: "h_fold" }); + ops.push({ type: "D", start: 1, end: 6 }); egressStateAppend(H.db, S, ops, 1_000); const before = egressStateView(H.db, S); assert.deepEqual(before.map((r) => r.msgid), ["fold", "m7", "m8", "m9", "m10"]); @@ -261,7 +281,7 @@ test("materialized view: state row count == live row count, flow keeps its full // ops after the fold still apply on the live view, numbers continue // from the flow high-water (11) egressStateAppend(H.db, S, [ - { type: "I", msgid: "m11", after: "m10", ref: "m00012", tokens: 11, typeTag: "text", bytes: "h_m11" }, + { type: "I", rid: 12, msgid: "m11", after: 10, ref: "m00012", tokens: 11, typeTag: "text", bytes: "h_m11" }, ], 3_000); const grown = egressStateView(H.db, S); assert.deepEqual(grown.map((r) => r.msgid), ["fold", "m7", "m8", "m9", "m10", "m11"]); @@ -283,18 +303,18 @@ test("rollback: every point — from 0 up — stays reconstructible from egress_ const snapshots = new Map(); for (let i = 1; i <= 5; i++) { egressStateAppend(H.db, S, [ - { type: "I", msgid: `m${i}`, after: i === 1 ? null : `m${i - 1}`, ref: `m0000${i}`, tokens: i, typeTag: "text", bytes: `h_m${i}` }, + { type: "I", rid: i, msgid: `m${i}`, after: i === 1 ? null : i - 1, ref: `m0000${i}`, tokens: i, typeTag: "text", bytes: `h_m${i}` }, ], 1_000 + i); snapshots.set(i, egressStateView(H.db, S)); } - egressStateAppend(H.db, S, [{ type: "U", msgid: "m2", bytes: "h_m2-edit" }], 6_000); + egressStateAppend(H.db, S, [{ type: "U", rid: 2, msgid: "m2", bytes: "h_m2-edit" }], 6_000); snapshots.set(6, egressStateView(H.db, S)); assert.equal(snapshots.get(6)![1].num, 2, "the +U did not change m2's canonical number"); // the materialized view serves the current point byte-identically to // the full replay (state == replay(flow) after every write) assert.deepEqual(egressStateView(H.db, S), egressStateAt(H.db, S, 6)); egressStateAppend(H.db, S, [ - { type: "I", msgid: "m6", after: "m5", ref: "m00006", tokens: 6, typeTag: "text", bytes: "h_m6" }, + { type: "I", rid: 6, msgid: "m6", after: 5, ref: "m00006", tokens: 6, typeTag: "text", bytes: "h_m6" }, ], 11_000); const later = egressStateView(H.db, S); assert.deepEqual(egressStateAt(H.db, S, 7), later, "a point after the last write"); @@ -317,38 +337,38 @@ const V = (msgid: string, bytes = "h_" + msgid, ref = "m" + msgid, tokens = 3, t test("diff: case 1 — tail append emits exactly one +I anchored to the last row", () => { - const prev = [V("a"), V("b")]; - const next = [V("a"), V("b"), V("c")]; + const prev = stamped([V("a"), V("b")]); + const next = [...prev, V("c")]; const ops = diffEgressView(prev, next); - assert.deepEqual(ops, [{ type: "I", msgid: "c", after: "b", ref: "mc", tokens: 3, typeTag: "text", bytes: "h_c" }]); + assert.deepEqual(ops, [{ type: "I", rid: 3, msgid: "c", after: 2, ref: "mc", tokens: 3, typeTag: "text", bytes: "h_c" }]); assert.deepEqual(norm(egressReplay(prev, ops)), norm(next)); }); test("diff: cases 2+3 — nudge appears (+I) and vanishes (-D) without touching the prefix", () => { - const base = [V("a"), V("b")]; - const nudged = [V("a"), V("b"), V("nudge", "h_n", "mn", 1, "nudge")]; + const base = stamped([V("a"), V("b")]); + const nudged = stamped([...base, V("nudge", "h_n", "mn", 1, "nudge")]); assert.deepEqual(diffEgressView(base, nudged), [ - { type: "I", msgid: "nudge", after: "b", ref: "mn", tokens: 1, typeTag: "nudge", bytes: "h_n" }, + { type: "I", rid: 3, msgid: "nudge", after: 2, ref: "mn", tokens: 1, typeTag: "nudge", bytes: "h_n" }, ]); assert.deepEqual(norm(egressReplay(base, diffEgressView(base, nudged))), norm(nudged)); - assert.deepEqual(diffEgressView(nudged, base), [{ type: "D", start: "nudge", end: "nudge" }]); + assert.deepEqual(diffEgressView(nudged, base), [{ type: "D", start: 3, end: 3 }]); assert.deepEqual(norm(egressReplay(nudged, diffEgressView(nudged, base))), norm(base)); }); test("diff: case 4 — fold replaces a range with one summary row after the surviving anchor", () => { - const prev = [V("a"), V("b"), V("c"), V("d"), V("e"), V("f")]; + const prev = stamped([V("a"), V("b"), V("c"), V("d"), V("e"), V("f")]); const folded = [V("a"), V("sum", "h_sum", "ms", 42, "acp_summary"), V("f")]; assert.deepEqual(diffEgressView(prev, folded), [ - { type: "D", start: "b", end: "e" }, - { type: "I", msgid: "sum", after: "a", ref: "ms", tokens: 42, typeTag: "acp_summary", bytes: "h_sum" }, + { type: "D", start: 2, end: 5 }, + { type: "I", rid: 7, msgid: "sum", after: 1, ref: "ms", tokens: 42, typeTag: "acp_summary", bytes: "h_sum" }, ]); assert.deepEqual(norm(egressReplay(prev, diffEgressView(prev, folded))), norm(folded)); }); test("diff: case U — content edit of an existing row is a +U, position and triple untouched", () => { - const prev = [V("a", "h_a1"), V("b")]; - const next = [V("a", "h_a2"), V("b")]; - assert.deepEqual(diffEgressView(prev, next), [{ type: "U", msgid: "a", bytes: "h_a2" }]); + const prev = stamped([V("a", "h_a1"), V("b")]); + const next = [{ ...prev[0], bytes: "h_a2" }, prev[1]]; + assert.deepEqual(diffEgressView(prev, next), [{ type: "U", rid: 1, msgid: "a", bytes: "h_a2" }]); const replayed = egressReplay(prev, diffEgressView(prev, next)); assert.deepEqual(norm(replayed), norm(next)); assert.equal(replayed[0].ref, "ma", "+U must not touch the ref"); @@ -366,13 +386,13 @@ test("diff: case U — content edit of an existing row is a +U, position and tri test("diff: a spine row that loses its citation emits a +U with num 0", () => { const R = (msgid: string, num: number): EgressViewRow => ({ num, msgid, ref: "m" + msgid, tokens: 3, type: "text", bytes: "h_" + msgid }); - const prev = [R("a", 2), R("p1", 91), R("p2", 92)]; + const prev = stamped([R("a", 2), R("p1", 91), R("p2", 92)]); const next = [{ ...R("p1", 0) }, { ...R("p2", 0) }, R("r", 91)]; assert.deepEqual(diffEgressView(prev, next, true), [ - { type: "D", start: "a", end: "a" }, - { type: "U", msgid: "p1", bytes: "h_p1", num: 0 }, - { type: "U", msgid: "p2", bytes: "h_p2", num: 0 }, - { type: "I", msgid: "r", after: "p2", ref: "mr", tokens: 3, typeTag: "text", bytes: "h_r", num: 91 }, + { type: "D", start: 1, end: 1 }, + { type: "U", rid: 2, msgid: "p1", bytes: "h_p1", num: 0 }, + { type: "U", rid: 3, msgid: "p2", bytes: "h_p2", num: 0 }, + { type: "I", rid: 4, msgid: "r", after: 3, ref: "mr", tokens: 3, typeTag: "text", bytes: "h_r", num: 91 }, ]); const replayed = egressReplay(prev, diffEgressView(prev, next, true), 92); assert.deepEqual(norm(replayed), norm(next)); @@ -381,18 +401,18 @@ test("diff: a spine row that loses its citation emits a +U with num 0", () => { test("diff+replay: re-citing a slot held by a STILL-cited live row still throws (true corruption)", () => { const R = (msgid: string, num: number): EgressViewRow => ({ num, msgid, ref: "m" + msgid, tokens: 3, type: "text", bytes: "h_" + msgid }); - const prev = [R("a", 91)]; - const next = [{ ...R("a", 91) }, R("r", 91)]; + const prev = stamped([R("a", 91)]); + const next = [...prev, R("r", 91)]; const ops = diffEgressView(prev, next, true); - assert.deepEqual(ops, [{ type: "I", msgid: "r", after: "a", ref: "mr", tokens: 3, typeTag: "text", bytes: "h_r", num: 91 }]); + assert.deepEqual(ops, [{ type: "I", rid: 2, msgid: "r", after: 1, ref: "mr", tokens: 3, typeTag: "text", bytes: "h_r", num: 91 }]); assert.throws(() => egressReplay(prev, ops, 91), (e: unknown) => e instanceof EgressStateCorruptError && /cited number 91 is already live/.test(e.message)); }); test("diff: a spine row that gains a citation below the high water emits a +U with it (retired slot re-homing)", () => { const R = (msgid: string, num: number): EgressViewRow => ({ num, msgid, ref: "m" + msgid, tokens: 3, type: "text", bytes: "h_" + msgid }); - const prev = [R("a", 0), R("b", 92)]; + const prev = stamped([R("a", 0), R("b", 92)]); const next = [{ ...R("a", 5) }, { ...R("b", 92) }]; - assert.deepEqual(diffEgressView(prev, next, true), [{ type: "U", msgid: "a", bytes: "h_a", num: 5 }]); + assert.deepEqual(diffEgressView(prev, next, true), [{ type: "U", rid: 1, msgid: "a", bytes: "h_a", num: 5 }]); const replayed = egressReplay(prev, diffEgressView(prev, next, true), 92); assert.equal(replayed[0].num, 5, "a retired slot is legal to re-cite"); }); @@ -404,25 +424,25 @@ test("append: a U with num persists through state replay, compaction, and the de // seed: system + a cited row at 2 and a dense pair at 91/92 (the // shape the live repro produced: protection rows dense-allocated) egressStateAppend(H.db, S, [ - { type: "I", msgid: EGRESS_SYSTEM_MSGID, after: null, ref: "", tokens: 1, typeTag: "system", bytes: "h_sys" }, - { type: "I", msgid: "a", after: EGRESS_SYSTEM_MSGID, ref: "m00002", tokens: 2, typeTag: "text", bytes: "h_a", num: 2 }, - { type: "I", msgid: "p1", after: "a", ref: "", tokens: 3, typeTag: "text", bytes: "h_p1" }, - { type: "I", msgid: "p2", after: "p1", ref: "", tokens: 3, typeTag: "text", bytes: "h_p2" }, + { type: "I", rid: 1, msgid: EGRESS_SYSTEM_MSGID, after: null, ref: "", tokens: 1, typeTag: "system", bytes: "h_sys" }, + { type: "I", rid: 2, msgid: "a", after: 1, ref: "m00002", tokens: 2, typeTag: "text", bytes: "h_a", num: 2 }, + { type: "I", rid: 3, msgid: "p1", after: 2, ref: "", tokens: 3, typeTag: "text", bytes: "h_p1" }, + { type: "I", rid: 4, msgid: "p2", after: 3, ref: "", tokens: 3, typeTag: "text", bytes: "h_p2" }, ], 1_000); const seeded = egressStateView(H.db, S); assert.deepEqual(seeded.map((r) => r.num), [0, 2, 3, 4], "dense allocation, before the repro shape"); // bring it into the repro shape with an explicit num on the cites egressStateAppend(H.db, S, [ - { type: "U", msgid: "p1", bytes: "h_p1", num: 91 }, - { type: "U", msgid: "p2", bytes: "h_p2", num: 92 }, + { type: "U", rid: 3, msgid: "p1", bytes: "h_p1", num: 91 }, + { type: "U", rid: 4, msgid: "p2", bytes: "h_p2", num: 92 }, ], 2_000); assert.deepEqual(egressStateView(H.db, S).map((r) => r.num), [0, 2, 91, 92], "the U-with-num lands in the stored view"); // the fix turn: both protection rows lose their citation; the fresh // reply cites 91 (the kernel counter never saw 91/92) egressStateAppend(H.db, S, [ - { type: "U", msgid: "p1", bytes: "h_p1", num: 0 }, - { type: "U", msgid: "p2", bytes: "h_p2", num: 0 }, - { type: "I", msgid: "r", after: "p2", ref: "m00091", tokens: 3, typeTag: "text", bytes: "h_r", num: 91 }, + { type: "U", rid: 3, msgid: "p1", bytes: "h_p1", num: 0 }, + { type: "U", rid: 4, msgid: "p2", bytes: "h_p2", num: 0 }, + { type: "I", rid: 5, msgid: "r", after: 4, ref: "m00091", tokens: 3, typeTag: "text", bytes: "h_r", num: 91 }, ], 3_000); assert.deepEqual(egressStateView(H.db, S).map((r) => r.num), [0, 2, 0, 0, 91], "demote + re-cite lands"); // the state rows carry the immutable I-twin anchors: the demoted rows @@ -453,7 +473,7 @@ test("append: a U with num persists through state replay, compaction, and the de // +U demotion (its kernel citation fact is 0), which frees the slot // earlier in the same batch. egressStateAppend(H.db, S, [ - { type: "I", msgid: "x", after: "r", ref: "", tokens: 1, typeTag: "text", bytes: "h_x" }, + { type: "I", rid: 6, msgid: "x", after: 5, ref: "", tokens: 1, typeTag: "text", bytes: "h_x" }, ], 5_000); const view = egressStateView(H.db, S); assert.equal(view[view.length - 1].num, 92, "dense continues above the flow high water"); @@ -464,28 +484,29 @@ test("append: a U with num persists through state replay, compaction, and the de } }); -test("diff: move = D+I (no M op), msgid survives both ops", () => { - const prev = [V("a"), V("b")]; - const next = [V("b"), V("a")]; +test("diff: move = D+I (no M op), msgid survives both ops — and the move CONSUMES a rid", () => { + const prev = stamped([V("a"), V("b")]); + const next = [prev[1], prev[0]]; assert.deepEqual(diffEgressView(prev, next), [ - { type: "D", start: "a", end: "a" }, - { type: "I", msgid: "a", after: "b", ref: "ma", tokens: 3, typeTag: "text", bytes: "h_a" }, + { type: "D", start: 1, end: 1 }, + { type: "I", rid: 3, msgid: "a", after: 2, ref: "ma", tokens: 3, typeTag: "text", bytes: "h_a" }, ]); const moved = egressReplay(prev, diffEgressView(prev, next)); assert.deepEqual(norm(moved), norm(next)); + assert.equal(moved.find((r) => r.msgid === "a")!.rid, 3, "2026-11-27: the D+I move lands on a FRESH rid; the retired one (1) stays spent — before/after stays distinguishable"); assert.equal(moved.find((r) => r.msgid === "a")!.num, 1, "the D+I move takes the next number; the old one stays retired"); }); test("diff: empty views and empty diff (both directions)", () => { assert.deepEqual(diffEgressView([], []), []); - assert.deepEqual(diffEgressView([V("a"), V("b")], [V("a"), V("b")]), []); + assert.deepEqual(diffEgressView(stamped([V("a"), V("b")]), [V("a"), V("b")]), []); const fromEmpty = diffEgressView([], [V("a"), V("b")]); assert.deepEqual(fromEmpty, [ - { type: "I", msgid: "a", after: null, ref: "ma", tokens: 3, typeTag: "text", bytes: "h_a" }, - { type: "I", msgid: "b", after: "a", ref: "mb", tokens: 3, typeTag: "text", bytes: "h_b" }, + { type: "I", rid: 1, msgid: "a", after: null, ref: "ma", tokens: 3, typeTag: "text", bytes: "h_a" }, + { type: "I", rid: 2, msgid: "b", after: 1, ref: "mb", tokens: 3, typeTag: "text", bytes: "h_b" }, ]); - const toEmpty = diffEgressView([V("a"), V("b")], []); - assert.deepEqual(toEmpty, [{ type: "D", start: "a", end: "b" }]); + const toEmpty = diffEgressView(stamped([V("a"), V("b")]), []); + assert.deepEqual(toEmpty, [{ type: "D", start: 1, end: 2 }]); }); test("diff property: 300 random sparse mutations — replay(prev, diff) ≡ next, ops apply to the DB state too", () => { @@ -517,7 +538,10 @@ test("diff property: 300 random sparse mutations — replay(prev, diff) ≡ next } const ops = diffEgressView(prev, next); assert.deepEqual(norm(egressReplay(prev, ops)), norm(next), `replay identity at iter ${iter}`); - view = next; + // carry the REPLAYED view forward (it carries the rids the next + // iteration's diff/replay must resolve; norm-identity above + // already proved it equals `next`) + view = egressReplay(prev, ops); } // the final view also round-trips through the DB: rebuild from ops const S = "prop-db"; @@ -542,10 +566,10 @@ test("fork: whole-table copy — the child inherits the parent number space and const P = "parent"; const C = "child"; egressStateAppend(H.db, P, [ - { type: "I", msgid: "a", after: null, ref: "m00001", tokens: 1, typeTag: "text", bytes: "h_a" }, - { type: "I", msgid: "b", after: "a", ref: "m00002", tokens: 1, typeTag: "text", bytes: "h_b" }, - { type: "I", msgid: "sum", after: "b", ref: "m00003", tokens: 5, typeTag: "summary", bytes: "h_sum" }, - { type: "D", start: "a", end: "b" }, + { type: "I", rid: 1, msgid: "a", after: null, ref: "m00001", tokens: 1, typeTag: "text", bytes: "h_a" }, + { type: "I", rid: 2, msgid: "b", after: 1, ref: "m00002", tokens: 1, typeTag: "text", bytes: "h_b" }, + { type: "I", rid: 3, msgid: "sum", after: 2, ref: "m00003", tokens: 5, typeTag: "summary", bytes: "h_sum" }, + { type: "D", start: 1, end: 2 }, ], 1_000); // no compaction step exists (7773): the state IS the live view and // the flow keeps everything — the fork copies both tables as-is @@ -556,15 +580,17 @@ test("fork: whole-table copy — the child inherits the parent number space and assert.deepEqual(egressStateView(H.db, C), parentView, "child view == parent view (incl. numbers)"); // the child's NEXT number continues where the parent stopped (a=1, - // b=2, sum=3 — b's deletion retired 2, it is never re-issued) + // b=2, sum=3 — b's deletion retired 2, it is never re-issued) AND + // its next rid continues where the parent's flow stopped (1..3 + // spent, 2 twice-over by the D) egressStateAppend(H.db, C, [ - { type: "I", msgid: "c2", after: "sum", ref: "m00004", tokens: 1, typeTag: "text", bytes: "h_c2" }, + { type: "I", rid: 4, msgid: "c2", after: 3, ref: "m00004", tokens: 1, typeTag: "text", bytes: "h_c2" }, ], 3_000); const childView = egressStateView(H.db, C); assert.equal(childView.find((r) => r.msgid === "c2")!.num, 4, "child continues the parent high-water"); // and the parent's own next number is UNTOUCHED by the fork egressStateAppend(H.db, P, [ - { type: "I", msgid: "p2", after: "sum", ref: "m00005", tokens: 1, typeTag: "text", bytes: "h_p2" }, + { type: "I", rid: 4, msgid: "p2", after: 3, ref: "m00005", tokens: 1, typeTag: "text", bytes: "h_p2" }, ], 4_000); assert.equal(egressStateView(H.db, P).find((r) => r.msgid === "p2")!.num, 4, "parent numbering independent of the fork"); diff --git a/tests/identity-tables-consolidate.test.ts b/tests/identity-tables-consolidate.test.ts index 80e664f7e0..b30a0fbe8e 100644 --- a/tests/identity-tables-consolidate.test.ts +++ b/tests/identity-tables-consolidate.test.ts @@ -90,12 +90,14 @@ function insertSession(db: ReturnType["db"], sid: str function egressOnRow(db: ReturnType["db"], sid: string, atMs: number, msgids: string[]): void { insertSession(db, sid, atMs, { egressAuthority: true }); - let after: string | null = null; + let after: number | null = null; + let rid = 0; for (const m of msgids) { + rid += 1; egressStateAppend(db, sid, [ - { type: "I", msgid: m, after, ref: "", tokens: 3, typeTag: "text", bytes: `{"id":"${m}","role":"user","text":"${m}"}`, role: "user" }, + { type: "I", rid, msgid: m, after, ref: "", tokens: 3, typeTag: "text", bytes: `{"id":"${m}","role":"user","text":"${m}"}`, role: "user" }, ], atMs); - after = m; + after = rid; } } @@ -320,7 +322,7 @@ test("S5: GC — an egress-on session with RECENT op-log activity is not stale e try { insertSession(h.db, sid, Date.now() - 100 * 86_400_000, { egressAuthority: true }); // row froze 100 days ago egressStateAppend(h.db, sid, [ - { type: "I", msgid: "m1", after: null, ref: "", tokens: 3, typeTag: "text", bytes: '{"id":"m1","role":"user","text":"m1"}', role: "user" }, + { type: "I", rid: 1, msgid: "m1", after: null, ref: "", tokens: 3, typeTag: "text", bytes: '{"id":"m1","role":"user","text":"m1"}', role: "user" }, ], Date.now() - 60_000); // but the op log moved a minute ago const plan = h.store.gcPlan(30); assert.ok(!plan.candidates.some((c) => c.sessionId === sid), "freshness = max(updated_at, last op-log row) — the session is active"); diff --git a/tests/issue7574-egress-log-integrity.test.ts b/tests/issue7574-egress-log-integrity.test.ts index 90d0898ba6..f5f09a4bb1 100644 --- a/tests/issue7574-egress-log-integrity.test.ts +++ b/tests/issue7574-egress-log-integrity.test.ts @@ -110,8 +110,8 @@ test("a batch that would break the log is refused before anything is written", ( const baseSeq = H.store.egressStateMaxSeq(S); const before = shape(H, S); assert.throws( - () => H.store.egressAppendTurn(S, [{ type: "I", msgid: "x", after: "not-there", ref: "m00009", tokens: 1, typeTag: "text", bytes: "h_x" }], baseSeq, 2), - (e: unknown) => e instanceof EgressStateCorruptError && /insert anchor not-there missing/.test(e.message), + () => H.store.egressAppendTurn(S, [{ type: "I", rid: 98, msgid: "x", after: 99, ref: "m00009", tokens: 1, typeTag: "text", bytes: "h_x" }], baseSeq, 2), + (e: unknown) => e instanceof EgressStateCorruptError && /insert anchor rid 99 missing/.test(e.message), ); assert.deepEqual(shape(H, S), before, "nothing was written"); assert.deepEqual(ids(H.store.egressStateView(S)), [SYS, "a", "b"], "the session is still on its healthy point"); @@ -169,14 +169,14 @@ test("the materialized state is healed by a full-history replay; a state row the const max = H.store.egressStateMaxSeq(S); // 1. the state alone is damaged (an orphan row): the self-healing // read replays the flow and rebuilds the state in place - H.db.prepare("INSERT INTO egress_state (session_id, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 'ghost', 99, 0, 0, '', 0, 'text', 'user', 0, 0, 'x', 9)") + H.db.prepare("INSERT INTO egress_state (session_id, rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 99, 'ghost', 99, 0, 0, '', 0, 'text', 'user', 0, 0, 'x', 9)") .run(S); assert.deepEqual(ids(H.store.egressStateView(S)), good, "the read answers from the flow, healed"); assert.equal(H.store.egressStateMaxSeq(S), max, "the flow is untouched"); assert.deepEqual(shape(H, S).state, good, "the orphan row was removed when the state was rebuilt"); // 2. the state alone runs AHEAD of the flow (a write that reached // one table): the row the flow does not carry is not served - H.db.prepare("INSERT INTO egress_state (session_id, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 'ghost', 99, 9, 9, 'm00009', 1, 'text', 'user', 0, 0, 'x', 9)") + H.db.prepare("INSERT INTO egress_state (session_id, rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 99, 'ghost', 99, 9, 9, 'm00009', 1, 'text', 'user', 0, 0, 'x', 9)") .run(S); assert.deepEqual(ids(H.store.egressStateView(S)), good, "a row the flow does not have is not served"); assert.deepEqual(shape(H, S).state, good, "the state is the flow, row for row"); @@ -195,7 +195,7 @@ test("the rebuild replays the flow row for row and leaves nothing of the old sta const S = "s-rebuild"; const view = recordEgressTurn({ store: H.ops, sessionId: S, prev: undefined, conversation: [M("a", "1"), M("b", "2")], systemText: "sys", nowMs: 1 }); H.db.prepare("DELETE FROM egress_state WHERE session_id = ?").run(S); - H.db.prepare("INSERT INTO egress_state (session_id, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 'ghost', 99, 0, 0, '', 0, 'text', 'user', 0, 0, 'x', 9)") + H.db.prepare("INSERT INTO egress_state (session_id, rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 99, 'ghost', 99, 0, 0, '', 0, 'text', 'user', 0, 0, 'x', 9)") .run(S); const rebuilt = egressRebuildState(H.db, S); assert.deepEqual(rebuilt, view, "the view comes back from the flow"); diff --git a/tests/issue7574-storage-schema-followups.test.ts b/tests/issue7574-storage-schema-followups.test.ts index e9de17cd1f..6c82180227 100644 --- a/tests/issue7574-storage-schema-followups.test.ts +++ b/tests/issue7574-storage-schema-followups.test.ts @@ -65,7 +65,7 @@ test("#7574 a library interrupted between the two egress tables completes on its assert.ok(names.includes("egress_flow"), "the missing egress_flow is created"); const idx = (db.prepare("SELECT name FROM sqlite_master WHERE type = 'index' AND name IN ('idx_egress_state_msgid', 'idx_egress_flow_msgid') ORDER BY name").all() as unknown as { name: string }[]) .map((r) => r.name); - assert.deepEqual(idx, ["idx_egress_flow_msgid"], "only the flow index of the group exists (7773: the state PK covers msgid lookups)"); + assert.deepEqual(idx, ["idx_egress_flow_msgid", "idx_egress_state_msgid"], "both msgid lookup indexes exist (PK is now (session_id, rid) — 2026-11-27 owner ruling)"); assert.ok( (db.prepare("SELECT COUNT(*) AS n FROM pragma_table_info('egress_state') WHERE name = 'pos'").get() as { n: number }).n === 1, "the rebuilt state table carries the 7773 materialized shape (pos column)", diff --git a/tests/issue7577-egress-kstate-derive.test.ts b/tests/issue7577-egress-kstate-derive.test.ts index 48a992f03b..43a0bf9af6 100644 --- a/tests/issue7577-egress-kstate-derive.test.ts +++ b/tests/issue7577-egress-kstate-derive.test.ts @@ -47,10 +47,10 @@ test("egressTsStamps derives the live view's msgid→ts map verbatim", () => { try { const sid = "egress-on-session"; h.store.egressAppendTurn(sid, [ - { type: "I", msgid: "rawA", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "hello", ts: 1_730_000_000_000 }, + { type: "I", rid: 1, msgid: "rawA", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "hello", ts: 1_730_000_000_000 }, ], 0, 1_730_000_000_000); h.store.egressAppendTurn(sid, [ - { type: "I", msgid: "rawB", after: "rawA", ref: "m00002", tokens: 4, typeTag: "text", bytes: "there", ts: 1_730_000_001_500 }, + { type: "I", rid: 2, msgid: "rawB", after: 1, ref: "m00002", tokens: 4, typeTag: "text", bytes: "there", ts: 1_730_000_001_500 }, ], 1, 1_730_000_001_500); assert.deepEqual(h.store.egressTsStamps(sid), { rawA: 1_730_000_000_000, @@ -64,19 +64,19 @@ test("folded messages drop out of the derived stamps (they are not rendered)", ( try { const sid = "egress-on-fold"; h.store.egressAppendTurn(sid, [ - { type: "I", msgid: "rawA", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "hello", ts: 1_730_000_000_000 }, - { type: "I", msgid: "rawB", after: "rawA", ref: "m00002", tokens: 4, typeTag: "text", bytes: "there", ts: 1_730_000_001_500 }, + { type: "I", rid: 1, msgid: "rawA", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "hello", ts: 1_730_000_000_000 }, + { type: "I", rid: 2, msgid: "rawB", after: 1, ref: "m00002", tokens: 4, typeTag: "text", bytes: "there", ts: 1_730_000_001_500 }, ], 0, 1_730_000_001_500); // fold both away (compaction in the same write) h.store.egressAppendTurn(sid, [ - { type: "D", start: "rawA", end: "rawB" }, + { type: "D", start: 1, end: 2 }, ], 2, 1_730_000_010_000); // nothing live left → null, not {} and not the folded stamps assert.equal(h.store.egressTsStamps(sid), null); // a message that survived the fold keeps its birth stamp // (the D turn consumed op 3 — 7773 has no in-step compaction row) h.store.egressAppendTurn(sid, [ - { type: "I", msgid: "rawC", after: null, ref: "m00003", tokens: 5, typeTag: "text", bytes: "survivor", ts: 1_730_000_012_000 }, + { type: "I", rid: 3, msgid: "rawC", after: null, ref: "m00003", tokens: 5, typeTag: "text", bytes: "survivor", ts: 1_730_000_012_000 }, ], 3, 1_730_000_012_000); assert.deepEqual(h.store.egressTsStamps(sid), { rawC: 1_730_000_012_000 }); } finally { closeH(h); } @@ -94,12 +94,12 @@ test("a corrupt egress log derives null — it never throws into the load path", try { const sid = "egress-on-corrupt"; h.store.egressAppendTurn(sid, [ - { type: "I", msgid: "rawA", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "hello", ts: 1_730_000_000_000 }, + { type: "I", rid: 1, msgid: "rawA", after: null, ref: "m00001", tokens: 3, typeTag: "text", bytes: "hello", ts: 1_730_000_000_000 }, ], 0, 1_730_000_000_000); // damage the log so the serving read goes to the rebuild path and // the rebuild replay meets the damaged row: a structurally stray // state row (pos density breaks) + an unreplayable flow payload - h.db.prepare(`INSERT INTO egress_state (session_id, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 'ghost', 99, 0, 0, '', 0, 'text', 'user', 0, 0, 'x', 9)`).run(sid); + h.db.prepare(`INSERT INTO egress_state (session_id, rid, msgid, pos, log_seq, num, ref, tokens, type, role, ts, sys_in, bytes, created_at) VALUES (?, 99, 'ghost', 99, 0, 0, '', 0, 'text', 'user', 0, 0, 'x', 9)`).run(sid); h.db.prepare(`UPDATE egress_flow SET payload = 'not-json' WHERE session_id = ? AND row_type = 'I'`).run(sid); assert.equal(h.store.egressTsStamps(sid), null); } finally { closeH(h); } From 1282f83f2f31ae0305ca36f5a0c6b634f303e2f3 Mon Sep 17 00:00:00 2001 From: ci-check Date: Fri, 27 Nov 2026 14:27:50 +0800 Subject: [PATCH 2/3] docs: fix egress payload key names (start/end/after, not start_rid/end_rid/after_rid) The docs wrote the D/I payload keys as start_rid/end_rid/after_rid, but the actual JSON payload keys are start/end/after (holding rid values). Also clarify that the U row's rid is a column, not a payload key. Drive-by fix from PR #7849 review (mirror 7850). --- docs/deprecations.md | 2 +- docs/deprecations.zh-CN.md | 2 +- docs/egress-plane.md | 2 +- docs/egress-plane.zh-CN.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/deprecations.md b/docs/deprecations.md index 0a3918f3a2..397c6cb5ef 100644 --- a/docs/deprecations.md +++ b/docs/deprecations.md @@ -18,7 +18,7 @@ Discipline: a surface is listed here **before** it goes default-off, and stays h | **l1_world dead arm-turn placeholder rows** | **Auto-cleaned** by `UnifiedStore.ensureEgressIdentity()` (same tx as the identity upsert): rows with `armed_at IS NULL AND r3_latched_at IS NULL AND witness_probe <> ''` are deleted; armed/R3 rows survive | the identity row + stateless stage-0 (nothing reads the dead row) | none (the carrier table itself retires with the l1_world row above) | discussions/7735, 2026-11-25 | | **egress `B` base row** (both planes: `row_type = 'B'` in `egress_flow` / `egress_block_flow`, payload `{entries, highWater}` / block base snapshot) | **Removed** (discussion #7773, 2026-11-26): no writer, no reader, no DDL `B` check remains; the frontier is `MAX(log_seq)` on the flow | the materialized state tables below — the base row's job (bounding the serving copy) is done by construction now | none left — the tables were never released with the `B` row in them: existing DBs **drop and rebuild** the five egress tables (owner runbook: delete `index.db*` + restart); the probe in `migrateSchema` does exactly that when it detects the old shape (`op_seq` column / missing `pos` column / `B` in the flow CHECK / missing `rid` column) | discussions/7773, 2026-11-26 | | **`egress_state` as op-copy read replica** (PK `(session_id, op_seq)`, replayed from flow at every write) | **Removed** (discussion #7773): replaced by the **materialized live view** — PK `(session_id, msgid)`, `pos`-ordered, I inserts / U in-place / D physically deletes + shifts, same-transaction apply after the flow append; the PK later moved to `(session_id, rid)` (next row, 2026-11-27) | the materialized `egress_state` / `egress_block_state` + full-history replay (`egressStateAt`) as the rebuild path; serving read rebuilds a damaged copy by replay and serves (the flow is the authority) | none left — see the `B` base row row above (same never-released table, same drop-and-rebuild). `idx_egress_state_msgid` is gone too (the PK covers the msgid lookup — superseded 2026-11-27: the index returned when the PK moved to `rid`, see next row) | discussions/7773, 2026-11-26 | -| **msgid-keyed log addressing in the egress tables** (D payload `{start, end}` = msgids, U payload `msgid` = target, I payload `after` = msgid, `egress_state` PK `(session_id, msgid)`) | **Removed** (owner ruling 2026-11-27, #7773 follow-up — the D-row audit in a field test): a msgid is a kernel identity the proxy may map from a content hash, can collide across hosts, and stops distinguishing occurrences after folds/re-homings — it cannot be a reliable PERSISTENT address. All addressing moves to `rid`, the dense per-session, append-only, never-reissued row id (the flow keeps every row, so `MAX(rid)+1` is always safe) | D payload `{start_rid, end_rid}` · U payload `rid` (+ the row's msgid as a cross-check) · I payload `after_rid` + `rid` column on `egress_flow` · `egress_state` PK `(session_id, rid)` with `idx_egress_state_msgid (session_id, msgid)` as the serving lookup. The kernel-identity seam (the prev↔next view diff) still matches on msgids — only the persistent layer changed. Suite: `tests/egress-state.test.ts` (incl. the msgid-collision row), `tests/egress-invariants-7773.test.ts` invariant ⑤ | none left — never released with msgid addressing: existing DBs drop and rebuild (the `migrateSchema` probe now treats a missing `rid` column as the old shape); dev DBs follow the destroy-&-rebuild runbook (egress-plane.md §7) | owner ruling 2026-11-27 (#7773 follow-up) | +| **msgid-keyed log addressing in the egress tables** (D payload `{start, end}` = msgids, U payload `msgid` = target, I payload `after` = msgid, `egress_state` PK `(session_id, msgid)`) | **Removed** (owner ruling 2026-11-27, #7773 follow-up — the D-row audit in a field test): a msgid is a kernel identity the proxy may map from a content hash, can collide across hosts, and stops distinguishing occurrences after folds/re-homings — it cannot be a reliable PERSISTENT address. All addressing moves to `rid`, the dense per-session, append-only, never-reissued row id (the flow keeps every row, so `MAX(rid)+1` is always safe) | D payload `{start, end}` (rid values) · U: `rid` column (+ the row's msgid as a cross-check) · I payload `after` (rid value) + `rid` column on `egress_flow` · `egress_state` PK `(session_id, rid)` with `idx_egress_state_msgid (session_id, msgid)` as the serving lookup. The kernel-identity seam (the prev↔next view diff) still matches on msgids — only the persistent layer changed. Suite: `tests/egress-state.test.ts` (incl. the msgid-collision row), `tests/egress-invariants-7773.test.ts` invariant ⑤ | none left — never released with msgid addressing: existing DBs drop and rebuild (the `migrateSchema` probe now treats a missing `rid` column as the old shape); dev DBs follow the destroy-&-rebuild runbook (egress-plane.md §7) | owner ruling 2026-11-27 (#7773 follow-up) | | **`egressStateCompact` / `egressBlockCompact`** (the compaction paths) | **Removed** (discussion #7773): no production caller existed for the block side; the message side's trim-below-base is replaced by physical D deletes on the materialized view | nothing — the state tables are bounded by the live view's size by construction; `tests/egress-invariants-7773.test.ts` pins the shape invariants after every write | none (functions deleted from `src/storage/egress-state.ts` / `src/storage/egress-block.ts`) | discussions/7773, 2026-11-26 | | **Bounded 16-step walk-back** (`EGRESS_HEALTHY_WALK_MAX`, `recoverEgressBase` one-step-at-a-time across bases) | **Removed** (discussion #7773): recovery is ONE full-history walk (`egressFlowWalkBack`) — the newest healthy prefix truncates the tail; no healthy point ⇒ null ⇒ latch + hard fail (7439-5) | `egressFlowWalkBack` in `src/storage/egress-state.ts` (O(n) single pass; density-checked) | none (constant deleted) | discussions/7773, 2026-11-26 | | **`egressMessageHighWater`'s B-payload fallback** (read `highWater` from the newest `B` row when the flow has no `log_seq`) | **Removed** (discussion #7773): the frontier is `MAX(log_seq)` on the flow only | `SELECT COALESCE(MAX(log_seq), 0) FROM egress_flow` | none | discussions/7773, 2026-11-26 | diff --git a/docs/deprecations.zh-CN.md b/docs/deprecations.zh-CN.md index 328839cc8f..fd6e14278d 100644 --- a/docs/deprecations.zh-CN.md +++ b/docs/deprecations.zh-CN.md @@ -18,7 +18,7 @@ | **l1_world 死 arm-turn 占位行** | **自动清理**:`UnifiedStore.ensureEgressIdentity()` 同一事务删除 `armed_at IS NULL AND r3_latched_at IS NULL AND witness_probe <> ''` 的行;armed/R3 行保留 | 身份行 + 无状态 stage-0(无人读死行) | 无(载体表本身按上方 l1_world 行退役) | discussions/7735,2026-11-25 | | **egress `B` base 行**(两平面:`egress_flow` / `egress_block_flow` 的 `row_type = 'B'`,payload `{entries, highWater}` / 块基线快照) | **移除**(discussion #7773,2026-11-26):不再有任何写入方、读取方、DDL `B` 检查;前沿 = flow 上的 `MAX(log_seq)` | 下方物化 state 表——base 行的职责(给服务副本封顶)现在由构造完成 | 无残留——这些表从未带 `B` 行随版本发布:已有库**drop 重建**五张 egress 表(owner 操作手册:删 `index.db*` + 重启);`migrateSchema` 探针检测到旧形态(`op_seq` 列 / 缺 `pos` 列 / flow CHECK 含 `B` / 缺 `rid` 列)时正是这么做的 | discussions/7773,2026-11-26 | | **`egress_state` 作为 op 副本读副本**(PK `(session_id, op_seq)`,每次写入从 flow 重放) | **移除**(discussion #7773):被**物化 live 视图**取代——PK `(session_id, msgid)`、`pos` 序、I 插入 / U 就地改 / D 物理删 + 前移、同事务在 flow append 之后应用;PK 后来移到 `(session_id, rid)`(下一行,2026-11-27) | 物化 `egress_state` / `egress_block_state` + 全史重放(`egressStateAt`)作为重建路径;serving 读发现副本损坏时重放重建后照常服务(flow 是正史) | 无残留——见上方 `B` base 行(同样的从未发布表,同样的 drop 重建)。`idx_egress_state_msgid` 也没了(PK 已覆盖 msgid 查找——2026-11-27 被取代:PK 移到 `rid` 后该索引回来了,见下一行) | discussions/7773,2026-11-26 | -| **egress 表里用 msgid 做日志寻址**(D payload `{start, end}` = msgid、U payload `msgid` = 目标、I payload `after` = msgid、`egress_state` PK `(session_id, msgid)`) | **移除**(owner 裁定 2026-11-27,#7773 后续——实测 D 行审计):msgid 是内核身份,proxy 可能从内容 hash 映射而来、宿主间可能冲突、折叠/re-home 之后分不清指哪一次——不能当**持久地址**。一切寻址改用 `rid`:稠密、每会话、append-only、永不重发的行 id(flow 永不删,所以 `MAX(rid)+1` 永远安全) | D payload `{start_rid, end_rid}` · U payload `rid`(+ 该行 msgid 作交叉校验)· I payload `after_rid` + `egress_flow` 新增 `rid` 列 · `egress_state` PK `(session_id, rid)`,`idx_egress_state_msgid (session_id, msgid)` 只做 serving 查找。内核身份缝(prev↔next 视图 diff)继续按 msgid 匹配——只有**持久层**变了。套件:`tests/egress-state.test.ts`(含 msgid 冲突用例)、`tests/egress-invariants-7773.test.ts` 不变量 ⑤ | 无残留——从未以 msgid 寻址随版本发布:已有库 drop 重建(`migrateSchema` 探针把缺 `rid` 列也判为旧形态);开发库按 egress-plane.md §7 手册毁库重建 | owner 裁定 2026-11-27(#7773 后续) | +| **egress 表里用 msgid 做日志寻址**(D payload `{start, end}` = msgid、U payload `msgid` = 目标、I payload `after` = msgid、`egress_state` PK `(session_id, msgid)`) | **移除**(owner 裁定 2026-11-27,#7773 后续——实测 D 行审计):msgid 是内核身份,proxy 可能从内容 hash 映射而来、宿主间可能冲突、折叠/re-home 之后分不清指哪一次——不能当**持久地址**。一切寻址改用 `rid`:稠密、每会话、append-only、永不重发的行 id(flow 永不删,所以 `MAX(rid)+1` 永远安全) | D payload `{start, end}`(rid 值)· U:`rid` 列(+ 该行 msgid 作交叉校验)· I payload `after`(rid 值)+ `egress_flow` 新增 `rid` 列 · `egress_state` PK `(session_id, rid)`,`idx_egress_state_msgid (session_id, msgid)` 只做 serving 查找。内核身份缝(prev↔next 视图 diff)继续按 msgid 匹配——只有**持久层**变了。套件:`tests/egress-state.test.ts`(含 msgid 冲突用例)、`tests/egress-invariants-7773.test.ts` 不变量 ⑤ | 无残留——从未以 msgid 寻址随版本发布:已有库 drop 重建(`migrateSchema` 探针把缺 `rid` 列也判为旧形态);开发库按 egress-plane.md §7 手册毁库重建 | owner 裁定 2026-11-27(#7773 后续) | | **`egressStateCompact` / `egressBlockCompact`**(压实路径) | **移除**(discussion #7773):块侧本无生产调用方;消息侧的 base 以下裁剪被物化视图上的物理 D 删除取代 | 无——state 表构造上以 live 视图大小为界;`tests/egress-invariants-7773.test.ts` 在每次写入后钉住形态不变量 | 无(函数已从 `src/storage/egress-state.ts` / `src/storage/egress-block.ts` 删除) | discussions/7773,2026-11-26 | | **有界 16 步回退**(`EGRESS_HEALTHY_WALK_MAX`,`recoverEgressBase` 跨过每个 base 逐步回退) | **移除**(discussion #7773):恢复 = **一趟全史 walk**(`egressFlowWalkBack`)——最新健康前缀截掉尾部;无健康点 ⇒ null ⇒ latch + 硬失败(7439-5) | `src/storage/egress-state.ts` 的 `egressFlowWalkBack`(O(n) 单趟,密度校验) | 无(常量已删) | discussions/7773,2026-11-26 | | **`egressMessageHighWater` 的 B-payload 回落**(flow 无 `log_seq` 时从最新 `B` 行读 `highWater`) | **移除**(discussion #7773):前沿 = flow 上的 `MAX(log_seq)`,仅此一种来源 | `SELECT COALESCE(MAX(log_seq), 0) FROM egress_flow` | 无 | discussions/7773,2026-11-26 | diff --git a/docs/egress-plane.md b/docs/egress-plane.md index 1e9ac3ae70..4bbcba5c4d 100644 --- a/docs/egress-plane.md +++ b/docs/egress-plane.md @@ -34,7 +34,7 @@ Creation note (KDD #25): on an **egressPlane-on** instance a **fresh** database | Table | PK | Role | Key columns | |---|---|---|---| -| `egress_flow` | `(session_id, op_seq)` | **Message** op log. Dense within the table (#7574 invariant). **Append-only: nothing ever prunes it** (#7439); recovery = walk back to the newest healthy point; every point stays reconstructible (`egressStateAt`). | `row_type` I/D/U (the retired `B` base row is gone, #7773) · I: `rid` (the row id, below), `msgid`, `log_seq` (canonical, never-reissued message number), `ref`, `tokens`, `bytes`, `role`, `type_tag` · D: range `(start_rid, end_rid)` — addressed by row id, NEVER by msgid (2026-11-27 owner ruling) — + the terminal full snapshot · U: `rid` (the target row; the row's msgid is kept as a cross-check) + new bytes (+ `num` on re-citation) | +| `egress_flow` | `(session_id, op_seq)` | **Message** op log. Dense within the table (#7574 invariant). **Append-only: nothing ever prunes it** (#7439); recovery = walk back to the newest healthy point; every point stays reconstructible (`egressStateAt`). | `row_type` I/D/U (the retired `B` base row is gone, #7773) · I: `rid` (the row id, below), `msgid`, `log_seq` (canonical, never-reissued message number), `ref`, `tokens`, `bytes`, `role`, `type_tag` · D: range `(start, end)` (rid values) — addressed by row id, NEVER by msgid (2026-11-27 owner ruling) — + the terminal full snapshot · U: `rid` (the target row; the row's msgid is kept as a cross-check) + new bytes (+ `num` on re-citation) | | `egress_state` | `(session_id, rid)` | **Materialized live view** (7773): one row per LIVE message, ordered by `pos`. Every append applies its ops to the rows in the same transaction — `I` inserts (shifting `pos`), `U` updates in place, `D` physically deletes + shifts. Bounded by the live view's size by construction; there is no compaction, no base row, no op mirror. A msgid MAY recur in the live view (a content-hash proxy can legitimately collide, or a re-homed slot can reappear); the `rid` cannot — that is why the key and every log anchor are `rid`, with `idx_egress_state_msgid` (session_id, msgid) as the serving lookup. | `rid` (dense, per-session, never re-issued — the flow keeps it forever, so `MAX(rid)+1` is always safe), `pos`, `log_seq` (the I-twin's flow number, immutable — the twin anchor), `num` (current kernel citation; 0 = uncited/retired), `msgid`, `ref`, `tokens`, `type`, `role`, `ts`, `sys_in`, `bytes`, `created_at`. This is what `snapPinLiveIds` / serving reads hit. | | `egress_block_flow` | `(session_id, op_seq)` | Append-only **block** history. **Own number pool** (dual clocks). | `row_type` I/U/D (reap = a `D` row carrying the block's **full terminal snapshot**, #7773; the retired `B` row is gone) · snapshot payload `{tier, startMsgid, startSeq, endMsgid, endSeq, supersedesBlockId, active, reaped, one, full}` · **`flow_op_seq`** = the flow's `MAX(op_seq)` at write time (the cross-table pointer) · kstate sidecar (residual field list) | | `egress_block_state` | `(session_id, block_id)` | **Materialized** live blocks: one row per non-reaped block, ordered by `pos`; reap physically deletes the row (the flow keeps the terminal `D` snapshot). | snapshot payload + `pos` + `op_seq`/`flow_op_seq` | diff --git a/docs/egress-plane.zh-CN.md b/docs/egress-plane.zh-CN.md index 642a4673f3..5b55ead8a5 100644 --- a/docs/egress-plane.zh-CN.md +++ b/docs/egress-plane.zh-CN.md @@ -34,7 +34,7 @@ | 表 | 主键 | 作用 | 关键列 | |---|---|---|---| -| `egress_flow` | `(session_id, op_seq)` | **消息**操作日志。表内稠密(#7574 不变量)。**append-only:任何机制都不裁剪它**(#7439);恢复 = 回退到最新健康点;任意点位可完整重建(`egressStateAt`)。 | `row_type` I/D/U(退役的 `B` base 行已不存在,#7773)· I 行:`rid`(行 id,见下)、`msgid`、`log_seq`(规范消息号,永不复用)、`ref`、`tokens`、`bytes`、`role`、`type_tag` · D 行:区间 `(start_rid, end_rid)`——用行 id 寻址,**永不**用 msgid(2026-11-27 owner 裁定)+ 终态全量快照 · U 行:`rid`(目标行;该行的 msgid 保留为交叉校验)+ 新字节(再引用时带 `num`) | +| `egress_flow` | `(session_id, op_seq)` | **消息**操作日志。表内稠密(#7574 不变量)。**append-only:任何机制都不裁剪它**(#7439);恢复 = 回退到最新健康点;任意点位可完整重建(`egressStateAt`)。 | `row_type` I/D/U(退役的 `B` base 行已不存在,#7773)· I 行:`rid`(行 id,见下)、`msgid`、`log_seq`(规范消息号,永不复用)、`ref`、`tokens`、`bytes`、`role`、`type_tag` · D 行:区间 `(start, end)`(rid 值)——用行 id 寻址,**永不**用 msgid(2026-11-27 owner 裁定)+ 终态全量快照 · U 行:`rid`(目标行;该行的 msgid 保留为交叉校验)+ 新字节(再引用时带 `num`) | | `egress_state` | `(session_id, rid)` | **物化 live 视图**(7773):每条**存活**消息一行,按 `pos` 排序。每次 append 在同一事务内把 op 应用到行上——`I` 插入(`pos` 后移)、`U` 就地改、`D` 物理删 + 前移。构造上以 live 视图大小为界;没有压实、没有 base 行、没有 op 镜像。msgid **可以**在 live 视图里重现(内容 hash 代理可以合法冲突、re-home 可以重现同一 msgid);`rid` 不可以——所以主键与日志里的一切锚点都是 `rid`,`idx_egress_state_msgid`(session_id, msgid)只做 serving 查找。 | `rid`(稠密、每会话、永不重发——flow 永不删,所以 `MAX(rid)+1` 永远安全)、`pos`、`log_seq`(I 孪生在 flow 里的编号,不可变——孪生锚点)、`num`(当前内核引用号;0 = 无引用/已退役)、`msgid`、`ref`、`tokens`、`type`、`role`、`ts`、`sys_in`、`bytes`、`created_at`。`snapPinLiveIds`/serving 读命中它。 | | `egress_block_flow` | `(session_id, op_seq)` | 追加式**块**历史。**独立编号池**(双时钟)。 | `row_type` I/U/D(reap = 一条 `D` 行,带该块的**终态全量快照**,#7773;退役的 `B` 行已不存在)· 快照 payload `{tier, startMsgid, startSeq, endMsgid, endSeq, supersedesBlockId, active, reaped, one, full}` · **`flow_op_seq`** = 写入时刻 flow 的 `MAX(op_seq)`(跨表指针)· kstate 边车(残差字段清单) | | `egress_block_state` | `(session_id, block_id)` | **物化** live 块:每个未 reap 的块一行,按 `pos` 排序;reap 物理删行(flow 保留终态 `D` 快照)。 | 快照 payload + `pos` + `op_seq`/`flow_op_seq` | From af89c93f2115045e188ca445bc8b406836cfd611 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Fri, 27 Nov 2026 15:42:42 +0800 Subject: [PATCH 3/3] docs: id map for the egress number space (op_seq/log_seq/num/pos/rid) + fork = zero id conversion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The five numbers across the five egress tables answer five different questions; this section puts them side by side (which one is the write counter, which the kernel citation, which the row identity, which the view offset) and states the fork consequence explicitly: every key is (session_id, rid), so fork copies rows verbatim with NO id conversion — the child keeps its forked rids as lineage identity and continues from its own MAX(rid)+1; the usage stream carries no rids at all, so its fork copy is a plain row copy (whole to-now / at<=W prefix point). en+zh (docs/egress-plane.md §3). Closes the doc gap flagged in the #7849 review thread. --- docs/egress-plane.md | 16 ++++++++++++++++ docs/egress-plane.zh-CN.md | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/docs/egress-plane.md b/docs/egress-plane.md index 4bbcba5c4d..5fbef92836 100644 --- a/docs/egress-plane.md +++ b/docs/egress-plane.md @@ -46,6 +46,22 @@ Retention rules: **flow is append-only and never pruned** (#7439 — its growth **Structural invariants (7773 §6, asserted after EVERY write, both planes).** ① the flow's row count never shrinks (append-only); ② the state row count == the live view's row count (a materialization, never an aggregate and never an op mirror); ③ the largest value in flow/state equals the historical maximum SINGLE-row size — the regression defense against the retired `B` row's whole-view aggregate payload; ④ the row alphabet is exactly I/D/U (message plane) and I/U/D (block plane) — `B` never appears; ⑤ **log addressing is by `rid`** — the dense, never-reissued per-session row id: D endpoints, U targets and I anchors in `egress_flow` payloads are rids, never msgids (a msgid is a kernel identity that the proxy may map from a content hash and that can legitimately recur; a rid is ours and cannot — owner ruling 2026-11-27, the follow-up to #7773). Suite: `tests/egress-invariants-7773.test.ts`. +### The id map — which question each number answers + +Five numbers appear across the five tables. They answer FIVE DIFFERENT questions; none of them is redundant: + +| id | lives on | the question it answers | re-use | +|---|---|---|---| +| `op_seq` | flow / block_flow / usage PK | "the Nth **write to this table**" — the physical journal cursor; fork and point-in-time watermarks ride it (or the block plane's `flow_op_seq` pointer onto it) | monotonic, but names **events**, not rows: one row's life (I→U→U→D) consumes several op_seqs — the row is addressed by its I row's `rid`, not by where its writes happened | +| `log_seq` | flow I rows / state | "the number the **kernel cites** for this row" — `mNNNNN` = m + log_seq, one number not two (§10) | re-citable: a fold summary may legitimately take over a retired slot (demote → re-home, §10 rule 7) — this is exactly why it CANNOT be a row identity | +| `num` | state row + U payload | the row's **current** kernel citation; `0` = not cited / demoted | follows the kernel's fact, +U num | +| `pos` | state table | "where does it sit in the **current live view**" | transient; shifts on every insert/delete | +| `rid` | flow I/U rows + state PK | "**which row**" — the target of every op payload (D endpoints, U target, I anchor) | dense per session (`MAX(rid)+1`), never re-issued (the flow is never pruned) | + +One-liner: **log_seq/num are citation numbers (re-issue allowed), rid is row identity (reuse forbidden), op_seq is a write counter, pos is a view offset.** The pre-#7849 shape had msgid carrying both citation-identity and row-identity duties at once; a content-hash-derived msgid can legitimately recur, which is what broke the D-row addressing (owner ruling 2026-11-27). + +Fork needs NO id conversion: every key is `(session_id, rid)`, so a child's copied rows are namespaced by the session id and no op can ever reach across sessions — the child keeps its forked rids as lineage identity and continues numbering from its own `MAX(rid)+1`. The **usage** stream (§12) carries no rids at all (its events reference kernel block ids and timestamps), so its fork copy — whole (to-now) or `at <= W` prefix (point) — is a plain row copy with replay reconstructing the ledger; nothing is remapped. + ## 4. One turn, step by step 1. **Prepare** — the plugin turn arrives; lane arbitration picks the egress path; **`recordEgressTurn`** diffs the turn's outbound view against the previous one and **appends I/D/U rows to the flow immediately (at prepare, not save)** — in one transaction: in-transaction `nextSeqs` (density-safe, #7574), a concurrent-writer guard, then the same ops applied to the **materialized state rows** (I inserts with `pos` shift, U in-place, D physically deletes + shifts), and finally the invariant checks (state row count == live view length, 7773 §6). diff --git a/docs/egress-plane.zh-CN.md b/docs/egress-plane.zh-CN.md index 5b55ead8a5..07be67e405 100644 --- a/docs/egress-plane.zh-CN.md +++ b/docs/egress-plane.zh-CN.md @@ -46,6 +46,22 @@ **结构不变量(7773 §6,每次写入后断言,两平面)。** ① flow 总行数只增(append-only);② state 行数 == live 视图行数(物化,不是聚合、不是 op 镜像);③ flow/state 里最大 value 大小 == 历史最大**单行**大小——针对退役 `B` 行全视图聚合 payload 的回归防线;④ 行字母表恰为 I/D/U(消息平面)与 I/U/D(块平面)——`B` 永不出现;⑤ **日志寻址一律用 `rid`**——稠密、永不重发的每会话行 id:`egress_flow` payload 里的 D 端点、U 目标、I 锚点都是 rid,永不 msgid(msgid 是内核身份,proxy 可能从内容 hash 映射而来、还可能合法重现;rid 是我们自己派的,不可能——owner 裁定 2026-11-27,#7773 后续)。套件:`tests/egress-invariants-7773.test.ts`。 +### id 总表——每个数字回答哪个问题 + +五张表里出现五个数字,它们回答**五个不同的问题**,没有一个是冗余的: + +| id | 在哪 | 它回答的问题 | 可否复用 | +|---|---|---|---| +| `op_seq` | flow / block_flow / usage 主键 | 「**这张表的第 N 次写盘**」——物理日志游标;fork 与 point 水位骑在它上(或块平面用 `flow_op_seq` 指针挂到它上) | 单调,但指**事件**不指行:一行的生命(I→U→U→D)要占好几个 op_seq——行用它的 I 行 `rid` 寻址,不指望写在哪 | +| `log_seq` | flow I 行 / state | 「**kernel 引用**这行用几号」——`mNNNNN` = m + log_seq,一个号不是两个(§10) | 可被重引:fold summary 合法接手退役槽位(demote → re-home,§10 规则 7)——正因如此它**不能**当行身份 | +| `num` | state 行 + U payload | 该行**当前**的 kernel 引用号;`0` = 未被引用/已 demote | 跟着 kernel 事实走,+U num | +| `pos` | state 表 | 「它在**当前 live 视图**里排第几」 | 瞬态,每次插入/删除都变 | +| `rid` | flow I/U 行 + state 主键 | 「**哪一行**」——每个 op payload 的指针目标(D 端点、U 目标、I 锚点) | 会话内稠密(`MAX(rid)+1`),永不重发(flow 永不裁剪) | + +一句话:**log_seq/num 是引用号(允许重发),rid 是行身份(禁止复用),op_seq 是写盘计数,pos 是视图偏移。** #7849 之前的形状让 msgid 一个人同时扛引用身份和行身份两件事——内容 hash 派生的 msgid 可能合法重现,D 行寻址就是这么坏的(owner 裁定 2026-11-27)。 + +fork **不需要任何 id 转换**:所有主键都是 `(session_id, rid)`,子会话的拷贝行由会话 id 隔离命名空间,op 永不跨会话——子的 rid 原样保留(血缘身份),从自己的 `MAX(rid)+1` 续编。**usage** 流(§12)根本不携带 rid(事件只引用 kernel 块 id 和时间戳),所以 fork 拷贝——整拷(to-now)或 `at <= W` 前缀(point)——就是纯行拷贝,重放重建 ledger,没有任何重映射。 + ## 4. 一轮的生命周期 1. **准备**——插件轮到达,车道仲裁选中 egress 路径;**`recordEgressTurn`** 把本轮出站视图与上一轮 diff,**立即(准备阶段,不是保存)追加 I/D/U 行到 flow**——单事务:事务内 `nextSeqs`(密度安全,#7574)、并发写守卫、然后把同一批 op 应用到**物化 state 行**(I 插入 + `pos` 后移、U 就地改、D 物理删 + 前移),最后跑不变量检查(state 行数 == live 视图长度,7773 §6)。