fix(storage): 계정 삭제 purge가 끝나지 않은 put을 보면 partition을 지운다

문제: 손상이 없는 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
This commit is contained in:
DongHyeonka
2026-11-04 20:29:34 +09:00
parent 1dfe86a372
commit d13a393600
8 changed files with 431 additions and 67 deletions
@@ -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<number>(
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<BrowserDataFailure>({
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 ||
@@ -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),
});
}
@@ -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<BrowserDataResult<boolean>>;
/**
* 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<BrowserDataResult<number>>;
/**
* [0929] 05-01. Deletes every row keyed to this one partition, readable or
* not: committed objects, journal rows, chunk references and the budget.