Questions on fs file handling for performance read-only access

The program I'm working on is going to end up with a set of read-only files containing collections of structure data. My original thought was to have the data split up into reasonably sized sets across a number of files, and load an entire file into memory at once, then switch files when a structure in a different file was needed (originally the need to access a different file would come maybe once every few minutes, nothing insane).

Due to changes, I'm going to have to figure out a way to allow either multiple processes or multiple threads to read the files to serve a higher rate of requests for the structures. Creating an index file to point which structures are at what offset in what file won't be too difficult, however there's a couple things I'm not sure of in fs:

  1. fs::File::open() "Opens" the file, but if I understand, doesn't load any of the file data to memory until a Reader method/function actually pulls it. Does this mean that using fs::File -> open() -> seek() -> read_exact() approach using the index information would minimize the memory usage to what is necessary to get the structure data from the file?

  2. Documentation indicates that "Files are automatically closed when they go out of scope." I'm guessing this means that using fs::File::open() indicates to the file system that the process is using that file, and access blocking for "opened" files is handled OS side and not program side?

  3. The fs::read() function indicates it skips the intermediate variable, would this sidestep the potential issue of a process or thread "holding open" the file and blocking others?

It's entirely possible no approach is non-blocking because the OS has the final say on who can access what file when, and I need to do something like async queuing for threads needing to read. Regardless, I'm going to continue beating my head into this wall, appreciate any insights.

File doesn't buffer data itself at all. It's a file descriptor (Unix-alikes) or file handle (Windows). That said, once you start doing reads, a BufReader<File> or the OS may.[1]

But anyway...

...if you want all the bytes in memory, yes. Alternatives would be some way to deserialize in a more streaming fashion or something like mmap. I'd only start thinking about those routes if I really had to.

I'm not sure what kind of access blocking you're thinking about, but I'm pretty sure the answer to this question is "it's on the OS side". There's no automatic file locking upon file open (see the methods with lock in their name if you want locking).

(The flow is more "ask the OS for a file descriptor/handle" and "tell the OS when we're done with it" than "notify the FS".)

If you do a bunch of things between open and reading, or between reading and the File getting destructed, then the file may be held open for longer. If you don't do much, it won't matter much.

You can control where the File gets destructed by calling drop(file).[2]

You can think of the following two code blocks as roughly the same.

let buf = read(path)?;
let mut file = File::open(path)?;
let mut buf = Vec::new();
read_to_end(&mut file, &mut buf)?;
drop(file);

  1. Well, the OS could plausibly do speculative reading and caching before you perform any reads, I suppose. ↩︎

  2. When the docs said "automatically closed when they go out of scope" they really meant "when the File is destructed". ↩︎

On Windows, opened files are locked unless FILE_SHARE_READ or FILE_SHARE_WRITE option is provided to CreateFile, TS could have meant it)

Some questions, to help prime the design:

  • How large is the dataset in total?
  • How much RAM, and how much storage, do your target platforms normally have? If it can vary, what does the low end of normal look like to you?
  • What proportion of your program's running time is presently spent loading data, and what proportion do you consider adequate for your purposes? (If proportion isn't the right measure, substitute accordingly - total wall time spent on IO is a common yardstick, for example).
  • A higher rate of requests... than what? What is your baseline, and how much higher does the rate need to be to cover your design needs?

These questions probably feel a little basic, and I'm reasonably sure you've taken the answers applicable to your system for granted in writing this, but we don't know what those answers are - and getting better performance out of a 32 MiB microcontroller running an embedded web server looks very different from getting better performance out of a machine with tens of gigabytes of RAM and a fast SSD.

Due to changes, I'm going to have to figure out a way to allow either multiple processes or multiple threads to read the files to serve a higher rate of requests for the structures. Creating an index file to point which structures are at what offset in what file won't be too difficult

Sounds like you're trying to implement a database. Does Sqlite fit your use case?

@quinedot Appreciate the clarification on File, that makes sense given the separate read methods.

Being that most of my experience is on user side, and with Windows, I'm used to seeing things along the line of "Error opening file: in use by another application". I wasn't sure if there was platform-dependent behavior like @throwable-one brought up, or if it was all program-requested locks.

