Skip to content

fix(platform): stop subscribing every backend read to the session probe - #4067

Merged
yannickmonney merged 4 commits into
mainfrom
fix/backend-read-session-observers
Oct 2, 2026
Merged

yannickmonney merged 4 commits into
mainfrom
fix/backend-read-session-observers

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

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, on main e6132644f.

The defect

Every useBackendQuery called useSessionUser(), and that ran two useQuerys. So each mounted read put one observer on ['backend','me','account','current-user'] (the /users/me session 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.addObserver scans with includes; removeObserver uses includes, then filter). 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 in app/hooks/use-session-probe.ts, is the gate's read of the probe, and it adds no observer on any read.
    • With when false, it reads nothing, fetches nothing and listens to nothing. It costs useQueryClient, two useCallbacks and a useSyncExternalStore over module-level no-ops.
    • With when true, 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.
    • Cost of the listener: joining and leaving the listener set takes constant time. Every cache event calls every listener, though, so it suits rare callers only. No shipped read lacks a row; the second review checked all 126 literal useBackendQuery names and every useActionQuery name.
  • useBackendQuery gates through it with when = no row, not skipped, requireAuth. useActionQuery uses no row, and useAutomationSettingsValues uses 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. d9212fb76 passed react-query's own subscribed: 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. e6bc3ae13 replaced 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 real QueryClient, a stubbed adapter registry, observer counts on both shared queries, and QueryCache.subscribe and prefetchQuery spied.

Finding Commit Test
Every adapted read held an observer on both shared session queries, so add and remove were O(observers) d9212fb76, then e6bc3ae13 "adapted reads leave no observer…": 1 → 60 mounted cards (a useBackendQuery and a useActionQuery each) keep 0 observers on both queries, take no cache listener and no prefetch
The missing-row auth gate stays, and stays reactive d9212fb76, e6bc3ae13 "a read with no adapter row still waits for the probe, then refuses by name once it answers a user". In use-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 from useSessionUser to the new hook
requireAuth:false and 'skip' read no probe d9212fb76, e6bc3ae13 "requireAuth:false and a skipped read take no probe subscription"
useActionQuery had the same pattern d9212fb76, e6bc3ae13 "an action read with no row gates on the probe; an adapted one does not subscribe"
useAutomationSettingsValues had the same pattern, with no test (review 1) 7679122a6, e6bc3ae13 "the automation settings read takes no probe subscription on its adapted lane"
useSessionUser held the Better Auth session query too d9212fb76 "useSessionUser observes the probe alone…"
An unsubscribed useQuery still cost an observer object per read, measured e6bc3ae13 "useSessionProbeSignedIn follows the probe only when asked", plus the campaign 2 table below
The gate relied on the app root to fetch the probe (review 2) f250d0724 "a gated read asks for a probe nothing has fetched yet"

On e6132644f, the file fails 6 of 6, without the hook's own cases. The first failure reads expected { probe: 120, session: 120 } to deeply equal { probe: 2, session: 2 }.

Mutants: nine one-condition mutants each fail a case:

  • each hook always listening;
  • useBackendQuery never listening;
  • the hook ignoring when;
  • !skipped dropped;
  • requireAuth dropped;
  • the session query back in useSessionUser;
  • the prefetch dropped.

Verification

CI at the exact head f250d0724: 49 checks succeeded. The rest were 1 neutral Trivy and 12 skipped by design, which are not counted as success. The job logs show cache miss, executing for:

  • @tale/platform:test:ui: 565 files, 5,103 tests, the new file included;
  • @tale/platform:test: server and pii;
  • test:browser, typecheck and lint.

