225 points · by segfaultbuserr · 4y ago · 139 comments
Though: Multiple copies of SQLite linked into the same application. Weird and rare scenario, but why not keep the global list of open sqlite files in a global shared memory segment?
I personally like how POSIX works, and how well documented its operation and failure modes. I love systems which don't prevent foot guns, and go bang spectacularly when I foot gun myself.
It's also ironic how we don't get to like systems which do limits us in severe ways, and then get angry to a system which doesn't limit us the same way. Fun times.
Because POSIX doesn't provide features that are necessary for reliability. Workarounds, if they exist, are highly platform-specific. That I'd say is damnation of the standard.
For example, how do you, within POSIX, ensure that a write to the storage media is "durable"? People argue about what combination of various "sync" calls and open flags you need to achieve this. (Disregard the case of hardware cheating -- nothing can be done about that.)
How do you make an "owning" lock on a file: a kind of that you and only you (the owner) can remove? Why is a lock applied per for file descriptor and not the file object? What is the workaround here?
In general, POSIX + threads = damnation because there's too much per-process global state, which was kind of OK "before MT". It's clear that the standard was written before multithreading was even foreseen to be the norm, and it contains many SNAFUs wrt threads, not just files. (Signals and fork are the first to come to mind.)
Oh, yeah, don't mention Linux. It has so many extensions and additions to POSIX to alleviate POSIX messups that it's not even funny.
Edit: I just reread the spec, and it is on POSIX: They recognized that "sync" was not actually writing, and documented the real usage. Unix 5 has this to say about sync:
> Sync causes all information in core memory that should be on disk to be written out..This includes modifi~ super blocks, modified i-nodes, and delayed block I/0. > It should be used by programs which examine a file system, for example check, d.£ etc. It is mandatory before a boot.
But by System 6, Lion's book is already referring to the peculiarities of delayed writes.
If you have a super-serious hardcore owner lock on a file that only the opening process can release, what happens when a buggy or hostile program locks a file and never unlocks it, even after exiting?
Observe that there is no way SQLite could fix this bug, the SQLite developers instead have to shove off the responsibility to everyone one using the SQLite library. Add a few more layers of libraries where this requirement isn't documented as clearly, and this is basically guaranteed to go wrong somewhere.
I love systems which don't prevent foot guns, and go bang spectacularly when I foot gun myself.
It's good that you know what you like. Just make sure that none of your software is run by me because when your software goes bang spectacularly and foot guns me instead of you I emphatically don't like it.That's because all my code is tested for both leaks and all scenarios. None of my code ever have gone bang in production. To be honest, no service I have written ever restarted outside system reboots or configuration changes.
Having systems with no guardrails doesn't equate to having bad code automatically.
But, related to the Posix thing about reusing fd's, I just ran into this a couple of days ago and it took me 6 hours to figure out.
I made a change in HashBackup to interrupt saving a big file if the backup time limit had been reached. Tested it a while, seemed like it worked fine. I was using a 15-second timeout. For whatever reason I tried it with a 5s timeout. This went bang, but in a completely different area of the program responsible for copying backup files to a destination, where it raised an exception "hey, this file was X bytes but I only copied Y". Go look at the source file, it's fine. Look at the destination file, and indeed, it is only Y bytes. Go look at the copy code, it looks fine but obviously isn't, so I start putting all kinds of debug stuff there to check file sizes, do double reads at EOF, ... nothing helps. Then I add an lseek to report the current file position and indeed it is at X, even though only Y bytes have been copied. So I realize that something else has moved this file pointer on me.
To help track that down, I override Python's os.open and os.close and display the pathname and fd so I have a history of who is using what fd's. After going through that with a microscope, I see that the file being backed up is open on fd 6, and when the timeout occurs, it gets closed. Then that fd gets used by the copy function for the source file.
BUT, there is an asynchronous read process used during the backup. It has exception handling if an fd is closed by higher levels and the read thread gets an EBADF error, then resets itself. But there is a race condition: if the fd gets reopened fast enough, the read thread will never see the EBADF error and thinks it is still reading from the file to backup, which it continues to do. Now there are 2 processes reading from the same file and mayhem ensues.
Of course it's ultimately my fault, but we do have at least 32 bits for a file descriptor number. It would be a lot nicer if Posix kept incrementing it instead of using the low numbers and then wrapped around, like Unix PIDs do. And yeah, I realize this would screw up select, dup, etc because of the way they are designed.
Nice! I'd recommend trying strace to track system calls in the future though. Monkey patching open and close will only catch code using those functions and not any c libraries or very smart people using ctypes.
Strace captures every syscall and dumps the parameters and returns.
You are conflating surprising systems and flexible systems.
Something that is flexible doesn't have to be surprising. Nor does something surprising have to be flexible.
The Principle of Least Surprise says that surprising behavior in software is bad. Systems should strive not to do things that catch users off guard absent a good reason.
Instead, for example Java has given me much more surprises, and at catastrophic levels. I was using Choco Solver [0] back in the day, and I created two instances of it, attached to different classes. Which is perfectly normal, right?
Somehow they've cross linked between these two instances, affected the results they have computed, and created persistent memory leaks which needed system reboots to claim back. Java should be immune to that, but no.
Preventing that needed to run only one instance of Choco, which limited my performance greatly. Luckily, the system had a queue/consumer structure, so running only one didn't need extensive changes.
Do I need to say anything more?
No. Let me re-iterate what I mean.
Systems without guardrails are explicit, transparent and flexible. It's easy to understand how they behave. It might be a little harder to get things right, but when you get it right, there's nothing to second guess.
Systems without guardrails are low in overhead. It's possible to get raw performance.
Yes, I love these systems. I might spend a little more time and need a little more concentration when I develop stuff on these systems, but when it runs, it runs for good.
Trying to make systems foolproof by limiting them is not good. If that's good, we should all love iOS, right?
Similar problems occur if you do in-place upgrades of software using dynamic libraries.
For what happens when you do that on Linux: the file entry gets deleted, but disk space doesn't get deallocated until the last program using the file has exited. If you replace the file, the program will still be referencing the old file (now unreferencable by any name/path, except possibly through /proc/../fd).
I don't know how you could avoid this, and it has me wondering if you understand the issue. This is basically the file descriptor version of a use-after-free bug. I'm not one of those "rust fixes everything" people, so I don't answer this about just anything, but I think this issue would completely disappear in a memory safe language and especially one where the wrapper for file descriptors had good prevention of race conditions closing a file, so it hardly seems fair to blame the filesystem API.
I mean, in some cases you could blame the API for high frequency of application bugs, but using a closed file seems like a bug category that is unreasonable to do so for. The issue of use-after-free is larger than the filesystem API.
I understand the issue. Someone else has already mentioned how you could avoid this: allocate fds randomly instead of sequentially. This would significantly reduce probability of accidental reuse. If you widen fds to 64 bits then you're pretty much good.
Yes, it'd break syscalls that rely on sequential allocation like select. It just shows how POSIX has painted itself into a historical corner, alongside with many interactions with threads being a kludge.
you're talking about the kernel interface that eventually maps onto a filesystem
This is an ownership issue is my point. It's not exactly memory safety but the same concept applied to an integer rather than a pointer.
… though if you’ve got a procfs around, /proc/self/fd/* is ripe for the writing.
Usually none of these issues are dealt with in the shared memory sdk you’ll be using, so you gotta model it with mental experiments just like you would a lock free implementation in a threaded process.
Simple no, doable yea, error prone you betcha.
I honestly think this one of the greates advantages of POSIX systems over Windows. If I as a (super)user want to delete a file I should always be able to do that and applications will just have to deal with it.
What exactly do you mean by “providing no means to prevent it”?
They would all use the same reserved "name". It's possible to atomically create or open a SHM segment with a given "name". Then have a header at the start of the segment with critical metadata like signature, version, etc. Barf unconditionally if the metadata is found to be invalid (i.e., some other process deliberately used the name to sabotage sqlite [1]), or, in addition, have an option to not use SHM.
[1] The situation is not different from some process sabotaging another by deleting or corrupting well-known files.
I used two different C# libraries to access the same database. And under the hood, they both used a different SQLite library, with different native SQLite builds (of the same version though).
Took me some time to figure out…
....ah, but if they were tripping over each other in memory I can see that going sideways.
What exactly happened?
But it’s also possible, that SQLite was built by different compilers/toolchains and that did the trick.
What happened: my database files were always corrupted and needed repair. The application did only a few writes, and sometimes the changes just disappeared.
Edit: the SQLite website says: „But, if multiple copies of SQLite are linked into the same application, then there will be multiple instances of this global list.“
SQLite is great, but I would not use it in a multi-machine, multi-processing environment.
Developers do need to understand that it's SQLite, not a poor man's Postgres. This require correct engineering, and the SQLite docs are in a class of their own in patiently explaining in simple terms how to do this.
If you embrace what SQLite is, you can do a remarkable number of things with it, safely and reliably.
> SQLite docs are in a class of their own in patiently explaining in simple terms how to do this.
Yes! I love reading the SQLite (and Fossil!) docs. They're so beautifully written!
Yeah great, you shouldn't. SQLite is meant to be replacement of custom files to store data by apps (mobile apps, desktop apps, server apps). This isn't meant to scale to millions of users, but just store data in a structured manner.
I should mention that I was able to repeat the corrupting problem reliably. The problem disappeared when I moved to a working directory that was not monitored by OneDrive.
I was setting up a very simple db from a few CSV files, for use in a data science exercise for a course. There was nothing interesting happening in my code at all-- maybe a simple table join sql query, at most.
Is it possible to turn off transactions alltogether in SQLite? So they function like a MyIsam table in MySql or a Aria table in MariaDB?
I have crunched many billions of queries over the last years in MySql and then MariaDB. I like MariaDB because it offers tables that are way faster due to no transaction overhead.
I know this goes against the popular opinion to use transactional tables for everything. But depending on the task at hand, the performance gain can be very well worth turning transactions off.
I consider trying SQLite. But if you cannot switch off transactions, performance will probably not be up to par.
PRAGMA synchronous=OFF;
PRAGMA journal_mode=OFF;
The first one yields saving to the OS instead of SQLite verifying that it has been written properly (https://sqlite.org/pragma.html#pragma_synchronous). The second one is basically turning off all journal capabilities, trading ACID for maximum performance (https://sqlite.org/pragma.html#pragma_journal_mode).I don't there is a way of turning off transactions completely, you can either do it explicitly or implicitly.
However, if you do it explicitly (wrapping BEGIN/COMMIT manually), you can batch all your INSERT/SELECT statements inside one transaction instead of one transaction per query. This should make things a bit faster as the lock would only have to be acquired/released once instead of once per operation.
At least according to my experiments with MyISAM tables vs InnoDB. I never got InnoDB tables to perform as well as MyISAM tables.
[1] https://www.mail-archive.com/sqlite-users@mailinglists.sqlit...
But it does not give you the performance you get if there are no transactions in the first place.
Is this also true of SSDs?
- I tested four NVMe SSDs from four vendors – half lose FLUSH’d data on power loss (twitter.com/xenadu02)
Unfortunately for me, they also had a thing where if a write-back battery passed a certain number of hours in operation the array would no longer trust it and defaulted to then not using it at all - which is entirely reasonable right up until the point where your systems team won't buy a replacement.
I once offended the lead sysadmin at that job on a phone call so much that he had to pass me off to his junior because I'd been telling him for months that the battery needed replacing and basically my opinion was "yeah, have fun waiting an hour while that system fscks" interspersed with helpless laughter.
(in my defence, I wasn't paid to be on call and he called me at 2am during a good friend's 30th birthday party, so my capacity for diplomacy was even more limited than normal)
That made me nervous!
I don't know enough about how Docker implements volumes under the hood to know how likely (or not) it is to break filesystem behavior that SQLite depends on for its transactional guarantees.
Perhaps someone here does?
What you should worry about though is the underlying volume driver and its storage type. Volumes can be simple bind mounts to your local disk, being more or less identical to no container. But volumes can also be attached straight to a network disk, where same dangers apply as if you would have mounted that network disk on host.
Volumes are made exactly for holding databases. And also bind mounts should work without any issue in most configurations.
But if there is some kind of network/virtualization between the physical disk and the container, you should investigate it in more detail.
Source: https://youtu.be/Jib2AmRb_rk
I'd link the exact timestamp, but then you might watch less than the entire talk, which would be unfortunate.
But the grammar would suggest they do say it by pronouncing each letter of the acronym separately.