Skip to content

FileStream.Flush(flushToDisk: true) causes corrupt (truncated) files to be written on macOS + SMB share #124722

Closed as not planned

Description

@sschultze

Description

When calling Flush(flushToDisk: true) on a FileStream that was created on an SMB network share after writing data and before Dispose, the files written to the network share are corrupt (truncated) with a high chance.

That issue was reported by customers and it was very hard to find, but in the end very easily reproducable.

Reproduction Steps

Use macOS, connect to a network share with Finder (in my case on a Synology DS224+), and then run the following code.

using System.Globalization;
using System.Security.Cryptography;

namespace flush_to_disk;

class Program
{
    static void Main(string[] args)
    {
        var basePath = "/Volumes/abc";

        var data = new byte[64 * 1024 * 1024]; // 64 MB
        RandomNumberGenerator.Fill(data);

        for (var i = 0; i < 16; i++)
        {
            var path = Path.Combine(basePath, i.ToString(CultureInfo.InvariantCulture));
            using (var fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                fs.Write(data);
                fs.Flush(flushToDisk: true);
            }
        }
    }
}

Expected behavior

16 files with a size of exactly 64 MB each are created.

Actual behavior

16 files with sizes all over the place are created.

drwx------  1 stefan  staff     16384 Feb 22 12:09 ./
drwxr-xr-x  4 root    wheel       128 Feb 22 11:46 ../
-rwx------@ 1 stefan  staff      8196 Feb 22 12:08 .DS_Store*
-rwx------  1 stefan  staff  67108864 Feb 22 12:08 0*
-rwx------  1 stefan  staff  67108864 Feb 22 12:08 1*
-rwx------  1 stefan  staff  58720256 Feb 22 12:09 10*
-rwx------  1 stefan  staff  58982400 Feb 22 12:09 11*
-rwx------  1 stefan  staff  59244544 Feb 22 12:09 12*
-rwx------  1 stefan  staff  58720256 Feb 22 12:09 13*
-rwx------  1 stefan  staff  58720256 Feb 22 12:09 14*
-rwx------  1 stefan  staff  59506688 Feb 22 12:09 15*
-rwx------  1 stefan  staff  60817408 Feb 22 12:08 2*
-rwx------  1 stefan  staff  60817408 Feb 22 12:08 3*
-rwx------  1 stefan  staff  60817408 Feb 22 12:08 4*
-rwx------  1 stefan  staff  58720256 Feb 22 12:08 5*
-rwx------  1 stefan  staff  60817408 Feb 22 12:09 6*
-rwx------  1 stefan  staff  60817408 Feb 22 12:09 7*
-rwx------  1 stefan  staff  59244544 Feb 22 12:09 8*
-rwx------  1 stefan  staff  58720256 Feb 22 12:09 9*

Regression?

I don't know.

Known Workarounds

Remove the line fs.Flush(flushToDisk: true); Then files with exactly 64 MB each are created.

Configuration

  • .NET 10.0.3 (arm64)
  • macOS Tahoe 26.3
  • Synology DS224+

Other information

At first I thought that it could be a problem with macOS' SMB client, but then I found that the F_FULLFSYNC that .NET uses is actually used quite commonly by database engines - which are typically not written in .NET - and I suspect that anyone would have found this easily reproducable bug if it really was in macOS itself. So now I suspect that the error could actually be in .NET.

I was not able to reproduce this on Windows, but on Windows .NET's flush-to-disk implementation is different because F_FULLFSYNC doesn't even exist there.

