TypeScript
perf(shared): SQLite reads stop queueing behind each other, up to 5x faster under load (#27097)
Julius Marmingefacaa08b36c5
diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.tsindex 99eb8b37a21..ac786993fa0 100644--- a/packages/shared/src/nodeSqliteClient.test.ts+++ b/packages/shared/src/nodeSqliteClient.test.ts@@ -238,6 +238,27 @@ it.effect("lets the writer commit while a read-only transaction is open", () =>),);+it.effect("serves another read while a read-only transaction is open", () =>+ withReaderClient((sql) =>+ Effect.gen(function* () {+ const opened = yield* Deferred.make<void>();+ const other = yield* Effect.forkChild(+ Deferred.await(opened).pipe(Effect.andThen(countEntries(sql).pipe(SqliteClient.readOnly))),+ );+ yield* sql+ .withTransaction(+ Effect.gen(function* () {+ yield* countEntries(sql);+ yield* Deferred.succeed(opened, undefined);+ // One shared reader would make this join wait on the transaction forever.+ assert.equal(yield* Fiber.join(other), 1);+ }),+ )+ .pipe(SqliteClient.readOnly);+ }),+ ),+);+// regression: #19226 read-only transactions run on the separate reader connectionit.effect("rejects a write in a read-only transaction", () =>withReaderClient((sql) =>@@ -333,6 +354,25 @@ it.effect("uses the writer when the reader cannot open the database", () =>assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);assert.equal(yield* sql.withTransaction(countEntries(sql)).pipe(SqliteClient.readOnly), 1);++ // A read beside an open read transaction must not start a worker on the next slot.+ const held = yield* Deferred.make<void>();+ const release = yield* Deferred.make<void>();+ const holder = yield* sql+ .withTransaction(+ countEntries(sql).pipe(+ Effect.andThen(Deferred.succeed(held, undefined)),+ Effect.andThen(Deferred.await(release)),+ ),+ )+ .pipe(SqliteClient.readOnly, Effect.forkChild);+ yield* Deferred.await(held);+ const other = yield* countEntries(sql).pipe(SqliteClient.readOnly, (effect) =>+ Effect.forkChild(effect, { startImmediately: true }),+ );+ yield* Deferred.succeed(release, undefined);+ yield* Fiber.join(holder);+ assert.equal(yield* Fiber.join(other), 1);assert.equal(startedWorkers.length, startedBefore + 1);}),),diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.tsindex a42943c065a..c0edfdb868d 100644--- a/packages/shared/src/nodeSqliteClient.ts+++ b/packages/shared/src/nodeSqliteClient.ts@@ -293,8 +293,14 @@ const failed = (cause: unknown, message: string, operation: string) =>// Read-transaction cleanup succeeds after worker exit because it can no longer change anything.const endsReadTransaction = (sql: string) => /^\s*ROLLBACK\b|^\s*COMMIT\b/i.test(sql);+// WAL readers run concurrently; one worker serialized every read behind the slowest transaction.+const READER_POOL_SIZE = 4;+// Bind transactions to one worker; fail after its exit instead of resuming outside the transaction on a replacement.-const makeReader = Effect.fnUntraced(function* (options: SqliteClientConfig) {+const makeReader = Effect.fnUntraced(function* (+ options: SqliteClientConfig,+ pool: { unavailable: boolean },+) {let current:| {readonly worker: NodeWorkerThreads.Worker;@@ -302,7 +308,6 @@ const makeReader = Effect.fnUntraced(function* (options: SqliteClientConfig) {readonly started: Promise<ReaderStartup>;}| undefined;- let unavailable = false;let nextRequestId = 0;const start = () => {@@ -439,8 +444,8 @@ const makeReader = Effect.fnUntraced(function* (options: SqliteClientConfig) {void reader.worker.terminate();}// @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.- if (unavailable) return Effect.succeed(undefined);- unavailable = true;+ if (pool.unavailable) return Effect.succeed(undefined);+ pool.unavailable = true;return Effect.logWarning("SQLite reader worker unavailable; reads use the main connection", {reason,}).pipe(Effect.as(undefined));@@ -448,7 +453,7 @@ const makeReader = Effect.fnUntraced(function* (options: SqliteClientConfig) {return Effect.suspend((): Effect.Effect<Connection | undefined> => {// @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.- if (unavailable) return Effect.succeed(undefined);+ if (pool.unavailable) return Effect.succeed(undefined);let reader: NonNullable<typeof current>;try {reader = current ?? start();@@ -467,7 +472,7 @@ const makeReader = Effect.fnUntraced(function* (options: SqliteClientConfig) {}),(startup): Effect.Effect<Connection | undefined> =>// A late ready event must not hand out a worker retired by another acquire timeout.- unavailable || current !== reader+ pool.unavailable || current !== reader? // @effect-diagnostics-next-line effectSucceedWithVoid:off - The connection result distinguishes undefined from void.Effect.succeed(undefined): Option.isSome(startup) && startup.value.type === "ready"@@ -1073,21 +1078,48 @@ const make = Effect.fn("makeWithDatabase")(function* (const semaphore = yield* Semaphore.make(1);const connection = yield* makeConnection;- const acquireReader =- options.readerWorker && isFileDatabase ? yield* makeReader(options) : undefined;- const readerSemaphore = yield* Semaphore.make(1);+ // A reader that cannot start turns off the whole pool, so routing never picks a dead slot.+ const readerPool = { unavailable: false };+ const readers =+ options.readerWorker && isFileDatabase+ ? yield* Effect.forEach(Array.from({ length: READER_POOL_SIZE }), () =>+ Effect.map(+ Effect.all([makeReader(options, readerPool), Semaphore.make(1)]),+ ([acquire, lock]) => ({+ acquire,+ lock,+ claims: 0,+ }),+ ),+ )+ : [];const writer = { name: "writer" as const, lock: semaphore, connection };let activeWriter: ConnectionOwner | undefined;- const route = Effect.withFiber((fiber) =>- acquireReader !== undefined && Context.get(fiber.context, ReadOnly)- ? Effect.map(acquireReader, (readerConnection) =>+ // Callers must run route uninterruptibly and pass `claimed` a finalizer that runs `release` once.+ const route = (claimed: (release: Effect.Effect<void>) => Effect.Effect<void>) =>+ Effect.withFiber((fiber) => {+ if (readers.length === 0 || readerPool.unavailable || !Context.get(fiber.context, ReadOnly)) {+ return Effect.succeed(writer);+ }+ // Least claimed wins and ties go to the lowest slot, so idle slots never start a worker.+ let slot = readers[0]!;+ for (const candidate of readers) if (candidate.claims < slot.claims) slot = candidate;+ slot.claims++;+ const reader = slot;+ return Effect.andThen(+ claimed(+ Effect.sync(() => {+ reader.claims--;+ }),+ ),+ Effect.map(reader.acquire, (readerConnection) =>readerConnection === undefined? writer- : { name: "reader" as const, lock: readerSemaphore, connection: readerConnection },- )- : Effect.succeed(writer),- );+ : { name: "reader" as const, lock: reader.lock, connection: readerConnection },+ ),+ );+ });const acquired = (target: { readonly name: Acquired["connection"] },@@ -1101,88 +1133,110 @@ const make = Effect.fn("makeWithDatabase")(function* (const writerBorrowBatchSize = 16;let writerBorrowsSinceYield = 0;const borrower: Borrower = (use) =>- Effect.flatMap(route, (target) =>- Effect.withFiber((fiber) => {- const clock = fiber.getRef(Clock.Clock);- const start = clock.monotonicTimeNanosUnsafe();- const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;- const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;- const useConnection = Effect.suspend(() => {- if (target.name === "writer") activeWriter = owner;- if (- fiber.getRef(References.TracerEnabled) &&- fiber.getRef(Statement.SpanPropagationEnabled)- ) {- annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);- }- return use(target.connection);- });- const useOwnedConnection =- target.name === "writer"- ? Effect.onExit(useConnection, () =>- Effect.sync(() => {- if (activeWriter === owner) activeWriter = undefined;- }),- )- : useConnection;- if (!options.checkpointWorker || target.name !== "writer") {- return target.lock.withPermits(1)(useOwnedConnection);- }- const writerUse = Effect.onExit(useOwnedConnection, (exit) =>- Effect.sync(() => {- writerBorrowsSinceYield = Exit.hasInterrupts(exit)- ? 0- : Math.min(writerBorrowsSinceYield + 1, writerBorrowBatchSize);- }),- );- return Effect.flatMap(target.lock.withPermitsIfAvailable(1)(writerUse), (result) =>- Option.isSome(result)- ? Effect.succeed(result.value)- : target.lock.withPermits(1)(- Effect.andThen(- // Failed SQL also consumes the batch; cancellation hands off immediately.- Effect.suspend(() => {- if (writerBorrowsSinceYield < writerBorrowBatchSize) return Effect.void;- writerBorrowsSinceYield = 0;- return Effect.callback<void>((resume) => {- const immediate = setImmediate(() => resume(Effect.void));- return Effect.sync(() => clearImmediate(immediate));- });- }),- writerUse,- ),- ),- );- }),- );- const transactionAcquirer = Effect.flatMap(route, (target) =>Effect.uninterruptibleMask((restore) => {- const fiber = Fiber.getCurrent()!;- const scope = Context.getUnsafe(fiber.context, Scope.Scope);+ let release: Effect.Effect<void> = Effect.void;+ const claimed = (next: Effect.Effect<void>) =>+ Effect.sync(() => {+ release = next;+ });+ return Effect.flatMap(route(claimed), (target) => restore(borrowTarget(target, use))).pipe(+ Effect.ensuring(Effect.suspend(() => release)),+ );+ });+ const borrowTarget = <A, E, R>(+ target: {+ readonly name: Acquired["connection"];+ readonly lock: Semaphore.Semaphore;+ readonly connection: Connection;+ },+ use: (connection: Connection) => Effect.Effect<A, E, R>,+ ): Effect.Effect<A, E, R> =>+ Effect.withFiber((fiber) => {const clock = fiber.getRef(Clock.Clock);const start = clock.monotonicTimeNanosUnsafe();- const pending = fiber.getRef(TransactionAcquire);const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;- const acquire = Effect.tap((pending?.restore ?? restore)(target.lock.take(1)), () => {+ const useConnection = Effect.suspend(() => {if (target.name === "writer") activeWriter = owner;- if (pending !== undefined) {- pending.acquired = acquired(target, clock, start);- pending.ownerAtWaitStart = ownerAtWaitStart;+ if (+ fiber.getRef(References.TracerEnabled) &&+ fiber.getRef(Statement.SpanPropagationEnabled)+ ) {+ annotateAcquired(fiber, acquired(target, clock, start), ownerAtWaitStart);}- return Scope.addFinalizer(- scope,- Effect.sync(() => {- if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;- }).pipe(Effect.andThen(target.lock.release(1))),- );+ return use(target.connection);});- return Effect.as(- // A scheduler yield after taking the permit must not precede its release finalizer.- Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),- target.connection,+ const useOwnedConnection =+ target.name === "writer"+ ? Effect.onExit(useConnection, () =>+ Effect.sync(() => {+ if (activeWriter === owner) activeWriter = undefined;+ }),+ )+ : useConnection;+ if (!options.checkpointWorker || target.name !== "writer") {+ return target.lock.withPermits(1)(useOwnedConnection);+ }+ const writerUse = Effect.onExit(useOwnedConnection, (exit) =>+ Effect.sync(() => {+ writerBorrowsSinceYield = Exit.hasInterrupts(exit)+ ? 0+ : Math.min(writerBorrowsSinceYield + 1, writerBorrowBatchSize);+ }),);- }),+ return Effect.flatMap(target.lock.withPermitsIfAvailable(1)(writerUse), (result) =>+ Option.isSome(result)+ ? Effect.succeed(result.value)+ : target.lock.withPermits(1)(+ Effect.andThen(+ // Failed SQL also consumes the batch; cancellation hands off immediately.+ Effect.suspend(() => {+ if (writerBorrowsSinceYield < writerBorrowBatchSize) return Effect.void;+ writerBorrowsSinceYield = 0;+ return Effect.callback<void>((resume) => {+ const immediate = setImmediate(() => resume(Effect.void));+ return Effect.sync(() => clearImmediate(immediate));+ });+ }),+ writerUse,+ ),+ ),+ );+ });+ const claimedUntilScopeCloses = (release: Effect.Effect<void>) =>+ Effect.withFiber((fiber) =>+ Scope.addFinalizer(Context.getUnsafe(fiber.context, Scope.Scope), release),+ );+ const transactionAcquirer = Effect.uninterruptible(route(claimedUntilScopeCloses)).pipe(+ Effect.flatMap((target) =>+ Effect.uninterruptibleMask((restore) => {+ const fiber = Fiber.getCurrent()!;+ const scope = Context.getUnsafe(fiber.context, Scope.Scope);+ const clock = fiber.getRef(Clock.Clock);+ const start = clock.monotonicTimeNanosUnsafe();+ const pending = fiber.getRef(TransactionAcquire);+ const ownerAtWaitStart = target.name === "writer" ? activeWriter : undefined;+ const owner = target.name === "writer" ? connectionOwner(fiber) : undefined;+ const acquire = Effect.tap((pending?.restore ?? restore)(target.lock.take(1)), () => {+ if (target.name === "writer") activeWriter = owner;+ if (pending !== undefined) {+ pending.acquired = acquired(target, clock, start);+ pending.ownerAtWaitStart = ownerAtWaitStart;+ }+ return Scope.addFinalizer(+ scope,+ Effect.sync(() => {+ if (target.name === "writer" && activeWriter === owner) activeWriter = undefined;+ }).pipe(Effect.andThen(target.lock.release(1))),+ );+ });+ return Effect.as(+ // A scheduler yield after taking the permit must not precede its release finalizer.+ Effect.provideService(acquire, Scheduler.PreventSchedulerYield, true),+ target.connection,+ );+ }),+ ),);const client = yield* Client.make({