feat(canvas): elide closed unsent lifetimes with durable local proofs
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { withLocalLifecycles } from './elision.ts';
|
||||
import type { Change, Document, FieldChange, HistoryState, Id, Json, OperationIntent, Registry } from '../canvas-core/types.ts';
|
||||
import { describeHistoryTransition, historyTransitionChanges, type HistoryTransition } from '../canvas-core/history-transition.ts';
|
||||
import { invert } from '../canvas-core/document.ts';
|
||||
@@ -41,7 +42,7 @@ export function planConflictRecovery(snapshot: EngineSnapshot, canonical: Canoni
|
||||
const adopted=new Set([...snapshot.runtime.recoveries.values()].filter(audit=>audit.historyReplay!==undefined).flatMap(audit=>audit.decisions.flatMap(decision=>decision.replacementId?[decision.replacementId]:[])));
|
||||
const content=records.filter(record=>record.intent.changes.length),hasEvidence=content.length>0&&content.every(record=>record.intent.historyTransition)||records.some(record=>['undo','redo'].includes(record.intent.origin)&&record.intent.historyTransition)||content.some(record=>adopted.has(record.intent.id));
|
||||
const journal=hasEvidence?createHistoryJournalRecovery(snapshot,records.map(record=>record.intent),registry,historyLimit):undefined;
|
||||
let document=canonical.document,sequence=0;for(const record of snapshot.runtime.ledger.operations.values())sequence=Math.max(sequence,record.intent.sequence);
|
||||
let document=withLocalLifecycles(canonical.document,snapshot.runtime.ledger),sequence=0;for(const record of snapshot.runtime.ledger.operations.values())sequence=Math.max(sequence,record.intent.sequence);
|
||||
for(const record of records){
|
||||
const intent=record.intent,choice=choices.get(intent.id)!;
|
||||
if(intent.operationSchemaVersion!==1)throw fault('operation_interpreter_unavailable',[intent.id]);
|
||||
|
||||
@@ -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) });
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { elisionBatchLimit, findElision } from './elision.ts';
|
||||
import type { Document, Id, Registry, Result, RunInput, RunApplyInput, RunCancelInput, Json, OperationIntent, Data } from '../canvas-core/types.ts';
|
||||
import { createEditor, type EditorOptions, type Transaction } from '../canvas-core/editor.ts';
|
||||
import { createDocument } from '../canvas-core/document.ts';
|
||||
@@ -199,6 +200,12 @@ export async function openProjectEngine(options: EngineOptions) {
|
||||
if (!options.assets || !resource?.digest) throw fault('asset_not_ready');
|
||||
return { kind: 'asset.upload', protocolVersion: 2, canvasIds: [], expectedVersions: {}, payload: { protocol_version: 2, request_id: id, resource_id: resource.id, operation_id: resource.operationId, sha256: resource.digest, byte_length: resource.byteLength, name: resource.name, mime_type: resource.mimeType } };
|
||||
},
|
||||
batchLimit(intents) { const snapshot = editor.getSnapshot(); return elisionBatchLimit(intents, snapshot.runtime.acknowledged, snapshot.runtime.ledger); },
|
||||
elide(intents) {
|
||||
const snapshot = editor.getSnapshot(), proof = findElision(intents, snapshot.runtime.acknowledged, snapshot.runtime.ledger);
|
||||
if (!proof) return [];
|
||||
mutate(ledger => ledger.elide(proof)); return proof.operationIds;
|
||||
},
|
||||
compileBatch: options.persistence.compileBatch ? (intents, id) => options.persistence.compileBatch!(intents, id, editor.getSnapshot()) : undefined,
|
||||
async submit(request, signal) {
|
||||
if (['run.start','run.cancel','run.apply'].includes(request.kind??'')) return options.runs ? network.run(signal, () => options.runs!.submit(request,signal)) : { outcome: 'unresolved', blocked: true, error: 'run_interpreter_unavailable' };
|
||||
|
||||
@@ -60,7 +60,7 @@ export function createHistoryJournalRecovery(snapshot:EngineSnapshot,pending:rea
|
||||
const event=events[next],record=event.record,before=history;
|
||||
if(!record)applyAdjustment(event);
|
||||
else{
|
||||
if(pendingIds.has(record.intent.id))throw fault('recovery_history_event_order',[record.intent.id]);if(record.resolution!=='applied')throw fault('recovery_history_event_unresolved',[record.intent.id]);
|
||||
if(pendingIds.has(record.intent.id))throw fault('recovery_history_event_order',[record.intent.id]);if(!['applied','elided'].includes(record.resolution??''))throw fault('recovery_history_event_unresolved',[record.intent.id]);
|
||||
if(record.intent.origin==='user')addUser(record.intent,record.intent.changes,record.intent.id,false);else if(['undo','redo'].includes(record.intent.origin))addConfirmedTraversal(record.intent);else throw fault('recovery_history_event_origin_unsupported',[record.intent.id]);
|
||||
}
|
||||
recordStep(before,event.transition.entryId,record?.intent.id);next++;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { assertElisionLineage, proveElision, type ElisionProof } from './elision.ts';
|
||||
import { applyChanges } from '../canvas-core/document.ts';
|
||||
import type { Change, Id, Json, OperationIntent } from '../canvas-core/types.ts';
|
||||
import { clone, equal, fault, freeze, readMap, validJson } from '../canvas-core/values.ts';
|
||||
@@ -13,7 +14,7 @@ export type FrozenRequest = {
|
||||
readonly phase: RequestPhase; readonly outcome: Outcome; readonly error?: string; readonly attempt: number;
|
||||
readonly retryAt?: number; readonly retryAction?: 'submit' | 'query';
|
||||
};
|
||||
export type OperationRecord = { readonly intent: OperationIntent; readonly phase: 'pending' | 'frozen' | 'resolved' | 'blocked'; readonly requestId?: Id; readonly blockers: readonly string[]; readonly resolution?: 'applied' | 'not-applied' | 'superseded' | 'discarded' | 'satisfied'; readonly recoveryId?: Id; readonly replacementId?: Id; readonly basePresence: Readonly<Record<Id, Presence>> };
|
||||
export type OperationRecord = { readonly intent: OperationIntent; readonly phase: 'pending' | 'frozen' | 'resolved' | 'blocked'; readonly requestId?: Id; readonly blockers: readonly string[]; readonly resolution?: 'applied' | 'not-applied' | 'superseded' | 'discarded' | 'satisfied' | 'elided'; readonly elisionId?: Id; readonly elision?: ElisionProof; readonly recoveryId?: Id; readonly replacementId?: Id; readonly basePresence: Readonly<Record<Id, Presence>> };
|
||||
export type LedgerSnapshot = { readonly generation: number; readonly durableGeneration: number; readonly operations: ReadonlyMap<Id, OperationRecord>; readonly requests: ReadonlyMap<Id, FrozenRequest> };
|
||||
|
||||
/** A field-safe compressor for a wholly unsent segment. Frozen records never enter here. */
|
||||
@@ -99,6 +100,22 @@ export function createLedger(initial?: LedgerSnapshot) {
|
||||
if (outcome === 'not-applied') for (const operationId of request.operationIds) operations.set(operationId, freeze({ ...operations.get(operationId)!, phase: 'blocked', blockers: [error || 'not_applied'] }));
|
||||
changed();
|
||||
},
|
||||
elide(proof: ElisionProof) {
|
||||
const ids = new Set(proof.operationIds), seen = new Set<Id>(), intents = proof.operationIds.map(id => {
|
||||
const record = operations.get(id);
|
||||
if (!record || record.phase !== 'pending' || record.requestId || record.blockers.length || record.intent.dependencies.some(dependency => ids.has(dependency) ? (operations.get(dependency)?.intent.sequence ?? Infinity) >= record.intent.sequence : operations.get(dependency)?.phase !== 'resolved')) throw fault('elision_not_safe', [id]);
|
||||
for (const change of record.intent.changes) if (change.kind !== 'canvas') { const target = change.kind === 'field' ? change.target.id : change.id; if (!seen.has(target) && (!Object.hasOwn(record.basePresence, target) || record.basePresence[target] !== 'absent')) throw fault('elision_not_safe', [target]); seen.add(target); }
|
||||
return record.intent;
|
||||
});
|
||||
if (!equal(proof, proveElision(intents, proof.baseTombstones))) throw fault('invalid_elision');
|
||||
const previous = new Map<Id, number>();
|
||||
for (const record of operations.values()) if (record.elision) for (const [id, incarnation] of Object.entries(record.elision.tombstones)) previous.set(id, Math.max(previous.get(id) ?? 0, incarnation));
|
||||
assertElisionLineage(proof, intents, previous);
|
||||
const first = intents[0].sequence, last = intents.at(-1)!.sequence;
|
||||
if ([...operations.values()].some(record => record.intent.sequence >= first && record.intent.sequence <= last && !ids.has(record.intent.id))) throw fault('elision_not_contiguous');
|
||||
for (const id of proof.operationIds) operations.set(id, freeze({ ...operations.get(id)!, phase: 'resolved', resolution: 'elided', elisionId: proof.operationIds[0], ...(id === proof.operationIds[0] ? { elision: clone(proof) } : {}) }));
|
||||
changed();
|
||||
},
|
||||
resolveNoEffect(id: Id) {
|
||||
const request=requireRequest(id);
|
||||
if(request.outcome!=='not-applied'||!['run.start','run.cancel'].includes(request.kind??''))throw fault('invalid_no_effect_resolution');
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { withLocalLifecycles } from './elision.ts';
|
||||
import type { Change, Document, Id, OperationIntent, Registry } from '../canvas-core/types.ts';
|
||||
import { applyChanges, validateDocument } from '../canvas-core/document.ts';
|
||||
import { equal, fault } from '../canvas-core/values.ts';
|
||||
@@ -51,7 +52,7 @@ export function operationCanvases(intent: OperationIntent, document: Document, a
|
||||
|
||||
/** Replay once, by logical sequence. A receipt can already contain a desired field value. */
|
||||
export function replayPending(base: Document, ledger: LedgerSnapshot, registry: Registry): Document {
|
||||
let document = base;
|
||||
let document = withLocalLifecycles(base, ledger);
|
||||
for (const record of [...ledger.operations.values()].sort((a, b) => a.intent.sequence - b.intent.sequence)) {
|
||||
if (record.phase === 'resolved' || !['document.change','run.apply'].includes(record.intent.operationType)) continue;
|
||||
for (const change of record.intent.changes) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { validateElisions, withLocalLifecycles } from './elision.ts';
|
||||
import type { Change, CoreSnapshot, Document, HistoryEntry, HistoryState, Id, Json, OperationIntent, Registry } from '../canvas-core/types.ts';
|
||||
import { validateHistoryReplay, replayHistoryEvidence, sameHistory } from './history-replay.ts';
|
||||
import type { RecoveryAudit } from './conflicts.ts';
|
||||
@@ -94,7 +95,7 @@ export function decodeRecovery(image: RecoveryImage, registry: Registry): CoreSn
|
||||
const raw = object(value); intent(raw.intent, id); strings(raw.blockers); object(raw.basePresence);
|
||||
if (((object(raw.intent).operationType === 'document.change'||object(raw.intent).operationType==='run.apply'&&array(object(raw.intent).changes).length>0) && !operations.has(id)) || !['pending', 'frozen', 'resolved', 'blocked'].includes(string(raw.phase))) throw fault('corrupt_recovery_image');
|
||||
if(operations.has(id)&&!equal(operations.get(id)!.historyTransition,(raw.intent as OperationIntent).historyTransition))throw fault('corrupt_recovery_image');
|
||||
if(raw.resolution!==undefined&&!['applied','not-applied','superseded','discarded','satisfied'].includes(string(raw.resolution)))throw fault('corrupt_recovery_image');
|
||||
if(raw.resolution!==undefined&&!['applied','not-applied','superseded','discarded','satisfied','elided'].includes(string(raw.resolution)))throw fault('corrupt_recovery_image');
|
||||
return freeze(value as OperationRecord);
|
||||
});
|
||||
if (operations.size !== [...records.values()].filter(record => (record.intent.operationType === 'document.change'||record.intent.operationType==='run.apply'&&record.intent.changes.length>0)).length) throw fault('corrupt_recovery_image');
|
||||
@@ -136,6 +137,12 @@ export function decodeRecovery(image: RecoveryImage, registry: Registry): CoreSn
|
||||
return freeze(value as FrozenRequest);
|
||||
});
|
||||
for (const record of records.values()) if (record.requestId && !requests.has(record.requestId) || record.phase === 'frozen' && !record.requestId) throw fault('corrupt_recovery_image');
|
||||
try {
|
||||
validateElisions({ operations: records });
|
||||
for (const record of records.values()) if (record.resolution === 'elided') { const original = operations.get(record.intent.id); if (!original || !equal(original.changes, record.intent.changes) || original.sequence !== record.intent.sequence || original.origin !== record.intent.origin) throw fault('invalid_elision'); }
|
||||
const local = withLocalLifecycles(document, { operations: records });
|
||||
if (!equal([...local.tombstones], [...document.tombstones])) throw fault('invalid_elision');
|
||||
} catch (error) { if ((error as {code?:string}).code === 'elision_interpreter_unavailable') throw error; throw fault('corrupt_recovery_image'); }
|
||||
const receipts=table(runtime.receipts,value=>freeze(value as Json));
|
||||
for(const record of records.values())if(record.resolution==='not-applied'){
|
||||
const request=record.requestId?requests.get(record.requestId):undefined;
|
||||
@@ -186,7 +193,7 @@ export function decodeRecovery(image: RecoveryImage, registry: Registry): CoreSn
|
||||
const original=readHistory(object(backup.history),operations);
|
||||
const composed=replayHistoryEvidence(original,replay,id=>{
|
||||
const record=records.get(id);
|
||||
return!!record?.intent.changes.length&&['user','undo','redo'].includes(record.intent.origin)&&(local.has(id)||record.resolution==='applied');
|
||||
return!!record?.intent.changes.length&&['user','undo','redo'].includes(record.intent.origin)&&(local.has(id)||['applied','elided'].includes(record.resolution??''));
|
||||
});
|
||||
const expected=applyHistoryTransition(original,raw.historyTransition as HistoryTransition,'forward');
|
||||
if(!sameHistory(composed,expected))throw fault('corrupt_recovery_image');
|
||||
|
||||
@@ -15,6 +15,8 @@ export type SchedulerOptions = {
|
||||
createId(): Id;
|
||||
participants(intent: OperationIntent): readonly Id[];
|
||||
compile(intent: OperationIntent, requestId: Id): CompiledRequest;
|
||||
batchLimit?: (intents: readonly OperationIntent[]) => number;
|
||||
elide?: (intents: readonly OperationIntent[]) => readonly Id[];
|
||||
compileBatch?: (intents: readonly OperationIntent[], requestId: Id) => CompiledRequest;
|
||||
submit(request: FrozenRequest, signal: AbortSignal): Promise<OperationStatus>;
|
||||
query(request: FrozenRequest, signal: AbortSignal): Promise<OperationStatus>;
|
||||
@@ -68,7 +70,7 @@ export function createScheduler(options: SchedulerOptions) {
|
||||
/** Only a contiguous mutable document prefix may share a request. Task barriers stay visible. */
|
||||
function batch(first: OperationIntent, canvases: Set<Id>): readonly OperationIntent[] {
|
||||
const selected = [first], ids = new Set([first.id]);
|
||||
if (!options.compileBatch || first.operationType !== 'document.change' || first.operationSchemaVersion !== 1) return selected;
|
||||
if ((!options.compileBatch && !options.elide) || first.operationType !== 'document.change' || first.operationSchemaVersion !== 1) return selected;
|
||||
let lo = 0, hi = ordered.length, changeCount = first.changes.length;
|
||||
while (lo < hi) { const mid = (lo + hi) >>> 1; if (ordered[mid].sequence <= first.sequence) lo = mid + 1; else hi = mid; }
|
||||
const ledger = options.getLedger();
|
||||
@@ -85,7 +87,7 @@ export function createScheduler(options: SchedulerOptions) {
|
||||
return selected;
|
||||
}
|
||||
function requestPump() {
|
||||
if (!options.compileBatch) { pump(); return; }
|
||||
if (!options.compileBatch && !options.elide) { pump(); return; }
|
||||
if (!scheduledPump) scheduledPump = Promise.resolve().then(() => { scheduledPump = undefined; pump(); });
|
||||
}
|
||||
function own(request: FrozenRequest) {
|
||||
@@ -185,8 +187,18 @@ export function createScheduler(options: SchedulerOptions) {
|
||||
for (const canvas of occupied) { const set = waiters.get(canvas) ?? new Set<Id>(); set.add(id); waiters.set(canvas, set); }
|
||||
continue;
|
||||
}
|
||||
const scope = new Set(canvases), intents = batch(record.intent, scope);
|
||||
const participants = [...scope].sort();
|
||||
const scope = new Set(canvases), selected = batch(record.intent, scope);
|
||||
const limit = options.batchLimit?.(selected) ?? selected.length;
|
||||
if (!Number.isSafeInteger(limit) || limit < 1 || limit > selected.length) throw fault('invalid_batch_limit');
|
||||
const candidates = selected.slice(0, limit);
|
||||
const elided = options.elide?.(candidates) ?? [];
|
||||
if (elided.length) {
|
||||
if (elided.some((id, index) => id !== candidates[index]?.id || options.getLedger().operations.get(id)?.resolution !== 'elided')) throw fault('invalid_elision');
|
||||
for (const id of elided) for (const dependent of dependents.get(id) ?? []) enqueue(dependent);
|
||||
continue;
|
||||
}
|
||||
const intents = options.compileBatch ? candidates : [record.intent];
|
||||
const participants = [...new Set(intents.flatMap(intent => options.participants(intent)))].sort();
|
||||
const requestId = options.createId(), compiled = intents.length > 1 ? options.compileBatch!(intents, requestId) : options.compile(record.intent, requestId);
|
||||
if (participants.length !== compiled.canvasIds.length || participants.some(canvas => !compiled.canvasIds.includes(canvas))) throw fault('participant_mismatch');
|
||||
options.mutate(ledger => ledger.freeze({ ...compiled, id: requestId, operationIds: intents.map(intent => intent.id) }));
|
||||
|
||||
Reference in New Issue
Block a user