From 7b55f0f83d0f065a55e2345fce3b9780c6231b56 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:34:28 +0900 Subject: [PATCH] =?UTF-8?q?fix(storage):=20partition=20lock=EC=9D=84=20?= =?UTF-8?q?=EA=B8=B0=EB=8B=A4=EB=A6=AC=EB=8A=94=20put=C2=B7delete=EA=B0=80?= =?UTF-8?q?=20=EC=9E=90=EA=B8=B0=20abort=EB=A1=9C=20=EB=81=9D=EB=82=9C?= =?UTF-8?q?=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;