This is an automated email from the ASF dual-hosted git repository.
laskoviymishka pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-go.git
The following commit(s) were added to refs/heads/main by this push:
new 4df39aac2 fix(catalog/sql): take the SQLite write lock before reading
in write transactions (#2589)
4df39aac2 is described below
commit 4df39aac2ae03c2eca966be6384520ed419f150c
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Tue Nov 17 16:54:10 2026 +0100
fix(catalog/sql): take the SQLite write lock before reading in write
transactions (#2589)
---
catalog/sql/drop_namespace_internal_test.go | 346 +++++++++++++++++-----------
catalog/sql/sql.go | 205 ++++++++++++++--
catalog/sql/sql_test.go | 128 +++++++++-
catalog/sql/update_view_test.go | 11 +-
catalog/sql/write_lock_internal_test.go | 269 +++++++++++++++++++++
5 files changed, 806 insertions(+), 153 deletions(-)
diff --git a/catalog/sql/drop_namespace_internal_test.go
b/catalog/sql/drop_namespace_internal_test.go
index ce3a3137f..f4b885eb2 100644
--- a/catalog/sql/drop_namespace_internal_test.go
+++ b/catalog/sql/drop_namespace_internal_test.go
@@ -21,6 +21,7 @@ import (
"context"
dbsql "database/sql"
"errors"
+ "fmt"
"net/url"
"path/filepath"
"strings"
@@ -49,45 +50,77 @@ const (
updatePropertiesOperation namespaceRaceOperation = "update-properties"
)
-type namespaceRaceHook struct {
- dropAtDelete chan struct{}
- createAtInsert chan struct{}
- updateAtInsert chan struct{}
- releaseDrop chan struct{}
- dropDone chan struct{}
- releaseUpdate chan struct{}
- dropAtDeleteOnce sync.Once
- createAtInsertOnce sync.Once
- updateAtInsertOnce sync.Once
+// racePause stops one operation, tagged on its context, at the first statement
+// match accepts. It closes reached there and, unless release is nil, waits for
+// release before the statement runs.
+type racePause struct {
+ operation namespaceRaceOperation
+ match func(*bun.QueryEvent) bool
+ reached chan struct{}
+ release chan struct{}
+ once sync.Once
}
+func newRacePause(operation namespaceRaceOperation, match
func(*bun.QueryEvent) bool, blocking bool) *racePause {
+ p := &racePause{operation: operation, match: match, reached: make(chan
struct{})}
+ if blocking {
+ p.release = make(chan struct{})
+ }
+
+ return p
+}
+
+func (p *racePause) await(t *testing.T, what string) {
+ t.Helper()
+ select {
+ case <-p.reached:
+ case <-time.After(5 * time.Second):
+ t.Fatalf("%s did not reach its pause point", what)
+ }
+}
+
+func isWriteLock(event *bun.QueryEvent) bool {
+ return event.Operation() == "UPDATE" && strings.Contains(event.Query,
"catalog_name = catalog_name")
+}
+
+func isNamespaceDelete(event *bun.QueryEvent) bool {
+ return event.Operation() == "DELETE" && strings.Contains(event.Query,
"iceberg_namespace_properties")
+}
+
+func isObjectInsert(event *bun.QueryEvent) bool {
+ return event.Operation() == "INSERT" && strings.Contains(event.Query,
"iceberg_tables")
+}
+
+func isPropertiesInsert(event *bun.QueryEvent) bool {
+ return event.Operation() == "INSERT" && strings.Contains(event.Query,
"iceberg_namespace_properties")
+}
+
+type namespaceRaceHook struct{ pauses []*racePause }
+
func (h *namespaceRaceHook) BeforeQuery(ctx context.Context, event
*bun.QueryEvent) context.Context {
operation, _ :=
ctx.Value(namespaceRaceContextKey{}).(namespaceRaceOperation)
- query := event.Query
-
- switch {
- case operation == dropNamespaceOperation && event.Operation() ==
"DELETE" && strings.Contains(query, "iceberg_namespace_properties"):
- h.dropAtDeleteOnce.Do(func() { close(h.dropAtDelete) })
- <-h.releaseDrop
- case operation == createObjectOperation && event.Operation() ==
"INSERT" && strings.Contains(query, "iceberg_tables"):
- h.createAtInsertOnce.Do(func() { close(h.createAtInsert) })
- <-h.releaseDrop
- <-h.dropDone
- case operation == updatePropertiesOperation && event.Operation() ==
"INSERT" && strings.Contains(query, "iceberg_namespace_properties"):
- h.updateAtInsertOnce.Do(func() { close(h.updateAtInsert) })
- <-h.releaseUpdate
+ for _, p := range h.pauses {
+ if p.operation == operation && p.match(event) {
+ p.once.Do(func() {
+ close(p.reached)
+ if p.release != nil {
+ <-p.release
+ }
+ })
+ }
}
return ctx
}
-
func (*namespaceRaceHook) AfterQuery(context.Context, *bun.QueryEvent) {}
func newNamespaceRaceCatalog(t *testing.T) *Catalog {
t.Helper()
+ // The busy timeout makes a writer that finds the lock held wait for
it, on
+ // both drivers sqliteshim selects, instead of each driver's own
default.
dbPath := filepath.Join(t.TempDir(), "catalog.db")
- db, err := dbsql.Open(sqliteshim.ShimName, dbPath)
+ db, err := dbsql.Open(sqliteshim.ShimName, dbPath+"?_busy_timeout=5000")
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, db.Close()) })
db.SetMaxOpenConns(4)
@@ -185,6 +218,8 @@ func TestRetryableSerializableError(t *testing.T) {
}
require.False(t, isRetryableSerializableError(errors.New("constraint
violation")))
+ require.False(t, isRetryableSerializableError(fmt.Errorf("create: %w",
&sqliteLockWaitError{err: errors.New("database is locked")})),
+ "a lock SQLite already waited busy_timeout for must not be
retried")
}
func TestRetryableSerializableErrorFromSQLiteDriver(t *testing.T) {
@@ -216,11 +251,14 @@ func TestRetryableSerializableErrorFromSQLiteDriver(t
*testing.T) {
require.True(t, isRetryableSerializableError(lockErr), "unexpected
SQLite lock error type %T: %v", lockErr, lockErr)
}
+// TestDropNamespaceDoesNotRaceWithObjectCreation pins that DropNamespace and
an object
+// create serialize on SQLite's write lock, in either order, and never leave
an object
+// without its namespace.
func TestDropNamespaceDoesNotRaceWithObjectCreation(t *testing.T) {
schema := iceberg.NewSchema(1, iceberg.NestedField{
ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64,
Required: true,
})
- tests := []struct {
+ creates := []struct {
name string
create func(*testing.T, context.Context, *Catalog,
table.Identifier) error
exists func(context.Context, *Catalog, table.Identifier) (bool,
error)
@@ -261,131 +299,181 @@ func TestDropNamespaceDoesNotRaceWithObjectCreation(t
*testing.T) {
},
}
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- cat := newNamespaceRaceCatalog(t)
- namespace := table.Identifier{"race_namespace"}
- objectID := table.Identifier{"race_namespace",
"race_object"}
- require.NoError(t,
cat.CreateNamespace(context.Background(), namespace, nil))
-
- hook := &namespaceRaceHook{
- dropAtDelete: make(chan struct{}),
- createAtInsert: make(chan struct{}),
- releaseDrop: make(chan struct{}),
- dropDone: make(chan struct{}),
- }
- cat.db = cat.db.WithQueryHook(hook)
+ dropCtx := context.WithValue(context.Background(),
namespaceRaceContextKey{}, dropNamespaceOperation)
+ createCtx := context.WithValue(context.Background(),
namespaceRaceContextKey{}, createObjectOperation)
+ namespace := table.Identifier{"race_namespace"}
+ objectID := table.Identifier{"race_namespace", "race_object"}
- released := false
- defer func() {
- if !released {
- close(hook.releaseDrop)
+ for _, tt := range creates {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Run("create waits for drop", func(t *testing.T) {
+ cat := newNamespaceRaceCatalog(t)
+ require.NoError(t,
cat.CreateNamespace(context.Background(), namespace, nil))
+
+ // The drop pauses holding the write lock; the
create reaches its own
+ // lock statement and waits behind it.
+ dropPause :=
newRacePause(dropNamespaceOperation, isNamespaceDelete, true)
+ createPause :=
newRacePause(createObjectOperation, isWriteLock, false)
+ cat.db =
cat.db.WithQueryHook(&namespaceRaceHook{pauses: []*racePause{dropPause,
createPause}})
+ defer func() {
+ select {
+ case <-dropPause.release:
+ default:
+ close(dropPause.release)
+ }
+ }()
+
+ dropErrCh := make(chan error, 1)
+ go func() { dropErrCh <-
cat.DropNamespace(dropCtx, namespace) }()
+ dropPause.await(t, "drop")
+
+ createErrCh := make(chan error, 1)
+ go func() { createErrCh <- tt.create(t,
createCtx, cat, objectID) }()
+ createPause.await(t, "create")
+
+ close(dropPause.release)
+ require.NoError(t, <-dropErrCh)
+ require.ErrorIs(t, <-createErrCh,
catalog.ErrNoSuchNamespace)
+
+ objectExists, err :=
tt.exists(context.Background(), cat, objectID)
+ require.NoError(t, err)
+ require.False(t, objectExists)
+ namespaceExists, err :=
cat.CheckNamespaceExists(context.Background(), namespace)
+ require.NoError(t, err)
+ require.False(t, namespaceExists)
+ })
+
+ t.Run("drop waits for create", func(t *testing.T) {
+ cat := newNamespaceRaceCatalog(t)
+ require.NoError(t,
cat.CreateNamespace(context.Background(), namespace, nil))
+
+ // The create pauses at its insert holding the
write lock; the drop
+ // cannot finish until the create commits, and
then finds the object.
+ createPause :=
newRacePause(createObjectOperation, isObjectInsert, true)
+ cat.db =
cat.db.WithQueryHook(&namespaceRaceHook{pauses: []*racePause{createPause}})
+ defer func() {
+ select {
+ case <-createPause.release:
+ default:
+ close(createPause.release)
+ }
+ }()
+
+ createErrCh := make(chan error, 1)
+ go func() { createErrCh <- tt.create(t,
createCtx, cat, objectID) }()
+ createPause.await(t, "create")
+
+ dropErrCh := make(chan error, 1)
+ go func() { dropErrCh <-
cat.DropNamespace(dropCtx, namespace) }()
+ select {
+ case err := <-dropErrCh:
+ t.Fatalf("drop finished while the
create held the write lock: %v", err)
+ case <-time.After(100 * time.Millisecond):
}
- }()
-
- dropCtx := context.WithValue(context.Background(),
namespaceRaceContextKey{}, dropNamespaceOperation)
- createCtx := context.WithValue(context.Background(),
namespaceRaceContextKey{}, createObjectOperation)
- dropErrCh := make(chan error, 1)
- createErrCh := make(chan error, 1)
-
- go func() {
- dropErr := cat.DropNamespace(dropCtx, namespace)
- close(hook.dropDone)
- dropErrCh <- dropErr
- }()
- select {
- case <-hook.dropAtDelete:
- case <-time.After(5 * time.Second):
- t.Fatal("drop did not reach namespace deletion")
- }
-
- go func() { createErrCh <- tt.create(t, createCtx, cat,
objectID) }()
- select {
- case <-hook.createAtInsert:
- case <-time.After(5 * time.Second):
- t.Fatal("creator did not reach catalog
insertion")
- }
-
- close(hook.releaseDrop)
- released = true
- dropErr := <-dropErrCh
- createErr := <-createErrCh
- require.False(t, dropErr == nil && createErr == nil,
"drop and create must not both report success")
- objectExists, err := tt.exists(context.Background(),
cat, objectID)
- require.NoError(t, err)
- namespaceExists, err :=
cat.CheckNamespaceExists(context.Background(), namespace)
- require.NoError(t, err)
+ close(createPause.release)
+ require.NoError(t, <-createErrCh)
+ require.ErrorIs(t, <-dropErrCh,
catalog.ErrNamespaceNotEmpty)
- switch {
- case createErr == nil:
- require.Error(t, dropErr)
+ objectExists, err :=
tt.exists(context.Background(), cat, objectID)
+ require.NoError(t, err)
require.True(t, objectExists)
+ namespaceExists, err :=
cat.CheckNamespaceExists(context.Background(), namespace)
+ require.NoError(t, err)
require.True(t, namespaceExists)
- case dropErr == nil:
- require.False(t, objectExists)
- require.False(t, namespaceExists)
- default:
- require.Equal(t, namespaceExists, objectExists,
- "failed operations must not leave an
object without its namespace")
- }
+ })
})
}
}
+// TestDropNamespaceDoesNotRaceWithUpdateNamespaceProperties pins that
DropNamespace and
+// UpdateNamespaceProperties serialize on SQLite's write lock, in either
order, and leave
+// no properties behind for a dropped namespace.
func TestDropNamespaceDoesNotRaceWithUpdateNamespaceProperties(t *testing.T) {
- cat := newNamespaceRaceCatalog(t)
+ dropCtx := context.WithValue(context.Background(),
namespaceRaceContextKey{}, dropNamespaceOperation)
+ updateCtx := context.WithValue(context.Background(),
namespaceRaceContextKey{}, updatePropertiesOperation)
namespace := table.Identifier{"race_namespace"}
- require.NoError(t, cat.CreateNamespace(context.Background(), namespace,
iceberg.Properties{"owner": "before"}))
- hook := &namespaceRaceHook{
- updateAtInsert: make(chan struct{}),
- releaseUpdate: make(chan struct{}),
- }
- cat.db = cat.db.WithQueryHook(hook)
-
- released := false
- defer func() {
- if !released {
- close(hook.releaseUpdate)
- }
- }()
+ propertyRows := func(t *testing.T, cat *Catalog) int64 {
+ t.Helper()
+ n, err :=
cat.db.NewSelect().Model((*sqlIcebergNamespaceProps)(nil)).
+ Where("catalog_name = ?", cat.name).
+ Where("namespace = ?", strings.Join(namespace, ".")).
+ Count(context.Background())
+ require.NoError(t, err)
- updateCtx := context.WithValue(context.Background(),
namespaceRaceContextKey{}, updatePropertiesOperation)
- updateErrCh := make(chan error, 1)
- go func() {
+ return n
+ }
+ update := func(cat *Catalog) error {
_, err := cat.UpdateNamespaceProperties(updateCtx, namespace,
nil, iceberg.Properties{"owner": "after"})
- updateErrCh <- err
- }()
- select {
- case <-hook.updateAtInsert:
- case <-time.After(5 * time.Second):
- t.Fatal("property update did not reach namespace property
insertion")
+ return err
}
- dropErrCh := make(chan error, 1)
- go func() { dropErrCh <- cat.DropNamespace(context.Background(),
namespace) }()
- select {
- case err := <-dropErrCh:
+ t.Run("update waits for drop", func(t *testing.T) {
+ cat := newNamespaceRaceCatalog(t)
+ require.NoError(t, cat.CreateNamespace(context.Background(),
namespace, iceberg.Properties{"owner": "before"}))
+
+ updatePause := newRacePause(updatePropertiesOperation,
isWriteLock, true)
+ cat.db = cat.db.WithQueryHook(&namespaceRaceHook{pauses:
[]*racePause{updatePause}})
+ defer func() {
+ select {
+ case <-updatePause.release:
+ default:
+ close(updatePause.release)
+ }
+ }()
+
+ updateErrCh := make(chan error, 1)
+ go func() { updateErrCh <- update(cat) }()
+ updatePause.await(t, "property update")
+
+ require.NoError(t, cat.DropNamespace(dropCtx, namespace))
+
+ close(updatePause.release)
+ require.ErrorIs(t, <-updateErrCh, catalog.ErrNoSuchNamespace)
+
+ exists, err := cat.CheckNamespaceExists(context.Background(),
namespace)
require.NoError(t, err)
- case <-time.After(5 * time.Second):
- t.Fatal("namespace drop did not complete while property update
was paused")
- }
+ require.False(t, exists)
+ require.Zero(t, propertyRows(t, cat))
+ })
- close(hook.releaseUpdate)
- released = true
+ t.Run("drop waits for update", func(t *testing.T) {
+ cat := newNamespaceRaceCatalog(t)
+ require.NoError(t, cat.CreateNamespace(context.Background(),
namespace, iceberg.Properties{"owner": "before"}))
- select {
- case err := <-updateErrCh:
- require.ErrorIs(t, err, catalog.ErrNoSuchNamespace)
- case <-time.After(5 * time.Second):
- t.Fatal("property update did not finish after namespace drop")
- }
+ updatePause := newRacePause(updatePropertiesOperation,
isPropertiesInsert, true)
+ cat.db = cat.db.WithQueryHook(&namespaceRaceHook{pauses:
[]*racePause{updatePause}})
+ defer func() {
+ select {
+ case <-updatePause.release:
+ default:
+ close(updatePause.release)
+ }
+ }()
+
+ updateErrCh := make(chan error, 1)
+ go func() { updateErrCh <- update(cat) }()
+ updatePause.await(t, "property update")
+
+ dropErrCh := make(chan error, 1)
+ go func() { dropErrCh <- cat.DropNamespace(dropCtx, namespace)
}()
+ select {
+ case err := <-dropErrCh:
+ t.Fatalf("drop finished while the property update held
the write lock: %v", err)
+ case <-time.After(100 * time.Millisecond):
+ }
- exists, err := cat.CheckNamespaceExists(context.Background(), namespace)
- require.NoError(t, err)
- require.False(t, exists)
+ close(updatePause.release)
+ require.NoError(t, <-updateErrCh)
+ require.NoError(t, <-dropErrCh)
+
+ exists, err := cat.CheckNamespaceExists(context.Background(),
namespace)
+ require.NoError(t, err)
+ require.False(t, exists)
+ require.Zero(t, propertyRows(t, cat))
+ })
}
func createTestView(ctx context.Context, cat *Catalog, identifier
table.Identifier, schema *iceberg.Schema, representation view.Representation,
props iceberg.Properties) error {
diff --git a/catalog/sql/sql.go b/catalog/sql/sql.go
index e3cd9ba91..ba868bfe4 100644
--- a/catalog/sql/sql.go
+++ b/catalog/sql/sql.go
@@ -20,6 +20,7 @@ package sql
import (
"context"
"database/sql"
+ "database/sql/driver"
"encoding/json"
"errors"
"fmt"
@@ -300,18 +301,184 @@ func withReadTx[R any](ctx context.Context, db *bun.DB,
fn func(context.Context,
}
func withWriteTx(ctx context.Context, db *bun.DB, fn func(context.Context,
bun.Tx) error) error {
- return db.RunInTx(ctx, &sql.TxOptions{Isolation: sql.LevelDefault},
func(ctx context.Context, tx bun.Tx) error {
+ return runWriteTx(ctx, db, &sql.TxOptions{Isolation: sql.LevelDefault},
fn)
+}
+
+// runWriteTx runs fn in a write transaction. On SQLite it runs on a dedicated
pooled
+// connection whose busy_timeout it caps to ctx's deadline for the transaction
and then
+// restores, and it takes the write lock before fn reads anything.
+func runWriteTx(ctx context.Context, db *bun.DB, opts *sql.TxOptions, fn
func(context.Context, bun.Tx) error) error {
+ if db.Dialect().Name() != dialect.SQLite {
+ return db.RunInTx(ctx, opts, fn)
+ }
+
+ conn, err := db.Conn(ctx)
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+
+ capped, restore, err := capSQLiteBusyTimeout(ctx, conn)
+ if err != nil {
+ return err
+ }
+ defer restore()
+
+ return conn.RunInTx(ctx, opts, func(ctx context.Context, tx bun.Tx)
error {
+ if err := lockSQLiteForWrite(ctx, tx, capped); err != nil {
+ return err
+ }
+
return fn(ctx, tx)
})
}
+// lockSQLiteForWrite takes SQLite's write lock as the transaction's first
statement.
+//
+// database/sql begins SQLite transactions as DEFERRED, so a write transaction
that
+// reads first holds a read snapshot when its first write asks for the write
lock.
+// SQLite does not consult the busy handler for that upgrade: it returns
SQLITE_BUSY
+// at once, whatever busy_timeout the connection sets. A write that matches no
rows,
+// issued before any read, requests the lock from no transaction, which is the
one case
+// where SQLite waits on the busy handler. Writers then queue on busy_timeout
instead of
+// failing fast, and the reads that follow see the latest committed state.
+//
+// The statement takes the lock even when the transaction goes on to return a
sentinel
+// without writing, such as an identifier that already exists, so those paths
wait for
+// a concurrent writer too.
+//
+// capped reports that busy_timeout was lowered to ctx's deadline, so a lock
timeout
+// means the deadline ended the wait even if ctx has not yet noticed:
busy_timeout is
+// whole milliseconds and can run out just before the deadline does.
+func lockSQLiteForWrite(ctx context.Context, tx bun.Tx, capped bool) error {
+ // The statement writes no rows; issuing it takes the write lock.
+ _, err := tx.NewUpdate().Model((*sqlIcebergTable)(nil)).
+ Set("catalog_name = catalog_name").Where("0").Exec(ctx)
+
+ return classifySQLiteLockError(ctx, err, capped, func() int64 {
+ // Read only now, so an uncontended transaction does not pay
for it. A
+ // failed read counts as no busy_timeout, which keeps the error
retryable.
+ var busyTimeout int64
+ _ = tx.QueryRowContext(ctx, "PRAGMA
busy_timeout").Scan(&busyTimeout)
+
+ return busyTimeout
+ })
+}
+
+// classifySQLiteLockError turns the lock statement's error into what the
+// transaction should do. busyTimeout returns the connection's busy_timeout in
+// milliseconds and is called only for a lock SQLite may have waited on.
+func classifySQLiteLockError(ctx context.Context, err error, capped bool,
busyTimeout func() int64) error {
+ switch {
+ case err == nil:
+ return nil
+ case ctx.Err() != nil, capped && isSQLiteBusyError(err):
+ // mattn reports a lock timeout here even when ctx's deadline
ended the
+ // wait; keep the context error so callers can match it.
+ cause := context.Cause(ctx)
+ if cause == nil {
+ cause = context.DeadlineExceeded
+ }
+
+ return fmt.Errorf("failed to acquire sqlite write lock: %w",
errors.Join(cause, err))
+ case isSQLiteReadOnlyError(err):
+ // Nothing can be written, so there is no lock to take and no
upgrade to
+ // protect. Carry on without it: reads still return the catalog
sentinels,
+ // such as an identifier that already exists, and a real write
fails with
+ // the driver's own read-only error.
+ return nil
+ case isSQLiteBusyError(err) && busyTimeout() > 0:
+ return &sqliteLockWaitError{err: err}
+ default:
+ // This includes a shared-cache table lock, which SQLite
reports at once
+ // without consulting the busy handler;
isRetryableSerializableError
+ // retries it.
+ return fmt.Errorf("failed to acquire sqlite write lock: %w",
err)
+ }
+}
+
+// capSQLiteBusyTimeout lowers conn's busy_timeout to the time remaining when
ctx
+// has a deadline that comes sooner, and reports whether it did. Neither driver
+// interrupts the busy handler when ctx ends, so without the cap a deadline
would
+// wait out the full busy_timeout. A cancellation without a deadline still
does.
+// restore puts the connection's own busy_timeout back, or discards the
connection
+// if it cannot, since the pragma would otherwise outlive this call in the
pool.
+func capSQLiteBusyTimeout(ctx context.Context, conn bun.Conn) (bool, func(),
error) {
+ noRestore := func() {}
+ deadline, ok := ctx.Deadline()
+ if !ok {
+ return false, noRestore, nil
+ }
+
+ var busyTimeout int64
+ if err := conn.QueryRowContext(ctx, "PRAGMA
busy_timeout").Scan(&busyTimeout); err != nil {
+ return false, noRestore, fmt.Errorf("failed to read sqlite
busy_timeout: %w", err)
+ }
+ if busyTimeout <= 0 {
+ return false, noRestore, nil
+ }
+ remaining := time.Until(deadline).Milliseconds()
+ if remaining <= 0 {
+ return false, noRestore, fmt.Errorf("failed to acquire sqlite
write lock: %w", context.DeadlineExceeded)
+ }
+ if remaining >= busyTimeout {
+ return false, noRestore, nil
+ }
+
+ if _, err := conn.ExecContext(ctx, fmt.Sprintf("PRAGMA busy_timeout =
%d", remaining)); err != nil {
+ return false, noRestore, fmt.Errorf("failed to cap sqlite
busy_timeout: %w", err)
+ }
+ restore := func() {
+ query := fmt.Sprintf("PRAGMA busy_timeout = %d", busyTimeout)
+ if _, err := conn.ExecContext(context.WithoutCancel(ctx),
query); err != nil {
+ _ = conn.Raw(func(any) error { return driver.ErrBadConn
})
+ }
+ }
+
+ return true, restore, nil
+}
+
+// sqliteshim selects different SQLite drivers by build target; their typed
error
+// APIs are incompatible, but both expose the stable messages matched below.
+
+// isSQLiteLockError reports a lock conflict of either kind.
+func isSQLiteLockError(err error) bool {
+ return isSQLiteBusyError(err) || strings.Contains(err.Error(),
"database table is locked")
+}
+
+// isSQLiteBusyError reports SQLITE_BUSY, the lock another connection holds on
the
+// database file and the only one the busy handler waits on. SQLITE_LOCKED, a
+// shared-cache table lock ("database table is locked"), is not one.
+func isSQLiteBusyError(err error) bool {
+ return strings.Contains(err.Error(), "database is locked")
+}
+
+// isSQLiteReadOnlyError reports SQLITE_READONLY: a read-only file, a mode=ro
+// DSN or PRAGMA query_only.
+func isSQLiteReadOnlyError(err error) bool {
+ return strings.Contains(err.Error(), "readonly database")
+}
+
+// sqliteLockWaitError reports a write lock SQLite did not grant within the
+// connection's busy_timeout. SQLite has already waited, so
retrySerializableWriteTx
+// returns it as is: retrying would multiply busy_timeout by the attempt count.
+type sqliteLockWaitError struct{ err error }
+
+func (e *sqliteLockWaitError) Error() string {
+ return "failed to acquire sqlite write lock within busy_timeout: " +
e.err.Error()
+}
+
+func (e *sqliteLockWaitError) Unwrap() error { return e.err }
+
const (
// The retry budget has to outlast a competing writer's transaction,
not just a
- // scheduling hiccup. SQLite serializes writers and reports a lock
conflict on
- // upgrade immediately, without consulting the busy handler, so a losing
- // CreateTable/CreateView only observes the catalog-level conflict it
should
- // report once the winner commits. At 3 attempts the budget was 30ms,
which a
- // loaded machine exceeds, surfacing SQLITE_BUSY instead of
+ // scheduling hiccup. On SQLite it applies only when the connection's
busy_timeout
+ // is 0, as with modernc's default: lockSQLiteForWrite then fails at
once on a held
+ // lock, and a losing CreateTable/CreateView observes the catalog-level
conflict it
+ // should report only once the winner commits. With a busy_timeout,
including
+ // mattn's 5000ms default, SQLite waits on the lock itself and a
timeout is not
+ // retried. At 3 attempts the budget was 30ms,
+ // which a loaded machine exceeds, surfacing SQLITE_BUSY instead of
// ErrTableAlreadyExists/ErrViewAlreadyExists.
//
// Attempts fire at 0/10/30/70/150/310ms (delay doubles per attempt),
so the
@@ -325,9 +492,7 @@ const (
func withSerializableWriteTx(ctx context.Context, db *bun.DB, fn
func(context.Context, bun.Tx) error) error {
return retrySerializableWriteTx(ctx, func() error {
- return db.RunInTx(ctx, &sql.TxOptions{Isolation:
sql.LevelSerializable}, func(ctx context.Context, tx bun.Tx) error {
- return fn(ctx, tx)
- })
+ return runWriteTx(ctx, db, &sql.TxOptions{Isolation:
sql.LevelSerializable}, fn)
})
}
@@ -356,6 +521,10 @@ func retrySerializableWriteTx(ctx context.Context, run
func() error) error {
}
func isRetryableSerializableError(err error) bool {
+ if _, ok := errors.AsType[*sqliteLockWaitError](err); ok {
+ return false
+ }
+
var stateErr interface{ SQLState() string }
if errors.As(err, &stateErr) {
switch stateErr.SQLState() {
@@ -373,10 +542,7 @@ func isRetryableSerializableError(err error) bool {
msg := err.Error()
- // sqliteshim selects different SQLite drivers by build target. Their
typed
- // error APIs are incompatible, but both expose these stable lock
messages.
- return strings.Contains(msg, "database is locked") ||
- strings.Contains(msg, "database table is locked") ||
+ return isSQLiteLockError(err) ||
strings.Contains(msg, "ORA-08177") ||
strings.Contains(msg, "ORA-00060")
}
@@ -421,7 +587,12 @@ func (c *Catalog) isV0() bool { return c.schemaVersion ==
schemaV0 }
// of catalog changes.
//
// SQLite callers that allow concurrent writers should configure WAL and a
busy timeout in the driver DSN so the
-// settings apply to every pooled connection. NewCatalog does not mutate
connection settings on the caller-owned db.
+// settings apply to every pooled connection, for example
"?_busy_timeout=5000", which both drivers sqliteshim
+// selects accept. Write transactions take SQLite's write lock before they
read, so concurrent writers queue for up
+// to the busy timeout, or until the context's deadline if that is sooner,
instead of failing with SQLITE_BUSY.
+// The driver's default applies when the DSN sets none: mattn waits 5000ms,
while modernc does not wait, so
+// CreateTable, CreateView and the other operations that retry on a lock
conflict give up after about 310ms and the
+// rest fail at once. NewCatalog does not mutate connection settings on the
caller-owned db.
func NewCatalog(name string, db *sql.DB, dialect SupportedDialect, props
iceberg.Properties) (*Catalog, error) {
d, err := getDialect(dialect)
if err != nil {
@@ -913,11 +1084,11 @@ func (c *Catalog) CommitTable(ctx context.Context, ident
table.Identifier, reqs
return nil, "", err
}
- runWriteTx := withWriteTx
+ commitTx := withWriteTx
if current == nil {
- runWriteTx = withSerializableWriteTx
+ commitTx = withSerializableWriteTx
}
- err = runWriteTx(ctx, c.db, func(ctx context.Context, tx bun.Tx) error {
+ err = commitTx(ctx, c.db, func(ctx context.Context, tx bun.Tx) error {
if current != nil {
// On V1, the model-driven UPDATE emits every non-PK
field, writing
// iceberg_type=TABLE; this also heals legacy NULLs on
commit, and the
diff --git a/catalog/sql/sql_test.go b/catalog/sql/sql_test.go
index 5ff6ed591..0a8550a3b 100644
--- a/catalog/sql/sql_test.go
+++ b/catalog/sql/sql_test.go
@@ -31,6 +31,7 @@ import (
"os"
"path/filepath"
"slices"
+ "strconv"
"strings"
"sync"
"sync/atomic"
@@ -177,12 +178,16 @@ func (s *SqliteCatalogTestSuite) SetupTest() {
// catalogUri returns the file-backed SQLite DSN the whole suite shares, with a
// busy timeout on every pooled connection; mattn and modernc both read
-// _busy_timeout. The timeout applies where SQLite consults the busy handler: a
-// lock requested before the transaction has read anything. A transaction that
-// reads first and then writes fails with SQLITE_BUSY at once, whatever the
-// timeout.
+// _busy_timeout. Catalog write transactions take the write lock before they
+// read, so a contended writer waits up to the timeout.
func (s *SqliteCatalogTestSuite) catalogUri() string {
- return "file://" + filepath.Join(s.warehouse, "sql-catalog.db") +
"?_busy_timeout=5000"
+ return s.catalogURIWithBusyTimeout(5 * time.Second)
+}
+
+// catalogURIWithBusyTimeout returns the suite's DSN with another busy timeout.
+func (s *SqliteCatalogTestSuite) catalogURIWithBusyTimeout(timeout
time.Duration) string {
+ return "file://" + filepath.Join(s.warehouse, "sql-catalog.db") +
+ "?_busy_timeout=" + strconv.FormatInt(timeout.Milliseconds(),
10)
}
func (s *SqliteCatalogTestSuite) confirmNoTables(db *sql.DB) {
@@ -3780,6 +3785,119 @@ func (s *SqliteCatalogTestSuite)
TestConcurrentTableViewCollisionUnderLockConten
}
}
+// TestCreateWaitsOnBusyTimeoutWhileWriteLockHeld pins that SQLite write
transactions
+// queue on the DSN's busy_timeout. A write transaction that reads before it
writes
+// cannot wait for the write lock: SQLite skips the busy handler for that
upgrade and
+// returns SQLITE_BUSY at once. The lock is held for longer than the whole
lock-retry
+// budget in retrySerializableWriteTx, so only a create that waits on
busy_timeout can
+// succeed.
+func (s *SqliteCatalogTestSuite)
TestCreateWaitsOnBusyTimeoutWhileWriteLockHeld() {
+ const holdWriteLockFor = 500 * time.Millisecond
+
+ tests := []struct {
+ name string
+ create func(context.Context, *sqlcat.Catalog, table.Identifier)
error
+ }{
+ {
+ name: "table",
+ create: func(ctx context.Context, cat *sqlcat.Catalog,
identifier table.Identifier) error {
+ _, err := cat.CreateTable(ctx, identifier,
tableSchemaNested)
+
+ return err
+ },
+ },
+ {
+ name: "view",
+ create: func(ctx context.Context, cat *sqlcat.Catalog,
identifier table.Identifier) error {
+ return createTestView(ctx, cat, identifier,
tableSchemaNested, view.Representation{SQL: "SELECT 1", Dialect: "spark"}, nil)
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ s.Run(tt.name, func() {
+ ctx := context.Background()
+ sqlDB := s.getDB()
+ _, err := sqlDB.Exec("PRAGMA journal_mode=WAL")
+ s.Require().NoError(err)
+ _, err = sqlDB.Exec("CREATE TABLE IF NOT EXISTS
lock_holder(x)")
+ s.Require().NoError(err)
+ s.Require().NoError(sqlDB.Close())
+
+ cat, err := catalog.Load(ctx, "default",
iceberg.Properties{
+ "uri":
s.catalogURIWithBusyTimeout(5 * time.Second),
+ sqlcat.DriverKey: sqliteshim.ShimName,
+ sqlcat.DialectKey: string(sqlcat.SQLite),
+ "type": "sql",
+ "warehouse": "file://" + s.warehouse,
+ })
+ s.Require().NoError(err)
+ db := cat.(*sqlcat.Catalog)
+ identifier := s.randomTableIdentifier()
+ s.Require().NoError(db.CreateNamespace(ctx,
catalog.NamespaceFromIdent(identifier), nil))
+
+ holder := s.getDB()
+ tx, err := holder.BeginTx(ctx, nil)
+ s.Require().NoError(err)
+ _, err = tx.ExecContext(ctx, "INSERT INTO lock_holder
VALUES (1)")
+ s.Require().NoError(err)
+
+ released := make(chan struct{})
+ time.AfterFunc(holdWriteLockFor, func() {
+ _ = tx.Rollback()
+ _ = holder.Close()
+ close(released)
+ })
+
+ s.Require().NoError(tt.create(ctx, db, identifier))
+ <-released
+ })
+ }
+}
+
+// TestCreateFailsAfterOneBusyTimeoutWhileWriteLockHeld pins that a write lock
SQLite
+// did not grant within busy_timeout is returned, not retried: retrying would
wait
+// busy_timeout once per attempt in retrySerializableWriteTx.
+func (s *SqliteCatalogTestSuite)
TestCreateFailsAfterOneBusyTimeoutWhileWriteLockHeld() {
+ const busyTimeout = 500 * time.Millisecond
+
+ ctx := context.Background()
+ sqlDB := s.getDB()
+ _, err := sqlDB.Exec("PRAGMA journal_mode=WAL")
+ s.Require().NoError(err)
+ _, err = sqlDB.Exec("CREATE TABLE IF NOT EXISTS lock_holder(x)")
+ s.Require().NoError(err)
+ s.Require().NoError(sqlDB.Close())
+
+ cat, err := catalog.Load(ctx, "default", iceberg.Properties{
+ "uri": s.catalogURIWithBusyTimeout(busyTimeout),
+ sqlcat.DriverKey: sqliteshim.ShimName,
+ sqlcat.DialectKey: string(sqlcat.SQLite),
+ "type": "sql",
+ "warehouse": "file://" + s.warehouse,
+ })
+ s.Require().NoError(err)
+ db := cat.(*sqlcat.Catalog)
+ identifier := s.randomTableIdentifier()
+ s.Require().NoError(db.CreateNamespace(ctx,
catalog.NamespaceFromIdent(identifier), nil))
+
+ holder := s.getDB()
+ defer holder.Close()
+ tx, err := holder.BeginTx(ctx, nil)
+ s.Require().NoError(err)
+ defer func() { _ = tx.Rollback() }()
+ _, err = tx.ExecContext(ctx, "INSERT INTO lock_holder VALUES (1)")
+ s.Require().NoError(err)
+
+ start := time.Now()
+ _, err = db.CreateTable(ctx, identifier, tableSchemaNested)
+ elapsed := time.Since(start)
+
+ s.Require().ErrorContains(err, "within busy_timeout")
+ // One wait is busy_timeout; a retried one would be six of them plus
backoff.
+ s.Less(elapsed, 3*busyTimeout, "create waited %v", elapsed)
+}
+
func (s *SqliteCatalogTestSuite)
TestCreateRemovesMetadataIfCatalogInsertFails() {
ctx := context.Background()
db := s.getCatalogSqlite()
diff --git a/catalog/sql/update_view_test.go b/catalog/sql/update_view_test.go
index 006104c22..294284088 100644
--- a/catalog/sql/update_view_test.go
+++ b/catalog/sql/update_view_test.go
@@ -22,6 +22,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync"
"testing"
"time"
@@ -162,15 +163,21 @@ func TestUpdateViewRetentionAndMetadataLocation(t
*testing.T) {
type viewUpdateContextKey struct{}
+// viewUpdateHook pauses the loser at its first iceberg_tables UPDATE, which
on SQLite
+// is the write-lock statement, so the winner commits before the loser takes
the lock
+// and the loser's compare-and-swap then finds the metadata location moved.
type viewUpdateHook struct {
staged chan struct{}
release chan struct{}
+ once sync.Once
}
func (h *viewUpdateHook) BeforeQuery(ctx context.Context, event
*bun.QueryEvent) context.Context {
if ctx.Value(viewUpdateContextKey{}) == true && event.Operation() ==
"UPDATE" && strings.Contains(event.Query, "iceberg_tables") {
- close(h.staged)
- <-h.release
+ h.once.Do(func() {
+ close(h.staged)
+ <-h.release
+ })
}
return ctx
diff --git a/catalog/sql/write_lock_internal_test.go
b/catalog/sql/write_lock_internal_test.go
new file mode 100644
index 000000000..1e44db4f3
--- /dev/null
+++ b/catalog/sql/write_lock_internal_test.go
@@ -0,0 +1,269 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package sql
+
+import (
+ "context"
+ dbsql "database/sql"
+ "errors"
+ "path/filepath"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/apache/iceberg-go"
+ "github.com/apache/iceberg-go/catalog"
+ "github.com/apache/iceberg-go/table"
+ "github.com/stretchr/testify/require"
+ "github.com/uptrace/bun"
+ "github.com/uptrace/bun/driver/sqliteshim"
+)
+
+// newWriteLockCatalog returns a catalog on a single pooled connection with
the given
+// busy_timeout, so a test can read back that connection's pragma.
+func newWriteLockCatalog(t *testing.T, busyTimeout time.Duration) (*Catalog,
string) {
+ t.Helper()
+
+ dbPath := filepath.Join(t.TempDir(), "catalog.db")
+ db, err := dbsql.Open(sqliteshim.ShimName,
dbPath+"?_busy_timeout="+strconv.FormatInt(busyTimeout.Milliseconds(), 10))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, db.Close()) })
+ db.SetMaxOpenConns(1)
+ _, err = db.Exec("PRAGMA journal_mode=WAL")
+ require.NoError(t, err)
+
+ cat, err := NewCatalog("default", db, SQLite, iceberg.Properties{
+ "warehouse": "file://" +
filepath.ToSlash(filepath.Join(t.TempDir(), "warehouse")),
+ })
+ require.NoError(t, err)
+
+ return cat, dbPath
+}
+
+// holdWriteLock takes the database's write lock from a second connection
until the
+// test ends.
+func holdWriteLock(t *testing.T, dbPath string) {
+ t.Helper()
+
+ holder, err := dbsql.Open(sqliteshim.ShimName, dbPath)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = holder.Close() })
+ _, err = holder.Exec("CREATE TABLE IF NOT EXISTS lock_holder(x)")
+ require.NoError(t, err)
+ tx, err := holder.Begin()
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = tx.Rollback() })
+ _, err = tx.Exec("INSERT INTO lock_holder VALUES (1)")
+ require.NoError(t, err)
+}
+
+func TestLockSQLiteForWrite(t *testing.T) {
+ const busyTimeout = 3 * time.Second
+
+ tests := []struct {
+ name string
+ setup func(*testing.T, *Catalog, string) (context.Context,
context.CancelFunc)
+ check func(*testing.T, error, time.Duration)
+ }{
+ {
+ name: "deadline caps the busy wait",
+ setup: func(t *testing.T, _ *Catalog, dbPath string)
(context.Context, context.CancelFunc) {
+ holdWriteLock(t, dbPath)
+
+ return
context.WithTimeout(context.Background(), 200*time.Millisecond)
+ },
+ check: func(t *testing.T, err error, elapsed
time.Duration) {
+ require.ErrorIs(t, err,
context.DeadlineExceeded)
+ require.Less(t, elapsed, busyTimeout/2, "waited
%v", elapsed)
+ },
+ },
+ {
+ name: "expired deadline does not wait",
+ setup: func(t *testing.T, _ *Catalog, dbPath string)
(context.Context, context.CancelFunc) {
+ holdWriteLock(t, dbPath)
+
+ return
context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
+ },
+ check: func(t *testing.T, err error, elapsed
time.Duration) {
+ require.ErrorIs(t, err,
context.DeadlineExceeded)
+ require.Less(t, elapsed, busyTimeout/2, "waited
%v", elapsed)
+ },
+ },
+ {
+ name: "non-lock error is not a lock wait",
+ setup: func(t *testing.T, cat *Catalog, _ string)
(context.Context, context.CancelFunc) {
+ _, err := cat.db.Exec("DROP TABLE
iceberg_tables")
+ require.NoError(t, err)
+
+ return context.WithCancel(context.Background())
+ },
+ check: func(t *testing.T, err error, _ time.Duration) {
+ require.ErrorContains(t, err, "no such table")
+ _, isLockWait :=
errors.AsType[*sqliteLockWaitError](err)
+ require.False(t, isLockWait)
+ require.False(t,
isRetryableSerializableError(err))
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ cat, dbPath := newWriteLockCatalog(t, busyTimeout)
+ ctx, cancel := tt.setup(t, cat, dbPath)
+ defer cancel()
+
+ start := time.Now()
+ err := withWriteTx(ctx, cat.db, func(context.Context,
bun.Tx) error { return nil })
+ tt.check(t, err, time.Since(start))
+
+ // The single pooled connection keeps the busy_timeout
it was opened with.
+ var restored int64
+ require.NoError(t, cat.db.QueryRow("PRAGMA
busy_timeout").Scan(&restored))
+ require.Equal(t, busyTimeout.Milliseconds(), restored)
+ })
+ }
+}
+
+func TestClassifySQLiteLockError(t *testing.T) {
+ var (
+ busy = errors.New("database is locked (5) (SQLITE_BUSY)")
+ tableLocked = errors.New("database table is locked (6)
(SQLITE_LOCKED)")
+ readOnly = errors.New("attempt to write a readonly database
(8)")
+ )
+ timeout := func(ms int64) func() int64 { return func() int64 { return
ms } }
+ unread := func() int64 {
+ t.Error("busy_timeout must be read only for a lock SQLite may
have waited on")
+
+ return 0
+ }
+
+ t.Run("no error reads nothing", func(t *testing.T) {
+ require.NoError(t, classifySQLiteLockError(t.Context(), nil,
false, unread))
+ })
+
+ t.Run("busy after a busy_timeout is a lock wait and not retried",
func(t *testing.T) {
+ err := classifySQLiteLockError(t.Context(), busy, false,
timeout(5000))
+ _, isLockWait := errors.AsType[*sqliteLockWaitError](err)
+ require.True(t, isLockWait)
+ require.False(t, isRetryableSerializableError(err))
+ })
+
+ t.Run("busy without a busy_timeout is retried", func(t *testing.T) {
+ err := classifySQLiteLockError(t.Context(), busy, false,
timeout(0))
+ require.ErrorIs(t, err, busy)
+ require.True(t, isRetryableSerializableError(err))
+ })
+
+ // SQLite reports a shared-cache table lock at once, without the busy
+ // handler, so no busy_timeout or deadline was waited out.
+ t.Run("shared-cache table lock is retried", func(t *testing.T) {
+ for _, capped := range []bool{false, true} {
+ err := classifySQLiteLockError(t.Context(),
tableLocked, capped, unread)
+ require.ErrorIs(t, err, tableLocked)
+ require.NotErrorIs(t, err, context.DeadlineExceeded)
+ require.True(t, isRetryableSerializableError(err))
+ }
+ })
+
+ t.Run("busy under a capped busy_timeout is the deadline", func(t
*testing.T) {
+ err := classifySQLiteLockError(t.Context(), busy, true, unread)
+ require.ErrorIs(t, err, context.DeadlineExceeded)
+ })
+
+ t.Run("read-only database carries on without the lock", func(t
*testing.T) {
+ require.NoError(t, classifySQLiteLockError(t.Context(),
readOnly, false, unread))
+ })
+}
+
+// A shared-cache connection gets SQLITE_LOCKED for a table another connection
of
+// the same cache is writing. modernc waits for that lock through
unlock_notify,
+// so only mattn reports it.
+func TestWriteRetriesSharedCacheTableLock(t *testing.T) {
+ if sqliteshim.DriverName() != "sqlite3" {
+ t.Skipf("driver %s waits for a shared-cache table lock itself",
sqliteshim.DriverName())
+ }
+
+ dsn := "file:" + filepath.Join(t.TempDir(), "catalog.db") +
"?cache=shared&_busy_timeout=5000"
+ db, err := dbsql.Open(sqliteshim.ShimName, dsn)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = db.Close() })
+ cat, err := NewCatalog("default", db, SQLite, iceberg.Properties{
+ "warehouse": "file://" +
filepath.ToSlash(filepath.Join(t.TempDir(), "warehouse")),
+ })
+ require.NoError(t, err)
+ ns := table.Identifier{"ns"}
+ require.NoError(t, cat.CreateNamespace(t.Context(), ns, nil))
+
+ holder, err := dbsql.Open(sqliteshim.ShimName, dsn)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = holder.Close() })
+ tx, err := holder.Begin()
+ require.NoError(t, err)
+ _, err = tx.Exec("UPDATE iceberg_tables SET catalog_name =
catalog_name")
+ require.NoError(t, err)
+ released := make(chan error, 1)
+ time.AfterFunc(100*time.Millisecond, func() { released <- tx.Commit() })
+
+ // DropNamespace opens with its write transaction, so the lock
statement is
+ // what meets the table lock.
+ require.NoError(t, cat.DropNamespace(t.Context(), ns))
+ require.NoError(t, <-released)
+}
+
+// On a database that cannot be written, the lock statement fails before the
+// transaction reads anything. The reads must still run and return the catalog
+// sentinels they returned before the lock statement existed.
+func TestReadOnlyDatabaseKeepsCatalogSentinels(t *testing.T) {
+ ctx := t.Context()
+ dbPath := filepath.Join(t.TempDir(), "catalog.db")
+ props := iceberg.Properties{
+ "warehouse": "file://" +
filepath.ToSlash(filepath.Join(t.TempDir(), "warehouse")),
+ }
+ ns := table.Identifier{"ns"}
+ tbl := table.Identifier{"ns", "tbl"}
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int32,
Required: true,
+ })
+
+ rw, err := dbsql.Open(sqliteshim.ShimName, dbPath)
+ require.NoError(t, err)
+ writable, err := NewCatalog("default", rw, SQLite, props)
+ require.NoError(t, err)
+ require.NoError(t, writable.CreateNamespace(ctx, ns, nil))
+ _, err = writable.CreateTable(ctx, tbl, schema)
+ require.NoError(t, err)
+ require.NoError(t, rw.Close())
+
+ ro, err := dbsql.Open(sqliteshim.ShimName, "file:"+dbPath+"?mode=ro")
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = ro.Close() })
+ props[initCatalogTablesKey] = "false"
+ cat, err := NewCatalog("default", ro, SQLite, props)
+ require.NoError(t, err)
+
+ require.ErrorIs(t, cat.CreateNamespace(ctx, ns, nil),
catalog.ErrNamespaceAlreadyExists)
+ _, err = cat.CreateTable(ctx, tbl, schema)
+ require.ErrorIs(t, err, catalog.ErrTableAlreadyExists)
+ require.ErrorIs(t, cat.DropNamespace(ctx, table.Identifier{"missing"}),
catalog.ErrNoSuchNamespace)
+
+ // A real write still fails, with the driver's read-only error.
+ err = cat.CreateNamespace(ctx, table.Identifier{"other"}, nil)
+ require.ErrorContains(t, err, "readonly database")
+ _, isLockWait := errors.AsType[*sqliteLockWaitError](err)
+ require.False(t, isLockWait)
+}