Repository navigation
feat(query-core)!: gc at latest removal time - #12680
benjavicente wants to merge 1 commit into
Conversation
🦋 Changeset detectedLatest commit: d878934 The changes in this PR will be included in the next version bump. This PR includes changesets to release 25 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the
|
|
View your CI Pipeline Execution ↗ for commit d878934
☁️ Nx Cloud last updated this comment at |
🎯 Changes
Schedules garbage collection at the latest removal time any user of a query or mutation has been promised, instead of after the largest or latest
gcTime. See this discussion.gcTime)gcTime5 min) becomes inactivegcTime1 min) becomes inactivequery.gcTimeandmutation.gcTimeare removed.File order in Github is incredibly annoying for this change: Removable should be reviewed first, then the 2 observers, then query and mutation, and finally tests.
🤖 Agents summary and details: implementation, breaking changes, verification
Changes
Removablenow remembers when an entry may be garbage collected, instead of thelargest
gcTimeit has seen. When severalgcTimevalues apply to one entry, thelatest removal time wins, instead of the largest
gcTime.RemovablegcTimefield andupdateGcTime.updateGcTimestamp(gcTime). It applies the defaultgcTime(5 minutes on theclient,
Infinityon the server) and keepsmax(previous, performance.now() + gcTime)in a private
#gcAt. ANaNis ignored, so it can't make#gcAtNaNfor good.scheduleGc(gcTime)now takes thegcTime: it records it, then sets its timeout forthe time left until
#gcAt, clamped at 0. Taking the value means a removal time isalways recorded before scheduling. As before, nothing is scheduled when that time is
Infinity.performance.now()clock, notDate.now(). Changingthe system clock doesn't move them, as with the plain timers used before.
QueryandMutationsetOptionsno longer touches garbage collection.removeObserver(observer, gcTime)records thegcTimethe observer passes, every timean observer leaves. The observer passes the one from its defaulted options. The
argument is required: with a default parameter, passing an
undefinedgcTimewould silently fall back to the observer's current options. On observer removal,
Queryschedules gc only when no observers are left.Mutationschedules it on everyremoval, as before; in practice a mutation only ever has the one observer that created
it.
the pending mutation reschedule use the current
options.gcTime. The end of a queryfetch uses the
gcTimefrom the options captured when that fetch started, because anobserver may replace the query's options while it runs.
QueryObserverandMutationObservergcTimefrom its previous options toremoveObserver. The observer replaces itsoptions before it leaves the old entry, so without this the old entry would get the
new key's
gcTime.MutationObserverdoes this through a private#reset(gcTime),which the public
reset()also uses with its currentgcTime.Motivation
Discussion: #12669 (comment)
With "largest
gcTimewins", one longgcTimesticks to the entry forever, even afterevery observer that asked for it is gone. With "latest
gcTimewins", a later shortgcTimecould cut short a longer one that was already promised. Taking the latestremoval time avoids both problems: an entry is never collected before any time it was
promised, and an old long finite
gcTimedoes not stay around once that time haspassed.
Infinitystill keeps an entry forever, as before.query.gcTimeandmutation.gcTimeare removed. They were public fields on theexported
QueryandMutationclasses (throughRemovable). Readquery.options.gcTimeormutation.options.gcTimeinstead. Note that those are theentry's own options, not the effective time. Nothing in
packages/*/srcreads thefield; earlier tests did, and users or devtools-like tooling may.
Query.removeObserverandMutation.removeObservernow require the leavingobserver's
gcTimeas a second argument. Both are marked@internal.gcTimevalues apply. Before, thelargest
gcTimeever passed tosetOptionswas used. Now the latest removal timerecorded wins:
gcTimefrom an earlier observer only counts while its removal time is stillin the future.
gcTimethat comes later can't bring the removal earlier.time has passed. Subscribing again only clears the timer; it doesn't reset the removal
time. For example: A unsubscribes with a
gcTimeof 5 min (removal at 5:00), thensubscribes again with a
gcTimeof 1 min and unsubscribes at 1:00. The removal staysat 5:00. Before this change it was 6:00, because 5 min was still the largest
gcTime. Resetting on subscribe would give 2:00, which would let a short mount pullan earlier promise forward.
scheduleGc(gcTime)records itsgcTimebeforescheduling, so removal is never earlier than now plus the current
gcTime.gcTimeat the moment it unsubscribes is what's recorded. AgcTimepassed toqueryClient.query()counts for the removal time recorded when thatfetch settles. It no longer raises the time applied when an observer unsubscribes
later. The same goes for mutations: if a
MutationObserver'sgcTimechanges whileits mutation is idle, the new value is what's recorded when it leaves. Before, an idle
mutation kept the
gcTimefrom its last options. This is the only case where removalcan now happen later than before.
Open questions
NaNgcTimeadds no removal time. The entry is then removed at the latest validremoval time recorded before, or right away if there is none or it has passed. Before,
a
NaNgcTimemeant no gc was scheduled until a later validgcTimereplaced it.Both are invalid input.
gcAt, be exposed for devtools in place of the removedgcTime?pages for
Query/Mutationstill listgcTime. CONTRIBUTING says not to rungenerate-docsin a PR, because the docs re-sync after merge. Onquery-v6it alsorewrites about 1400 unrelated files.
Pitfalls for alternative implementations
Found while building and reviewing this change. They're worth checking in any other way
of storing gc state:
QueryObserver.setOptionssetsthis.optionsbefore#updateQuery()detaches itfrom the previous query, and
MutationObserver.setOptionsdoes the same before itresets. Reading
observer.options.gcTimeinsideremoveObservergives the old entrythe new key's
gcTime, so the previousgcTimehas to be passed in.gcTime. An observer whose previousoptions had no
gcTimepassesundefined, which triggers the default, and that readsthe new options again.
gcTimeit started with. An observer can callquery.setOptionswhile a fetch is in flight, sothis.optionsat settle time maybelong to someone else. Use the options captured for the fetch.
#gcAtstarts at 0, soscheduling without recording removes the entry right away. A pending mutation that
reschedules without recording would loop on 0 ms timers.
nothing is scheduled yet. Otherwise its longer
gcTimeis lost when a shorter oneleaves last.
Date.now(), a system clock change moves removaltimes; a large backwards jump even overflowed
setTimeout(over 2³¹ ms) and firedafter about 1 ms. Plain timers never had this, because they only count elapsed time.
performance.now()is available in browsers, Node, React Native and Workers.NaNsticks throughMath.max, so it has to be filtered before it reaches thestored time. Returning early from the scheduler on
NaNinstead also cancels aremoval that was already scheduled.
Infinitysticks forever. That's the same as before, and it is what makes theserver default work.
MutationObserverthat built themutation with
mutate(). Removing it leaves no observers.performance.now()gives fractional delays, which timers truncate, so removal canhappen up to 1 ms before the promised time. This is accepted.
performance. Vitest's default fake timers do. AtoFakelistthat only fakes timers and
Dategives misleading timelines.✅ Verification
New test in
query.test.tsx: observer A (gcTime5 min) unsubscribes at 0:30, andobserver B (
gcTime1 min) unsubscribes at 1:30. The query is still cached at 2:30and at 5:29.999, and it is removed at 5:30. A unsubscribes 30 seconds in, so the test
also catches A's removal time not being recorded; the query was created at 0:00 with
A's
gcTime. The table shows the same case shifted to start at 0:00:With the production changes reverted (
query-v6as is), this test fails at thefinal assertion, because the query is still cached at 5:30 (it is removed at 6:30).
With the changes, it passes.
Key-switch tests, one in
query.test.tsxand one inmutationObserver.test.tsx. Anobserver with
gcTime1000 switches to another key withgcTime: Infinity, and theold entry must be removed after 1000 ms. Both pass on
query-v6, where the old entrynever saw the new options. They fail on the first version of this change, where the
old entry got the new key's
Infinity, and pass with the observer fix.Fetch test in
query.test.tsx: an existing query withgcTime10 is fetched withqueryClient.query({ gcTime: 1000 }), and an observer withgcTime10 subscribeswhile the fetch runs. The query must be kept until 1000 ms after the fetch settles.
It fails when the end of the fetch reads the query's current options, and passes
when it uses the options captured for the fetch.
Other new tests in
query.test.tsxandmutationObserver.test.tsx:queryClient.query()fetch stays when alater fetch records an earlier one. This fails on
query-v6, where the largestgcTimerestarts from the second fetch.after it settles: it settles at 45 ms and is collected at 50 ms with
gcTime: 10.This passes on
query-v6too.Updated tests:
removable.test.tsxnow coversupdateGcTimestampandscheduleGc(gcTime):after;
NaNgcTimebeing ignored, and not discarding an earlier removal time.query.test.tsx: the server test now checks that the query is still cached after24h, instead of reading
query.gcTime.query.test-d.tsx/mutation.test-d.tsx:gcTimeis dropped from the publicmember lists, along with the
mutation.gcTimetype test. TheremoveObserverparameter types now include the
gcTimeargument.query-core:vitest rungives 44 files and 1626 tests passed, with no type errors.test:types(TS 5.7 to 7.1),test:oxlint,oxfmt --checkandgit diff --checkare clean.
react-querypassed 38 files and 654 tests, andpreact-querypassed 35 files and 570tests, both including type tests.
Three review passes, by Claude Opus 5.5 and GPT-6.1 Sol. Their findings are fixed, or
listed under "Pitfalls for alternative implementations" above.
Not run: the full
pnpm run test:pr, and the other adapters.Size limit comparison: pending (needs Preview CI on the PR).
✅ Checklist
pnpm run test:pr, or these tests do not apply to this pull request (there are red checks in devtools that are unrelated)🚀 Release Impact