Hello, and thank you for SQLCipher. We hit a rare first-use race and think we have traced it to a known SQLite initialization issue. Details below.
Versions: SQLCipher 4.19.0 (SQLite 3.53.4, libtomcrypt 1.18.2 provider), bundled by the Rust crates rusqlite 0.41.0 / libsqlite3-sys 0.39.1 (sqlcipher-src 419.0.6). Linux x86_64, default threading mode (serialized).
What happens: a process starts several threads. Each one opens its own new database file and sets a valid 32-byte raw key (PRAGMA key = "x'…'") before the library has been used anywhere else in the process. Sometimes one or more threads get:
An error occurred with PRAGMA key or rekey. PRAGMA key requires a key of one or more characters. …
The key is not empty. A retry on the same thread succeeds. It failed safely for us: nothing was written.
How often: rarely by chance. We saw it once in a test suite (4 threads failed together) and 0 times in 720 repeat runs. It is reliable with a debugger:
- Start 4 threads. Put a breakpoint on
sqlcipher_extra_init(gdb non-stop mode) so the first thread to call it waits there. - Let the other threads continue. Each thread opens a new file, sets the key and runs
CREATE TABLE t(x). - The other three threads failed with the error above in 5 of 5 runs.
- With the same breakpoint, opening and closing one
:memory:connection on the main thread before starting the others gave 0 failures in 5 of 5 runs.
Cause (from the 4.19.0 amalgamation): sqlite3_initialize() sets sqlite3GlobalConfig.isInit = 1, releases pInitMutex, and only then calls SQLITE_EXTRA_INIT(0). Meanwhile any other thread’s sqlite3_initialize() takes the if( sqlite3GlobalConfig.isInit ) return SQLITE_OK; fast path and goes on to key a database while sqlcipher_extra_init is still running. SQLCipher requires this hook (#error "SQLCipher must be compiled with -DSQLITE_EXTRA_INIT=sqlcipher_extra_init ..."), so every build has the window. The same race in the generic hook was raised on the SQLite forum in February 2025 (SQLite User Forum: SQLITE_EXTRA_INIT mutex), and SQLite added SQLITE_EXTRA_INIT_MUTEXED, which is called under the init mutex before isInit is set. It is already present in the 4.19.0 amalgamation. Would using SQLITE_EXTRA_INIT_MUTEXED=sqlcipher_extra_init be the right fix? (Today the #error above refuses a build without SQLITE_EXTRA_INIT, so this would need a source change, not only a flag.) We have not checked whether that is safe for sqlcipher_extra_init (it allocates its own mutexes and runs under the recursive init mutex), so we leave that to you.
Workaround we use: one process-wide once-guard that opens and closes a :memory: connection before any database is keyed.
Happy to test a fix. A minimal Rust reproduction (about 40 lines, synthetic data) and the gdb script are available on request.