@tanstack/db
Version:
A reactive client store for building super fast apps on sync
1 lines • 87.7 kB
Source Map (JSON)
{"version":3,"file":"collection-config-builder.cjs","names":["findProblems","createSourceRecord","buildQueryFromConfig","extractCollectionsFromQuery","extractCollectionSources","extractCollectionFromSource","LIVE_QUERY_INTERNAL","SetWindowRequiresOrderByError","SetWindowFindOneLimitError","SetWindowReentrancyError","LoadSubsetOperationAbortedError","codedMessage","createDeferred","hasPendingJoinedSourceWork","normalizeError","D2","compileCollectionQuery","reducePublicKeys","MissingAliasInputsError","output","sourcePermitsInitialReadiness","getCollectionBuilder","CollectionSubscriber","isFailedStatus","runAllCallbacks","deepEquals","collectionSources","dependentEntry","resultKeys","orderByIndices","isGraphRunning","graphInputRevision","fatalQueryError","reloadSnapshotPending","builderDependencies","includeSourceIds","activeDemands","demandGeneration","pendingOrderedLoads","orderedLoadFailed","windowFailed","windowRequestGeneration","initialWindow","settledWindow","compileBasePipeline","getSyncConfig","windowFn","activeWindowOperation","currentWindow","pendingSourceRecovery","latestWindowRequest","settlement","hasFailedSourceRecovery","maybeRunGraphFn","crashQuery","loadMoreFn","updateLiveQueryStatus","syncFn","clearSyncRunState","extendPipelineWithChangeProcessing","subscribeToAllCollections","graphCache","inputsCache","pipelineCache","valueResolverCache","bucketFacadesCache","includesRuntimeCache","maybeCompileBasePipeline","isResultComplete","applyChanges","handleSourceStatusChange","handleSourceCleanupStart","allRequiredSourcesReady","enterErrorState"],"sources":["../../../../src/query/live/collection-config-builder.ts"],"sourcesContent":["import { D2, output } from '@tanstack/db-ivm'\nimport { compileCollectionQuery } from '../compiler/index.js'\nimport { validateLimit } from '../validate-limit.js'\nimport {\n LoadSubsetOperationAbortedError,\n MissingAliasInputsError,\n SetWindowFindOneLimitError,\n SetWindowReentrancyError,\n SetWindowRequiresOrderByError,\n} from '../../errors.js'\nimport { withPublicationContext } from '../../scheduler.js'\nimport { createDeferred } from '../../deferred.js'\nimport { deepEquals } from '../../utils.js'\nimport { runAllCallbacks } from '../../utils/callbacks.js'\nimport { normalizeError } from '../../utils/error.js'\nimport { createSourceRecord } from '../../utils/source-record.js'\nimport { codedMessage, devBuild } from '../../error-message.js'\nimport { collectSourceRefs } from '../ir.js'\nimport { findProblems } from '../../collection/health-tree.js'\nimport { isFailedStatus } from '../../live-query-primitives.js'\nimport { reducePublicKeys } from './public-key-reduction.js'\nimport { CollectionSubscriber } from './collection-subscriber.js'\nimport { getCollectionBuilder } from './collection-registry.js'\nimport { LIVE_QUERY_INTERNAL } from './internal.js'\nimport { scheduleQueryGraphRun } from './graph-scheduler.js'\nimport { hasPendingJoinedWork as hasPendingJoinedSourceWork } from './subset-demand-controller.js'\nimport {\n buildQueryFromConfig,\n extractCollectionFromSource,\n extractCollectionSources,\n extractCollectionsFromQuery,\n sourcePermitsInitialReadiness,\n} from './utils.js'\nimport type { LiveQueryInternalUtils } from './internal.js'\nimport type { IncludesRuntime } from './includes-runtime.js'\nimport type { BucketFacadeAdapter } from './bucket-facade-adapter.js'\nimport type {\n ValueResolver,\n materializeCompilation,\n} from './materialized-pipeline.js'\nimport type { WindowOptions } from '../compiler/index.js'\nimport type { SchedulerContextId } from '../../scheduler.js'\nimport type { CollectionSubscription } from '../../collection/subscription.js'\nimport type { RootStreamBuilder } from '@tanstack/db-ivm'\nimport type { OrderByOptimizationInfo } from '../compiler/order-by.js'\nimport type { Collection } from '../../collection/index.js'\nimport type { HealthSource } from '../../collection/health-tree.js'\nimport type {\n CollectionConfigSingleRowOption,\n CollectionDependent,\n KeyedStream,\n ResultStream,\n StringCollationConfig,\n SyncConfig,\n UtilsRecord,\n} from '../../types.js'\nimport type { Context, GetResult } from '../builder/types.js'\nimport type { BasicExpression, QueryIR } from '../ir.js'\nimport type { LazyCollectionCallbacks } from '../compiler/joins.js'\nimport type { Deferred } from '../../deferred.js'\nimport type {\n Changes,\n FullSyncState,\n LiveQueryCollectionConfig,\n SyncState,\n} from './types.js'\nimport type { AllCollectionEvents } from '../../collection/events.js'\n\nexport type LiveQueryCollectionUtils = UtilsRecord & {\n /** Most recent subset-load failure observed by this live query. */\n readonly lastSubsetError: unknown | undefined\n /**\n * Sets the offset and limit of the query's window, its ordered view. A\n * windowed query has an `orderBy`. A `findOne` keeps its compiled limit (1,\n * or 0 for `.limit(0).findOne()`); an ordered `findOne` has a movable window,\n * and an unordered one is a fixed one-row result that accepts only its\n * compiled limit at offset 0.\n *\n * Existing query-shape and reentrancy guards run before limit validation.\n *\n * @throws `SetWindowRequiresOrderByError` if the query is neither windowed\n * nor a `findOne`, or an unordered `findOne` would move its offset.\n * @throws `SetWindowFindOneLimitError` if a `findOne` would change its limit.\n * @throws `SetWindowReentrancyError` during synchronous graph or source work.\n * @throws RangeError if the supplied limit is negative and those guards pass.\n * @returns `true` if no subset loading was triggered, or `Promise<void>` that resolves when the subset has been loaded\n */\n setWindow: (options: WindowOptions) => true | Promise<void>\n /**\n * Gets the current window (offset and limit) for an ordered query.\n *\n * @returns The current window settings, or `undefined` if the query is not windowed\n */\n getWindow: () => { offset: number; limit: number } | undefined\n [LIVE_QUERY_INTERNAL]: LiveQueryInternalUtils\n}\n\n// Global counter for auto-generated collection IDs\nlet liveQueryCollectionCounter = 0\n\ntype SyncMethods<TResult extends object> = Parameters<\n SyncConfig<TResult>[`sync`]\n>[0]\n\nexport class CollectionConfigBuilder<\n TContext extends Context,\n TResult extends object = GetResult<TContext>,\n> {\n private readonly id: string\n readonly query: QueryIR\n private readonly collections: Record<string, Collection<any, any, any>>\n private readonly collectionSources: ReturnType<\n typeof extractCollectionSources\n >\n\n // WeakMap to store the keys of the results\n // so that we can retrieve them in the getKey function\n private readonly resultKeys = new WeakMap<object, unknown>()\n\n // WeakMap to store the orderBy index for each result\n private readonly orderByIndices = new WeakMap<object, string>()\n\n private readonly compare?: (val1: TResult, val2: TResult) => number\n private readonly compareOptions: StringCollationConfig\n readonly queryCompareOptions: StringCollationConfig\n\n private isGraphRunning = false\n private graphInputRevision = 0\n\n // Current sync run state (set when sync starts, cleared when it stops)\n // Public for testing purposes (CollectionConfigBuilder is internal, not public API)\n public currentSyncConfig:\n Parameters<SyncConfig<TResult>[`sync`]>[0] | undefined\n public currentSyncState: FullSyncState | undefined\n\n // Error state tracking\n private fatalQueryError = false\n private lastSubsetError: unknown | undefined\n // The query's own reload: its new run publishes nothing until its graph\n // result is complete (law 9), then commits that result as the snapshot\n // that replaces the kept rows and completes the reload.\n private reloadSnapshotPending = false\n\n // Reference to the live query collection for error state transitions\n public liveQueryCollection?: Collection<TResult, any, any>\n private dependentEntry: CollectionDependent | undefined\n\n /**\n * Reload each source with an error anywhere in its tree, then this query if\n * its own node shows an error. A nested live query passes the reload down the\n * same way. A source's reload keeps this query's status until it commits.\n * A query that is not running starts once its sources reloaded, as any\n * Collection's reload starts one; `query` is the live-query Collection,\n * which a query that never started has not given this builder yet.\n */\n async reload(\n query: Collection<any, any, any> | undefined = this.liveQueryCollection,\n ): Promise<void> {\n // A crashed query rejects without touching its sources.\n if (query?.status === `crashed`) return query._sync.reload()\n const failed = this.collectionSources\n .map(({ collection }) => collection)\n .filter(\n (collection, index, all) =>\n all.indexOf(collection) === index &&\n findProblems(collection.health).some((node) => node.error !== null),\n )\n // Only a query that was not running starts: a cleanup that ends it during\n // the reload cancels the reload, as the app ended it.\n const ended = query?.status === `idle` || query?.status === `cleaned-up`\n await Promise.all(failed.map((collection) => collection.reload()))\n // Its preload is what lets a live query start its sources.\n if (ended) return query.preload()\n // The query reloads itself after its sources when its own node shows an\n // error (a failed first load or a request error); a reload of it already\n // in flight settles with that run.\n if (query?._lifecycle.problems.error || query?._lifecycle.reloading)\n await query._sync.reload()\n }\n\n /** This live query as its sources' `subscribers` list it. */\n dependent(): CollectionDependent | undefined {\n const collection = this.liveQueryCollection\n if (!collection) return undefined\n return (this.dependentEntry ??= {\n kind: `live-query`,\n collection,\n get active() {\n return collection.subscribers.length > 0\n },\n end: () => collection.cleanup({ dependents: true }),\n })\n }\n\n /**\n * Whether this live-query Collection had a subscriber or a preload in its\n * current sync run. Until then it reads its source Collections without\n * starting provider work.\n */\n hasSubscriberOrPreload(): boolean {\n // A builder driven without its Collection, as its own tests do, has no\n // subscriber state to defer on.\n return this.liveQueryCollection?._hasSubscriberOrPreload() ?? true\n }\n\n private windowFn: ((options: WindowOptions) => void) | undefined\n private readonly initialWindow: WindowOptions | undefined\n private currentWindow: WindowOptions | undefined\n private settledWindow: WindowOptions | undefined\n private activeWindowOperation:\n { generation: number; failed: boolean; error?: unknown } | undefined\n\n private maybeRunGraphFn: (() => void) | undefined\n private loadMoreFn: (() => void) | undefined\n private readonly builderDependencies = new Set<\n CollectionConfigBuilder<any, any>\n >()\n\n private graphCache: D2 | undefined\n private inputsCache: Record<string, RootStreamBuilder<unknown>> | undefined\n private pipelineCache: ResultStream | undefined\n public sourceWhereClausesCache:\n Map<string, BasicExpression<boolean>> | undefined\n private valueResolverCache: ValueResolver | undefined\n private includesRuntimeCache: IncludesRuntime | undefined\n private bucketFacadesCache:\n ReturnType<typeof materializeCompilation>[`facades`] | undefined\n private readonly includeSourceIds = new Set<string>()\n\n // Map of opaque source ID to subscription\n readonly subscriptions = createSourceRecord<CollectionSubscription>()\n // Map of opaque source ID to demand callbacks for that lazy source\n lazySourcesCallbacks = createSourceRecord<LazyCollectionCallbacks>()\n // Set of opaque source IDs that are lazy (don't load initial state)\n readonly lazySources = new Set<string>()\n private readonly activeDemands = new Map<\n string,\n {\n generation: number\n settled: boolean\n participant?: Deferred<void>\n }\n >()\n private demandGeneration = 0\n private readonly pendingOrderedLoads = new Set<Promise<unknown>>()\n private orderedLoadFailed = false\n // Source replay cannot settle a failed imperative window operation.\n private windowFailed = false\n private syncRunGeneration = 0\n private windowOperationGeneration = 0\n // Counts setWindow calls, deferred or not. A separate count from window\n // operations, so a deferred call does not drop the settlement of a move\n // that already applied.\n private windowRequestGeneration = 0\n // The newest call's settlement. An older call that a newer one superseded\n // resolves only once it settles, so an awaited call reflects the window\n // that won. A superseded call that fails still rejects with its own error.\n private latestWindowRequest: Promise<void> | undefined\n // Map of lexical source IDs to optimizable ORDER BY state\n optimizableOrderByCollections = createSourceRecord<OrderByOptimizationInfo>()\n\n constructor(\n private readonly config: LiveQueryCollectionConfig<TContext, TResult>,\n ) {\n // Generate a unique ID if not provided\n this.id = config.id || `live-query-${++liveQueryCollectionCounter}`\n\n this.query = buildQueryFromConfig({\n query: config.query,\n requireObjectResult: true,\n })\n this.initialWindow =\n this.query.orderBy?.length || this.query.singleResult\n ? {\n offset: this.query.offset ?? 0,\n limit: this.query.singleResult\n ? Math.min(this.query.limit ?? 1, 1)\n : (this.query.limit ?? Infinity),\n }\n : undefined\n this.settledWindow = this.initialWindow\n this.collections = extractCollectionsFromQuery(this.query)\n this.collectionSources = extractCollectionSources(this.query)\n collectSourceRefs(this.query, this.includeSourceIds)\n\n // Create compare function for ordering if the query has orderBy\n if (this.query.orderBy && this.query.orderBy.length > 0) {\n this.compare = createOrderByComparator<TResult>(this.orderByIndices)\n }\n\n // Query ordering inherits from the leading source. The live-query Collection\n // may independently override the collation it exposes to downstream queries.\n this.queryCompareOptions = extractCollectionFromSource(\n this.query,\n ).compareOptions\n this.compareOptions =\n this.config.defaultStringCollation ?? this.queryCompareOptions\n\n // Compile the base pipeline once initially\n // This is done to ensure that any errors are thrown immediately and synchronously\n this.compileBasePipeline()\n }\n\n /** Direct lexical source Collections, including joins, unions, and includes. */\n getSourceCollections(): ReadonlyArray<Collection<any, any, any>> {\n return this.collectionSources.map(({ collection }) => collection)\n }\n\n /**\n * Recursively checks if a query or any of its subqueries contains joins\n */\n private hasJoins(query: QueryIR): boolean {\n // Check if this query has joins\n if (query.join && query.join.length > 0) {\n return true\n }\n\n // Recursively check subqueries in the from clause\n if (query.from.type === `queryRef`) {\n if (this.hasJoins(query.from.query)) {\n return true\n }\n } else if (query.from.type === `unionFrom`) {\n for (const source of query.from.sources) {\n if (source.type === `queryRef` && this.hasJoins(source.query)) {\n return true\n }\n }\n } else if (query.from.type === `unionAll`) {\n for (const branch of query.from.queries) {\n if (this.hasJoins(branch)) {\n return true\n }\n }\n }\n\n return false\n }\n\n getConfig(): CollectionConfigSingleRowOption<TResult> & {\n utils: LiveQueryCollectionUtils\n } {\n const builder = this\n return {\n id: this.id,\n getKey:\n this.config.getKey ||\n ((item: any) =>\n (this.resultKeys.get(item) ?? item.$key) as string | number),\n sync: this.getSyncConfig(),\n compare: this.compare,\n defaultStringCollation: this.compareOptions,\n gcTime: this.config.gcTime ?? 5000, // 5 seconds by default for live queries\n autoIndex: this.config.autoIndex,\n defaultIndexType: this.config.defaultIndexType,\n schema: this.config.schema,\n onInsert: this.config.onInsert,\n onUpdate: this.config.onUpdate,\n onDelete: this.config.onDelete,\n startSync: this.config.startSync,\n singleResult: this.query.singleResult,\n utils: {\n get lastSubsetError() {\n return builder.lastSubsetError\n },\n setWindow: this.setWindow.bind(this),\n getWindow: this.getWindow.bind(this),\n [LIVE_QUERY_INTERNAL]: {\n getBuilder: () => this,\n hasCustomGetKey: !!this.config.getKey,\n hasJoins: this.hasJoins(this.query),\n hasDistinct: !!this.query.distinct,\n },\n },\n }\n }\n\n setWindow(options: WindowOptions): true | Promise<void> {\n const windowFn = this.windowFn\n if (!windowFn) {\n throw new SetWindowRequiresOrderByError()\n }\n // A findOne keeps its compiled limit, and only an ordered one moves.\n if (this.query.singleResult) {\n if (!this.query.orderBy?.length && (options.offset ?? 0) !== 0)\n throw new SetWindowRequiresOrderByError()\n if (\n (options.limit ?? this.initialWindow!.limit) !==\n this.initialWindow!.limit\n )\n throw new SetWindowFindOneLimitError()\n }\n if (\n this.activeWindowOperation ||\n this.isGraphRunning ||\n Object.values(this.optimizableOrderByCollections).some((info) =>\n info.isRequesting?.(),\n )\n ) {\n throw new SetWindowReentrancyError()\n }\n\n validateLimit(options.limit)\n\n // Keep caller-owned objects out of the long-lived query state. A caller may\n // reuse and mutate its options object after this operation settles.\n const baseWindow =\n this.currentWindow ?? this.settledWindow ?? this.initialWindow\n const requestedWindow: WindowOptions = {\n offset: options.offset ?? baseWindow?.offset,\n limit: options.limit ?? baseWindow?.limit,\n }\n const request = ++this.windowRequestGeneration\n const sourceRecovery = this.pendingSourceRecovery()\n if (sourceRecovery) {\n const syncRuns = this.syncRuns()\n const resume = async (): Promise<void> => {\n // Wait for every replay that holds publication, including one a\n // newer truncate starts meanwhile. A replay that a newer truncate or\n // a retired demand discards rejects its completion with an\n // AbortError, but it did not fail. Cleanup and a reload end the sync\n // run the move waits in, and the move rejects with that error.\n for (\n let recovery: Promise<void> | undefined = sourceRecovery;\n recovery;\n recovery = this.pendingSourceRecovery()\n ) {\n try {\n await recovery\n } catch (error) {\n if (\n !(error instanceof LoadSubsetOperationAbortedError) ||\n syncRuns !== this.syncRuns()\n )\n throw error\n }\n }\n // A newer call wins, even if this deferred one resumes after it.\n if (request !== this.windowRequestGeneration) {\n await this.latestWindowRequest\n return\n }\n // A failed replay rejects the call. Otherwise it applies the window.\n const settlement = this.setWindow(requestedWindow)\n // The resumed call settles on behalf of this one.\n this.latestWindowRequest = deferred\n if (settlement !== true) await settlement\n }\n const deferred = resume()\n return (this.latestWindowRequest = deferred)\n }\n if (this.hasFailedSourceRecovery()) {\n return (this.latestWindowRequest = Promise.reject(\n this.lastSubsetError ??\n new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Source recovery failed`\n : codedMessage(147),\n ),\n ))\n }\n const windowOperationGeneration = ++this.windowOperationGeneration\n const loadOperation =\n this.liveQueryCollection?._sync.beginLoadSubsetOperation()\n for (const info of Object.values(this.optimizableOrderByCollections)) {\n for (const sourceId of info.joinedFilterSourceIds ?? []) {\n for (const plan of this.lazySourcesCallbacks[sourceId]?.plans ?? []) {\n const participant = this.activeDemands.get(plan.id)?.participant\n if (participant?.isPending()) {\n this.trackSubsetLoadOperationPromise(participant.promise)\n }\n }\n }\n }\n const operation: {\n generation: number\n failed: boolean\n error?: unknown\n } = { generation: windowOperationGeneration, failed: false }\n this.activeWindowOperation = operation\n this.windowFailed = false\n if (this.pendingOrderedLoads.size === 0) this.orderedLoadFailed = false\n try {\n // The window and all source work it causes form one synchronous\n // publication. This makes operation tracking see requests scheduled by\n // the graph rather than declaring the window settled too early.\n this.currentWindow = requestedWindow\n withPublicationContext(() => {\n windowFn(requestedWindow)\n this.maybeRunGraphFn?.()\n })\n if (operation.failed) throw operation.error\n } catch (error) {\n if (windowOperationGeneration === this.windowOperationGeneration) {\n this.windowFailed = true\n this.currentWindow = this.settledWindow\n }\n loadOperation?.cancel()\n throw error\n } finally {\n this.activeWindowOperation = undefined\n }\n\n const settlement = loadOperation?.wait() ?? true\n if (settlement === true) {\n this.settledWindow = requestedWindow\n this.latestWindowRequest = undefined\n return true\n }\n return (this.latestWindowRequest = settlement.then(\n () => {\n if (windowOperationGeneration === this.windowOperationGeneration) {\n this.settledWindow = requestedWindow\n }\n return request === this.windowRequestGeneration\n ? undefined\n : this.latestWindowRequest\n },\n (error) => {\n if (windowOperationGeneration === this.windowOperationGeneration) {\n this.windowFailed = true\n this.currentWindow = this.settledWindow\n }\n throw error\n },\n ))\n }\n\n getWindow(): { offset: number; limit: number } | undefined {\n // A windowed query or an ordered findOne returns its window. An unordered\n // findOne returns its fixed result: offset 0 and its compiled limit.\n const window = this.settledWindow ?? this.initialWindow\n if (!this.windowFn || !window) {\n return undefined\n }\n return {\n offset: window.offset ?? 0,\n limit: window.limit ?? 0,\n }\n }\n\n isLazySource(sourceId: string): boolean {\n return this.lazySources.has(sourceId)\n }\n\n beginDemand(planId: string, pending = false): number {\n const generation = ++this.demandGeneration\n const previous = this.activeDemands.get(planId)\n const participant = pending ? createDeferred<void>() : undefined\n if (participant) {\n void participant.promise.catch(() => {})\n this.trackSubsetLoadOperationPromise(participant.promise)\n }\n this.activeDemands.set(planId, {\n generation,\n settled: false,\n participant,\n })\n previous?.participant?.resolve()\n return generation\n }\n\n /** The source aliases of this query, in query order, for its health tree. */\n healthSources(): ReadonlyArray<HealthSource> {\n return this.collectionSources.map(({ sourceId, alias, collection }) => ({\n id: sourceId,\n alias,\n collection,\n ...(this.includeSourceIds.has(sourceId)\n ? { kind: `include` as const }\n : {}),\n }))\n }\n\n settleDemand(planId: string, generation: number): void {\n const demand = this.activeDemands.get(planId)\n if (!demand || demand.generation !== generation || demand.settled) return\n demand.settled = true\n try {\n this.maybeRunGraphFn?.()\n demand.participant?.resolve()\n } catch (error) {\n demand.participant?.reject(error)\n throw error\n }\n }\n\n hasPendingJoinedWork(joinedSourceId: string): boolean {\n return hasPendingJoinedSourceWork(\n joinedSourceId,\n this.lazySourcesCallbacks,\n this.subscriptions,\n (planId) => this.activeDemands.get(planId)?.settled === false,\n )\n }\n\n failDemand(\n subscription: CollectionSubscription,\n collection: Collection,\n planId: string,\n generation: number,\n error: unknown,\n ): void {\n const demand = this.activeDemands.get(planId)\n if (!demand || demand.generation !== generation) return\n const normalized = this.recordSubsetError(error)\n demand.participant?.reject(normalized)\n if (this.liveQueryCollection?._lifecycle.status === `ready`) {\n // The failure settles the demand: the request errors of its keys show\n // it, and ordered work must not wait for a load that already ended.\n // Output held for this demand publishes now, unless a replay of this\n // source still holds publication: the failure then holds this\n // subscription's publication too. Neither sibling settlement nor\n // retirement of its failed demand may publish without these rows.\n demand.settled = true\n if (\n this.collectionSources.some(\n (source) =>\n source.collection === collection &&\n this.subscriptions[source.sourceId]?.hasPendingTruncateReplacement,\n )\n )\n subscription.failReplacement(normalized)\n this.maybeRunGraphFn?.()\n return\n }\n this.failQuery(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Subset demand '${planId}' failed: ${normalized.message}`\n : codedMessage(228, { planId, cause: normalized.message }),\n normalized,\n )\n }\n\n recordSubsetError(error: unknown, fatalBeforeReady = false): Error {\n const normalized = normalizeError(error)\n this.lastSubsetError = normalized\n if (this.activeWindowOperation) {\n this.activeWindowOperation.failed = true\n this.activeWindowOperation.error = normalized\n // A synchronous adapter failure can arrive before it returns a promise\n // for the ordered-load tracker. Keep any private graph changes hidden.\n this.orderedLoadFailed = true\n }\n if (fatalBeforeReady) {\n this.failQuery(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Initial subset load failed: ${normalized.message}`\n : codedMessage(229, { cause: normalized.message }),\n normalized,\n )\n }\n return normalized\n }\n\n trackSubsetLoadPromise(promise: Promise<unknown>): void {\n this.liveQueryCollection!._sync.trackLoadPromise(promise)\n }\n\n trackSubsetLoadOperationPromise(promise: Promise<unknown>): void {\n this.liveQueryCollection!._sync.trackLoadSubsetOperationPromise(promise)\n }\n\n hasActiveWindowOperation(): boolean {\n return this.activeWindowOperation !== undefined\n }\n\n getActiveWindowOperationGeneration(): number | undefined {\n return this.activeWindowOperation?.generation\n }\n\n scheduleGraphRunIfSyncRunCurrent(syncRunGeneration: number): void {\n if (\n syncRunGeneration !== this.syncRunGeneration ||\n !this.currentSyncConfig ||\n !this.currentSyncState\n ) {\n return\n }\n this.scheduleGraphRun()\n }\n\n trackOrderedLoadPromise(\n promise: Promise<unknown>,\n holdPublication = false,\n ): void {\n // Hold the last complete public snapshot during an initial load or an\n // imperative window move. Source changes that arrive during the move join\n // its private graph state and publish with the completed replacement.\n if (\n !holdPublication &&\n !this.activeWindowOperation &&\n this.liveQueryCollection?._lifecycle.inFirstLoad !== true &&\n this.pendingOrderedLoads.size === 0\n ) {\n return\n }\n const syncRunGeneration = this.syncRunGeneration\n if (this.pendingOrderedLoads.size === 0) this.orderedLoadFailed = false\n this.pendingOrderedLoads.add(promise)\n const finish = (succeeded: boolean) => {\n // Admission precedes mutation: cleanup retires this sync run's participants.\n if (\n syncRunGeneration !== this.syncRunGeneration ||\n !this.pendingOrderedLoads.delete(promise)\n ) {\n return\n }\n if (!succeeded) this.orderedLoadFailed = true\n if (!this.orderedLoadFailed && this.pendingOrderedLoads.size === 0) {\n // The ordered chain already drove its source graph to quiescence.\n // Flush the retained result without invoking the source loaders again.\n this.scheduleGraphRun()\n }\n }\n void promise.then(\n () => finish(true),\n () => finish(false),\n )\n }\n\n retireDemand(planId: string): void {\n const demand = this.activeDemands.get(planId)\n this.activeDemands.delete(planId)\n demand?.participant?.resolve()\n }\n\n /** A root load of an eager source failed. */\n failRootLoad(sourceId: string, error: Error): void {\n this.reportFailedRequest(`root:${sourceId}`, [error])\n }\n\n /** A later root load of the source succeeded. */\n settleRootLoad(sourceId: string): void {\n this.clearFailedRequest(`root:${sourceId}`)\n }\n\n /** A source's truncate replay loaded the query's demand again. */\n settleReplayedRequests(sourceId: string): void {\n this.settleRootLoad(sourceId)\n this.clearFailedRequest(`replay:${sourceId}`)\n }\n\n /**\n * A source's truncate replay could not load the query's data again: each\n * of its failures, in failure order. Before the first ready the earliest\n * fails the query.\n */\n failReplay(sourceId: string, errors: Array<Error>): void {\n if (this.reportFailedRequest(`replay:${sourceId}`, errors)) return\n this.failQuery(errors[0]!.message, errors[0])\n }\n\n // After the first ready, a failed load is a request error on this query's\n // node. It clears when the failed request settles later or is released.\n reportFailedRequest(key: string, errors: Array<Error>): boolean {\n const lifecycle = this.liveQueryCollection?._lifecycle\n if (lifecycle?.status !== `ready`) return false\n lifecycle.reportRequestError(key, errors)\n return true\n }\n\n /** A request settled later, or the query no longer needs its data. */\n clearFailedRequest(key: string): void {\n this.liveQueryCollection?._lifecycle.clearRequestError(key)\n }\n\n /** This query's sync run and its sources' sync runs. */\n private syncRuns(): string {\n return [\n this.syncRunGeneration,\n ...this.collectionSources.map(({ collection }) =>\n collection._sync.getSyncRunGeneration(),\n ),\n ].join()\n }\n\n /** Replays of other subscriptions to a source's collection that still load. */\n siblingReplays(\n collection: Collection,\n sourceId: string,\n ): Promise<unknown> | undefined {\n const pending = this.collectionSources.flatMap((source) => {\n const subscription = this.subscriptions[source.sourceId]\n // A replay whose completion already settled cannot be waited on.\n return source.sourceId !== sourceId &&\n source.collection === collection &&\n subscription?.hasTruncateReplayWork &&\n subscription.pendingTruncateReplacement\n ? [subscription.pendingTruncateReplacement]\n : []\n })\n return pending.length > 0 ? Promise.allSettled(pending) : undefined\n }\n\n hasPendingSourceRecovery(): boolean {\n return Object.values(this.subscriptions).some(\n (subscription) => subscription.hasPendingTruncateReplacement,\n )\n }\n\n private pendingSourceRecovery(): Promise<void> | undefined {\n const pending = Object.values(this.subscriptions).flatMap((subscription) =>\n subscription.pendingTruncateReplacement\n ? [subscription.pendingTruncateReplacement]\n : [],\n )\n return pending.length > 0\n ? Promise.all(pending).then(() => undefined)\n : undefined\n }\n\n private hasFailedSourceRecovery(): boolean {\n return Object.values(this.subscriptions).some(\n (subscription) => subscription.hasFailedTruncateReplacement,\n )\n }\n\n getSyncRunGeneration(): number {\n return this.syncRunGeneration\n }\n\n advanceGraphInputRevision(): void {\n this.graphInputRevision++\n }\n\n getGraphInputRevision(): number {\n return this.graphInputRevision\n }\n\n // Every graph turn checks ordered demand after D2 reaches a checkpoint.\n // The source loader owns the fixed-point latches that prevent repeat requests.\n maybeRunGraph() {\n if (this.isGraphRunning) {\n // no nested runs of the graph\n // which is possible if a loader synchronously sends more source rows\n return\n }\n\n // Should only be called when sync is active\n if (!this.currentSyncConfig || !this.currentSyncState) {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `maybeRunGraph called without active sync run. This should not happen.`\n : codedMessage(148),\n )\n }\n\n this.isGraphRunning = true\n\n try {\n const syncRunGeneration = this.syncRunGeneration\n const config = this.currentSyncConfig\n const { begin, commit } = config\n const syncState = this.currentSyncState\n const isCurrentSyncRun = () =>\n syncRunGeneration === this.syncRunGeneration &&\n this.currentSyncConfig === config &&\n this.currentSyncState === syncState\n\n // Don't run if the live query is in an error state\n if (this.fatalQueryError) {\n return\n }\n\n // Always run the graph if subscribed (eager execution)\n if (syncState.subscribedToAllCollections) {\n let checkedLoaders = false\n while (syncState.graph.pendingWork() || !checkedLoaders) {\n if (syncState.graph.pendingWork()) {\n try {\n syncState.graph.run()\n } catch (error) {\n // A first load that already failed in this run reported its\n // error.\n if (\n isCurrentSyncRun() &&\n this.liveQueryCollection?._lifecycle.stoppedThisRun !== true\n ) {\n this.crashQuery(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Live query graph failed`\n : codedMessage(212),\n error,\n )\n }\n throw error\n }\n if (!isCurrentSyncRun()) return\n }\n // A synchronous loader can write while this graph run is active.\n // Process that input before publishing, even if this turn began empty.\n this.loadMoreFn?.()\n if (!isCurrentSyncRun()) return\n checkedLoaders = true\n }\n\n // Publish only after every operator has reached quiescence. A source\n // change can reach sibling materializations in different graph steps;\n // flushing between those steps would expose a mixed root snapshot.\n syncState.flushPendingChanges?.()\n if (!isCurrentSyncRun()) return\n\n // On the initial run, we may need to do an empty commit to ensure that\n // the collection is initialized. A reload's run commits its snapshot\n // instead.\n if (syncState.messagesCount === 0 && !this.reloadSnapshotPending) {\n begin()\n commit()\n }\n\n // After graph processing completes, check if we should mark ready.\n // This is the canonical place to transition to ready state because:\n // 1. All data has been processed through the graph\n // 2. All source collections have had a chance to send their initial data\n // This prevents marking ready before data is processed (fixes isReady=true with empty data)\n this.updateLiveQueryStatus(config)\n }\n } finally {\n this.isGraphRunning = false\n }\n }\n\n /**\n * Schedules a graph run with the transaction-scoped scheduler.\n * Ensures each builder runs at most once per transaction, with automatic dependency tracking\n * to run parent queries before child queries. Outside a transaction, runs immediately.\n *\n * Multiple calls during a transaction are coalesced into a single execution.\n * Dependencies are discovered from subscribed live queries.\n *\n * Uses the current sync run's config and syncState from instance properties.\n *\n * @param options - Optional scheduling configuration\n * @param options.contextId - Transaction ID to group work; defaults to active transaction\n */\n scheduleGraphRun(options?: { contextId?: SchedulerContextId }) {\n if (!this.currentSyncConfig || !this.currentSyncState) {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `scheduleGraphRun called without active sync run. This should not happen.`\n : codedMessage(149),\n )\n }\n\n const syncRunGeneration = this.syncRunGeneration\n scheduleQueryGraphRun(\n this,\n this.builderDependencies,\n () => {\n if (\n syncRunGeneration === this.syncRunGeneration &&\n this.currentSyncConfig &&\n this.currentSyncState\n ) {\n this.maybeRunGraph()\n }\n },\n options?.contextId,\n )\n }\n\n private getSyncConfig(): SyncConfig<TResult> {\n return {\n rowUpdateMode: `full`,\n sync: this.syncFn.bind(this),\n }\n }\n\n private syncFn(config: SyncMethods<TResult>) {\n const syncRunGeneration = ++this.syncRunGeneration\n // Store reference to the live query collection for error state transitions\n this.liveQueryCollection = config.collection\n this.reloadSnapshotPending = config.collection._lifecycle.reloading\n // Reset error state from any previous sync run so a restarted sync can become ready again.\n this.fatalQueryError = false\n this.lastSubsetError = undefined\n // Store config and syncState as instance properties for the duration of this sync run\n this.currentSyncConfig = config\n\n const syncState: SyncState = {\n messagesCount: 0,\n subscribedToAllCollections: false,\n unsubscribeCallbacks: new Set<() => void>(),\n }\n\n let tornDown = false\n const teardown = () => {\n if (tornDown) return\n tornDown = true\n if (this.syncRunGeneration === syncRunGeneration) {\n this.syncRunGeneration++\n }\n\n // Release every source in one attempt; the first failure wins after the\n // peers finish. Each subscription release is itself one-shot, so the\n // Collection's cleanup retry has nothing left to repeat here.\n try {\n runAllCallbacks(syncState.unsubscribeCallbacks)\n } finally {\n syncState.unsubscribeCallbacks.clear()\n this.clearSyncRunState()\n }\n }\n\n try {\n // Extend the pipeline such that it applies the incoming changes to the collection\n const fullSyncState = this.extendPipelineWithChangeProcessing(\n config,\n syncState,\n )\n this.currentSyncState = fullSyncState\n\n // Listen for loadingSubset changes on the live query collection BEFORE subscribing.\n // This ensures we don't miss the event if subset loading completes synchronously.\n // When isLoadingSubset becomes false, we may need to mark the collection as ready\n // (if all source collections are already ready but we were waiting for subset load to complete)\n const loadingSubsetUnsubscribe = config.collection.on(\n `loadingSubset:change`,\n (event) => {\n if (!event.isLoadingSubset) {\n // Subset loading finished, check if we can now mark ready\n this.updateLiveQueryStatus(config)\n if (this.hasPendingSourceRecovery()) this.maybeRunGraphFn?.()\n }\n },\n )\n syncState.unsubscribeCallbacks.add(loadingSubsetUnsubscribe)\n\n this.loadMoreFn = this.subscribeToAllCollections(config, fullSyncState)\n\n this.maybeRunGraphFn = () => this.scheduleGraphRun()\n\n this.scheduleGraphRun()\n } catch (error) {\n try {\n teardown()\n } catch {\n // Preserve the setup failure. It is the error the caller can act on.\n }\n throw error\n }\n\n return teardown\n }\n\n private clearSyncRunState(): void {\n // Late window settlement belongs to the discarded graph, not its restart.\n this.windowOperationGeneration++\n // Clear current sync run state\n this.currentSyncConfig = undefined\n this.currentSyncState = undefined\n this.maybeRunGraphFn = undefined\n this.loadMoreFn = undefined\n // The query's own reload retries its data, not the window the app chose:\n // the new run starts from the settled window, and a pending move ends\n // with the retired run. Cleanup discards the window, also during the\n // reload: it tears the run down before it ends the reload.\n const lifecycle = this.liveQueryCollection?._lifecycle\n if (lifecycle?.reloading && !lifecycle.hasStartedCleanup())\n this.currentWindow = this.settledWindow\n else {\n this.currentWindow = undefined\n this.settledWindow = this.initialWindow\n }\n this.fatalQueryError = false\n this.reloadSnapshotPending = false\n\n // Reset caches so a fresh graph/pipeline is compiled on next start\n // This avoids reusing a finalized D2 graph across GC restarts\n this.graphCache = undefined\n this.inputsCache = undefined\n this.pipelineCache = undefined\n this.sourceWhereClausesCache = undefined\n this.valueResolverCache = undefined\n this.bucketFacadesCache = undefined\n this.includesRuntimeCache = undefined\n\n // Reset lazy source alias state\n this.lazySources.clear()\n for (const demand of this.activeDemands.values()) {\n demand.participant?.reject(new LoadSubsetOperationAbortedError())\n }\n this.activeDemands.clear()\n this.pendingOrderedLoads.clear()\n this.orderedLoadFailed = false\n this.windowFailed = false\n this.optimizableOrderByCollections = createSourceRecord()\n this.lazySourcesCallbacks = createSourceRecord()\n\n // Clear subscription references to prevent memory leaks\n // Note: Individual subscriptions are already unsubscribed via unsubscribeCallbacks\n Object.keys(this.subscriptions).forEach(\n (key) => delete this.subscriptions[key],\n )\n }\n\n /**\n * Compiles the query pipeline with all declared aliases.\n */\n private compileBasePipeline() {\n this.graphCache = new D2()\n const inputs = createSourceRecord<RootStreamBuilder<unknown>>()\n for (const source of this.collectionSources) {\n inputs[source.sourceId] = this.graphCache.newInput<any>()\n }\n this.inputsCache = inputs\n\n const compilation = compileCollectionQuery(\n this.query,\n this.inputsCache as Record<string, KeyedStream>,\n this.collections,\n this.subscriptions,\n this.lazySourcesCallbacks,\n this.lazySources,\n this.optimizableOrderByCollections,\n (windowFn: (options: WindowOptions) => void) => {\n this.windowFn = windowFn\n // `setWindow` mutates the compiled top-K operator, which is replaced\n // whenever a cleaned-up live query compiles a fresh pipeline. Keep the\n // desired window on the builder and replay it into each new operator.\n if (this.currentWindow) {\n windowFn(this.currentWindow)\n }\n },\n )\n\n // Includes bring the materializer. A joined query with a custom key\n // reduces its public keys without it.\n const includesRuntime = compilation.includes?.[0]?.runtime\n const getKey = this.config.getKey\n const materialized = includesRuntime\n ? includesRuntime.materializeCompilation(compilation, getKey)\n : getKey && this.hasJoins(this.query)\n ? reducePublicKeys(compilation, getKey)\n : { pipeline: compilation.pipeline, facades: undefined }\n this.pipelineCache = materialized.pipeline\n this.sourceWhereClausesCache = compilation.sourceWhereClauses\n this.valueResolverCache =\n `resolve` in materialized ? materialized.resolve : undefined\n this.bucketFacadesCache = materialized.facades\n this.includesRuntimeCache = includesRuntime\n\n const missingSources = this.collectionSources\n .map((source) => source.sourceId)\n .filter((sourceId) => !Object.hasOwn(this.inputsCache!, sourceId))\n if (missingSources.length > 0) {\n throw new MissingAliasInputsError(missingSources)\n }\n }\n\n private maybeCompileBasePipeline() {\n if (!this.graphCache || !this.inputsCache || !this.pipelineCache) {\n this.compileBasePipeline()\n }\n return {\n graph: this.graphCache!,\n inputs: this.inputsCache!,\n pipeline: this.pipelineCache!,\n }\n }\n\n private extendPipelineWithChangeProcessing(\n config: SyncMethods<TResult>,\n syncState: SyncState,\n ): FullSyncState {\n const { begin, commit } = config\n const { graph, inputs, pipeline } = this.maybeCompileBasePipeline()\n\n // Accumulator for changes across all output callbacks within a single graph run.\n // This allows us to batch all changes from intermediate join states into a single\n // transaction, avoiding duplicate key errors when joins produce multiple outputs\n // for the same key (e.g., first output with null, then output with joined data).\n let pendingChanges: Map<unknown, Changes<TResult>> = new Map()\n\n pipeline.pipe(\n output((data) => {\n const messages = data.getInner()\n syncState.messagesCount += messages.length\n\n // Accumulate changes from this output callback into the pending changes map.\n // Changes for the same key are merged (inserts/deletes are added together).\n messages.reduce(accumulateChanges<TResult>, pendingChanges)\n }),\n )\n\n // A query without includes publishes its rows directly and pays for no\n // facade state. With includes, the adapter also strips private route\n // state at publication, even when every include is inline. A joined\n // query with a custom key is materialized for key reduction only.\n const facadeCompilations = this.bucketFacadesCache\n const includesRuntime = this.includesRuntimeCache\n const bucketFacades =\n facadeCompilations && includesRuntime\n ? includesRuntime.createBucketFacades(\n this.id,\n facadeCompilations,\n (count) => {\n syncState.messagesCount += count\n },\n this.valueResolverCache!,\n )\n : undefined\n if (bucketFacades) {\n syncState.unsubscribeCallbacks.add(() => bucketFacades.cleanup())\n }\n\n // Flush pending changes and reset the accumulator.\n // Called at the end of each graph run to commit all accumulated changes.\n syncState.flushPendingChanges = () => {\n const hasParentChanges = pendingChanges.size > 0\n const hasChildChanges = bucketFacades?.hasPendingChanges() ?? false\n // A reload's run holds its result until it is complete, then commits\n // it as a snapshot, also an empty one.\n const snapshot = this.reloadSnapshotPending\n if (snapshot && !this.isResultComplete()) return\n const writesRoot = hasParentChanges || snapshot\n\n if (!writesRoot && !hasChildChanges) {\n return\n }\n\n if (\n this.windowFailed ||\n this.orderedLoadFailed ||\n this.hasPendingSourceRecovery() ||\n this.pendingOrderedLoads.size > 0 ||\n Object.values(this.optimizableOrderByCollections).some((info) =>\n info.joinedFilterSourceIds?.some((sourceId) =>\n this.hasPendingJoinedWork(sourceId),\n ),\n )\n ) {\n return\n }\n\n // A key has at most one result row, so one flush can add or remove at\n // most one. Check before any state changes: anything else means an\n // upstream operator broke multiplicity.\n for (const [key, { inserts, deletes }] of pendingChanges) {\n if (Math.abs(inserts - deletes) > 1) {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Live query result key ${String(key)} changed by ${inserts - deletes} rows in one flush; a key has at most one result row.`\n : codedMessage(150, { key, change: inserts - deletes }),\n )\n }\n }\n\n let facadePublication:\n ReturnType<BucketFacadeAdapter[`flush`]> | undefined\n let rootPublication:\n ReturnType<Collection[`_deferPublication`]> | undefined\n try {\n facadePublication = bucketFacades?.flush()\n rootPublication = writesRoot\n ? config.collection._deferPublication()\n : undefined\n const changesToApply: Map<unknown, Changes<TResult>> = bucketFacades\n ? new Map(\n [...pendingChanges].map(([key, changes]) => {\n const resolved: Changes<TResult> = {\n ...changes,\n value: bucketFacades.resolve(changes.value),\n }\n if (changes.previousValue !== undefined) {\n resolved.previousValue = bucketFacades.resolve(\n changes.previousValue,\n )\n }\n return [key, resolved]\n }),\n )\n : pendingChanges\n // New facades are not reachable until their root row is installed, so\n // make them ready first. A facade failure then leaves the root intact,\n // and the root commit is the final state change before publication.\n facadePublication?.prepare()\n if (writesRoot) {\n begin(snapshot ? { snapshot } : undefined)\n let lookup: ((key: string | number) => boolean) | undefined\n const hasSyncedKey = (key: string | number) => {\n // A snapshot replaces every row, so no earlier row exists for\n // the batch it holds.\n if (snapshot) return false\n lookup ??= config.collection._state.createSyncedKeyLookup()\n return lookup(key)\n }\n changesToApply.forEach(\n this.applyChanges.bind(this, config, hasSyncedKey),\n )\n if (hasOrderOnlyMove(changesToApply)) {\n markLayoutChange(config.collection)\n }\n commit()\n this.reloadSnapshotPending = false\n }\n } catch (error) {\n rootPublication?.discard()\n facadePublication?.rollback()\n throw error\n }\n pendingChanges = new Map()\n\n let publicationError: unknown\n for (const publish of [\n rootPublication?.publish,\n facadePublication?.publish,\n ]) {\n if (!publish) continue\n try {\n publish()\n } catch (error) {\n publicationError ??= error\n }\n }\n if (publicationError !== undefined) throw publicationError\n }\n graph.finalize()\n\n // Extend the sync state with the graph, inputs, and pipeline\n syncState.graph = graph\n syncState.inputs = inputs\n syncState.pipeline = pipeline\n\n return syncState as FullSyncState\n }\n\n private applyChanges(\n config: SyncMethods<TResult>,\n hasSyncedKey: (key: string | number) => boolean,\n changes: {\n deletes: number\n inserts: number\n value: TResult\n orderByIndex: string | undefined\n },\n key: unknown,\n ) {\n const { write, collection } = config\n const { deletes, inserts, value, orderByIndex } = changes\n // Store the key of the result so that we can retrieve it in the\n // getKey function\n this.resultKeys.set(value, key)\n\n // Store the orderBy index if it exists\n if (orderByIndex !== undefined) {\n this.orderByIndices.set(value, orderByIndex)\n }\n\n // Simple singular insert.\n if (inserts && deletes === 0) {\n write({\n value,\n type: `insert`,\n })\n } else if (\n // Insert & update(s) (updates are a delete & insert)\n inserts > deletes ||\n // A balanced delta updates an existing authoritative row, even if an\n // optimistic delete hides it or its earlier insert is still queued.\n (inserts === deletes && hasSyncedKey(collection.getKeyFromItem(value)))\n ) {\n write({\n value,\n type: `update`,\n })\n // Only delete is left as an option\n } else if (deletes > 0) {\n write({\n value,\n type: `delete`,\n })\n } else {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Could not apply changes: ${JSON.stringify(changes)}. This should never happen.`\n : codedMessage(151),\n )\n }\n }\n\n /**\n * Handle status changes from source collections\n */\n private handleSourceStatusChange(\n config: SyncMethods<TResult>,\n sourceId: string,\n collectionId: string,\n event: AllCollectionEvents[`status:change`],\n ) {\n const { status } = event\n\n // A crashed source cannot serve reads, so it ends this query at any time.\n if (status === `crashed`) {\n this.crashQuery(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Source collection '${collectionId}' crashed`\n : codedMessage(172, { collectionId }),\n event.collection._lifecycle.getSyncError(),\n )\n return\n }\n\n // A source whose first load failed fails this query's first load. Once\n // the query has shown data, the failure is a sync problem on the source's\n // node: the query keeps its status and rows.\n if (status === `error`) {\n if (this.liveQueryCollection?.status === `ready`) return\n this.failQuery(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Source collection '${collectionId}' failed its first load`\n : codedMessage(260, { collectionId }),\n event.collection._lifecycle.getSyncError(),\n )\n return\n }\n\n // Handle manual cleanup - this should not happen due to GC prevention,\n // but could happen if user manually calls cleanup()\n if (status === `cleaned-up`) {\n this.handleSourceCleanupStart(collectionId)\n return\n }\n\n if (status === `ready`) {\n if (\n Object.values(this.optimizableOrderByCollections).some((info) =>\n info.joinedFilterSourceIds?.includes(sourceId),\n )\n ) {\n this.maybeRunGraphFn?.()\n }\n }\n\n // Update ready status based on all source collections\n this.updateLiveQueryStatus(config)\n }\n\n private handleSourceCleanupStart(collectionId: string): Error | undefined {\n if (this.fatalQueryError) return\n const error = new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Source collection '${collectionId}' was manually cleaned up while live query '${this.id}' depends on it. ` +\n `Live queries prevent automatic GC, so this was likely a manual cleanup() call.`\n : codedMessage(152, { collectionId, id: this.id }),\n )\n this.crashQuery(error.message, error)\n return error\n }\n\n /**\n * Update the live query status based on source collection statuses\n */\n private updateLiveQueryStatus(config: SyncMethods<TResult>) {\n // Don't update status if already in error\n if (this.fatalQueryError || !this.isResultComplete()) return\n // A reload's run commits its complete result as its snapshot first. The\n // snapshot completes the reload, so a run that keeps its result private\n // (after a failed window move or ordered load) does not mark ready.\n if (this.reloadSnapshotPending)\n this.currentSyncState?.flushPendingChanges?.()\n if (!this.reloadSnapshotPending) config.markReady()\n }\n\n /** Whether the current run's graph result is complete. */\n private isResultComplete(): boolean {\n const syncState = this.currentSyncState\n const allReady = this.allRequiredSourcesReady()\n const allDemandsSettled = [...this.activeDemands.values()].every(\n (demand) => demand.settled,\n )\n const isLoading = this.liveQueryCollection?.isLoadingSubset\n // Mark ready when:\n // 1. All subscriptions are set up (subscribedToAllCollections)\n // 2. The graph processed all its input: a source can announce its\n // readiness while its last batch still waits in this graph's\n // scheduled run, and that run marks ready when it ends\n // 3. All source collections are ready\n // 4. Every active route demand has settled\n // 5. The live query collection is not loading subset data\n // 6. No source reload's replay is still loading the demand again\n // This prevents marking the live query ready before its data is processed\n // (fixes issue where useLiveQuery returns isReady=true with empty data)\n return (\n syncState?.subscribedToAllCollections === true &&\n !syncState.graph.pendingWork() &&\n allReady &&\n allDemandsSettled &&\n isLoading !== true &&\n !this.hasPendingSourceRecovery()\n )\n }\n\n /**\n * The query's first load failed: status `error`. A sync problem or a\n * request error after the first ready never reaches here.\n */\n private failQuery(message: string, error?: unknown) {\n if (!this.enterErrorState(message)) return\n this.liveQueryCollection?._lifecycle.fail(error ?? new Error(message))\n }\n\n /**\n * The query can no longer serve reads: a crashed source, a graph failure,\n * or a contract violation such as a source cleaned up under this query.\n */\n private crashQuery(message: string, error?: unknown) {\n this.enterErrorState(message)\n this.liveQueryCollection?._lifecycle.crash(error ?? new Error(message))\n }\n\n /** Returns false when the query already ended. */\n private enterErrorState(message: string): boolean {\n if (this.fatalQueryError) return false\n this.fatalQueryError = true\n console.error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `[Live Query Error] ${message}`\n : message,\n )\n return true\n }\n\n private allRequiredSourcesReady() {\n return this.collectionSources.every(({ collection }) =>\n sourcePermitsInitialReadiness(collection),\n )\n }\n\n /**\n * Creates one subscription per lexical collection source.\n * Each source gets independent filters, even when aliases or collections repeat.\n * Example: `{ employee: col, manager: col }` creates two separate subscriptions.\n */\n private subscribeToAllCollections(\n config: SyncMethods<TResult>,\n syncState: FullSyncState,\n ) {\n if (this.collectionSources.length === 0) {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Query '${this.id}' has no collection sources. This should not happen; please report.`\n : codedMessage(153, { id: this.id }),\n )\n }\n\n // A Collection read under several aliases changes this query's tree once\n // per change, so its relay is registered once.\n const relayed = new Set<object>()\n const loaders = this.collectionSources.map((source) => {\n const { sourceId, alias, collection } = source\n const collectionId = collection.id\n\n const dependencyBuilder = getCollectionBuilder(collection)\n if (dependencyBuilder && dependencyBuilder !== this) {\n this.builderDependencies.add(dependencyBuilder)\n }\n\n // CollectionSubscriber handles the actual subscription to the source collection\n // and feeds data into the D2 graph inputs for this specific alias\n const collectionSubscriber = new CollectionSubscriber(\n sourceId,\n alias,\n collection,\n this,\n )\n\n // Subscribe to status changes for status flow\n const statusUnsubscribe = collection.on(`status:change`, (event) => {\n this.handleSourceStatusChange(config, sourceId, collectionId, event)\n })\n // Relay health tree changes so this query's tree stays current.\n if (!relayed.has(collection)) {\n relayed.add(collection)\n syncState.unsubscribeCallbacks.add(\n collection.on(`health:change`, () =>\n this.liveQueryCollection?._emitHealthChange(),\n ),\n )\n }\n let cleanupStartError: Error | undefined\n const cleanupStartUnsubscribe = collection._onCleanupStart(() => {\n cleanupStartError = this.handleSourceCleanupStart(collectionId)\n })\n // Registration reports an already-active cleanup synchronously. That\n // terminal transition must roll back earlier source ownership and stop\n // this source and later aliases from acquiring any.\n if (cleanupStartError) {\n cleanupStartUnsubscribe()\n statusUnsubscribe()\n throw cleanupStartError\n }\n syncState.unsubscribeCallbacks.add(statusUnsubscribe)\n syncState.unsubscribeCallbacks.add(cleanupStartUnsubscribe)\n\n // The source may have failed before this live query subscribed. Register\n // the listener first, then reconcile that current state so no transition\n // can be missed between observation and subscription.\n if (isFailedStatus(collection.status)) {\n this.handleSourceStatusChange(config, sourceId, collectionId, {\n type: `status:change`,\n collection,\n status: collection.status,\n previousStatus: collection.status,\n })\n }\n\n const subscription = collectionSubscriber.subscribe()\n this.subscriptions[sourceId] = subscription\n if (subscription.isDeferringAcquisition()) {\n // No subscriber or preload yet: source reads stay local, and the\n // deferred provider work starts when the first one arrives.\n syncState.unsubscribeCallbacks.add(\n this.liveQueryCollection!._onFirstSubscriberOrPreload(() =>\n subscription.resumeDeferredAcquisition(),\n ),\n )\n // Creating the subscription can run user code, such as an inner live\n // query's status handler, that already requested this one's data.\n if (this.hasSubscriberOrPreload()) {\n subscription.resumeDeferredAcquisition()\n }\n }\n\n const lazyCallbacks = this.lazySourcesCallbacks[sourceId]\n if (lazyCallbacks) {\n lazyCallbacks.setDemand = (plan, keys) =>\n collectionSubscriber.setDemand(subscription, plan, keys)\n for (const plan of lazyCallbacks.plans ?? []) {\n // A window requested before start with a nonzero offset can drop\n // the rows a static filter names, so it gets no static demand.\n if (plan.initialKeys.size > 0 && !this.currentWindow?.offset) {\n lazyCallbacks.setDemand(plan, plan.initialKeys)\n }\n }\n }\n\n // Create a callback for loading more data if needed (used by OrderBy optimization)\n const loadMore = collectionSubscriber.loadMoreIfNeeded.bind(\n collectionSubscriber,\n subscription,\n )\n\n return loadMore\n })\n\n // Mark as subscribed so the graph can start running\n // (graph only runs when all collections are subscribed)\n syncState.subscribedToAllCollections = true\n\n // Note: We intentionally don't call updateLiveQueryStatus() here.\n // The graph hasn't run yet, so marking ready would be premature.\n // The canonical place to mark ready is after the graph processes data\n // in maybeRunGraph(), which ensures data has been processed first.\n\n return () => runAllCallbacks(loaders)\n }\n}\n\nfunction createOrderByComparator<T extends object>(\n orderByIndices: WeakMap<object, string>,\n) {\n return (val1: T, val2: T): number => {\n // Use the orderBy index stored in the WeakMap\n const index1 = orderByIndices.get(val1)\n const index2 = orderByIndices.get(val2)\n\n // Compare fractional indices lexicographically\n if (index1 && index2) {\n if (index1 < index2) {\n return -1\n } else if (index1 > index2) {\n return 1\n } else {\n return 0\n }\n }\n\n // Fallback to no ordering if indices are missing\n return 0\n }\n}\n\nfunction accumulateChanges<T>(\n acc: Map<unknown, Changes<T>>,\n [[key, tupleData], multiplicity]: [\n [unknown, [any, string | undefined]],\n number,\n ],\n) {\n // All queries now consistently return [value, orderByIndex] format\n // where orderByIndex is undefined for queries without ORDER BY\n const [value, orderByIndex] = tupleData as [T, string | undefined]\n\n const changes = acc.get(key) || {\n deletes: 0,\n inserts: 0,\n value,\n orderByIndex,\n }\n if (multiplicity < 0) {\n // Keep the first retraction so order-only moves compare with the last publication.\n if (changes.deletes === 0) {\n changes.previousValue = value\n changes.previousOrderByIndex = orderByIndex\n }\n changes.deletes += Math.abs(multiplicity)\n } else if (multiplicity > 0) {\n changes.inserts += multiplicity\n // Update value to the latest version for this key\n changes.value = value\n if (orderByIndex !== undefined) {\n changes.orderByIndex = orderByIndex\n }\n }\n acc.set(key, changes)\n return acc\n}\n\n/**\n * Decide whether a flush contains an order-only move.\n *\n * An \"order-only move\" — a row updated in place whose `orderByIndex` moved but\n * whose projected value is deep-equal to before — is swallowed by the value-diff\n * and needs an explicit layout notification. The collection coalesces that\n * signal with any ordinary row publication per subscriber.\n */\nfunction hasOrderOnlyMove<T>(\n changesToApply: Map<unknown, Changes<T>>,\n): boolean {\n for (const changes of changesToApply.values()) {\n const isUpdate = changes.inserts > 0 && changes.deletes > 0\n if (\n isUpdate &&\n changes.previousValue !== undefined &&\n deepEquals(changes.previousValue, changes.value) &&\n changes.orderByIndex !== changes.previousOrderByIndex\n ) {\n return true\n }\n }\n return false\n}\n\n/** Mark the collection's next commit as layout-changing. */\nfunction markLayoutChange(collection: { _markLayoutChange: () => void }): void {\n collection._markLayoutChange()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkGA,IAAI,6BAA6B;AAMjC,IAAa,0BAAb,MAGE;;;;;;;;;CAgDA,MAAM,OACJ,QAA+C,KAAK,qBACrC;EAEf,IAAI,OAAO,WAAW,WAAW,OAAO,MAAM,MAAM,OAAO;EAC3D,MAAM,SAAS,KAAK0B,GACjB,KAAK,EAAE,iBAAiB,UAAU,CAAA,CAClC,QACE,YAAY,OAAO,QAClB,IAAI,QAAQ,UAAU,MAAM,SAC5B1B,oBAAAA,aAAa,WAAW,MAAM,CAAA,CAAE,MAAM,SAAS,KAAK,UAAU,IAAI,CACtE;EAGF,MAAM,QAAQ,OAAO,WAAW,UAAU,OAAO,WAAW;EAC5D,MAAM,QAAQ,IAAI,OAAO,KAAK,eAAe,WAAW,OAAO,CAAC,CAAC;EAEjE,IAAI,OAAO,OAAO,MAAM,QAAQ;EAIhC,IAAI,OAAO,WAAW,SAAS,SAAS,OAAO,WAAW,WACxD,MAAM,MAAM,MAAM,OAAO;CAC7B;;CAGA,YAA6C;EAC3C,MAAM,aAAa,KAAK;EACxB,IAAI,CAAC,YAAY,OAAO,KAAA;EACxB,OAAQ,KAAK2B,OAAmB;GAC9B,MAAM;GACN;GACA,IAAI,SAAS;IACX,OAAO,WAAW,YAAY,SAAS;GACzC;GACA,WA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