Local, scoped, on a 2-CPU, 4 GiB box, so not the whole suite:

  • At e6bc3ae13:
    • bunx oxlint --type-aware on the 7 changed files: rc 0;
    • bunx oxfmt --check: clean;
    • a scoped tsc --noEmit over the changed files and the platform .d.ts files: 0 errors;
    • bunx vitest run --maxWorkers=2: the 72 test files of every direct importer of the changed hooks, 676 tests, plus the 5 app/routes importers under --config vitest.ui.config.ts, 50 tests. All pass.
  • At f250d0724, which changes only the gated path and comments:
    • the three hook test files, 27 tests: pass;
    • oxlint: rc 0;
    • the scoped tsc: 0 errors.

Reviews: two read-only adversarial reviews by subagents, before the distinct reviewer. Neither found a high or medium issue. Their lows are fixed in 7679122a6 and f250d0724, or listed under Behaviour notes.

Performance

The kit: the TALE-361 replay kit. Every arm used the same stack:

  • a production build (SITE_URL=http://127.0.0.1:3453 bun run build) served by vite preview on :3453;
  • the real backend on :3457 (ROLE=api, NODE_ENV=production, an inert no-egress preload) on its own Postgres 16.14 on :55453;
  • the deterministic fixture r3 (seed-http.mjs + seed-tasks.ts, seed 361000 + size; "zebra" in 20 of 2,000 titles);
  • Playwright with Chromium 141.0.7390.37, headless, 1440×900;
  • GC forced before each sample.

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, through ab3.sh and bench2.mjs:

Campaign 2 (cand = e6bc3ae13; its adapted-read path is identical to the head's). Medians with min–max, 2,000 tasks, n=6:

base e6132644f cand e6bc3ae13 exp
Search narrow (to 20 cards) 22.6 s (17.9–29.1) 3.04 s (2.95–3.33) 2.92 s (2.78–3.15)
Leave (click General) 27.9 s (19.7–32.0) 2.60 s (2.49–3.56) 2.99 s (2.45–3.32)
Clear search (back to 2,000) 22.2 s (20.7–24.4) 20.3 s (19.3–22.0) 20.1 s (19.0–20.8)
Open in-app (click Tasks) 26.2 s (25.1–27.2) 20.7 s (20.0–21.8) 21.1 s (20.2–25.2)
Cold load 27.4 s (26.2–28.2) 28.7 s (26.2–30.2) 26.6 s (24.6–26.9)
JS heap after cold load 1,063 MB 889 MB 857 MB
react-query observers, full board 94,175 34,084 34,091

At 50 tasks (n=8):

  • in-app open: 1.12 s (1.06–1.31) for base, 1.02 s (0.90–1.27) for cand, 1.03 s (0.94–1.20) for exp;
  • leave: 262 ms, 239 ms and 222 ms.

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-useQuery design), 2,000 tasks, n=6:

base cand d9212fb76 exp
Search narrow 24.3 s (23.1–25.7) 2.72 s (2.52–2.99) 2.77 s (2.63–10.0)
Leave 27.3 s (23.4–31.0) 2.74 s (2.56–3.66) 2.77 s (2.40–4.96)
Clear 20.0 s (18.8–44.3) 18.2 s (18.0–19.5) 19.2 s (17.7–58.3)
Open in-app 24.9 s (23.7–25.8) 21.3 s (20.6–22.7) 20.2 s (19.1–21.6)
Cold load 29.0 s (27.4–31.9) 27.6 s (25.5–30.4) 25.7 s (24.0–26.1)
JS heap after cold load 1,060 MB 971 MB 848 MB

At 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 f250d0724 against e6132644f, in ABBA blocks (ARMS="base cand cand base", LABEL_PREFIX=c3). Medians with min–max:

2,000 tasks base e6132644f head f250d0724
Search narrow, n=6 25.7 s (23.9–29.2) 3.02 s (2.73–3.57)
Leave, n=4 23.9 s (18.9–26.3) 2.75 s (2.37–3.08)
Clear search, n=6 22.1 s (21.4–47.6) 19.6 s (18.6–20.2)
Open in-app, n=4 25.7 s (25.2–28.8) 21.3 s (19.8–22.6)
react-query observers, full board 94,175 34,084

At 50 tasks (n=8):

  • in-app open: 1.21 s (1.02–1.38) for base, 1.10 s (0.94–1.31) for the head;
  • leave: 272 ms and 266 ms.

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:

    • 2.72 s for d9212fb76 in campaign 1;
    • 3.04 s for e6bc3ae13 in campaign 2, where exp, with no gate at all, took 2.92 s;
    • 3.02 s for the exact head in campaign 3.

    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-user and the Better Auth client from the preloaded read-state chunk into the preloaded entry chunk. Recompressed at gzip -9, the two chunks together differ by 142 bytes.

Concept sweep

  • Hooks: the only per-instance subscribers to the two shared queries were useBackendQuery and useActionQuery, plus useAutomationSettingsValues with one instance. All three now gate through the new hook.
    • useAuth and useCurrentUser callers are page or list level; none is per card or per read (review 2).
    • Still observing the probe: the root ColdLoadProbe (useSessionUser) and the root useFileEvents → useAuth. The latter also keeps ['auth','session'] observed on every route.
  • Security: the client gate is not a security boundary. A read with no row rejects locally and sends nothing. Adapted reads were never gated, and the server authenticates every read by its session cookie.
  • Accessibility, locales, docs, migrations: none. There is no UI, no string, no user docs and no schema change; code comments were updated.

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 useSessionUser for reads that are all adapted, so the mocks are harmless dead code:

    • tasks-workspace.read-state;
    • the .read-failure tests of documents-table, knowledge-entries-table, knowledge-entry-view-dialog and project-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:

  • two actor directories, whose org-level queries still get one observer per card, which is 2,000² rather than 30,000²;
  • the automation listings;
  • about 20 useTranslation instances;
  • eagerly built picker options;
  • no windowing.

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
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Independent review: accepted at f250d07242dbd88273eab6a3deec3af74d4fc60d

  • Reviewer: Tale agent update dashboard ui (#508) #2 3f9fdcee-79e7-430b-a430-ba179d5b5132, run de4b44e2-7238-4166-bf5f-b555bb502cad (TALE-359 review-merge occurrence, 2026-10-02 09:45 Europe/Zurich).
  • Implementation: agent optimize rag action #4 5f5307c9-4cbd-416a-a456-8bb667fc584d, run 8b674941-5daa-4469-aa5b-db3fc5a8ddc4 (TALE-453). The reviewer is distinct.
  • The head: the one named in the handoff, 4 commits on e6132644f. A read-only review agent mapped every consumer of the two shared queries in parallel; I re-checked what I cite.

Verdict: the change is right, and it keeps the auth gate.

  • Each hook asks for the probe exactly on the branch that reads it. That is the no-row branch, which main already confined the gate to.
  • After the PR, no route loses its last observer of either query. The probe keeps ColdLoadProbe and FileEventsListener at the root, and the session keeps FileEventsListener through useAuth. So GC, reconnect and the invalidateAuthState refetches behave as before.
  • Session-lapse detection still comes from the fetch seam's 401s.

Local checks, on the exact head with synthetic data and no egress

  • Unit: the new file passes 8/8, and with use-backend-query.test.ts and use-session-user.test.ts, 27/27.

  • Negative control: with main's four hook files under the new test, 7 of 8 fail on observer counts or the missing prefetch. The one that passes tests the new hook alone.

  • Mutants: 15 one-change mutants, 11 killed. The 4 that survive are P3 item 1 below.

  • Real Chromium, on a production build with a local backend and Postgres, comparing this head with the same build using main's four hook files (ABBA, n=3 visits each):

    600-task board base head
    Observers on probe / session 9,055 / 9,054 11 / 7
    Leave (click General), visible frame 3.67 s (3.19–5.88) 0.83 s (0.70–1.34)
    Search narrow, visible frame 333 ms 339 ms
    Search narrow, blocking long task after it 3.30 s (1.90–4.21) 0.61 s (0.57–1.05)
    Clear, blocking 6.2 s 5.6 s
    • The narrow's visible frame sits at the 300 ms debounce in both arms, because React paints the filtered list before the passive cleanup runs. The page then stays blocked for that long task.
    • An earlier ABBA round without the long-task probe gave the same direction: leave 2.47 s → 0.69 s.
    • Clear is unchanged: mounting cards is slice 2.
    • No page errors and no 4xx in any visit.
  • Session lapse, both arms: the session was signed out from a second client, then I made a client-side navigation. "Your session has ended" showed after about 0.45 s, through the reads' own 401s (/api/app/teams) and the get-session recheck.

CI at the exact head (merge ref 438d5d1, onto 62df44379)

  • Workflows: all five succeeded: Checks 36972459069, Build 36972459051, E2E 36972459067, SAST 36972459097 and Commitlint 36972459043.
  • Tally: 49 checks succeeded.
  • Executed, not replayed: platform test (997 files), test:ui (565 files, 5,103 tests), test:browser (43 files, 307 tests), typecheck and lint.
  • Not counted as success: 1 neutral Trivy, and 12 skipped by design:
    • 5× Candidate gate;
    • Backend integration, out of scope for an app-only change;
    • the AI gateway, Docs, UI docs and Web container tests, by path filter;
    • the 2 fork-PR jobs.
  • Since that run: main gained feat(platform): let project agents triage task metadata #4072 (bb6095205) and fix(platform): treat an embedding 429 as a rate limit, pace and retry it #4071 (9b91fb64a). They share no file with this PR and change no build input. Their only app files are the skills menu and the websites scan-error lib, and git merge-tree is clean.

Non-blocking (P3), for follow-up

  1. Unpinned branches. These one-change mutants pass every case:

    • snapshot = read even when not asked: "false when not asked" holds only because the quiet hook mounts while the probe is null;
    • subscribe returning () => {}: a gated read that leaks its cache listener on unmount;
    • the listener ignoring the probe's hash;
    • useAutomationSettingsValues never gating its unadapted lane. That lane is unreachable today.

    Seeding a user before the quiet mount and asserting getQueryCache().hasListeners() is false after unmount would pin the first two.

  2. Robustness. The cache listener isn't wrapped in notifyManager.batchCalls, as react-query's own useIsFetching is. No failing case was found.

  3. The gate's cache lifetime rests on root observers. It holds none of its own, and a GC'd probe reads signed out until a remount.

    • One of those observers is ColdLoadProbe. Its doc (main.tsx:44-45) still says "Dev-only probe … the one request every auth-gated read waits on", and both halves are now wrong.
    • The hook's "(as a mounting observer would)" overstates too: an observer also keeps the query and refetches on reconnect.
  4. Comment and naming nits.

    • use-backend-query.ts:117-118 says "resolves", while the doc says "holding a user".
    • use-session-probe.ts:14-15 says only removal is linear, but adding is too.
    • use-settings-values.ts:77-79 still talks of a Convex socket.
    • The local isAuthenticated in useBackendQuery reads false for every adapted read; gateOpen would be safer.
  5. More dead useSessionUser mocks than the six named.

    • Also in user-button.test.tsx, dashboard-layout.test.tsx (whose "drives both" comment is now wrong), dashboard-shell.browser.test.tsx, account-form.name.test.tsx, account-form.password.test.tsx and forced-change-password.test.tsx.
    • No assertion became vacuous: every read in those trees has a row.
  6. Pre-existing, now a little more visible. users/mutations:updateUserName (settings.ts:1276-1281) invalidates nothing. A renamed user's probe answer now refreshes only when a probe observer mounts, or after the 5-minute stale window. Before, any read mounting after that window also refreshed it. Invalidating currentUserQuery in that row would fix it.

Not covered:

  • I did not repeat the 2,000-task campaign; the table above is my own 600-task A/B.
  • The app's default staleTime is 5 minutes (router.tsx:39), not 0. So "a read no longer refetches a stale probe" only concerns probes older than that.
  • No production contact.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant