GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(core): hold the client permit across each sqlite statement attempt · anomalyco/opencode@3e90cf2

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/core
    • src/database
      • sqlite.ts
    • test
      • sqlite-lock-retry.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/core/src/database/sqlite.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/database/sqlite.ts
+35-38Lines changed: 35 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ export const makeConnection = <Extensions extends object>(run: Run, runValues: R
9595
...extensions,
9696
})
9797

98-
// One key per client, so the gate only ever reads this client's transaction marker.
98+
// One key per client, so a gate never mistakes another client's transaction for its own.
9999
let transactionCounter = 0
100100

101101
export const makeClient = <
@@ -115,53 +115,50 @@ export const makeClient = <
115115
SqlClient.TransactionConnection,
116116
SqlClient.TransactionConnection.Service
117117
>(`@opencode/core/database/SqliteTransaction/${transactionCounter++}`)
118-
let transactionOpen = false
118+
// Body statements of our own transaction carry its service and run while
119+
// the transaction holds the semaphore, so both gates pass them through
120+
// untouched — a BUSY_SNAPSHOT there repeats until rollback and retrying
121+
// would only burn budget (see the block comment above).
119122
const gateStatement = <A>(attempt: Effect.Effect<A, SqlError>): Effect.Effect<A, SqlError> =>
120123
Effect.withFiber((fiber) => {
121124
if (Context.getOption(fiber.context, transactionService)._tag === "Some") return attempt
122-
// Only the transaction's own control statements can reach here with
123-
// the flag set. Every gated statement runs while holding the client
124-
// semaphore — both acquirers take it before handing out the
125-
// connection, and the statement executes inside their scope — and
126-
// `transactionOpen` is true exactly while a transaction holds that
127-
// semaphore. A foreign statement therefore never observes it true:
128-
// it queues on the semaphore until the transaction closes, by which
129-
// point the flag has flipped back. effect-sql runs BEGIN before it
130-
// provides the transaction service and COMMIT/ROLLBACK after that
131-
// context is withdrawn (nested savepoints run inside it, so they
132-
// arrive above with the service), so exactly those three arrive here
133-
// service-less while owning the semaphore; re-taking it there would
134-
// deadlock, so they retry in place.
135-
if (transactionOpen) return retryLockTimeout(attempt)
136-
return retryLockTimeout(Effect.andThen(acquirer, attempt))
125+
// The permit covers the attempt, not just handing out the connection:
126+
// effect-sql runs the statement after its acquirer has already
127+
// returned, so a permit dropped there would let a transaction opened
128+
// in that gap swallow the attempt. A transaction holds the semaphore
129+
// for its whole life, so this take waits out any that opened while a
130+
// previous attempt slept.
131+
return retryLockTimeout(semaphore.withPermits(1)(attempt))
137132
})
138-
const gatedConnection: SqliteConnection = {
133+
// Service-less statements on the transaction connection are exactly its
134+
// BEGIN, COMMIT and ROLLBACK: effect-sql runs BEGIN after the acquirer
135+
// returns and COMMIT/ROLLBACK after the body's service is withdrawn, all
136+
// before the transaction's scope releases the semaphore (nested
137+
// savepoints run inside the body, so they arrive above with the service).
138+
// The transaction already holds the semaphore, so re-taking it would
139+
// deadlock; they retry in place.
140+
const gateTransactionStatement = <A>(attempt: Effect.Effect<A, SqlError>): Effect.Effect<A, SqlError> =>
141+
Effect.withFiber((fiber) => {
142+
if (Context.getOption(fiber.context, transactionService)._tag === "Some") return attempt
143+
return retryLockTimeout(attempt)
144+
})
145+
const gateConnection = (
146+
gate: <A>(attempt: Effect.Effect<A, SqlError>) => Effect.Effect<A, SqlError>,
147+
): SqliteConnection => ({
139148
...connection,
140-
execute: (query, params, transformRows) => gateStatement(connection.execute(query, params, transformRows)),
141-
executeRaw: (query, params) => gateStatement(connection.executeRaw(query, params)),
142-
executeValues: (query, params) => gateStatement(connection.executeValues(query, params)),
149+
execute: (query, params, transformRows) => gate(connection.execute(query, params, transformRows)),
150+
executeRaw: (query, params) => gate(connection.executeRaw(query, params)),
151+
executeValues: (query, params) => gate(connection.executeValues(query, params)),
143152
executeUnprepared: (query, params, transformRows) =>
144-
gateStatement(connection.executeUnprepared(query, params, transformRows)),
145-
}
146-
const acquirer = semaphore.withPermits(1)(Effect.succeed(gatedConnection))
153+
gate(connection.executeUnprepared(query, params, transformRows)),
154+
})
155+
const acquirer = semaphore.withPermits(1)(Effect.succeed(gateConnection(gateStatement)))
147156
const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
148157
const fiber = Fiber.getCurrent()!
149158
const scope = Context.getUnsafe(fiber.context, Scope.Scope)
150159
return Effect.as(
151-
Effect.tap(restore(semaphore.take(1)), () => {
152-
transactionOpen = true
153-
// Flip before releasing so a plain statement racing the close is gated.
154-
return Scope.addFinalizer(
155-
scope,
156-
Effect.andThen(
157-
Effect.sync(() => {
158-
transactionOpen = false
159-
}),
160-
semaphore.release(1),
161-
),
162-
)
163-
}),
164-
gatedConnection,
160+
Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))),
161+
gateConnection(gateTransactionStatement),
165162
)
166163
})
167164
const transformRows = options.transformResultNames
Collapse file

