Repository navigation
Closed
Description
Envorinment
- OS: Windows 10
- Rust: stable 1.55.0 MSVC
- sqlx: { version = "0.5.7", features = ["runtime-tokio-rustls", "sqlite"] }
Following code crashes while run.
use std::time::Instant;
use anyhow::Result;
use sqlx::{Connection, ConnectOptions};
use sqlx::sqlite::SqliteConnectOptions;
use rand;
use rand::Rng;
#[tokio::main]
async fn main() -> Result<()> {
let mut conn = SqliteConnectOptions::new()
.filename(":memory:")
.connect().await?;
sqlx::query(r#"
CREATE TABLE kv (k PRIMARY KEY, v);
CREATE INDEX idx_kv ON kv (v);
"#).execute(&mut conn).await?;
let mut rng = rand::thread_rng();
for i in 0..1_000_000 {
if i % 1_000 == 0{
println!("{}", i);
}
let key = rng.gen_range(0..1_000);
let value = rng.gen_range(0..1_000);
let mut tx = conn.begin().await?;
let exists = sqlx::query("SELECT 1 FROM kv WHERE k = ?")
.bind(key)
.fetch_optional(&mut tx)
.await?;
if exists.is_some() {
sqlx::query("UPDATE kv SET v = ? WHERE k = ?")
.bind(value)
.bind(key)
.execute(&mut tx)
.await?;
} else {
sqlx::query("INSERT INTO kv(k, v) VALUES (?, ?)")
.bind(key)
.bind(value)
.execute(&mut tx)
.await?;
}
tx.commit().await?;
}
Ok(())
}log:
...
176000
177000
178000
179000
Exception: Exception 0xc0000005 encountered at address 0x7ff6caea661f: Access violation reading location 0x10000003e
stacktrace:
sqlite3DbMallocRawNN(sqlite3 *,unsigned long long) sqlite3.c:28224
sqlite3DbMallocRaw(sqlite3 *,unsigned long long) sqlite3.c:28191
sqlite3VdbeMemGrow(sqlite3_value *,int,int) sqlite3.c:76723
sqlite3VdbeMemClearAndResize(sqlite3_value *,int) sqlite3.c:76765
allocateCursor(Vdbe *,int,int,int,unsigned char) sqlite3.c:86156
sqlite3VdbeExec(Vdbe *) sqlite3.c:89797
sqlite3Step(Vdbe *) sqlite3.c:84331
sqlite3_step(sqlite3_stmt *) sqlite3.c:84389
sqlx_core::sqlite::statement::worker::impl$0::new::closure$0(closure$0) worker.rs:51
std::sys_common::backtrace::__rust_begin_short_backtrace<sqlx_core::sqlite::statement::worker::impl$0::new::closure$0,tuple$<> >(closure$0) backtrace.rs:125
std::thread::impl$0::spawn_unchecked::closure$0::closure$0<sqlx_core::sqlite::statement::worker::impl$0::new::closure$0,tuple$<> >(closure$0) mod.rs:476
std::panic::impl$30::call_once<tuple$<>,std::thread::impl$0::spawn_unchecked::closure$0::closure$0>(AssertUnwindSafe<std::thread::impl$0::spawn_unchecked::closure$0::closure$0>) panic.rs:347
std::panicking::try::do_call<std::panic::AssertUnwindSafe<std::thread::impl$0::spawn_unchecked::closure$0::closure$0>,tuple$<> >(unsigned char *) panicking.rs:401
_$LT$core..ptr..unique..Unique$LT$T$GT$$u20$as$u20$core..convert..From$LT$$RF$mut$u20$T$GT$$GT$::from::hd0746f89f6d41b16 0x00007ff6cacfc483
std::panicking::try<tuple$<>,std::panic::AssertUnwindSafe<std::thread::impl$0::spawn_unchecked::closure$0::closure$0> >(AssertUnwindSafe<std::thread::impl$0::spawn_unchecked::closure$0::closure$0>) panicking.rs:365
std::panic::catch_unwind<std::panic::AssertUnwindSafe<std::thread::impl$0::spawn_unchecked::closure$0::closure$0>,tuple$<> >(AssertUnwindSafe<std::thread::impl$0::spawn_unchecked::closure$0::closure$0>) panic.rs:434
std::thread::impl$0::spawn_unchecked::closure$0<sqlx_core::sqlite::statement::worker::impl$0::new::closure$0,tuple$<> >(closure$0) mod.rs:475
core::ops::function::FnOnce::call_once<std::thread::impl$0::spawn_unchecked::closure$0,tuple$<> >(std::thread::impl$0::spawn_unchecked::closure$0 *) function.rs:227
std::sys::windows::thread::impl$0::new::thread_start() thread.rs:57
BaseThreadInitThunk 0x00007ffc15717034
RtlUserThreadStart 0x00007ffc17482651
It doesn't crash if I run it without the transaction.
Metadata
Metadata
Assignees
Labels
No labels
Activity
[-]"Access violation" while simple upsert loop with transaction.[/-][+]Sqlite "Access violation" while simple upsert loop with transaction.[/+]abonander commentedon Oct 2, 2021
@foriequal0 can you reproduce this with
0.5.9? we recently put out some fixes to do with SQLite.foriequal0 commentedon Oct 3, 2021
It still happens with 0.5.9.
Dhole commentedon Nov 4, 2021
I can reproduce this under Linux. I'm actually investigating a similar segfault that happens in a project I'm working on, but haven't managed to reproduce it in a small test.
I've run the exact same code from the first message in this issue (in a test, with
#[async_std::test]) with the following environment:I get segfaults at two different points. The first one is like the one in the first message:
The second one is longer. I've redacted the beginning of the stack trace:
Dhole commentedon Nov 6, 2021
Hey I think I found the bug in sqlx.
The sqlite connection is being opened with
SQLITE_OPEN_NOMUTEX:So the database connection shouldn't be used simultaneously in two or more threads. I've seen that the ConnectionHandle doesn't implement the
Synctrait, so apparently all should be good... But I'm afraid that's not the whole picture.I believe the segmentation fault here happens because sqlite is using the
Lookaside memory allocatorhttps://sqlite.org/malloc.html#lookaside for the statements, which is found inside the database connection, and there can be unsafe concurrent operations on this structure happening in different threads. The first one is whensqlite3_prepare_v3is being called, which takes a connection pointer. This one will try to allocate the statement into the db'sconnection lookaside memory allocator. The other one is insqlite3_finalizewhich can free the statement from the db'sconnection lookaside memory allocator. See sqlite source to verify how the statement contains a pointer to the db.Since the
StatementHandledoesn't contain theConnectionHandle, and is Sync, operations on theStatementHandlecan happen concurrently to operations on theConnectionHandle, but sometimes this is problematic.Since the method
sqlite3_finalizecan touch the database (at least when theLookaside memory allocatoris used this happens, there may be other cases), then I think there are two possible solutions:A. If
SQLITE_OPEN_NOMUTEXis desired, then we must guarantee thatsqlite3_finalizeis called always in the same thread that operates on theConnectionHandlewhich created that statement.B. Use
SQLITE_OPEN_FULLMUTEXto allow complete thread-safety.madadam commentedon Nov 9, 2021
I think I encountered the same issue. Here is a much simpler reproduction case:
Note I can only reproduce the crash with
--releasefor some reason.Dhole commentedon Nov 9, 2021
As a temporary solution until this bug is fixed, you can now set the sqlite connection to be opened in
SQLITE_OPEN_FULLMUTEXmode like this:This option setting was introduced recently and is not yet available in a release, so you'd need to pull the crate from github. For example, in your
Cargo.tomlyou can add:abonander commentedon Nov 13, 2021
We probably don't need
SQLITE_OPEN_FULLMUTEXas that's a bit overkill, but we do need some sort of mutual exclusion when potentially calling SQLite functions concurrently. The likely culprit here is that we're callingsqlite3_reseton the main thread whilesqlite3_stepis still executing on the worker thread, so we need to make sure to always wait for the latter to finish before executing on a new statement.On the other hand, I'm wondering if we should just have the worker thread manage the connection directly, never calling any SQLite functions outside of it, and then we essentially interact with it like any other client/server database model, with only high-level commands being sent between threads. We're already talking about doing that more or less in #1175 since the SQLite driver in its current incarnation is so slow anyways.
Dhole commentedon Nov 14, 2021
The only instance of
sqlite3_resetI see is in the worker thread. https://github.com/launchbadge/sqlx/blob/829968787891b5aacbe9d4b76e5f29ed9a453ea9/sqlx-core/src/sqlite/statement/worker.rs#L66As I stated before, I believe the data race that causes this segfault is between
sqlite3_prepare_v3andsqlite3_finalizeI believe this is the right approach to achieve a safe sqlite wrapper with
SQLITE_OPEN_NOMUTEX.abonander commentedon Nov 23, 2021
Would you folks mind trying the changes I have in #1551 and see if the access violations still happen or not?
Dhole commentedon Nov 23, 2021
I've run the test code from the first message 5 times using #1551 and all runs completed successfully without any segmentation fault :) (on Linux x86_64)
@abonander thanks for working on this!
madadam commentedon Nov 30, 2021
I can confirm that #1551 fixes the issue for me as well 👍