Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/deferred-is-subset-loaded.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@tanstack/db': patch
---

Add an optional `isSubsetLoaded` sync hook, so a live query with no subscriber yet can publish a window whose rows the source already holds on its first frame.

A joined filter's first ordered request also waits for pending joined work, and a synchronously answered request whose refill waits on joined work returns instead of spinning.
244 changes: 117 additions & 127 deletions docs/contributing/oracle-coverage.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/db/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"test": "vitest --run",
"test:dist": "vitest run --config vitest.dist.config.ts",
"test:facade-retention": "node --expose-gc --import tsx tests/facade-retention.probe.ts",
"test:oracles": "vitest --run --coverage.enabled=false tests/oracle-campaign-units.test.ts tests/reverse-index-oracle.property.test.ts tests/query/compiler/in-evaluator-oracle.property.test.ts tests/query/compiler/group-by-pipeline-oracle.test.ts tests/cleanup-queue-oracle.property.test.ts tests/comparison-oracle.property.test.ts tests/duration-query-equality-oracle.test.ts tests/cursor-oracle.property.test.ts tests/index-update-oracle.property.test.ts tests/utils-oracle.property.test.ts tests/change-event-history-oracle.test.ts tests/index-suggestion-oracle.test.ts tests/btree-map-oracle.test.ts tests/paced-mutations-oracle.test.ts tests/db-client-hydration-authority-oracle.test.ts tests/local-storage-eager-reload-oracle.property.test.ts tests/local-only-direct-write-oracle.test.ts tests/local-storage-order-oracle.test.ts tests/local-storage-write-order-oracle.test.ts tests/local-storage-peers-oracle.test.ts tests/local-storage-value-fidelity-oracle.property.test.ts tests/collection-cleanup-restart-oracle.test.ts tests/collection-gc-transaction-oracle.property.test.ts tests/collection-gc-retention-oracle.property.test.ts tests/collection-gc-mutation-oracle.property.test.ts tests/effect-disposal-oracle.test.ts tests/optimistic-transaction-oracle.property.test.ts tests/transaction-ownership-oracle.property.test.ts tests/optimistic-history-oracle.property.test.ts tests/optimistic-history-publication-oracle.test.ts tests/optimistic-history-outcomes-oracle.test.ts tests/collection-metadata-publication-oracle.property.test.ts tests/collection-index-value-oracle.test.ts tests/collection-state-retention-oracle.property.test.ts tests/collection-subscription-lifecycle-history-oracle.property.test.ts tests/collection-subscription-lifecycle-oracle.test.ts tests/collection-subscription-reentrancy-oracle.test.ts tests/collection-subscription-lifecycle-publication-oracle.property.test.ts tests/collection-subscription-replay-oracle.property.test.ts tests/d2-source-reconciliation-oracle.property.test.ts tests/live-query-cache-options-oracle.test.ts tests/mutation-confirmation-calibration.test.ts tests/mutation-handler-types-oracle.test.ts tests/live-query-observer-history-oracle.property.test.ts tests/live-query-observer-hydration-oracle.property.test.ts tests/live-query-observer-snapshot-oracle.property.test.ts tests/query/cold-join-reconciliation-oracle.test.ts tests/query/identity-output-shape-oracle.test.ts tests/query/optimizer-semantics-oracle.test.ts tests/query/index-path-collision-oracle.test.ts tests/query/custom-index-order-selection-oracle.test.ts tests/query/mixed-index-order-oracle.test.ts tests/query/includes-collection-oracle.property.test.ts tests/query/includes-functional-projection-oracle.test.ts tests/query/includes-functional-input-boundary.test.ts tests/query/public-container-copy-oracle.test.ts tests/query/includes-context-transport-oracle.test.ts tests/query/includes-cross-formulation-oracle.property.test.ts tests/query/includes-optimistic-oracle.property.test.ts tests/query/includes-oracle.property.test.ts tests/query/includes-alias-shadowing-oracle.test.ts tests/query/includes-outer-join-route-work-oracle.test.ts tests/query/includes-publication-oracle.test.ts tests/query/includes-query-shape-oracle.test.ts tests/query/subquery-user-value-oracle.test.ts tests/query/includes-temporal-oracle.test.ts tests/query/includes-work-counter-oracle.test.ts tests/query/load-subset-oracle.property.test.ts tests/query/load-subset-replay-refinement-oracle.test.ts tests/query/load-subset-source-readiness-refinement-oracle.test.ts tests/query/load-subset-transaction-refinement-oracle.test.ts tests/query/ordered-source-loader-state-oracle.test.ts tests/query/ordered-demand-retirement.test.ts tests/query/ordered-default-work.test.ts tests/query/ordered-lifecycle-oracle.property.test.ts tests/query/ordered-work-oracle.property.test.ts tests/query/pagination-oracle.property.test.ts tests/query/includes-space-oracle.test.ts tests/query/virtual-row-fields-oracle.test.ts tests/query/virtual-row-fields-input-oracle.test.ts tests/query/virtual-row-fields-effect-oracle.test.ts tests/query/virtual-row-fields-types-oracle.test.ts tests/query/where-predicate-publication-oracle.property.test.ts tests/query/join-result-key-oracle.property.test.ts tests/query/pooled-live-query-oracle.property.test.ts tests/live-query-deferred-acquisition-oracle.test.ts tests/flat-change-tracking-oracle.property.test.ts tests/truncate-readiness-oracle.test.ts tests/proxy-detachment-contract-oracle.test.ts tests/production-error-messages-oracle.test.ts tests/query/bucket-facade-rollback-oracle.property.test.ts tests/query/aggregate-select-oracle.property.test.ts tests/query/load-subset-joint-replay-oracle.property.test.ts",
"test:oracles": "vitest --run --coverage.enabled=false tests/oracle-campaign-units.test.ts tests/query/deferred-loaded-subset-oracle.test.ts tests/reverse-index-oracle.property.test.ts tests/query/compiler/in-evaluator-oracle.property.test.ts tests/query/compiler/group-by-pipeline-oracle.test.ts tests/cleanup-queue-oracle.property.test.ts tests/comparison-oracle.property.test.ts tests/duration-query-equality-oracle.test.ts tests/cursor-oracle.property.test.ts tests/index-update-oracle.property.test.ts tests/utils-oracle.property.test.ts tests/change-event-history-oracle.test.ts tests/index-suggestion-oracle.test.ts tests/btree-map-oracle.test.ts tests/paced-mutations-oracle.test.ts tests/db-client-hydration-authority-oracle.test.ts tests/local-storage-eager-reload-oracle.property.test.ts tests/local-only-direct-write-oracle.test.ts tests/local-storage-order-oracle.test.ts tests/local-storage-write-order-oracle.test.ts tests/local-storage-peers-oracle.test.ts tests/local-storage-value-fidelity-oracle.property.test.ts tests/collection-cleanup-restart-oracle.test.ts tests/collection-gc-transaction-oracle.property.test.ts tests/collection-gc-retention-oracle.property.test.ts tests/collection-gc-mutation-oracle.property.test.ts tests/effect-disposal-oracle.test.ts tests/optimistic-transaction-oracle.property.test.ts tests/transaction-ownership-oracle.property.test.ts tests/optimistic-history-oracle.property.test.ts tests/optimistic-history-publication-oracle.test.ts tests/optimistic-history-outcomes-oracle.test.ts tests/collection-metadata-publication-oracle.property.test.ts tests/collection-index-value-oracle.test.ts tests/collection-state-retention-oracle.property.test.ts tests/collection-subscription-lifecycle-history-oracle.property.test.ts tests/collection-subscription-lifecycle-oracle.test.ts tests/collection-subscription-reentrancy-oracle.test.ts tests/collection-subscription-lifecycle-publication-oracle.property.test.ts tests/collection-subscription-replay-oracle.property.test.ts tests/d2-source-reconciliation-oracle.property.test.ts tests/live-query-cache-options-oracle.test.ts tests/mutation-confirmation-calibration.test.ts tests/mutation-handler-types-oracle.test.ts tests/live-query-observer-history-oracle.property.test.ts tests/live-query-observer-hydration-oracle.property.test.ts tests/live-query-observer-snapshot-oracle.property.test.ts tests/query/cold-join-reconciliation-oracle.test.ts tests/query/identity-output-shape-oracle.test.ts tests/query/optimizer-semantics-oracle.test.ts tests/query/index-path-collision-oracle.test.ts tests/query/custom-index-order-selection-oracle.test.ts tests/query/mixed-index-order-oracle.test.ts tests/query/includes-collection-oracle.property.test.ts tests/query/includes-functional-projection-oracle.test.ts tests/query/includes-functional-input-boundary.test.ts tests/query/public-container-copy-oracle.test.ts tests/query/includes-context-transport-oracle.test.ts tests/query/includes-cross-formulation-oracle.property.test.ts tests/query/includes-optimistic-oracle.property.test.ts tests/query/includes-oracle.property.test.ts tests/query/includes-alias-shadowing-oracle.test.ts tests/query/includes-outer-join-route-work-oracle.test.ts tests/query/includes-publication-oracle.test.ts tests/query/includes-query-shape-oracle.test.ts tests/query/subquery-user-value-oracle.test.ts tests/query/includes-temporal-oracle.test.ts tests/query/includes-work-counter-oracle.test.ts tests/query/load-subset-oracle.property.test.ts tests/query/load-subset-replay-refinement-oracle.test.ts tests/query/load-subset-source-readiness-refinement-oracle.test.ts tests/query/load-subset-transaction-refinement-oracle.test.ts tests/query/ordered-source-loader-state-oracle.test.ts tests/query/ordered-demand-retirement.test.ts tests/query/ordered-default-work.test.ts tests/query/ordered-lifecycle-oracle.property.test.ts tests/query/ordered-work-oracle.property.test.ts tests/query/pagination-oracle.property.test.ts tests/query/includes-space-oracle.test.ts tests/query/virtual-row-fields-oracle.test.ts tests/query/virtual-row-fields-input-oracle.test.ts tests/query/virtual-row-fields-effect-oracle.test.ts tests/query/virtual-row-fields-types-oracle.test.ts tests/query/where-predicate-publication-oracle.property.test.ts tests/query/join-result-key-oracle.property.test.ts tests/query/pooled-live-query-oracle.property.test.ts tests/live-query-deferred-acquisition-oracle.test.ts tests/flat-change-tracking-oracle.property.test.ts tests/truncate-readiness-oracle.test.ts tests/proxy-detachment-contract-oracle.test.ts tests/production-error-messages-oracle.test.ts tests/query/bucket-facade-rollback-oracle.property.test.ts tests/query/aggregate-select-oracle.property.test.ts tests/query/load-subset-joint-replay-oracle.property.test.ts",
"bench:nested-includes": "vitest bench tests/query/includes-performance.bench.ts --run --coverage.enabled=false --reporter=verbose",
"test:indexed-db:package": "pnpm --filter @tanstack/db... build && vitest run --config vitest.indexed-db.package.config.ts",
"test:local-stores:browser": "vitest run --config vitest.local-stores.config.ts --maxWorkers=1",
Expand Down
103 changes: 94 additions & 9 deletions packages/db/src/collection/subscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,22 +307,78 @@ export class CollectionSubscription
if (status !== `loading` && status !== `ready`) return
const syncRunGeneration = this.collection._sync.getSyncRunGeneration()
const replayState = this.truncateReplayState
if (
this.subsetDemands.some(
(demand) => demand.acquisitionState === `detached`,
)
) {
this.setStatus(`loadingSubset`)
}
this.reconcileDeferredDemands(replayState)
Comment thread
daveycodez marked this conversation as resolved.
Resolved
queueMicrotask(() => {
if (this.truncateReplayState === replayState) {
// A source that becomes ready inside its own sync() emits before
// it returns the hook, so ask again once it has.
if (
this.defersAcquisition &&
this.isSyncRunGenerationCurrent(syncRunGeneration)
)
this.reconcileDeferredDemands(replayState)
this.restartDetachedDemands(syncRunGeneration)
}
})
}),
// A peer's load can make a deferred demand held while the source stays ready.
this.collection.on(`loadingSubset:change`, ({ isLoadingSubset }) => {
if (!isLoadingSubset) this.reconcileHeldDeferredDemands()
}),
]
}

/** Recheck deferred demands after rows arrived outside a status change. */
private reconcileHeldDeferredDemands(): void {
if (
this.defersAcquisition &&
!this.unsubscribed &&
!this.truncateReplayState &&
this.subsetDemands.some(
(demand) => demand.acquisitionState === `detached`,
)
) {
this.reconcileDeferredDemands(undefined)
}
}

/**
* Settle the deferred demands whose rows are held, and report
* `loadingSubset` exactly while a detached demand still owes a load.
*/
private reconcileDeferredDemands(
replayState: TruncateReplayState | undefined,
): void {
if (this.defersAcquisition && !replayState) {
// Rows that became held answer a deferred demand's waiting caller.
for (const demand of this.subsetDemands) {
if (
demand.acquisitionState === `detached` &&
this.isSubsetLoadedLocally(demand.requestOptions)
) {
demand.initialResult?.resolve()
}
}
}
if (
this.subsetDemands.some(
(demand) =>
demand.acquisitionState === `detached` &&
// A deferred demand whose rows are held owes no load yet.
!(
this.defersAcquisition &&
this.isSubsetLoadedLocally(demand.requestOptions)
),
)
) {
this.setStatus(`loadingSubset`)
} else if (this.defersAcquisition && this.status === `loadingSubset`) {
// The queued restart returns while acquisition is deferred, so a
// demand that became held leaves the loading state here.
this.setReadyIfIdle()
}
}

