From a39eed6c11a631f3da85ebf86c7115c38b54e18a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 24 Sep 2026 12:01:16 +0900 Subject: [PATCH] fix(query-cache): fence the scope only when session state or subject changes (R-3.2) Every session notification aborted in-flight requests, bumped the generation and cleared the cache, even when nothing changed. A repeated sign-out or a token-refresh notification wiped the cache, and with V3 calling onUnauthenticated() on a logged-out query it could loop. The scope runtime now reads (getState, getSubject) and skips a notification that leaves both unchanged. An identity it cannot prove unchanged still fences: a session without getState (old behavior), a throwing owner, or an authenticated session with no subject. A FAILED scope still retries its reset on any notification. To make the subject observable, SessionGateway gets an optional `getSubject?(): string | null` and ExternalSessionOwner an optional `readSubject?()` (additive; existing owners keep fencing on every authenticated notification). RED before fix: tests/unit/server-state-scope-runtime.test.ts "does not fence, abort or clear on a repeated sign-out" / "... on a token refresh for the same subject" saw FENCED. Pinned (passing before and after): "still fences when the state changes / the subject changes / an authenticated session cannot name its subject", "retries a failed reset ...". Gates: check:architecture, check:types:app, check:types:test, lint, test:component, test:integration, test:reference-feature pass. test:unit passes except removal-fixture.test.ts (needs generated artifacts/ release evidence absent in a fresh worktree; unrelated). Co-Authored-By: Claude Opus 5.5 --- src/adapters/auth/external-session-adapter.ts | 3 + .../query-cache/server-state-scope-runtime.ts | 40 ++++++- src/application/ports/auth-session-port.ts | 7 ++ tests/unit/server-state-scope-runtime.test.ts | 111 ++++++++++++++++++ 4 files changed, 160 insertions(+), 1 deletion(-) diff --git a/src/adapters/auth/external-session-adapter.ts b/src/adapters/auth/external-session-adapter.ts index 4089a83c..34e519ee 100644 --- a/src/adapters/auth/external-session-adapter.ts +++ b/src/adapters/auth/external-session-adapter.ts @@ -9,6 +9,8 @@ import { CREDENTIAL_HEADER_NAMES } from "../../contracts/rest-profiles.ts"; export type ExternalSessionOwner = Readonly<{ readState(): SessionState; + /** Opaque subject identifier; see `SessionGateway.getSubject`. */ + readSubject?(): string | null; subscribe(listener: () => void): () => void; beginSignIn(returnTo?: string): Promise; signOut(): Promise; @@ -53,6 +55,7 @@ export function createExternalAuthSessionAdapter( ): AuthSessionPort { return Object.freeze({ getState: () => owner.readState(), + getSubject: () => owner.readSubject?.() ?? null, subscribe: (listener) => owner.subscribe(listener), beginSignIn: (returnTo) => owner.beginSignIn(returnTo), signOut: () => owner.signOut(), diff --git a/src/adapters/query-cache/server-state-scope-runtime.ts b/src/adapters/query-cache/server-state-scope-runtime.ts index 8aea9da3..af25286f 100644 --- a/src/adapters/query-cache/server-state-scope-runtime.ts +++ b/src/adapters/query-cache/server-state-scope-runtime.ts @@ -24,7 +24,12 @@ export type ScopeResetParticipant = Readonly<{ }>; export type ServerStateScopeDependencies = Readonly<{ - session: Pick; + /** + * `getState`/`getSubject` let the runtime skip a notification that changes + * neither. Without `getState` every notification fences, as before. + */ + session: Pick & + Partial>; queryInvalidation: Pick; tokenFactory?: () => string; participants?: readonly ScopeResetParticipant[]; @@ -49,6 +54,7 @@ export function createServerStateScopeRuntime( let phase: ClientScopePhase = "READY"; let disposed = false; let resetChain = Promise.resolve(); + let sessionIdentity = readSessionIdentity(dependencies.session); function createSnapshot(): CacheScopeSnapshot { const capturedGeneration = generation; @@ -89,6 +95,18 @@ export function createServerStateScopeRuntime( const unsubscribe = dependencies.session.subscribe(() => { if (disposed) return; + // §10.6 is for identity-affecting changes only. A notification that keeps + // (state, subject) — a token refresh, a repeated sign-out — must not abort + // requests and clear the cache. A FAILED scope still retries its reset. + const nextSessionIdentity = readSessionIdentity(dependencies.session); + if ( + nextSessionIdentity !== null && + nextSessionIdentity === sessionIdentity && + phase !== "FAILED" + ) { + return; + } + sessionIdentity = nextSessionIdentity; const previousIdentities = identities; const previousGeneration = generation; @@ -185,6 +203,26 @@ export function createServerStateScopeRuntime( }); } +/** + * `null` means the identity cannot be proven unchanged: no `getState`, a + * throwing owner, or an authenticated session without a subject. Those always + * fence, which keeps an account switch from reusing the previous cache. + */ +function readSessionIdentity( + session: ServerStateScopeDependencies["session"], +): string | null { + try { + const state = session.getState?.(); + if (state === undefined) return null; + const subject = session.getSubject?.(); + const knownSubject = typeof subject === "string" ? subject : null; + if (state === "authenticated" && knownSubject === null) return null; + return JSON.stringify([state, knownSubject]); + } catch { + return null; + } +} + function newIdentityRegistry( tokenFactory: (() => string) | undefined, ): RuntimeIdentityRegistry { diff --git a/src/application/ports/auth-session-port.ts b/src/application/ports/auth-session-port.ts index 3a4d57f4..818b6bc5 100644 --- a/src/application/ports/auth-session-port.ts +++ b/src/application/ports/auth-session-port.ts @@ -6,6 +6,13 @@ export type SessionState = export type SessionGateway = Readonly<{ getState(): SessionState; + /** + * Optional opaque identifier of the signed-in subject. The server-state scope + * fences only when (state, subject) changes, so a token refresh does not clear + * the cache. An authenticated session that returns `null` or omits this is + * treated as possibly switched and still fences on every notification. + */ + getSubject?(): string | null; subscribe(listener: () => void): () => void; beginSignIn(returnTo?: string): Promise; signOut(): Promise; diff --git a/tests/unit/server-state-scope-runtime.test.ts b/tests/unit/server-state-scope-runtime.test.ts index ef182c91..f4654ba6 100644 --- a/tests/unit/server-state-scope-runtime.test.ts +++ b/tests/unit/server-state-scope-runtime.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import { createServerStateScopeRuntime } from "../../src/adapters/query-cache/server-state-scope-runtime.ts"; +import type { SessionState } from "../../src/application/ports/auth-session-port.ts"; import type { ClientScopeLifecycleEvent } from "../../src/contracts/server-state-scope.ts"; describe("server-state session generation runtime", () => { @@ -195,3 +196,113 @@ describe("server-state session generation runtime", () => { ); }); }); + +describe("identity-affecting session changes only", () => { + function fakeSession( + initial: Readonly<{ state: SessionState; subject?: string | null }>, + ) { + let current = initial; + let listener: () => void = () => {}; + return { + session: { + getState: () => current.state, + getSubject: () => current.subject ?? null, + subscribe(next: () => void) { + listener = next; + return () => {}; + }, + }, + notify(next: Readonly<{ state: SessionState; subject?: string | null }>) { + current = next; + listener(); + }, + }; + } + + function scopeFor(session: ReturnType["session"]) { + const resetLocal = vi.fn(async () => {}); + const lifecycle: ClientScopeLifecycleEvent[] = []; + let tokenSequence = 0; + const runtime = createServerStateScopeRuntime({ + session, + queryInvalidation: { resetLocal }, + tokenFactory: () => + `scope-identity-token-${String(tokenSequence++).padStart(6, "0")}`, + }); + runtime.subscribeLifecycle((event) => lifecycle.push(event)); + return { runtime, resetLocal, lifecycle }; + } + + it.each([ + ["a repeated sign-out", { state: "unauthenticated" as const }], + [ + "a token refresh for the same subject", + { state: "authenticated" as const, subject: "user-a" }, + ], + ])("does not fence, abort or clear on %s", async (_label, identity) => { + const fake = fakeSession(identity); + const { runtime, resetLocal, lifecycle } = scopeFor(fake.session); + const before = runtime.getSnapshot(); + + fake.notify(identity); + fake.notify({ ...identity }); + await Promise.resolve(); + + expect(lifecycle).toEqual([]); + expect(before.isCurrent()).toBe(true); + expect(before.signal.aborted).toBe(false); + expect(resetLocal).not.toHaveBeenCalled(); + expect(runtime.getPhase()).toBe("READY"); + }); + + it.each([ + [ + "the state changes", + { state: "unauthenticated" as const }, + { state: "authenticated" as const, subject: "user-a" }, + ], + [ + "the subject changes", + { state: "authenticated" as const, subject: "user-a" }, + { state: "authenticated" as const, subject: "user-b" }, + ], + [ + "an authenticated session cannot name its subject", + { state: "authenticated" as const }, + { state: "authenticated" as const }, + ], + ])("still fences when %s", async (_label, initial, next) => { + const fake = fakeSession(initial); + const { runtime, resetLocal, lifecycle } = scopeFor(fake.session); + const before = runtime.getSnapshot(); + + fake.notify(next); + + expect(before.isCurrent()).toBe(false); + expect(before.signal.aborted).toBe(true); + expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 }); + await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY")); + expect(resetLocal).toHaveBeenCalledOnce(); + }); + + it("retries a failed reset on a notification with the same identity", async () => { + const fake = fakeSession({ state: "unauthenticated" }); + const resetLocal = vi + .fn<() => Promise>() + .mockRejectedValueOnce(new Error("reset failed")) + .mockResolvedValue(undefined); + const runtime = createServerStateScopeRuntime({ + session: fake.session, + queryInvalidation: { resetLocal }, + tokenFactory: () => "scope-retry-token-0000001", + }); + + fake.notify({ state: "authenticated", subject: "user-a" }); + await vi.waitFor(() => + expect(runtime.getPhase() as string).toBe("FAILED"), + ); + fake.notify({ state: "authenticated", subject: "user-a" }); + await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY")); + expect(resetLocal).toHaveBeenCalledTimes(2); + }); +});