@tanstack/db
Version:
A reactive client store for building super fast apps on sync
1 lines • 77.6 kB
Source Map (JSON)
{"version":3,"file":"ordered-source-loader.cjs","sources":["../../../../src/query/live/ordered-source-loader.ts"],"sourcesContent":["import {\n buildCursorCurrent,\n canExpressCursorOrder,\n} from '../../utils/cursor.js'\nimport { normalizeError } from '../../utils/error.js'\nimport { reportUncaught, runAllCallbacks } from '../../utils/callbacks.js'\nimport { normalizeOrderByPaths } from '../compiler/expressions.js'\nimport type {\n CollectionSubscription,\n ReleaseLoadSubset,\n} from '../../collection/subscription.js'\nimport type {\n ChangeMessage,\n LoadSubsetOptions,\n LoadSubsetRequestResult,\n} from '../../types.js'\nimport type { OrderByOptimizationInfo } from '../compiler/order-by.js'\n\ntype OrderedRequestKind =\n `ordered` | `ordered-repair` | `boundary` | `full-source`\n\n// What a request or its continuation carries from issue: the ordered-load\n// generation (cursor resets), the authority generation (authoritative\n// starts), the ordering generation (invalidations), and the request's role.\n// `standing()` and `supersedes()` are the only comparisons.\ntype RequestStamp = {\n orderedLoadGeneration: number\n authorityGeneration: number\n orderingInvalidationGeneration: number\n role: `finite` | `repair` | `full-source`\n}\n\ntype OrderedContinuation = RequestStamp & {\n kind: `boundary` | `more`\n windowOperationGeneration?: number\n continuesOrderedPrefixRepair: boolean\n}\n\n// The authoritative work the loader holds. A bounded repair runs as a chain\n// (prefix, tie, refill) fenced by the ordering epoch it started in. A\n// full-source read is held while in flight or awaiting replay, complete once\n// it covers the source, and failed until a retry.\ntype AuthoritativeWork =\n | { kind: `idle` }\n | { kind: `repair`; epoch: number }\n | { kind: `full-source`; status: `held` | `complete` | `failed` }\n\n// The repair the loader owes. An ordering invalidation after settled work\n// owes a bounded repair; partial writes or an unexpressible boundary owe a\n// full-source read.\ntype RepairDebt = `none` | `bounded` | `full`\n\ntype WorkState = `idle` | `repair` | `held` | `complete` | `failed`\n\nconst workState = (work: AuthoritativeWork): WorkState =>\n work.kind === `full-source` ? work.status : work.kind\n\n/** The loader's work slot or debt reached a state its rules forbid. */\nexport class OrderedLoaderInvariantError extends Error {}\n\n// A release that throws is an adapter bug and is reported uncaught. An\n// invariant violation raised by code that the release reentered still fails.\nfunction reportReleaseError(error: unknown): void {\n if (error instanceof OrderedLoaderInvariantError) throw error\n reportUncaught(error)\n}\n\nclass OrderedPostSettlementError {\n constructor(readonly cause: unknown) {}\n}\n\n/** Owns the conservative provider-loading policy for one ordered source. */\nexport class OrderedSourceLoader {\n private pending: Promise<void> | undefined\n // Exact request settlement is not provider extent. This latch only records\n // that some request once completed; reset may discard the boundary, and an\n // empty page retains it. A failure never reads it before a full-source\n // completion sets it again, so it never needs clearing.\n private hasSettledSourceRequest = false\n private settledSourceBoundary: Record<string, unknown> | undefined\n // Independent of ordinary finite success. A live delete or order-changing\n // update owes a bounded repair: unlike a failed request it cannot have\n // partially written unknown rows, so re-reading the exact ordered prefix is\n // authoritative for the current window and preserves the provider query\n // shape.\n private debt: RepairDebt = `none`\n private requesting = false\n // Retaining a demand does not prove it succeeded. Async failure retains it\n // (`failed`) for replay; a synchronous startup failure retains nothing.\n private work: AuthoritativeWork = { kind: `idle` }\n // Keep callbacks, not copied requests or rows. Successful full-source work\n // subsumes these logical owners; unfinished transports remain observed.\n // Each records its prefix count and, for a repair's own acquisitions, the\n // epoch of the repair chain it belongs to.\n private settledFiniteAcquisitions = new Map<\n ReleaseLoadSubset,\n { count: number | undefined; chain: number | undefined }\n >()\n // The record's presence blocks automatic retry, including initial requests\n // that have no explicit window-operation generation.\n private failedRequest:\n { windowOperationGeneration: number | undefined } | undefined\n // A superseded failure owes only a full-source read, so that read's success\n // retires it without an explicit retry.\n private failedAcquisitions = new Map<\n ReleaseLoadSubset,\n { kind: OrderedRequestKind; superseded: boolean }\n >()\n private active = true\n private orderedLoadGeneration = 0\n private orderingInvalidationGeneration = 0\n // Counts authoritative reads started. A request issued before one is\n // superseded: its failure raises the repair debt but blocks nothing.\n private authorityGeneration = 0\n private lastPage: { count: number; boundary: unknown } | undefined\n private lastPrefixCount: number | undefined\n // The rows the source's prefix held when it last grew.\n private grownPrefixRows: number | undefined\n // The count of the last request that read from the start of the order,\n // until a continuation reads past it.\n private ownPrefixCount: number | undefined\n private lastBoundary: unknown\n private needsOptimisticRefill = false\n private retiringSupersededAcquisitions = false\n private repairRetries = 0\n private repairTimer: ReturnType<typeof setTimeout> | undefined\n private stagedContinuation: OrderedContinuation | undefined\n private blockedLoadMore:\n | {\n windowOperationGeneration?: number\n continuesOrderedPrefixRepair: boolean\n }\n | undefined\n private drainingNoInputContinuations = false\n // The graph input revision at which a graph turn asked for more data while\n // a synchronous request was running. That turn has already processed the\n // request's writes, and it will not ask again.\n private graphCheckedDuringRequest: number | undefined\n // An eager source holds every row, so an index on a single order term can\n // answer a prefix with only the first rows of the window.\n private readonly readsBoundedPrefix: boolean\n\n constructor(\n private readonly info: OrderByOptimizationInfo,\n private readonly subscription: CollectionSubscription,\n private readonly alias: string,\n private readonly onResult: (\n result: LoadSubsetRequestResult,\n holdPublication: boolean,\n settlesAsync: boolean,\n options?: LoadSubsetOptions,\n ) => void = () => {},\n private readonly canRetryRepair: () => boolean = () => false,\n private readonly getGraphInputRevision?: () => number,\n private readonly hasPendingJoinedWork: () => boolean = () => false,\n ) {\n this.info.isRequesting = () => this.requesting\n // A joined filter drops rows after the source's limit, so a full window\n // after a bounded read would not prove it holds the first eligible rows.\n this.readsBoundedPrefix =\n info.sourceHoldsAllRows &&\n info.index !== undefined &&\n info.orderBy.length === 1 &&\n info.joinedFilterSourceId === undefined\n }\n\n private get needsOrderingRepair(): boolean {\n return this.debt !== `none`\n }\n\n // Every move of the work slot names the states it may leave. Any other\n // move, or a work and debt pair the rules forbid, is an invariant violation.\n private moveWork(\n next: AuthoritativeWork,\n from: ReadonlyArray<WorkState>,\n debt = this.debt,\n ): void {\n if (!from.includes(workState(this.work))) {\n throw new OrderedLoaderInvariantError(\n `Ordered loader work cannot move from ${workState(this.work)} to ${workState(next)}`,\n )\n }\n this.work = next\n this.debt = debt\n this.checkCoherence()\n }\n\n private oweDebt(next: RepairDebt): void {\n this.debt = next\n this.checkCoherence()\n }\n\n // Complete coverage owes nothing, a repair runs only to pay a debt, and a\n // failed full-source read owes its replacement.\n private checkCoherence(): void {\n const state = workState(this.work)\n if (\n (state === `complete` && this.debt !== `none`) ||\n (state === `repair` && this.debt === `none`) ||\n (state === `failed` && this.debt !== `full`)\n ) {\n throw new OrderedLoaderInvariantError(\n `Ordered loader work ${state} cannot owe ${this.debt} debt`,\n )\n }\n }\n\n private coversSource(): boolean {\n return this.work.kind === `full-source` && this.work.status === `complete`\n }\n\n // A repair whose epoch moved, or whose debt rose to a full-source read, is\n // replaced before it issues another tie or refill.\n private repairNeedsReplacement(): boolean {\n return (\n this.work.kind === `repair` &&\n (this.work.epoch !== this.orderingInvalidationGeneration ||\n this.debt === `full`)\n )\n }\n\n /** Derive invalidation from actual contributions, not a second cursor. */\n onSourceChanges(\n changes: Array<ChangeMessage<Record<string, unknown>, string | number>>,\n sentRows: ReadonlyMap<string | number, Record<string, unknown>> | undefined,\n hasOptimisticOverlay: (key: string | number) => boolean,\n ): void {\n let hasNewRows = false\n let hasOptimisticDeparture = false\n for (const change of changes) {\n const previous = sentRows?.get(change.key)\n // A finished repair holds every row through its boundary, so releasing\n // what it superseded removes only rows outside its coverage.\n if (change.type === `delete` && this.retiringSupersededAcquisitions) {\n continue\n }\n // A sent row that leaves or moves. An optimistic overlay may still\n // revert, so it only checks the local supply; a source move invalidates\n // the order.\n if (\n change.type !== `insert` &&\n previous !== undefined &&\n (change.type === `delete` ||\n this.info.comparator(previous, change.value) !== 0)\n ) {\n if (hasOptimisticOverlay(change.key)) hasOptimisticDeparture = true\n else {\n this.invalidateSourceOrdering()\n return\n }\n }\n if (change.type !== `delete` && previous === undefined) hasNewRows = true\n }\n if (hasOptimisticDeparture && !this.info.sourceHoldsAllRows) {\n const locallyAvailable = this.subscription\n .readOrderedSnapshot({\n orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias),\n limit: this.info.offset + this.info.limit,\n })\n .filter(({ key }) => !hasOptimisticOverlay(key)).length\n if (locallyAvailable < this.info.offset + this.info.limit) {\n this.needsOptimisticRefill = true\n this.invalidateCursor()\n }\n }\n // New keys, including ties, may need another page. Duplicate delivery or\n // an order-equal update cannot invalidate an already attempted request.\n if (hasNewRows) this.invalidateCursor()\n }\n\n start(): void {\n const { index, limit, offset, requiresFullSource } = this.info\n if (index) this.subscription.setOrderByIndex(index)\n if (limit === 0) return\n if (requiresFullSource) {\n this.loadFullSource()\n return\n }\n if (!index) {\n this.loadPrefix(offset + limit)\n return\n }\n this.loadPage(offset + limit)\n }\n\n loadMore(\n windowOperationGeneration?: number,\n continuesOrderedPrefixRepair = false,\n ): Promise<void> | undefined {\n if (this.requesting) {\n this.graphCheckedDuringRequest = this.getGraphInputRevision?.()\n }\n if (!this.active || this.info.limit === 0 || this.requesting) return\n windowOperationGeneration ??=\n this.blockedLoadMore?.windowOperationGeneration\n continuesOrderedPrefixRepair ||=\n this.blockedLoadMore?.continuesOrderedPrefixRepair ?? false\n if (this.info.joinedFilterSourceId && this.hasPendingJoinedWork()) {\n if (\n windowOperationGeneration !== undefined ||\n continuesOrderedPrefixRepair\n ) {\n this.blockedLoadMore = {\n windowOperationGeneration,\n continuesOrderedPrefixRepair,\n }\n }\n return this.pending\n }\n this.blockedLoadMore = undefined\n // A finite step staged under ordering debt cannot run ahead of the owed\n // read. An invalidation drops it. A failure, even one from before a\n // cursor reset that keeps the work staged after it, clears the boundary,\n // so a staged tie has nothing to read from, and a staged `more` step\n // runs this method, which follows the debt.\n if (this.stagedContinuation) {\n this.consumeStagedContinuation(windowOperationGeneration)\n // The consumed continuation can synchronously dispose this loader.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!this.active || this.pending) return this.pending\n }\n const mayRetryFailure =\n this.failedRequest === undefined ||\n (windowOperationGeneration !== undefined &&\n windowOperationGeneration !==\n this.failedRequest.windowOperationGeneration)\n if (!mayRetryFailure) return this.pending\n // A failed full-source read stops owning the source before its lease is\n // released, so a replay during or after a throwing release cannot count it.\n if (this.work.kind === `full-source` && this.work.status === `failed`) {\n this.moveWork({ kind: `idle` }, [`failed`])\n }\n if (\n (this.failedRequest || this.failedAcquisitions.size > 0) &&\n windowOperationGeneration !== undefined &&\n // The explicit retry releases them, not a repair-chain step that runs\n // inside it: a throwing release would unwind the chain mid-step.\n !continuesOrderedPrefixRepair\n ) {\n this.cancelRepairRetry()\n this.repairRetries = 0\n // Move ownership to the explicit replacement before releasing the old\n // acquisition lease. Adapter cleanup may reenter the loader.\n if (this.failedRequest) {\n this.failedRequest.windowOperationGeneration = windowOperationGeneration\n }\n // Adapter cleanup can synchronously tear down this loader; every later\n // step checks that it is still active.\n this.releaseOwned(this.failedAcquisitions, () => true)\n }\n if (\n this.work.kind !== `idle` &&\n !(continuesOrderedPrefixRepair && this.work.kind === `repair`)\n ) {\n if (windowOperationGeneration !== undefined) {\n // A window move held behind repair still needs its source-coverage\n // check when that repair resumes ordered loading.\n this.blockedLoadMore = {\n windowOperationGeneration,\n continuesOrderedPrefixRepair,\n }\n }\n return this.pending\n }\n if (\n (this.needsOrderingRepair &&\n !(continuesOrderedPrefixRepair && this.work.kind === `repair`)) ||\n this.info.requiresFullSource\n ) {\n if (this.debt === `bounded` && !this.info.requiresFullSource) {\n this.loadOrderedPrefixRepair(windowOperationGeneration)\n } else {\n this.loadFullSource(windowOperationGeneration)\n }\n return this.pending\n }\n if (!this.info.index) {\n const shouldLoad =\n windowOperationGeneration !== undefined ||\n this.needsOptimisticRefill ||\n (this.info.dataNeeded?.(this.settledSourceBoundary) ?? 0) > 0 ||\n (this.lastPrefixCount !== undefined &&\n this.lastPrefixCount < this.info.offset + this.info.limit)\n if (shouldLoad) {\n this.needsOptimisticRefill = false\n this.loadPrefix(\n this.info.offset + this.info.limit,\n windowOperationGeneration,\n continuesOrderedPrefixRepair,\n )\n } else if (continuesOrderedPrefixRepair) {\n this.finishOrderedPrefixRepair(windowOperationGeneration)\n }\n return this.pending\n }\n if (!this.info.dataNeeded || this.pending) {\n if (this.pending && windowOperationGeneration !== undefined) {\n // A window move can wait behind an ordered repair. Its source-coverage\n // check still belongs to the continuation after that repair settles.\n this.blockedLoadMore = {\n windowOperationGeneration,\n continuesOrderedPrefixRepair,\n }\n }\n if (continuesOrderedPrefixRepair && !this.pending) {\n this.finishOrderedPrefixRepair(windowOperationGeneration)\n }\n return this.pending\n }\n // A recorded failure always carries repair debt, so it cannot reach this\n // finite path; only the first request needs the whole prefix here.\n let count = Math.max(\n this.info.dataNeeded(this.settledSourceBoundary),\n this.hasSettledSourceRequest ? 0 : this.info.offset + this.info.limit,\n this.needsOptimisticRefill ? 1 : 0,\n )\n if (\n windowOperationGeneration !== undefined &&\n this.settledSourceBoundary !== undefined\n ) {\n const needed = this.info.offset + this.info.limit\n count = Math.max(count, needed - this.countAcquiredRows())\n }\n if (count > 0) {\n this.needsOptimisticRefill = false\n this.loadPage(\n count,\n windowOperationGeneration,\n continuesOrderedPrefixRepair,\n )\n } else if (continuesOrderedPrefixRepair) {\n this.finishOrderedPrefixRepair(windowOperationGeneration)\n }\n return this.pending\n }\n\n loadFullSource(windowOperationGeneration?: number): void {\n if (!this.active || this.work.kind !== `idle`) return\n // An authoritative read supersedes an in-flight finite request; the old\n // request still settles its own participant, and its result is ignored\n // for the boundary. Authority must not wait behind it, or nothing resumes\n // the work when the old request settles.\n this.pending = undefined\n this.moveWork({ kind: `full-source`, status: `held` }, [`idle`])\n this.requestAndObserve(\n (tracking) => this.subscription.requestSnapshot(tracking),\n `full-source`,\n windowOperationGeneration,\n )\n }\n\n private loadOrderedPrefixRepair(windowOperationGeneration?: number): void {\n if (!this.active || this.work.kind !== `idle`) return\n // As for a full-source read, the repair does not wait behind it.\n this.pending = undefined\n // Any older finite request may still settle, but it cannot refine from a\n // boundary that predates this authoritative prefix.\n this.moveWork(\n { kind: `repair`, epoch: this.orderingInvalidationGeneration },\n [`idle`],\n )\n this.ownPrefixCount = this.info.offset + this.info.limit\n this.requestAndObserve(\n (tracking) =>\n this.subscription.requestSnapshot({\n ...tracking,\n orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias),\n limit: this.info.offset + this.info.limit,\n boundedPrefix: this.readsBoundedPrefix,\n }),\n `ordered-repair`,\n windowOperationGeneration,\n true,\n this.info.offset + this.info.limit,\n )\n }\n\n private loadPrefix(\n count: number,\n windowOperationGeneration?: number,\n continuesOrderedPrefixRepair = false,\n ): void {\n if (!this.active || this.pending || this.stagedContinuation) return\n const last = this.lastPrefixCount ?? 0\n if (last >= count) {\n if ((this.info.dataNeeded?.(this.settledSourceBoundary) ?? 0) === 0) {\n if (continuesOrderedPrefixRepair) {\n this.finishOrderedPrefixRepair(windowOperationGeneration)\n }\n return\n }\n // A filter after the read dropped rows, so the prefix doubles: each read\n // stays bounded by twice the last one, and none reads the full source.\n // A pending optimistic departure can hide a row from this count, so the\n // prefix grows while growing still adds rows. Once growing adds none,\n // the source holds no more rows.\n const rows = this.subscription.readOrderedSnapshot({\n orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias),\n limit: last,\n }).length\n if (rows <= (this.grownPrefixRows ?? -1)) {\n if (continuesOrderedPrefixRepair) {\n this.finishOrderedPrefixRepair(windowOperationGeneration)\n }\n return\n }\n this.grownPrefixRows = rows\n count = last * 2\n }\n this.requestAndObserve(\n (tracking) =>\n this.subscription.requestSnapshot({\n ...tracking,\n orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias),\n limit: count,\n boundedPrefix: this.readsBoundedPrefix,\n }),\n `ordered`,\n windowOperationGeneration,\n continuesOrderedPrefixRepair,\n count,\n )\n this.lastPrefixCount = count\n this.ownPrefixCount = count\n }\n\n resetCursor(): void {\n this.cancelRepairRetry()\n this.repairRetries = 0\n this.orderedLoadGeneration++\n if (this.coversSource())\n this.moveWork({ kind: `full-source`, status: `held` }, [`complete`])\n this.pending = undefined\n this.blockedLoadMore = undefined\n this.lastBoundary = undefined\n this.settledSourceBoundary = undefined\n this.stagedContinuation = undefined\n this.invalidateCursor()\n }\n\n settleFullSourceReplay(): void {\n if (this.work.kind === `repair`) {\n this.finishOrderedPrefixRepair()\n return\n }\n // Replay repaired the retained logical acquisition. A later window retry\n // must not release that now-successful source demand. A failed finite\n // page is still obsolete: the replay's full coverage releases it when\n // authoritative work superseded it, and the retry releases it otherwise.\n if (this.work.kind === `full-source` && this.work.status === `failed`) {\n for (const [release, { kind }] of this.failedAcquisitions) {\n if (kind === `full-source`) this.failedAcquisitions.delete(release)\n }\n }\n // The replay is the full-source read's success: it pays the debt.\n if (this.work.kind !== `idle`) {\n this.coverSource([`held`, `failed`, `complete`])\n }\n }\n\n // Full coverage pays every debt, ends the backoff retry, and retires both\n // kinds of lease; a throwing release in one pass must not skip the other.\n private coverSource(from: ReadonlyArray<WorkState>): void {\n this.cancelRepairRetry()\n this.repairRetries = 0\n this.moveWork({ kind: `full-source`, status: `complete` }, from, `none`)\n runAllCallbacks([\n () => this.retireSettledFiniteAcquisitions(),\n () => this.retireSupersededFailures(),\n ])\n }\n\n private retireSettledFiniteAcquisitions(\n prefix?: {\n release: ReleaseLoadSubset\n count: number\n },\n // Retire everything outside this repair chain, which keeps its own.\n keptChain?: number,\n ): void {\n if (\n (!this.coversSource() && !prefix && keptChain === undefined) ||\n this.subscription.hasPendingTruncateReplacement\n )\n return\n this.releaseOwned(\n this.settledFiniteAcquisitions,\n (release, { count, chain }) =>\n keptChain !== undefined\n ? chain !== keptChain\n : this.coversSource() ||\n (prefix !== undefined &&\n release !== prefix.release &&\n count !== undefined &&\n count <= prefix.count),\n )\n }\n\n // A full-source read covers every row, so it supersedes the partial writes\n // of each failed request that authoritative work had superseded.\n private retireSupersededFailures(): void {\n if (this.subscription.hasPendingTruncateReplacement) return\n this.releaseOwned(\n this.failedAcquisitions,\n (_, { superseded }) => superseded,\n )\n }\n\n // Release each selected lease once. A release that resets the cursor, which\n // dispose also does, stops the pass; the replay that follows owns the\n // remaining leases. A release can run the graph synchronously, so\n // refinement stays blocked until the pass unwinds.\n private releaseOwned<TEntry>(\n owner: Map<ReleaseLoadSubset, TEntry>,\n selected: (release: ReleaseLoadSubset, entry: TEntry) => boolean,\n ): void {\n const orderedLoadGeneration = this.orderedLoadGeneration\n const requesting = this.requesting\n this.requesting = true\n try {\n runAllCallbacks(\n Array.from(owner, ([release, entry]) => () => {\n if (\n orderedLoadGeneration !== this.orderedLoadGeneration ||\n !selected(release, entry)\n )\n return\n // Within one generation no other pass can reach this map while\n // refinement is blocked; a missing lease would be a double release.\n if (owner.get(release) !== entry) {\n throw new OrderedLoaderInvariantError(\n `Ordered loader lease was released by another pass`,\n )\n }\n owner.delete(release)\n // A release that throws never changes a load, a window, or the\n // loader's state; it is reported uncaught.\n try {\n release()\n } catch (error) {\n reportReleaseError(error)\n }\n }),\n )\n } finally {\n this.requesting = requesting\n }\n }\n\n invalidateCursor(): void {\n if ((this.stagedContinuation?.role ?? `finite`) === `finite`) {\n this.stagedContinuation = undefined\n }\n this.lastPage = undefined\n this.lastPrefixCount = undefined\n this.grownPrefixRows = undefined\n }\n\n invalidateSourceOrdering(): void {\n this.orderingInvalidationGeneration++\n this.invalidateCursor()\n this.lastBoundary = undefined\n // In-flight page or tie work does not force a full-source read. The\n // bounded repair starts at once, and that work's later result is ignored\n // for its boundary. Full-source reads can be very expensive.\n if (this.debt === `none` && !this.coversSource()) {\n this.oweDebt(\n this.hasSettledSourceRequest && this.work.kind === `idle`\n ? `bounded`\n : `full`,\n )\n }\n this.settledSourceBoundary = undefined\n }\n\n /**\n * The source's sync adapter reports that served pages may have shifted.\n * Coverage that one full-source acquisition established has no page\n * boundary to repair, and the adapter's refetch has already re-read it.\n * A window inside this loader's own first page needs no repair either.\n */\n revalidateLoadedCoverage(): void {\n // A `requiresFullSource` plan's coverage is its full-source read: nothing\n // has settled before it. Coverage that one full-source read completed\n // owes an ordering invalidation nothing, so the invalidation below starts\n // no request for it, and the loader ignores the report (ARCHITECTURE.md).\n if (!this.hasSettledSourceRequest) return\n const end = this.ownPrefixEnd()\n // An installed row past the page proves the source's next row only when\n // the page read it, or when it ties with an end whose tie the loader\n // read. A refetch can move the end before that tie, and then the bounded\n // repair proves the window again. An `undefined` end also matches a\n // loader that attempted no tie. No cursor expresses a nullish end, so the\n // loader has started or will start a full-source read, which covers it.\n if (\n end !== undefined &&\n ((this.ownPrefixCount ?? 0) > this.info.offset + this.info.limit ||\n Object.is(this.info.valueExtractorForRawRow(end), this.lastBoundary))\n )\n return\n this.invalidateSourceOrdering()\n }\n\n // The refetched first page holds every row from the start of the order\n // through its end, and any row it left out sorts after that end. So a\n // window whose rows all sort at or before the end is right. A row after\n // the page that ties with its end could sort before a window row; then\n // the window is not proven. Returns the end when the window is inside\n // the page.\n private ownPrefixEnd(): Record<string, unknown> | undefined {\n const size = this.info.offset + this.info.limit\n // A report can arrive while the refetched rows are accepted but held\n // back, as behind a persisting optimistic transaction. The visible rows\n // then predate the refetch and prove nothing about its page.\n if (\n (this.ownPrefixCount ?? 0) < size ||\n !this.info.dataNeeded ||\n this.subscription.hasHeldSyncTransaction\n ) {\n return undefined\n }\n const rows = this.subscription.readOrderedSnapshot({\n orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias),\n limit: size + 1,\n })\n // Optimistic rows are left out, so a short read proves nothing.\n if (rows.length <= size) return undefined\n const end = rows[size - 1]!.value\n return this.info.comparator(rows[size]!.value, end) > 0 &&\n this.info.dataNeeded(end) === 0\n ? end\n : undefined\n }\n\n private finishOrderedPrefixRepair(windowOperationGeneration?: number): void {\n if (this.work.kind !== `repair`) return\n const epoch = this.work.epoch\n if (this.repairNeedsReplacement()) {\n // A later mutation invalidated the source order while this chain was\n // running. Start its replacement before the current participant settles\n // so Collection and Effect publication remain behind one continuous gate.\n this.moveWork({ kind: `idle` }, [`repair`])\n // A failure during the chain raised the debt to a full-source read.\n if (this.debt === `full`) {\n this.loadFullSource(windowOperationGeneration)\n } else {\n this.loadOrderedPrefixRepair(windowOperationGeneration)\n }\n return\n }\n this.retiringSupersededAcquisitions = true\n try {\n this.retireSettledFiniteAcquisitions(undefined, epoch)\n } finally {\n this.retiringSupersededAcquisitions = false\n const hasSupersededAcquisition = [\n ...this.settledFiniteAcquisitions.values(),\n ].some(({ chain }) => chain !== epoch)\n // A release callback may synchronously begin truncate replay. Keep the\n // repair ownership open so replay settlement can finish retiring the\n // remaining superseded leases without releasing the refreshed prefix.\n if (!this.active || !hasSupersededAcquisition) {\n this.cancelRepairRetry()\n this.repairRetries = 0\n this.moveWork({ kind: `idle` }, [`repair`], `none`)\n }\n }\n }\n\n private abandonOrderedPrefixRepair(): void {\n if (this.work.kind !== `repair`) return\n this.moveWork({ kind: `idle` }, [`repair`], `full`)\n }\n\n dispose(): void {\n this.active = false\n this.resetCursor()\n this.failedAcquisitions.clear()\n this.settledFiniteAcquisitions.clear()\n }\n\n private countAcquiredRows(): number {\n return this.subscription\n .readOrderedSnapshot({\n orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias),\n limit: this.info.offset + this.info.limit,\n })\n .filter(\n ({ value }) =>\n this.info.comparator(value, this.settledSourceBoundary) <= 0,\n ).length\n }\n\n private loadPage(\n count: number,\n windowOperationGeneration?: number,\n continuesOrderedPrefixRepair = false,\n ): void {\n if (!this.active || this.pending || this.stagedContinuation) return\n // Rows observed before the first provider request do not prove ordered\n // source coverage. In particular, a row inserted while limit is zero must\n // not become the cursor when that window first opens.\n const startsFromSourcePrefix = this.settledSourceBoundary === undefined\n const biggest = this.settledSourceBoundary\n let minValues: Array<unknown> | undefined\n if (biggest !== undefined) {\n const value = this.info.valueExtractorForRawRow(biggest)\n if (!canExpressCursorOrder(this.info.orderBy, [value])) {\n this.loadPrefix(\n this.info.offset + this.info.limit,\n windowOperationGeneration,\n continuesOrderedPrefixRepair,\n )\n return\n }\n minValues = [value]\n }\n const boundary = minValues?.[0]\n if (\n this.lastPage?.count === count &&\n Object.is(this.lastPage.boundary, boundary)\n ) {\n if (continuesOrderedPrefixRepair) {\n this.finishOrderedPrefixRepair(windowOperationGeneration)\n }\n return\n }\n this.lastPage = { count, boundary }\n this.ownPrefixCount = startsFromSourcePrefix ? count : undefined\n this.requestAndObserve(\n (tracking) =>\n this.subscription.requestLimitedSnapshot({\n ...tracking,\n orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias),\n limit: count,\n minValues,\n // Local rows seen before the first provider request prove neither\n // a cursor nor a remote offset. Start the first acquisition at zero.\n offset: startsFromSourcePrefix ? 0 : this.countAcquiredRows(),\n }),\n `ordered`,\n windowOperationGeneration,\n continuesOrderedPrefixRepair,\n count,\n )\n }\n\n // A result is dead after a cursor reset. A non-authoritative result is stale\n // after an ordering invalidation: it proves no current coverage.\n private standing(stamp: RequestStamp): `dead` | `stale` | `current` {\n if (stamp.orderedLoadGeneration !== this.orderedLoadGeneration)\n return `dead`\n // A replacement repair or a full-source read started after a repair\n // chain supersedes it; a chain that finished still owns its requests. A\n // finite request is stale once the ordering epoch moves. A full-source\n // read stays current.\n const stale =\n stamp.role === `repair`\n ? this.supersedes(stamp)\n : stamp.role === `finite` &&\n stamp.orderingInvalidationGeneration !==\n this.orderingInvalidationGeneration\n return stale ? `stale` : `current`\n }\n\n // Authoritative work started after the request was issued.\n private supersedes(stamp: RequestStamp): boolean {\n return stamp.authorityGeneration !== this.authorityGeneration\n }\n\n private runContinuation(\n continuation: OrderedContinuation,\n windowOperationGeneration = continuation.windowOperationGeneration,\n ): void {\n if (!this.active || this.standing(continuation) !== `current`) return\n if (continuation.kind === `boundary`) {\n this.loadBoundary(\n windowOperationGeneration,\n continuation.continuesOrderedPrefixRepair,\n )\n } else {\n if (this.info.joinedFilterSourceId && this.hasPendingJoinedWork()) {\n this.stagedContinuation = continuation\n return\n }\n this.loadMore(\n windowOperationGeneration,\n continuation.continuesOrderedPrefixRepair,\n )\n }\n }\n\n private consumeStagedContinuation(windowOperationGeneration?: number): void {\n const continuation = this.stagedContinuation\n if (!continuation) return\n this.stagedContinuation = undefined\n this.runContinuation(continuation, windowOperationGeneration)\n }\n\n // A staged continuation waits for the graph to process the writes that\n // staged it; the graph turn that does so resumes it. If no write arrived\n // since `graphInputRevision`, or a graph turn already processed every\n // write while the request ran and asked for more, no turn will resume it,\n // so the loader continues now.\n private graphHasProcessedInput(graphInputRevision: number): boolean {\n const revision = this.getGraphInputRevision?.()\n return (\n revision === graphInputRevision ||\n revision === this.graphCheckedDuringRequest\n )\n }\n\n private drainNoInputContinuations(graphInputRevision: number): void {\n if (this.drainingNoInputContinuations) return\n this.drainingNoInputContinuations = true\n try {\n while (\n this.stagedContinuation &&\n !this.pending &&\n this.graphHasProcessedInput(graphInputRevision)\n ) {\n this.consumeStagedContinuation()\n }\n } finally {\n this.drainingNoInputContinuations = false\n }\n }\n\n private loadBoundary(\n windowOperationGeneration?: number,\n continuesOrderedPrefixRepair = false,\n ): Promise<void> | undefined {\n const biggest = this.settledSourceBoundary\n if (biggest === undefined) {\n return continuesOrderedPrefixRepair\n ? this.loadMore(windowOperationGeneration, true)\n : undefined\n }\n const value = this.info.valueExtractorForRawRow(biggest)\n const orderBy = normalizeOrderByPaths(this.info.orderBy, this.alias)\n if (!canExpressCursorOrder(orderBy.slice(0, 1), [value])) {\n if (continuesOrderedPrefixRepair) this.abandonOrderedPrefixRepair()\n this.loadFullSource(windowOperationGeneration)\n return this.pending\n }\n // Undefined is not an expressible cursor boundary, so it denotes that no\n // tie request has been attempted. Other falsy values remain valid keys.\n if (Object.is(this.lastBoundary, value)) {\n return this.loadMore(\n windowOperationGeneration,\n continuesOrderedPrefixRepair,\n )\n }\n const where = buildCursorCurrent(orderBy, [value])\n if (!where) {\n if (continuesOrderedPrefixRepair) this.abandonOrderedPrefixRepair()\n this.loadFullSource(windowOperationGeneration)\n return this.pending\n }\n this.lastBoundary = value\n return this.requestAndObserve(\n (tracking) => this.subscription.requestSnapshot({ ...tracking, where }),\n `boundary`,\n windowOperationGeneration,\n continuesOrderedPrefixRepair,\n )\n }\n\n private requireFullSourceRepair(): void {\n this.settledSourceBoundary = undefined\n // A running repair sees the full debt and is replaced by that read. Full\n // coverage owes nothing.\n if (!this.coversSource()) this.oweDebt(`full`)\n }\n\n private cancelRepairRetry(): void {\n clearTimeout(this.repairTimer)\n this.repairTimer = undefined\n }\n\n // Only the loader's own failure outside a window move schedules a retry.\n // That failure blocks the ordinary passes that could fail again, and the\n // timer clears itself before it retries, so no timer is pending here. An\n // explicit move cancels the timer before it takes the failure over.\n private scheduleRepairRetry(): void {\n if (!this.active || !this.canRetryRepair() || this.repairRetries >= 2)\n return\n const orderedLoadGeneration = this.orderedLoadGeneration\n const failedRequest = this.failedRequest\n this.repairTimer = setTimeout(\n () => {\n this.repairTimer = undefined\n const retry = Promise.resolve().then(() => {\n if (\n !this.active ||\n !this.canRetryRepair() ||\n orderedLoadGeneration !== this.orderedLoadGeneration ||\n this.failedRequest !== failedRequest\n )\n return\n this.moveWork({ kind: `idle` }, [`idle`, `failed`])\n this.releaseOwned(this.failedAcquisitions, () => true)\n // Release may dispose or start a new replay; neither belongs to this retry.\n if (\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- release callbacks can dispose the loader\n !this.active ||\n orderedLoadGeneration !== this.orderedLoadGeneration ||\n this.subscription.hasPendingTruncateReplacement\n )\n return\n this.failedRequest = undefined\n this.loadFullSource()\n })\n void retry.catch(() => {})\n this.onResult(retry, true, true)\n },\n 250 * 2 ** this.repairRetries++,\n )\n }\n\n /** A failed request blocks ordinary refinement until a new operation. */\n private recordRequestFailure(windowOperationGeneration?: number): void {\n this.failedRequest = { windowOperationGeneration }\n this.stagedContinuation = undefined\n this.blockedLoadMore = undefined\n this.invalidateCursor()\n this.lastBoundary = undefined\n }\n\n /** Observe settlement only after all synchronous request work succeeds. */\n private requestAndObserve(\n request: (tracking: {\n refetch?: true\n trackLoadSubsetPromise: false\n onLoadSubsetResult: (\n result: LoadSubsetRequestResult,\n options: LoadSubsetOptions,\n release: ReleaseLoadSubset,\n ) => void\n }) => void,\n kind: OrderedRequestKind,\n windowOperationGeneration?: number,\n continuesOrderedPrefixRepair = false,\n requestedCount?: number,\n ): Promise<void> | undefined {\n const isFullSource = kind === `full-source`\n const isOrderedRepair = kind === `ordered-repair`\n const isAuthoritativeRequest =\n isFullSource || isOrderedRepair || continuesOrderedPrefixRepair\n let observed:\n | {\n result: LoadSubsetRequestResult\n options: LoadSubsetOptions\n release: ReleaseLoadSubset\n }\n | undefined\n this.requesting = true\n this.graphCheckedDuringRequest = undefined\n let observing = false\n const graphInputRevision = this.getGraphInputRevision?.()\n // A request belongs to the ordering epoch it is issued in. Its own\n // synchronous delivery can invalidate ordering before it returns; it\n // still proves no coverage for the newer epoch.\n const issuedOrderingGeneration = this.orderingInvalidationGeneration\n try {\n try {\n // Authoritative work re-reads the source, except a full-source read\n // that owes no ordering repair.\n request({\n ...((isFullSource ? this.needsOrderingRepair : isAuthoritativeRequest)\n ? { refetch: true }\n : {}),\n trackLoadSubsetPromise: false,\n onLoadSubsetResult: (result, options, release) => {\n observed = { result, options, release }\n },\n })\n } finally {\n this.requesting = false\n }\n // An authoritative read supersedes in-flight finite requests once it\n // is issued; one that throws while starting supersedes nothing.\n if (isFullSource || isOrderedRepair) {\n this.authorityGeneration++\n }\n if (!observed) return\n observing = true\n const { result, options, release } = observed\n const retryRepair =\n isAuthoritativeRequest &&\n this.hasSettledSourceRequest &&\n this.needsOrderingRepair &&\n windowOperationGeneration === undefined\n // A repair request belongs to the chain it is issued in. One that settles\n // after its replacement started is outside the replacement's chain.\n const chain =\n (isOrderedRepair || continuesOrderedPrefixRepair) &&\n this.work.kind === `repair`\n ? this.work.epoch\n : undefined\n const stamp: RequestStamp = {\n orderedLoadGeneration: this.orderedLoadGeneration,\n authorityGeneration: this.authorityGeneration,\n orderingInvalidationGeneration: issuedOrderingGeneration,\n role: isFullSource\n ? `full-source`\n : isAuthoritativeRequest\n ? `repair`\n : `finite`,\n }\n const settlesAsync = result instanceof Promise\n const canSettleSynchronously =\n !settlesAsync &&\n windowOperationGeneration === undefined &&\n // A full-source request without ordering-repair debt can finish in the\n // current graph turn, including an initial fallback. A bounded prefix\n // repair reads only installed rows and can also finish in that turn.\n // Other repairs keep asynchronous settlement.\n (!isAuthoritativeRequest ||\n (isFullSource\n ? !this.needsOrderingRepair\n : this.readsBoundedPrefix)) &&\n graphInputRevision !== undefined\n let synchronousCompletionFailure: { error: unknown } | undefined\n const continuation = (\n continuationKind: OrderedContinuation[`kind`],\n ): OrderedContinuation => ({\n ...stamp,\n kind: continuationKind,\n windowOperationGeneration,\n continuesOrderedPrefixRepair,\n })\n const continueOrStage = (\n next: OrderedContinuation,\n deferContinuation: boolean,\n ): void => {\n if (deferContinuation) {\n this.stagedContinuation = next\n } else {\n this.runContinuation(next)\n }\n }\n const complete = (\n trackedRequest?: Promise<void>,\n deferContinuation = false,\n ): void => {\n if (trackedRequest && this.pending === trackedRequest) {\n this.pending = undefined\n }\n if (!this.active) return\n // A callback that fails after a successful acquisition does not undo\n // it. Finish its boundary and continuation, then report the first error.\n runAllCallbacks([\n () => {\n if (!isFullSource) {\n // A replay can replace the acquisition lease while this older\n // transport finishes. Retire its logical owner only outside the\n // replay barrier.\n const prefixCount =\n options.orderBy && !options.cursor ? options.limit : undefined\n this.settledFiniteAcquisitions.set(release, {\n count: prefixCount,\n chain,\n })\n // Full-source coverage also retires a repair request that\n // settles after it.\n this.retireSettledFiniteAcquisitions()\n // A prefix issued before an ordering invalidation proves no\n // current coverage, so it cannot supersede the repair's prefix.\n if (\n !continuesOrderedPrefixRepair &&\n this.standing(stamp) === `current` &&\n prefixCount !== undefined\n ) {\n this.retireSettledFiniteAcquisitions({\n release: release,\n count: prefixCount,\n })\n }\n // A request issued before an ordering invalidation that settles\n // after the repair finished is already superseded by that repair.\n if (\n this.standing(stamp) === `stale` &&\n this.work.kind === `idle` &&\n !this.needsOrderingRepair &&\n this.settledFiniteAcquisitions.delete(release)\n ) {\n this.retiringSupersededAcquisitions = true\n try {\n release()\n } catch (error) {\n reportReleaseError(error)\n } finally {\n this.retiringSupersededAcquisitions = false\n }\n }\n }\n },\n () => {\n if (this.standing(stamp) !== `current`) return\n // A finite request may finish behind an authoritative repair. It cannot\n // clear that repair's failure or resume finite refinement around it.\n if (\n !isAuthoritativeRequest &&\n (this.failedRequest || this.work.kind !== `idle`)\n )\n return\n this.failedRequest = undefined\n if (kind !== `boundary`) {\n this.hasSettledSourceRequest = true\n // Source delivery can invalidate the in-flight prefix marker.\n if (options.orderBy && !options.cursor) {\n this.lastPrefixCount = options.limit\n }\n if (!isFullSource && options.orderBy) {\n try {\n this.settledSourceBoundary =\n this.subscription\n .readOrderedSnapshot({\n ...options,\n // Provider limits include optimistic headroom. Those\n // extra local ranks do not prove a source boundary.\n limit: requestedCount ?? options.limit,\n })\n .at(-1)?.value ?? this.settledSourceBoundary\n } catch (error) {\n if (canSettleSynchronously) {\n synchronousCompletionFailure = { error }\n throw error\n }\n fail(error)\n }\n }\n }\n if (\n (isOrderedRepair || continuesOrderedPrefixRepair) &&\n (this.work.kind !== `repair` || this.repairNeedsReplacement())\n ) {\n // The settled request may apply its rows, but a later mutation has\n // already invalidated this chain. Replace it before issuing stale\n // tie or refill work.\n this.finishOrderedPrefixRepair(windowOperationGeneration)\n return\n }\n if (isFullSource) this.coverSource([`held`, `complete`])\n if (isOrderedRepair || kind === `ordered`) {\n continueOrStage(continuation(`boundary`), deferContinuation)\n return\n }\n // A boundary request may add tied rows without filling the query's\n // window. Resume forward loading once it settles.\n continueOrStage(continuation(`more`), deferContinuation)\n },\n ])\n }\n const fail = (error: unknown, trackedRequest?: Promise<void>) => {\n this.settledFiniteAcquisitions.delete(release)\n if (trackedRequest && this.pending === trackedRequest) {\n this.pending = undefined\n }\n // Dispose resets the cursor, so a disposed loader's requests are dead.\n // A replay already reacquired this full-source read's demand. Its late\n // transport failure leaves that coverage, and its lease, in place.\n if (isFullSource && this.coversSource()) return\n // A failed request may already have written only part of its result.\n // None of those rows is a safe continuation boundary.\n this.requireFullSourceRepair()\n // Work staged after a cursor reset belongs to the new generation.\n if (this.standing(stamp) === `dead`) return\n // Only the running authoritative work owns its staged step; a replaced\n // chain's request is stale and drops nothing. A chain request owns\n // authority only while its chain runs: one whose chain a replay\n // finished is superseded by that replay.\n const ownsAuthority =\n isAuthoritativeRequest &&\n this.standing(stamp) === `current` &&\n (isFullSource || this.work.kind === `repair`)\n if (\n ownsAuthority ||\n (this.stagedContinuation?.role ?? `finite`) === `finite`\n ) {\n this.stagedContinuation = undefined\n }\n // Authoritative work started after this request supersedes it. Its\n // failure is not the loader's own: its partial writes only raise the\n // debt to the full-source read that the overlap replaced. A running\n // repair restarts as that read; otherwise it starts now, unless the\n // loader's own failure is waiting for an explicit retry.\n if (isAuthoritativeRequest ? !ownsAuthority : this.supersedes(stamp)) {\n this.failedAcquisitions.set(release, {\n kind,\n superseded: true,\n })\n // Full-source coverage may already have covered its rows.\n if (this.coversSource()) {\n this.retireSupersededFailures()\n }\n this.invalidateCursor()\n this.lastBoundary = undefined\n // The loader's own recorded failure still waits for an explicit retry.\n if (this.failedRequest === undefined && this.work.kind === `idle`) {\n // A recovery read that throws while it starts is the loader's own\n // failure, recorded and reported on its own; this request still\n // reports its error.\n try {\n this.loadFullSource(windowOperationGeneration)\n } catch (startError) {\n if (startError instanceof OrderedLoaderInvariantError) {\n throw startError\n }\n }\n }\n throw error\n }\n // A failed request proves no full-source coverage. An explicit window\n // move or later replay may retry it, but an ordinary graph pass must\n // not start an eager retry loop.\n if (isFullSource) {\n this.moveWork({ kind: `full-source`, status: `failed` }, [`held`])\n } else if (isAuthoritativeRequest) {\n this.moveWork({ kind: `idle` }, [`repair`])\n }\n this.recordRequestFailure(windowOperationGeneration)\n this.failedAcquisitions.set(release, {\n kind,\n superseded: false,\n })\n if (retryRepair) this.scheduleRepairRetry()\n throw error\n }\n if (canSettleSynchronously) {\n try {\n runAllCallbacks([\n () => complete(undefined, true),\n () => {\n if (!synchronousCompletionFailure) {\n this.onResult(true, false, false)\n }\n },\n () => {\n if (\n !synchronousCompletionFailure &&\n this.graphHasProcessedInput(graphInputRevision)\n ) {\n this.drainNoInputContinuations(graphInputRevision)\n }\n },\n ])\n } catch (error) {\n if (synchronousCompletionFailure) {\n throw synchronousCompletionFailure.error\n }\n throw new OrderedPostSettlementError(error)\n }\n return this.pending\n }\n const transport: Promise<void> = settlesAsync ? result : Promise.resolve()\n const tracked: Promise<void> = transport.then(\n () => complete(tracked),\n (error) => fail(error, tracked),\n )\n this.pending = tracked\n void tracked.catch(() => {})\n // Register each request separately. The operation tracker observes the\n // next request before this promise settles, so the logical chain remains\n // pending without retaining every ancestor promise until the final page.\n this.onResult(\n tracked,\n isAuthoritativeRequest && this.needsOrderingRepair,\n settlesAsync,\n options,\n )\n return tracked\n } catch (error) {\n if (error instanceof OrderedPostSettlementError) throw error.cause\n if (error instanceof OrderedLoaderInvariantError) throw error\n // Both request and settlement callbacks may reenter through cleanup.\n // Keep refinement blocked until failure and release finish unwinding.\n this.requesting = true\n try {\n const failure = normalizeError(error)\n // A settlement that failed synchronously is not observed again.\n if (observing) {\n this.orderedLoadGeneration++\n this.pending = undefined\n }\n this.requireFullSourceRepair()\n this.recordRequestFailure(windowOperationGeneration)\n if (isAuthoritativeRequest) {\n this.moveWork({ kind: `idle` }, [`held`, `repair`])\n }\n try {\n observed?.release({ error: failure })\n } catch (releaseError) {\n reportReleaseError(releaseError)\n }\n if (isAuthoritativeRequest && this.hasSettledSourceRequest) {\n if (windowOperationGeneration === undefined) {\n this.scheduleRepairRetry()\n }\n if (!observing) {\n // A synchronous repair failure has no transport promise, but must\n // still close publication before the triggering graph turn\n // returns.\n const rejected = Promise.reject(failure)\n void rejected.catch(() => {})\n this.onResult(rejected, true, true)\n }\n }\n throw failure\n } finally {\n this.requesting = false\n }\n }\n }\n}\n"],"names":["error","reportUncaught","onResult","canRetryRepair","hasSettledSourceRequest","debt","requesting","settledFiniteAcquisitions","failedAcquisitions","needsOptimisticRefill","retiringSupersededAcquisitions","repairRetries","drainingNoInputContinuations","readsBoundedPrefix","needsOrderingRepair","moveWork","checkCoherence","oweDebt","coversSource","repairNeedsReplacement","normalizeOrderByPaths","loadPrefix","loadPage","graphCheckedDuringRequest","blockedLoadMore","stagedContinuation","consumeStagedContinuation","failedRequest","cancelRepairRetry","releaseOwned","loadOrderedPrefixRepair","settledSourceBoundary","lastPrefixCount","finishOrderedPrefixRepair","countAcquiredRows","requestAndObserve","ownPrefixCount","grownPrefixRows","lastBoundary","coverSource","runAllCallbacks","retireSettledFiniteAcquisitions","retireSupersededFailures","lastPage","ownPrefixEnd","abandonOrderedPrefixRepair","canExpressCursorOrder","standing","supersedes","runContinuation","loadBoundary","graphHasProcessedInput","drainNoInputContinuations","buildCursorCurrent","requireFullSourceRepair","repairTimer","scheduleRepairRetry","recordRequestFailure","result","options","release","normalizeError"],"mappings":";;;;;;AAsDA,MAAM,YAAY,CAAC,SACjB,KAAK,SAAS,gBAAgB,KAAK,SAAS,KAAK;AAG5C,MAAM,oCAAoC,MAAM;AAAC;AAIxD,SAAS,mBAAmBA,QAAsB;AAChD,MAAIA,kBAAiB,4BAA6B,OAAMA;AACxDC,YAAAA,eAAeD,MAAK;AACtB;AAEA,MAAM,2BAA2B;AAAA,EAC/B,YAAqB,OAAgB;AAAhB,SAAA,QAAA;AAAA,EAAiB;AACxC;AAGO,MAAM,oBAAoB;AAAA,EAsE/B,YACmB,MACA,cACA,OACA,WAKL,MAAM;AAAA,EAAC,GACF,iBAAgC,MAAM,OACtC,uBACA,uBAAsC,MAAM,OAC7D;AAZiB,SAAA,OAAA;AACA,SAAA,eAAA;AACA,SAAA,QAAA;AACA,SAAAE,KAAA;AAMA,SAAAC,KAAA;AACA,SAAA,wBAAA;AACA,SAAA,uBAAA;AA5EnB,SAAQC,KAA0B;AAOlC,SAAQC,KAAmB;AAC3B,SAAQC,KAAa;AAGrB,SAAQ,OAA0B,EAAE,MAAM,OAAA;AAK1C,SAAQC,yBAAgC,IAAA;AAUxC,SAAQC,yBAAyB,IAAA;AAIjC,SAAQ,SAAS;AACj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