Activity

  1. added
    untriaged
    on Feb 22, 2026
  2. changed the title [-]FileStream.Flush(flushToDisk: true) writes corrupt (truncated) files on macOS + SMB share[/-] [+]FileStream.Flush(flushToDisk: true) causes corrupt (truncated) files to be written on macOS + SMB share[/+] on Feb 22, 2026
  3. added
    in-pr
    and removed
    untriaged
    on Feb 22, 2026
  4. sschultze commented on Feb 22, 2026

    @sschultze
    Author

    I just let Gemini port this to version to Rust (with non-random data though), including the call to libc::fcntl(fd, libc::F_FULLFSYNC) that .NET does.

    Finding: The Rust version did not produce the error. All files exactly 64 MB. From my point of view, this is a strong indication that the error is indeed in .NET.

    Please note that I am not a Rust programmer, but the conversion looks pretty plausible to me.

    For reference:

    use std::fs::File;
    use std::io::Write;
    use std::os::unix::io::AsRawFd;
    use std::path::Path;
    
    fn main() -> std::io::Result<()> {
        let base_path = "/Volumes/abc";
        let size = 64 * 1024 * 1024; // 64 MB
    
        // Create "dirty" test data (not zeros) without external crates
        let mut data = vec![0u8; size];
        for (i, byte) in data.iter_mut().enumerate() {
            *byte = (i % 255) as u8; 
        }
    
        for i in 0..16 {
            let path = Path::new(base_path).join(i.to_string());
            println!("Writing and F_FULLFSYNC: {:?}", path);
    
            // FileMode.CreateNew equivalent
            let mut file = std::fs::OpenOptions::new()
                .write(true)
                .create_new(true) 
                .open(&path)?;
    
            // Write to OS Page Cache
            file.write_all(&data)?;
    
            // THE CRITICAL PART: Exact equivalent of .NET flushToDisk: true
            // This bypasses the SSD's volatile cache.
            full_fsync(&file)?;
        }
    
        Ok(())
    }
    
    /// Triggers macOS-specific F_FULLFSYNC via fcntl
    fn full_fsync(file: &File) -> std::io::Result<()> {
        let fd = file.as_raw_fd();
        unsafe {
            // F_FULLFSYNC is constant 51 on macOS
            let ret = libc::fcntl(fd, libc::F_FULLFSYNC);
            if ret == -1 {
                return Err(std::io::Error::last_os_error());
            }
        }
        Ok(())
    }
  5. stephentoub commented on Feb 22, 2026

    @stephentoub
    Member

    Hopefully if you also have it port the bug being fixed in #124725 you're also able to repro again?

  6. sschultze commented on Feb 22, 2026

    @sschultze
    Author

    @stephentoub If, in "my" Rust code, libc::fcntl(fd, libc::F_FULLFSYNC) would have failed, then I would have gotten an error. But I didn't, so I don't think that porting the code fixed in #124725 would make any difference.

    Also, why would an effectively ignored F_FULLFSYNC failure in the .NET code lead to truncated / corrupt files? From my naive point of view, the only bad thing that can happen is that there's no "full f-sync".

    But I see that there are error codes like EAGAIN or EBUSY. Perhaps differences between .NET's internals and the Rust version cause error codes like these, and some internal state corrupts, so that the close command is sent with unfinished data? Just guessing, I'm unfortunately not deep enough into the .NET internals.

  7. stephentoub commented on Feb 22, 2026

    @stephentoub
    Member

    why would an effectively ignored F_FULLFSYNC failure in the .NET code lead to truncated / corrupt files?

    Because the sync is what ensures data is actually flushed to disk. If the syscall returned an errno like AGAIN / EINTR suggesting a retry is needed, which is much more common with remote stores, it won't have been retried, so the system would think it successfully sync'd even though it didn't, and you end up with corruption (I assume by corruption you mean missing data).

  8. sschultze commented on Feb 22, 2026

    @sschultze
    Author

    Because the sync is what ensures data is actually flushed to disk. If the syscall returned an errno like AGAIN / EINTR suggesting a retry is needed, which is much more common with remote stores, it won't have been retried, so the system would think it successfully sync'd even though it didn't, and you end up with corruption (I assume by corruption you mean missing data).

    @stephentoub Thank you. I totally understand that when there's a ignored F_FULLFSYNC failure, the data might still not actually have been flushed to disk. But then you end up with the same situation as when Flush(flushToDisk: true) wasn't called at all - the data will be actually flushed to disk automatically after a few milliseconds. But, as I pointed out, in the latter case (no flush-to-disk) all files have the correct identical sizes, where with flush-to-disk, they don't.

    Is there probably a bug in the macOS SMB client that goes like this:

    • .NET performs a F_FULLFSYNC
    • The SMB client notices that there are some pending writes, so it sets some flag (like "didFullFSync"), starts sending, returns EAGAIN and sets some flag
    • .NET ignores the result and closes the file handle
    • The SMB client notices the flag ("didFullFSync") set above and thinks, okay, everything has been sent
    • The SMB client closes the connection, and the file is not complete yet

    Another workaround

    I just tried to add Thread.Sleep(5000) before the Flush(flushToDisk: true) and ran my reproduction code again. This also "fixes" the problem, most likely because 5s is enough time to perform all the pending writes before the F_FULLFSYNC.

  9. sschultze commented on Feb 22, 2026

    @sschultze
    Author

    I just checked out v10.0.3 and changed SystemNative_FSync to this (from the GitHub pull request #124725, but with an additional fprintf):

    int32_t SystemNative_FSync(intptr_t fd)
    {
        // Inside the function in pal_io.c
        fprintf(stderr, "DEBUG: Custom pal_io logic hit!\n");
    
        int fileDescriptor = ToFileDescriptor(fd);
    
        int32_t result;
    #if defined(TARGET_OSX) && HAVE_F_FULLFSYNC
        while ((result = fcntl(fileDescriptor, F_FULLFSYNC)) < 0 && errno == EINTR);
        if (result >= 0)
            return result;
        // F_FULLFSYNC is not supported on all file systems and handle types (e.g.,
        // network file systems, read-only handles). Fall back to fsync.
        // For genuine I/O errors (e.g., EIO), fsync will also fail and propagate the error.
    #endif
        while ((result = fsync(fileDescriptor)) < 0 && errno == EINTR);
        return result;
    }

    Then compiled with ./build.sh -subset libs.native -c Release and "integrated" the result with

    export DYLD_LIBRARY_PATH="/Users/stefan/nobackup/runtime/artifacts/bin/native/net10.0-osx-Release-arm64/"
    

    Result: The DEBUG: Custom pal_io logic hit! string is written to the console 16x, so the code change is used.

    But unfortunately, the file sizes on the SMB share are still not correct. So the code change doesn't help in my case.

    drwx------  1 stefan  staff     16384 Feb 22 23:16 ./
    drwxr-xr-x  4 root    wheel       128 Feb 22 14:18 ../
    -rwx------@ 1 stefan  staff      8196 Feb 22 21:45 .DS_Store*
    -rwx------  1 stefan  staff  60817408 Feb 22 23:15 0*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:15 1*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:16 10*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:16 11*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:16 12*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:16 13*
    -rwx------  1 stefan  staff  67108864 Feb 22 23:16 14*
    -rwx------  1 stefan  staff  67108864 Feb 22 23:16 15*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:15 2*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:15 3*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:16 4*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:16 5*
    -rwx------  1 stefan  staff  60817408 Feb 22 23:16 6*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:15 7*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:16 8*
    -rwx------  1 stefan  staff  58720256 Feb 22 23:16 9*
    
  10. sschultze commented on Feb 22, 2026

    @sschultze
    Author

    Additional experiment 1: No-op

    Changed the function SystemNative_FSync to just do a fprintf and return 0. Result: File sizes are all correct.

    Additional experiment 2: Only fsync

    Changed it to not try F_FULLFSYNC, but only fsync.

    int32_t SystemNative_FSync(intptr_t fd)
    {
        // Inside the function in pal_io.c
        fprintf(stderr, "DEBUG: Custom pal_io logic hit - VERSION 3 FSYNC!\n");
    
        int fileDescriptor = ToFileDescriptor(fd);
    
        int32_t result;
        while ((result = fsync(fileDescriptor)) < 0 && errno == EINTR);
        return result;
    }

    Result: Same. File sizes are all correct.

    PS: Never thought it would be that easy to compile my custom version. Really really cool!

  11. tmds commented on Feb 23, 2026

    @tmds
    Member

    I think the rust reproducer (#124722 (comment)) was meant to behave like current .NET, but it didn't actually fail?

    We've had issues with samba and how .NET uses file locks to implement FileShare on non-Windows. Does export DOTNET_SYSTEM_IO_DISABLEFILELOCKING=1 make a difference?

  12. sschultze commented on Feb 23, 2026

    @sschultze
    Author

    @tmds Yes, you're right, the rust reproducer was meant to behave like .NET 10.0.3, but it didn't fail.

    Just tested DOTNET_SYSTEM_IO_DISABLEFILELOCKING=1 dotnet run. With this configuration, the resulting file sizes are indeed correct.

    Do you have any details on this issue with Samba? Can I expect FileShare.None to work with Samba when I don't do the Flush(flushToDisk: true)?

  13. 2 remaining items

  14. sschultze commented on Feb 24, 2026

    @sschultze
    Author

    @tmds @stephentoub @adamsitnik Here the final update on my investigation. I converted my code to direct libc calls in order to have better control (see below).

    Findings

    • The error (wrong file sizes) is reproducable with the direct libc calls, so there is no "error" in .NET.
    • Changing F_FULLFSYNC to a standard fsync "solves" the problem. So the problem is really the F_FULLFSYNC.
    • Changing the lock from LOCK_EX to LOCK_SH has no positive effect. Wrong file sizes too. So the lock type doesn't matter - both create a problem together with F_FULLFSYNC.

    Summary

    The combination of

    • macOS
    • Synology NAS (Samba server)
    • flock with either LOCK_EX or LOCK_SH (combined with LOCK_NB like in .NET)
    • F_FULLFSYNC

    has a high chance of creating truncated files.

    Code

    using System.Globalization;
    using System.Runtime.InteropServices;
    using System.Security.Cryptography;
    
    namespace flush_to_disk;
    
    unsafe class Program
    {
        private const string Libc = "libc";
    
        public const int O_WRONLY = 0x0001;
        public const int O_CREAT = 0x0200;
        public const int O_TRUNC = 0x0400;
        public const int O_CLOEXEC = 0x1000000;
    
        public const int F_FULLFSYNC = 51;
    
        public const int LOCK_SH = 1; // Shared
        public const int LOCK_EX = 2; // Exclusive
        public const int LOCK_NB = 4; // Non-blocking flag
        public const int LOCK_UN = 8; // Unlock
    
        [DllImport(Libc, EntryPoint = "open", SetLastError = true, CharSet = CharSet.Ansi)]
        public static extern int Open(string pathname, int flags, int mode);
    
        [DllImport(Libc, EntryPoint = "write", SetLastError = true)]
        public static unsafe extern nint Write(int fd, byte* buf, nuint count);
    
        [DllImport(Libc, EntryPoint = "fcntl", SetLastError = true)]
        public static extern int Fcntl(int fd, int cmd, int arg);
    
        [DllImport(Libc, EntryPoint = "fsync", SetLastError = true)]
        public static extern int Fsync(int fd);
    
        [DllImport(Libc, EntryPoint = "flock", SetLastError = true)]
        public static extern int Flock(int fd, int operation);
    
        [DllImport(Libc, EntryPoint = "close", SetLastError = true)]
        public static extern int Close(int fd);
    
        static void Main(string[] args)
        {
            var basePath = "/Volumes/abc";
    
            var data = new byte[64 * 1024 * 1024]; // 64 MB
            RandomNumberGenerator.Fill(data);
    
            for (var i = 0; i < 16; i++)
            {
                var path = Path.Combine(basePath, "test-" + i.ToString(CultureInfo.InvariantCulture));
                Console.WriteLine(path);
    
                var fd = Open(path, O_WRONLY | O_CREAT | O_TRUNC, 0x644);
                if (fd == -1)
                {
                    throw new IOException($"Could not open file '{path}'. errno: {Marshal.GetLastWin32Error()}");
                }
    
                try
                {
                    if (Flock(fd, LOCK_EX | LOCK_NB) == -1)
                    {
                        throw new IOException($"Could not acquire flock: {Marshal.GetLastWin32Error()}");
                    }
    
                    fixed (byte* pData = data)
                    {
                        var written = Write(fd, pData, (nuint)(data.Length));
                        if (written == -1)
                        {
                            throw new IOException($"write failed: {Marshal.GetLastWin32Error()}");
                        }
                        if (written != data.Length)
                        {
                            throw new Exception($"Only {written} bytes written");
                        }
                    }
    
                    if (Fcntl(fd, F_FULLFSYNC, 0) == -1)
                    {
                        throw new IOException($"fcntl F_FULLFSYNC failed: {Marshal.GetLastWin32Error()}");
                    }
    
                    // if (Fsync(fd) == -1)
                    // {
                    //     throw new IOException($"fsync failed. errno: {Marshal.GetLastWin32Error()}");
                    // }
                }
                finally
                {
                    Flock(fd, LOCK_UN);
                    Close(fd);
                }
            }
        }
    }
  15. tmds commented on Feb 24, 2026

    @tmds
    Member

    @sschultze thanks for investigating and figuring out what exactly triggers the problem!

    Changing F_FULLFSYNC to a standard fsync "solves" the problem. So the problem is really the F_FULLFSYNC.

    It seems the F_FULLFSYNC causes pending writes to get discarded.

    So a fix for .NET can be to not use F_FULLFSYNC when the file descriptor is for one of network file systems that we are already treating special in CanLockTheFile.

  16. sschultze commented on Feb 24, 2026

    @sschultze
    Author

    @tmds Thank you for taking care of that!

    So a fix for .NET can be to not use F_FULLFSYNC when the file descriptor is for one of network file systems that we are already treating special in CanLockTheFile.

    This seems like a plausible solution to the problem to me.

    For my specific app I will disable file locking entirely. Since it isn't required for my use case, the potential for conflict seems to outweigh the benefits.

  17. tmds commented on Feb 24, 2026

    @tmds
    Member

    Since your NAS runs Linux, the locking on the system is "advisory" which means it is only respected by those who care to check. So even when .NET would do the locking, non-.NET applications will very likely not be aware.

  18. sschultze commented on Feb 24, 2026

    @sschultze
    Author

    Since your NAS runs Linux, the locking on the system is "advisory" which means it is only respected by those who care to check. So even when .NET would do the locking, non-.NET applications will very likely not be aware.

    Yes, this is also what I found. In only brings some value in quite specific use cases.

  19. adamsitnik commented on Jul 15, 2026

    @adamsitnik
    Member

    It seems the F_FULLFSYNC causes pending writes to get discarded.

    I agree. Overall it seems to be macOS/SMB bug. But since it can have very bad consequences for our users, I think it's reasonable to detect macOS+SMB and just use fsync rather than F_FULLFSYNC.

  20. added this to the 11.0.0 milestone on Jul 15, 2026
  21. adamsitnik commented on Jul 24, 2026

    @adamsitnik
    Member

    We have prepared the workaround fix (#130779), but was unable to reproduce the issue (#130779 (comment)).

    Closing as won't fix. I think it would be best to provide a small C repro and report the bug in Samba directly. Thanks!

  22. removed this from the 11.0.0 milestone on Jul 24, 2026
  23. removed
    in-pr
    on Jul 24, 2026
  24. locked and limited conversation to collaborators on Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions