feat(canvas): elide closed unsent lifetimes with durable local proofs
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
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';
|
||||
|
||||
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. */
|
||||
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>();
|
||||
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');
|
||||
for (const [index, intent] of intents.entries()) {
|
||||
if (intent.operationType !== 'document.change' || intent.operationSchemaVersion !== 1 || !intent.changes.length || index && intent.sequence <= intents[index - 1].sequence) throw fault('invalid_elision');
|
||||
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);
|
||||
}
|
||||
if (change.kind === 'element') {
|
||||
if (change.after && (!Number.isSafeInteger(change.after.incarnation) || change.after.incarnation < 1 || !change.before && change.after.incarnation <= (highWater.get(id) ?? 0) || change.before && change.after.incarnation !== change.before.incarnation)) throw fault('stale_incarnation', [id]);
|
||||
if (change.before && !change.after) highWater.set(id, Math.max(highWater.get(id) ?? 0, change.before.incarnation));
|
||||
}
|
||||
}
|
||||
}
|
||||
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)) };
|
||||
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. */
|
||||
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) {
|
||||
const record = ledger.operations.get(intent.id);
|
||||
if (!record || record.phase !== 'pending' || record.requestId || record.blockers.length || !equal(record.intent, intent) || intent.operationType !== 'document.change' || intent.operationSchemaVersion !== 1) break;
|
||||
if (intent.dependencies.some(id => !selected.some(intent => intent.id === id) && !preceding.has(id) && ledger.operations.get(id)?.phase !== 'resolved')) break;
|
||||
let safe = true;
|
||||
for (const change of intent.changes) {
|
||||
const id = change.kind === 'field' ? change.target.id : change.id, known = change.kind === 'canvas' ? canvases : seen;
|
||||
if (known.has(id)) continue;
|
||||
if (change.kind === 'field' || change.before !== null || !change.after || (change.kind === 'canvas' ? acknowledged.canvases.has(id) : acknowledged.elements.has(id) || !Object.hasOwn(record.basePresence, id) || record.basePresence[id] !== 'absent')) { safe = false; break; }
|
||||
known.add(id);
|
||||
if (change.kind === 'element' && acknowledged.tombstones.has(id)) bases[id] = acknowledged.tombstones.get(id)!;
|
||||
}
|
||||
if (!safe) break;
|
||||
selected.push(intent);
|
||||
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);
|
||||
if (!fragment.elements.size && !fragment.canvases.size) { bestLength = selected.length; bestBases = { ...bases }; }
|
||||
}
|
||||
return bestLength ? proveElision(selected.slice(0, bestLength), bestBases) : undefined;
|
||||
}
|
||||
|
||||
/** 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>();
|
||||
for (let offset = 1; offset < intents.length; offset++) {
|
||||
preceding.add(intents[offset - 1].id);
|
||||
if (findElision(intents.slice(offset), acknowledged, ledger, preceding)) return offset;
|
||||
}
|
||||
return intents.length;
|
||||
}
|
||||
|
||||
/** 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)!;
|
||||
if (!equal(proveElision(intents, bases).tombstones, proof.tombstones)) throw fault('invalid_elision');
|
||||
}
|
||||
|
||||
/** Validate persisted local facts independently of the current (possibly newer) server baseline. */
|
||||
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; }
|
||||
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)!;
|
||||
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');
|
||||
if (ordered[offset + index]?.intent.id !== id || member.intent.dependencies.some(dependency => members.has(dependency) ? (ledger.operations.get(dependency)?.intent.sequence ?? Infinity) >= member.intent.sequence : ledger.operations.get(dependency)?.phase !== 'resolved')) throw fault('invalid_elision');
|
||||
for (const change of member.intent.changes) if (change.kind !== 'canvas') { const target = change.kind === 'field' ? change.target.id : change.id; if (!seen.has(target) && (!Object.hasOwn(member.basePresence, target) || member.basePresence[target] !== 'absent')) throw fault('invalid_elision'); seen.add(target); }
|
||||
return member.intent;
|
||||
});
|
||||
if (!equal(proof, proveElision(intents, proof.baseTombstones))) throw fault('invalid_elision');
|
||||
assertElisionLineage(proof, intents, previous);
|
||||
for (const [id, incarnation] of Object.entries(proof.tombstones)) previous.set(id, Math.max(previous.get(id) ?? 0, incarnation));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Local high-water marks belong to working state, never to the server ACK document. */
|
||||
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));
|
||||
return Object.freeze({ ...document, tombstones: readMap(tombstones) });
|
||||
}
|
||||
Reference in New Issue
Block a user