/** Whether this subscription still defers provider work. */
public isDeferringAcquisition(): boolean {
return this.defersAcquisition
Expand Down Expand Up @@ -1187,6 +1243,16 @@ export class CollectionSubscription
}
}

private isSubsetLoadedLocally(options: LoadSubsetOptions): boolean {
const isSubsetLoaded = this.collection._sync.syncIsSubsetLoadedFn
if (!isSubsetLoaded) return false
try {
return isSubsetLoaded(options) === true
} catch {
return false
}
}

/** Start and retain the first acquisition for one logical subset demand. */
private startSubsetDemand(requestOptions: LoadSubsetOptions): {
demand: SubsetDemand
Expand All @@ -1208,11 +1274,13 @@ export class CollectionSubscription
const replayState = this.truncateReplayState
const replayAttempt = replayState?.currentAttempt
try {
const deferred =
this.defersAcquisition &&
this.collection.config.syncMode === `on-demand`
const detached =
this.collection.status === `cleaned-up` ||
// A deferring subscription starts no acquisition attempt until it resumes.
(this.defersAcquisition &&
this.collection.config.syncMode === `on-demand`) ||
deferred ||
// Ready/error callbacks can run before sync returns its loader. Idle
// deferred starts still acquire through the sync manager's queue.
(this.collection.config.syncMode === `on-demand` &&
Expand Down Expand Up @@ -1252,6 +1320,15 @@ export class CollectionSubscription
initialResult.promise,
requestOptions.signal,
)
// Rows the Collection already holds whole answer a deferred demand
// now. Its acquisition still starts when the subscription resumes.
if (
deferred &&
!replayState &&
this.isSubsetLoadedLocally(requestOptions)
) {
return { demand, result: true, started: false }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
return { demand, result: initialResult.promise, started: false }
}
const syncRunGeneration = acquisition.syncRunGeneration
Expand Down Expand Up @@ -1312,6 +1389,14 @@ export class CollectionSubscription

emitEvents(changes: Array<ChangeMessage<any, any>>): boolean {
if (this.unsubscribed) return false
try {
return this.emitChanges(changes)
} finally {
this.reconcileHeldDeferredDemands()
}
}

private emitChanges(changes: Array<ChangeMessage<any, any>>): boolean {
const newChanges = this.filterAndFlipChanges(changes)

// Reconciliation can reduce a source delta to no visible change. Do not
Expand Down
5 changes: 5 additions & 0 deletions packages/db/src/collection/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import type {
ChangeMessageOrDeleteKeyMessage,
CleanupFn,
CollectionConfig,
IsSubsetLoadedFn,
LoadSubsetFn,
LoadSubsetOptions,
LoadSubsetRequestResult,
Expand Down Expand Up @@ -95,6 +96,7 @@ export class CollectionSyncManager<
private rejectPreload?: (error: unknown) => void
public syncCleanupFn: CleanupFn | null = null
public syncLoadSubsetFn: LoadSubsetFn | null = null
public syncIsSubsetLoadedFn: IsSubsetLoadedFn | null = null
public syncUnloadSubsetFn: ((options: LoadSubsetOptions) => void) | null =
null

Expand Down Expand Up @@ -484,6 +486,7 @@ export class CollectionSyncManager<

// Store unloadSubset function if provided
this.syncUnloadSubsetFn = syncRes?.unloadSubset ?? null
this.syncIsSubsetLoadedFn = syncRes?.isSubsetLoaded ?? null

// Validate: on-demand mode requires a loadSubset function
if (this.syncMode === `on-demand` && !this.syncLoadSubsetFn) {
Expand Down Expand Up @@ -1144,6 +1147,7 @@ export class CollectionSyncManager<
this.syncCleanupFn = null
this.syncLoadSubsetFn = null
this.syncUnloadSubsetFn = null
this.syncIsSubsetLoadedFn = null
this.abortLoadSubsetWork()
try {
const result = this.invokeCleanup(cleanup)
Expand Down Expand Up @@ -1191,6 +1195,7 @@ export class CollectionSyncManager<
this.syncCleanupFn = null
this.syncLoadSubsetFn = null
this.syncUnloadSubsetFn = null
this.syncIsSubsetLoadedFn = null

let cleanupResult: true | Promise<void> = true
let cleanupFailure: { error: unknown } | undefined
Expand Down
12 changes: 11 additions & 1 deletion packages/db/src/query/live/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1380,6 +1380,10 @@ If an explicit window operation consumes a staged boundary continuation and
that continuation has no boundary row, it starts no acquisition. The operation
must continue normal demand selection for the enlarged window; consuming the
empty continuation does not settle that window operation.
Pending joined demand holds a joined filter's ordered requests, its first
request included: the graph pass after that demand settles issues them. A
synchronous answer that stages a refill behind joined demand returns to its
caller and leaves the refill staged for that pass.
If joined demand blocks an explicit retry, the loader retains its window
generation and repair intent until it can select the request. A new failure or
cursor reset discards that blocked intent.
Expand Down Expand Up @@ -1682,7 +1686,13 @@ Collections already hold. A framework render or `startSync: true` may start the
live-query Collection's sync run; that is not a subscriber. An ordered window
over an on-demand source Collection stays unpublished until its acquisitions
settle, by atomic window publication; an unordered query publishes the rows its
source Collections hold as a partial result. Without a subscriber or preload,
source Collections hold as a partial result. A sync adapter's optional
`isSubsetLoaded` hook is a local statement that the Collection already holds a
subset: a deferred demand it answers `true` for settles at once, so its window
publishes those rows, and its acquisition still starts on resume. A demand
that becomes held later, by a status change, a peer's load or rows the source
pushes, settles the same way without starting acquisition. Without a
subscriber or preload,
the live-query Collection is ready only when it needs no provider work: every
source Collection is eager and already started, or is a live-query Collection
whose acquisitions settled. The first subscriber or preload resumes deferred
Expand Down
Loading