solid_queue: SQLite queue database corruption
I’m seeing a strange error. I dropped @fractaledmind a note and he suggested I post here.
W, [2024-09-05T18:49:32.074281 #809854] WARN -- : SolidQueue-0.3.4 Error deregistering Supervisor (1.1ms) process_id: 68, pid: 564289, hostname: "HOST", last_heartbeat_at: Sat, 31 Aug 2024 15:16:55.474066000 UTC +00:00, claimed_size: 0, pruned: {:process=>#<SolidQueue::Process id: 68>, :pruned=>true, :claimed_size=>0, :error=>#<ActiveRecord::StatementInvalid: SQLite3::CorruptException: database disk image is malformed>, :exception=>["ActiveRecord::StatementInvalid", "SQLite3::CorruptException: database disk image is malformed"], :exception_object=>#<ActiveRecord::StatementInvalid: SQLite3::CorruptException: database disk image is malformed>}, error: "ActiveRecord::StatementInvalid SQLite3::CorruptException: database disk image is malformed"
In sqlite3 client.
sqlite> .open production-queue.sqlite3
sqlite> pragma integrity_check;
*** in database main ***
On tree page 523 cell 23: Rowid 146 out of order
NULL value in solid_queue_jobs.created_at
NULL value in solid_queue_jobs.updated_at
row 146 missing from index index_solid_queue_jobs_for_alerting
row 146 missing from index index_solid_queue_jobs_for_filtering
row 146 missing from index index_solid_queue_jobs_on_finished_at
row 146 missing from index index_solid_queue_jobs_on_active_job_id
row 146 missing from index index_solid_queue_jobs_on_class_name
NULL value in solid_queue_jobs.created_at
NULL value in solid_queue_jobs.updated_at
row 147 missing from index index_solid_queue_jobs_for_alerting
row 147 missing from index index_solid_queue_jobs_for_filtering
row 147 missing from index index_solid_queue_jobs_on_finished_at
row 147 missing from index index_solid_queue_jobs_on_active_job_id
row 147 missing from index index_solid_queue_jobs_on_class_name
NULL value in solid_queue_jobs.created_at
NULL value in solid_queue_jobs.updated_at
row 148 missing from index index_solid_queue_jobs_for_alerting
row 148 missing from index index_solid_queue_jobs_for_filtering
row 148 missing from index index_solid_queue_jobs_on_finished_at
row 148 missing from index index_solid_queue_jobs_on_active_job_id
row 148 missing from index index_solid_queue_jobs_on_class_name
NULL value in solid_queue_jobs.created_at
NULL value in solid_queue_jobs.updated_at
row 149 missing from index index_solid_queue_jobs_for_alerting
row 149 missing from index index_solid_queue_jobs_for_filtering
row 149 missing from index index_solid_queue_jobs_on_finished_at
row 149 missing from index index_solid_queue_jobs_on_active_job_id
row 149 missing from index index_solid_queue_jobs_on_class_name
Error: stepping, database disk image is malformed (11)
sqlite> pragma integrity_check;
*** in database main ***
On tree page 523 cell 23: Rowid 146 out of order
NULL value in solid_queue_jobs.created_at
NULL value in solid_queue_jobs.updated_at
row 146 missing from index index_solid_queue_jobs_for_alerting
row 146 missing from index index_solid_queue_jobs_for_filtering
row 146 missing from index index_solid_queue_jobs_on_finished_at
row 146 missing from index index_solid_queue_jobs_on_active_job_id
row 146 missing from index index_solid_queue_jobs_on_class_name
Error: stepping, database disk image is malformed (11)
Doing a .clone doesn’t seem to fix.
I’m not in “real” production and this is a job queue and thus somewhat destroyable, so I’m going to take that approach.
I’ve also seen similar corruption on my local development environment too akin to that mentioned by @marcoroth on X.
https://x.com/marcoroth_/status/1831045885423497223
In that case I just destroyed and recreated the file and moved on.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 85 (60 by maintainers)
Commits related to this issue
- Make SQLite3Adapter fork-safe. Sqlite itself is not fork-safe, as documented in https://www.sqlite.org/howtocorrupt.html section 2.6. Any databases that are inherited from the parent process are unsa... — committed to flavorjones/rails by flavorjones 2 years ago
- SQLite3Adapter: Ensure fork-safety Sqlite itself is not fork-safe, as documented in https://www.sqlite.org/howtocorrupt.html section 2.6. Any databases that are inherited from the parent process are ... — committed to flavorjones/rails by flavorjones 2 years ago
- SQLite3Adapter: Ensure fork-safety Sqlite itself is not fork-safe, as documented in https://www.sqlite.org/howtocorrupt.html section 2.6. Any databases that are inherited from the parent process are ... — committed to flavorjones/rails by flavorjones 2 years ago
OK, I understand what’s happening. Problems result when an inherited (from the parent process) database connection is
sqlite3_close()ed or a prepared statement issqlite3_finalize()ed in the child process.In a Rails app it seems much more likely to be a statement being finalized because of the cached statements, but it can happen with the database objects as well.
I think we should be able to work around this now that I understand the mechanism.
Epic team work, all 🤘. Sqlite is going to be a much bigger role in Rails apps going forward.
Released https://github.com/sparklemotion/sqlite3-ruby/releases/tag/v2.1.0.rc2 addressing a performance regression in rc1.
OMG! You two are such absolute legends! @flavorjones you are a complete baller. @rosa you are a total magician. I am so grateful to get to work in the general vicinity of you both. I will buy you both some kind of drink in Toronto to show my thanks.
Git bisecting, this is the PR/commit where this behavior changed:
https://github.com/sparklemotion/sqlite3-ruby/pull/392 / https://github.com/sparklemotion/sqlite3-ruby/commit/0c24631d5b8c9b2e361b1a0bbfc1823a18793b71
which has to do with the lifecycle of database connections and prepared statements. Getting closer.
👋 Hey all. I spent a chunk of time yesterday trying to reproduce this. My hunch after reading this issue and How To Corrupt An SQLite Database File is that it might have to do with process forking.
So that’s where I focused my time, and it paid off. I’m able to easily reproduce at least some form of database corruption using nothing but active record and forking. Some caveats, though:
That said, here’s the ad-hoc repro script that reproduces corruption on my system:
https://gist.github.com/flavorjones/1f1dffa6bdd6ab81a227d10d73891f34
The broader context is that I run it in a vanilla rails app with a scaffolded Post model, and I run it like this:
It exits with nonzero status if the sqlite integrity check fails. I see lots of exceptions (“disk I/O error”) but those don’t always result in corruption, so I run it in a loop and reliably reproduce database corruption in under a minute.
I will post a full Rails app repo later this morning, with more comments, etc. but the corruption only happens when BOTH of these conditions are true:
So if the parent waits for the children to exit: no problem. If the parent closes its connections before it forks: no problem.
Please note that in this scenario the children aren’t even using the database connection inherited from the parent process – Rails is doing the right thing and creating new connections, as instructed in https://www.sqlite.org/howtocorrupt.html, and the problem still happens.
It’s still very early in the investigation, but my current hypothesis is that something is going on in shared memory space when the parent exits that then causes problems in the child processes. This may or may not be intended behavior but I’d like to isolate this with a reproduction in C and move the conversation upstream to the sqlite forum.
OK, I hacked on the sqlite3 adapter so that it closes database connections before forking, and that seems to prevent the data corruption and disk i/o errors. I think we just need to polish the patch and land it in Rails and everything will be OK! Stay tuned.
FYI I have upgraded rubyvideo.dev with this latest version(https://github.com/adrienpoly/rubyvideo/commit/71ece9b9d678ee4cba1c929de8a9367ca9f9a0ba). It is now live in prod. So fare everything looks perfect.
Aww @fractaledmind you’re too kind! This was all @flavorjones, he’s the magician 🪄. Plus it’s me who’s beyond grateful to you and everyone here for the help, it’s a privilege to have people like you in the community 🙇🏻♀️ I’m definitely the one getting you drinks at Rails World! 😆 and Marco, Nick, Andy… 🥹🙏🏻
Repository with a full Rails app reproduction here: https://github.com/flavorjones/2024-09-13-sqlite-corruption
@rosa Yea im living on the edge and following main.
with a database config of:
For sure! Never been so excited to get a corrupted database before 😅
puma
yup!
Yeah, this sounds like it might be what is occurring:
If it helps, here’s how my
pragma integrity_checklooks like:See https://github.com/sparklemotion/sqlite3-ruby/pull/566
Changed direction, here’s the latest plan, I’d love feedback:
See https://github.com/rails/rails/pull/52931 which should address at least one of the issues discussed in this thread (fork-safety). I’d love to get some feedback on it!
Ok, I finally could reproduce this with @flavorjones’s test on macOS. Yesterday when I was testing that I didn’t realise I was running this version of SQLite3
Today, I’ve got the corruption error with both:
I’m doing other tests now with different versions, there’s also a difference if I reduce the number of children to 3 like yesterday.
Update: yes, the number of children makes a difference. With
N=10, I get the corruption with older versions of the sqlite3 gem (tested with 1.5.0).~One more note amending what I wrote above: I can sometimes reproduce this even when the parent has closed all its connections, and even when it has created zero connections. I honestly don’t know what to make of this fact yet and it seems like absolutely bonkers spooky-action-at-a-distance.~
Ignore this, it was a procedural mistake on my part.
Just a quick update on this one: I’ve been busy the last couple of days with other work stuff but I plan to come back to this tomorrow. I’ve spent more time learning about how Active Record prevents connections from leaking across forks as well, as this was something I wasn’t familiar with (I only knew it was supposed to handle it). I’ll also test a bit more #337 in production and will merge it, and then will dedicate most of the effort to try to reproduce the original error with the real corruption.
I think there are two issues, this
SQLite3::CorruptExceptionI hit just now is closer to what @alvernier is describing. It happened shortly after waking up my mac, which happened to me for the first time now. The other ones I encountered I could easily reproduce and didn’t involve waking up my MacBook.But after it crashed this time I could run
rails sagain and it wasn’t complaining about the corrupted file. The pragma check is confirming that the database is actually in tact.Which leads me to believe that these are two separate issues having very similar symptoms.
App: RubyVideo on
fb0a8c7Ruby:3.3.4Rails:7.2.0SolidQueue:0.5.0sqlite3:3.43.2 2023-10-10 13:08:14 1b37c146ee9ebb7acd0160c0ab1fd11017a419fa8a3187386ed8cb32b709aapl (64-bit)sqlite3 gem:sqlite3-2.0.3-x86_64-darwinHere are the full-logs, from
rails sto ctrl-c-ing to exception.I tried to annotate them to give more context. Note: My system time is on CEST (UTC+2), db queries are on UTC.
rails s/feed.xmlis from a local RSS subscription in the RSS reader app, I think it did fetch the file again as soon as I unlocked my macSQLite3::CorruptExceptionis thrownI just got a
SQLite3::CorruptExceptionshortly after waking up my Mac 👀 Going to collect whatever could be useful…One weird thing I noticed, my mac was lagging for a bit and then I saw the exception. My guess is that it could have to do when the system is running low on available resources.
@rosa Awesome ill give the branch a try!
I can reproduce this issue after Mac hibernation with this config:
note:
config:
Edit: sqlite version
Just a small reminder for years of debugging in the dark: save your brain cycles and energy trying to find the problem. Definitionally we have missing info and/or faulty assumptions somewhere. The exclusive focus for us all should be creating a reproduction. I promise we won’t solve this without that. So containing to explore the space of scenarios in an attempt to deterministically reproduce is going to be the highest leverage activity.
That reminds me that was my hunch when I saw this a while back. I upgrade aggressively and I’ve been conference prepping, so I haven’t seen this personally in a while. But I recall wondering if it was related to closing the laptop.
I think im on to something. Just had it happen to me. Cant quite reproduce reliably yet but i think it may have something to do with me keeping the server running with the puma plugin running and closing my laptop for some period of time. Cant confirm yet but just a hunch. Will report back if i mind reliable instructions. Heres the log. It’s weird that there are rollbacks happening trying to update the Process model and then it corrupts.
I upgraded SolidQueue to
0.6.0so I could later upgrade to0.8.xto see if the issue is still present on the latest version.But I couldn’t reproduce it on
0.6.0. And now, after downgrading again, I can’t reproduce it on0.5.0anymore weirdly enough 🤔Prior to upgrading to
0.6.0I was able to reliably reproduce it.Is there any chance that this is dependent on the sqlite3 gem variant you get?
I’m running the
x86_64-darwinone (and I assume @andycroll is probably also running ax86_64-*variant in production) whereas most of you are probably running aarm64-*variant on your local dev machines.Also, here is a one-liner to check the queue database integrity:
sqlite3 storage/development-queue.sqlite3 'pragma integrity_check;'@marcoroth: I created this repo to hopefully help us find a reproduction: https://github.com/fractaledmind/solid_queue_bughunt
You will see that I have a
LongRunningQueryJobthat I enqueue automatically once Solid Queue is loaded. I am trying toctrl + ctwice once the job starts up such that the Rails process is killed and the job dies. But, the job always resolves. I’m curious what your experience is. Can you get everything to stop mid-operation? Or does the job eventually resolve for you to?You can see if the job eventually resolves by just waiting 5 seconds or so after you kill the Rails process and waiting for logs to print. All you have to do is
bin/rails sand everything goes automatically.You will see I have commented out automatically killing the Rails server process. I was trying that as well. Still, the job resolves. My hunch is that it is/was somehow possible to force Solid Queue to not stop gracefully and if a job was running and connected to the database, that could corrupt. But I am not sure. Maybe if we all work on this reproduction repo, we can hunt it down.
Ohhhh, thanks a lot @fractaledmind. That’d make perfect sense as the culprit! I thought Rails would handle this properly and wouldn’t reuse the same connection but I need to dig more.
I haven’t been able to dig in myself yet, but after reading this: https://www.sqlite.org/howtocorrupt.html and knowing the bits that I know about the supervisor architecture, I was first drawn to: