From f19d4c6e9c9b26a8cb4c1f77f51313c93b688eeb Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:14:34 +0900 Subject: [PATCH 01/18] =?UTF-8?q?fix(cache-storage):=20=ED=99=9C=EC=84=B1?= =?UTF-8?q?=ED=99=94=EA=B0=80=20=EB=B3=B8=EB=AC=B8=20=EC=9D=BD=EA=B8=B0=20?= =?UTF-8?q?=EC=9D=BC=EC=8B=9C=20=EC=98=A4=EB=A5=98=EB=A5=BC=20=EC=86=90?= =?UTF-8?q?=EC=83=81=EC=9C=BC=EB=A1=9C=20=EB=B3=B4=EA=B3=A0=ED=95=98?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: verifyReleaseCandidate는 cache.match()가 던질 때만 UNKNOWN으로 본다. 본문 stream 읽기가 끊기면 readAndValidateResponse가 UNAVAILABLE(retry=true)이나 NOT_READABLE을 돌려주는데, 판정이 ABORTED 밖의 실패를 모두 REPAIRABLE로 바꾼다. 그래서 같은 I/O 오류가 조회에서는 UNAVAILABLE/RETRY, 활성화에서는 INTEGRITY_FAILED/REHYDRATE가 된다. stage 재사용 경로는 후보를 고치려고 모든 asset을 네트워크로 다시 받는다. 같은 파일의 타입 주석은 "unreadable candidate"를 UNKNOWN이라고 적는다. 고른 방법: 저장된 바이트·헤더에 대한 판정인 INTEGRITY_FAILED· CORRUPT_DATA·POLICY_REJECTED·LIMIT_EXCEEDED만 REPAIRABLE로 두고, 나머지 (UNAVAILABLE·NOT_READABLE·ABORTED 등)는 UNKNOWN으로 둔다. 활성화와 stage 재사용은 이미 UNKNOWN을 자기 operation으로 rebase해 돌려준다. 리뷰가 적은 최소 개선 방향 그대로다. 거꾸로 "실패 code 목록을 UNKNOWN 쪽에 적는" 방식은 새 code가 생기면 손상으로 떨어지므로 버렸다. 위험·한계: stage 재사용 경로는 본문을 읽지 못하면 이제 repair 대신 실패를 돌려준다. 손상이 아닌 것을 손상으로 고치지 않는다는 STO-RR-04와 같은 방향이다. inspect()가 판정 불가를 verified:false로 합치는 것 (0929/02-02)은 그대로다. service-worker-pwa 번들 9,716 → 9,733 / 10,100 gzip B. 검증: - RED: public-response-cache-repair.test.ts 새 테스트가 활성화 INTEGRITY_FAILED/REHYDRATE(기대 UNAVAILABLE/RETRY)로 실패. - GREEN: 같은 파일 10건 통과. 바이트가 다르면 여전히 INTEGRITY_FAILED 인지 보는 테스트를 같이 넣었다. cache 단위 3파일 + tests/recipes 62건 통과. check:types 통과. check:optional-recipes:source PASS. Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 02-02 --- .../public-response-cache-adapter.ts | 18 +++- .../unit/public-response-cache-repair.test.ts | 88 +++++++++++++++++++ 2 files changed, 102 insertions(+), 4 deletions(-) diff --git a/src/adapters/cache-storage/public-response-cache-adapter.ts b/src/adapters/cache-storage/public-response-cache-adapter.ts index 10d153e9..c66c33fb 100644 --- a/src/adapters/cache-storage/public-response-cache-adapter.ts +++ b/src/adapters/cache-storage/public-response-cache-adapter.ts @@ -1071,6 +1071,13 @@ type ReleaseCandidateVerdict = /** Abort or an unreadable candidate: never success, never a silent delete. */ | Readonly<{ kind: "UNKNOWN"; failure: BrowserFailureResult }>; +const REPAIRABLE_READ_CODES: ReadonlySet = new Set([ + "INTEGRITY_FAILED", + "CORRUPT_DATA", + "POLICY_REJECTED", + "LIMIT_EXCEEDED", +]); + /** * STO-04. The single verification authority shared by the stage fast path and * activation, so "the marker says it is staged" can never stand in for "every @@ -1117,12 +1124,15 @@ async function verifyReleaseCandidate( signal, ); if (!verified.ok) { - return verified.error.code === "ABORTED" - ? Object.freeze({ + // 2026-11-03 02-02. Only a verdict about the stored bytes or headers is + // damage. A body read that failed (UNAVAILABLE, NOT_READABLE, ABORTED) + // says nothing about them, so it stays unknown and is retried. + return REPAIRABLE_READ_CODES.has(verified.error.code) + ? Object.freeze({ kind: "REPAIRABLE" as const }) + : Object.freeze({ kind: "UNKNOWN" as const, failure: asFailure(verified), - }) - : Object.freeze({ kind: "REPAIRABLE" as const }); + }); } } return Object.freeze({ kind: "VERIFIED" as const }); diff --git a/tests/unit/public-response-cache-repair.test.ts b/tests/unit/public-response-cache-repair.test.ts index 3ae5807c..adab7ff8 100644 --- a/tests/unit/public-response-cache-repair.test.ts +++ b/tests/unit/public-response-cache-repair.test.ts @@ -173,6 +173,94 @@ describe("public response cache repair is failure-atomic", () => { ]); }); + it("reports a cached body that cannot be read during activation as retryable, not as damage (2026-11-03 02-02)", async () => { + const release = await stagedRelease("unreadable-body"); + const cache = release.cacheStorage.caches.get(release.cacheName)!; + const realMatch = cache.match.bind(cache); + const assetUrls = new Set(release.assets.map((asset) => asset.absoluteUrl)); + cache.match = async (request: RequestInfo | URL) => { + const url = + request instanceof Request ? request.url : String(request); + const stored = await realMatch(request); + if (!stored || !assetUrls.has(url)) return stored; + // The entry is there and its headers are intact; only reading the + // stored bytes fails, as a disk or browser I/O error does. + return new Response( + new ReadableStream({ + pull(controller) { + controller.error(new TypeError("disk read failed")); + }, + }), + { headers: stored.headers }, + ); + }; + const transient = (operation: string) => ({ + ok: false, + error: { + code: "UNAVAILABLE", + operation, + retryable: true, + recovery: "RETRY", + }, + }); + + expect( + await release.adapter.responses.matchActiveExact({ + absoluteUrl: release.assets[0]!.absoluteUrl, + }), + ).toMatchObject(transient("CACHE_LOOKUP")); + expect( + await release.adapter.admin.activateRelease( + release.manifest.releaseRegistryId, + release.manifest.manifestDigestHex, + ), + ).toMatchObject(transient("CACHE_ACTIVATE")); + // The stage fast path shares the verdict: an unreadable candidate is + // neither reused nor fetched again over the network. + const fetchesBefore = release.fetchLog.length; + expect( + await release.adapter.admin.stageRelease(release.manifest), + ).toMatchObject(transient("CACHE_STAGE")); + expect(release.fetchLog).toHaveLength(fetchesBefore); + + cache.match = realMatch; + expect( + await release.adapter.admin.activateRelease( + release.manifest.releaseRegistryId, + release.manifest.manifestDigestHex, + ), + ).toMatchObject({ ok: true }); + }); + + it("still reports stored bytes that no longer match as an integrity failure", async () => { + const release = await stagedRelease("mismatched-body"); + const cache = release.cacheStorage.caches.get(release.cacheName)!; + const index = cache.responses.findIndex( + (entry) => entry.request.url === release.assets[0]!.absoluteUrl, + ); + const entry = cache.responses[index]!; + cache.responses.splice(index, 1, { + request: entry.request, + response: new Response(new Uint8Array([9, 9, 9, 9]), { + headers: entry.response.headers, + }), + }); + + expect( + await release.adapter.admin.activateRelease( + release.manifest.releaseRegistryId, + release.manifest.manifestDigestHex, + ), + ).toMatchObject({ + ok: false, + error: { + code: "INTEGRITY_FAILED", + operation: "CACHE_ACTIVATE", + recovery: "REHYDRATE", + }, + }); + }); + it("keeps every healthy asset when one repair fetch fails", async () => { const release = await stagedRelease("partial-repair"); const cache = release.cacheStorage.caches.get(release.cacheName)!; From 7e7614fd488a0f500499aa5d3b1cbeea5aa24ee1 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:16:38 +0900 Subject: [PATCH 02/18] =?UTF-8?q?fix(cache-storage):=20=EC=86=90=EC=83=81?= =?UTF-8?q?=20pointer=EC=97=90=EC=84=9C=EB=8F=84=20inspect=EA=B0=80=20?= =?UTF-8?q?=EC=83=81=ED=83=9C=EC=99=80=20=ED=9B=84=EB=B3=B4=EB=A5=BC=20?= =?UTF-8?q?=EB=B3=B4=EC=97=AC=20=EC=A4=80=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: inspect()는 active pointer 읽기가 실패하면 그 실패를 그대로 돌려준다. 손상 pointer(CORRUPT_DATA)는 조회·cleanup을 막고 다음 activation이 rollback 없이 덮어쓰는 상태인데, 그 상태를 진단할 유일한 관리 API도 같이 멈춘다. 운영자는 어떤 후보가 남았는지, 다음 activation이 무엇을 덮어쓰고 그 뒤 cleanup이 무엇을 지울지 모른 채 배포한다. PublicCacheInspection에는 pointer 상태를 담을 칸이 없다. 고른 방법: PublicCacheInspection에 activePointer("NONE" | "READABLE" | "UNREADABLE")를 둔다. pointer 읽기가 CORRUPT_DATA면 UNREADABLE로 적고 activeReleaseRegistryId는 null로 둔 채 후보 목록을 끝까지 채운다. 일시 오류(UNAVAILABLE 등)는 지금처럼 실패로 돌려준다. activation이 이미 쓰는 "CORRUPT_DATA만 손상으로 본다" 규칙과 같다. recipe fake도 같은 칸을 채운다. 리뷰가 함께 적은 inspect 전용 operation 이름은 공유 operation union을 바꾸는 일이라 이번에 하지 않았다. 위험·한계: 공개 포트 타입에 필수 칸이 하나 는다. 결과를 읽는 쪽은 그대로지만 이 포트를 직접 구현한 쪽은 칸을 채워야 한다([계약]). repo 안 소비자는 없다. inspect의 signal·판정 불가(0929/02-02)는 그대로다. service-worker-pwa 번들 9,733 → 9,758 / 10,100 gzip B. 검증: - RED: public-response-cache-repair.test.ts 새 테스트가 activePointer 없음으로 실패. - GREEN: 같은 파일 11건 통과(손상 중 inspect ok, UNREADABLE, 후보 r1·r2 verified, 일시 오류는 UNAVAILABLE). cache 단위 3파일 + tests/recipes 63건 통과. check:types, 바꾼 파일 eslint, check:optional-recipes:source PASS, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 02-05 --- .../browser-file-and-origin-storage.md | 5 +- .../browser-file-storage-fakes.ts | 1 + .../public-response-cache-adapter.ts | 15 ++++- .../cache-storage-ports.ts | 9 +++ .../browser-file-storage-contracts.test.ts | 1 + .../unit/public-response-cache-repair.test.ts | 61 +++++++++++++++++++ 6 files changed, 88 insertions(+), 4 deletions(-) diff --git a/docs/architecture/browser-file-and-origin-storage.md b/docs/architecture/browser-file-and-origin-storage.md index d4ff71c7..72399f25 100644 --- a/docs/architecture/browser-file-and-origin-storage.md +++ b/docs/architecture/browser-file-and-origin-storage.md @@ -982,7 +982,10 @@ active pointer의 rollback 목록 길이는 읽을 때 현재 pointer(`CORRUPT_DATA`: 손상, 또는 지금 정책으로 허용되지 않는 ID)는 조회와 cleanup을 계속 막지만, 다음 `activateRelease`가 전체 재검증을 통과한 후보로 rollback 목록 없이 덮어쓴다. pointer 읽기의 일시 오류는 activation을 멈춘다 -(0929/02-01). +(0929/02-01). 그동안 `inspect()`는 멈추지 않고 `activePointer: "UNREADABLE"`과 +남은 후보 목록을 돌려준다. 운영자는 다음 activation이 무엇을 덮어쓰고 그 뒤 +cleanup이 무엇을 지울지 볼 수 있다. 일시 오류에서는 inspect도 실패한다 +(2026-11-03 02-05). 현재 `cleanupOwned()`와 `inspect()`는 위 ownership/integrity 경계를 지키지만 cache count에 대한 cursor, per-invocation max count와 deadline은 제공하지 않는다. diff --git a/recipes/frontend-capabilities/browser-file-storage-fakes.ts b/recipes/frontend-capabilities/browser-file-storage-fakes.ts index 19baa3fc..473b2ed6 100644 --- a/recipes/frontend-capabilities/browser-file-storage-fakes.ts +++ b/recipes/frontend-capabilities/browser-file-storage-fakes.ts @@ -2051,6 +2051,7 @@ export class MemoryPublicResponseCache // Every release here was staged after its entries passed policy, so each // owned cache is readable and each candidate is verified. return success({ + activePointer: this.#activeReleaseId === null ? "NONE" : "READABLE", activeReleaseRegistryId: this.#activeReleaseId, ownedCacheCount: this.#releases.size, unreadableOwnedCacheCount: 0, diff --git a/src/adapters/cache-storage/public-response-cache-adapter.ts b/src/adapters/cache-storage/public-response-cache-adapter.ts index c66c33fb..efd75876 100644 --- a/src/adapters/cache-storage/public-response-cache-adapter.ts +++ b/src/adapters/cache-storage/public-response-cache-adapter.ts @@ -867,7 +867,12 @@ export function createPublicResponseCacheAdapter( dependencies.cacheStorage, policy, ); - if (!pointer.ok) return pointer; + // 2026-11-03 02-05. A damaged pointer is the state this API is for, + // so it is reported with the candidates; a transient read is not. + if (!pointer.ok && pointer.error.code !== "CORRUPT_DATA") { + return pointer; + } + const active = pointer.ok ? pointer.value : null; const candidates: PublicCacheInspection["releaseCandidates"][number][] = []; @@ -903,8 +908,12 @@ export function createPublicResponseCacheAdapter( } return browserDataSuccess( Object.freeze({ - activeReleaseRegistryId: - pointer.value?.releaseRegistryId ?? null, + activePointer: !pointer.ok + ? "UNREADABLE" + : active + ? "READABLE" + : "NONE", + activeReleaseRegistryId: active?.releaseRegistryId ?? null, ownedCacheCount: owned.length, unreadableOwnedCacheCount, releaseCandidates: Object.freeze(candidates), diff --git a/src/application/ports/browser-file-storage/cache-storage-ports.ts b/src/application/ports/browser-file-storage/cache-storage-ports.ts index 8072a33b..81851ea3 100644 --- a/src/application/ports/browser-file-storage/cache-storage-ports.ts +++ b/src/application/ports/browser-file-storage/cache-storage-ports.ts @@ -40,6 +40,15 @@ export type CachedPublicResponse = Readonly<{ }>; export type PublicCacheInspection = Readonly<{ + /** + * 2026-11-03 02-05. `UNREADABLE` is a damaged pointer, or one this policy + * no longer accepts: lookup and cleanup stop on it and the next verified + * activation replaces it with an empty rollback list. The candidates are + * still listed so the operator can see what that activation and the + * cleanup after it will keep. A transient pointer read is a failure. + */ + activePointer: "NONE" | "READABLE" | "UNREADABLE"; + /** `null` unless `activePointer` is `READABLE`. */ activeReleaseRegistryId: string | null; ownedCacheCount: number; unreadableOwnedCacheCount: number; diff --git a/tests/recipes/browser-file-storage-contracts.test.ts b/tests/recipes/browser-file-storage-contracts.test.ts index 1b5c6d97..b571f41e 100644 --- a/tests/recipes/browser-file-storage-contracts.test.ts +++ b/tests/recipes/browser-file-storage-contracts.test.ts @@ -733,6 +733,7 @@ describe("production browser file and storage recipe contracts", () => { expect(await cache.inspect()).toEqual({ ok: true, value: { + activePointer: "READABLE", activeReleaseRegistryId: "release-1", ownedCacheCount: 1, unreadableOwnedCacheCount: 0, diff --git a/tests/unit/public-response-cache-repair.test.ts b/tests/unit/public-response-cache-repair.test.ts index adab7ff8..9f67c020 100644 --- a/tests/unit/public-response-cache-repair.test.ts +++ b/tests/unit/public-response-cache-repair.test.ts @@ -465,6 +465,67 @@ describe("public cache pointer after a policy change or damage (0929/02-01)", () ).toMatchObject({ ok: true, value: expect.anything() }); }); + it("shows a damaged pointer and the candidates it leaves behind in inspect (2026-11-03 02-05)", async () => { + const cacheStorage = new MemoryCacheStorage(); + const policy = policyRetaining(1); + const adapter = adapterFor(cacheStorage, policy); + expect(await adapter.admin.inspect()).toMatchObject({ + ok: true, + value: { activePointer: "NONE", activeReleaseRegistryId: null }, + }); + expect(await deploy(adapter, "r1", policy)).toMatchObject({ ok: true }); + expect(await deploy(adapter, "r2", policy)).toMatchObject({ ok: true }); + expect(await adapter.admin.inspect()).toMatchObject({ + ok: true, + value: { activePointer: "READABLE", activeReleaseRegistryId: "r2" }, + }); + const control = await cacheStorage.open(controlCacheName(policy)); + await control.put( + activePointerRequest(policy), + new Response('{"schemaVersion":1,"releaseRegis', { + headers: { "content-type": "application/json" }, + }), + ); + + const inspected = await adapter.admin.inspect(); + + expect(inspected).toMatchObject({ + ok: true, + value: { + activePointer: "UNREADABLE", + activeReleaseRegistryId: null, + ownedCacheCount: 3, + unreadableOwnedCacheCount: 0, + }, + }); + expect( + inspected.ok + ? inspected.value.releaseCandidates + .map(({ releaseRegistryId, verified }) => ({ + releaseRegistryId, + verified, + })) + .sort((left, right) => + left.releaseRegistryId.localeCompare(right.releaseRegistryId), + ) + : null, + ).toEqual([ + { releaseRegistryId: "r1", verified: true }, + { releaseRegistryId: "r2", verified: true }, + ]); + + // A pointer that could not be read right now is not reported as damage. + const realMatch = control.match.bind(control); + control.match = async () => { + throw new DOMException("Storage is busy", "InvalidStateError"); + }; + expect(await adapter.admin.inspect()).toMatchObject({ + ok: false, + error: { code: "UNAVAILABLE", retryable: true }, + }); + control.match = realMatch; + }); + it("still stops activation when the pointer read fails transiently", async () => { const cacheStorage = new MemoryCacheStorage(); const policy = policyRetaining(1); From 60b721fd1c9c415e484bfc364c92d89365690b15 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:17:50 +0900 Subject: [PATCH 03/18] =?UTF-8?q?fix(browser-files):=20inspect=20=EC=A4=91?= =?UTF-8?q?=EC=97=90=20=EB=86=93=EC=9D=80=20ref=EC=97=90=EB=8A=94=20receip?= =?UTF-8?q?t=EB=A5=BC=20=EB=B0=9C=EA=B8=89=ED=95=98=EC=A7=80=20=EC=95=8A?= =?UTF-8?q?=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: vault inspect()는 이전 receipt를 무효화한 뒤 파일을 읽으며 두 번 await한다. 그 뒤 #disposed는 다시 보지만 ref가 아직 있는지는 보지 않고 receipt를 발급한다. 그 사이 release(ref)가 record와 receipt를 지우면, inspect는 사라진 ref에 ok와 receipt를 돌려주고 receipt 기록이 놓은 File을 runtime dispose까지 붙잡는다(activeReferenceCount 0, activeVerificationCount 1). 지금은 resolveVerifiedFile의 records.has 검사가 preview를 막지만, 그 검사를 지운 변이(L11)를 잡는 테스트가 없었다. 고른 방법: #disposed 재확인 바로 뒤에서 record가 없으면 NOT_FOUND/RESELECT로 끝낸다. resolveFile이 ref를 못 찾을 때와 같은 결과라 호출자가 이미 처리하는 분기다. 리뷰의 최소 개선 방향 그대로다. 위험·한계: 같은 ref에 inspect 두 개가 겹치면 receipt가 둘 생기는 것은 이 변경 범위 밖이다(두 receipt 모두 release·dispose가 지운다). 이 수정 뒤에는 놓은 ref에 receipt가 남는 경로가 없어서, L11 검사는 다시 두 번째 방어선이 된다. 새 테스트는 이 커밋의 검사를 지우면 실패한다. file-transfer 번들 56,053 → 56,068 / 57,800 gzip B. 검증: - RED: browser-file-content.test.ts 새 테스트가 inspect ok(기대 NOT_FOUND)로 실패. - GREEN: browser-files 단위 5파일 + tests/recipes 85건 통과. check:types, 바꾼 파일 eslint, check:optional-recipes:source PASS. Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 02-04 --- .../browser-files/browser-file-vault.ts | 9 ++++++ tests/unit/browser-file-content.test.ts | 32 +++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/adapters/browser-files/browser-file-vault.ts b/src/adapters/browser-files/browser-file-vault.ts index 8d36b126..7db2bfed 100644 --- a/src/adapters/browser-files/browser-file-vault.ts +++ b/src/adapters/browser-files/browser-file-vault.ts @@ -352,6 +352,15 @@ export class BrowserFileVault browserDataFailure("UNAVAILABLE", "FILE_INSPECT"), ); } + // 2026-11-03 02-04. release() may have run during the reads above; a + // receipt issued now would hold the released File until dispose. + if (!this.#records.has(request.ref)) { + return this.#observeFailureResult( + browserDataFailure("NOT_FOUND", "FILE_INSPECT", { + recovery: "RESELECT", + }), + ); + } const cancelled = abortedResult( request.signal, "FILE_INSPECT", diff --git a/tests/unit/browser-file-content.test.ts b/tests/unit/browser-file-content.test.ts index a1de678e..9afef765 100644 --- a/tests/unit/browser-file-content.test.ts +++ b/tests/unit/browser-file-content.test.ts @@ -614,6 +614,38 @@ describe("browser file content policy", () => { }); }); + it("issues no receipt for a ref released while inspect() was reading it (2026-11-03 02-04)", async () => { + const vault = new BrowserFileVault({ policies: pngPolicies() }); + const captured = vault.captureFiles( + [ + new File( + [new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])], + "released.png", + { type: "image/png", lastModified: 1 }, + ), + ], + pngSelectionPolicy, + ); + if (!captured.ok || !captured.value[0]) throw new Error("capture"); + const ref = captured.value[0].ref; + + // The user removes the file from the list before the check finishes. + const pending = vault.inspect({ + ref, + policy: pngPolicy, + signal: new AbortController().signal, + }); + vault.release(ref); + + expect(await pending).toMatchObject({ + ok: false, + error: { code: "NOT_FOUND", recovery: "RESELECT" }, + }); + expect(vault.activeReferenceCount).toBe(0); + expect(vault.activeVerificationCount).toBe(0); + expect(vault.retainedByteLength).toBe(0); + }); + it("returns ABORTED without a lease when the caller aborts right after create() (02-01)", async () => { const revoked: string[] = []; let urlSequence = 0; From 1dfe86a372fce215b364a3f47ad53da20d181d6e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:20:11 +0900 Subject: [PATCH 04/18] =?UTF-8?q?test(browser-files):=20=EC=86=90=EC=83=81?= =?UTF-8?q?=20=EB=8D=B0=EC=9D=B4=ED=84=B0=C2=B7=EB=A1=9C=EA=B7=B8=EC=95=84?= =?UTF-8?q?=EC=9B=83=20=EA=B2=BD=EB=A1=9C=EC=9D=98=20=EB=B3=B4=ED=98=B8=20?= =?UTF-8?q?=EA=B7=9C=EC=B9=99=205=EA=B0=9C=EB=A5=BC=20=EA=B3=A0=EC=A0=95?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 2026-11-03 리뷰 변이 중 아래 5개가 관련 unit 파일을 모두 통과했다. 규칙을 고치는 사람은 테스트가 통과해도 손상·로그아웃 보호가 남았는지 알 수 없다. - L6 cleanupOwned()가 읽을 수 없는 pointer를 "pointer 없음"으로 보고 지금 서비스 중인 release까지 지운다. - L7 stage가 손상된 marker를 고치지 않고 실패한다. REHYDRATE 안내가 기대는 회복 경로다. - L4 preview가 파일 resolve 뒤 #disposed를 다시 보지 않는다. - L5 vault resolveFile이 load 뒤 #disposed를 다시 보지 않는다. - L1 vault dispose()가 File 참조 Map을 비우지 않는다. L4·L5는 lease registry가 dispose 뒤에도 lease를 내주기 때문에 소비자 쪽 검사가 유일한 방어선이다. 고른 방법: 규칙마다 실패하는 테스트 하나를 더한다. 리뷰가 L5에 제안한 readRange()는 slice 읽기 뒤에 #disposed를 한 번 더 보므로 L5를 잡지 못한다. 그래서 resolve 직후 소스를 돌려주는 openSource()로 고정했다. 위험·한계: 테스트만 바꾼다. 동작 변경 없음. 검증: 5개 변이를 하나씩 넣고 browser-files 단위 5파일 + tests/recipes, cache 단위 3파일 + tests/recipes를 돌렸다. L1·L4·L5·L6·L7 모두 새 테스트 하나씩이 실패했고(되돌린 뒤 통과), 원래 코드에서 두 파일 34건 통과. check:types:test, 바꾼 파일 eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 02-03 --- tests/unit/browser-file-content.test.ts | 69 +++++++++++++++++++ .../unit/public-response-cache-repair.test.ts | 58 ++++++++++++++++ 2 files changed, 127 insertions(+) diff --git a/tests/unit/browser-file-content.test.ts b/tests/unit/browser-file-content.test.ts index 9afef765..b44ef84a 100644 --- a/tests/unit/browser-file-content.test.ts +++ b/tests/unit/browser-file-content.test.ts @@ -646,6 +646,75 @@ describe("browser file content policy", () => { expect(vault.retainedByteLength).toBe(0); }); + // 2026-11-03 02-03. Logout disposes the runtime while a call is in flight. + // The lease registry still hands out leases after dispose, so each + // consumer's own re-check is the only thing that keeps a URL from outliving + // the session. + it("creates no object URL for a preview whose runtime is disposed while it resolves", async () => { + let urlSequence = 0; + const leases = new ObjectUrlLeaseRegistry({ + createObjectURL: () => `blob:disposed-${urlSequence++}`, + revokeObjectURL() {}, + }); + const { preview, request } = await verifiedPngPreview(leases); + + const pending = preview.create(request(new AbortController().signal)); + preview.dispose(); + + expect(await pending).toMatchObject({ + ok: false, + error: { code: "UNAVAILABLE", operation: "PREVIEW" }, + }); + expect(urlSequence).toBe(0); + expect(leases.activeLeaseCount).toBe(0); + }); + + it("opens no byte source for a file whose vault is disposed while it loads", async () => { + const vault = new BrowserFileVault({ policies: pngPolicies() }); + const captured = vault.captureFiles( + [ + new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], "a.png", { + type: "image/png", + lastModified: 1, + }), + ], + pngSelectionPolicy, + ); + if (!captured.ok || !captured.value[0]) throw new Error("capture"); + + const pending = vault.openSource({ + ref: captured.value[0].ref, + signal: new AbortController().signal, + }); + vault.dispose(); + + expect(await pending).toMatchObject({ + ok: false, + error: { code: "UNAVAILABLE", operation: "FILE_READ" }, + }); + }); + + it("lets go of every selected File on dispose", () => { + const vault = new BrowserFileVault({ policies: pngPolicies() }); + expect( + vault.captureFiles( + [ + new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], "a.png", { + type: "image/png", + lastModified: 1, + }), + ], + pngSelectionPolicy, + ), + ).toMatchObject({ ok: true }); + expect(vault.activeReferenceCount).toBe(1); + + vault.dispose(); + + expect(vault.activeReferenceCount).toBe(0); + expect(vault.retainedByteLength).toBe(0); + }); + it("returns ABORTED without a lease when the caller aborts right after create() (02-01)", async () => { const revoked: string[] = []; let urlSequence = 0; diff --git a/tests/unit/public-response-cache-repair.test.ts b/tests/unit/public-response-cache-repair.test.ts index 9f67c020..692cc95b 100644 --- a/tests/unit/public-response-cache-repair.test.ts +++ b/tests/unit/public-response-cache-repair.test.ts @@ -4,6 +4,7 @@ import type { PublicCacheAsset } from "../../src/application/ports/browser-file- import { activePointerRequest, controlCacheName, + markerRequest, } from "../../src/adapters/cache-storage/public-cache-codec.ts"; import { createDefaultPublicCachePolicy, @@ -526,6 +527,63 @@ describe("public cache pointer after a policy change or damage (0929/02-01)", () control.match = realMatch; }); + it("does not clean up on a damaged pointer, which may name the release being served (2026-11-03 02-03)", async () => { + const cacheStorage = new MemoryCacheStorage(); + const policy = policyRetaining(1); + const adapter = adapterFor(cacheStorage, policy); + expect(await deploy(adapter, "r1", policy)).toMatchObject({ ok: true }); + expect(await deploy(adapter, "r2", policy)).toMatchObject({ ok: true }); + const control = await cacheStorage.open(controlCacheName(policy)); + await control.put( + activePointerRequest(policy), + new Response('{"schemaVersion":1,"releaseRegis', { + headers: { "content-type": "application/json" }, + }), + ); + const before = (await cacheStorage.keys()).sort(); + + expect(await adapter.admin.cleanupOwned()).toMatchObject({ + ok: false, + error: { code: "CORRUPT_DATA", operation: "CACHE_DELETE" }, + }); + expect((await cacheStorage.keys()).sort()).toEqual(before); + }); + + it("repairs a damaged release marker by staging the same manifest again (2026-11-03 02-03)", async () => { + const cacheStorage = new MemoryCacheStorage(); + const policy = policyRetaining(1); + const adapter = adapterFor(cacheStorage, policy); + expect(await deploy(adapter, "r1", policy)).toMatchObject({ ok: true }); + const releaseName = (await cacheStorage.keys()).find((name) => + name.includes("release:r1:"), + ); + if (!releaseName) throw new Error("release cache missing"); + const release = await cacheStorage.open(releaseName); + await release.put( + markerRequest(policy), + new Response('{"schemaVersion":1,"verif', { + headers: { "content-type": "application/json" }, + }), + ); + // REHYDRATE: the damaged candidate cannot be activated as it is ... + const manifest = await manifestOf("r1", policy); + expect( + await adapter.admin.activateRelease( + manifest.releaseRegistryId, + manifest.manifestDigestHex, + ), + ).toMatchObject({ + ok: false, + error: { code: "CORRUPT_DATA", recovery: "REHYDRATE" }, + }); + + // ... and staging it again is the recovery that hint promises. + expect(await deploy(adapter, "r1", policy)).toMatchObject({ ok: true }); + expect( + await adapter.responses.matchActiveExact({ absoluteUrl: assetUrl("r1") }), + ).toMatchObject({ ok: true, value: expect.anything() }); + }); + it("still stops activation when the pointer read fails transiently", async () => { const cacheStorage = new MemoryCacheStorage(); const policy = policyRetaining(1); From d13a393600a3b91dee127c5b47509af4a03b358d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:29:34 +0900 Subject: [PATCH 05/18] =?UTF-8?q?fix(storage):=20=EA=B3=84=EC=A0=95=20?= =?UTF-8?q?=EC=82=AD=EC=A0=9C=20purge=EA=B0=80=20=EB=81=9D=EB=82=98?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EC=9D=80=20put=EC=9D=84=20=EB=B3=B4?= =?UTF-8?q?=EB=A9=B4=20partition=EC=9D=84=20=EC=A7=80=EC=9A=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 손상이 없는 LOGOUT·ACCOUNT_DELETION purge는 commit된 object 행과 참조 없는 chunk만 본다. 같은 partition의 끝나지 않은 journal 행 (PREPARING·FILES_READY)은 보지 않고, sweep은 staging receipt가 가리키는 chunk를 건너뛰면서도 COMPLETED를 돌려준다. 그래서 - 다른 탭이 put 중이면 purge가 "COMPLETED"를 보고한 뒤 그 객체가 그대로 읽힌다(X1, 실제 Chromium·Firefox에서도 같음). - commit 직전에 멈춘 put(FILES_READY)은 purge 뒤 다음 reconcile이 commit해 계정 삭제한 사용자 파일이 객체로 다시 생긴다(X2). - 업로드 중 멈춘 put(PREPARING)은 chunk가 grace 기간 동안 남고(X2b), 그 행이 손상됐으면 partition 삭제도 일어나지 않아 영원히 남는다(X3). 손상이 있을 때만 partition 삭제가 진행 중 put까지 기다렸다 지웠다. 고른 방법(리뷰 5.1절 (c)): LOGOUT·ACCOUNT_DELETION이 객체를 다 돈 뒤 그 partition 키를 가진 journal 행 수를 센다. 하나라도 있으면(읽을 수 있든 없든) sweep 대신 이미 있는 partition 삭제로 넘긴다. partition 삭제는 exclusive partition lock으로 진행 중 put·delete가 돌아오기를 기다린 뒤 디렉터리와 그 partition의 행을 모두 지운다(e5b7b3e). OpfsJournalPort에 countPartitionTransactions(scope)를 더했다. removePartition이 지우는 같은 LOGICAL_KEY_INDEX 범위를 세므로, 센 행은 삭제가 지운다. 버린 대안: (a) 문서에 "reconcile 먼저" 안내 — X1·X3을 막지 못한다. (b) report에 수만 추가 — 지울 방법이 없다(X3). (d) 항상 partition 삭제 — 더 단순하지만 끝나지 않은 행이 없을 때의 예산 단위 진행과 removedObjects·releasedBytes 보고를 잃는다. 위험·한계: - 공개 포트에 필수 메서드가 하나 는다. OpfsJournalPort를 직접 구현한 쪽은 추가해야 한다([계약]). - 끝나지 않은 행이 하나라도 있으면 purge가 예산 없는 partition 삭제가 되고, 다른 탭의 진행 중 put이 끝날 때까지 기다린다. 그 put의 결과도 지운다(손상 경로와 같은 의미). purge가 행을 센 뒤 시작한 put은 남는다(point-in-time). - 기존 테스트 "never sweeps the chunk of a put that runs while the purge does"는 X1 동작을 기대값으로 고정하고 있었다. 새 의미로 바꿨다. 0929/05-02 테스트는 덮어쓰기가 purge의 목록과 remove 사이에 끝나도록 바꿔 CONFLICT 경로를 계속 본다. - 소속을 알 수 없는(logicalKey가 깨진) 행은 여기서도 세지 못한다(05-03). - WebKit은 기본 정책에서 OPFS 지원 판정을 통과하지 못해 browser spec이 일찍 끝난다. offline-indexeddb 번들 37,423 → 37,521 / 38,500 gzip B. 검증: - RED: opfs-worker-runtime.test.ts 새 4건(X1, FILES_READY, PREPARING, 손상 행)이 partitionDeleted 없음으로 실패. - GREEN: OPFS 단위 3파일 + optional-runtime-host + tests/recipes + tests/contract 172건 통과. journal에 countPartitionTransactions 테스트 1건(손상 행 포함, 다른 partition 제외, 삭제 뒤 0). - browser: opfs-runtime.spec.ts에 X1 2탭 판을 더했다. heavy lock 안에서 3엔진 9/9 통과(WebKit은 지원 판정에서 끝남). - check:types, 바꾼 파일 eslint, check:optional-recipes:source PASS, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/05-adapters-storage-kernel.md 05-01 --- .../browser-file-storage-recovery.md | 36 ++-- .../storage/opfs/indexeddb-opfs-journal.ts | 42 ++++ .../storage/opfs/opfs-byte-store-adapter.ts | 22 ++- .../ports/browser-file-storage/opfs-ports.ts | 24 ++- .../browser-capabilities/opfs-runtime.spec.ts | 180 ++++++++++++++---- tests/unit/indexeddb-opfs-journal.test.ts | 45 +++++ tests/unit/opfs-byte-store.test.ts | 9 + tests/unit/opfs-worker-runtime.test.ts | 140 ++++++++++++-- 8 files changed, 431 insertions(+), 67 deletions(-) diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index 66ae77e5..074dd405 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -44,8 +44,9 @@ cleanup 결과를 확인하지 못하면 성공 값이 아니라 실패로 답 근거가 사라지고 quota만 누수된다. 4. OPFS root나 journal database를 통째로 삭제하거나 schema를 downgrade하지 않는다. rollback은 새 v2 write admission을 닫고 v1+v2 reader를 유지하는 것으로 - 수행한다. runtime이 스스로 지우는 것은 승인된 purge가 손상 때문에 끝나지 못할 - 때의 그 partition 디렉터리 하나와 그 partition의 journal row뿐이다(§7). + 수행한다. runtime이 스스로 지우는 것은 승인된 purge가 손상이나 끝나지 않은 + transaction 때문에 끝나지 못할 때의 그 partition 디렉터리 하나와 그 partition의 + journal row뿐이다(§7). ## 1. 공통 원칙 @@ -58,8 +59,9 @@ incident 중에도 다음 작업은 금지한다. - origin의 모든 `caches.keys()` 삭제 - user-authored/unsynced IndexedDB 또는 OPFS data 자동 purge - OPFS의 예외도 하나다. authority가 승인한 LOGOUT/ACCOUNT_DELETION이 손상된 - journal row나 staging 때문에 끝나지 못할 때, runtime이 그 partition - 디렉터리 하나와 그 partition의 journal row만 지운다(§7 recovery). + row나 staging, 또는 그 partition의 끝나지 않은 put·delete 때문에 끝나지 못할 + 때, runtime이 그 partition 디렉터리 하나와 그 partition의 journal row만 + 지운다(§7 recovery). - schema version downgrade - 무한 reload/update loop - filename, path, record/object key, URL/query, digest, body를 incident log에 복사 @@ -438,20 +440,28 @@ VD-15 목표 runtime을 먼저 구현한다. - `COMMITTED` + file missing/corrupt: reconstructable만 server rehydrate; user-created private는 read-only/export/recovery - stale staging/orphan chunk는 grace period와 bounded mark/sweep 후 제거 -- `LOGOUT`/`ACCOUNT_DELETION` purge는 객체를 모두 지운 뒤 그 partition의 chunk를 +- `LOGOUT`/`ACCOUNT_DELETION` purge는 객체를 모두 지운 뒤 그 partition의 journal + row를 센다. 하나라도 있으면(다른 tab에서 진행 중인 put·delete, crash가 남긴 + `PREPARING`·`FILES_READY`, 키는 읽히는 손상 row) sweep 대신 아래 partition + 삭제로 간다(2026-11-03 05-01). 예전에는 이 row를 보지 않고 `COMPLETED`를 + 돌려줬다. 그래서 진행 중 put의 객체가 purge 뒤에도 읽혔고, `FILES_READY` row는 + 다음 reconcile이 commit해 객체로 되살렸다. row가 없으면 그 partition의 chunk를 grace 없이 sweep한다(05-04, `opfs-byte-store-adapter.ts` `enforcePolicies`). - journal이나 staging receipt가 참조하는 chunk는 이때도 지우지 않는다. report의 - `chunkSweep`이 `COMPLETED`여야 bytes가 지워진 것이다. `DEADLINE_REACHED`면 같은 + staging receipt가 참조하는 chunk는 이때도 지우지 않는다. 이 두 reason에서는 + report의 `chunkSweep`이 `COMPLETED`이거나 `partitionDeleted`가 있을 때 그 + partition의 bytes가 지워진 것이다. `DEADLINE_REACHED`면 같은 purge를 다시 호출하고, `STAGING_STATE_UNREADABLE`이면 읽을 수 없는 staging부터 처리한다. 다른 탭이 바꾸고 있던 객체를 지우지 못하면 report는 `moreObjectsAvailable: true`이고 `chunkSweep`이 없다. 이때도 같은 purge를 다시 호출한다([0929] 05-02) -- 손상 때문에 끝나지 못하는 `LOGOUT`/`ACCOUNT_DELETION` purge는 partition을 - 통째로 지운다([0929] 05-01, `opfs-byte-store-adapter.ts` `enforcePolicies`). +- 손상이나 끝나지 않은 transaction 때문에 끝나지 못하는 `LOGOUT`/ + `ACCOUNT_DELETION` purge는 partition을 통째로 지운다([0929] 05-01, + 2026-11-03 05-01, `opfs-byte-store-adapter.ts` `enforcePolicies`). - 조건: 정책이 그 reason을 허용하고, authority가 이번 purge의 proof를 내주고 consumer가 소비했을 때(IndexedDB의 database 전체 삭제와 같은 승인). 그리고 다음 중 하나를 만났을 때: 목록에서 건너뛴 손상 object row, 손상 row 때문에 - `CORRUPT_DATA`로 끝난 remove나 chunk sweep, `STAGING_STATE_UNREADABLE`. + `CORRUPT_DATA`로 끝난 remove나 chunk sweep, `STAGING_STATE_UNREADABLE`, 그 + partition 키를 가진 journal row(`countPartitionTransactions`가 1 이상). TTL·SESSION_END·UNTIL_SYNCED·PRESSURE는 손상 row를 건너뛰고 세기만 한다. - 범위: worker가 origin mutation lease를 쥔 채 `authorities///` 디렉터리를 @@ -479,9 +489,9 @@ VD-15 목표 runtime을 먼저 구현한다. approved purge meets another tab's put parked before …"(5가지 순서). - 한계: 삭제는 진행 중인 put·delete를 기다린다. source가 멈춘 put은 put idle bound(05-07)까지 삭제를 붙잡는다. purge의 `signal`을 abort하면 기다림을 - 멈추고 `ABORTED`를 반환한다. 삭제가 lock을 요청한 뒤 온 put의 데이터는 다른 - purge처럼 남는다(point-in-time). purge 전에 그 partition의 쓰기를 멈추는 - 것이 composition의 몫이다. + 멈추고 `ABORTED`를 반환한다. purge가 journal row를 센 뒤에 시작한 put, 삭제가 + lock을 요청한 뒤 온 put의 데이터는 남는다(point-in-time). purge 전에 그 + partition의 쓰기를 멈추는 것이 composition의 몫이다. - lock/worker 문제면 OPFS write off → approved capped fallback 또는 online-only - scope binding mismatch면 affected scope를 read-only로 격리하고 registry/ composition을 forward fix; 다른 token path로 bytes를 이동하거나 추측 복구 금지 diff --git a/src/adapters/storage/opfs/indexeddb-opfs-journal.ts b/src/adapters/storage/opfs/indexeddb-opfs-journal.ts index e215e086..b449952f 100644 --- a/src/adapters/storage/opfs/indexeddb-opfs-journal.ts +++ b/src/adapters/storage/opfs/indexeddb-opfs-journal.ts @@ -864,6 +864,48 @@ export function createIndexedDbOpfsJournal( ); }, + async countPartitionTransactions(scope) { + if ( + !keyRange || + !isBoundScope(scope) || + !isValidOpfsStorageScope(scope) + ) { + return browserDataFailure( + keyRange ? "INVALID_INPUT" : "UNSUPPORTED", + "INDEXEDDB_READ", + ); + } + return await withDatabase("INDEXEDDB_READ", (db) => + runTransaction( + db, + [JOURNAL_STORE], + "readonly", + "INDEXEDDB_READ", + (transaction, context) => { + // 2026-11-03 05-01. The key range `removePartition` deletes, so a + // row counted here is a row that delete takes. + const scopeKey = storageScopeKey(scope); + let rows = 0; + walkIndexedDbCursor({ + request: transaction + .objectStore(JOURNAL_STORE) + .index(LOGICAL_KEY_INDEX) + .openCursor( + keyRange.bound(`${scopeKey}|`, `${scopeKey}|\uffff`), + ), + sink: context, + translate: translateFor("INDEXEDDB_READ"), + visit: () => { + rows += 1; + return { kind: "CONTINUE" }; + }, + done: () => context.succeed(rows), + }); + }, + ), + ); + }, + async removePartition(scope) { if ( !keyRange || diff --git a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts index 0f68c3f6..f2b8e2ad 100644 --- a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts +++ b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts @@ -876,6 +876,22 @@ export function createOpfsByteStoreAdapter( } afterObjectId = page.value.nextObjectId; } + // 2026-11-03 05-01. A put or delete of this partition that has not + // finished holds bytes the object walk never sees and the sweep skips: + // one running in another tab, or a row a crash left (PREPARING, or + // FILES_READY, which the next reconcile would commit) or nothing can + // read. Any such row sends the purge to the partition delete below, + // which first waits for every live one. + let unfinished = 0; + if (sweeping && !request.signal?.aborted) { + const counted = await dependencies.journal.countPartitionTransactions( + dependencies.scope, + ); + if (!counted.ok) { + return rebaseFailure(counted.error, "OBJECT_RECONCILE"); + } + unfinished = counted.value; + } // 05-04. Removing an object leaves its chunks, and GC only takes a // chunk 24 h after it was written, so a purged user's bytes stayed on // the device. Once every object is gone the partition's chunks are swept @@ -884,6 +900,7 @@ export function createOpfsByteStoreAdapter( let chunkSweep: OpfsPolicyMaintenanceReport["chunkSweep"]; if ( sweeping && + !unfinished && !corruptObjects && !damaged && !moreObjectsAvailable && @@ -920,7 +937,7 @@ export function createOpfsByteStoreAdapter( // wait for every put and delete of the partition in any tab. const partitionDeleted = sweeping && - (corruptObjects > 0 || damaged) && + (corruptObjects > 0 || damaged || unfinished > 0) && !request.signal?.aborted; if (partitionDeleted) { const removed = await withPartitionLock( @@ -1610,6 +1627,7 @@ function snapshotOpfsJournal( listIncomplete, listCommittedObjects, isChunkReferenced, + countPartitionTransactions, removePartition, } = source; if ( @@ -1624,6 +1642,7 @@ function snapshotOpfsJournal( listIncomplete, listCommittedObjects, isChunkReferenced, + countPartitionTransactions, removePartition, ].some((method) => typeof method !== "function") ) { @@ -1640,6 +1659,7 @@ function snapshotOpfsJournal( listIncomplete: listIncomplete.bind(source), listCommittedObjects: listCommittedObjects.bind(source), isChunkReferenced: isChunkReferenced.bind(source), + countPartitionTransactions: countPartitionTransactions.bind(source), removePartition: removePartition.bind(source), }); } diff --git a/src/application/ports/browser-file-storage/opfs-ports.ts b/src/application/ports/browser-file-storage/opfs-ports.ts index 1d21467e..a43ddffd 100644 --- a/src/application/ports/browser-file-storage/opfs-ports.ts +++ b/src/application/ports/browser-file-storage/opfs-ports.ts @@ -145,9 +145,12 @@ export type OpfsPolicyMaintenanceReport = Readonly<{ moreObjectsAvailable: boolean; deadlineReached: boolean; /** - * 05-04. LOGOUT and ACCOUNT_DELETION only, once every object is removed: - * how the sweep of the partition's now unreferenced chunks ended. Chunk - * bytes are gone only when it is `COMPLETED`, or when `partitionDeleted`. + * 05-04. LOGOUT and ACCOUNT_DELETION only, once every object is removed and + * no put or delete of the partition is unfinished: how the sweep of the + * partition's now unreferenced chunks ended. For those two reasons the + * partition's bytes are gone exactly when this is `COMPLETED` or + * `partitionDeleted` is set; a put that begins after the purge reached its + * journal check is kept (2026-11-03 05-01). */ chunkSweep?: "COMPLETED" | "DEADLINE_REACHED" | "STAGING_STATE_UNREADABLE"; /** @@ -157,8 +160,11 @@ export type OpfsPolicyMaintenanceReport = Readonly<{ corruptObjects?: number; /** * [0929] 05-01. An approved LOGOUT or ACCOUNT_DELETION that damage kept - * from finishing removed the whole partition directory and the partition's - * journal rows instead. Every byte of the partition is gone. + * from finishing, or that found an unfinished put or delete of the + * partition (2026-11-03 05-01), removed the whole partition directory and + * the partition's journal rows instead, after every put and delete of the + * partition then running in any tab had returned. Every byte of the + * partition is gone. */ partitionDeleted?: true; }>; @@ -376,6 +382,14 @@ export interface OpfsJournalPort { scope: OpfsStorageScope, digestHex: string, ): Promise>; + /** + * 2026-11-03 05-01. How many journal rows are keyed to this one partition, + * readable or not: every put or delete of it that has not finished, live in + * some tab or left by a crash. Found by key, like `removePartition`. + */ + countPartitionTransactions( + scope: OpfsStorageScope, + ): Promise>; /** * [0929] 05-01. Deletes every row keyed to this one partition, readable or * not: committed objects, journal rows, chunk references and the budget. diff --git a/tests/browser-capabilities/opfs-runtime.spec.ts b/tests/browser-capabilities/opfs-runtime.spec.ts index cecf5a07..7157a7fc 100644 --- a/tests/browser-capabilities/opfs-runtime.spec.ts +++ b/tests/browser-capabilities/opfs-runtime.spec.ts @@ -229,13 +229,15 @@ type OpfsTabScope = Readonly<{ /** * Installs an OPFS runtime for `scope` in this tab and keeps it on - * `globalThis.__opfsTab` for later evaluate calls. + * `globalThis.__opfsTab` for later evaluate calls. `approvePurges` stands in + * for an authority that approves every LOGOUT and ACCOUNT_DELETION. */ async function installOpfsTab( page: import("@playwright/test").Page, scope: OpfsTabScope, + approvePurges = false, ): Promise { - return await page.evaluate(async (tabScope) => { + return await page.evaluate(async ({ tabScope, approvePurges }) => { const runtimeModulePath = "/src/adapters/storage/opfs/browser-opfs-runtime.ts"; const policyModulePath = "/src/adapters/storage/opfs/opfs-policy.ts"; @@ -272,11 +274,153 @@ async function installOpfsTab( unavailableFallback: "EXPORT_REQUIRED", }, policy, + ...(approvePurges + ? { + requestMaintenanceAuthority: () => ({ + authorized: true as const, + proofToken: `proof_${crypto.randomUUID().replaceAll("-", "")}`, + expiresAtEpochMs: Date.now() + 60_000, + }), + consumeMaintenanceAuthority: () => true, + } + : {}), }); return true; + }, { tabScope: scope, approvePurges }); +} + +/** Deletes everything the OPFS runtime wrote for `scope`'s authority. */ +async function removeOpfsAuthority( + page: import("@playwright/test").Page, + scope: OpfsTabScope, +): Promise { + return await page.evaluate(async (tabScope) => { + const journalModulePath = + "/src/adapters/storage/opfs/indexeddb-opfs-journal.ts"; + const policyModulePath = "/src/adapters/storage/opfs/opfs-policy.ts"; + const { opfsJournalDatabaseName } = (await import( + /* @vite-ignore */ journalModulePath + )) as typeof import("../../src/adapters/storage/opfs/indexeddb-opfs-journal.ts"); + const { DEFAULT_OPFS_RUNTIME_POLICY } = (await import( + /* @vite-ignore */ policyModulePath + )) as typeof import("../../src/adapters/storage/opfs/opfs-policy.ts"); + const deletion = await new Promise((resolve) => { + const request = indexedDB.deleteDatabase( + opfsJournalDatabaseName(tabScope.authorityToken), + ); + request.onsuccess = () => resolve("DELETED"); + request.onerror = () => resolve(request.error?.name ?? "UNKNOWN"); + request.onblocked = () => resolve("BLOCKED"); + }); + try { + const root = await ( + await navigator.storage.getDirectory() + ).getDirectoryHandle(DEFAULT_OPFS_RUNTIME_POLICY.rootDirectoryName); + await ( + await root.getDirectoryHandle("authorities") + ).removeEntry(tabScope.authorityToken, { recursive: true }); + } catch { + // Nothing was written for this authority. + } + return deletion; }, scope); } +// 2026-11-03 05-01 X1. The purge used to report a completed sweep while the +// other tab's put landed, and the object stayed readable after the account +// deletion. It now waits for that put and takes it with the partition. +test("05-01 an approved purge in another tab waits for a live put and takes it with the partition", async ({ + page, +}) => { + const secondPage = await page.context().newPage(); + const suffix = crypto.randomUUID().replaceAll("-", ""); + const scope: OpfsTabScope = { + namespace: "durable-objects", + authorityToken: `authority_${suffix}`, + namespaceToken: `namespace_${suffix}`, + partitionToken: `partition_${suffix}`, + }; + type Tab = import("../../src/adapters/storage/opfs/browser-opfs-runtime.ts").BrowserOpfsRuntime; + try { + await Promise.all([page.goto("/"), secondPage.goto("/")]); + if (!(await installOpfsTab(page, scope))) return; + expect(await installOpfsTab(secondPage, scope, true)).toBe(true); + + await page.evaluate(async () => { + const state = globalThis as unknown as { + __opfsTab: Tab; + __release?: () => void; + __put?: Promise; + }; + let streaming!: () => void; + const started = new Promise((resolve) => { + streaming = resolve; + }); + const gate = new Promise((resolve) => { + state.__release = resolve; + }); + state.__put = state.__opfsTab.objects.put({ + objectId: "object_tab_12345678", + expectedGeneration: null, + mediaType: "application/octet-stream", + source: { + byteLength: 4, + async *stream() { + streaming(); + await gate; + yield { ok: true as const, value: new Uint8Array([2, 7, 1, 8]) }; + }, + }, + }); + await started; + }); + await secondPage.evaluate(() => { + const state = globalThis as unknown as { + __opfsTab: Tab; + __purge?: Promise; + }; + state.__purge = state.__opfsTab.maintenance.enforcePolicies({ + reason: "ACCOUNT_DELETION", + }); + }); + await page.waitForTimeout(250); + const put = await page.evaluate(async () => { + const state = globalThis as unknown as { + __release: () => void; + __put: Promise; + }; + state.__release(); + return await state.__put; + }); + const report = await secondPage.evaluate( + async () => + await (globalThis as unknown as { __purge: Promise }).__purge, + ); + const opened = await secondPage.evaluate(async () => { + const runtime = (globalThis as unknown as { __opfsTab: Tab }).__opfsTab; + const result = await runtime.objects.open({ + objectId: "object_tab_12345678", + }); + return result.ok ? "OPENED" : result.error.code; + }); + + expect(put).toMatchObject({ ok: true, value: { generation: 1 } }); + expect(report).toMatchObject({ + ok: true, + value: { moreObjectsAvailable: false, partitionDeleted: true }, + }); + expect(opened).toBe("NOT_FOUND"); + } finally { + for (const tab of [page, secondPage]) { + await tab.evaluate(() => + (globalThis as unknown as { __opfsTab?: Tab }).__opfsTab?.close(), + ); + } + expect(await removeOpfsAuthority(page, scope)).toBe("DELETED"); + await secondPage.close(); + } +}); + test("05-01 a reconcile in another tab skips a live put and the put stays readable", async ({ page, }) => { @@ -375,37 +519,7 @@ test("05-01 a reconcile in another tab skips a live put and the put stays readab (globalThis as unknown as { __opfsTab?: Tab }).__opfsTab?.close(), ); } - const cleanup = await page.evaluate(async (tabScope) => { - const journalModulePath = - "/src/adapters/storage/opfs/indexeddb-opfs-journal.ts"; - const policyModulePath = "/src/adapters/storage/opfs/opfs-policy.ts"; - const { opfsJournalDatabaseName } = (await import( - /* @vite-ignore */ journalModulePath - )) as typeof import("../../src/adapters/storage/opfs/indexeddb-opfs-journal.ts"); - const { DEFAULT_OPFS_RUNTIME_POLICY } = (await import( - /* @vite-ignore */ policyModulePath - )) as typeof import("../../src/adapters/storage/opfs/opfs-policy.ts"); - const deletion = await new Promise((resolve) => { - const request = indexedDB.deleteDatabase( - opfsJournalDatabaseName(tabScope.authorityToken), - ); - request.onsuccess = () => resolve("DELETED"); - request.onerror = () => resolve(request.error?.name ?? "UNKNOWN"); - request.onblocked = () => resolve("BLOCKED"); - }); - try { - const root = await ( - await navigator.storage.getDirectory() - ).getDirectoryHandle(DEFAULT_OPFS_RUNTIME_POLICY.rootDirectoryName); - await ( - await root.getDirectoryHandle("authorities") - ).removeEntry(tabScope.authorityToken, { recursive: true }); - } catch { - // Nothing was written for this authority. - } - return deletion; - }, scope); - expect(cleanup).toBe("DELETED"); + expect(await removeOpfsAuthority(page, scope)).toBe("DELETED"); await secondPage.close(); } }); diff --git a/tests/unit/indexeddb-opfs-journal.test.ts b/tests/unit/indexeddb-opfs-journal.test.ts index daca31de..ed3dab4d 100644 --- a/tests/unit/indexeddb-opfs-journal.test.ts +++ b/tests/unit/indexeddb-opfs-journal.test.ts @@ -865,6 +865,51 @@ describe("[0929] 05-01 a corrupt row is skipped and counted; a partition's rows ).toMatchObject({ preparedObject: { corrupt: true } }); }); + it("counts the unfinished rows of one partition, a damaged one included (2026-11-03 05-01)", async () => { + const { factory, journal } = createHarness(); + await commitObject(journal, "transaction_obj00001", "object_aaaa0001", 1); + expect(await journal.countPartitionTransactions(scope)).toEqual({ + ok: true, + value: 0, + }); + expect( + await journal.begin( + beginInput("transaction_live0002", "object_bbbb0002", 1), + ), + ).toMatchObject({ ok: true }); + expect( + await journal.begin( + beginInput( + "transaction_kept0003", + "object_kept_0003", + 1, + otherPartition, + ), + ), + ).toMatchObject({ ok: true }); + // A row whose keys still read but whose value does not. + factory.seed("opfs-journal", { + ...(factory.readRaw("opfs-journal", "transaction_live0002") as object), + transactionId: "transaction_bad00004", + logicalKey: `${scopeKeyOf(scope)}|object_dddd0004`, + phase: "GARBLED", + }); + + expect(await journal.countPartitionTransactions(scope)).toEqual({ + ok: true, + value: 2, + }); + expect(await journal.countPartitionTransactions(otherPartition)).toEqual({ + ok: true, + value: 1, + }); + expect(await journal.removePartition(scope)).toMatchObject({ ok: true }); + expect(await journal.countPartitionTransactions(scope)).toEqual({ + ok: true, + value: 0, + }); + }); + it("removes every row keyed to one partition, the corrupt one included, and none of another", async () => { const { factory, journal } = createHarness(); await commitObject(journal, "transaction_obj00001", "object_aaaa0001", 1); diff --git a/tests/unit/opfs-byte-store.test.ts b/tests/unit/opfs-byte-store.test.ts index 2467ad41..fb60e1e3 100644 --- a/tests/unit/opfs-byte-store.test.ts +++ b/tests/unit/opfs-byte-store.test.ts @@ -243,6 +243,15 @@ function createJournal(): OpfsJournalPort & { ), ); }, + async countPartitionTransactions(scope) { + return browserDataSuccess( + [...transactions.values()].filter( + (transaction) => + transaction.scope.namespaceToken === scope.namespaceToken && + transaction.scope.partitionToken === scope.partitionToken, + ).length, + ); + }, async removePartition() { objects.clear(); transactions.clear(); diff --git a/tests/unit/opfs-worker-runtime.test.ts b/tests/unit/opfs-worker-runtime.test.ts index e3514111..5e1aa194 100644 --- a/tests/unit/opfs-worker-runtime.test.ts +++ b/tests/unit/opfs-worker-runtime.test.ts @@ -11,7 +11,10 @@ import type { BrowserStoragePolicy, ByteSource, } from "../../src/application/ports/browser-file-storage/shared.ts"; -import { browserDataSuccess } from "../../src/adapters/browser-file-storage/result.ts"; +import { + browserDataFailure, + browserDataSuccess, +} from "../../src/adapters/browser-file-storage/result.ts"; import { createOpfsByteStoreAdapter } from "../../src/adapters/storage/opfs/opfs-byte-store-adapter.ts"; import { createIndexedDbOpfsJournal } from "../../src/adapters/storage/opfs/indexeddb-opfs-journal.ts"; import { @@ -649,6 +652,7 @@ function referenceJournal(referenced: ReadonlySet): OpfsJournalPort { complete: unused, rollback: unused, listCommittedObjects: unused, + countPartitionTransactions: unused, removePartition: unused, async listIncomplete() { return browserDataSuccess({ @@ -2414,8 +2418,12 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh expect(filesUnder(root, scopeA)).toEqual([]); }); - it("never sweeps the chunk of a put that runs while the purge does", async () => { - const { tab } = sharedRootTabs(); + // 2026-11-03 05-01 X1. The purge used to walk past a put that began before + // it, report a completed sweep and leave that object readable. A put or + // delete of the partition that has not finished now sends the purge to the + // partition delete, which waits for it and then takes it. + it("waits for a put that began before the purge and takes it with the partition", async () => { + const { root, tab } = sharedRootTabs(); const purger = tab("p", authority); const writer = tab("w", authority); expect(await putBytes(purger, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true }); @@ -2432,23 +2440,127 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh stalled.release(); expect(await put).toMatchObject({ ok: true }); - expect(await purge).toMatchObject({ ok: true, value: { removedObjects: 1 } }); - expect(await openedBytes(writer, "object_late_0001")).toEqual({ - generation: 1, - bytes: [5], + const report = await purge; + expect(report).toMatchObject({ + ok: true, + value: { + removedObjects: 1, + moreObjectsAvailable: false, + partitionDeleted: true, + }, }); + expect(report.ok && report.value.chunkSweep).toBeUndefined(); + expect(filesUnder(root, scopeA)).toEqual([]); + expect(await openedBytes(writer, "object_late_0001")).toBe("NOT_FOUND"); }); + // 2026-11-03 05-01 X2, X2b, X3. A put that stopped before it finished leaves + // its journal row and its staged files. The purge reported a completed sweep + // over them; the next reconcile then committed a FILES_READY put, so the + // account's file came back as a readable object. + it.each([ + ["stopped before commit (FILES_READY)", "commitPut", false], + ["stopped while uploading (PREPARING)", "markFilesReady", false], + ["whose journal row is damaged", "commitPut", true], + ] as const)( + "takes the partition when an approved purge finds a put %s", + async (_label, failingStep, damageRow) => { + const { root, idb, tab } = sharedRootTabs(); + const journal = createIndexedDbOpfsJournal({ + authorityToken: scopeA.authorityToken, + factory: idb.factory, + keyRange: idb.keyRange, + }); + const writerWorker = loopbackGateway( + createOpfsWorkerRuntime({ + root: root as unknown as FileSystemDirectoryHandle, + crypto: globalThis.crypto, + policy: runtimePolicy, + leaseManager: exclusiveLeases(), + dedicatedWorker: true, + supportsSynchronousAccessHandles: false, + }), + ); + const unavailable = async () => + browserDataFailure("UNAVAILABLE", "INDEXEDDB_WRITE", { + retryable: true, + recovery: "RETRY", + }); + // The tab crashes at this step: the journal write never lands and, + // before commit, its compensation never runs either. + const writer = tab("w", { + journal: { ...journal, [failingStep]: unavailable } as OpfsJournalPort, + worker: { + ...writerWorker, + abortPreparedPut: async () => + browserDataFailure("UNAVAILABLE", "OBJECT_WRITE", { + retryable: true, + recovery: "RETRY", + }), + }, + }); + const purger = tab("p", authority); + expect(await putBytes(purger, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true }); + expect(await putBytes(writer, "object_dead_0001", [9, 9, 9])).toMatchObject({ + ok: false, + }); + expect(idb.readRaw("opfs-journal", "transaction_w_1")).toBeDefined(); + if (damageRow) { + idb.seed("opfs-journal", { + ...(idb.readRaw("opfs-journal", "transaction_w_1") as object), + phase: "GARBLED", + }); + } + + const report = await purger.maintenance.enforcePolicies({ + reason: "ACCOUNT_DELETION", + }); + + expect(report).toMatchObject({ + ok: true, + value: { moreObjectsAvailable: false, partitionDeleted: true }, + }); + expect(filesUnder(root, scopeA)).toEqual([]); + expect(idb.readRaw("opfs-journal", "transaction_w_1")).toBeUndefined(); + // Nothing is left for a later reconcile to bring back. + expect(await purger.maintenance.reconcile()).toMatchObject({ + ok: true, + value: { committedTransactions: 0, corruptTransactions: 0 }, + }); + expect(await openedBytes(purger, "object_dead_0001")).toBe("NOT_FOUND"); + expect(filesUnder(root, scopeA)).toEqual([]); + }, + ); + // [0929] 05-02. Another tab overwrites the object the purge is removing, so // the purge's remove ends in CONFLICT. That purge is not finished and must - // not claim a completed chunk sweep. + // not claim a completed chunk sweep. The overwrite finishes between the + // purge's listing and its remove: one still running when the purge checks + // the journal sends it to the partition delete instead (2026-11-03 05-01). it("reports a purge that skipped a changing object as unfinished", async () => { - const { root, tab } = sharedRootTabs(); - const purger = tab("p", authority); - const writer = tab("w", authority); - expect(await putBytes(purger, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true }); + const { root, idb, tab } = sharedRootTabs(); + const journal = createIndexedDbOpfsJournal({ + authorityToken: scopeA.authorityToken, + factory: idb.factory, + keyRange: idb.keyRange, + }); const stalled = stalledSource(); - const overwrite = writer.objects.put({ + let overwrite: ReturnType | undefined; + const purger = tab("p", { + ...authority, + journal: { + ...journal, + async listCommittedObjects(request) { + const page = await journal.listCommittedObjects(request); + stalled.release(); + await overwrite; + return page; + }, + }, + }); + const writer = tab("w", authority); + expect(await putBytes(writer, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true }); + overwrite = writer.objects.put({ objectId: "object_secret_1", expectedGeneration: 1, mediaType: "application/octet-stream", @@ -2456,8 +2568,6 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh }); await stalled.streaming; const purge = purger.maintenance.enforcePolicies({ reason: "ACCOUNT_DELETION" }); - await new Promise((resolve) => setTimeout(resolve, 20)); - stalled.release(); expect(await overwrite).toMatchObject({ ok: true }); const first = await purge; From 7b55f0f83d0f065a55e2345fce3b9780c6231b56 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:34:28 +0900 Subject: [PATCH 06/18] =?UTF-8?q?fix(storage):=20partition=20lock=EC=9D=84?= =?UTF-8?q?=20=EA=B8=B0=EB=8B=A4=EB=A6=AC=EB=8A=94=20put=C2=B7delete?= =?UTF-8?q?=EA=B0=80=20=EC=9E=90=EA=B8=B0=20abort=EB=A1=9C=20=EB=81=9D?= =?UTF-8?q?=EB=82=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: withTransactionLock은 partition lock을 signal 없이 요청한다 (withPartitionLock("shared", operation, undefined, run)). put·remove의 request.signal이 거기까지 오지 않고, Web Locks 요청은 signal이 없으면 시간 제한도 없다. mutationLockWaitTimeoutMs는 worker의 origin lease에만 걸린다. 다른 탭의 partition 삭제가 큰 업로드를 기다리는 동안 같은 partition에 put·remove(또는 만료 객체를 지우는 open)를 부르고 취소하면, 삭제가 끝날 때까지 결과가 오지 않는다(X5: abort 뒤 200 ms 동안 대기). 05-01로 정상 purge도 partition 삭제를 쓰게 되어 이 대기가 더 자주 난다. 고른 방법: put·remove가 request.signal을 withTransactionLock에 넘기고, withPartitionLock은 kernel createAbortableOperation으로 caller signal과 mutationLockWaitTimeoutMs를 묶은 signal로 lock을 요청한다. caller abort면 ABORTED, 시간이 다 되면 BLOCKED(retryable, RETRY)다. worker의 acquireLease와 같은 값·같은 결과다. lock을 얻으면 바로 close해 타이머를 지운다(얻은 lock에 대한 abort는 Web Locks에서 아무 일도 하지 않는다). lock 전 abort는 journal begin 전이라 보상할 것이 없다. 버린 대안: signal만 넘기기(리뷰 최소안). 취소는 되지만 "상한 없음"이 남는다. 새 정책 값 추가. 같은 의미의 값이 이미 있다. 위험·한계: 같은 상한이 partition 삭제(exclusive)의 기다림에도 걸린다. 다른 탭 put이 10분(기본값)보다 오래 걸리면 purge가 BLOCKED로 끝나고 호출자가 다시 부른다. 전에는 끝없이 기다렸다. 실제 브라우저에서 abort 경합은 돌리지 않았고 Node Web Locks로만 확인했다. offline-indexeddb 번들 37,521 → 37,555 / 38,500 gzip B. 검증: - RED: opfs-worker-runtime.test.ts 새 2건. abort한 put이 200 ms 안에 끝나지 않음(STILL_WAITING), 가짜 시계로 상한을 넘겨도 put이 끝나지 않아 10초 timeout. - GREEN: OPFS 단위 3파일 + optional-runtime-host + tests/recipes 151건 통과. check:types, 바꾼 파일 eslint, check:optional-recipes:source PASS, verify:documentation 통과. - browser: heavy lock 안에서 opfs-runtime·indexeddb-runtime spec 3엔진 27/27 통과. 첫 실행은 dev server가 실행 중에 페이지를 다시 불러 5건이 "Execution context was destroyed"로 떨어졌고, 다시 돌려 통과했다. Refs: docs/reviews/2026-11-03-maturity-review/05-adapters-storage-kernel.md 05-02 --- .../browser-file-storage-recovery.md | 5 +- .../storage/opfs/opfs-byte-store-adapter.ts | 33 ++++- src/adapters/storage/opfs/opfs-policy.ts | 4 +- tests/unit/opfs-worker-runtime.test.ts | 125 ++++++++++++++++++ 4 files changed, 158 insertions(+), 9 deletions(-) diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index 074dd405..ddf1006d 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -489,7 +489,10 @@ VD-15 목표 runtime을 먼저 구현한다. approved purge meets another tab's put parked before …"(5가지 순서). - 한계: 삭제는 진행 중인 put·delete를 기다린다. source가 멈춘 put은 put idle bound(05-07)까지 삭제를 붙잡는다. purge의 `signal`을 abort하면 기다림을 - 멈추고 `ABORTED`를 반환한다. purge가 journal row를 센 뒤에 시작한 put, 삭제가 + 멈추고 `ABORTED`를 반환한다. 삭제 뒤에 줄 선 put·delete도 자기 `signal`로 + 기다림을 멈춘다. 어느 쪽이든 partition lock 기다림은 + `mutationLockWaitTimeoutMs`(기본 10분)에서 `BLOCKED`(retryable)로 끝난다 + (2026-11-03 05-02). purge가 journal row를 센 뒤에 시작한 put, 삭제가 lock을 요청한 뒤 온 put의 데이터는 남는다(point-in-time). purge 전에 그 partition의 쓰기를 멈추는 것이 composition의 몫이다. - lock/worker 문제면 OPFS write off → approved capped fallback 또는 online-only diff --git a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts index f2b8e2ad..3912218f 100644 --- a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts +++ b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts @@ -23,6 +23,7 @@ import { browserDataFailure, browserDataSuccess, } from "../../browser-file-storage/result.ts"; +import { createAbortableOperation } from "../../platform/abortable-operation.ts"; import { byteBucket, observeOpfsSafely, @@ -221,6 +222,7 @@ export function createOpfsByteStoreAdapter( return await withTransactionLock( transactionId, "OBJECT_WRITE", + request.signal, async () => { // STO-01. The logical generation is reused across transactions; this // token makes the physical target unique so a late compensation can never @@ -495,6 +497,7 @@ export function createOpfsByteStoreAdapter( return await withTransactionLock( transactionId, "OBJECT_DELETE", + request.signal, async () => { const begun = await dependencies.journal.begin({ transactionId, @@ -1118,6 +1121,7 @@ export function createOpfsByteStoreAdapter( async function withTransactionLock( transactionId: string, operation: "OBJECT_WRITE" | "OBJECT_DELETE", + signal: AbortSignal | undefined, run: () => Promise>, ): Promise> { let release: (() => void) | null; @@ -1132,7 +1136,7 @@ export function createOpfsByteStoreAdapter( // A fresh transaction id is never held; a holder means a duplicate id. if (!release) return browserDataFailure("CONFLICT", operation); try { - return await withPartitionLock("shared", operation, undefined, run); + return await withPartitionLock("shared", operation, signal, run); } finally { release(); } @@ -1147,6 +1151,11 @@ export function createOpfsByteStoreAdapter( * files after the directory went, the second step took its journal row, and * nothing was left to clean those files. Tested by "leaves no partition * bytes when an approved purge meets another tab's put parked before …". + * + * 2026-11-03 05-02. The wait ends on the caller's own abort and, like the + * worker's origin lease, at `mutationLockWaitTimeoutMs` as a retryable + * BLOCKED. A put or delete queued behind a long partition delete used to + * ignore its signal until that delete let go. */ async function withPartitionLock( mode: LockMode, @@ -1154,24 +1163,34 @@ export function createOpfsByteStoreAdapter( signal: AbortSignal | undefined, run: () => Promise>, ): Promise> { + const wait = createAbortableOperation({ + ...(signal ? { signal } : {}), + timeoutMs: policy.mutationLockWaitTimeoutMs, + }); let granted = false; try { return await requestLock( `${policy.mutationLockName}:partition:${scope.authorityToken}:${scope.namespaceToken}:${scope.partitionToken}`, - { mode, ...(signal ? { signal } : {}) }, + { mode, signal: wait.signal }, async () => { granted = true; + // Only the wait is bounded; aborting a granted request is a no-op. + wait.close(); return await run(); }, ); } catch (error) { if (granted) throw error; - return signal?.aborted + const terminal = wait.terminal(); + return terminal === "CALLER_ABORT" ? browserDataFailure("ABORTED", operation) - : browserDataFailure("UNAVAILABLE", operation, { - retryable: true, - recovery: "RETRY", - }); + : browserDataFailure( + terminal === "DEADLINE" ? "BLOCKED" : "UNAVAILABLE", + operation, + { retryable: true, recovery: "RETRY" }, + ); + } finally { + wait.close(); } } diff --git a/src/adapters/storage/opfs/opfs-policy.ts b/src/adapters/storage/opfs/opfs-policy.ts index c0776aa8..f15e415d 100644 --- a/src/adapters/storage/opfs/opfs-policy.ts +++ b/src/adapters/storage/opfs/opfs-policy.ts @@ -17,7 +17,9 @@ export type OpfsRuntimePolicy = Readonly<{ /** * R-5.3 (D-3). How long a request may queue for the origin mutation lock. * Another context's put holds that lock for its whole upload, so this wait - * is bounded on its own and never counted against `rpcTimeoutMs`. + * is bounded on its own and never counted against `rpcTimeoutMs`. The page + * bounds its wait for the partition lock by the same value (2026-11-03 + * 05-02). */ mutationLockWaitTimeoutMs: number; /** diff --git a/tests/unit/opfs-worker-runtime.test.ts b/tests/unit/opfs-worker-runtime.test.ts index 5e1aa194..35d66fcd 100644 --- a/tests/unit/opfs-worker-runtime.test.ts +++ b/tests/unit/opfs-worker-runtime.test.ts @@ -2900,6 +2900,131 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh }); }); +// 2026-11-03 05-02. A put or delete queued behind a partition delete held the +// partition lock request without its caller's signal and without a bound, so +// cancelling it did nothing until the delete let go. +describe("05-02 a put or delete waiting on the partition lock", () => { + const lockName = (policy: typeof runtimePolicy) => + `${policy.mutationLockName}:partition:${scopeA.authorityToken}:${scopeA.namespaceToken}:${scopeA.partitionToken}`; + + afterEach(() => { + vi.useRealTimers(); + }); + + /** Another tab's partition delete holds the lock until `release`. */ + async function heldPartitionLock(policy: typeof runtimePolicy) { + const holding = checkpoint(); + const holder = navigator.locks.request( + lockName(policy), + { mode: "exclusive" }, + () => holding.pass(), + ); + await holding.reached; + return { + async release() { + holding.open(); + await holder; + }, + }; + } + + async function queuedOnPartitionLock( + policy: typeof runtimePolicy, + tick: () => Promise, + ) { + while ( + !(await navigator.locks.query()).pending?.some( + (lock) => lock.name === lockName(policy) && lock.mode === "shared", + ) + ) { + await tick(); + } + } + + const settledWithin = async (work: Promise, ms: number) => + await Promise.race([ + work, + new Promise<"STILL_WAITING">((resolve) => + setTimeout(() => resolve("STILL_WAITING"), ms), + ), + ]); + + it("ends a queued put and a queued delete as soon as their caller aborts", async () => { + const { tab } = sharedRootTabs(); + const store = tab("s"); + expect( + await store.objects.put({ + objectId: "object_kept_0001", + expectedGeneration: null, + mediaType: "application/octet-stream", + source: oneByteSource(), + }), + ).toMatchObject({ ok: true }); + const held = await heldPartitionLock(runtimePolicy); + const controller = new AbortController(); + + const put = store.objects.put({ + objectId: "object_aborted01", + expectedGeneration: null, + mediaType: "application/octet-stream", + source: oneByteSource(), + signal: controller.signal, + }); + const removal = store.objects.remove({ + objectId: "object_kept_0001", + expectedGeneration: 1, + signal: controller.signal, + }); + await queuedOnPartitionLock( + runtimePolicy, + () => new Promise((resolve) => setTimeout(resolve, 1)), + ); + controller.abort(); + + expect(await settledWithin(put, 200)).toMatchObject({ + ok: false, + error: { code: "ABORTED", operation: "OBJECT_WRITE" }, + }); + expect(await settledWithin(removal, 200)).toMatchObject({ + ok: false, + error: { code: "ABORTED", operation: "OBJECT_DELETE" }, + }); + await held.release(); + expect(await openedBytes(store, "object_aborted01")).toBe("NOT_FOUND"); + expect(await openedBytes(store, "object_kept_0001")).toEqual({ + generation: 1, + bytes: [6], + }); + }); + + it("ends a partition lock wait at the policy bound as a retryable BLOCKED", async () => { + const policy = resolveOpfsRuntimePolicy({ + ...runtimePolicy, + mutationLockWaitTimeoutMs: 300_000, + }); + const { tab } = sharedRootTabs(policy); + const store = tab("s"); + const held = await heldPartitionLock(policy); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + + const put = store.objects.put({ + objectId: "object_blocked01", + expectedGeneration: null, + mediaType: "application/octet-stream", + source: oneByteSource(), + }); + await queuedOnPartitionLock(policy, () => vi.advanceTimersByTimeAsync(1)); + await vi.advanceTimersByTimeAsync(policy.mutationLockWaitTimeoutMs); + + expect(await put).toMatchObject({ + ok: false, + error: { code: "BLOCKED", operation: "OBJECT_WRITE", retryable: true }, + }); + vi.useRealTimers(); + await held.release(); + }); +}); + /** A step that parks until opened and says when something reached it. */ function checkpoint(): Readonly<{ reached: Promise; From fd6b6315c0daf611b710a075f309c7eb7b19241f Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:38:17 +0900 Subject: [PATCH 07/18] =?UTF-8?q?fix(storage):=20=EC=86=8C=EC=86=8D=20part?= =?UTF-8?q?ition=EC=9D=B4=20=EC=97=86=EB=8A=94=20=EC=86=90=EC=83=81=20jour?= =?UTF-8?q?nal=20=ED=96=89=EC=9D=84=20=EB=94=B0=EB=A1=9C=20=EC=84=B8?= =?UTF-8?q?=EA=B3=A0=20=EA=B2=BD=EB=B3=B4=EC=97=90=EC=84=9C=20=EB=BA=80?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: partition 삭제는 journal 행을 LOGICAL_KEY_INDEX로 찾는다. 인덱스에는 logicalKey 값이 있는 행만 들어가므로, 그 값까지 깨진 행은 승인된 ACCOUNT_DELETION으로도 지워지지 않는다(X4: partition 파일 0개인데 행은 남음). 그 행은 reconcile마다 corruptTransactions 1, OBJECT_RECONCILE DEGRADED/CORRUPT_DATA로 남는다. runbook은 "키로 찾으므로 손상 row도 지워진다", "partition이 승인된 purge로 지워질 때만 함께 지워진다"고 적고 수동 삭제를 금지한다. 운영자는 늘 켜진 경보를 받지만 할 수 있는 일이 없고, 그 경보가 진짜 손상을 가린다. 고른 방법(리뷰 (a)+(b)): 소속을 모르는 행은 지울 근거가 없으므로 지우지 않는다. 대신 - journal의 listIncomplete가 손상 행 가운데 이 authority의 partition 키 범위에 들지 않는 행을 unattributedRows로 따로 센다(0이면 칸 없음). - reconcile report에 unattributedCorruptTransactions를 싣고(0이면 칸 없음), DEGRADED 관측은 purge가 지울 수 있는 손상 행이 있을 때만 낸다. - runbook §0·§7 문장을 코드와 맞추고, 이런 행에 대해 할 일(같은 수면 없음, 늘면 writer를 찾음, 수동 삭제 금지)을 적었다. 버린 대안: (a)만 — 경보가 계속 켜진다. (c) 소속을 모르는 행 자동 삭제 — 그 행이 가리키던 staging을 추적할 근거가 사라진다(runbook §0 3번). 위험·한계: 공개 타입에 선택 칸 두 개가 는다(OpfsJournalPage .unattributedRows, OpfsReconciliationReport .unattributedCorruptTransactions). 직접 만든 journal이 칸을 채우지 않으면 지금처럼 모든 손상 행이 경보에 남는다. 소속 없는 행만 있을 때 관측이 SUCCEEDED가 되므로, 그 수는 report로만 보인다. 이런 행의 staging은 purge의 partition 삭제 조건(countPartitionTransactions)에 잡히지 않는다. offline-indexeddb 번들 37,555 → 37,705 / 38,500 gzip B. 검증: - RED: indexeddb-opfs-journal.test.ts 새 테스트가 unattributedRows 없음, opfs-worker-runtime.test.ts 새 X4 테스트가 unattributedCorruptTransactions 없음으로 실패. - GREEN: 키 있는 손상 행은 removePartition이 지우고 키 없는 행은 남는다. 키 없는 행만 있으면 관측 SUCCEEDED, 키 있는 손상 행이 더해지면 DEGRADED:CORRUPT_DATA. OPFS 단위 3파일 + optional-runtime-host + tests/recipes + tests/contract 176건 통과. check:types, 바꾼 파일 eslint, check:optional-recipes:source PASS, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/05-adapters-storage-kernel.md 05-03 --- .../browser-file-storage-recovery.md | 20 +++++-- .../storage/opfs/indexeddb-opfs-journal.ts | 25 +++++++++ .../storage/opfs/opfs-byte-store-adapter.ts | 13 ++++- .../ports/browser-file-storage/opfs-ports.ts | 13 +++++ tests/unit/indexeddb-opfs-journal.test.ts | 55 ++++++++++++++++++- tests/unit/opfs-worker-runtime.test.ts | 54 ++++++++++++++++++ 6 files changed, 173 insertions(+), 7 deletions(-) diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index ddf1006d..07f5f29e 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -38,8 +38,18 @@ cleanup 결과를 확인하지 못하면 성공 값이 아니라 실패로 답 저장소 손상이다. 예전에는 이런 row 하나가 목록 전체를 실패시켜 authority의 모든 partition에서 reconcile과 GC가 멈췄다. 이제 나머지 row와 orphan GC는 계속 돌고, 관측은 `OBJECT_RECONCILE` `DEGRADED` / `CORRUPT_DATA`로 남는다 - ([0929] 05-01). reconcile은 그 row를 지우지 않는다. 그 row가 속한 - partition이 승인된 purge로 통째로 지워질 때만 함께 지워진다(§7). + ([0929] 05-01). reconcile은 그 row를 지우지 않는다. 그 partition이 승인된 + purge로 통째로 지워질 때 함께 지워지는 것은 partition 키(`logicalKey`)를 + 읽을 수 있는 row뿐이다(§7). 승인된 LOGOUT/ACCOUNT_DELETION purge는 그런 + row를 보면 그 partition을 지운다(2026-11-03 05-01). + - `unattributedCorruptTransactions`: 위 수 가운데 `logicalKey`까지 읽을 수 + 없는 row 수다. 어느 partition에도 속하지 않아 partition 삭제도 지우지 + 못한다. 그래서 따로 세고 `DEGRADED` 관측에서 뺀다(2026-11-03 05-03). 예전에는 + 이런 row 하나가 reconcile마다 `DEGRADED`를 남겨 경보가 늘 켜졌다. 같은 수로 + 남아 있으면 할 일이 없다. 수가 늘면 키 없는 row를 쓴 writer(다른 release, + 외부 도구)를 찾는다. 이 row도 수동으로 지우지 않는다(3번). 그 row의 + staging은 partition 디렉터리 안에 있어 그 partition이 지워지면 함께 + 지워지지만, 이 row는 purge의 partition 삭제 조건에 들지 않는다. 3. journal row를 수동으로 삭제하지 않는다. row가 사라지면 stale staging을 추적할 근거가 사라지고 quota만 누수된다. 4. OPFS root나 journal database를 통째로 삭제하거나 schema를 downgrade하지 @@ -466,8 +476,10 @@ VD-15 목표 runtime을 먼저 구현한다. - 범위: worker가 origin mutation lease를 쥔 채 `authorities///` 디렉터리를 지우고, 이어서 journal에서 그 partition 키로 시작하는 object·journal·chunk - reference row와 budget row를 지운다. 값을 읽지 않고 키로 찾으므로 손상 row도 - 지워진다. scope binding row는 남긴다. 다른 partition은 건드리지 않는다. + reference row와 budget row를 지운다. 값을 읽지 않고 키로 찾으므로 키가 남은 + 손상 row도 지워진다. journal row는 `logicalKey` 인덱스로 찾으므로 그 값까지 + 깨진 row는 남는다(§0 2번 `unattributedCorruptTransactions`). scope binding + row는 남긴다. 다른 partition은 건드리지 않는다. - 결과: `partitionDeleted: true`, `moreObjectsAvailable: false`, 건너뛴 row 수 `corruptObjects`. 이 report면 그 partition의 bytes는 모두 지워진 것이다. `chunkSweep`은 없다. 디렉터리는 지웠는데 journal 정리가 실패하면 실패를 diff --git a/src/adapters/storage/opfs/indexeddb-opfs-journal.ts b/src/adapters/storage/opfs/indexeddb-opfs-journal.ts index b449952f..ea4b49c9 100644 --- a/src/adapters/storage/opfs/indexeddb-opfs-journal.ts +++ b/src/adapters/storage/opfs/indexeddb-opfs-journal.ts @@ -699,6 +699,7 @@ export function createIndexedDbOpfsJournal( (transaction, context) => { const rows: OpfsJournalTransaction[] = []; let corruptRows = 0; + let unattributedRows = 0; walkIndexedDbCursor({ request: transaction .objectStore(JOURNAL_STORE) @@ -720,6 +721,8 @@ export function createIndexedDbOpfsJournal( rows.push(cursor.value); } else { corruptRows += 1; + // 2026-11-03 05-03. No partition's key range holds it. + if (!hasPartitionKey(cursor.value)) unattributedRows += 1; } return { kind: "CONTINUE" }; }, @@ -730,6 +733,7 @@ export function createIndexedDbOpfsJournal( moreAvailable: summary.reason === "STOPPED" && rows.length === limit, corruptRows, + ...(unattributedRows ? { unattributedRows } : {}), }), ); }, @@ -969,6 +973,27 @@ export function createIndexedDbOpfsJournal( return Object.freeze(journal); + /** + * 2026-11-03 05-03. Whether a row's `logicalKey` lies in the key range + * `removePartition` deletes for some partition of this authority. + */ + function hasPartitionKey(value: unknown): boolean { + const key = + value && typeof value === "object" && "logicalKey" in value + ? value.logicalKey + : undefined; + if (typeof key !== "string") return false; + const [authority, namespaceToken, partitionToken, objectId] = + key.split("|"); + return ( + authority === dependencies.authorityToken && + objectId !== undefined && + [namespaceToken, partitionToken].every( + (token) => token !== undefined && SAFE_BOUNDARY_ID.test(token), + ) + ); + } + async function commitMutation( transactionId: string, fencingToken: string, diff --git a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts index 3912218f..9c918f51 100644 --- a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts +++ b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts @@ -639,6 +639,7 @@ export function createOpfsByteStoreAdapter( // skipped. The page is read again under those locks: a row listed while // its owner still ran may have moved on before the owner let go. const held = new Map void>(); + let unattributed: number; try { for (const transaction of listed.value.transactions) { let release: (() => void) | null; @@ -663,6 +664,7 @@ export function createOpfsByteStoreAdapter( report.moreTransactionsAvailable = page.value.moreAvailable; // [0929] 05-01. The journal skipped these rows; they stop nothing now. report.corruptTransactions = page.value.corruptRows; + unattributed = page.value.unattributedRows ?? 0; for (const transaction of page.value.transactions) { if (!held.has(transaction.transactionId)) continue; if (request.signal?.aborted) { @@ -709,12 +711,19 @@ export function createOpfsByteStoreAdapter( operation: "OBJECT_RECONCILE", transactionBucket: transactionBucket(report.inspectedTransactions), // A skipped corrupt row is observed, not hidden behind a success. - ...(report.corruptTransactions + // 2026-11-03 05-03. One no partition owns is reported, not observed: + // nothing clears it, so it would keep the signal on for good. + ...(report.corruptTransactions > unattributed ? { outcome: "DEGRADED", failureCode: "CORRUPT_DATA" } : { outcome: "SUCCEEDED" }), }); return browserDataSuccess( - Object.freeze({ ...report }), + Object.freeze({ + ...report, + ...(unattributed + ? { unattributedCorruptTransactions: unattributed } + : {}), + }), ); }, diff --git a/src/application/ports/browser-file-storage/opfs-ports.ts b/src/application/ports/browser-file-storage/opfs-ports.ts index a43ddffd..7c638698 100644 --- a/src/application/ports/browser-file-storage/opfs-ports.ts +++ b/src/application/ports/browser-file-storage/opfs-ports.ts @@ -131,6 +131,13 @@ export type OpfsReconciliationReport = Readonly<{ * zero is storage damage for an operator to look at. */ corruptTransactions: number; + /** + * 2026-11-03 05-03. Of `corruptTransactions`, the rows whose partition key + * cannot be read either. No approved partition delete takes them, so they + * stay; they are not observed as `DEGRADED`, which is kept for damage a + * purge can clear. Present only when there were some. + */ + unattributedCorruptTransactions?: number; }>; export type OpfsPolicyMaintenanceReport = Readonly<{ @@ -324,6 +331,12 @@ export type OpfsJournalPage = Readonly<{ transactions: readonly OpfsJournalTransaction[]; moreAvailable: boolean; corruptRows: number; + /** + * 2026-11-03 05-03. Of `corruptRows`, the rows without a readable partition + * key, which `removePartition` never reaches. Absent means none, or a + * journal that does not tell them apart. + */ + unattributedRows?: number; }>; export type OpfsCommittedObjectPage = Readonly<{ diff --git a/tests/unit/indexeddb-opfs-journal.test.ts b/tests/unit/indexeddb-opfs-journal.test.ts index ed3dab4d..bd193f6e 100644 --- a/tests/unit/indexeddb-opfs-journal.test.ts +++ b/tests/unit/indexeddb-opfs-journal.test.ts @@ -508,7 +508,12 @@ describe("IndexedDB OPFS journal", () => { // [0929] 05-01. The row is counted, not returned and not deleted. expect(await journal.listIncomplete(10)).toEqual({ ok: true, - value: { transactions: [], moreAvailable: false, corruptRows: 1 }, + value: { + transactions: [], + moreAvailable: false, + corruptRows: 1, + unattributedRows: 1, + }, }); expect(factory.readRaw("opfs-journal", "transaction_88888888")).toMatchObject({ corrupt: true, @@ -865,6 +870,54 @@ describe("[0929] 05-01 a corrupt row is skipped and counted; a partition's rows ).toMatchObject({ preparedObject: { corrupt: true } }); }); + // 2026-11-03 05-03. The partition delete finds journal rows by their + // `logicalKey`. A damaged row that still has one goes with its partition; a + // row without one belongs to no partition, so no delete takes it. The page + // tells the two apart so an operator can. + it("tells a damaged journal row its partition delete takes from one no partition owns", async () => { + const { factory, journal } = createHarness(); + // Opens the database the seeds below write into. + expect(await journal.listIncomplete(10)).toMatchObject({ ok: true }); + factory.seed("opfs-journal", { + transactionId: "transaction_keyed001", + logicalKey: `${scopeKeyOf(scope)}|object_aaaa0001`, + startedAtEpochMs: 1, + phase: "GARBLED", + }); + factory.seed("opfs-journal", { + transactionId: "transaction_keyless1", + startedAtEpochMs: 2, + corrupt: true, + }); + + expect(await journal.listIncomplete(10)).toEqual({ + ok: true, + value: { + transactions: [], + moreAvailable: false, + corruptRows: 2, + unattributedRows: 1, + }, + }); + expect(await journal.removePartition(scope)).toMatchObject({ ok: true }); + + expect( + factory.readRaw("opfs-journal", "transaction_keyed001"), + ).toBeUndefined(); + expect( + factory.readRaw("opfs-journal", "transaction_keyless1"), + ).toMatchObject({ corrupt: true }); + expect(await journal.listIncomplete(10)).toEqual({ + ok: true, + value: { + transactions: [], + moreAvailable: false, + corruptRows: 1, + unattributedRows: 1, + }, + }); + }); + it("counts the unfinished rows of one partition, a damaged one included (2026-11-03 05-01)", async () => { const { factory, journal } = createHarness(); await commitObject(journal, "transaction_obj00001", "object_aaaa0001", 1); diff --git a/tests/unit/opfs-worker-runtime.test.ts b/tests/unit/opfs-worker-runtime.test.ts index 35d66fcd..a9699b72 100644 --- a/tests/unit/opfs-worker-runtime.test.ts +++ b/tests/unit/opfs-worker-runtime.test.ts @@ -2720,6 +2720,60 @@ describe("05-04 a LOGOUT or ACCOUNT_DELETION purge leaves no partition bytes beh }); }); + // 2026-11-03 05-03 X4. A damaged journal row without a readable partition + // key outlives every approved partition delete. It used to keep each + // reconcile DEGRADED for good, with nothing the runbook lets anyone do. It + // is now counted apart and kept out of the partition damage signal; a row + // its partition delete would take still raises it. + it("reports a damaged journal row no partition owns apart from partition damage", async () => { + const { root, idb, tab } = sharedRootTabs(); + const outcomes: string[] = []; + const store = tab("s", { + ...authority, + observer: (observation) => { + if ( + observation.operation === "OBJECT_RECONCILE" && + observation.outcome !== "STARTED" + ) { + outcomes.push(`${observation.outcome}:${observation.failureCode ?? ""}`); + } + }, + }); + expect(await putBytes(store, "object_secret_1", [1, 2, 3])).toMatchObject({ ok: true }); + idb.seed("opfs-objects", corruptObjectRow(scopeA, "object_secret_2")); + idb.seed("opfs-journal", { + transactionId: "transaction_corrupt1", + startedAtEpochMs: 1, + corrupt: true, + }); + + expect( + await store.maintenance.enforcePolicies({ reason: "ACCOUNT_DELETION" }), + ).toMatchObject({ ok: true, value: { partitionDeleted: true } }); + expect(filesUnder(root, scopeA)).toEqual([]); + expect(idb.readRaw("opfs-journal", "transaction_corrupt1")).toMatchObject({ + corrupt: true, + }); + + expect(await store.maintenance.reconcile()).toMatchObject({ + ok: true, + value: { corruptTransactions: 1, unattributedCorruptTransactions: 1 }, + }); + expect(outcomes).toEqual(["SUCCEEDED:"]); + + idb.seed("opfs-journal", { + transactionId: "transaction_keyed001", + logicalKey: `${scopeA.authorityToken}|${scopeA.namespaceToken}|${scopeA.partitionToken}|object_secret_3`, + startedAtEpochMs: 2, + phase: "GARBLED", + }); + expect(await store.maintenance.reconcile()).toMatchObject({ + ok: true, + value: { corruptTransactions: 2, unattributedCorruptTransactions: 1 }, + }); + expect(outcomes.at(-1)).toBe("DEGRADED:CORRUPT_DATA"); + }); + it("removes a partition directory only under the origin mutation lease", async () => { const root = new MemoryDirectory(); const leases = exclusiveLeases(); From 8da33a5cf009763588a7d8acf42977022c743f4e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:40:25 +0900 Subject: [PATCH 08/18] =?UTF-8?q?test(storage):=20=EB=A9=94=EB=AA=A8?= =?UTF-8?q?=EB=A6=AC=20OPFS=20=ED=8C=8C=EC=9D=BC=20=EC=8B=9C=EC=8A=A4?= =?UTF-8?q?=ED=85=9C=EC=9D=84=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20helper?= =?UTF-8?q?=EB=A1=9C=20=EC=98=AE=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: OPFS worker runtime을 메모리에서 돌리는 MemoryDirectory·MemoryFile이 tests/unit/opfs-worker-runtime.test.ts 안에만 있다. 05-04를 고치려면 recipe fake와 runtime에 같은 시나리오를 돌리는 parity 테스트가 tests/recipes에 필요한데, 그 테스트는 이 파일 시스템을 쓸 수 없다. unit 테스트가 recipe를 import하면 optional-recipe 제거 드릴이 깨지므로 parity 테스트를 unit 쪽에 둘 수도 없다. 고른 방법: 그 블록(MemoryNode·MemoryFile·MemoryDirectory·fileHandle· notFound)을 그대로 tests/helpers/memory-opfs.ts로 옮기고 export한다. memory-indexeddb.ts와 같은 자리다. 코드는 바꾸지 않았다. helper는 src를 import하지 않아 browser-file-storage 제거 드릴에서도 남아도 된다. 위험·한계: 동작 변경 없음. 검증: opfs-worker-runtime.test.ts 82건 통과. check:types:test, 바꾼 파일 eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/05-adapters-storage-kernel.md 05-04 --- tests/helpers/memory-opfs.ts | 123 +++++++++++++++++++++++++ tests/unit/opfs-worker-runtime.test.ts | 122 +----------------------- 2 files changed, 128 insertions(+), 117 deletions(-) create mode 100644 tests/helpers/memory-opfs.ts diff --git a/tests/helpers/memory-opfs.ts b/tests/helpers/memory-opfs.ts new file mode 100644 index 00000000..ec226ffe --- /dev/null +++ b/tests/helpers/memory-opfs.ts @@ -0,0 +1,123 @@ +/** + * An in-memory Origin Private File System for the OPFS worker runtime: just + * the `FileSystemDirectoryHandle` / `FileSystemFileHandle` surface it uses. + * Moved out of `tests/unit/opfs-worker-runtime.test.ts` so the recipe tests + * can run the same runtime (2026-11-03 05-04). + */ + +export type MemoryNode = MemoryDirectory | MemoryFile; + +export class MemoryFile { + readonly kind = "file"; + bytes = new Uint8Array(); + lastModified = 0; + reads = 0; +} + +export class MemoryDirectory { + readonly kind = "directory"; + readonly children = new Map(); + + async getDirectoryHandle( + name: string, + options: FileSystemGetDirectoryOptions = {}, + ): Promise { + const current = this.children.get(name); + if (current instanceof MemoryDirectory) { + return current as unknown as FileSystemDirectoryHandle; + } + if (current || !options.create) throw notFound(); + const created = new MemoryDirectory(); + this.children.set(name, created); + return created as unknown as FileSystemDirectoryHandle; + } + + async getFileHandle( + name: string, + options: FileSystemGetFileOptions = {}, + ): Promise { + const current = this.children.get(name); + if (current instanceof MemoryFile) { + return fileHandle(current); + } + if (current || !options.create) throw notFound(); + const created = new MemoryFile(); + this.children.set(name, created); + return fileHandle(created); + } + + async removeEntry( + name: string, + options: FileSystemRemoveOptions = {}, + ): Promise { + const current = this.children.get(name); + if (!current) throw notFound(); + if ( + current instanceof MemoryDirectory && + current.children.size > 0 && + !options.recursive + ) { + throw new DOMException("Directory is not empty.", "InvalidModificationError"); + } + this.children.delete(name); + } + + async *entries(): AsyncIterableIterator< + [string, FileSystemDirectoryHandle | FileSystemFileHandle] + > { + for (const [name, node] of this.children) { + yield [ + name, + node instanceof MemoryDirectory + ? (node as unknown as FileSystemDirectoryHandle) + : fileHandle(node), + ]; + } + } + + has(path: readonly string[]): boolean { + let current: MemoryNode = this; + for (const segment of path) { + if (!(current instanceof MemoryDirectory)) return false; + const next = current.children.get(segment); + if (!next) return false; + current = next; + } + return true; + } +} + +function fileHandle(file: MemoryFile): FileSystemFileHandle { + return { + kind: "file", + name: "memory", + async getFile() { + file.reads += 1; + const blob = new Blob([Uint8Array.from(file.bytes)]); + Object.defineProperty(blob, "lastModified", { + value: file.lastModified, + }); + return blob as File; + }, + async createWritable() { + let pending = Uint8Array.from(file.bytes); + return { + async write(data: FileSystemWriteChunkType) { + if (!(data instanceof Uint8Array)) { + throw new TypeError("The test writer accepts Uint8Array only."); + } + pending = Uint8Array.from(data); + }, + async close() { + file.bytes = pending; + file.lastModified = Date.now(); + }, + async abort() {}, + } as unknown as FileSystemWritableFileStream; + }, + } as FileSystemFileHandle; +} + +function notFound(): DOMException { + return new DOMException("Entry was not found.", "NotFoundError"); +} diff --git a/tests/unit/opfs-worker-runtime.test.ts b/tests/unit/opfs-worker-runtime.test.ts index a9699b72..9b361ebc 100644 --- a/tests/unit/opfs-worker-runtime.test.ts +++ b/tests/unit/opfs-worker-runtime.test.ts @@ -38,6 +38,11 @@ import { type OpfsWorkerRuntime, } from "../../src/adapters/storage/opfs/opfs-worker-runtime.ts"; import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts"; +import { + MemoryDirectory, + MemoryFile, + type MemoryNode, +} from "../helpers/memory-opfs.ts"; const scopeA: OpfsStorageScope = Object.freeze({ namespace: "durable-objects", @@ -71,123 +76,6 @@ const runtimePolicy = resolveOpfsRuntimePolicy({ orphanGracePeriodMs: 60_000, }); -type MemoryNode = MemoryDirectory | MemoryFile; - -class MemoryFile { - readonly kind = "file"; - bytes = new Uint8Array(); - lastModified = 0; - reads = 0; -} - -class MemoryDirectory { - readonly kind = "directory"; - readonly children = new Map(); - - async getDirectoryHandle( - name: string, - options: FileSystemGetDirectoryOptions = {}, - ): Promise { - const current = this.children.get(name); - if (current instanceof MemoryDirectory) { - return current as unknown as FileSystemDirectoryHandle; - } - if (current || !options.create) throw notFound(); - const created = new MemoryDirectory(); - this.children.set(name, created); - return created as unknown as FileSystemDirectoryHandle; - } - - async getFileHandle( - name: string, - options: FileSystemGetFileOptions = {}, - ): Promise { - const current = this.children.get(name); - if (current instanceof MemoryFile) { - return fileHandle(current); - } - if (current || !options.create) throw notFound(); - const created = new MemoryFile(); - this.children.set(name, created); - return fileHandle(created); - } - - async removeEntry( - name: string, - options: FileSystemRemoveOptions = {}, - ): Promise { - const current = this.children.get(name); - if (!current) throw notFound(); - if ( - current instanceof MemoryDirectory && - current.children.size > 0 && - !options.recursive - ) { - throw new DOMException("Directory is not empty.", "InvalidModificationError"); - } - this.children.delete(name); - } - - async *entries(): AsyncIterableIterator< - [string, FileSystemDirectoryHandle | FileSystemFileHandle] - > { - for (const [name, node] of this.children) { - yield [ - name, - node instanceof MemoryDirectory - ? (node as unknown as FileSystemDirectoryHandle) - : fileHandle(node), - ]; - } - } - - has(path: readonly string[]): boolean { - let current: MemoryNode = this; - for (const segment of path) { - if (!(current instanceof MemoryDirectory)) return false; - const next = current.children.get(segment); - if (!next) return false; - current = next; - } - return true; - } -} - -function fileHandle(file: MemoryFile): FileSystemFileHandle { - return { - kind: "file", - name: "memory", - async getFile() { - file.reads += 1; - const blob = new Blob([Uint8Array.from(file.bytes)]); - Object.defineProperty(blob, "lastModified", { - value: file.lastModified, - }); - return blob as File; - }, - async createWritable() { - let pending = Uint8Array.from(file.bytes); - return { - async write(data: FileSystemWriteChunkType) { - if (!(data instanceof Uint8Array)) { - throw new TypeError("The test writer accepts Uint8Array only."); - } - pending = Uint8Array.from(data); - }, - async close() { - file.bytes = pending; - file.lastModified = Date.now(); - }, - async abort() {}, - } as unknown as FileSystemWritableFileStream; - }, - } as FileSystemFileHandle; -} - -function notFound(): DOMException { - return new DOMException("Entry was not found.", "NotFoundError"); -} - const PHYSICAL_GENERATION_A = "a".repeat(32) as OpfsPhysicalGenerationId; function beginRequest( From 36ff63379454861701f8188a695052f00ea3a739 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:46:30 +0900 Subject: [PATCH 09/18] =?UTF-8?q?fix(recipes):=20OPFS=20fake=EA=B0=80=20FI?= =?UTF-8?q?LES=5FREADY=EC=97=90=EC=84=9C=20=EB=A9=88=EC=B6=98=20put?= =?UTF-8?q?=EC=9D=84=20runtime=EC=B2=98=EB=9F=BC=20commit=ED=95=9C?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: recipe fake MemoryDurableObjectStore의 reconcile은 멈춘 put 행을 모두 rollback으로 센다. runtime은 FILES_READY 행을 다시 검증한 뒤 commit하고 finalize한다(runbook, 설계 문서의 roll-forward). recipe 테스트 주석은 "Like the runtime, reconcile rolls a stopped put back"이라고 적는다. 이 fake로 쓴 다운스트림 테스트는 "멈춘 업로드는 reconcile 뒤 사라진다"를 통과하지만 실제로는 객체가 다시 생긴다. fake의 LOGOUT·ACCOUNT_DELETION도 멈춘 행을 보지 않아 05-01을 fake 테스트로 찾을 수 없었다. 고른 방법: fake가 멈춘 단계를 기억한다. FILES_READY까지 간 행은 commit될 객체를 함께 둔다. reconcile은 그 행을 runtime과 같은 generation 검사로 commit하고(committedTransactions), PREPARING 행은 rollback한다. LOGOUT·ACCOUNT_DELETION은 멈춘 행도 지우고, 그런 행이 있었으면 runtime처럼 chunkSweep 대신 partitionDeleted를 보고한다. 같은 네 시나리오(두 단계 × reconcile 전 계정 삭제 여부)를 메모리 OPFS·IndexedDB 위의 실제 runtime과 fake에 돌려 결과가 같은지 보는 parity 테스트를 tests/recipes에 더했다. unit 테스트가 recipe를 import하면 optional-recipe 제거 드릴이 깨지므로 parity 테스트는 recipe 쪽에 두었다(앞 커밋이 메모리 OPFS를 helper로 옮긴 이유). 위험·한계: 이 fake를 쓰는 다운스트림 테스트 중 FILES_READY 멈춤 뒤 rollback을 기대하던 것은 기대값이 바뀐다. 기존 recipe 테스트는 같은 흐름을 유지하려고 PREPARING 멈춤으로 바꿨다. fake는 runtime의 재검증 실패(digest 불일치) 경로는 흉내 내지 않는다. 검증: - RED: parity 테스트 4건 중 3건 실패(fake가 FILES_READY를 rollback, 계정 삭제가 partitionDeleted 없이 COMPLETED). runtime 쪽 기대값은 처음부터 통과. - GREEN: tests/recipes 24건 통과. check:types, 바꾼 파일 eslint, check:optional-recipes:source PASS. Refs: docs/reviews/2026-11-03-maturity-review/05-adapters-storage-kernel.md 05-04 --- .../browser-file-storage-fakes.ts | 62 +++-- .../browser-file-storage-contracts.test.ts | 220 +++++++++++++++++- 2 files changed, 267 insertions(+), 15 deletions(-) diff --git a/recipes/frontend-capabilities/browser-file-storage-fakes.ts b/recipes/frontend-capabilities/browser-file-storage-fakes.ts index 473b2ed6..d23f572b 100644 --- a/recipes/frontend-capabilities/browser-file-storage-fakes.ts +++ b/recipes/frontend-capabilities/browser-file-storage-fakes.ts @@ -1649,8 +1649,11 @@ type MemoryDurableObjectStoreOptions = Readonly<{ * test written against it compiles against the runtime too. It keeps the * runtime's visible rules: a put is invisible until its logical commit, a * stale `expectedGeneration` is `CONFLICT`, a put that stopped mid-way leaves - * a journal row that `reconcile` rolls back (never resumes), and a LOGOUT or - * ACCOUNT_DELETION the policy allows leaves the partition empty. + * a journal row, and a LOGOUT or ACCOUNT_DELETION the policy allows leaves the + * partition empty. `reconcile` rolls a row that stopped while PREPARING back + * and commits one that stopped after FILES_READY, like the runtime's + * roll-forward; such a purge also drops every stopped row and reports + * `partitionDeleted` (2026-11-03 05-01, 05-04). * * It does not model the worker, Web Locks, the composition authority, chunk * dedup, orphan GC or the other maintenance reasons (`UNSUPPORTED`). Its @@ -1661,8 +1664,14 @@ export class MemoryDurableObjectStore implements DurableObjectStorePort, DurableObjectMaintenancePort { readonly #objects = new Map(); - /** Journal rows of puts that stopped before they committed or rolled back. */ - readonly #pending = new Set(); + /** + * Journal rows of puts that stopped before they committed or rolled back. + * A row that reached FILES_READY keeps the object its commit would publish. + */ + readonly #pending = new Map< + number, + Readonly<{ expectedGeneration: number | null; ready: MemoryObject | null }> + >(); readonly #scope: OpfsStorageScope; readonly #storagePolicy: BrowserStoragePolicy; readonly #maxObjectBytes: number; @@ -1711,7 +1720,10 @@ export class MemoryDurableObjectStore return dataFailure("CONFLICT", "OBJECT_WRITE", false, "REOPEN"); } const row = ++this.#sequence; - this.#pending.add(row); + this.#pending.set( + row, + Object.freeze({ expectedGeneration: request.expectedGeneration, ready: null }), + ); const stopped = (phase: "PREPARING" | "FILES_READY") => { if (this.#failurePhase !== phase) return null; this.#failurePhase = null; @@ -1755,8 +1767,6 @@ export class MemoryDurableObjectStore if (declared !== null && totalBytes !== declared) { return settle(dataFailure("INTEGRITY_FAILED", "OBJECT_WRITE")); } - const afterFilesReady = stopped("FILES_READY"); - if (afterFilesReady) return afterFilesReady; const chunkDigests = await Promise.all(chunks.map(sha256Hex)); const chunkSizeBytes = Math.max( @@ -1787,7 +1797,14 @@ export class MemoryDurableObjectStore }), storagePolicy: this.#storagePolicy, }); - this.#objects.set(request.objectId, { descriptor, chunks }); + const ready: MemoryObject = { descriptor, chunks }; + this.#pending.set( + row, + Object.freeze({ expectedGeneration: request.expectedGeneration, ready }), + ); + const afterFilesReady = stopped("FILES_READY"); + if (afterFilesReady) return afterFilesReady; + this.#objects.set(request.objectId, ready); this.#pending.delete(row); return dataSuccess(descriptor); } @@ -1853,13 +1870,26 @@ export class MemoryDurableObjectStore return dataFailure("INVALID_INPUT", "OBJECT_RECONCILE"); } const rows = [...this.#pending].slice(0, maxTransactions); - for (const row of rows) this.#pending.delete(row); + let committed = 0; + for (const [row, { expectedGeneration, ready }] of rows) { + this.#pending.delete(row); + // The runtime re-verifies a FILES_READY row and commits it under the + // same generation check a live put has; anything else is rolled back. + const current = ready && this.#objects.get(ready.descriptor.objectId); + if ( + ready && + (current?.descriptor.generation ?? null) === expectedGeneration + ) { + this.#objects.set(ready.descriptor.objectId, ready); + committed += 1; + } + } return dataSuccess( Object.freeze({ inspectedTransactions: rows.length, - committedTransactions: 0, - rolledBackTransactions: rows.length, - cleanedTransactions: 0, + committedTransactions: committed, + rolledBackTransactions: rows.length - committed, + cleanedTransactions: committed, inspectedOrphanChunks: 0, deletedOrphanChunks: 0, orphanGcStatus: "COMPLETED" as const, @@ -1895,6 +1925,10 @@ export class MemoryDurableObjectStore } const removedObjects = this.#objects.size; this.#objects.clear(); + // 2026-11-03 05-01. A stopped put goes with the partition, as the + // runtime's partition delete takes its row and its files. + const partitionDeleted = this.#pending.size > 0; + this.#pending.clear(); return dataSuccess( Object.freeze({ inspectedObjects: removedObjects, @@ -1902,7 +1936,9 @@ export class MemoryDurableObjectStore releasedBytes, moreObjectsAvailable: false, deadlineReached: false, - chunkSweep: "COMPLETED" as const, + ...(partitionDeleted + ? { partitionDeleted: true as const } + : { chunkSweep: "COMPLETED" as const }), }), ); } diff --git a/tests/recipes/browser-file-storage-contracts.test.ts b/tests/recipes/browser-file-storage-contracts.test.ts index b571f41e..f4e0202b 100644 --- a/tests/recipes/browser-file-storage-contracts.test.ts +++ b/tests/recipes/browser-file-storage-contracts.test.ts @@ -37,6 +37,17 @@ import type { StorageDurabilityPort, TransientPreviewPort, } from "../../src/application/ports/browser-file-storage/index.ts"; +import { browserDataFailure } from "../../src/adapters/browser-file-storage/result.ts"; +import { + createIndexedDbOpfsJournal, + createOpfsByteStoreAdapter, + createOpfsWorkerGateway, + createOpfsWorkerRuntime, + createWebLockLeaseManager, + resolveOpfsRuntimePolicy, +} from "../../src/adapters/storage/opfs/index.ts"; +import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts"; +import { MemoryDirectory } from "../helpers/memory-opfs.ts"; async function* byteChunks( ...values: ReadonlyArray @@ -587,7 +598,7 @@ describe("production browser file and storage recipe contracts", () => { stream: () => byteChunks(...values), }); - store.failNextPutAfter("FILES_READY"); + store.failNextPutAfter("PREPARING"); expect( await store.put({ objectId, @@ -603,7 +614,8 @@ describe("production browser file and storage recipe contracts", () => { ok: false, error: { code: "NOT_FOUND" }, }); - // Like the runtime, reconcile rolls a stopped put back; it never resumes. + // Like the runtime, reconcile rolls a put that stopped before FILES_READY + // back. One that stopped after it is committed (2026-11-03 05-04, below). expect(await store.reconcile()).toMatchObject({ ok: true, value: { rolledBackTransactions: 1, moreTransactionsAvailable: false }, @@ -742,3 +754,207 @@ describe("production browser file and storage recipe contracts", () => { }); }); }); + +/** + * 2026-11-03 05-04. The fake rolled every stopped put back, while the runtime + * commits one that stopped after FILES_READY and rolls back one that stopped + * while PREPARING. A downstream test written against the fake then passed + * "a stopped upload is gone after reconcile" although the runtime brings the + * file back. The same scenarios now run on both and must agree. + */ +describe("the durable object fake reconciles a stopped put like the runtime (2026-11-03 05-04)", () => { + type StoppablePhase = "PREPARING" | "FILES_READY"; + type StoppableStore = Readonly<{ + store: DurableObjectStorePort & DurableObjectMaintenancePort; + stopNextPutAfter(phase: StoppablePhase): void; + }>; + + const scope = Object.freeze({ + namespace: "durable-objects", + authorityToken: "authority_12345678", + namespaceToken: "namespace_12345678", + partitionToken: "partition_12345678", + }); + const storagePolicy: BrowserStoragePolicy = Object.freeze({ + owner: "recipe-test", + namespace: "durable-objects", + classification: "PERSONAL", + authority: "LOCAL_FIRST", + accountScope: "OPAQUE_PARTITION", + retention: Object.freeze({ kind: "EXPLICIT_DELETE" }), + softBudgetBytes: 32, + hardBudgetBytes: 64, + evictionPriority: "USER_AUTHORED", + logoutAction: "EXPORT_THEN_PURGE", + accountDeletionAction: "PURGE_PARTITION", + pressureAction: "RETAIN", + unavailableFallback: "EXPORT_REQUIRED", + }); + + function fake(): StoppableStore { + const store = new MemoryDurableObjectStore({ + scope, + storagePolicy, + maxObjectBytes: 32, + }); + return { store, stopNextPutAfter: (phase) => store.failNextPutAfter(phase) }; + } + + /** The reference runtime on an in-memory OPFS root and IndexedDB. */ + function runtime(): StoppableStore { + const policy = resolveOpfsRuntimePolicy({ + chunkSizeBytes: 64 * 1024, + maxObjectBytes: 64 * 1024, + maxChunkCount: 1, + }); + const worker = createOpfsWorkerRuntime({ + root: new MemoryDirectory() as unknown as FileSystemDirectoryHandle, + crypto: globalThis.crypto, + policy, + leaseManager: createWebLockLeaseManager( + navigator.locks, + `${policy.mutationLockName}:${crypto.randomUUID()}`, + ), + dedicatedWorker: true, + supportsSynchronousAccessHandles: false, + }); + let listener: ((event: MessageEvent) => void) | undefined; + const gateway = createOpfsWorkerGateway({ + worker: { + postMessage(message) { + void worker + .handleRequest(message) + .then((response) => listener?.({ data: response } as MessageEvent)); + }, + addEventListener(_type, next) { + listener = next; + }, + removeEventListener() { + listener = undefined; + }, + }, + policy, + }); + const idb = new MemoryIndexedDbFactory(); + const journal = createIndexedDbOpfsJournal({ + authorityToken: scope.authorityToken, + factory: idb.factory, + keyRange: idb.keyRange, + }); + let stopAfter: StoppablePhase | null = null; + let compensationLost = false; + // The tab closes at this step: the journal write never lands and, before + // commit, neither does its compensation. + const crashed = async () => { + compensationLost = stopAfter === "PREPARING"; + stopAfter = null; + return browserDataFailure("UNAVAILABLE", "INDEXEDDB_WRITE", { + retryable: true, + recovery: "RETRY", + }); + }; + const { objects, maintenance } = createOpfsByteStoreAdapter({ + journal: { + ...journal, + markFilesReady: (...input) => + stopAfter === "PREPARING" ? crashed() : journal.markFilesReady(...input), + commitPut: (...input) => + stopAfter === "FILES_READY" ? crashed() : journal.commitPut(...input), + }, + worker: { + ...gateway, + async abortPreparedPut(input) { + if (!compensationLost) return await gateway.abortPreparedPut(input); + compensationLost = false; + return browserDataFailure("UNAVAILABLE", "OBJECT_WRITE", { + retryable: true, + recovery: "RETRY", + }); + }, + }, + scope, + storagePolicy, + policy, + requestMaintenanceAuthority: () => ({ + authorized: true as const, + proofToken: "proof_token_1234567890", + expiresAtEpochMs: Date.now() + 60_000, + }), + consumeMaintenanceAuthority: () => true, + }); + return { + store: { ...objects, ...maintenance }, + stopNextPutAfter(phase) { + stopAfter = phase; + }, + }; + } + + async function stoppedPut( + { store, stopNextPutAfter }: StoppableStore, + phase: StoppablePhase, + purgeBeforeReconcile: boolean, + ) { + const objectId = asDurableObjectId("object_opaque_0001"); + const opened = async () => { + const result = await store.open({ objectId }); + if (!result.ok) return result.error.code; + const bytes: number[] = []; + for await (const chunk of result.value.source.stream( + new AbortController().signal, + )) { + if (!chunk.ok) return chunk.error.code; + bytes.push(...chunk.value); + } + return new TextDecoder().decode(new Uint8Array(bytes)); + }; + stopNextPutAfter(phase); + const put = await store.put({ + objectId, + expectedGeneration: null, + mediaType: "application/octet-stream", + source: { byteLength: 4, stream: () => byteChunks("ab", "cd") }, + }); + const beforeReconcile = await opened(); + const purge = purgeBeforeReconcile + ? await store.enforcePolicies({ reason: "ACCOUNT_DELETION" }) + : null; + const reconciled = await store.reconcile(); + if (!reconciled.ok || (purge && !purge.ok)) { + throw new Error("maintenance failed"); + } + return { + putSucceeded: put.ok, + beforeReconcile, + purge: purge && { + partitionDeleted: purge.value.partitionDeleted ?? false, + chunkSweep: purge.value.chunkSweep ?? null, + }, + committedTransactions: reconciled.value.committedTransactions, + rolledBackTransactions: reconciled.value.rolledBackTransactions, + afterReconcile: await opened(), + }; + } + + it.each([ + ["FILES_READY", false, { committed: 1, rolledBack: 0, after: "abcd" }], + ["PREPARING", false, { committed: 0, rolledBack: 1, after: "NOT_FOUND" }], + ["FILES_READY", true, { committed: 0, rolledBack: 0, after: "NOT_FOUND" }], + ["PREPARING", true, { committed: 0, rolledBack: 0, after: "NOT_FOUND" }], + ] as const)( + "agrees on a put stopped after %s (account deleted before reconcile: %s)", + async (phase, purge, expected) => { + const fromRuntime = await stoppedPut(runtime(), phase, purge); + + expect(fromRuntime).toEqual({ + putSucceeded: false, + beforeReconcile: "NOT_FOUND", + purge: purge ? { partitionDeleted: true, chunkSweep: null } : null, + committedTransactions: expected.committed, + rolledBackTransactions: expected.rolledBack, + afterReconcile: expected.after, + }); + expect(await stoppedPut(fake(), phase, purge)).toEqual(fromRuntime); + }, + ); +}); From f485e51e211f7d1d2c2cdf04aca16208c75623c0 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:54:20 +0900 Subject: [PATCH 10/18] =?UTF-8?q?feat(bootstrap):=20=EC=A0=9C=ED=92=88?= =?UTF-8?q?=EC=9D=B4=20=EC=84=B8=EC=85=98=EA=B3=BC=20=ED=95=A8=EA=BB=98=20?= =?UTF-8?q?=EB=8B=AB=EC=9D=84=20=EA=B2=83=EC=9D=84=20scopeParticipants?= =?UTF-8?q?=EB=A1=9C=20=EB=84=98=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: browser-files runtime은 세션을 모르고, 닫는 수단은 runtime.dispose() 하나다. 설계 문서는 로그아웃·계정 전환에 "server-state scope reset participant로 dispose()를 등록하라"며 템플릿 소유 파일 runtime-adapters.ts를 가리키는데, 매뉴얼은 제품이 그 파일을 고치지 않는다고 한다(09-02). 제품 확장 지점 composeProduct는 부팅 때 한 번 불리고, context에 participant 등록도 lifecycle 구독도 없다. 그래서 연결하지 않으면 이전 사용자가 고른 File, preview blob URL, 진행 중 download가 다음 세션까지 남는다(공유 기기에서 이전 사용자 파일이 메모리와 다운로드 폴더에 남을 수 있다). 고른 방법(리뷰 5.3절 (다) + 레시피 예제): - ProductComposition에 선택 칸 scopeParticipants(ProductScopeParticipant: label, close)를 둔다. 템플릿은 scope reset의 §10.6 10단계(offline lease 해제) 자리에 "product" participant 하나를 두고, composeProduct가 돌려준 것을 순서대로 부른다. 하나가 실패해도 나머지를 부르고, 실패가 있으면 template participant와 같이 READY로 가지 않는다(FAILED). composeProduct는 scope가 생긴 뒤 불리므로(context가 fence를 쓴다) 이 자리를 미리 만들고 나중에 채운다. - recipes/frontend-capabilities/browser-file-session-capability.ts: 기능에는 runtime 대신 current() getter를 주고, participant가 dispose한 뒤 다음 호출에서 새 runtime을 만든다. indexeddb 레시피와 같은 자리다. - 설계 문서와 매뉴얼 03 C절이 이 방법을 가리킨다. 제거 드릴이 새 레시피 파일도 같이 지운다. 버린 대안: (가) 문서만 고침 — feature presentation은 adapter를 만들 수 없어 제품마다 factory를 다시 설계한다. (나) context에 lifecycle 구독 위임 — FENCED → participant → READY 순서와 "실패는 READY를 막는다"를 제품이 직접 지켜야 한다. (라) runtime이 세대 AbortSignal을 받음 — adapter가 세대를 알게 되고 다른 opt-in runtime도 따로 받아야 한다. 위험·한계: - 제품 계약 표면이 하나 는다(선택 칸이라 기존 제품 파일은 그대로 컴파일된다, [계약]). - 기능은 current()를 작업마다 불러야 한다. 이전 세대에서 받은 runtime을 들고 있으면 UNAVAILABLE을 받는다. FENCED 동안 current()를 부르면 다음 세대 runtime이 미리 만들어진다(빈 runtime이라 이전 사용자 데이터는 없다). - app dispose(infrastructure.dispose)는 제품 participant를 부르지 않는다. - 실제 브라우저 2탭 로그아웃 E2E는 없다(조립된 화면이 없다). - scripts/test-browser-file-storage-runtime-removal.ts는 02-06 담당 작업도 고칠 수 있는 파일이다. runtimePaths에 한 줄만 더했다. 검증: - RED: tests/recipes/browser-file-session-capability.test.ts가 계정 전환 뒤에도 이전 runtime의 readRange가 ok로 실패. - GREEN: 같은 테스트에서 계정 전환 뒤 ① 이전 runtime readRange UNAVAILABLE ② 진행 중 bounded download ABORTED, handoff 0회 ③ 새 세대 runtime의 파일 선택 SELECTED. tests/unit/runtime-adapters-product-scope- participants.test.ts 2건(순서, 실패 시 FAILED와 나머지 실행). - 변이 4개(등록 누락, 실패 삼킴, 첫 실패에서 멈춤, 레시피 dispose 누락) 모두 새 테스트가 잡았다. - runtime-adapters 관련 unit 3파일 + tests/recipes 47건 통과. check:types, 바꾼 파일 eslint, check:architecture, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 02-01 --- .../browser-file-and-origin-storage.md | 16 +- docs/manual/03-outside-feature-folder.md | 1 + .../browser-file-session-capability.ts | 58 ++++ ...st-browser-file-storage-runtime-removal.ts | 3 +- src/bootstrap/product-composition-contract.ts | 19 ++ src/bootstrap/runtime-adapters.ts | 29 +- .../browser-file-session-capability.test.ts | 284 ++++++++++++++++++ ...dapters-product-scope-participants.test.ts | 152 ++++++++++ 8 files changed, 556 insertions(+), 6 deletions(-) create mode 100644 recipes/frontend-capabilities/browser-file-session-capability.ts create mode 100644 tests/recipes/browser-file-session-capability.test.ts create mode 100644 tests/unit/runtime-adapters-product-scope-participants.test.ts diff --git a/docs/architecture/browser-file-and-origin-storage.md b/docs/architecture/browser-file-and-origin-storage.md index 72399f25..0144fdb5 100644 --- a/docs/architecture/browser-file-and-origin-storage.md +++ b/docs/architecture/browser-file-and-origin-storage.md @@ -371,10 +371,18 @@ digest 또는 별도 검토된 streaming hash adapter를 사용한다. 세션을 모른다(`src/adapters/browser-files/create-browser-file-runtime.ts:93`). `runtime.dispose()`(`:177-188`)가 이전 사용자가 고른 File 참조, preview lease, 진행 중 download(`download-delivery-adapter.ts:390-396`)를 한 번에 닫는다. - runtime을 route·feature보다 오래 사는 곳에서 만들었다면 server-state scope - reset participant(`src/adapters/query-cache/server-state-scope-runtime.ts:19`, - 등록 예 `src/bootstrap/runtime-adapters.ts:410-416`)로 `dispose()`를 등록하고 - 다음 세대에서 새 runtime을 만든다. dispose한 runtime은 다시 쓸 수 없다. + runtime을 route·feature보다 오래 사는 곳(`product-composition.ts`의 + capability)에서 만들었다면 제품 소유 파일만 고친다. `composeProduct`가 + `scopeParticipants`로 `dispose()`를 돌려주면 템플릿이 로그아웃·계정 전환마다 + FENCED와 READY 사이에서 부르고, 실패하면 READY로 가지 않는다 + (`ProductScopeParticipant`, `src/bootstrap/product-composition-contract.ts`). + `composeProduct`는 부팅 때 한 번만 불리므로 기능에는 runtime 대신 getter를 + 주고 그 뒤에서 세대마다 새 runtime을 만든다. 예제는 + `recipes/frontend-capabilities/browser-file-session-capability.ts`이고 + `tests/recipes/browser-file-session-capability.test.ts`가 계정 전환 뒤 이전 + runtime의 읽기가 `UNAVAILABLE`, 진행 중 download가 `ABORTED`(handoff 0회), + 다음 세대의 파일 선택이 성공함을 확인한다(2026-11-03 02-01). dispose한 + runtime은 다시 쓸 수 없다. - SVG, HTML, untrusted PDF 같은 active content를 same-origin object URL iframe에 직접 preview하지 않는다. 별도 격리 origin 또는 안전한 decode/re-encode 결과, 아니면 attachment-only 정책을 사용한다. diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 1c13012f..1bb10385 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -103,6 +103,7 @@ release admission refused for staging: - `src/contexts//context-layout.tsx`: context가 `AppShell` 대신 자기 틀을 쓸 때. 예제: `tests/helpers/fixture-layout-product.tsx`. - `tests/e2e/accessibility.spec.ts`: 경로 파라미터가 `:resourceId`가 아닐 때, 또는 모든 API가 `[]`를 답하면 그려지지 않는 보호 페이지일 때. 치환 줄 고치는 법은 [01 문서 6단계](01-add-a-feature.md#6단계-라우트). - `src/bootstrap/product-composition.ts`: `needs`에 템플릿이 만들지 않는 capability를 적었을 때. 제품 인증 프로필의 자격 증명도 여기서 준다. + - 로그아웃·계정 전환 때 닫아야 하는 것(파일 runtime 등)은 `scopeParticipants`로 돌려준다. 예제: `recipes/frontend-capabilities/browser-file-session-capability.ts`. - 템플릿 파일 `src/bootstrap/runtime-adapters.ts`는 고치지 않는다. - `src/contracts/product-contracts.ts`: 제품 인증 프로필이나 제품 런타임 설정 키가 필요할 때. - 템플릿 파일 `src/contracts/rest-profiles.ts`는 고치지 않는다. diff --git a/recipes/frontend-capabilities/browser-file-session-capability.ts b/recipes/frontend-capabilities/browser-file-session-capability.ts new file mode 100644 index 00000000..04d95996 --- /dev/null +++ b/recipes/frontend-capabilities/browser-file-session-capability.ts @@ -0,0 +1,58 @@ +import type { BrowserFileRuntime } from "../../src/adapters/browser-files/index.ts"; +import type { ProductScopeParticipant } from "../../src/bootstrap/product-composition-contract.ts"; + +/** What features receive: this session's runtime, asked for per operation. */ +export type SessionBrowserFiles = Readonly<{ + /** + * The current session's runtime, built on first use. Ask again for each + * operation; one kept past a sign-out answers `UNAVAILABLE`. + */ + current(): BrowserFileRuntime; +}>; + +/** + * 2026-11-03 02-01. How a product gives features a browser file runtime that + * lives for one session. The runtime does not know the session, and + * `composeProduct` runs once at boot, so the capability is a getter and the + * runtime behind it is disposed by a scope participant on every sign-out and + * account switch: the previous user's selected files, preview object URLs and + * running downloads end there. The next call to `current()` builds a fresh one. + * + * file-transfer is an opt-in recipe (`productionComposition: false`), so the + * template does not build this. A product that installs a feature using it + * augments `FeaturePlatformCapabilities` with `files: SessionBrowserFiles` and + * returns both halves from `src/bootstrap/product-composition.ts`: + * + * const browserFiles = createSessionBrowserFileCapability(() => + * createBrowserFileRuntime({ input, policies, limits, download }), + * ); + * return { + * capabilities: { files: browserFiles.files }, + * credentialProviders: {}, + * scopeParticipants: [browserFiles.scopeParticipant], + * }; + * + * The runtime options are the product's decisions (policies, limits, the + * download capability resolver); none is chosen here. + */ +export function createSessionBrowserFileCapability( + create: () => BrowserFileRuntime, +): Readonly<{ + files: SessionBrowserFiles; + scopeParticipant: ProductScopeParticipant; +}> { + let runtime: BrowserFileRuntime | null = null; + return Object.freeze({ + files: Object.freeze({ + current: () => (runtime ??= create()), + }), + scopeParticipant: Object.freeze({ + label: "browser-files", + close() { + const ending = runtime; + runtime = null; + ending?.dispose(); + }, + }), + }); +} diff --git a/scripts/test-browser-file-storage-runtime-removal.ts b/scripts/test-browser-file-storage-runtime-removal.ts index 399d9910..2dd386de 100644 --- a/scripts/test-browser-file-storage-runtime-removal.ts +++ b/scripts/test-browser-file-storage-runtime-removal.ts @@ -36,8 +36,9 @@ const runtimePaths = [ "src/adapters/storage/opfs", "tests/browser-capabilities", "tests/fixtures/browser-file-storage-boundaries", - // The composition example of this runtime goes with it. + // The composition examples of this runtime go with it. "recipes/frontend-capabilities/indexeddb-feature-capability.ts", + "recipes/frontend-capabilities/browser-file-session-capability.ts", // [0929] 05-03. These recipe contracts re-export this runtime's ports and // their fakes implement them, so they go with it too, with their test. ...RUNTIME_RECIPE_MODULES.map( diff --git a/src/bootstrap/product-composition-contract.ts b/src/bootstrap/product-composition-contract.ts index 0f5190b3..5637335f 100644 --- a/src/bootstrap/product-composition-contract.ts +++ b/src/bootstrap/product-composition-contract.ts @@ -55,10 +55,29 @@ export type ProductCompositionContext = Readonly<{ isScopeReady(): boolean; }>; +/** + * 2026-11-03 02-01. Something a product built that must not outlive a session, + * such as a browser file runtime holding the previous user's files. The + * template closes it on every sign-out and account switch, after FENCED and + * before READY, at the step that releases offline leases. A close that throws + * or rejects keeps the scope from reaching READY, as the template's own do. + */ +export type ProductScopeParticipant = Readonly<{ + label: string; + close(): void | Promise; +}>; + export type ProductComposition = Readonly<{ capabilities: Readonly< Partial> >; /** Auth profile id → provider. An ANONYMOUS profile never reaches one. */ credentialProviders: Readonly>; + /** + * Closed in this order on each identity change. A capability that needs a + * fresh object for the next session hands features a getter and rebuilds + * behind it, as `recipes/frontend-capabilities/browser-file-session-capability.ts` + * does. + */ + scopeParticipants?: readonly ProductScopeParticipant[]; }>; diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index d419621b..7175108e 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -62,7 +62,10 @@ import { composeProduct, composeProductSessionOwner, } from "./product-composition.ts"; -import type { ProductComposition } from "./product-composition-contract.ts"; +import type { + ProductComposition, + ProductScopeParticipant, +} from "./product-composition-contract.ts"; import { createInstalledContractRegistry } from "../features/installed-contract-contributions.ts"; import { indexInvalidationRegistry, @@ -377,6 +380,11 @@ export async function createRuntimeAdapters( crossContextInvalidation?.getStatus() ?? "DEGRADED_LOCAL_ONLY", }); }); + // 2026-11-03 02-01. The product's closers. `composeProduct` runs after the + // scope exists (its context needs the fence), so they join through this one + // slot, filled below. Each runs even when an earlier one fails, and any + // failure keeps the scope from READY, as for the template's own. + const productScopeParticipants: ProductScopeParticipant[] = []; const serverStateScope = createServerStateScopeRuntime({ session: authSession, diagnostics, @@ -389,6 +397,21 @@ export async function createRuntimeAdapters( label: "conditional-validators", close: () => conditionalValidators.clear(), }, + { + order: 10, + label: "product", + async close() { + let failed = false; + for (const participant of productScopeParticipants) { + try { + await participant.close(); + } catch { + failed = true; + } + } + if (failed) throw new Error("A product scope participant failed."); + }, + }, ], activateNextGeneration: () => serverStateGeneration.activateNext(), }); @@ -615,6 +638,10 @@ export async function createRuntimeAdapters( }) satisfies ProductComposition; const productCredentialProviders: ProductComposition["credentialProviders"] = product.credentialProviders; + // `product` keeps its narrow type above so a missing capability still fails + // the typecheck; the optional field is read through the contract type. + const composedProduct: ProductComposition = product; + productScopeParticipants.push(...(composedProduct.scopeParticipants ?? [])); // Each installed contribution receives only the capabilities it declares. // The template's own capabilities come last, so a product cannot replace // them. 09-05. `indexedDb` is not built here: IndexedDB is an opt-in diff --git a/tests/recipes/browser-file-session-capability.test.ts b/tests/recipes/browser-file-session-capability.test.ts new file mode 100644 index 00000000..7afb7aab --- /dev/null +++ b/tests/recipes/browser-file-session-capability.test.ts @@ -0,0 +1,284 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { LocalFileRef } from "../../src/application/ports/browser-file-storage/index.ts"; +import { + browserFilePolicyReference, + createBrowserFileRuntime, + type BrowserFilePolicyProfile, +} from "../../src/adapters/browser-files/index.ts"; +import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; +import { createSessionBrowserFileCapability } from "../../recipes/frontend-capabilities/browser-file-session-capability.ts"; + +/** + * 2026-11-03 02-01. A product wires the browser file runtime to the session by + * filling only its own `product-composition.ts`: the recipe capability goes to + * features, its scope participant to the template. The real + * `createRuntimeAdapters` runs; only the product-owned file is replaced, with + * what a product would write in it. + */ + +const selectPolicy = browserFilePolicyReference("session-file", "select-text"); +const downloadPolicy = browserFilePolicyReference( + "session-download", + "bounded-generated-bin", +); +const policies: readonly BrowserFilePolicyProfile[] = [ + { + reference: selectPolicy, + selection: { + policyId: "attachment-v1", + purpose: "attachment", + classification: "PERSONAL", + multiple: false, + maxCount: 1, + maxFileBytes: 8, + maxTotalBytes: 8, + allowEmpty: false, + accept: [{ mediaType: "text/plain", extensions: [".txt"] }], + }, + }, + { + reference: downloadPolicy, + download: { + strategy: "BOUNDED_OBJECT_URL", + mediaType: "application/octet-stream", + safeExtension: ".bin", + maxTransferBytes: 8, + maxBufferedBytes: 8, + integrity: "OPTIONAL", + }, + }, +]; + +const fixture = vi.hoisted(() => ({ + files: undefined as + | ReturnType["files"] + | undefined, + inputs: [] as HTMLInputElement[], + handoffs: 0, + owner: undefined as + | Readonly<{ switchUser(subject: string): void }> + | undefined, +})); + +function fileInput(): HTMLInputElement { + const input = document.createElement("input"); + input.type = "file"; + input.setAttribute("aria-label", "Attachment"); + Object.defineProperty(input, "click", { configurable: true, value: vi.fn() }); + document.body.append(input); + fixture.inputs.push(input); + return input; +} + +function externalOwner() { + const listeners = new Set<() => void>(); + let subject = "user-a"; + return { + readState: () => "authenticated", + readSubject: () => subject, + subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: async () => ({ headers: {} }), + recoverSession: async () => "no-session", + notifyUnauthenticated: () => {}, + switchUser(next: string) { + subject = next; + for (const listener of listeners) listener(); + }, + }; +} + +/** The product-owned file, filled the way a product fills it. */ +vi.mock("../../src/bootstrap/product-composition.ts", () => ({ + composeProductSessionOwner: () => { + const owner = externalOwner(); + fixture.owner = owner; + return owner; + }, + composeProduct: () => { + const browserFiles = createSessionBrowserFileCapability(() => + createBrowserFileRuntime({ + input: fileInput(), + policies, + limits: { + hardMaxPreviewBytes: 8, + hardMaxObjectUrlBytes: 8, + hardMaxTransferBytes: 16, + }, + objectUrlApi: { + createObjectURL: () => "blob:session-download", + revokeObjectURL() {}, + }, + download: { + host: { + handoff() { + fixture.handoffs += 1; + }, + }, + browserManagedCapabilities: { + resolve: () => ({ + ok: false as const, + error: { + code: "POLICY_REJECTED" as const, + operation: "DOWNLOAD" as const, + retryable: false, + recovery: "NONE" as const, + }, + }), + }, + }, + }), + ); + fixture.files = browserFiles.files; + return { + capabilities: {}, + credentialProviders: {}, + scopeParticipants: [browserFiles.scopeParticipant], + }; + }, +})); + +let current: Awaited> | undefined; +afterEach(() => { + current?.infrastructure.dispose(); + current = undefined; + for (const input of fixture.inputs.splice(0)) input.remove(); + fixture.files = undefined; + fixture.handoffs = 0; +}); + +async function compose() { + current = await createRuntimeAdapters({ + runtime: { + config: { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + TELEMETRY_ENABLED: false, + AUTH_MODE: "external", + REQUEST_TIMEOUT_MS: 10_000, + MAX_RETRY_ATTEMPTS: 0, + RELEASE_MANIFEST_URL: "/release-manifest.json", + CONFIG_SCHEMA_VERSION: "2.0", + CAPABILITY_OVERRIDES: { + REALTIME: "DEFAULT", + WEB_WORKER: "DEFAULT", + SERVICE_WORKER: "DEFAULT", + OFFLINE_COMMANDS: "DEFAULT", + }, + FEATURE_OVERRIDES: {}, + }, + configSchema: "V2", + build: { + buildId: "build-a", + commitSha: "abc123", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + validationDurationMs: 0, + }, + release: { + schemaVersion: 2, + appVersion: "0.1.0", + buildId: "build-a", + commitSha: "abc123", + configSchemaVersion: "2.0", + contractSet: { + setAlgorithm: "CA_CONTRACT_SET_V1", + setDigest: `sha256:${"0".repeat(64)}`, + packages: [], + }, + assetManifestHash: "hash-a", + releaseId: "release-a", + builtAt: "2026-07-25T00:00:00Z", + routeChunks: { "route-home": "assets/home.js" }, + }, + host: {}, + }); + const files = fixture.files; + const owner = fixture.owner; + if (!files || !owner) throw new Error("The product composition did not run"); + return { adapters: current, files, owner }; +} + +async function selectOne( + runtime: ReturnType["current"]>, + name: string, +) { + const pending = runtime.baselinePicker.select({ policy: selectPolicy }); + const input = fixture.inputs.at(-1)!; + Object.defineProperty(input, "files", { + configurable: true, + value: [new File(["text"], name, { type: "text/plain", lastModified: 1 })], + }); + input.dispatchEvent(new Event("change")); + return await pending; +} + +describe("a session-scoped browser file runtime (2026-11-03 02-01)", () => { + it("closes the previous user's files and downloads on an account switch and serves the next session a new runtime", async () => { + const { adapters, files, owner } = await compose(); + const previous = files.current(); + const selected = await selectOne(previous, "user-a.txt"); + if (!selected.ok || selected.value.kind !== "SELECTED") { + throw new Error(`The first selection failed: ${JSON.stringify(selected)}`); + } + const ref: LocalFileRef = selected.value.files[0]!.ref; + let producing!: () => void; + const started = new Promise((resolve) => { + producing = resolve; + }); + const download = previous.downloads.deliver({ + policy: downloadPolicy, + source: { + kind: "GENERATED", + bytes: { + byteLength: 1, + async *stream() { + producing(); + await new Promise(() => {}); + yield { ok: true as const, value: new Uint8Array([1]) }; + }, + }, + }, + suggestedFileName: "user-a-report", + maxTransferBytes: 8, + maxBufferedBytes: 8, + signal: new AbortController().signal, + onProgress() {}, + }); + await started; + + owner.switchUser("user-b"); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + + expect( + await previous.content.readRange({ + ref, + offset: 0, + length: 1, + signal: new AbortController().signal, + }), + ).toMatchObject({ ok: false, error: { code: "UNAVAILABLE" } }); + expect(await download).toMatchObject({ + ok: false, + error: { code: "ABORTED", operation: "DOWNLOAD" }, + }); + expect(fixture.handoffs).toBe(0); + + const next = files.current(); + expect(next).not.toBe(previous); + expect(await selectOne(next, "user-b.txt")).toMatchObject({ + ok: true, + value: { kind: "SELECTED" }, + }); + }); +}); diff --git a/tests/unit/runtime-adapters-product-scope-participants.test.ts b/tests/unit/runtime-adapters-product-scope-participants.test.ts new file mode 100644 index 00000000..698a7723 --- /dev/null +++ b/tests/unit/runtime-adapters-product-scope-participants.test.ts @@ -0,0 +1,152 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { ProductScopeParticipant } from "../../src/bootstrap/product-composition-contract.ts"; +import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; + +/** + * 2026-11-03 02-01. A product hands the template what must close with a + * session through `ProductComposition.scopeParticipants`, so it never edits + * `runtime-adapters.ts`. The real `createRuntimeAdapters` runs; only the + * product-owned file is replaced. + */ + +const fixture = vi.hoisted(() => ({ + participants: [] as ProductScopeParticipant[], + owner: undefined as Readonly<{ switchUser(subject: string): void }> | undefined, +})); + +vi.mock("../../src/bootstrap/product-composition.ts", () => ({ + composeProductSessionOwner: () => { + const listeners = new Set<() => void>(); + let subject = "user-a"; + const owner = { + readState: () => "authenticated", + readSubject: () => subject, + subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: async () => ({ headers: {} }), + recoverSession: async () => "no-session", + notifyUnauthenticated: () => {}, + switchUser(next: string) { + subject = next; + for (const listener of listeners) listener(); + }, + }; + fixture.owner = owner; + return owner; + }, + composeProduct: () => ({ + capabilities: {}, + credentialProviders: {}, + scopeParticipants: fixture.participants, + }), +})); + +let current: Awaited> | undefined; +afterEach(() => { + current?.infrastructure.dispose(); + current = undefined; + fixture.participants = []; +}); + +async function compose() { + current = await createRuntimeAdapters({ + runtime: { + config: { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + TELEMETRY_ENABLED: false, + AUTH_MODE: "external", + REQUEST_TIMEOUT_MS: 10_000, + MAX_RETRY_ATTEMPTS: 0, + RELEASE_MANIFEST_URL: "/release-manifest.json", + CONFIG_SCHEMA_VERSION: "2.0", + CAPABILITY_OVERRIDES: { + REALTIME: "DEFAULT", + WEB_WORKER: "DEFAULT", + SERVICE_WORKER: "DEFAULT", + OFFLINE_COMMANDS: "DEFAULT", + }, + FEATURE_OVERRIDES: {}, + }, + configSchema: "V2", + build: { + buildId: "build-a", + commitSha: "abc123", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + validationDurationMs: 0, + }, + release: { + schemaVersion: 2, + appVersion: "0.1.0", + buildId: "build-a", + commitSha: "abc123", + configSchemaVersion: "2.0", + contractSet: { + setAlgorithm: "CA_CONTRACT_SET_V1", + setDigest: `sha256:${"0".repeat(64)}`, + packages: [], + }, + assetManifestHash: "hash-a", + releaseId: "release-a", + builtAt: "2026-07-25T00:00:00Z", + routeChunks: { "route-home": "assets/home.js" }, + }, + host: {}, + }); + const owner = fixture.owner; + if (!owner) throw new Error("The product session owner was not asked"); + return { scope: current.infrastructure.serverStateScope, owner }; +} + +describe("product scope participants (2026-11-03 02-01)", () => { + it("closes each one, in order, on every identity change before READY", async () => { + const closed: string[] = []; + fixture.participants = [ + { label: "first", close: () => void closed.push("first") }, + { + label: "second", + async close() { + await Promise.resolve(); + closed.push("second"); + }, + }, + ]; + const { scope, owner } = await compose(); + expect(closed).toEqual([]); + + owner.switchUser("user-b"); + expect(scope.getPhase()).toBe("FENCED"); + await vi.waitFor(() => expect(scope.getPhase()).toBe("READY")); + expect(closed).toEqual(["first", "second"]); + + owner.switchUser("user-c"); + await vi.waitFor(() => expect(closed).toHaveLength(4)); + await vi.waitFor(() => expect(scope.getPhase()).toBe("READY")); + }); + + it("keeps the scope from READY when one fails, and still closes the rest", async () => { + const closed: string[] = []; + fixture.participants = [ + { + label: "broken", + close() { + throw new Error("cannot close"); + }, + }, + { label: "after", close: () => void closed.push("after") }, + ]; + const { scope, owner } = await compose(); + + owner.switchUser("user-b"); + + await vi.waitFor(() => expect(scope.getPhase()).toBe("FAILED")); + expect(closed).toEqual(["after"]); + }); +}); From f6b74ed496bcc2f0ec990d877ee8e515d0ec5846 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:56:03 +0900 Subject: [PATCH 11/18] =?UTF-8?q?fix(storage):=20put=20idle=20=EC=83=81?= =?UTF-8?q?=ED=95=9C=EC=9D=B4=20lock=20=EB=8C=80=EA=B8=B0=20=EC=83=81?= =?UTF-8?q?=ED=95=9C=EB=B3=B4=EB=8B=A4=20=EC=A7=A7=EC=A7=80=20=EC=95=8A?= =?UTF-8?q?=EC=9D=80=20OPFS=20=EC=A0=95=EC=B1=85=EC=9D=84=20=EA=B1=B0?= =?UTF-8?q?=EC=A0=88=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: putIdleTimeoutMs < mutationLockWaitTimeoutMs는 05-07이 기대는 관계다(멈춘 put이 idle 상한에서 origin lock을 놓아야 줄 선 writer가 대기 상한 전에 돈다). 이 관계가 opfs-policy.ts 주석에만 있고, 정책 검사는 각 값의 범위만 본다. 두 값을 뒤집은 정책은 조용히 통과하고, 멈춘 put 하나가 다른 탭의 모든 쓰기를 BLOCKED로 끝낸다. 고른 방법: assertOpfsRuntimePolicy가 putIdleTimeoutMs >= mutationLockWaitTimeoutMs를 TypeError로 거절한다. 다른 정책 오류와 같은 자리·같은 방식이다. 기본값(2분 < 10분)과 repo 안의 모든 정책은 이미 관계를 지킨다. 위험·한계: 이 관계를 어긴 정책을 쓰던 다운스트림은 조립 때 실패한다. 의도한 동작이다. 검증: - RED: opfs-worker-runtime.test.ts 새 2건(같음, 김)이 throw 없음으로 실패. - GREEN: OPFS 단위 3파일 + tests/recipes + tests/contract 174건 통과. check:types, 바꾼 파일 eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/05-adapters-storage-kernel.md 0929/05-09 --- src/adapters/storage/opfs/opfs-policy.ts | 7 +++++-- tests/unit/opfs-worker-runtime.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/adapters/storage/opfs/opfs-policy.ts b/src/adapters/storage/opfs/opfs-policy.ts index f15e415d..c1dc0e56 100644 --- a/src/adapters/storage/opfs/opfs-policy.ts +++ b/src/adapters/storage/opfs/opfs-policy.ts @@ -25,8 +25,9 @@ export type OpfsRuntimePolicy = Readonly<{ /** * 05-07. How long a put may wait for its source's next bytes. The put holds * the origin mutation lock from BEGIN to FINISH, so a stalled source would - * otherwise stop every tab's writes until their lock wait ran out. Keep it - * below `mutationLockWaitTimeoutMs` so a queued writer outlasts it. + * otherwise stop every tab's writes until their lock wait ran out. It must + * be below `mutationLockWaitTimeoutMs` so a queued writer outlasts it; the + * policy check refuses one that is not ([0929] 05-09). */ putIdleTimeoutMs: number; reconciliationBudgetMs: number; @@ -107,6 +108,8 @@ export function assertOpfsRuntimePolicy(policy: OpfsRuntimePolicy): void { !Number.isSafeInteger(policy.putIdleTimeoutMs) || policy.putIdleTimeoutMs < 1_000 || policy.putIdleTimeoutMs > 60 * 60_000 || + // [0929] 05-09. A queued writer must outlast a stalled one. + policy.putIdleTimeoutMs >= policy.mutationLockWaitTimeoutMs || !Number.isSafeInteger(policy.reconciliationBudgetMs) || policy.reconciliationBudgetMs < 1 || policy.reconciliationBudgetMs > 60_000 || diff --git a/tests/unit/opfs-worker-runtime.test.ts b/tests/unit/opfs-worker-runtime.test.ts index 9b361ebc..e319754c 100644 --- a/tests/unit/opfs-worker-runtime.test.ts +++ b/tests/unit/opfs-worker-runtime.test.ts @@ -3034,6 +3034,29 @@ describe("05-07 a put whose source stops lets go of the origin lock", () => { expect(await putB).toMatchObject({ ok: true, value: { generation: 1 } }); stalled.release(); }); + + // [0929] 05-09. The test above holds only while a queued writer outlasts a + // stalled one. That ordering was a comment; a policy that breaks it is now + // refused when it is resolved. + it.each([ + ["equal to", 60_000], + ["longer than", 120_000], + ])("rejects an idle bound %s the lock wait", (_, putIdleTimeoutMs) => { + expect(() => + resolveOpfsRuntimePolicy({ + ...runtimePolicy, + mutationLockWaitTimeoutMs: 60_000, + putIdleTimeoutMs, + }), + ).toThrow(TypeError); + expect( + resolveOpfsRuntimePolicy({ + ...runtimePolicy, + mutationLockWaitTimeoutMs: putIdleTimeoutMs + 1, + putIdleTimeoutMs, + }).putIdleTimeoutMs, + ).toBe(putIdleTimeoutMs); + }); }); describe("05-10 the object id grammar is the prepared-object grammar", () => { From b5c7128bdae5e401df11c3640f75f04241020862 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:57:19 +0900 Subject: [PATCH 12/18] =?UTF-8?q?test(storage):=20Web=20Storage=EC=9D=98?= =?UTF-8?q?=20Firefox=20quota=20=EC=9D=B4=EB=A6=84=EA=B3=BC=20=EB=A7=8C?= =?UTF-8?q?=EB=A3=8C=20=EA=B2=BD=EA=B3=84=EB=A5=BC=20=EA=B3=A0=EC=A0=95?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 2026-11-01 05-06에서 남은 두 분기를 테스트가 잡지 못한다. 이번 리뷰에서도 두 변이가 Web Storage 관련 테스트 3파일 49건을 통과했다. - W4: quota 판정 목록에서 Firefox의 NS_ERROR_DOM_QUOTA_REACHED를 빼도 테스트가 통과한다. 빠지면 Firefox의 quota 실패가 memory fallback 없이 STORAGE_UNAVAILABLE이 된다. - W8: 만료 비교 `<=`를 `<`로 바꿔도 통과한다. 만료 시각과 같은 순간에 값을 돌려준다. 고른 방법: 각 분기에 실패하는 테스트 하나씩. 저장소 test double에 Firefox 이름으로 던지는 모드를 더했고, 만료 경계는 expiresAt 100·101을 now 100에서 읽는다. 위험·한계: 테스트만 바꾼다. codec을 직접 부르는 테스트는 여전히 없다. 검증: W4·W8 변이를 하나씩 넣고 storage-registry·runtime-adapters· browser-storage-policy 테스트를 돌렸다. 둘 다 새 테스트가 실패했고, 원래 코드에서 storage-registry 26건 통과. check:types:test, eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/05-adapters-storage-kernel.md 1101/05-06 --- tests/unit/storage-registry.test.ts | 57 ++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/tests/unit/storage-registry.test.ts b/tests/unit/storage-registry.test.ts index 7259492e..44e03db1 100644 --- a/tests/unit/storage-registry.test.ts +++ b/tests/unit/storage-registry.test.ts @@ -11,7 +11,7 @@ import { type StorageKeyInput, } from "../../src/contracts/storage-keys.ts"; -type StorageFailureMode = "none" | "quota" | "security"; +type StorageFailureMode = "none" | "quota" | "firefox-quota" | "security"; function createStorage(options: { initial?: Readonly>; @@ -54,6 +54,10 @@ function throwFor(mode: StorageFailureMode): void { if (mode === "quota") { throw new DOMException("private quota detail", "QuotaExceededError"); } + if (mode === "firefox-quota") { + // Older Firefox names the quota error this way, with code 1014. + throw new DOMException("private quota detail", "NS_ERROR_DOM_QUOTA_REACHED"); + } if (mode === "security") { throw new DOMException("private security detail", "SecurityError"); } @@ -278,6 +282,22 @@ describe("storage registry", () => { ); }); + // 2026-11-01 05-06. The second quota name was in the adapter's list but no + // test sent it, so dropping it went unseen. + it("falls back to memory on Firefox's quota error name too", () => { + const { storage: localStorage } = createStorage({ + writeFailure: "firefox-quota", + }); + const adapter = createBrowserStorageAdapter({ localStorage }); + + expect(adapter.write("COLOR_SCHEME", "dark")).toMatchObject({ + ok: false, + fallback: "memory", + error: { kind: "STORAGE_QUOTA_EXCEEDED" }, + }); + expect(adapter.read("COLOR_SCHEME")).toEqual({ ok: true, value: "dark" }); + }); + it("discards data from a previous schema version", () => { const { storage: localStorage, values, removeItem } = createStorage({ initial: { @@ -396,6 +416,41 @@ describe("storage registry", () => { expect(removeItem).toHaveBeenCalledWith(expiring.physicalKey); }); + // 2026-11-01 05-06. A record is expired at its expiry instant, not after it. + it.each([ + [100, undefined], + [101, "private-expiring"], + ])("reads a record expiring at %i at time 100 as %s", (expiresAt, value) => { + const expiring = defineStorageKey({ + logicalName: "EXPIRING_PREFERENCE", + scope: "preference", + name: "expiring", + backend: "localStorage", + classification: "public-preference", + schemaVersion: 1, + valueCodec: "opaque-string-v1", + ttl: 10, + migration: "discard", + quotaFallback: "memory", + }); + const { storage } = createStorage({ + initial: { + [expiring.physicalKey]: serializedEnvelope("private-expiring", { + expiresAt, + }), + }, + }); + const adapter = createBrowserStorageAdapter({ + localStorage: storage, + now: () => 100, + resolveDefinition: definitionResolver({ + EXPIRING_PREFERENCE: expiring, + }), + }); + + expect(adapter.read("EXPIRING_PREFERENCE")).toEqual({ ok: true, value }); + }); + it("prioritizes a failed-write memory envelope over stale persistent data and expires it", () => { let timestamp = 100; const expiring = defineStorageKey({ From 0a74bd42b049b9370fc19df42a306aca5dd01aa8 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:59:25 +0900 Subject: [PATCH 13/18] =?UTF-8?q?test(browser-files):=20handoff=20?= =?UTF-8?q?=EC=8B=A4=ED=8C=A8=20lease=20=EB=B0=98=ED=99=98=EA=B3=BC=20?= =?UTF-8?q?=EB=82=A8=EC=9D=80=20=EB=B3=B4=ED=98=B8=20=EA=B7=9C=EC=B9=99=20?= =?UTF-8?q?3=EA=B0=9C=EB=A5=BC=20=EA=B3=A0=EC=A0=95=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 이번 리뷰에서도 아래 browser-files 변이가 관련 unit 파일을 모두 통과했다. - M10(0929/02-05): bounded download의 catch에서 lease?.release()를 지운다. handoff가 던지면 만든 blob URL이 runtime dispose까지 남는다. - N27(1101/02-04 ③): 같은 파일을 다시 inspect할 때 이전 receipt를 무효화하지 않는다. 다른 정책으로 검사한 옛 receipt로 preview가 열린다. - N29(1101/02-04 ①): object URL lease의 합계 바이트 상한을 지운다. 기존 테스트는 개수 상한이 먼저 막아 바이트 상한을 보지 못했다. - N30(1101/02-04 ⑥): browser-managed handoff의 fragment 거절을 지운다. 고른 방법: 규칙마다 실패하는 테스트 하나. N29는 개수 여유가 있을 때도 바이트가 막는 경우를 기존 상한 테스트 끝에 더했고, N30은 target 규칙 표에 fragment href 한 줄을 더했다. 위험·한계: 테스트만 바꾼다. 1101/02-04의 나머지(N26·N26b는 다음 커밋, N38 host storageArea, N39 조회 keys() 재확인)는 이 커밋에 없다. 검증: 네 변이를 하나씩 넣고 browser-files 단위 5파일 + tests/recipes를 돌렸다. 모두 새 테스트(또는 늘린 행)가 실패했고 되돌린 뒤 통과. 원래 코드에서 두 파일 47건 통과. check:types:test, eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 0929/02-05, 1101/02-04 --- tests/unit/browser-file-content.test.ts | 77 ++++++++++++++++++++++++ tests/unit/browser-file-download.test.ts | 35 +++++++++++ 2 files changed, 112 insertions(+) diff --git a/tests/unit/browser-file-content.test.ts b/tests/unit/browser-file-content.test.ts index b44ef84a..fde5dcbf 100644 --- a/tests/unit/browser-file-content.test.ts +++ b/tests/unit/browser-file-content.test.ts @@ -981,6 +981,83 @@ describe("browser file content policy", () => { ).toThrowError(DOMException); lease.release(); expect(leases.aggregateLeaseByteLength).toBe(0); + + // 2026-11-01 02-04 (N29). A free slot does not lift the byte cap. + const byBytes = new ObjectUrlLeaseRegistry( + { + createObjectURL: () => `blob:bytes-${urlSequence++}`, + revokeObjectURL() {}, + }, + { + hardMaxActiveLeases: 2, + hardMaxSingleLeaseBytes: 4, + hardMaxAggregateLeaseBytes: 6, + }, + ); + const held = byBytes.create(new Blob([new Uint8Array(4)])); + expect(() => + byBytes.create(new Blob([new Uint8Array(3)])), + ).toThrowError(DOMException); + expect(byBytes.activeLeaseCount).toBe(1); + held.release(); + expect(() => + byBytes.create(new Blob([new Uint8Array(3)])), + ).not.toThrow(); + }); + + // 2026-11-01 02-04 (N27). Inspecting again replaces the receipt: the file + // may have been checked against a different policy, so the old one ends. + it("ends the previous receipt when the same file is inspected again", async () => { + const policies = pngPolicies(); + const vault = new BrowserFileVault({ policies }); + const captured = vault.captureFiles( + [ + new File( + [new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])], + "again.png", + { type: "image/png", lastModified: 1 }, + ), + ], + pngSelectionPolicy, + ); + if (!captured.ok || !captured.value[0]) throw new Error("capture"); + const ref = captured.value[0].ref; + const receiptOf = async () => { + const inspected = await vault.inspect({ + ref, + policy: pngPolicy, + signal: new AbortController().signal, + }); + if (!inspected.ok || !inspected.value.verificationReceipt) { + throw new Error("inspect"); + } + return inspected.value.verificationReceipt; + }; + const first = await receiptOf(); + const second = await receiptOf(); + expect(vault.activeVerificationCount).toBe(1); + const preview = new BrowserTransientPreview({ + files: vault, + policies, + leases: new ObjectUrlLeaseRegistry({ + createObjectURL: () => "blob:again", + revokeObjectURL() {}, + }), + hardMaxPreviewBytes: 10, + }); + const create = (verificationReceipt: FileVerificationReceipt) => + preview.create({ + ref, + verificationReceipt, + policy: pngPolicy, + signal: new AbortController().signal, + }); + + expect(await create(first)).toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED" }, + }); + expect(await create(second)).toMatchObject({ ok: true }); }); it("converts native stream exceptions to closed chunk failures", async () => { diff --git a/tests/unit/browser-file-download.test.ts b/tests/unit/browser-file-download.test.ts index 4521d7e7..40effd97 100644 --- a/tests/unit/browser-file-download.test.ts +++ b/tests/unit/browser-file-download.test.ts @@ -293,9 +293,11 @@ describe("browser download delivery", () => { it("rejects cross-origin or query-bearing browser-managed targets", async () => { // 02-08. Each href breaks one rule, so neither check hides the other. + // 2026-11-01 02-04 (N30): a fragment is refused on its own too. for (const href of [ "https://evil.example/downloads/a", "/downloads/a?token=secret", + "/downloads/a#token=secret", ]) { const handoff = vi.fn(); const adapter = createDownloadDeliveryAdapter({ @@ -767,6 +769,39 @@ describe("browser download delivery", () => { expect(revoked).toEqual(["blob:download-1"]); }); + // [0929] 02-05. A handoff that throws hands nothing to the browser, so the + // lease made for it is revoked at once instead of waiting for dispose. + it("revokes the lease of a handoff that throws", async () => { + const revoked: string[] = []; + const leases = new ObjectUrlLeaseRegistry({ + createObjectURL: () => "blob:download-failed", + revokeObjectURL: (url) => revoked.push(url), + }); + const adapter = createDownloadDeliveryAdapter({ + ...HARD_LIMITS, + policies, + host: { + handoff() { + throw new DOMException("blocked", "NotAllowedError"); + }, + }, + browserManagedCapabilities: capabilityResolver(), + objectUrls: leases, + userActivation: { isActive: true }, + }); + + expect( + await adapter.deliver( + deliveryInput( + { kind: "GENERATED", bytes: byteSource([new Uint8Array([1, 2])]) }, + "BOUNDED_OBJECT_URL", + ), + ), + ).toMatchObject({ ok: false }); + expect(leases.activeLeaseCount).toBe(0); + expect(revoked).toEqual(["blob:download-failed"]); + }); + it("revokes only its own leases on dispose when the registry is shared (2026-11-01 02-01)", async () => { const revoked: string[] = []; let urlSequence = 0; From de2670cda5e8daa753acf1eb99a9aba6a3bf9a23 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 21:00:22 +0900 Subject: [PATCH 14/18] =?UTF-8?q?test(cache-storage):=20no-cache=EC=99=80?= =?UTF-8?q?=20Set-Cookie=20=EC=9D=91=EB=8B=B5=20=EA=B1=B0=EC=A0=88?= =?UTF-8?q?=EC=9D=84=20=EB=94=B0=EB=A1=9C=20=EA=B3=A0=EC=A0=95=ED=95=9C?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 1101/02-04의 두 변이가 이번에도 cache 단위 테스트를 모두 통과했다. N26b는 Cache-Control: no-cache 거절, N26은 Set-Cookie 응답 거절을 지운다. 둘 다 빠지면 사용자별이거나 재검증이 필요한 응답이 익명 공용 캐시에 들어간다. 기존 표는 no-store·pragma·www-authenticate만 따로 보았다. 고른 방법: 응답 검증 표("keeps response validation failure codes")에 두 행을 더한다. 각 행은 규칙 하나만 어긴다. 위험·한계: 테스트만 바꾼다. 검증: 두 변이를 하나씩 넣고 cache 단위 3파일 + tests/recipes를 돌렸다. 둘 다 이 테스트가 실패했고 되돌린 뒤 통과. eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 1101/02-04 --- tests/unit/public-response-cache-codec.test.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/unit/public-response-cache-codec.test.ts b/tests/unit/public-response-cache-codec.test.ts index 5d5d8573..5c3dc7a1 100644 --- a/tests/unit/public-response-cache-codec.test.ts +++ b/tests/unit/public-response-cache-codec.test.ts @@ -157,6 +157,13 @@ describe("public cache codec and response validation (characterization)", () => expect(await stageCode([valid], response({ pragma: "no-cache" }))).toBe( "POLICY_REJECTED", ); + // 2026-11-01 02-04 (N26b, N26). Each directive or header on its own. + expect( + await stageCode([valid], response({ "cache-control": "no-cache" })), + ).toBe("POLICY_REJECTED"); + expect( + await stageCode([valid], response({ "set-cookie": "session=1" })), + ).toBe("POLICY_REJECTED"); expect( await stageCode([valid], response({ "www-authenticate": "Basic" })), ).toBe("POLICY_REJECTED"); From 3bfe6a85809da7e41bc691c58fe0c026548d4858 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 21:01:49 +0900 Subject: [PATCH 15/18] =?UTF-8?q?test(cache-storage):=20=EC=A1=B0=ED=9A=8C?= =?UTF-8?q?=EA=B0=80=20eviction=20=ED=8C=90=EC=A0=95=20=EC=A0=84=EC=97=90?= =?UTF-8?q?=20=EC=BA=90=EC=8B=9C=20=EB=AA=A9=EB=A1=9D=EC=9D=84=20=EB=8B=A4?= =?UTF-8?q?=EC=8B=9C=20=EC=9D=BD=EB=8A=94=EC=A7=80=20=EA=B3=A0=EC=A0=95?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 조회는 cache 이름 목록을 pointer보다 먼저 읽는다. 그 사이 다른 탭의 activation이 pointer를 새 캐시로 옮기면 목록에 그 캐시가 없다. 코드는 목록을 한 번 더 읽고서야 STORAGE_EVICTED를 낸다 (1101/02-04 ⑤, N39). 이 재확인을 지워도 테스트가 모두 통과했다. 빠지면 방금 배포한 release의 첫 조회가 "지워졌다"로 끝나고 REHYDRATE로 간다. 고른 방법: 첫 keys()만 배포 전 목록을 돌려주는 저장소로 r2 활성화 뒤 조회한다. adapter는 만들 때 keys를 잡아 두므로 저장소 하위 클래스로 한 번만 낡은 답을 준다. 위험·한계: 테스트만 바꾼다. 1101/02-04의 N38(host storageArea 비교)은 pulse wire 값을 만드는 하네스가 필요해 이번에 하지 않았다. 검증: N39 변이를 넣으면 이 테스트가 STORAGE_EVICTED로 실패하고(cache 단위 3파일 + tests/recipes 71건 중 1건), 되돌리면 같은 파일 14건 통과. check:types:test, eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 1101/02-04 --- .../unit/public-response-cache-repair.test.ts | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/unit/public-response-cache-repair.test.ts b/tests/unit/public-response-cache-repair.test.ts index 692cc95b..554ee1b6 100644 --- a/tests/unit/public-response-cache-repair.test.ts +++ b/tests/unit/public-response-cache-repair.test.ts @@ -584,6 +584,33 @@ describe("public cache pointer after a policy change or damage (0929/02-01)", () ).toMatchObject({ ok: true, value: expect.anything() }); }); + // 2026-11-01 02-04 (N39). The cache name list is read before the pointer. + // An activation in between moves the pointer to a cache that list does not + // have yet; the lookup lists again rather than report it evicted. + it("lists caches again before it reports the active release evicted", async () => { + // The adapter captures `keys` when it is built, so the stale answer is + // armed through the storage itself. + class StaleOnceCacheStorage extends MemoryCacheStorage { + staleNames: string[] | null = null; + override async keys(): Promise { + const stale = this.staleNames; + this.staleNames = null; + return stale ?? (await super.keys()); + } + } + const cacheStorage = new StaleOnceCacheStorage(); + const policy = policyRetaining(1); + const adapter = adapterFor(cacheStorage, policy); + expect(await deploy(adapter, "r1", policy)).toMatchObject({ ok: true }); + const namesBeforeR2 = await cacheStorage.keys(); + expect(await deploy(adapter, "r2", policy)).toMatchObject({ ok: true }); + cacheStorage.staleNames = namesBeforeR2; + + expect( + await adapter.responses.matchActiveExact({ absoluteUrl: assetUrl("r2") }), + ).toMatchObject({ ok: true, value: expect.anything() }); + }); + it("still stops activation when the pointer read fails transiently", async () => { const cacheStorage = new MemoryCacheStorage(); const policy = policyRetaining(1); From d9ca6537d8687e29de4e577a78114851b75f788b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 21:02:15 +0900 Subject: [PATCH 16/18] =?UTF-8?q?docs(architecture):=20=EC=BA=90=EC=8B=9C?= =?UTF-8?q?=20=EB=AC=B8=EC=84=9C=EC=9D=98=20=EB=B0=80=EB=A6=B0=20=EC=A4=84?= =?UTF-8?q?=20=EB=B2=88=ED=98=B8=20=EC=B0=B8=EC=A1=B0=EB=A5=BC=20=EC=8B=AC?= =?UTF-8?q?=EB=B3=BC=20=EC=9D=B4=EB=A6=84=EC=9C=BC=EB=A1=9C=20=EB=B0=94?= =?UTF-8?q?=EA=BE=BC=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: client-cache-and-storage.md의 cross-context 조립 설명이 runtime-adapters.ts·server-state-scope-runtime.ts·tanstack-cache- coordinator.ts의 줄 번호를 가리키는데, 네 곳 모두 다른 코드로 밀렸다 (0929/02-04). 문서 줄 번호를 보는 검사는 없어서 다음 변경에도 또 밀린다. browser-file-and-origin-storage.md의 participant 등록 예 줄 번호는 앞 커밋(02-01)이 이미 고쳤다. 고른 방법: 줄 번호 대신 함수·호출 이름을 적는다(1101/05-05와 같은 방식). 리뷰가 맞다고 확인한 다른 줄 번호는 그대로 둔다. 위험·한계: 문서만 바꾼다. 다른 문서의 줄 번호 참조는 건드리지 않았다. 검증: verify:documentation PASS_SCOPED. Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 0929/02-04 --- docs/architecture/client-cache-and-storage.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/architecture/client-cache-and-storage.md b/docs/architecture/client-cache-and-storage.md index f7915853..8e7143d6 100644 --- a/docs/architecture/client-cache-and-storage.md +++ b/docs/architecture/client-cache-and-storage.md @@ -90,14 +90,16 @@ host facade는 native `StorageEvent.storageArea`를 캡처한 `localStorage` 객 (`browser-cross-context-invalidation.ts:197-201`). 현재 epoch는 release 하나다. `cacheEpoch`는 release ID의 64-bit FNV-1a digest를 -`release.<16자리 hex>`로 쓴 값이다(`browser-cross-context-host.ts:45-51`, 조립 -`src/bootstrap/runtime-adapters.ts:364-366`). 세션 identity가 바뀌면 scope +`release.<16자리 hex>`로 쓴 값이다(`browser-cross-context-host.ts` +`crossContextCacheEpochForRelease`, 조립은 `src/bootstrap/runtime-adapters.ts`의 +`createServerStateGenerationStore` 콜백). 세션 identity가 바뀌면 scope runtime이 다음 server-state generation을 열고 -(`src/adapters/query-cache/server-state-scope-runtime.ts:148`), generation마다 -새 `QueryClient`와 새 cross-context transport(새 `sourceId`·`sourceEpoch`)를 -만든다(`src/bootstrap/server-state-generation-store.ts:50-57`, -`runtime-adapters.ts:359-372`). 이전 generation의 transport는 coordinator -dispose에서 닫힌다(`src/adapters/query-cache/tanstack-cache-coordinator.ts:276-280`). +(`src/adapters/query-cache/server-state-scope-runtime.ts`의 +`activateNextGeneration` 호출), generation마다 새 `QueryClient`와 새 +cross-context transport(새 `sourceId`·`sourceEpoch`)를 만든다 +(`src/bootstrap/server-state-generation-store.ts:50-57`, 같은 콜백). 이전 +generation의 transport는 coordinator `dispose()`에서 닫힌다 +(`src/adapters/query-cache/tanstack-cache-coordinator.ts`). session/account epoch, opaque account partition과 durable namespace epoch는 아직 없다. wire event에 사용자·세션 scope가 없으므로 현재 cross-tab event는 같은 release의 등록 query topic을 빠르게 stale 처리하는 용도에 한정된다. From 3f72ae7df97f200e0a5af1aa99c79f9411661420 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 21:17:39 +0900 Subject: [PATCH 17/18] =?UTF-8?q?docs(architecture):=20adapter=20kernel=20?= =?UTF-8?q?=EC=84=A4=EB=AA=85=EC=9D=84=20=EC=8B=A4=EC=A0=9C=20platform=20?= =?UTF-8?q?=ED=8F=B4=EB=8D=94=20=EB=82=B4=EC=9A=A9=EC=97=90=20=EB=A7=9E?= =?UTF-8?q?=EC=B6=98=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: layers.md와 .dependency-cruiser.json 규칙 주석은 kernel (src/adapters/platform/**)을 "clock, abort primitive, capacity guard"로만 적는다(0929/05-08). 실제 폴더에는 IndexedDB 연결·트랜잭션, Retry-After, JSON member scanner와 bootstrap만 쓰는 lifecycle runtime·mutation intent factory까지 10개 파일이 있다. 편입 기준("must never own")은 indexeddb-connection.ts 머리 주석에만 있어, 폴더에 무엇을 넣어도 되는지 문서로는 알 수 없다. 고른 방법: 리뷰 5.3절 (b). 두 곳의 설명을 실제 목록으로 고치고, 공유 메커니즘과 bootstrap 전용 서비스를 나눠 적고, 기준이 있는 위치를 가리킨다. 파일을 옮기는 (c)·(d)는 하지 않았다(1101/05-04, 남음). 위험·한계: 문서와 규칙 주석만 바꾼다. 규칙 동작은 같다. 폴더에 무엇을 넣을지를 기계가 보지 않는 것은 그대로다. 검증: check:architecture, verify:documentation 통과. bootstrap 밖에서 lifecycle·mutation intent factory를 쓰는 곳이 없음을 grep으로 확인했다. Refs: docs/reviews/2026-11-03-maturity-review/05-adapters-storage-kernel.md 0929/05-08 --- .dependency-cruiser.json | 2 +- docs/architecture/layers.md | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.dependency-cruiser.json b/.dependency-cruiser.json index 133c1641..c3c50d5d 100644 --- a/.dependency-cruiser.json +++ b/.dependency-cruiser.json @@ -251,7 +251,7 @@ }, { "name": "adapters-do-not-know-other-concrete-adapters", - "comment": "docs/architecture/layers.md §4: a concrete adapter never depends on another concrete adapter. The adapter kernel is shared on purpose and any adapter may import it: src/adapters/platform/** (clock, abort primitive, capacity guard), src/adapters/browser-file-storage/result.ts (browser-data result helpers) and src/adapters/cross-context-invalidation/index.ts (the cross-context invalidation transport and its types). Owner: frontend-platform. No new file-level exception is added here; a new shared primitive goes into src/adapters/platform/.", + "comment": "docs/architecture/layers.md §4: a concrete adapter never depends on another concrete adapter. The adapter kernel is shared on purpose and any adapter may import it: src/adapters/platform/** (shared mechanisms only: clock, abort primitive, capacity guard, IndexedDB connection and transaction, Retry-After, JSON member scanner; plus two bootstrap-only services, see layers.md), src/adapters/browser-file-storage/result.ts (browser-data result helpers) and src/adapters/cross-context-invalidation/index.ts (the cross-context invalidation transport and its types). Owner: frontend-platform. No new file-level exception is added here; a new shared primitive goes into src/adapters/platform/.", "severity": "error", "from": { "path": "^src/adapters/([^/]+)/" diff --git a/docs/architecture/layers.md b/docs/architecture/layers.md index 973e6e6a..63d25c2c 100644 --- a/docs/architecture/layers.md +++ b/docs/architecture/layers.md @@ -80,8 +80,14 @@ passing. which is shared on purpose and is the only adapter code an adapter may reach across a group for: -- `src/adapters/platform/**` — the system clock, the shared abort primitive and - the bounded-capacity guard +- `src/adapters/platform/**` — mechanisms more than one adapter group shares: + the system clock, the shared abort primitive, the bounded-capacity guard, + the IndexedDB connection and transaction helpers, `Retry-After` parsing and + the JSON member scanner. Two bootstrap-only platform services live there + too: the browser lifecycle runtime and the mutation intent factory (no + adapter imports them). A kernel file owns mechanics only, never names, + schemas, failure codes or observation shapes; the full list of what it must + never own is at the top of `indexeddb-connection.ts` - `src/adapters/browser-file-storage/result.ts` — the browser-data result and failure constructors - `src/adapters/cross-context-invalidation/index.ts` — the cross-context From 4f78890576b8d5a9004372f2b8c31cd883d9990b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 21:18:51 +0900 Subject: [PATCH 18/18] =?UTF-8?q?fix(browser-files):=20=EC=9C=84=ED=97=98?= =?UTF-8?q?=20=ED=99=95=EC=9E=A5=EC=9E=90=EB=A5=BC=20safe=20extension?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=93=B0=EB=8A=94=20=EB=8B=A4=EC=9A=B4?= =?UTF-8?q?=EB=A1=9C=EB=93=9C=20=EC=A0=95=EC=B1=85=EC=9D=84=20=EA=B1=B0?= =?UTF-8?q?=EC=A0=88=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: download 정책 registry는 safeExtension의 형식만 본다. 파일명 금지 목록(.exe, .html, .js 등)은 사용자가 준 이름에만 쓴다 (1101/02-02). 그래서 mediaType application/pdf + safeExtension .exe 정책이 조립되고, invoice.pdf가 invoice.exe로 browser handoff된다 (리뷰 E-7). 고른 방법: snapshotDownload가 금지 목록에 있거나 그것으로 끝나는 (.tar.js) safeExtension을 다른 정책 오류와 같이 TypeError로 거절한다. 목록은 file-policy.ts의 DEFAULT_FORBIDDEN_EXTENSIONS 하나를 쓰고, isForbiddenDownloadExtension으로 내보낸다. browser-managed capability는 정책과 같은 safeExtension이어야 하므로 그 경로도 함께 막힌다. 버린 대안: media type과 확장자 짝 표를 두는 것. 표를 누가 소유할지 정해야 하고 범위가 크다. 이번에는 하지 않았다. 위험·한계: 이 확장자를 쓰던 다운스트림 정책은 조립 때 실패한다(보안 강화 방향). media type과 확장자가 서로 맞는지는 여전히 보지 않는다 (설계 문서에 적었다). file-transfer 번들 56,068 → 56,100 / 57,800 gzip B. 검증: - RED: browser-file-policy-registry.test.ts 새 3건(.exe, .HTML, .tar.js)이 throw 없음으로 실패. - GREEN: browser-files 단위 5파일 + tests/recipes 98건 통과. check:types, 바꾼 파일 eslint, check:optional-recipes:source PASS, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/02-adapters-browser-files-cache.md 1101/02-02 --- .../browser-file-and-origin-storage.md | 5 +++- .../browser-file-policy-registry.ts | 2 ++ src/adapters/browser-files/file-policy.ts | 11 ++++++++ .../unit/browser-file-policy-registry.test.ts | 28 +++++++++++++++++++ 4 files changed, 45 insertions(+), 1 deletion(-) diff --git a/docs/architecture/browser-file-and-origin-storage.md b/docs/architecture/browser-file-and-origin-storage.md index 0144fdb5..d9762ec6 100644 --- a/docs/architecture/browser-file-and-origin-storage.md +++ b/docs/architecture/browser-file-and-origin-storage.md @@ -447,7 +447,10 @@ stream-to-file에서 integrity를 close 전에 확인해야 하면 writable을 `INTEGRITY_FAILED` 또는 partial-save failure를 반환한다. 전략, media type, safe extension, integrity mode와 최대 bytes는 composition -registry가 소유한다. caller는 composition이 등록한 정확한 +registry가 소유한다. registry는 사용자 파일명에서 지우는 위험 확장자 +(`.exe`, `.html`, `.js` 등)이거나 그것으로 끝나는 safe extension을 조립 때 +거절한다(2026-11-01 02-02). media type과 확장자가 서로 맞는지는 아직 보지 +않는다. caller는 composition이 등록한 정확한 `FilePolicyReference` 객체, 아래 source union의 최소 입력, filename과 limit reduction만 전달한다. `policyKey`/`intention`이 같은 새 객체나 raw 전략을 제출할 수 없다. source는 다음처럼 분리한다. diff --git a/src/adapters/browser-files/browser-file-policy-registry.ts b/src/adapters/browser-files/browser-file-policy-registry.ts index a4f639f0..4b253d41 100644 --- a/src/adapters/browser-files/browser-file-policy-registry.ts +++ b/src/adapters/browser-files/browser-file-policy-registry.ts @@ -15,6 +15,7 @@ import { assertFileInspectionPolicy, assertFileSelectionPolicy, EXACT_MEDIA_TYPE, + isForbiddenDownloadExtension, isPositiveSafeInteger, sanitizeSuggestedFileName, type RegisteredFileInspectionPolicy, @@ -452,6 +453,7 @@ function snapshotDownload( "BOUNDED_OBJECT_URL", ].includes(input.strategy) || !EXACT_MEDIA_TYPE.test(mediaType) || + isForbiddenDownloadExtension(safeExtension) || !isPositiveSafeInteger(input.maxTransferBytes) || !isPositiveSafeInteger(input.maxBufferedBytes) || input.maxTransferBytes > hardLimits.maxTransferBytes || diff --git a/src/adapters/browser-files/file-policy.ts b/src/adapters/browser-files/file-policy.ts index 988fc285..380df048 100644 --- a/src/adapters/browser-files/file-policy.ts +++ b/src/adapters/browser-files/file-policy.ts @@ -96,6 +96,17 @@ const DEFAULT_FORBIDDEN_EXTENSIONS = Object.freeze([ ".xll", ] as const); +/** + * 2026-11-01 02-02. A download policy's own extension may not be one a + * user-supplied file name is stripped of, nor end in one (`.tar.js`). + */ +export function isForbiddenDownloadExtension(extension: string): boolean { + const normalized = extension.normalize("NFC").toLowerCase(); + return DEFAULT_FORBIDDEN_EXTENSIONS.some((forbidden) => + normalized.endsWith(forbidden), + ); +} + export type SuggestedFileNamePolicy = Readonly<{ safeExtension: string; fallbackBaseName?: string; diff --git a/tests/unit/browser-file-policy-registry.test.ts b/tests/unit/browser-file-policy-registry.test.ts index 5249d388..60d8e651 100644 --- a/tests/unit/browser-file-policy-registry.test.ts +++ b/tests/unit/browser-file-policy-registry.test.ts @@ -174,6 +174,34 @@ describe("browser file composition policy registry", () => { }); }); + // 2026-11-01 02-02. The download extension was checked for shape only, so a + // policy could hand `invoice.pdf` to the browser as `invoice.exe`. The + // extensions a user-supplied file name is stripped of are refused here too. + it.each([".exe", ".HTML", ".tar.js"])( + "refuses a download policy whose safe extension is %s", + (safeExtension) => { + expect( + () => + new BrowserFilePolicyRegistry({ + profiles: [ + { + reference: browserFilePolicyReference("downloads", "invoice"), + download: { + strategy: "BOUNDED_OBJECT_URL", + mediaType: "application/pdf", + safeExtension, + maxTransferBytes: 100, + maxBufferedBytes: 50, + integrity: "OPTIONAL", + }, + }, + ], + hardLimits, + }), + ).toThrow(TypeError); + }, + ); + it("binds verification receipts to the exact profile, not a reused policyId", async () => { const profileA = browserFilePolicyReference( "images-a",