fix(storage): let fail() win over succeed() and abort late upgrades (Q-6.5-10)

Two small holes in the IndexedDB kernel (src/adapters/platform/):

- runIndexedDbTransaction: a `fail(x)` after `succeed()` kept the success
  candidate, so the abort it triggered was reported as an anonymous
  NATIVE_EXCEPTION and `x` was lost. `fail` now replaces a success
  candidate; an earlier failure still wins.
- openIndexedDbDatabase: when the open had already settled (caller abort,
  terminal BLOCKED, blocked deadline, close) before `onupgradeneeded`
  fired, the upgrade still ran and committed the migration. The handler now
  aborts the versionchange transaction when the open is already settled.

Tests that encoded the old behavior were updated in this commit:
tests/unit/indexeddb-transaction.test.ts ("an abort after succeed...")
expected NATIVE_EXCEPTION and now expects the caller's failure, and
tests/unit/indexeddb-runtime.test.ts ("times out a blocked upgrade...")
expected the late upgrade to commit and its connection to be closed; it now
expects no schema commit. Both fail without the fix.

Verified: new tests (fail after succeed on a real fake DB does not commit,
first failure still wins, late upgrade after caller abort and after
BLOCKED is aborted without running the upgrade callback) were RED and are
GREEN. All gates pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-24 13:30:26 +09:00
co-authored by Claude Opus 5.5
parent 510cd80a5c
commit b3a68f70ca
5 changed files with 118 additions and 11 deletions
@@ -332,7 +332,9 @@ export function openIndexedDbDatabase<Failure>(
// A null `newVersion` means a delete is in progress, and no `upgrade`
// policy can be applied to a schema that is going away. It is reported
// before the callback runs so a caller never sees a half-open upgrade.
if (!transaction || newVersion === null || !input.upgrade) {
// Q-6.5-10. An open that already settled (caller abort, BLOCKED, close)
// must not commit a migration behind its caller's back either.
if (settled || !transaction || newVersion === null || !input.upgrade) {
upgradeRejection = { kind: "UPGRADE_REJECTED", oldVersion, newVersion };
abortUpgrade();
return;
@@ -26,7 +26,8 @@ export type IndexedDbDurability = "default" | "strict" | "relaxed";
*/
export type IndexedDbRequestSink<Failure> = Readonly<{
/**
* Records the failure and aborts the transaction. The first failure wins.
* Records the failure and aborts the transaction. The first failure wins,
* and it wins over an earlier `succeed`.
* This is `indexeddb-runtime.ts:1047-1054`'s `fail`.
*/
fail(failure: Failure): void;
@@ -266,7 +267,9 @@ export function runIndexedDbTransaction<Value, Failure>(
candidate ??= succeeded(value);
},
fail(failure) {
candidate ??= failed(failure);
// Q-6.5-10. A failure replaces an earlier `succeed`; only an earlier
// failure outranks it.
if (candidate?.ok !== false) candidate = failed(failure);
try {
transaction.abort();
} catch {
+59
View File
@@ -469,6 +469,65 @@ describe("shared IndexedDB connection mechanics", () => {
});
});
describe("Q-6.5-10 an upgrade that starts after the open settled", () => {
function openWithUpgrade(
stub: StubFactory,
options: Readonly<{ signal?: AbortSignal }> = {},
) {
const upgrade = vi.fn(() => ({ kind: "APPLIED" as const }));
const pending = openIndexedDbDatabase<TestFailure>({
factory: stub.factory,
databaseName: "kernel",
version: 2,
translate: recordingTranslate([]),
upgrade,
...options,
});
const request = stub.opened[0];
if (!request) throw new Error("no open request");
return { pending, request, upgrade };
}
function startUpgrade(request: StubOpenRequest) {
const abort = vi.fn();
request.transaction = { abort } as unknown as IDBTransaction;
request.onupgradeneeded?.(versionChangeEvent(1, 2));
return abort;
}
it("is aborted instead of migrating after the caller gave up", async () => {
const stub = stubFactory();
const controller = new AbortController();
const { pending, request, upgrade } = openWithUpgrade(stub, {
signal: controller.signal,
});
// No versionchange transaction exists yet, so there is nothing to abort.
controller.abort();
await expect(pending).resolves.toEqual({
ok: false,
error: { cause: "CALLER_ABORT" },
});
const abort = startUpgrade(request);
expect(upgrade).not.toHaveBeenCalled();
expect(abort).toHaveBeenCalledTimes(1);
});
it("is aborted after a terminal BLOCKED", async () => {
const stub = stubFactory();
const { pending, request, upgrade } = openWithUpgrade(stub);
request.onblocked?.(versionChangeEvent(1, 2));
await expect(pending).resolves.toMatchObject({
ok: false,
error: { cause: "BLOCKED" },
});
const abort = startUpgrade(request);
expect(upgrade).not.toHaveBeenCalled();
expect(abort).toHaveBeenCalledTimes(1);
});
});
it("closes a connection that arrives after the caller gave up", async () => {
const memory = new MemoryIndexedDbFactory();
const controller = new AbortController();
+5 -2
View File
@@ -449,7 +449,7 @@ describe("IndexedDB runtime", () => {
expect(runtime.getStatus()).toEqual({ kind: "READY", schemaVersion: 1 });
});
it("times out a blocked upgrade, then closes a late successful connection", async () => {
it("times out a blocked upgrade, then aborts the late upgrade instead of committing it", async () => {
const memory = new MemoryIndexedDbFactory();
memory.blockNextOpen();
let timeout: (() => void) | undefined;
@@ -484,7 +484,10 @@ describe("IndexedDB runtime", () => {
memory.releaseBlockedOpen();
await Promise.resolve();
expect(memory.isConnectionClosed()).toBe(true);
// Q-6.5-10. The upgrade that starts after the deadline is aborted, so no
// schema commits and no connection exists to leak. (This test used to
// expect the late upgrade to commit and its connection to be closed.)
expect(memory.hasStore("records")).toBe(false);
expect(runtime.getStatus()).toEqual({
kind: "CLOSED",
reason: "NOT_OPENED",
+46 -6
View File
@@ -383,12 +383,52 @@ describe("shared IndexedDB transaction mechanics", () => {
transaction.error = new DOMException("aborted", "AbortError");
transaction.onabort?.(new Event("abort"));
const result = await pending;
expect(result.ok).toBe(false);
if (result.ok) return;
// The first candidate wins, so the later `fail` never becomes the value;
// an aborted transaction still cannot report the success it never kept.
expect(result.error.cause).toBe("NATIVE_EXCEPTION");
// Q-6.5-10. A `fail` after `succeed` replaces the success candidate, so
// the caller's own failure is reported instead of an anonymous native
// abort. (This test used to expect NATIVE_EXCEPTION, which dropped it.)
expect(await pending).toEqual({ ok: false, error: { cause: "CLOSED" } });
});
it("keeps the first failure when fail() is called twice", async () => {
const stub = stubDatabase();
const pending = runIndexedDbTransaction<string, TestFailure>({
database: stub.database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (_transaction, context) => {
context.fail({ cause: "CLOSED" });
context.succeed("value");
context.fail({ cause: "BLOCKED" });
},
});
stub.transactions[0]?.onabort?.(new Event("abort"));
expect(await pending).toEqual({ ok: false, error: { cause: "CLOSED" } });
});
it("does not commit a write when fail() follows succeed()", async () => {
const { database, memory } = await seededDatabase();
const result = await runIndexedDbTransaction<string, TestFailure>({
database,
stores: ["rows"],
mode: "readwrite",
translate: recordingTranslate(),
queue: (transaction, context) => {
const store = transaction.objectStore("rows");
onIndexedDbRequest(store.put({ id: "e", rank: 5 }), context, () => {
context.succeed("written");
context.fail({ cause: "ADMISSION_REJECTED", detail: "late" });
});
},
});
expect(result).toEqual({
ok: false,
error: { cause: "ADMISSION_REJECTED", detail: "late" },
});
expect(memory.readRaw("rows", "e")).toBeUndefined();
});
});