Skip to content

SqlClient: a withTransaction waiting for the connection cannot be interrupted #9514

Closed

Description

@rogierpennink

What version of Effect is running?

  • [email protected] and @effect/[email protected] on Bun 1.4.3 (macOS, arm64), unmodified published packages.
  • makeWithTransaction is unchanged on main at 7f823c1.
  • First seen on 4.0.0-rc.112; also present in rc.117.

What steps can reproduce the bug?

Fiber A holds the connection in a transaction for 1 s. Fiber B calls withTransaction and queues behind it. Interrupting B does not complete until A lets go of the connection. A queued plain statement, by contrast, can be interrupted at once.

// repro.ts - bun repro.ts
import { SqliteClient } from "@effect/sql-sqlite-bun"
import { Effect, Fiber } from "effect"
import * as SqlClient from "effect/sql/SqlClient"
import { mkdtempSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"

const dir = mkdtempSync(join(tmpdir(), "effect-txn-"))

const program = Effect.gen(function*() {
  const sql = yield* SqlClient.SqlClient
  yield* sql`CREATE TABLE t (id INTEGER PRIMARY KEY)`

  // A holds the connection inside a transaction for one second.
  const holder = yield* Effect.forkChild(sql.withTransaction(Effect.sleep("1 second")))
  yield* Effect.sleep("50 millis")

  // B queues behind A for the connection.
  const queuedTransaction = yield* Effect.forkChild(sql.withTransaction(sql`INSERT INTO t DEFAULT VALUES`))
  const queuedRead = yield* Effect.forkChild(sql`SELECT 1`)
  yield* Effect.sleep("50 millis")

  const time = (fiber: Fiber.Fiber<unknown, unknown>) =>
    Effect.gen(function*() {
      const start = Date.now()
      yield* Fiber.interrupt(fiber)
      return Date.now() - start
    })

  console.log(`interrupting a queued plain statement took ${yield* time(queuedRead)} ms`)
  console.log(`interrupting a queued transaction took ${yield* time(queuedTransaction)} ms`)
  yield* Fiber.join(holder)
})

await Effect.runPromise(
  program.pipe(Effect.provide(SqliteClient.layer({ filename: join(dir, "repro.db") })))
)
rmSync(dir, { recursive: true, force: true })

What is the expected behavior?

Interrupting a fiber that is waiting for the transaction connection completes at once, as it does for a plain statement. The transaction never starts.

What do you see instead?

interrupting a queued plain statement took 1 ms
interrupting a queued transaction took 899 ms

The interrupt completes only once the holder releases the connection. B then gets the connection and is interrupted before BEGIN (no row is inserted), so no data is wrong. But the caller waits for as long as the current transaction runs.

In practice: an HTTP handler whose client disconnects while its transaction is queued keeps its fiber alive until the connection frees up. The same goes for a Effect.timeout around a transaction: the timeout fires late.

Additional information

The cause is in makeWithTransaction (L525-L539). The whole transaction runs inside Effect.uninterruptibleMask((restore) => ...), and restore is applied only to the user's effect (restore(effect)). options.acquireConnection runs unrestored, so it runs uninterruptibly.

The SQLite acquirer's lease (L427-L433) does try to make its wait interruptible, with restore(semaphore.take(1)). But its restore belongs to its own uninterruptibleMask, and it restores to the interruptibility around that mask. Inside makeWithTransaction, the surrounding state is already uninterruptible, so the wait stays uninterruptible.

A possible fix is to run the acquisition with the outer restore, while keeping the scope in the uninterruptible region, so an interrupt can never strand a taken connection. A sketch, not tested:

// in makeWithTransaction: give acquireConnection the caller's restore
readonly acquireConnection: (
  restore: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
) => Effect.Effect<readonly [Scope.Closeable | undefined, S], SqlError>

// in make: the scope is created and closed outside restore, and only the
// acquirer's wait is interruptible
acquireConnection: (restore) =>
  Effect.flatMap(Scope.make(), (scope) =>
    restore(Scope.provide(transactionAcquirer!, scope)).pipe(
      Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))),
      Effect.map((conn) => [scope, conn] as const)
    ))

Our workaround is a one-permit semaphore in front of the writer, taken with the caller's own interruptibility before withTransaction is called. That way the connection is always free when acquireConnection runs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions