import { QueryClient, hashKey } from '@tanstack/query-core' import { BTreeIndex, createCollection, createLiveQueryCollection, liveQueryCollectionOptions, eq, isUndefined, toArray, include, LoadSubsetOperationAbortedError, } from '@tanstack/db' import { evaluateReferenceExpression } from '../../db/tests/reference-expression-oracle.js' import { D2 } from '../../db-ivm/src/d2.js' import { withAcceptedReceipt } from '../../db/src/sync-receipt.js' import { getBuilderFromConfig, registerCollectionBuilder, } from '../../db/src/query/live/collection-registry.js' import { queryCollectionOptions } from '../src/query.js' import { activeWindowBeforeReload, pivotOf, sourceFacts, terminalSourceInterruption, } from './queued-answer-progress-history.js' import { observePausedHost } from './queued-answer-paused-host.js' import type { CollectionSubscription } from '../../db/src/collection/subscription.js' import type { ProgressHistory } from './queued-answer-progress-history.js' import type { Collection, LoadSubsetOptions } from '@tanstack/db' type Marker = { id: number; rowId: number } type ResultRow = { id: number rank: number markers: Array | Collection<{ id: number }> details: Array | Collection<{ id: number }> sibling: Array } type Request = { atom: string scope: number[] pending: boolean signal: AbortSignal | undefined query: object startCount: number release: (error?: Error) => void } function markerIds(value: unknown): Array { if (Array.isArray(value)) { if (value.some((id: unknown) => typeof id !== 'number')) throw new Error('Inline marker is not a number') return value } if ( !value || typeof value !== 'object' || !('toArray' in value) || !Array.isArray(value.toArray) ) throw new Error('Expected a marker Collection facade') return value.toArray.map((row: unknown) => { if ( !row || typeof row !== 'object' || !('id' in row) || typeof row.id !== 'number' ) throw new Error('Facade marker is missing its numeric key') return row.id }) } /** * Control finite provider replies and read facts from actual Query objects, * acquisition calls, and public Collections. The receiver preserves each * adapter argument, return value and user-visible payload. */ export async function driveQueuedAnswer( history: ProgressHistory, observe: (checkpoint: string, value: unknown) => void, ) { const { shift, route, siblingReplay, rootReceipt } = history const terminalSource = terminalSourceInterruption(history) const terminalAdmission = history.terminalWindowAdmission ?? 'after-pause' const terminalActive = terminalSource && terminalAdmission === 'before-reload' const activeBeforeReload = activeWindowBeforeReload(history) || terminalActive const orderedFailureBeforeReload = history.orderedFailureBeforeReload const previousOrderedFailure = new Error('earlier ordered request failed') let failNextOrderedRequest = false let priorOrderedFailureObserved = false let orderedRecoveryCalls = 0 let rejectHeldOrder: ((error: Error) => void) | undefined const observeRetirement = history.interruptPause === 'cleanup-unawaited' const firstLoadFailure = history.interruptPause === 'source-first-load-failure' const sourceFailure = new Error( firstLoadFailure ? 'root first load failed' : 'root sync threw on reload', ) let rootSyncThrows = false let failFirstLoad!: () => void let lifecycleError: unknown const cleanupPaused = history.interruptPause === 'cleanup' || observeRetirement const retiresPause = cleanupPaused || history.interruptPause === 'reload' const repeatPause = history.interruptPause === 'repeat' const siblingFails = siblingReplay === 'fails' const recoversWithHeldOutput = siblingReplay === 'recovers-with-held-output' const replacesAbortFailure = siblingReplay === 'replaces-abort-error' const providerAbortFailure = siblingReplay === 'abort-error' || replacesAbortFailure const { rows: roots, marked } = sourceFacts(history) const pivot = pivotOf(history) const prefix = ['queued-answer-progress'] const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: 0, gcTime: Infinity }, }, }) const owners = new WeakMap() let ownerCount = 0 const pending: Request[] = [] const queryIds = new WeakMap() let nextQueryId = 0 const queryId = (query: object) => { let id = queryIds.get(query) if (id === undefined) { id = ++nextQueryId queryIds.set(query, id) } return id } const leases = new WeakMap< LoadSubsetOptions, { attempt: number; key: unknown; queryId?: number } >() let startingLease: { attempt: number; key: unknown; queryId?: number } | undefined const cacheUnsubscribe = client .getQueryCache() .subscribe(({ query, type }) => { const answer = answers.get(query.queryHash) if ( type === 'updated' && answer?.query === query && answer.version === 1 && query.state.dataUpdateCount === answer.startCount + 1 ) { emit('answer-installed', { key: query.queryKey, queryId: queryId(query), updateCount: query.state.dataUpdateCount, rowIds: rowIds(query.state.data), }) } }) const answers = new Map< string, { version: number ids: number[] query: object startCount: number } >() const pivotCaches = () => client .getQueryCache() .getAll() .filter( (query) => JSON.stringify(query.queryKey.at(-1)) === JSON.stringify([pivot]), ) .map((query) => ({ key: query.queryKey, queryId: queryId(query), active: query.getObserversCount() > 0, data: rowIds(query.state.data), status: query.state.status, fetchStatus: query.state.fetchStatus, updateCount: query.state.dataUpdateCount, })) let version = 0 let holding = false let finishAnswer!: () => void const answerFinished = new Promise((resolve) => { finishAnswer = resolve }) let windowMove: Promise | undefined let windowReplayError = false let sourceRunsBeforeFailure: string | undefined let siblingFailureReported = false let retirement: Promise | undefined let retiredRequests: Array = [] let pauseCheckpoints = 0 let parkedGraph: D2 | undefined let graphResumptions = 0 let expectGraphCompletion = false let graphCompletion: 'missing' | 'pending' | 'fulfilled' | 'rejected' = 'missing' let graphCompletionError: unknown let retiringGeneration: number | undefined let pausedHost: ReturnType | undefined const replayFailure = providerAbortFailure ? new LoadSubsetOperationAbortedError() : new Error('marker replay failed while graph was paused') let siblingReload: Promise | undefined let holdSibling = true const siblingLoads = new Map< (error?: Error) => void, { signal: AbortSignal | undefined subscription: CollectionSubscription | undefined } >() const siblingIsHeld = () => [...siblingLoads.values()].some( ({ signal, subscription }) => !signal?.aborted && subscription?.pendingTruncateReplacement, ) const observeWindowRetry = ( options: { offset?: number; limit?: number } = { offset: 0 }, ) => { let status: 'fulfilled' | 'rejected' | 'pending' = 'pending' let cause: unknown const rejected = (error: unknown) => { status = 'rejected' cause = error } let settled: Promise | undefined try { settled = Promise.resolve(live.utils.setWindow(options)).then(() => { status = 'fulfilled' }, rejected) } catch (error) { rejected(error) } return { settled, hasError: (error: unknown) => cause === error, read: () => ({ retry: status, sameError: cause === replayFailure, live: payload(live.toArray), window: live.utils.getWindow(), }), } } let orderedMoveAtReload: ReturnType | undefined let activeWindowRetry: ReturnType | undefined const releaseSibling = (error?: Error) => { holdSibling = false for (const finish of siblingLoads.keys()) finish(error) siblingLoads.clear() } let outputMutation: Promise | undefined let rootReceiptError: unknown let windowError: unknown let replacementReplay = false let deliverRetiredRejection: (() => void) | undefined let retainedFacade: object | undefined let retainedRootId: number | undefined let releaseOutput!: () => void const outputGate = new Promise((resolve) => { releaseOutput = resolve }) let windowSettled = false let queued = false let queuedAttempt = 0 let queuedRelease = 0 let conflictObserved = false let fetches = 0 let attempts = 0 let releases = 0 let turns = 0 const emit = (phase: string, data: Record = {}) => observe(phase, { attempts, releases, fetches, turns, ...data }) const hostTurn = () => new Promise((resolve) => setTimeout(() => { turns++ resolve() }, 0), ) const rowIds = (data: unknown) => Array.isArray(data) ? data.map(({ id }) => id) : undefined const scopeOf = (options: LoadSubsetOptions) => roots .filter( ({ id }) => !options.where || evaluateReferenceExpression(options.where, { id, rowId: id }) === true, ) .map(({ id }) => id) const exact = (ids: number[], scope: number[]) => ids.length === scope.length && ids.every((id, index) => id === scope[index]) function requestWindow(offset = 0, limit?: number) { const move = live.utils.setWindow({ offset, limit }) if (terminalSource) { emit('terminal window admission', { pending: move !== true, pauseCheckpoints, heldAcquisitions: heldMarkerAcquisitions(), acceptedRootReceipts: pendingRootReceipts().length, }) } emit('window-request', { pending: move !== true, window: live.utils.getWindow(), live: payload(live.toArray), held: pending.some((request) => request.pending), }) windowMove = Promise.resolve(move === true ? undefined : move).then( () => { windowSettled = true emit('window-settled', { window: live.utils.getWindow(), live: payload(live.toArray), }) }, (error: unknown) => { if ( !history.interruptPause && !history.cleanupHeldOutput && !orderedFailureBeforeReload && !rootReceipt ) throw error if (rootReceipt || orderedFailureBeforeReload || terminalSource) windowError = error windowReplayError = error === replayFailure emit('window-rejected', { error: error instanceof Error ? error.name : String(error), replayFailure: windowReplayError, previousOrderedFailure: error === previousOrderedFailure, window: live.utils.getWindow(), }) }, ) void windowMove.catch(() => {}) return move !== true } function enqueue(kind: string) { if (queued) return const run = () => { emit('answer-executed', { kind, pending: pending .filter(({ pending }) => pending) .map(({ atom }) => atom), }) if (replacementReplay) { const realPause = pauseCheckpoints > 0 && graphCompletion === 'pending' requestWindow() deliverRetiredRejection?.() setTimeout(() => { observe('replacement pause after old receipt', { realPause, delivered: Boolean(deliverRetiredRejection), graphCompletion, windowSettled, windowError: windowError instanceof Error ? windowError.name : null, sameRootError: windowError !== undefined && windowError === rootReceiptError, }) holding = false for (const request of pending) request.release() emit('answer-callback-returned', { kind }) finishAnswer() }, 0) return } // Record the current runs after starting the sibling's replacement. // The provider's AbortError then comes from a demand that remained held. if (providerAbortFailure) { siblingReload = sibling?.reload() void siblingReload?.catch(() => {}) sourceRunsBeforeFailure = sourceRuns() } if (history.holdOutput) { const transaction = live.update( live.toArray[0]!.id, { optimistic: false }, (draft) => { draft.rank += history.rankScale }, ) outputMutation = transaction.when('settled') emit('output-hold-start', { persisting: transaction.state === 'persisting', }) } if (repeatPause) { emit('paused again before answer', { pauseCheckpoints, graphResumptions, windowSettled, window: live.utils.getWindow(), live: payload(live.toArray), }) } else if ( history.moveWindow && (!terminalSource || terminalAdmission === 'after-pause') ) { requestWindow() } if (retiresPause) { retiringGeneration = cleanupPaused ? live._sync.getSyncRunGeneration() : markers._sync.getSyncRunGeneration() emit('retire-paused-run', { pauseCheckpoints, live: payload(live.toArray), downstream: downstream.toArray.map(({ id, rank }) => ({ id, rank })), }) retiredRequests = pending.filter( (request) => request.pending && !request.signal?.aborted, ) } if (terminalSource) { pausedHost!.retire() emit('before terminal source failure', { graphCompletion, pauseCheckpoints, scheduledGraphTasks: pausedHost!.read().pendingAtCleanup, heldMarkerReplay: heldMarkerAcquisitions() > 0, status: live.status, }) if (firstLoadFailure) failFirstLoad() else { rootSyncThrows = true void source.reload().catch((error: unknown) => { lifecycleError = error }) } } else if (history.interruptPause === 'failure') { if (!providerAbortFailure) { siblingReload = sibling?.reload() void siblingReload?.catch(() => {}) } // Let the scheduled graph turn return while the replay still holds // publication. The failed answer then runs on its own host turn. setTimeout(() => { const requests = pending.filter((request) => request.pending) emit('reject-paused-replay', { pauseCheckpoints, graphResumptions, graphCompletion, requests: requests.filter((request) => !request.signal?.aborted) .length, live: payload(live.toArray), }) if (siblingFails) { emit('fail-loaded-sibling', { siblingHeld: siblingIsHeld() }) releaseSibling(replayFailure) } else { holding = false for (const request of requests) request.release( request.signal?.aborted ? undefined : replayFailure, ) } }, 0) } else { holding = false if (retiresPause) { pausedHost?.retire() retirement = cleanupPaused ? live.cleanup({ dependents: true }) : markers.reload() void retirement.catch(() => {}) } for (const request of pending) request.release() } emit('answer-callback-returned', { kind }) finishAnswer() } if (repeatPause) { // The provider uses a second timer turn for its already queued answer. // The original window attaches before the still-held graph runs again. setTimeout(() => { requestWindow() emit('window at first pause', { pauseCheckpoints, graphResumptions }) setTimeout(run, 0) }, 0) } else if (history.host === 'timer') setTimeout(run, 0) else queueMicrotask(run) queued = true queuedAttempt = attempts queuedRelease = releases emit('answer-enqueued', { kind }) } function measureConflict() { if (queued || !holding || conflictObserved) return const queries = client.getQueryCache().getAll() for (const request of pending) { if ( !request.pending || request.signal?.aborted || !exact(request.scope, [pivot]) ) continue const actual = queries.find((query) => query.queryHash === request.atom) if ( !actual || actual !== request.query || actual.state.dataUpdateCount !== request.startCount || actual.state.status !== 'success' || actual.state.fetchStatus !== 'fetching' || !rowIds(actual.state.data)?.includes(pivot) ) continue const sibling = queries.find((query) => { const answer = answers.get(query.queryHash) return ( query !== actual && query.state.status === 'success' && rowIds(query.state.data)?.length === 0 && Array.isArray(query.queryKey.at(-1)) && exact(query.queryKey.at(-1) as number[], [pivot]) && answer?.query === query && answer.version === 1 && answer.ids.length === 0 && query.state.dataUpdateCount === answer.startCount + 1 ) }) if (!sibling) continue conflictObserved = true emit('cache-conflict', { actual: actual.queryKey, actualIds: rowIds(actual.state.data), actualStatus: actual.state.fetchStatus, sibling: sibling.queryKey, siblingIds: rowIds(sibling.state.data), cacheStates: pivotCaches(), requestAborted: request.signal?.aborted ?? false, rawHasPivot: markers.has(pivot), liveIds: rowIds(live.toArray), downstreamIds: rowIds(downstream.toArray), materialization: live.toArray.map(({ markers: value }) => Array.isArray(value) ? 'inline' : 'facade', ), }) if (route === 'conflict') enqueue('resolving-cache-conflict') return } } let truncateMarkers: (() => void) | undefined const markerOptions = queryCollectionOptions({ queryClient: client, queryKey: (options) => { if (!options.subscription) return prefix let owner = owners.get(options.subscription) if (owner === undefined) { owner = ++ownerCount owners.set(options.subscription, owner) } const key = route === 'shared-key' ? [...prefix, scopeOf(options)] : [...prefix, owner, scopeOf(options)] if (startingLease) startingLease.key = key return key }, getKey: ({ id }) => id, syncMode: 'on-demand', autoIndex: 'eager', defaultIndexType: BTreeIndex, queryFn: (context) => { const options = (context.meta?.loadSubsetOptions as LoadSubsetOptions | undefined) ?? {} if ( options.orderBy !== undefined || options.limit !== undefined || options.offset !== undefined || options.cursor !== undefined ) { throw new Error('Expected a predicate-only marker request') } const scope = scopeOf(options) const atom = hashKey(context.queryKey) const query = client .getQueryCache() .getAll() .find((entry) => entry.queryHash === atom) if (!query) throw new Error('Actual Query absent at provider start') const startCount = query.state.dataUpdateCount if (startingLease) startingLease.queryId = queryId(query) fetches++ const result = () => { const ids = scope.filter((id) => marked.has(id)) answers.set(atom, { version, ids, query, startCount }) if (version === 1) emit('provider-answer', { atom, scope, ids, startCount, queryId: queryId(query), active: query.getObserversCount() > 0, stale: rowIds(query.state.data)?.includes(pivot) ?? false, aborted: options.signal?.aborted ?? false, }) return ids.map((id) => ({ id, rowId: id })) } if (!holding) return Promise.resolve(result()) emit('held-fetch', { scope, key: context.queryKey }) return new Promise((resolve, reject) => { const request: Request = { atom, scope, query, startCount, signal: options.signal, pending: true, release: (error) => { if (!request.pending) return request.pending = false if (error) reject(error) else resolve(result()) }, } pending.push(request) measureConflict() }) }, }) const markers = createCollection({ ...markerOptions, sync: { ...markerOptions.sync, sync: (params) => { if (history.truncateDuringReload || replacesAbortFailure) { truncateMarkers = () => { params.begin() params.truncate({ markReady: false }) params.commit() } } return markerOptions.sync.sync(params) }, }, }) // Observe delegated adapter calls and cache facts. The wrappers always pass // through the original arguments, return value and effects. const load = markers._sync.loadSubset.bind(markers._sync) const markerSubscriptions = new Set() markers._sync.loadSubset = (options) => { if (replacesAbortFailure && options.subscription) markerSubscriptions.add(options.subscription as CollectionSubscription) measureConflict() attempts++ if (queued && attempts - queuedAttempt <= 64) { emit('load', { scope: scopeOf(options), pivotPresent: markers.has(pivot), caches: pivotCaches(), }) } const attempt = attempts const lease = { attempt, key: undefined as unknown, queryId: undefined as number | undefined, } leases.set(options, lease) const outerLease = startingLease startingLease = lease let result try { result = load(options) } finally { startingLease = outerLease } if ( version === 1 && exact(scopeOf(options), [pivot]) && result instanceof Promise && attempt <= queuedAttempt + 24 ) { const receipt = () => ({ ...lease, aborted: options.signal?.aborted ?? false, rawHasPivot: markers.has(pivot), }) void result.then( () => emit('subset-applied', receipt()), (error: unknown) => emit('subset-rejected', { ...receipt(), error: String(error) }), ) } return result } const unload = markers._sync.unloadSubset.bind(markers._sync) markers._sync.unloadSubset = (options) => { releases++ if (queued && releases - queuedRelease <= 64) { emit('unload', { scope: scopeOf(options), pivotPresent: markers.has(pivot), lease: leases.get(options), }) } return unload(options) } let updateRoot!: (row: (typeof roots)[number]) => void const source = createCollection<(typeof roots)[number]>({ getKey: ({ id }) => id, ...(orderedFailureBeforeReload ? { syncMode: 'on-demand' as const } : {}), autoIndex: 'eager', defaultIndexType: BTreeIndex, sync: { sync: ({ begin, write, commit, markReady, fail }) => { if (rootSyncThrows) throw sourceFailure begin() for (const row of roots) write({ type: 'insert', value: row }) commit() if (firstLoadFailure) failFirstLoad = () => fail(sourceFailure) else markReady() updateRoot = (row) => { begin() write({ type: 'update', value: row }) commit() } if (!orderedFailureBeforeReload) return return { loadSubset: () => { if (failNextOrderedRequest) { priorOrderedFailureObserved = true if (orderedFailureBeforeReload === 'current') { failNextOrderedRequest = false return new Promise((_resolve, reject) => { rejectHeldOrder = reject }) } return Promise.reject(previousOrderedFailure) } if (priorOrderedFailureObserved) orderedRecoveryCalls++ return true }, } }, }, }) const sibling = siblingReplay ? createCollection({ getKey: ({ id }) => id, syncMode: 'on-demand', autoIndex: 'eager', defaultIndexType: BTreeIndex, sync: { sync: ({ markReady }) => { // Only the replacement run waits for the sibling provider. const hold = version === 1 markReady() return { loadSubset: ({ signal, subscription }) => hold && holdSibling ? new Promise((resolve, reject) => siblingLoads.set( (error) => (error ? reject(error) : resolve()), { signal, subscription: subscription as CollectionSubscription | undefined, }, ), ) : true, } }, }, }) : undefined const liveOptions = liveQueryCollectionOptions({ getKey: (row: ResultRow) => row.id, onUpdate: () => outputGate, query: (q) => { const window = q .from({ row: source }) .leftJoin({ marker: markers }, ({ row, marker }) => eq(row.id, marker.rowId), ) .where(({ marker }) => isUndefined(marker.rowId)) .orderBy(({ row }) => row.rank) .offset(1) .limit(1) const children = ( id: Parameters[0]>[0]['row']['id'], ) => q.from({ child: markers }).where(({ child }) => eq(child.rowId, id)) return window.select(({ row }) => ({ id: row.id, rank: row.rank, markers: route === 'no-include' ? ([] as Array) : history.materialization === 'inline' ? toArray(children(row.id).select(({ child }) => child.id)) : include( children(row.id).select(({ child }) => ({ id: child.id })), ), details: history.holdFacade ? include( q .from({ detail: source }) .where(({ detail }) => eq(detail.id, row.id)) .select(({ detail }) => ({ id: detail.id })), ) : [], sibling: sibling ? toArray( q .from({ extra: sibling }) .where(({ extra }) => eq(extra.rowId, row.id)) .select(({ extra }) => extra.id), ) : [], })) }, }) const builder = getBuilderFromConfig(liveOptions)! const applicationSchedules: Array = [] let handlingReceipt: number | undefined let rootCommit: Promise | undefined let cleanupFromRoot: Promise | undefined const live = createCollection< ResultRow, string | number, typeof liveOptions.utils >( rootReceipt ? { ...liveOptions, sync: { ...liveOptions.sync, sync(params) { return liveOptions.sync.sync({ ...params, commit(signal) { // Use the real core commit. Cancel only before acceptance // and only for the first root write after a real pause. if ( rootReceipt === 'cancel root commit before acceptance' && graphCompletion === 'pending' && !rootCommit ) { const canceled = params.commit(AbortSignal.abort()) if (canceled !== true) { rootCommit = canceled void canceled.catch((error: unknown) => { rootReceiptError = error }) } return canceled } const receipt = params.commit(signal) if ( rootReceipt === 'ignore an application rejection from the retired root' && receipt !== true && outputMutation && !rootCommit ) { // This wrapped sync already handed its write to Core. Its // application error is delivered at a controlled later // cut, without replacing Core's exact rejection. rootCommit = new Promise((resolve, reject) => { void receipt.then(resolve, (error: unknown) => { rootReceiptError = error deliverRetiredRejection = () => reject(error) }) }) void rootCommit.catch(() => undefined) return withAcceptedReceipt(rootCommit, true) } if ( receipt !== true && outputMutation && rootReceipt !== 'cancel root commit before acceptance' ) { const index = applicationSchedules.push(0) - 1 rootCommit ??= receipt // Observe which exact applied receipt requested a graph // turn, independently of data and other schedule calls. receipt.then = new Proxy(receipt.then, { apply(target, receiver, [fulfill, reject]) { return Reflect.apply(target, receiver, [ typeof fulfill === 'function' ? (...values: Array) => { handlingReceipt = index try { return Reflect.apply( fulfill, undefined, values, ) } finally { handlingReceipt = undefined } } : fulfill, reject, ]) }, }) } return receipt }, }) }, }, } : liveOptions, ) registerCollectionBuilder(live, builder) const scheduleGraphRun = builder.scheduleGraphRun if (rootReceipt) builder.scheduleGraphRun = function (options) { if (handlingReceipt !== undefined) { applicationSchedules[handlingReceipt]!++ // A retired receipt must never enter the dead query's scheduler. // Record that attempted entry without letting its invariant throw // escape the controlled receiver as an unrelated host error. if (cleanupFromRoot) return } return scheduleGraphRun.call(this, options) } const downstream = createLiveQueryCollection((q) => q .from({ row: live }) .orderBy(({ row }) => row.rank) .select(({ row }) => ({ id: row.id, rank: row.rank })), ) const payload = (rows: typeof live.toArray) => rows.map(({ id, rank, markers: child, details }) => ({ id, rank, markers: markerIds(child), ...(history.holdFacade ? { details: markerIds(details) } : {}), })) const snapshot = (phase: string) => emit(phase, { live: payload(live.toArray), downstream: downstream.toArray.map(({ id, rank }) => ({ id, rank })), materialization: live.toArray.map(({ markers: value }) => Array.isArray(value) ? 'inline' : 'facade', ), rawHasPivot: markers.has(pivot), pivotCaches: phase === 'final' ? pivotCaches() : undefined, status: live.status, inFlight: pending.filter((request) => request.pending).length, }) const sub = live.subscribeChanges((changes) => { emit('root-events', { changes: changes.map(({ type, value }) => ({ type, value: payload([value])[0], })), }) snapshot('live-callback') }) const childSub = downstream.subscribeChanges(() => snapshot('downstream-callback'), ) const sourceRuns = () => `${markers._sync.getSyncRunGeneration()}:${sibling?._sync.getSyncRunGeneration()}` let replacedFailure = false const stopFailureReplacement = replacesAbortFailure ? live.on('health:change', () => { if ( replacedFailure || live.health.error?.cause !== replayFailure || ![...markerSubscriptions].some((sub) => sub.failedTruncateReplacement) ) return replacedFailure = true const before = sourceRuns() truncateMarkers!() emit('same-run-truncate-replaces-failure', { sameSourceRuns: before === sourceRuns() && before === sourceRunsBeforeFailure, pendingReplacement: [...markerSubscriptions].some( (sub) => sub.pendingTruncateReplacement, ), retainedFailure: [...markerSubscriptions].some( (sub) => sub.failedTruncateReplacement, ), }) }) : undefined const stopSiblingFailureObservation = siblingFails ? live.on('health:change', () => { if (live.health.error?.cause === replayFailure) siblingFailureReported = true }) : undefined const peer = route === 'peer' ? createLiveQueryCollection((q) => q .from({ marker: markers }) .where(({ marker }) => eq(marker.rowId, pivot)), ) : undefined const runGraph = D2.prototype.run const tracksGraphCompletion = history.route === 'conflict' && (history.holdOutput || history.interruptPause === 'failure' || terminalSource || observeRetirement || orderedFailureBeforeReload) const trackOperation = live._sync.trackLoadSubsetOperationPromise if (observeRetirement || terminalSource) pausedHost = observePausedHost() let stopFacadeObservation: (() => void) | undefined if (tracksGraphCompletion) { live._sync.trackLoadSubsetOperationPromise = function (receipt) { // The first concrete pause hands its publication receipt to the // operation tracker before this graph turn returns to the host. if (expectGraphCompletion) { expectGraphCompletion = false graphCompletion = 'pending' if (observeRetirement) pausedHost?.captureCompletion(receipt) else void receipt.then( () => { graphCompletion = 'fulfilled' }, (error: unknown) => { graphCompletion = 'rejected' graphCompletionError = error }, ) } trackOperation.call(this, receipt) } } if ( history.interruptPause || recoversWithHeldOutput || tracksGraphCompletion ) { // Observe the real operator checkpoint without choosing where it runs or // changing the returned pause decision. D2.prototype.run = function (shouldPause) { if (this === parkedGraph) graphResumptions++ const before = pauseCheckpoints const result = runGraph.call( this, shouldPause && (() => { const pause = shouldPause() if (pause && this.pendingWork()) { pauseCheckpoints++ parkedGraph = this } return pause }), ) if (tracksGraphCompletion && before === 0 && pauseCheckpoints > 0) { expectGraphCompletion = true queueMicrotask(() => { expectGraphCompletion = false }) } if (before !== pauseCheckpoints) pausedHost?.arm() return result } } const pendingRootReceipts = () => live._state.pendingSyncedTransactions .filter((batch) => batch.committed && batch.applied.isPending()) .map((batch) => batch.applied) const heldMarkerAcquisitions = () => pending.filter((request) => request.pending && !request.signal?.aborted) .length async function releaseOrderedMarkerRequests() { for (const scope of [[shift + 1, shift + 2], [pivot]]) { const request = pending.find( (candidate) => candidate.pending && !candidate.signal?.aborted && exact(candidate.scope, scope), ) if (request) { emit('release', { scope, atom: request.atom }) request.release() await hostTurn() if (route === 'peer' && exact(scope, [pivot])) { emit('held-peer', { rawHasPivot: markers.has(pivot), peerHasPivot: peer?.has(pivot), }) } } else { emit('release-premise-missing', { scope }) } } } async function receiveOldRejectionInReplacement() { const accepted = pendingRootReceipts().length const realPause = pauseCheckpoints > 0 && graphCompletion === 'pending' const retiredRun = live._sync.getSyncRunGeneration() await live.cleanup({ dependents: true }) await windowMove releaseOutput() await outputMutation await hostTurn() observe('retire before old application rejection', { accepted, realPause, deliveryReady: Boolean(deliverRetiredRejection), status: live.status, windowError: windowError instanceof Error ? windowError.name : null, }) // Restart from the previous provider relation through fresh real Query // subscriptions. The replacement reload creates its own cache conflict // and its own pause on the same live-query Collection. version = 0 marked.add(pivot) holding = false await live.preload() await downstream.preload() observe('replacement before its replay', { newRun: live._sync.getSyncRunGeneration() !== retiredRun, live: payload(live.toArray), }) version = 1 marked.delete(pivot) replacementReplay = true conflictObserved = false queued = false pauseCheckpoints = 0 graphResumptions = 0 pending.length = 0 windowSettled = false windowError = undefined holding = true const answer = new Promise((resolve) => { finishAnswer = resolve }) const reload = markers.reload() void reload.catch(() => {}) await hostTurn() await releaseOrderedMarkerRequests() if (!queued) enqueue('control') await answer await reload for (let turn = 0; turn < 6; turn++) await hostTurn() observe('replacement window after old application rejection', { graphCompletion, windowSettled, windowError: windowError instanceof Error ? windowError.name : null, live: payload(live.toArray), window: live.utils.getWindow(), status: live.status, }) } async function recoverWhileRootOutputIsHeld() { if (!sibling) throw new Error('Expected an independent replay source') const run = live._sync.getSyncRunGeneration() const first = pendingRootReceipts() updateRoot({ id: pivot, rank: 3 * history.rankScale + 1 }) await hostTurn() const second = pendingRootReceipts() const failing = sibling.reload() void failing.catch(() => {}) await hostTurn() const siblingHeld = siblingIsHeld() releaseSibling(replayFailure) await hostTurn() const failureReported = live.health.error?.cause === replayFailure // A source change runs the graph while the independent replay has failed. // This row is outside the result, so it does not add another root batch. updateRoot({ id: shift + 5, rank: 5 * history.rankScale + 1 }) await sibling.reload() for (let turn = 0; turn < 3; turn++) await hostTurn() const retry = observeWindowRetry({ offset: 1, limit: 2 }) await hostTurn() emit('recovered replay and root receipts held', { ...retry.read(), sameRun: live._sync.getSyncRunGeneration() === run, pauseCheckpoints, siblingHeld, failureReported, failureCleared: live.health.error === null, firstAccepted: first.length, secondAccepted: second.length, retainedFirst: first.every((receipt) => second.includes(receipt)), pendingRoot: pendingRootReceipts().length, retainedBoth: second.every((receipt) => receipt.isPending()), }) return retry } try { if (firstLoadFailure) { void live.preload().catch((error: unknown) => { lifecycleError = error }) void downstream.preload().catch(() => {}) // Let initial rows reach both layers while the root has yet to mark ready. for (let turn = 0; turn < 5; turn++) await hostTurn() } else { await live.preload() await downstream.preload() } if (peer) await peer.preload() snapshot('initial') if (history.holdFacade) { const candidate: unknown = live.toArray[0]?.details if ( !candidate || typeof candidate !== 'object' || !('subscribeChanges' in candidate) ) throw new Error('The prior window has no retained facade') const details = candidate as Collection<{ id: number }> retainedFacade = details retainedRootId = live.toArray[0]!.id emit('retained-facade-start', { detailIds: markerIds(details) }) const subscription = details.subscribeChanges( (changes) => emit('facade-callback', { live: payload(live.toArray), detailIds: markerIds(details), changes: changes.map(({ type, value }) => ({ type, id: value.id })), }), { includeInitialState: false }, ) stopFacadeObservation = () => subscription.unsubscribe() } if (activeBeforeReload) { const prior = live.toArray[0]! const mutation = live.update(prior.id, { optimistic: false }, (draft) => { draft.rank += 1 }) updateRoot({ id: prior.id, rank: prior.rank + 1 }) outputMutation = mutation.when('settled') if (terminalActive) await hostTurn() emit('window admitted before reload', { pending: requestWindow(1, terminalActive ? 2 : undefined), persisting: mutation.state === 'persisting', pauseCheckpoints, rows: payload(live.toArray), window: live.utils.getWindow(), }) } if (orderedFailureBeforeReload) { // A real widening owns this ordered load. The provider can settle // before the independent source reload or remain held through it. failNextOrderedRequest = true const old = observeWindowRetry({ limit: roots.length + 5 }) if (orderedFailureBeforeReload === 'previous') { await old.settled failNextOrderedRequest = false emit('ordered failure before reload', { ...old.read(), rootProviderFailed: priorOrderedFailureObserved, exactFailure: old.hasError(previousOrderedFailure), }) } else { orderedMoveAtReload = old await hostTurn() } } version = 1 marked.delete(pivot) if (recoversWithHeldOutput) marked.add(shift + 4) holding = true emit('reload-start') const reload = markers.reload() void reload.catch((error: unknown) => emit('reload-rejected', { error: String(error) }), ) await hostTurn() snapshot('held') if (terminalSource && terminalAdmission === 'during-replay') requestWindow() if (history.truncateDuringReload) { if (!truncateMarkers) throw new Error('The source sync run did not start') const prior = pending.filter( (request) => request.pending && !request.signal?.aborted, ) const before = pending.length truncateMarkers() await hostTurn() emit('truncate-replaced-reload', { retired: prior.filter((request) => request.signal?.aborted).length, replacement: pending .slice(before) .filter((request) => request.pending && !request.signal?.aborted) .length, live: payload(live.toArray), downstream: downstream.toArray.map(({ id, rank }) => ({ id, rank })), }) } await releaseOrderedMarkerRequests() if (!queued) enqueue(route === 'peer' ? 'peer-release' : 'control') await answerFinished if (terminalSource) { // Keep the marker provider held until the terminal verdict is visible. // The native task would have entered by this point if it survived. await hostTurn() const host = pausedHost!.read() emit('paused work after terminal source failure', { graphCompletion, exactGraphError: graphCompletionError === sourceFailure, exactLifecycleError: lifecycleError === sourceFailure, exactWindowError: windowError === sourceFailure, scheduledGraphTasks: host.outstandingAfterCleanup, retiredGraphEntries: host.enteredAfterCleanup, sourceStatus: source.status, liveStatus: live.status, downstreamStatus: downstream.status, window: live.utils.getWindow(), }) snapshot('terminal retained result') const takeNextWindow = async (checkpoint: string) => { const next = observeWindowRetry() await hostTurn() emit(checkpoint, { ...next.read(), exactError: next.hasError(sourceFailure), heldAcquisitions: heldMarkerAcquisitions(), }) } await takeNextWindow('terminal window admission with held provider') // A healthy provider may still finish after the terminal error. Its // answer and any older accepted application must not fulfill this move. holding = false for (const request of pending) request.release() if (terminalActive) { releaseOutput() await outputMutation } for (let turn = 0; turn < 5; turn++) await hostTurn() emit('terminal window after independent work settles', { windowSettled, exactWindowError: windowError === sourceFailure, heldAcquisitions: heldMarkerAcquisitions(), acceptedRootReceipts: pendingRootReceipts().length, window: live.utils.getWindow(), }) snapshot('final') let rejectsInvalidLimit = false try { const request = live.utils.setWindow({ limit: -1 }) if (request !== true) void request.catch(() => {}) } catch (error) { rejectsInvalidLimit = error instanceof RangeError } emit('terminal invalid window validation', { rejectsInvalidLimit }) await takeNextWindow( 'terminal window admission after provider settlement', ) return } if (siblingFails) { for (let turn = 0; turn < 5 && !siblingFailureReported; turn++) await hostTurn() await hostTurn() emit('late-sibling-failure', { earlierReplayHeld: pending.some( ({ pending, signal }) => pending && !signal?.aborted, ), failureReported: siblingFailureReported, windowReplayError, live: payload(live.toArray), window: live.utils.getWindow(), }) holding = false for (const request of pending) request.release() } if (history.interruptPause === 'failure') await reload.catch(() => {}) else await reload if (orderedMoveAtReload) { emit('ordered receipt held after independent replay', { ...orderedMoveAtReload.read(), rootHeld: rejectHeldOrder !== undefined, pauseCheckpoints, graphCompletion, }) rejectHeldOrder?.(previousOrderedFailure) for (let turn = 0; turn < 3; turn++) await hostTurn() emit('owned ordered failure while graph waits', { ...orderedMoveAtReload.read(), exactFailure: orderedMoveAtReload.hasError(previousOrderedFailure), }) } if (retirement) { await retirement await windowMove const generation = cleanupPaused ? live._sync.getSyncRunGeneration() : markers._sync.getSyncRunGeneration() emit('retired-run', { status: live.status, live: payload(live.toArray), window: live.utils.getWindow(), aborted: retiredRequests.filter((request) => request.signal?.aborted) .length, runChanged: generation !== retiringGeneration, }) if (cleanupPaused) { // Let the old host callback's turn pass while the query is closed. await hostTurn() if (pausedHost) { // A browser rejection event may itself be dispatched in a later // task after the rejected promise's microtask checkpoint. await hostTurn() const cut = pausedHost.read() emit('retired pause host work', cut) pausedHost.stop() pausedHost = undefined if ( cut.enteredAfterCleanup || cut.outstandingAfterCleanup || cut.unhandledCompletions ) return } await live.preload() await downstream.preload() } } if (outputMutation) { for (let turn = 0; turn < 3; turn++) await hostTurn() emit('output-held', { windowSettled, graphCompletion, pauseCheckpoints, acceptedReceipts: pendingRootReceipts().length, window: live.utils.getWindow(), live: payload(live.toArray), rawHasPivot: markers.has(pivot), ...(retainedRootId === undefined ? {} : { sameFacade: live.get(retainedRootId)?.details === retainedFacade, }), acceptedReplacement: live._state.getAcceptedSyncedRow(pivot) !== undefined || live._state.getAcceptedSyncedRow(history.shift + 2) !== undefined, }) if (rootReceipt) { if ( rootReceipt === 'ignore an application rejection from the retired root' ) { await receiveOldRejectionInReplacement() return } if (rootReceipt === 'apply two accepted root receipts') { updateRoot({ id: pivot, rank: 3 * history.rankScale + 1 }) await hostTurn() } const accepted = pendingRootReceipts().length const prior = payload(live.toArray) const beforeWindow = live.utils.getWindow() let stopRootRetirement: (() => void) | undefined if (rootReceipt === 'cleanup from root publication') { const subscription = live.subscribeChanges((changes) => { if (!cleanupFromRoot && changes.length) cleanupFromRoot = live.cleanup({ dependents: true }) }) stopRootRetirement = () => subscription.unsubscribe() } let receiptVerdict = 'pending' void rootCommit?.then( () => { receiptVerdict = 'fulfilled' }, () => { receiptVerdict = 'rejected' }, ) releaseOutput() await outputMutation await cleanupFromRoot for (let turn = 0; turn < 3; turn++) await hostTurn() stopRootRetirement?.() observe('paused root receipt outcome', { accepted, prior, beforeWindow, realPause: pauseCheckpoints > 0, receiptVerdict, graphCompletion, windowSettled, windowError: windowError instanceof Error ? windowError.name : null, sameRootError: rootReceiptError !== undefined && windowError === rootReceiptError, applicationSchedules, live: payload(live.toArray), window: live.utils.getWindow(), status: live.status, }) return } if (history.cleanupHeldOutput) { await live.cleanup({ dependents: true }) await windowMove } const recoveredWindow = recoversWithHeldOutput ? await recoverWhileRootOutputIsHeld() : undefined releaseOutput() await outputMutation if (activeBeforeReload) { await hostTurn() emit('active window after releasing persistence', { windowSettled, windowReplayError, replacedFailure, siblingHeld: siblingIsHeld(), pauseCheckpoints, window: live.utils.getWindow(), }) } if (recoveredWindow) { for (let turn = 0; turn < 3; turn++) await hostTurn() emit('recovered window after releasing root output', { ...recoveredWindow.read(), pendingRoot: pendingRootReceipts().length, }) } if (history.cleanupHeldOutput) { await hostTurn() emit('settled-after-cleanup', { window: live.utils.getWindow(), live: payload(live.toArray), status: live.status, }) await live.preload() await downstream.preload() } } if (repeatPause) { for (let turn = 0; turn < 8 && !windowSettled; turn++) await hostTurn() emit('window after repeated pause', { windowSettled, window: live.utils.getWindow(), live: payload(live.toArray), rawHasPivot: markers.has(pivot), }) if (!windowSettled) return } if (siblingReplay === 'abort-error') { for ( let turn = 0; turn < 5 && live.health.error?.cause !== replayFailure; turn++ ) await hostTurn() await hostTurn() emit('current-abort-error', { failureReported: live.health.error?.cause === replayFailure, sameSourceRuns: sourceRunsBeforeFailure === sourceRuns(), siblingHeld: siblingIsHeld(), windowReplayError, }) } else if (!siblingFails && !replacesAbortFailure) { // The late-sibling case judged this waiter before releasing its peer. await windowMove } if (replacesAbortFailure) { emit('replaced-failure-before-release', { siblingHeld: siblingIsHeld(), live: payload(live.toArray), window: live.utils.getWindow(), }) releaseSibling() await siblingReload if (activeBeforeReload) activeWindowRetry = observeWindowRetry({ offset: 1 }) else await windowMove } else if (history.interruptPause === 'failure' && !siblingFails) { const retry = observeWindowRetry() await hostTurn() emit('failed-window-retry', { ...retry.read(), siblingHeld: siblingIsHeld(), failureReported: live.health.error?.cause === replayFailure, }) let recovered: ReturnType | undefined if (siblingReplay === 'recovers') { await markers.reload() for (let turn = 0; turn < 6 && live.health.error; turn++) await hostTurn() recovered = observeWindowRetry() await hostTurn() emit('repaired-replay-with-held-sibling', { ...recovered.read(), siblingHeld: siblingIsHeld(), failureCleared: live.health.error === null, }) } releaseSibling() await siblingReload if (recovered) { await recovered.settled emit('repaired-window-settled', recovered.read()) } } // Once Query Core is quiet, allow a separately scheduled graph turn and // its settled subscriptions to run before comparing the public result. let quietTurns = 0 for (let i = 0; i < 10 && quietTurns < 3; i++) { await hostTurn() if ( client .getQueryCache() .getAll() .every((query) => query.state.fetchStatus === 'idle') ) quietTurns++ else quietTurns = 0 } if (activeWindowRetry) emit('retry after active window failure', activeWindowRetry.read()) snapshot('final') if (orderedFailureBeforeReload === 'previous') emit('window after unrelated replay', { committed: windowSettled, previousFailure: windowError === previousOrderedFailure, pauseCheckpoints, orderedRecoveryCalls, window: live.utils.getWindow(), }) if (tracksGraphCompletion) emit('first paused graph verdict', { state: graphCompletion, replayFailure: graphCompletionError === replayFailure, }) } finally { rejectHeldOrder?.(previousOrderedFailure) if (rootReceipt) builder.scheduleGraphRun = scheduleGraphRun pausedHost?.stop() if (tracksGraphCompletion) live._sync.trackLoadSubsetOperationPromise = trackOperation if ( history.interruptPause || recoversWithHeldOutput || tracksGraphCompletion ) D2.prototype.run = runGraph stopSiblingFailureObservation?.() stopFailureReplacement?.() stopFacadeObservation?.() releaseOutput() releaseSibling() holding = false for (const request of pending) request.release() childSub.unsubscribe() sub.unsubscribe() await downstream.cleanup() await live.cleanup() if (peer) await peer.cleanup() await markers.cleanup() if (sibling) await sibling.cleanup() await source.cleanup() cacheUnsubscribe() client.clear() emit('cleanup-complete') } }