Repository navigation
fix(platform): stop subscribing every backend read to the session probe - #4067
Conversation
Every useBackendQuery called useSessionUser(), whose two useQuery calls put one observer per mounted read on ['backend','me','account','current-user'] and on ['auth','session']. An adapted read never uses that answer: the probe gates only the branch for a name with no adapter row. react-query removes an observer in time linear in its query's observer count, so a 2,000-card board held ~30,000 observers on each query and took ~20 s to unmount its cards on a search, a filter or leaving the board (#4062). - useSessionUser reads the probe alone and takes `subscribed`: `false` reads the cached answer without an observer (react-query's own option). The Better Auth session query it also held answers nothing it returns. - useBackendQuery subscribes only for a no-row read that is not skipped and keeps requireAuth; useActionQuery and useAutomationSettingsValues only on their no-row lane. The gate itself is unchanged. - session-probe-observers.test.tsx counts both queries' observers with a real QueryClient: flat as mounted reads grow, one for a gated read, and the gate still opens when the probe answers. It fails on e613264. Refs #4062
… isLoading From the self-review of d9212fb: - No test covered useAutomationSettingsValues: reverting it to a subscribed useSessionUser() passed every case. A case now reads its adapted lane and finds no probe observer; the revert fails it. - Unsubscribed, useSessionUser's isLoading reports the fetch a mount would start, which never comes. The option's doc now says to read isAuthenticated alone; every unsubscribed caller already does. Refs #4062
d9212fb kept an unsubscribed useQuery on the probe in every read. It joined no observer list, so unmounting stopped being quadratic, but every read still built an observer and a result on each render. On the 2,000-task board (fixture r3, three arms in balanced blocks against e613264 and #4062's experiment, n=6 each) that cost 971 MB of JS heap after a cold load against the experiment's 848 MB, and 21.3 s against 20.2 s to open the board in-app. - useSessionProbeSignedIn(when) reads the probe's cached answer only when its caller's branch gates on it. When it does, it re-renders on the probe's cache events through a QueryCache listener, which joins and leaves in constant time. With when false it reads and listens to nothing. It never fetches the probe, which useSessionUser at the app root keeps observed. - useBackendQuery, useActionQuery and useAutomationSettingsValues gate through it on their no-row lanes. useSessionUser loses its subscribed option and observes the probe alone, as before. - session-probe-observers.test.tsx also spies on QueryCache.subscribe, so a gate that listened per adapted read fails too. Eight mutants, each dropping or widening one condition, each fail a case. On e613264 the file fails 6 of 6. - use-backend-query.test.ts stubs the new hook in place of useSessionUser. Its assertions are unchanged. Refs #4062
From the second self-review of e6bc3ae: - The gate never fetched the probe and relied on the app root to keep it observed, where main.tsx's comment calls ColdLoadProbe dev-only. Its subscription now prefetches the probe, which fetches only when the answer is missing or stale, as a mounting observer would. A new case pins it, and dropping the prefetch fails that case. - The doc claimed constant time outright. Joining and leaving the listener set is constant time, but every cache event calls every listener, so the doc now says it suits rare callers: no shipped read lacks a row. It also says the answer is false when not asked. - useSyncExternalStore gets the same snapshot for the server render, as react-query's own useBaseQuery passes. - requireAuth's doc says the gate waits for the probe to hold a user, which is what it checks. Adapted reads are untouched: with when false none of this runs. Refs #4062
|
Independent review: accepted at
Verdict: the change is right, and it keeps the auth gate.
Local checks, on the exact head with synthetic data and no egress
CI at the exact head (merge ref
Non-blocking (P3), for follow-up
Not covered:
|
Refs #4062. This is slice 1 of 2: the quadratic unmount. Open, clear and cold load at 2,000 tasks stay with the per-card mount cost, which is a later slice. That is why this PR says Refs, not Closes.
Exact head:
f250d07242dbd88273eab6a3deec3af74d4fc60d, onmaine6132644f.The defect
Every
useBackendQuerycalleduseSessionUser(), and that ran twouseQuerys. So each mounted read put one observer on['backend','me','account','current-user'](the/users/mesession probe) and one on['auth','session'].An adapted read never uses that answer. The probe gates only the branch for a name with no adapter row, which rejects locally with
MissingBackendRowError.react-query adds and removes an observer in time linear in its query's observer count (
Query.addObserverscans withincludes;removeObserverusesincludes, thenfilter). A 2,000-card board held about 30,000 observers on each of the two queries. Unmounting its cards on a search, a filter or leaving the board took 20–28 s on this host.What changed
useSessionProbeSignedIn(when), new inapp/hooks/use-session-probe.ts, is the gate's read of the probe, and it adds no observer on any read.whenfalse, it reads nothing, fetches nothing and listens to nothing. It costsuseQueryClient, twouseCallbacks and auseSyncExternalStoreover module-level no-ops.whentrue, it reads the probe's cached answer and re-renders on the probe's cache events through a query-cache listener. It also prefetches the probe, which fetches only when the answer is missing or stale, as a mounting observer would.useBackendQuerynames and everyuseActionQueryname.useBackendQuerygates through it withwhen= no row, not skipped,requireAuth.useActionQueryuses no row, anduseAutomationSettingsValuesuses its unadapted lane. The gate's logic is unchanged.useSessionUser()observes the probe alone. It no longer also observes the Better Auth session query, whose answer it never returned.useAuth()is unchanged.Why not the first head's design.
d9212fb76passed react-query's ownsubscribed: false. That joined no observer list, but every read still built an observer object and a result on each render. In campaign 1, that cost +123 MB of heap after a cold load, and 1–2 s of mount, against #4062's experiment.e6bc3ae13replaced it, and campaign 2 brought the gap down to +32 MB.Finding → commit → test
All tests are in
app/hooks/session-probe-observers.test.tsx: a realQueryClient, a stubbed adapter registry, observer counts on both shared queries, andQueryCache.subscribeandprefetchQueryspied.d9212fb76, thene6bc3ae13useBackendQueryand auseActionQueryeach) keep 0 observers on both queries, take no cache listener and no prefetchd9212fb76,e6bc3ae13use-backend-query.test.ts, all assertions are unchanged, among them "gates on auth by default" and "requireAuth:false runs even when unauthenticated". Its stub moved fromuseSessionUserto the new hookrequireAuth:falseand'skip'read no probed9212fb76,e6bc3ae13useActionQueryhad the same patternd9212fb76,e6bc3ae13useAutomationSettingsValueshad the same pattern, with no test (review 1)7679122a6,e6bc3ae13useSessionUserheld the Better Auth session query tood9212fb76useQuerystill cost an observer object per read, measurede6bc3ae13f250d0724On
e6132644f, the file fails 6 of 6, without the hook's own cases. The first failure readsexpected { probe: 120, session: 120 } to deeply equal { probe: 2, session: 2 }.Mutants: nine one-condition mutants each fail a case:
useBackendQuerynever listening;when;!skippeddropped;requireAuthdropped;useSessionUser;Verification
CI at the exact head
f250d0724: 49 checks succeeded. The rest were 1 neutralTrivyand 12 skipped by design, which are not counted as success. The job logs showcache miss, executingfor:@tale/platform:test:ui: 565 files, 5,103 tests, the new file included;@tale/platform:test: server and pii;test:browser,typecheckandlint.Local, scoped, on a 2-CPU, 4 GiB box, so not the whole suite:
e6bc3ae13:bunx oxlint --type-awareon the 7 changed files: rc 0;bunx oxfmt --check: clean;tsc --noEmitover the changed files and the platform.d.tsfiles: 0 errors;bunx vitest run --maxWorkers=2: the 72 test files of every direct importer of the changed hooks, 676 tests, plus the 5app/routesimporters under--config vitest.ui.config.ts, 50 tests. All pass.f250d0724, which changes only the gated path and comments:Reviews: two read-only adversarial reviews by subagents, before the distinct reviewer. Neither found a high or medium issue. Their lows are fixed in
7679122a6andf250d0724, or listed under Behaviour notes.Performance
The kit: the TALE-361 replay kit. Every arm used the same stack:
SITE_URL=http://127.0.0.1:3453 bun run build) served byvite previewon :3453;ROLE=api,NODE_ENV=production, an inert no-egress preload) on its own Postgres 16.14 on :55453;seed-http.mjs+seed-tasks.ts, seed 361000 + size; "zebra" in 20 of 2,000 titles);The visible frame: for search, it is timed from the last key, including the 300 ms debounce. For open and leave, it is timed from the click.
Arms: in balanced blocks per flow,
base cand exp exp cand base, throughab3.shandbench2.mjs:e6132644f;e6132644f+ Bug: a 2,000-task board blocks the tab for 16–26 s when it is searched, left or opened #4062's candidate-a, which has no session subscription and no gate.Campaign 2 (cand =
e6bc3ae13; its adapted-read path is identical to the head's). Medians with min–max, 2,000 tasks, n=6:e6132644fe6bc3ae13At 50 tasks (n=8):
Campaign 2's first cand block of each 2,000-task flow ran under 0.75–1.27 CPU of external load, against 0.37–0.64 for the other blocks (
contention.py). Its second cand blocks: narrow 2.95–3.04 s, cold 26.2–28.7 s.Campaign 1 (cand =
d9212fb76, the unsubscribed-useQuerydesign), 2,000 tasks, n=6:d9212fb76At 50 tasks (n=8), open took 1.12, 1.08 and 1.03 s, and leave 275, 242 and 220 ms.
Campaign 3: the exact head
f250d0724againste6132644f, in ABBA blocks (ARMS="base cand cand base",LABEL_PREFIX=c3). Medians with min–max:e6132644ff250d0724At 50 tasks (n=8):
External CPU averaged 0.42–1.06 per block (
contention.py), above campaign 1's 0.35–0.45.Against #4062's targets
Search narrow and leave, ≤ 3 s (the target of this slice): leave meets it in all three campaigns: 2.74, 2.60 and 2.75 s. Narrow sits at the line:
d9212fb76in campaign 1;e6bc3ae13in campaign 2, where exp, with no gate at all, took 2.92 s;The design is within about 0.1 s of the experiment, and today's host ran slower than campaign 1's. What remains of the narrow is the 300 ms debounce plus unmounting 1,980 cards: React's unmount, and the per-card observers on org-level queries, which are 2,000² rather than 30,000². Slice 2's board-level reads remove that.
Open, clear and cold load, ≤ 10 s, and heap ≤ 600 MB: not met, and not in this slice's scope. They are 20–29 s, with a heap of 889 MB after a cold load. Cold load did not move outside noise.
50 tasks: in-app open was 1.08, 1.02 and 1.10 s in the three campaigns, below base each time (1.12, 1.12 and 1.21 s). The 1.10 s sample came under 0.6–1.1 CPU of external load.
TASK-P1(< 3 s at ~50 tasks) holds.Bundle: Cold-load JS reads 2,062 KB gzip against 2,059 KB, 44 modules in both. Rollup moved
use-session-userand the Better Auth client from the preloadedread-statechunk into the preloaded entry chunk. Recompressed atgzip -9, the two chunks together differ by 142 bytes.Concept sweep
useBackendQueryanduseActionQuery, plususeAutomationSettingsValueswith one instance. All three now gate through the new hook.useAuthanduseCurrentUsercallers are page or list level; none is per card or per read (review 2).ColdLoadProbe(useSessionUser) and the rootuseFileEvents→useAuth. The latter also keeps['auth','session']observed on every route.Behaviour notes
No refetch on mount: an adapted read no longer refetches a stale probe (older than 5 minutes) when it mounts. A session that ends on the server is then reported by the first stale read or write, through the same 401 seam, instead of by the next mount. The cached data on screen is the user's own (review 1).
Leftover mocks: six test files still mock
useSessionUserfor reads that are all adapted, so the mocks are harmless dead code:tasks-workspace.read-state;.read-failuretests ofdocuments-table,knowledge-entries-table,knowledge-entry-view-dialogandproject-files-tab;use-governance-policy-toggle.race.They are left for a later cleanup.
Improvement: open and close task dialogs in under a second on a 2,000-task board #3974: its dialog close on the same board rides the same multiplier, and its numbers should be rechecked after this.
Not changed
The per-card mount cost is #4062's cause 2:
useTranslationinstances;