From ac98facd16ba501d79de7a38379b9354eedbe460 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 19 Nov 2026 11:49:34 +0900 Subject: [PATCH 1/2] =?UTF-8?q?fix(cross-context-invalidation):=20?= =?UTF-8?q?=EB=93=A3=EA=B8=B0=20=EC=A0=84=EC=97=90=20localStorage=EB=A5=BC?= =?UTF-8?q?=20=EC=9D=BD=EC=96=B4=20pulse=EB=A5=BC=20=EC=9E=83=EC=A7=80=20?= =?UTF-8?q?=EC=95=8A=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: Chromium은 탭의 첫 localStorage 읽기에서 그 탭의 캐시를 채우며 변경 observer를 새로 건다(Blink CachedStorageArea::EnsureLoaded). 이때 이미 도착했지만 아직 처리하지 않은 다른 탭의 변경 알림은 버려진다. storage fallback의 pulse는 쓰자마자 지우므로 채운 캐시에도 흔적이 없어, 받는 탭은 그 무효화를 영영 받지 못한다. browser-capabilities 시험 「falls back to native localStorage events」가 runner run 371과 desktop 부하 20회 중 1회에서 이렇게 실패했다(받은 deliveries []). 받는 page가 바쁠 때 그 page의 첫 읽기(발행 직후의 snapshot, 또는 앱 부트의 설정 읽기)가 쌓인 알림보다 먼저 돌았다. 제품에서도 탭의 다른 코드가 처음 읽는 순간 같은 창이 열린다. 고친 방법: host가 잡은 localStorage를 storage 리스너를 걸기 전에 한 번 읽는다(getItem). 그 뒤의 읽기는 캐시를 다시 채우지 않으므로 observer가 바뀌지 않는다. 읽기가 거절되는 host에서도 리스너는 그대로 건다. 버린 대안: - 시험만 고치기(발행 전에 받는 page에서 한 번 읽기): 제품의 같은 창을 남긴다. - poll 시한 늘리기: 늦는 것이 아니라 잃는 것이라 소용없다. 위험·한계: 런타임을 만들 때 그 origin의 localStorage 전체를 renderer로 한 번 읽는다(Chromium sync GetAll). 앱이 이미 localStorage를 쓰면 추가 비용이 없다. storage service가 다시 연결될 때(ResetConnection)의 손실은 다루지 않는다. 받는 page가 바쁜 동안 다른 탭의 cookie 변경을 보는 것은 Chromium뿐이라, 새 브라우저 시험은 Chromium에서만 받는 page를 붙잡는다. 새 시험은 앱 없는 같은 origin 빈 문서에서 돈다. 앱 부트가 먼저 읽어 받는 탭을 채우면 캐시 채우기를 빼도 통과하기 때문이다. 검증(desktop, scripts/verify.sh exec, 트리 ddda30a3): - node scripts/run-vitest.ts run tests/unit/cross-tab-invalidation.test.ts 21 통과 - playwright cross-context-invalidation.spec.ts --repeat-each 5, 3엔진: 45 통과 - 변이(캐시 채우기 호출 제거, 트리 2f460282): 새 단위 시험 실패, 새 브라우저 시험 chromium 5/5 실패, 나머지 40 통과 - 고치기 전 탐침(main f3de258d): 받는 page가 막힌 사이 발행하고 같은 작업에서 첫 읽기 → chromium 5/5 실패, firefox·webkit 10/10 통과. 리스너 전에 한 번 읽게 한 대조는 15/15 통과 Refs: runner run 371 merge / browser tests --- .../browser-cross-context-host.ts | 22 +++ .../cross-context-invalidation.spec.ts | 138 ++++++++++++++++++ tests/unit/cross-tab-invalidation.test.ts | 135 +++++++++++++++++ 3 files changed, 295 insertions(+) diff --git a/src/adapters/cross-context-invalidation/browser-cross-context-host.ts b/src/adapters/cross-context-invalidation/browser-cross-context-host.ts index 62f6f2d8..913d1b6b 100644 --- a/src/adapters/cross-context-invalidation/browser-cross-context-host.ts +++ b/src/adapters/cross-context-invalidation/browser-cross-context-host.ts @@ -97,6 +97,7 @@ export function createBrowserCrossContextInvalidationFromHost( } const capturedLocalStorage = captureLocalStorage(host); + primeStorageCache(capturedLocalStorage); return createBrowserCrossContextInvalidation({ channelName: CHANNEL_NAME, @@ -233,6 +234,27 @@ function captureLocalStorage( return candidate && typeof candidate === "object" ? candidate : undefined; } +/** + * 2026-11-19. Chromium loads a tab's localStorage cache on the tab's first + * read, and that load replaces the change observer: change notifications from + * other tabs that have arrived but not run yet are dropped + * (`CachedStorageArea::EnsureLoaded` in Blink). A pulse is written and removed + * at once, so the loaded cache holds no trace of it and this tab never gets + * its `storage` event. Any later first read in the tab (a preference, another + * adapter) would open that window, so the runtime reads once before it starts + * listening. Best-effort: a host that refuses the read keeps the listener. + */ +function primeStorageCache(candidate: object | undefined): void { + if (!candidate) return; + const getItem = safeGet(candidate as Record, "getItem"); + if (typeof getItem !== "function") return; + try { + Reflect.apply(getItem, candidate, [STORAGE_PULSE_KEY]); + } catch { + // A refused read leaves the cache cold; the listener is still installed. + } +} + function storageFacade( candidate: object, ): StoragePulseFacade | undefined { diff --git a/tests/browser-capabilities/cross-context-invalidation.spec.ts b/tests/browser-capabilities/cross-context-invalidation.spec.ts index bdead72e..38dbfa22 100644 --- a/tests/browser-capabilities/cross-context-invalidation.spec.ts +++ b/tests/browser-capabilities/cross-context-invalidation.spec.ts @@ -288,3 +288,141 @@ test("falls back to native localStorage events and removes the pulse during clea await secondPage.close(); } }); + +// 2026-11-19, runner run 371. Chromium loads a tab's localStorage cache on the +// tab's first read, and the load drops the change notifications from other +// tabs that have arrived but not run yet (Blink CachedStorageArea::EnsureLoaded). +// A pulse is removed as soon as it is written, so the test above lost it when +// the receiver was busy as the pulse arrived and the receiver's first read (the +// snapshot, or the app's boot reading a preference) ran before the queued +// notifications. Here the receiver stays busy until the publisher is done and +// then reads localStorage for the first time in the same task, as other code +// in the tab would. Only Chromium lets a busy page see another tab's cookie +// change, so only there does the receiver wait for the publisher's cookie; the +// other engines read at once and check the same delivery. +// +// Both pages are a blank same-origin document, not the app: the app's boot +// reads localStorage on its own schedule, and a read before the test's would +// prime the receiver whether or not the runtime does. +const BLANK_DOCUMENT_PATH = "/__cross-context-capability-blank"; + +async function gotoBlankDocument(target: Page): Promise { + await target.route(`**${BLANK_DOCUMENT_PATH}`, (route) => + route.fulfill({ + contentType: "text/html", + body: 'cross-context capability', + }), + ); + await target.goto(BLANK_DOCUMENT_PATH); +} + +test("keeps a pulse that reaches a busy receiver before other code first reads localStorage", async ({ + page, + browserName, +}) => { + const secondPage = await page.context().newPage(); + const cacheEpoch = `browser.busy.${Date.now()}`; + const signal = `cross-context-busy-${Date.now()}`; + try { + await Promise.all([ + gotoBlankDocument(page), + gotoBlankDocument(secondPage), + ]); + await page.evaluate( + (pulseKey) => localStorage.removeItem(pulseKey), + STORAGE_PULSE_KEY, + ); + const statuses = await Promise.all([ + installRuntime(page, "STORAGE", cacheEpoch), + installRuntime(secondPage, "STORAGE", cacheEpoch), + ]); + expect(statuses).toEqual([ + "ACTIVE_STORAGE_FALLBACK", + "ACTIVE_STORAGE_FALLBACK", + ]); + + // The publisher publishes as soon as the receiver says it is busy, then + // sets the cookie the busy receiver waits for. + await page.evaluate( + ({ currentSignal, stateKey, topic, topicVersion }) => { + const state = Reflect.get(globalThis, stateKey) as { + runtime: { + publish(input: { topic: string; topicVersion: number }): unknown; + }; + published?: Promise; + }; + const channel = new BroadcastChannel(currentSignal); + state.published = new Promise((resolve) => { + channel.addEventListener( + "message", + () => { + channel.close(); + const result = state.runtime.publish({ topic, topicVersion }); + document.cookie = `${currentSignal}=published; path=/`; + resolve(result); + }, + { once: true }, + ); + }); + }, + { + currentSignal: signal, + stateKey: STATE_KEY, + topic: TOPIC, + topicVersion: TOPIC_VERSION, + }, + ); + const firstRead = secondPage.evaluate( + ({ currentSignal, holdBusy }) => { + const channel = new BroadcastChannel(currentSignal); + channel.postMessage("busy"); + if (holdBusy) { + // The publisher's cookie ends the wait. The guard only turns a + // publisher that never answers into a message before the test + // timeout. + const guard = performance.now() + 20_000; + while (!document.cookie.includes(`${currentSignal}=published`)) { + if (performance.now() > guard) { + throw new Error( + "the publisher's cookie never reached the busy receiver", + ); + } + } + } + channel.close(); + return localStorage.getItem("cross-context-busy-receiver:other-code"); + }, + { currentSignal: signal, holdBusy: browserName === "chromium" }, + ); + + // Awaited together, so a receiver that gives up waiting fails the test + // with its own message instead of leaving the publisher's wait to time out. + const [published, read] = await Promise.all([ + page.evaluate( + (stateKey) => + (Reflect.get(globalThis, stateKey) as { published: Promise }) + .published, + STATE_KEY, + ), + firstRead, + ]); + expect(published).toEqual({ ok: true, transport: "STORAGE" }); + expect(read).toBeNull(); + await expect + .poll(async () => (await snapshot(secondPage)).deliveries) + .toEqual([ + { + ordering: "NEXT", + sequence: 1, + topic: TOPIC, + transport: "STORAGE", + }, + ]); + } finally { + await Promise.allSettled([ + disposeRuntime(page), + disposeRuntime(secondPage), + ]); + await secondPage.close(); + } +}); diff --git a/tests/unit/cross-tab-invalidation.test.ts b/tests/unit/cross-tab-invalidation.test.ts index 318f0564..0322cf68 100644 --- a/tests/unit/cross-tab-invalidation.test.ts +++ b/tests/unit/cross-tab-invalidation.test.ts @@ -480,6 +480,141 @@ describe("browser cross-context host", () => { receiver.close(); }); + // 2026-11-19, runner run 371. Chromium loads a tab's localStorage cache on + // the tab's first read, and the load drops the change notifications from + // other tabs that have arrived but not run yet (Blink + // CachedStorageArea::EnsureLoaded). A pulse is removed as soon as it is + // written, so the loaded cache has no trace of it either. This model queues + // each tab's notifications until the tab runs them and drops the queue on + // the tab's first read. + describe("in a browser that drops queued notifications on a tab's first read", () => { + type Listener = (event: unknown) => void; + type Tab = { + listeners: Set; + queued: unknown[]; + loaded: boolean; + localStorage: Record; + }; + + function chromiumLikeTabs(options: { refuseReads?: boolean } = {}) { + const tabs: Tab[] = []; + const values = new Map(); + const open = () => { + const tab: Tab = { + listeners: new Set(), + queued: [], + loaded: false, + localStorage: {}, + }; + const load = () => { + if (tab.loaded) return; + tab.loaded = true; + tab.queued.length = 0; + }; + const notifyOthers = (key: string, newValue: string | null) => { + for (const other of tabs) { + if (other === tab) continue; + other.queued.push({ + key, + newValue, + storageArea: other.localStorage, + }); + } + }; + tab.localStorage = { + getItem(key: string) { + if (options.refuseReads) { + throw new DOMException("Storage is disabled", "SecurityError"); + } + load(); + return values.get(key) ?? null; + }, + setItem(key: string, value: string) { + load(); + values.set(key, value); + notifyOthers(key, value); + }, + removeItem(key: string) { + load(); + values.delete(key); + notifyOthers(key, null); + }, + }; + tabs.push(tab); + const host: Record = { + crypto: globalThis.crypto, + localStorage: tab.localStorage, + addEventListener(type: string, listener: Listener) { + if (type === "storage") tab.listeners.add(listener); + }, + removeEventListener(type: string, listener: Listener) { + if (type === "storage") tab.listeners.delete(listener); + }, + }; + return { tab, host }; + }; + // The tab's event loop gets to the queued notifications. + const runQueued = (tab: Tab) => { + for (const event of tab.queued.splice(0)) { + for (const listener of [...tab.listeners]) listener(event); + } + }; + return { open, runQueued }; + } + + it("reads its localStorage before it listens, so a later first read in the tab drops no pulse", () => { + const { open, runQueued } = chromiumLikeTabs(); + const topics = [{ topic: TOPIC, topicVersion: 1 }]; + const publisherTab = open(); + const receiverTab = open(); + const publisher = createBrowserCrossContextInvalidationFromHost({ + host: publisherTab.host, + cacheEpoch: CACHE_EPOCH, + topics, + }); + const receiver = createBrowserCrossContextInvalidationFromHost({ + host: receiverTab.host, + cacheEpoch: CACHE_EPOCH, + topics, + }); + if (!publisher || !receiver) throw new Error("host runtime not created"); + const received = vi.fn(); + receiver.subscribe(received); + + expect( + publisher.publish({ topic: TOPIC, topicVersion: 1 }), + ).toEqual({ ok: true, transport: "STORAGE" }); + // The receiver tab is busy as the pulse arrives; then other code in it + // reads localStorage (a preference, another adapter) before the tab + // runs the queued notifications. + const otherCode = receiverTab.tab.localStorage as { getItem(key: string): unknown }; + otherCode.getItem("another-adapter:preference"); + runQueued(receiverTab.tab); + + expect(received).toHaveBeenCalledOnce(); + expect(received.mock.calls[0]?.[0]).toMatchObject({ + ordering: "NEXT", + transport: "STORAGE", + event: { sequence: 1, topic: TOPIC }, + }); + + publisher.close(); + receiver.close(); + }); + + it("still listens when the host refuses the priming read", () => { + const { open } = chromiumLikeTabs({ refuseReads: true }); + const receiver = createBrowserCrossContextInvalidationFromHost({ + host: open().host, + cacheEpoch: CACHE_EPOCH, + topics: [{ topic: TOPIC, topicVersion: 1 }], + }); + + expect(receiver?.getStatus()).toBe("ACTIVE_STORAGE_FALLBACK"); + receiver?.close(); + }); + }); + it("derives a valid, stable cache epoch from any release id (Q-6.2-9)", () => { const releaseIds = [ "1.2.3+sha.abc", -- 2.54.0 From 7b68b9e8ed5b32e20ae1bb3a4179b2ea04eab22e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 19 Nov 2026 12:32:23 +0900 Subject: [PATCH 2/2] =?UTF-8?q?docs(ledger):=20storage=20pulse=20=ED=9D=94?= =?UTF-8?q?=EB=93=A4=EB=A6=BC=EC=9D=98=20=EC=9B=90=EC=9D=B8=EA=B3=BC=20?= =?UTF-8?q?=EA=B3=A0=EC=B9=9C=20=EB=B3=80=EA=B2=BD=EC=9D=84=20=EC=A0=81?= =?UTF-8?q?=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit browser-capabilities cross-context-invalidation.spec.ts:223이 runner run 371과 desktop 부하 20회 중 1회에서 실패한 흔들림 한 줄을 더한다. 범주는 concurrency-order, 원인은 Chromium이 탭의 첫 localStorage 읽기에서 이미 도착한 다른 탭의 변경 알림을 버리는 것이다. 고친 변경은 프론트 #63. 검증: scripts/verify.sh docs OK, desktop verify:documentation rc=0 --- docs/ledger/flaky-tests.jsonl | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/ledger/flaky-tests.jsonl b/docs/ledger/flaky-tests.jsonl index fb8f3560..d27bb08b 100644 --- a/docs/ledger/flaky-tests.jsonl +++ b/docs/ledger/flaky-tests.jsonl @@ -12,3 +12,4 @@ {"date": "2026-11-13", "test": "tests/system/ci-runner/provider-process-group.test.ts:11", "category": "fixed-time", "first_run": "309", "verdict": "runner run 309(#57 head, FE-GATE-013)에서 1회 실패(ENOENT descendant.pid). 시험이 runProviderProcess에 실제 250 ms 시한을 주고 그 안에 provider가 손자를 띄우고 pid를 쓴다고 가정했다. provider 시작을 400 ms 늦춘 탐침으로 결정적 재현(1/1 ENOENT), 고친 시험은 같은 탐침에서 통과. 고친 트리에서 desktop 시스템 컨테이너 20회 중 실패 0(부하 8.3~9.8, 12코어)", "quarantined_until": "", "fixed_by": "프론트 #61"} {"date": "2026-11-14", "test": "tests/system/ci-runner/ci-artifact-contract.test.ts:983", "category": "concurrency-order", "first_run": "/tmp/claude-gates/fe125-loop1-runs/run-1.log", "verdict": "desktop 시스템 컨테이너 파일 전체 4회 중 1회 실패(시작 load 15.34). 기대한 `provider guardian failed|SIGKILL` 대신 supervisor가 guardian commit 쓰기(scripts/lib/provider-guardian-client.ts:286)의 처리되지 않은 `write EPIPE`로 죽었다. 원인 조사 전", "quarantined_until": "", "fixed_by": ""} {"date": "2026-11-14", "test": "tests/system/ci-runner/ci-artifact-contract.test.ts:983", "category": "concurrency-order", "first_run": "/tmp/claude-gates/fe125-loop1-runs/run-1.log", "verdict": "원인 확정(2026-11-18). guardian이 SIGKILL로 죽은 뒤 supervisor가 그 종료를 처리하기 전에 COMMIT을 쓰면 EPIPE가 나고, scripts/lib/provider-guardian-client.ts의 commit()이 종료 결과보다 그 쓰기 오류를 먼저 던졌다(시험이 GITHUB_OUTPUT FIFO를 여는 때와 SIGCHLD 처리의 순서 경쟁). 같은 순서를 결정적으로 만든 통합 시험이 수정 전 1/1 실패(write EPIPE), 수정 뒤 통과. 고친 트리에서 desktop 시스템 컨테이너 그 시험 20회 중 실패 0(부하 8.7~17.2, 12코어)", "quarantined_until": "", "fixed_by": "프론트 #60"} +{"date": "2026-11-19", "test": "tests/browser-capabilities/cross-context-invalidation.spec.ts:223", "category": "concurrency-order", "first_run": "371", "verdict": "원인 확정(2026-11-19). [chromium] runner run 371 1회 실패(받은 deliveries []). desktop main f3de258d 단독 3회 모두 통과, CPU·메모리 hog 12개(nice 19, load 17.5) 아래 --repeat-each 20 중 1회 실패(같은 단언). Chromium은 탭의 첫 localStorage 읽기(CachedStorageArea::EnsureLoaded)에서 observer를 바꾸며 이미 도착한 다른 탭의 변경 알림을 버린다. 받는 page가 바쁠 때 그 page의 첫 읽기(발행 직후 snapshot, 또는 앱 부트의 설정 읽기)가 먼저 돌아 pulse를 잃었다(늦음이 아니라 잃음: 실패 회차에 raw storage 이벤트 0개). 받는 page를 막은 사이 발행하고 같은 작업에서 첫 읽기를 하는 탐침이 고치기 전 chromium 5/5 실패(firefox·webkit 10/10 통과). 고친 트리 ddda30a3에서 hog 12개 아래 chromium 그 spec 120회 실패 0", "quarantined_until": "", "fixed_by": "프론트 #63"} -- 2.54.0