temporal icon indicating copy to clipboard operation
temporal copied to clipboard

SQLite plugin treats SQLITE_BUSY and other unrelated errors as duplicate-key errors

Open shinseongsu opened this issue 1 month ago • 1 comments

Expected Behavior

IsDupEntryError in the SQLite plugin should return true only for duplicate keys (primary key / unique constraint violations), the same as the MySQL and PostgreSQL plugins. Other errors, such as "database is locked", should be returned to the caller as errors.

Actual Behavior

It returns true for many unrelated errors, so callers treat real failures as "the row already exists".

The check in common/persistence/sql/sqlplugin/sqlite/driver.go is a bitwise AND against three OR'ed codes:

sqlConstraintCodes = sqlite3.SQLITE_CONSTRAINT | sqlite3.SQLITE_CONSTRAINT_PRIMARYKEY | sqlite3.SQLITE_CONSTRAINT_UNIQUE // 19 | 1555 | 2067 = 0xE13
...
return sqlErr.Code()&sqlConstraintCodes != 0

modernc returns extended result codes, so any code that shares a bit with 0xE13 matches. That covers SQLITE_ERROR (1), SQLITE_BUSY (5), SQLITE_LOCKED (6), SQLITE_IOERR (10), SQLITE_FULL (13) and NOT NULL violations (1299), among others.

What this looks like from the store side:

  • PutReplicationTaskToDLQ (execution_tasks.go:608) ignores duplicates on purpose. When the database is locked, it returns nil and the replication task is never written to the DLQ.
  • CreateQueue (queue_v2.go:203) returns queue already exists. service/history/queues/dlq_writer.go then ignores that error.
  • createExecution, AppendHistoryNodes and CreateNamespace return "already running", "condition failed" and "namespace already exists" errors instead of the real one.
  • task_queues.go, task_user_data.go, nexus_endpoint_store.go and shard.go use the same check.

SQLITE_BUSY happens in file mode when another connection holds the write lock (e.g. MaxConns > 1, or a second process on the same file), since busy_timeout defaults to 0.

Steps to Reproduce the Problem

1. Call IsDupEntryError on real driver errors

Put this in common/persistence/sql/sqlplugin/sqlite/ and run go test ./common/persistence/sql/sqlplugin/sqlite/ -run TestReproIsDupEntryError -v:

func TestReproIsDupEntryError(t *testing.T) {
	dsn := "file:" + filepath.Join(t.TempDir(), "t.db")
	conn, _ := sqlx.Connect(goSQLDriverName, dsn)
	defer conn.Close()
	conn.MustExec(`CREATE TABLE t (id INTEGER PRIMARY KEY, nn TEXT NOT NULL)`)
	conn.MustExec(`INSERT INTO t VALUES (1, 'x')`)

	_, dupErr := conn.Exec(`INSERT INTO t VALUES (1, 'x')`)
	_, notNullErr := conn.Exec(`INSERT INTO t (id) VALUES (2)`)
	_, noTableErr := conn.Exec(`SELECT * FROM missing`)

	// Another connection holds the write lock.
	other, _ := sqlx.Connect(goSQLDriverName, dsn)
	defer other.Close()
	lock, _ := other.Conn(context.Background())
	lock.ExecContext(context.Background(), "BEGIN IMMEDIATE")
	_, busyErr := conn.Exec(`INSERT INTO t VALUES (3, 'x')`)
	lock.ExecContext(context.Background(), "ROLLBACK")

	d := &db{}
	for _, err := range []error{dupErr, notNullErr, noTableErr, busyErr} {
		t.Logf("IsDupEntryError=%-5v  %v", d.IsDupEntryError(err), err)
	}
}

Output on main:

IsDupEntryError=true   constraint failed: UNIQUE constraint failed: t.id (1555)
IsDupEntryError=true   constraint failed: NOT NULL constraint failed: t.nn (1299)
IsDupEntryError=true   SQL logic error: no such table: missing (1)
IsDupEntryError=true   database is locked (5) (SQLITE_BUSY)

Only the first line should be true.

2. Same thing through the store

Create the SQLite DB in file mode through the plugin, hold the write lock from a second connection with BEGIN IMMEDIATE, then call the store:

err = store.PutReplicationTaskToDLQ(ctx, &persistence.PutReplicationTaskToDLQRequest{
	ShardID:           1,
	SourceClusterName: "remote",
	TaskInfo:          &persistencespb.ReplicationTaskInfo{TaskId: 42},
})
// main: err == nil, but nothing was written

_, err = queue.CreateQueue(ctx, &persistence.InternalCreateQueueRequest{
	QueueType: persistence.QueueTypeHistoryDLQ,
	QueueName: "q",
})
// main: "queue already exists: queue type 2 and name q", but the queue was never created

Possible fix

Compare the exact extended codes:

switch sqlErr.Code() {
case sqlite3.SQLITE_CONSTRAINT_PRIMARYKEY, sqlite3.SQLITE_CONSTRAINT_UNIQUE:
	return true
}
return false

With this change, the test above prints:

IsDupEntryError=true   constraint failed: UNIQUE constraint failed: t.id (1555)
IsDupEntryError=false  constraint failed: NOT NULL constraint failed: t.nn (1299)
IsDupEntryError=false  SQL logic error: no such table: missing (1)
IsDupEntryError=false  database is locked (5) (SQLITE_BUSY)

Both store calls return the database is locked error, and go test ./common/persistence/tests/ -run SQLite still passes (966 subtests, including the *_Fail_Duplicate cases).

I have this change and a regression test ready, and I'm happy to open a PR if this looks right.

Specifications

  • Version: main (7726647d6)
  • Platform: SQLite plugin (modernc.org/sqlite), macOS arm64, Go 1.27.3

shinseongsu avatar Oct 30 '26 12:10 shinseongsu

I'll pick this up. Plan is to check the actual constraint codes (SQLITE_CONSTRAINT_PRIMARYKEY / SQLITE_CONSTRAINT_UNIQUE) with equality instead of the bitmask, plus a test with real driver errors like your repro.

cestercian avatar Nov 01 '26 15:11 cestercian