‎packages/core/test/sqlite-lock-retry.test.ts‎

Copy file name to clipboardExpand all lines: packages/core/test/sqlite-lock-retry.test.ts
+109-2Lines changed: 109 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import { mkdtemp, rm } from "node:fs/promises"
22
import { tmpdir } from "node:os"
33
import { join } from "node:path"
4-
import { Database } from "bun:sqlite"
4+
import { Database, type SQLQueryBindings } from "bun:sqlite"
55
import { expect, test } from "bun:test"
66
import { EffectDrizzleSqlite } from "@opencode/core/database/drizzle"
7-
import { Deferred, Effect, Fiber } from "effect"
7+
import { Deferred, Effect, Fiber, Layer } from "effect"
8+
import { Reactivity } from "effect/reactivity"
89
import { sql } from "drizzle-orm"
10+
import { SqlClient } from "effect/sql"
11+
import { classifySqliteError, SqlError } from "effect/sql/SqlError"
912
import { Sqlite } from "@opencode/core/database/sqlite"
1013
import { sqliteLayer } from "@opencode/core/database/sqlite.bun"
1114

@@ -260,3 +263,107 @@ test("a retrying statement waits out a transaction opened while it sleeps", asyn
260263
expect(await readValue(filename)).toBe("after")
261264
})
262265
})
266+
267+
// A driver like the bun one except that the client's first statement
268+
// suspends until `midflight` is done — parking the fiber that reaches a
269+
// statement exactly in the gap between effect-sql's acquirer returning and
270+
// the statement running, so the test below can order that gap against
271+
// another fiber's BEGIN deterministically.
272+
const yieldingSqliteLayer = (filename: string, midflight: Deferred.Deferred<void>) =>
273+
Layer.effect(
274+
SqlClient.SqlClient,
275+
Effect.gen(function* () {
276+
const native = new Database(filename)
277+
yield* Effect.addFinalizer(() => Effect.sync(() => native.close()))
278+
let parked = false
279+
const firstStatementSuspends = <A, E>(self: Effect.Effect<A, E>): Effect.Effect<A, E> =>
280+
Effect.suspend(() => {
281+
if (parked) return self
282+
parked = true
283+
return Effect.andThen(Deferred.await(midflight), () => self)
284+
})
285+
const run = (query: string, params: ReadonlyArray<unknown> = []) =>
286+
firstStatementSuspends(
287+
Effect.try({
288+
try: () =>
289+
native.query<Record<string, unknown>, SQLQueryBindings[]>(query).all(
290+
...(params as SQLQueryBindings[]),
291+
) ?? [],
292+
catch: (cause) =>
293+
new SqlError({
294+
reason: classifySqliteError(cause, { message: "Failed to execute statement", operation: "execute" }),
295+
}),
296+
}),
297+
)
298+
const runValues = (query: string, params: ReadonlyArray<unknown> = []) =>
299+
firstStatementSuspends(
300+
Effect.try({
301+
try: () =>
302+
native.query<unknown, SQLQueryBindings[]>(query).values(...(params as SQLQueryBindings[])) ?? [],
303+
catch: (cause) =>
304+
new SqlError({
305+
reason: classifySqliteError(cause, { message: "Failed to execute statement", operation: "execute" }),
306+
}),
307+
}),
308+
)
309+
return yield* Sqlite.makeClient({}, Sqlite.makeConnection(run, runValues, {}), "~test/SqliteYielding", () => ({}))
310+
}),
311+
).pipe(Layer.provide(Reactivity.layer))
312+
313+
// Regression: the permit has to cover the statement itself, not just handing
314+
// out the connection. effect-sql runs a plain statement after its acquirer
315+
// has already returned, so with the semaphore free in that gap a transaction
316+
// opening there swallows the statement — its write joins the transaction and
317+
// rolls back with it. The driver parks the write exactly in that gap, so the
318+
// interleaving is ordered by the test, not by timing.
319+
test("a plain statement does not join a transaction that opens while it runs", async () => {
320+
await withDatabase("sqlite-midflight-", async (filename) => {
321+
await initFile(filename, (native, text) => (native as Database).run(text))
322+
323+
await Effect.runPromise(
324+
Deferred.make<void>().pipe(
325+
Effect.flatMap((midflight) =>
326+
Effect.gen(function* () {
327+
const db = yield* EffectDrizzleSqlite.makeWithDefaults()
328+
329+
// A: a plain autocommit write, parked mid-statement — past its
330+
// acquirer, before the statement executes.
331+
const writer = yield* Effect.forkChild(db.run(sql`update t set v = 'after' where id = 1`))
332+
yield* Effect.sleep("1 second")
333+
334+
// B: open a transaction while A is parked and hold it on `inside`.
335+
// With the permit released early, B opens here and A's write lands
336+
// inside it; B's rollback below would erase the write.
337+
const inside = yield* Deferred.make<void>()
338+
const transactor = yield* Effect.forkChild(
339+
db
340+
.transaction(
341+
(tx) =>
342+
Effect.gen(function* () {
343+
yield* tx.get(sql`select v from t where id = 1`)
344+
yield* Deferred.await(inside)
345+
yield* Effect.fail(new Error("rollback requested"))
346+
}),
347+
{ behavior: "deferred" },
348+
)
349+
.pipe(Effect.ignore),
350+
)
351+
yield* Effect.sleep("1 second")
352+
353+
// Let A execute, then let B finish. A's write only survives if it
354+
// ran in autocommit.
355+
yield* Deferred.succeed(midflight, undefined)
356+
yield* Effect.sleep("1 second")
357+
yield* Deferred.succeed(inside, undefined)
358+
yield* Fiber.join(transactor)
359+
yield* Fiber.join(writer)
360+
}).pipe(Effect.provide(yieldingSqliteLayer(filename, midflight))),
361+
),
362+
Effect.scoped,
363+
),
364+
)
365+
366+
// B rolled back, so the update only survives if A ran in autocommit.
367+
expect(await readValue(filename)).toBe("after")
368+
})
369+
})

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.