I did have the opportunity today to dink around and do some learning, and based on tests (on Linux) reading a file with the bytes for the string "123456789", it seems:

  1. Nothing prevents multiple File type variables from being created referencing the same path in the same scope or with overlapping lifetimes.

  2. Even though you can run parallel read calls to the same file using threads (without having to use async in the rust code), it seems the file system isn't able to serve those read calls simultaneously. I tested a thread and main each looping 500,000 read calls to the file at the same time, then just main looping 1,000,000 read calls to the file, and the parallel split was consistently slower overall execution time.

  3. Assuming that open() -> seek() -> read_exact() actually reduces extraneous RAM usage (which I don't know how to test for cleanly right now), the trade-off looks to be longer time to execute versus reading the whole file and taking whatever slice is needed.

These are entirely reasonable questions, and I wish I had good answers to half of them. The data set is likely to be 5 to 10 MB per cohesive set, with one process handling read calls to some arbitrary number of cohesive sets, let's say 400. There's a choice to be made as to whether each cohesive set gets put in one file, or broken up into smaller chunks. Target platform is server hardware, so a healthy amount of RAM, storage, and CPU, probably far more than is strictly needed for the process. The... I don't know what the technical term is, the non-IO computation done to the data before output, is fairly trivial, so I would expect the IO to be the bulk of wall time between call and output. As for the actual request rate, I'm still trying to figure that out from the person who runs the existing system.

That being said, the existing system is a JavaScript based interpreter that loads and processes plain-text source files for output, so I don't think that it should be too difficult to improve on its performance.

Fairly database-like at this point, it seems. I've been reading through some of the SQLite information when I can, and the structure definitely makes sense. Some of the things I'm not sure of on that front are how RAM-heavy it is (if I can just load all the data to memory, file system read performance is a moot point), and whether I would be 'paying' for all the DB functionality I don't use, since my needs are fairly simple.

That is true. Also, different paths can lead to the same filesystem file. Also, you can have two Files which share the same underlying file description (not that I think you want to). Which would be like using dup (on Unix anyway, I'm less familiar with Windows).

There are a lot of servers out there where your four-gigabyte-ish data set would fit comfortably in RAM. If you care about raw access speed and are willing to spend memory to achieve it, then it might be reasonable to load all of the segments on startup into a suitable immutable data structure and then reuse those during the life of your program.

Taking that idea a step further, if the data changes infrequently enough, you could even compile it into your program. A multi-gigabyte binary is unwieldy in some ways, but you would be able to rely on the OS to cache frequently-accessed static data in unused RAM, while disposing of infrequently-accessed data as needed to free up pages for other uses. I'm not sure how much effort I'd personally spend on this approach, but it's one I'd probably at least benchmark.

I would also second @sunyizhe's suggestion to look into sqlite. Preprocessing the data into something SQL-shaped and designing indexes to suit your query patterns will get you shockingly good IO performance for a lot of workloads. sqlite has its limitations when used as a general-purpose database engine, but works well as a structured access layer over data that is available locally and changes relatively slowly over time.

This doesn't sound right to me because it doesn't match at all my experience and I know that SSDs (I assume you're not using a spinning disk!) get very large amounts of parallelism. I would try two things:

  1. Look for other things in your test that are preventing parallelism, ie, locking of any kind, use of the same File object for both threads, etc, basically anything shared between the threads.
  2. Add more threads, since 2 is a small number for a test like this.

EDIT: Also note that you're not testing disk parallelism if both threads are reading the same data (same file, within the same file system block), since the data is cached by the file system. You may want to just post or give a link to the test source code.

Being that most of my experience is on user side, and with Windows, I'm used to seeing things along the line of "Error opening file: in use by another application". I wasn't sure if there was platform-dependent behavior like @throwable-one brought up, or if it was all program-requested locks.

Windows locks files by default (but you can enable multiple readers , or even multiple writers mode though), Unix doesn't. Unix also has locks, but they are pure optional and should be used by both applications: one app sets a lock, another one obeys it (but can always ignore it).

Nothing prevents multiple File type variables from being created referencing the same path in the same scope or with overlapping lifetimes.

Absolutelly. Rust File is just a convenient RAII wrapper over what OS providies as a file.

Moreover, a "path" isn't the best file pointer. There might be different paths pointing to the same physcial file (symlinks) or same path pointing to different files depending on a process (/dev/tty on Unix for example).

Some paths aren't files at all, they can be pipes or devices. On Unix they are still files of special type (devices in /dev, unix domain sockets, pipes) or not so special, think /proc or /sys on Linux, on Windows they aren't files at all (something like \\.\PhysicalDrive0 or \\.\pipe\..)

So when you have a path as a string, you just ask OS to provide you a file abstraction for this path. If you're interested in what OS does to convert a path string to something that provides an API, you should read about VFS namei on Linux or Object Manager on Windows, but it is a rabbit hole)

it seems the file system isn't able to serve those read calls simultaneously.

If you read from the same blocks, chances are high you hit the cache and it should be fast on any modern OS. If not.. well it really depends on underlying block device, its bus/protocol and drivers.

For example, in IDE/ATA HDD there was no reason to read something in parallel at all (unless you had RAID-1), while SCSI had TCQ: clients sent several requests and it was up to controller to sort them wisely (becase it was expensive to move an HDD head).
In SATA they introduced NCQ and so on.

Currently, we have nvme, and they work pretty good with concurrent reads, so unless you locked a range of bytes inside of a file (e.g. LockFileEx on Windows, fcntl on Unix) it should work.

For the purpose of completeness, File::try_clone on Windows uses the equivalent but much more fiddly DuplicateHandle

I'm still thinking through the information everyone has provided, but I thought I would go ahead and post the code I was using to test as @jumpnbrownweasel suggested.

When I ran the concurrency test yesterday, I was only using read_from1 and one spawned thread. I modified it today to use two spawned threads, and tested both read functions. read_from1 seems to be roughly the same speed as single-thread, and read_from2 comes in faster (Edit: Reran it again after posting, stopped being significantly faster, computers are sorcery), so I might have just shot myself in the foot somewhere in read_from1. Regardless:

use std::fs;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::thread;
use std::time::Instant;

fn main() {
    let mut file = fs::File::create("./test_file").unwrap();
    let _ = file.write("123456789".as_bytes());
    drop(file);

    let path = Path::new("./test_file");

    let timer = Instant::now();

    let handle = thread::spawn(|| {
        for i in 0..500000 {
            let _ = read_from2(path, i % 5, 3);
        }
    });

    let handle2 = thread::spawn(|| {
        for i in 0..500000 {
            let _ = read_from2(path, i % 5, 3);
        }
    });

    for i in 0..500000 {
        let _ = read_from2(path, i % 5, 3);
    }
    
    handle.join().unwrap();
    handle2.join().unwrap();

    let t1 = timer.elapsed().as_millis();

    let timer = Instant::now();

    for i in 0..1500000 {
        let _ = read_from2(path, i % 5, 3);
    }

    let t2 = timer.elapsed().as_millis();

    println!("{} {}", t1, t2);
}

fn read_from1(path: &Path, pos: u64, length: usize) -> Vec<u8> {
    let mut file = fs::File::open(path).unwrap();
    let _ = file.seek(SeekFrom::Start(pos));
    let mut buf: Vec<u8> = vec![0; length];
    let _ = file.read_exact(buf.as_mut_slice());
    return buf;
}

fn read_from2(path: &Path, pos: usize, length: usize) -> Vec<u8> {
    let buf = fs::read(path).unwrap();
    return buf[pos..pos + length].to_vec();
}

Because you're opening the file each time you read, and reading a very small amount each time, most of the time is probably used by the file open operation. In a more realistic test, the file handle should be cached per-thread.

I'm not sure if that reflects the use case of a large volume of requests that may each ask for some small amount of data from some arbitrary file, unless it's reasonable to keep an opened File handle for every potential file needed, and pass a reference to it into the thread to use (I was having issues figuring out how to pass the File handle reference in to a thread, and not have to recreate it in each thread's scope, which would get me right back to creating a handle per read request, since to my mind you would spawn a thread or have a thread pool handling each request).

Regardless, I did change the test code to cache a file handle per thread, and changed the function signature to take an &mut reference to the file handle. Results were interesting and show I may have been wrong about seek being slower:

Seek-based: 325 ms concurrent / 504 ms single-thread
Rewind and read whole file: 606 ms concurrent / 1224 ms single thread

I used rewind() inside read_from2 to reset the file handle's stream position, which seemed to be necessary for multiple calls to a shared handle.

My assumption is that what you described would best be implemented by opening a set of file handles in each thread. Opening a file is relatively expensive. If the number of files and threads is too large, you can use a fixed size cache of open files and some sort of LRU mechansm -- this is what we did in the database I worked on. But if you really want to optimize like this, perhaps just using a database (SQLite) is best.

It's best not to share file handles concurrently, since sharing may causing locking.

If the set of files does not change constantly, it may be preferable to just bypass the filesystem and combine all the files into one large file, with a directory of seek offsets at the beginning. This is what eg. games almost always do with assets in order to reduce overhead. This also opens the possibility to memmap the entire file, or just read it entirely into RAM if it fits.

Good point. I'm not clear on why the OP wanted to use multiple files.

I'll note for OP's benefit that this is basically the architecture of a ZIP archive, though ZIP puts the list of elements and their respective offsets at the end, rather than the beginning. If OP wants to explore that option, it might even be reasonable to use a ZIP file; if decompressing the elements is a bottleneck, compression can always be disabled.

First, we create one lengthy file, then we split it into blocks (say, 8KB each) and create an index somwhere near its head to seek to the right block quickly. Then, we support block erasure, and create an index of free blocks by means of bitmap (one bit -- one block) to find an empty block quickly. Then we decide not to write to blocks and index directly (because we might leave them in insosistent state if we lose power) but use log. We write to the log, sync it and then play it. Then, we need to deal with fragmentation. And as a last step, we create a buffer in front of our file, and use O_DIRECT to bypass an OS buffer.

But with all of that, do we really need a file system? Probably we could use a bare block device?:slight_smile:

At least, we are in a good company: Many databases do something similiar (8KB page is exact size used by PostgreSQL)

A couple of considerations pushed me a bit in that direction, such as that the data sets would be assembled from different sources, but the real answer is that the concept of reading only part of a file is very new to me, and it's taking time to catch up on the implications. Am user brain, file is file.

Noted, thank you. I will now be doing a dive into that file structure sometime in the near future.

@throwable-one Overkill for the application? Probably. Am I now going to play with implementing a small-scale version of that just to see if I can? Probably.