docs(canvas): explain ledger scheduling and recovery invariants

This commit is contained in:
2026-11-12 00:00:36 +08:00
parent 391cd48be8
commit 4c1b35e0cf
7 changed files with 207 additions and 0 deletions
+22
View File
@@ -1,14 +1,23 @@
/**
* 未发出的创建→编辑→删除闭合生命周期可以不发 wire 请求,但不能抹掉本地身份事实。
* 抵消要求 absent 基线、连续未冻结意图、闭合依赖和完整零最终记录效果;墓碑保留在 working。
* 已发/可能已应用或存在基线上的修改不进入该路径,原 history/意图继续保留以支持撤销与恢复。
*/
import type { Document, Id, OperationIntent } from '../canvas-core/types.ts';
import { applyChanges } from '../canvas-core/document.ts';
import { equal, fault, freeze, readMap } from '../canvas-core/values.ts';
import type { LedgerSnapshot } from './ledger.ts';
/** 抵消证据:连续逻辑 ID、起始墓碑与最终生命周期水位;version 管理本地证明解释器。 */
export type ElisionProof = { readonly version: 1; readonly operationIds: readonly Id[]; readonly baseTombstones: Readonly<Record<Id, number>>; readonly tombstones: Readonly<Record<Id, number>> };
/** Reconstruct a closed lifetime from an empty fragment. Existing objects cannot enter this proof. */
/** 在空记录片段上重建至多 64 意图/10000 changes,验证每个对象首触及都是创建且最终全删。
* 墓碑变化是允许保留的本地效果,不等于服务器执行过这些创建/删除。 */
export function proveElision(intents: readonly OperationIntent[], baseTombstones: Readonly<Record<Id, number>>): ElisionProof {
if (!intents.length || intents.length > 64 || new Set(intents.map(intent => intent.id)).size !== intents.length) throw fault('invalid_elision');
const created = new Set<Id>(), canvases = new Set<Id>();
// 用起始+本段删除水位阻止创建/恢复复用已死亡 incarnation。
const highWater = new Map(Object.entries(baseTombstones));
let count = 0;
for (const [id, incarnation] of Object.entries(baseTombstones)) if (!id || !Number.isSafeInteger(incarnation) || incarnation < 1) throw fault('invalid_elision');
@@ -17,6 +26,7 @@ export function proveElision(intents: readonly OperationIntent[], baseTombstones
for (const change of intent.changes) {
if (++count > 10_000) throw fault('invalid_elision');
const id = change.kind === 'field' ? change.target.id : change.id, seen = change.kind === 'canvas' ? canvases : created;
// 字段修改不能作为首次接触:它意味着已有外部对象,不能纳入纯本地闭合证明。
if (!seen.has(id)) {
if (change.kind === 'field' || change.before !== null || !change.after) throw fault('elision_existing_target', [id]);
seen.add(id);
@@ -29,15 +39,19 @@ export function proveElision(intents: readonly OperationIntent[], baseTombstones
}
if (Object.keys(baseTombstones).some(id => !created.has(id))) throw fault('invalid_elision');
const fragment: Document = { projectId: '', elements: new Map(), canvases: new Map(), tombstones: new Map(Object.entries(baseTombstones)) };
// 条件执行仍使用真实 applyChanges;before 不匹配不能因最终想删除就被忽略。
const final = applyChanges(fragment, intents.flatMap(intent => intent.changes));
if (final.elements.size || final.canvases.size) throw fault('elision_has_effect');
return freeze({ version: 1, operationIds: intents.map(intent => intent.id), baseTombstones: { ...baseTombstones }, tombstones: Object.fromEntries(final.tombstones) });
}
/** Longest closed prefix before an existing-object write or another unsafe precondition. */
/** 寻找最长安全闭合前缀;遇 frozen/blocker/外部未解依赖/已有对象首写即停止扩展。
* preceding 只允许前面已选独立真实段作为依赖屏障,不把它当作已经 applied 的回执。 */
export function findElision(intents: readonly OperationIntent[], acknowledged: Document, ledger: LedgerSnapshot, preceding: ReadonlySet<Id> = new Set()): ElisionProof | undefined {
const selected: OperationIntent[] = [], seen = new Set<Id>(), canvases = new Set<Id>(), bases: Record<Id, number> = Object.create(null);
if (intents.length > 64 || !intents.some(intent => intent.changes.some(change => change.kind !== 'field' && change.after === null))) return undefined;
// 每次片段归空时保存最佳前缀;后续又创建未删对象,不影响之前已找到的闭合边界。
let bestLength = 0, bestBases: Record<Id, number> = {};
let fragment: Document = { projectId: acknowledged.projectId, elements: new Map(), canvases: new Map(), tombstones: new Map() };
for (const intent of intents) {
@@ -54,6 +68,7 @@ export function findElision(intents: readonly OperationIntent[], acknowledged: D
}
if (!safe) break;
selected.push(intent);
// 新发现对象的 ACK 墓碑合入私有片段后再回放,验证本次生命周期严格高于已知水位。
const tombstones = new Map(fragment.tombstones);
for (const [id, incarnation] of Object.entries(bases)) tombstones.set(id, Math.max(tombstones.get(id) ?? 0, incarnation));
fragment = applyChanges({ ...fragment, tombstones }, intent.changes);
@@ -63,6 +78,7 @@ export function findElision(intents: readonly OperationIntent[], acknowledged: D
}
/** Keep a later closed segment mutable while earlier real edits obtain their own receipt. */
/** 若后面存在可抵消段,限制前面的真实请求前缀,避免一次冻结把可抵消段也锁死。 */
export function elisionBatchLimit(intents: readonly OperationIntent[], acknowledged: Document, ledger: LedgerSnapshot): number {
if (!intents.some(intent => intent.changes.some(change => change.kind !== 'field' && change.after === null)) || findElision(intents, acknowledged, ledger)) return intents.length;
const preceding = new Set<Id>();
@@ -74,6 +90,7 @@ export function elisionBatchLimit(intents: readonly OperationIntent[], acknowled
}
/** A later locally canceled lifetime cannot reuse an incarnation retired by an earlier one. */
/** 用更早本地抵消的墓碑水位重新证明本段,拒绝跨两段复用已死代次。 */
export function assertElisionLineage(proof: ElisionProof, intents: readonly OperationIntent[], previous: ReadonlyMap<Id, number>): void {
const bases: Record<Id, number> = Object.assign(Object.create(null), proof.baseTombstones);
for (const id of Object.keys(proof.tombstones)) if ((previous.get(id) ?? 0) > (bases[id] ?? 0)) bases[id] = previous.get(id)!;
@@ -81,17 +98,21 @@ export function assertElisionLineage(proof: ElisionProof, intents: readonly Oper
}
/** Validate persisted local facts independently of the current (possibly newer) server baseline. */
/** 恢复时按逻辑顺序复验持久抵消组:成员连续、依赖闭合、anchor 唯一、证明与水位一致。
* 不依赖当前可能更新过的 ACK 基线来重新猜历史 absent 事实。 */
export function validateElisions(ledger: Pick<LedgerSnapshot, 'operations'>): void {
const ordered = [...ledger.operations.values()].sort((a, b) => a.intent.sequence - b.intent.sequence), positions = new Map(ordered.map((record, index) => [record.intent.id, index]));
const previous = new Map<Id, number>();
for (const record of ordered) {
if (record.resolution !== 'elided') { if (record.elision !== undefined || record.elisionId !== undefined) throw fault('invalid_elision'); continue; }
// 只有组首成员保存整份 proof,其余成员通过 elisionId 引用它,避免重复矛盾证明。
const anchor = record.elisionId ? ledger.operations.get(record.elisionId) : undefined, proof = anchor?.elision;
if (proof && Number.isSafeInteger(proof.version) && proof.version > 1) throw fault('elision_interpreter_unavailable');
if (!proof || proof.version !== 1 || proof.operationIds[0] !== record.elisionId || !proof.operationIds.includes(record.intent.id) || record.phase !== 'resolved' || record.requestId || record.blockers.length) throw fault('invalid_elision');
if (record !== anchor && record.elision !== undefined) throw fault('invalid_elision');
if (record === anchor) {
const seen = new Set<Id>(), members = new Set(proof.operationIds), offset = positions.get(record.intent.id)!;
// 每个成员仍必须 resolved/elided、无 request/blocker,不能伪造为已发送后又本地抵消。
const intents = proof.operationIds.map((id, index) => {
const member = ledger.operations.get(id);
if (!member || member.phase !== 'resolved' || member.resolution !== 'elided' || member.elisionId !== record.intent.id || member.requestId || member.blockers.length) throw fault('invalid_elision');
@@ -107,6 +128,7 @@ export function validateElisions(ledger: Pick<LedgerSnapshot, 'operations'>): vo
}
/** Local high-water marks belong to working state, never to the server ACK document. */
/** 只给 working 候选补本地墓碑最大值,不修改源文档,也不向服务器 ACK 事实表灌入本地证明。 */
export function withLocalLifecycles(document: Document, ledger: Pick<LedgerSnapshot, 'operations'>): Document {
const tombstones = new Map(document.tombstones);
for (const record of ledger.operations.values()) if (record.elision) for (const [id, incarnation] of Object.entries(record.elision.tombstones)) tombstones.set(id, Math.max(tombstones.get(id) ?? 0, incarnation));