UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

1 lines • 76.5 kB
{"version":3,"file":"ordered-source-loader.cjs","names":["normalizeOrderByPaths","canExpressCursorOrder","buildCursorCurrent","normalizeError","onResult","canRetryRepair","hasSettledSourceRequest","settledSourcePrefix","debt","requesting","settledFiniteAcquisitions","failedAcquisitions","needsOptimisticRefill","retiringSupersededAcquisitions","repairRetries","drainingNoInputContinuations","readsBoundedPrefix","needsOrderingRepair","moveWork","checkCoherence","oweDebt","coversSource","repairNeedsReplacement","settledSourceBoundary","loadPrefix","loadPage","graphCheckedDuringRequest","blockedLoadMore","stagedContinuation","consumeStagedContinuation","failedRequest","cancelRepairRetry","releaseOwned","loadOrderedPrefixRepair","lastPrefixCount","finishOrderedPrefixRepair","countAcquiredRows","requestAndObserve","ownPrefixCount","grownPrefixRows","lastBoundary","coverSource","retireSettledFiniteAcquisitions","retireSupersededFailures","lastPage","ownPrefixEnd","abandonOrderedPrefixRepair","standing","supersedes","runContinuation","loadBoundary","graphHasProcessedInput","drainNoInputContinuations","requireFullSourceRepair","repairTimer","scheduleRepairRetry","recordRequestFailure","result","options","release"],"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  // The settled prefix ending at that boundary: a row that ties with the\n  // boundary but is not among these rows lies outside the prefix.\n  private settledSourcePrefix: ReadonlyArray<\n    ChangeMessage<Record<string, unknown>, string | number>\n  > = []\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.joinedFilterSourceIds?.length\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 of its prefix, so releasing what it\n      // superseded removes only rows after it, such as a tie only an old tie\n      // request held. Deleting a sent row of the prefix is new source\n      // information.\n      if (change.type === `delete` && this.retiringSupersededAcquisitions) {\n        const order =\n          previous === undefined || this.settledSourceBoundary === undefined\n            ? 1\n            : this.info.comparator(previous, this.settledSourceBoundary)\n        if (\n          order > 0 ||\n          (order === 0 &&\n            this.settledSourcePrefix.every(({ key }) => key !== change.key))\n        )\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 (\n      this.info.joinedFilterSourceIds?.length &&\n      this.hasPendingJoinedWork()\n    ) {\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        // Retirement can deliver a newer invalidation or raise the debt to a\n        // full-source read. Keep that debt for the next pass; otherwise this\n        // chain has paid its own epoch.\n        this.moveWork(\n          { kind: `idle` },\n          [`repair`],\n          this.repairNeedsReplacement() ? this.debt : `none`,\n        )\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 (\n        this.info.joinedFilterSourceIds?.length &&\n        this.hasPendingJoinedWork()\n      ) {\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                  const prefix = this.subscription.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                  const boundary = prefix.at(-1)?.value\n                  if (boundary) {\n                    this.settledSourceBoundary = boundary\n                    this.settledSourcePrefix = prefix\n                  }\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"],"mappings":";;;;AAsDA,IAAM,aAAa,SACjB,KAAK,SAAS,gBAAgB,KAAK,SAAS,KAAK;AAGnD,IAAa,8BAAb,cAAiD,MAAM,CAAC;AAIxD,SAAS,mBAAmB,OAAsB;CAChD,IAAI,iBAAiB,6BAA6B,MAAM;CACxD,kBAAA,eAAe,KAAK;AACtB;AAEA,IAAM,6BAAN,MAAiC;CAC/B,YAAY,OAAyB;EAAhB,KAAA,QAAA;CAAiB;AACxC;AAGA,IAAa,sBAAb,MAAiC;CA2E/B,YACE,MACA,cACA,OACA,iBAKkB,CAAC,GACnB,uBAAuD,OACvD,uBACA,6BAA6D,OAC7D;EAZiB,KAAA,OAAA;EACA,KAAA,eAAA;EACA,KAAA,QAAA;EACA,KAAAI,KAAA;EAMA,KAAAC,KAAA;EACA,KAAA,wBAAA;EACA,KAAA,uBAAA;EAjFe,KAAAC,KAAA;EAM9B,KAAAC,KAAA,CAAC;EAMsB,KAAAC,KAAA;EACN,KAAAC,KAAA;EAGa,KAAA,OAAA,EAAE,MAAM,OAAO;EAKb,KAAAC,qBAAA,IAAI,IAGtC;EAO2B,KAAAC,qBAAA,IAAI,IAG/B;EACe,KAAA,SAAA;EACe,KAAA,wBAAA;EACS,KAAA,iCAAA;EAGX,KAAA,sBAAA;EASE,KAAAC,IAAA;EACS,KAAAC,IAAA;EACjB,KAAAC,KAAA;EASe,KAAAC,KAAA;EAuBrC,KAAK,KAAK,qBAAqB,KAAKN;EAGpC,KAAKO,KACH,KAAK,sBACL,KAAK,UAAU,KAAA,KACf,KAAK,QAAQ,WAAW,KACxB,CAAC,KAAK,uBAAuB;CACjC;CAEA,IAAYC,KAA+B;EACzC,OAAO,KAAKT,OAAS;CACvB;CAIAU,GACE,MACA,MACA,OAAO,KAAKV,IACN;EACN,I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