fix(cross-context-invalidation): 듣기 전에 localStorage를 읽어 pulse를 잃지 않는다 #63

Merged
donghyeon.kang merged 4 commits from donghyeon.kang/fix/flaky-cross-context-storage AGit into main 2026-11-19 06:12:53 +00:00
4 changed files with 296 additions and 0 deletions
+1
View File
@@ -14,3 +14,4 @@
{"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-14", "test": "tests/system/ci-runner/ci-artifact-contract.test.ts:892", "category": "fixed-time", "first_run": "294", "verdict": "runner 1회 실패(FE-GATE-013, 4271 ms, 상한 4000). 단언은 공급자가 4초 감독 시한 전에 스스로 끝났는지가 아니라 완료 뒤 trace 확인까지의 벽시계를 쟀다. desktop 탐침에서 감독은 2574 ms에 exit 0·timed out 없이 끝났는데 완료 뒤 2.6초를 두자 같은 줄이 5180 ms로 실패(결정적). 같은 모양 :1105(CPU rlimit 시험의 5초 상한)도 고침", "quarantined_until": "", "fixed_by": "프론트 #57"}
{"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"}
@@ -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<string, unknown>, "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 {
@@ -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<void> {
await target.route(`**${BLANK_DOCUMENT_PATH}`, (route) =>
route.fulfill({
contentType: "text/html",
body: '<!doctype html><link rel="icon" href="data:,"><title>cross-context capability</title>',
}),
);
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<unknown>;
};
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<unknown> })
.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();
}
});
+135
View File
@@ -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<Listener>;
queued: unknown[];
loaded: boolean;
localStorage: Record<string, unknown>;
};
function chromiumLikeTabs(options: { refuseReads?: boolean } = {}) {
const tabs: Tab[] = [];
const values = new Map<string, string>();
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<string, unknown> = {
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",