Skip to content

buf_file: release file handles for queued chunks - #5684

Open
git-jxj wants to merge 5 commits into
fluent:masterfrom
git-jxj:fix-queued-chunk-fds-20261125
Open

git-jxj wants to merge 5 commits into
fluent:masterfrom
git-jxj:fix-queued-chunk-fds-20261125

Conversation

@git-jxj

@git-jxj git-jxj commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Which issue(s) this PR fixes:
Fixes #5494
Refs #3040

What this PR does / why we need it:

A file buffer keeps the data and metadata files open after queueing a chunk. Restarting with an existing backlog also holds one open file per restored queued chunk. A downstream outage can therefore leave Fluentd without enough descriptors to create chunks or drain the queue.

Close both files after a successful enqueue. During restart, open and immediately close each queued data file, including legacy v0.12 chunks without metadata. A failed open stops startup and leaves the unreadable data file on disk. Restore queued chunks from file stats and metadata, and open chunk data on demand for output. Descriptor exhaustion while reading metadata still propagates. Other metadata read errors use broken-chunk recovery. The reader registry lets abandoned enumerators release their descriptors while close and purge can still interrupt live reads.

With a Linux process limit of 32 descriptors, the previous behavior hit EMFILE while building a backlog and recovered only 26 of 64 preexisting chunks. With this change, both scenarios drain all 64 records exactly once and release all queued bytes. The regression tests cover text, gzip and zstd, legacy chunks, failed opens during startup, and cleanup after a reader raises.

Docs Changes:
None.

Release Note:
File buffers release the file descriptors of queued chunks, so a large backlog can be recovered without keeping a descriptor open for each chunk.

Signed-off-by: xinjun.jiang <xinjun.jiang@daocloud.io>

@Watson1978 Watson1978 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this. Not keeping a descriptor open for every queued chunk is a clear improvement.

I checked it with out_forward and a file buffer while the receiver was down. With 75 queued chunks, master held 158 descriptors and this PR held 8. Then I restarted with ulimit -n 48. Master failed to open the metadata of 36 chunks and treated them as broken. The backup of each one also failed, and the broken chunk cleanup deleted the original files. This PR kept every chunk and delivered all 300 records exactly once after the receiver came back.

I left three requests inline. The first one keeps master's handling of a .meta that fails to read for a reason other than running out of descriptors. The second one keeps master's behavior when a chunk is purged while it is being read. The third one makes the new test pass when the file runs on its own.

Comment thread lib/fluent/plugin/buffer/file_chunk.rb Outdated
Comment on lines +382 to +385
# Only malformed metadata should trigger broken-chunk backup and removal.
bindata = File.binread(@meta_path)
begin
restore_metadata(File.open(@meta_path){|f| f.set_encoding(Encoding::ASCII_8BIT); f.binmode; f.read })
restore_metadata(bindata)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MUST: When File.binread(@meta_path) raises while a queued chunk is restored, the error now escapes FileBuffer#resume and the buffer cannot start. This is not limited to running out of descriptors. On master, the metadata was opened and read inside the begin block that turns errors into FileChunkError. So an error such as EIO or EISDIR made FileBuffer#resume treat that one chunk as broken, back up its data file, and restore the others.

To reproduce it, I put two queued chunks in the buffer path and replaced one .meta with a directory. On master, Fluentd logs "found broken chunk file during resume", backs up that chunk's data file, and flushes the other chunk. With this PR, the worker exits with Errno::EISDIR and restarts again and again (more than 20 times in 12 seconds), so nothing in that output is flushed.

Could you re-raise only descriptor exhaustion and keep the broken chunk handling for other errors? This keeps the EMFILE fix from the description. With the change below, the case above behaves like master, and a restart with ulimit -n 48 still keeps every chunk.

Suggested change
# Only malformed metadata should trigger broken-chunk backup and removal.
bindata = File.binread(@meta_path)
begin
restore_metadata(File.open(@meta_path){|f| f.set_encoding(Encoding::ASCII_8BIT); f.binmode; f.read })
restore_metadata(bindata)
begin
restore_metadata(File.binread(@meta_path))
rescue Errno::EMFILE, Errno::ENFILE
# Running out of descriptors does not mean the chunk is broken.
raise

A test next to the EMFILE one would cover this. It fails without the change:

    test 'handles a metadata read error other than running out of descriptors as a broken chunk' do
      stub(File).binread(@enqueued_path + '.meta') { raise Errno::EIO }

      assert_raise(Fluent::Plugin::Buffer::FileChunk::FileChunkError) do
        @klass.new(gen_metadata, @enqueued_path, :queued)
      end
    end

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metadata read failures now go through broken-chunk recovery, with EMFILE and ENFILE still propagated. The regression checks that an EIO chunk is backed up and the healthy chunk still loads.

Comment thread lib/fluent/plugin/buffer/file_chunk.rb Outdated

# Queued chunks normally have no open handles. A failed rename can
# leave the original handle open so committed data remains readable.
return File.open(@path, 'rb') { |file| yield file } unless @chunk

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MUST: A reader opened here keeps reading the chunk after it is purged. On master, #purge and #close closed the shared handle, so a reader in progress failed. This changes what the bundled out_forward does when a retry overlaps a late ACK.

I reproduced this on Linux with require_ack_response true and flush_thread_count 2. The first send completed, but its ACK was still outstanding when delayed_commit_timeout expired. Fluentd requeued the chunk and started a retry. I then returned the first ACK while the retry was sending the chunk body.

  • On master, the in-progress copy failed, and the receiver never got a second complete frame.
  • With this PR, the receiver got two complete frames with the same chunk ID and payload.

Windows has one more problem with this PR. In a separate FileChunk test on Windows 10 with Ruby 3.4, purging a queued chunk while another thread held its data file open failed with Errno::EACCES. Both files stayed on disk after the buffer had dropped the chunk, so the buffer can restore the chunk and send it again after a restart.

Could you keep master's behavior here? Please close any underlying chunk data files that are still in use by #open or #read when a queued chunk is purged or closed. Here is one way that I tested on Linux and Windows. It keeps the open files in a list, and close_file_handles closes them. It checks closed? and opens the file under the same lock, so a purge cannot slip in between. File::SHARE_DELETE lets Windows delete a file that a reader still has open. It also reads @chunk once, so a purge during a read of a staged chunk raises IOError as on master, not NoMethodError.

--- a/lib/fluent/plugin/buffer/file_chunk.rb
+++ b/lib/fluent/plugin/buffer/file_chunk.rb
@@ -45,6 +45,8 @@ module Fluent
           @permission = perm.is_a?(String) ? perm.to_i(8) : perm
           @bytesize = @size = @adding_bytes = @adding_size = 0
           @chunk = @meta = nil
+          @readers = []
+          @readers_mutex = Mutex.new
 
           case mode
           when :create then create_new_chunk(path, @permission)
@@ -398,6 +400,9 @@ module Fluent
           @chunk&.close
           @meta&.close
           @chunk = @meta = nil
+          # Like the shared handle on master, stop readers of a closed or purged chunk.
+          readers = @readers_mutex.synchronize { @readers.dup.tap { @readers.clear } }
+          readers.each(&:close)
         end
 
         def open_chunk
@@ -405,13 +410,28 @@ module Fluent
 
           # Queued chunks normally have no open handles. A failed rename can
           # leave the original handle open so committed data remains readable.
-          return File.open(@path, 'rb') { |file| yield file } unless @chunk
+          if (chunk = @chunk)
+            chunk.seek(0, IO::SEEK_SET)
+            begin
+              return yield chunk
+            ensure
+              chunk.seek(0, IO::SEEK_END) if staged?
+            end
+          end
 
-          @chunk.seek(0, IO::SEEK_SET)
+          file = nil
           begin
-            yield @chunk
+            @readers_mutex.synchronize do
+              raise IOError, 'closed stream' if closed?
+              file = File.open(@path, File::RDONLY | File::SHARE_DELETE, binmode: true)
+              @readers << file
+            end
+            yield file
           ensure
-            @chunk.seek(0, IO::SEEK_END) if staged?
+            if file
+              file.close
+              @readers_mutex.synchronize { @readers.delete(file) }
+            end
           end
         end
 

This test fails on Linux and Windows without such a change and passes with it:

  test 'stops readers and removes the files when a queued chunk is purged' do
    chunk = @klass.new(gen_metadata, gen_path('queued.*.log'), :create)
    chunk.append(['record'])
    chunk.commit
    chunk.enqueued!
    path = chunk.path
    meta_path = chunk.meta_path

    chunk.open do |io|
      assert_equal 'r', io.read(1)
      chunk.purge
      assert_raise(IOError) { io.read(1) }
    end
    assert_false File.exist?(path)
    assert_false File.exist?(meta_path)
  end

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

close and purge now close active readers, and the Windows reader enables delete sharing. In the late-ACK replay, purging the chunk interrupted the retry before it sent a second complete frame.

end
assert_true reader.closed?

output = StringIO.new

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SHOULD: StringIO.new uses the default external encoding, so this assertion fails when the file runs without -Eascii-8bit:ascii-8bit. rake test passes that option. But bundle exec ruby -Ilib -Itest test/plugin/test_buffer_file_chunk.rb, the command in AGENTS.md, fails for text, gzip and zstd with LANG=C.UTF-8. Other tests in this file set the encoding explicitly.

Suggested change
output = StringIO.new
output = StringIO.new
output.set_encoding(Encoding::ASCII_8BIT)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test now uses a binary StringIO and passes on its own under a UTF-8 locale.

Signed-off-by: xinjun.jiang <xinjun.jiang@daocloud.io>
@git-jxj

git-jxj commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Could a maintainer approve the Test workflow for 19080622b35d? I'd like to verify the queued chunk reader cleanup on Windows.

@Watson1978 Watson1978 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update. The three points from my previous review are addressed. I checked them on Linux and on Windows 10.

This change affects every user of the file buffer, so we need to verify it carefully before merging.

I left two more requests inline. The first one is a problem with the reader list that I asked for last time, sorry about that. The second one is about restoring a queued chunk whose data file cannot be read. I looked at this case in my first review, but I missed its effect on the healthy chunks behind it. It has two comments because the check is needed in two places.

Comment thread lib/fluent/plugin/buffer/file_chunk.rb Outdated

# Allow deletion on Windows even if a native read is still unwinding.
file = File.open(@path, File::RDONLY | File::SHARE_DELETE, binmode: true)
@readers << file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MUST: The reader list keeps a reader open until #purge or #close, even when the reader never reaches the ensure below. This happens when an output reads only the first event with an external enumerator, such as chunk.enum_for(:msgpack_each).next, and then drops the enumerator. Its fiber stays suspended inside the open block, so the ensure does not run. Without the list, GC would close the dropped File. With the list, it stays open.

I reproduced it on Linux with one queued chunk. After 200 calls of chunk.enum_for(:msgpack_each).next and full GCs, this PR had 200 more descriptors open. Master and the previous commit (db16f14) had no extra descriptors. With five descriptors already open and a limit of 32, 27 calls succeeded and the 28th failed with Errno::EMFILE. If each retry drops another enumerator for the same queued chunk, the descriptors pile up until the chunk is purged or closed.

This comes from the reader list I asked for in my previous review, sorry about that. Could you change the list so that it does not keep readers alive by itself? A dropped reader should be closed by GC, as in the previous commit (db16f14). #purge and #close should still close the underlying chunk data files that are still in use, as in this commit. The decompressed temporary files for compressed: :text do not need to change. One way is ObjectSpace::WeakMap (Fluentd requires Ruby 3.3 or later). When I tried it, it fixed the descriptor leak on Linux. On Windows 10, purging during a read still removed both files and stopped the reader.

A test for the dropped reader depends on GC, so I am fine without one if it cannot be made stable.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reader list now uses a weak map. Dropping 200 enumerators and running GC left the descriptor count unchanged. close and purge still close live readers.

Could a maintainer approve the Test workflow so we can recheck reader cleanup on Windows?

@commit_position = @chunk.size
stat = File.stat(@path)
@bytesize = stat.size
raise FileChunkError, "enqueued file chunk is empty" if @bytesize.zero?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MUST: Restoring a queued chunk no longer checks that its data file can be read. File.stat succeeds even when the file has no read permission. On master, File.open(@path, 'rb') raised Errno::EACCES here, so Fluentd stopped at startup and kept the files on disk.

With this PR, the buffer starts, and every flush of that chunk fails with Errno::EACCES. With flush attempts running one at a time, the unreadable chunk goes back to the front after each failed attempt, so the healthy chunk behind it is never flushed. When the retry limit is reached, clear_queue! removes the whole queue. With the default evacuation settings, the healthy chunk is copied to the evacuation directory first. The unreadable chunk cannot be copied, and its files are then removed.

I reproduced it on Linux as a non-root user with two queued chunks and chmod 0 on the data file of the first one, with retry_max_times 0. Master failed to start with Errno::EACCES and kept both chunks. This PR started and removed both chunks from the buffer directory, and only the healthy one was in the evacuation directory. This can happen after the user that runs Fluentd changes, for example.

Could you keep master's behavior here? A nonempty queued chunk whose data file cannot be read should raise Errno::EACCES during restore and leave its files in place. Please keep the existing empty file check first, and check the permission without keeping a descriptor open. File.readable? worked for this case on Linux. The v0.12 branch of load_existing_staged_chunk needs a similar check (see the next comment). Please also add a test for the unreadable queued chunk. chmod 0 does not make a file unreadable for root or on Windows, so the test needs to be skipped there.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Restore now raises Errno::EACCES for a nonempty unreadable queued chunk before it enters the flush queue. The startup regression verifies that both the unreadable and healthy chunks stay on disk.

@chunk.set_encoding(Encoding::ASCII_8BIT)
@chunk.binmode
@chunk.seek(0, IO::SEEK_SET)
stat = File.stat(@path)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MUST: This v0.12 branch, for a .b file without a .meta file, needs the read permission check too. On master, an unreadable file stopped restore here with Errno::EACCES. Please do not add the empty file check here. On master, a readable zero-byte file in this branch is still restored as queued.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The v0.12 metadata-less restore now checks readability too. Readable zero-byte chunks still restore as queued, and the startup regression covers an unreadable v0.12 chunk.

Signed-off-by: xinjun.jiang <xinjun.jiang@daocloud.io>
…fds-20261125

Signed-off-by: xinjun.jiang <xinjun.jiang@daocloud.io>
@Watson1978

Watson1978 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the update. In my last review, I wrote that this change affects every user of the file buffer, so we need to verify it carefully before merging. Your replies say what changed, but not how you verified that existing users are not affected. Could you report the verification behind that judgment? Please include:

  • The test commands you ran, with the OS and Ruby version. Did you run the full test suite, or only some files?
  • How you checked the three points from my last review: the dropped enumerator, the unreadable queued chunk, and the unreadable v0.12 chunk. The steps or a short script would help. The chmod 0 tests are skipped as root, so did you run them as a non-root user?
  • Whether you ran the earlier scenarios again on bb0794c. These are the backlog with a limit of 32 descriptors, the late ACK replay with out_forward, and the metadata read error.

If you did not check something, please say so.

@git-jxj

git-jxj commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

@Watson1978 I reran the checks from your comment on bb0794cf. The runs used Ubuntu 22.04.5 LTS (x86_64), Ruby 3.3.6 and Bundler 2.5.22.

Full suite

I ran the full suite from separate clean checkouts at bb0794cf and its upstream base 6a48ae6, both as UID 65534 with the same locked dependencies. The relocated Ruby runtime was configured to load the locked JSON 3.1.0. The command was

ruby -S bundle exec rake test TESTOPTS="-v --report-slow-tests --no-show-detail-immediately"
Commit Tests Assertions Failures Errors Pending Omissions
bb0794cf 5,021 16,322 82 13 1 37
6a48ae6 5,011 16,264 82 13 1 37

Both full runs exited 1. All 95 failures and errors match by test name and result type. Both unreadable-file tests and the metadata-read regression also passed in the PR's full run.

Targeted checks on bb0794cf

  • Dropped enumerators. I ran ruby -S bundle exec ruby -Ilib "$repro/second-review/gc-repro.rb". I queued a MessagePack chunk, held one enumerator open, and called chunk.enum_for(:msgpack_each).next on 200 more enumerators that I discarded. After three full GCs, the count of /proc/self/fd entries pointing at that chunk stayed at 1. The retained enumerator accounts for that descriptor.

  • Unreadable queued chunk and v0.12 chunk. I ran the command below as real and effective UID 65534. Both cases ran, with 2 tests, 11 assertions and zero failures, errors or omissions. Each creates an unreadable chunk and a healthy queued chunk, applies chmod 000 to the unreadable chunk, then checks that startup raises EACCES and all the original buffer files remain. The v0.12 case removes the .meta sidecar first.

    ruby -S bundle exec ruby -Ilib -Itest test/plugin/test_buf_file.rb \
      --name '/startup preserves buffered files when a queued chunk cannot be read/' \
      --verbose=verbose
  • Backlog with 32 descriptors. I seeded 64 chunks on the pre-fix checkout (affb1d0, limit 1024), then ran the accumulation and restart paths below from bb0794cf. Each drained all 64 distinct records exactly once, left zero queued bytes and removed the chunk files. The script reported 6 entries in /proc/self/fd both after queueing and after draining.

    (ulimit -S -n 1024 && ruby -S bundle exec ruby -Ilib "$repro/reproduce.rb" seed "$scratch/seed")
    (ulimit -S -n 32 && ruby -S bundle exec ruby -Ilib "$repro/reproduce.rb" accumulate "$scratch/accumulate")
    (ulimit -S -n 32 && ruby -S bundle exec ruby -Ilib "$repro/reproduce.rb" resume "$scratch/seed")
  • Late ACK. I ran ruby -S bundle exec ruby -Ilib "$repro/review-scope/replay-forward.rb" after "$scratch/forward". The replay uses the real out_forward send, rollback and ACK processing paths and pauses a 1 MiB retry at its first body write. A late success ACK purged the chunk. The retry stopped with Errno::EBADF, the in-memory receiver got no second complete frame, and the data and metadata files were gone.

  • Metadata read errors. I ran ruby -S bundle exec ruby -Ilib -Itest test/plugin/test_buf_file.rb -n '/metadata read error/' (1 test, 8 assertions, passed). It injects EIO and checks that the healthy chunk is restored and the bad chunk's data is backed up byte for byte. I also ran ruby -S bundle exec ruby -Ilib "$repro/watson-20261127/replays/metadata-directory.rb" "$scratch/metadata-directory" with a directory at the bad chunk's .meta path. It hit EISDIR, backed up the bad chunk's data and restored the healthy chunk. The directory itself remained on disk.

In the replay commands, $repro is the directory containing my local scripts and $scratch is a temporary directory for the fixtures. The late-ACK replay used an in-memory receiver. I did not run a live two-node Forward replay or rerun the current commit on Windows or macOS.

@Watson1978

Copy link
Copy Markdown
Contributor

Thanks for the detailed report.

I cannot rely on the full suite results yet. 95 tests also fail or error on master in your environment. This is likely due to the setup, such as the relocated Ruby runtime with a pinned JSON gem and running as UID 65534. If some of those tests cover the buffer or outputs, a regression there would be hidden.

The other checks are short scripts in one process on one environment. This change affects every user of the file buffer. So I think we need at least stress tests and long-running tests on each environment (Linux, Windows, and macOS) before merging. For example, run a real Fluentd process with a file buffer and out_forward. Build up a large backlog while the receiver is down, restart Fluentd during the backlog, and then let it drain. Please check that open file descriptors and memory stay bounded, that all records are delivered, and how throughput compares with master.

@git-jxj

git-jxj commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@Watson1978 I reran the stress test with separate Fluentd sender and receiver processes and a file buffer using out_forward. Each run queued 65,536 sequenced records (99 MiB), restarted the sender with the receiver still down, then brought the receiver back after about six minutes. The PR and its exact base both delivered every ID with the payload intact on all three platforms.

Platform Offline peak FDs or handles, base → PR Offline peak RSS, base → PR Throughput, base → PR
Linux 3,757 → 14 FDs 83 → 74 MiB 11.6k → 11.5k records/s, six interleaved trials. Current master was 10.6k.
macOS arm64 3,759 → 14 FDs 97 → 97 MiB 7,854 → 7,955 records/s, median of three online trials.
Windows x64 4,088 → 324 handles 103 → 104 MiB 342 → 345 records/s during backlog drain, one run per revision including receiver startup.

Linux and macOS delivered without duplicates at a 60-second ACK timeout. On Windows the base produced 2,150 duplicate records during backlog drain and the PR produced zero. Both Windows revisions then timed out with pending records and duplicates in the unthrottled online stress step, so the Windows throughput above is for the backlog drain. The earlier Linux run with a 5-second ACK timeout saw duplicates on both the PR and current master. At a 128-FD limit the Linux base exhausted buffer-file FDs during queueing, while the PR delivered all 8,192 records after two transient socket-open errors during drain.

The Linux full suite also passed in a standalone run with a native YJIT-enabled Ruby 3.3.14, with 5,021 tests, 17,861 assertions, zero failures or errors, one pending and 37 omissions.

macOS run · Windows run

@Watson1978 Watson1978 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update. The dropped enumerator case is fixed, and an unreadable queued chunk, including a v0.12 chunk, now stops startup when its permission bits deny read. I checked them on Linux and on Windows 10, also after merging the current master.

One restore case remains, where the readability check succeeds but opening the file fails. It is the only code change I am asking for, and I left it inline. It comes from the File.readable? check that I gave as an example last time, sorry about that.

Thanks also for the detailed stress test. Separate processes, sequenced IDs and a comparison with the exact base are what I hoped for. The offline FD numbers clearly show the improvement.

Some parts I asked for are still missing, and some results are hard to judge:

  • Configuration. I could read the settings of the macOS and Windows runs in forward_validation.py on your validation branch. They use out_forward with require_ack_response and a file buffer with chunk_limit_size 64k and flush_thread_count 4, without compress. Please share the configurations and scripts of the Linux runs, or say that they are the same. For the run with the 128-FD limit, please also share the command line and the effective soft and hard limits.
  • Long-running test. Each run had one outage of about six minutes. Please run for several hours with steady input and several outages and recoveries, and sample FDs and RSS every minute or so. This would help detect gradual growth across recovery cycles.
  • During and after the drain. The uploaded logs of the macOS and Windows runs already show the peaks during the drain and the counts after it. Please report the same for the Linux runs. At the 128-FD limit, what held the descriptors when the PR could not open a socket? Were they sockets waiting for an ACK, or chunk files? If you did not record it, please say so.
  • Restart during the drain. Please restart the sender after delivery has begun and while chunks are still queued. After recovery, check all IDs and report duplicates separately.
  • Settings. Please include runs with compress gzip in <buffer> (and the default compress in out_forward, so the chunks are decompressed when read). Please also run with total_limit_size and overflow_action drop_oldest_chunk, so that queued chunks are purged while others are read. Only in that run, count the dropped records as expected.
  • Windows. Both revisions timed out in the first online trial, and each was run once. By the time it timed out, the PR had delivered 1,563 duplicate records and the base 32, so the comparison is not conclusive yet. Please find a setting where the base completes, for example with throttled input or a longer ACK timeout, and compare a few runs. The PR peaked at 324 handles while offline and was back at 314 after the drain, the same post-drain count as the base.

For throughput, please add the min and max of the trials. On Linux, you reported 11.6k records/s for the base and 10.6k for current master, about 9% apart, so I would like to see the spread across the six trials. On macOS, the backlog drain took 12.8 s with the PR and 11.0 s with the base, one run each. Please include the drain time with its spread too.

The rates in your runs are also low or short compared with production. During the 180-second publish phase, the sender received about 0.56 MB/s of payload (1,536 bytes per record). The macOS online trials lasted 4.0 to 5.2 s, and the Windows drain ran at about 0.5 MB/s. I have seen about 3 MB/s of steady input in a production setup. Please also run with a steady input close to that, with a larger chunk_limit_size such as 8 MB as well as 64 KB. At 3 MB/s, 180 seconds of input is about 540 MB of payload, more than your total_limit_size 512m, so please size the buffer so that these runs do not overflow.

If you cannot run something, for example a long run on the macOS or Windows runners, please say so.

Comment thread lib/fluent/plugin/buffer/file_chunk.rb Outdated
stat = File.stat(@path)
@bytesize = stat.size
raise FileChunkError, "enqueued file chunk is empty" if @bytesize.zero?
raise Errno::EACCES, @path unless File.readable?(@path)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MUST: File.readable? asks for the permission but does not open the file, so it can return true when the open fails. I reproduced this in two ways.

  • On Windows 10, File.readable? looks only at the file attributes, not at the ACL. A queued chunk whose ACL denies read to the user was restored by this PR, and the first read failed with Errno::EACCES. On master, the restore stopped with Errno::EACCES.
  • On Linux, I denied read of one queued chunk with Landlock and restarted Fluentd with a healthy chunk and retry_max_times 0. Master stopped at startup with Errno::EACCES and kept all buffer files. This PR started and hit the retry limit. The original buffer directory was empty, and only the healthy chunk was recovered in the evacuation directory. The same happened for a v0.12 chunk at line 371.

I gave File.readable? as an example last time, sorry about that. Could you open the file and close it right away instead, so that the OS decides and raises the real error? This does not keep a descriptor open. The same applies to line 371. When I tried it, both cases above behaved like master, and the tests in this PR passed on Linux and Windows. In my three-run Linux benchmark, restoring 50,000 queued chunks took about 4% longer than with File.readable?, which was still faster than master.

If you add Windows coverage, please check that opening the data file is denied, that buffer startup raises EACCES, and that both chunks remain on disk. The current test also expects File.readable? to return false, which does not hold for an ACL on Windows.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both restore paths now open the data file in binary read mode and close it immediately. An open failure propagates from startup, including for a legacy v0.12 chunk without metadata. The regression test simulates File.open raising EACCES while File.readable? returns true and checks that both chunks and any metadata are preserved byte for byte. It fails on the previous head in both cases and passes with this change.

I also reproduced both cases with a real NTFS deny ACL on Windows Server 2025. File.readable? returned true for the denied file. The previous head started and failed on the first read. The exact base and the updated head both raised EACCES at startup and kept both chunks and any metadata unchanged. Windows ACL run

Signed-off-by: xinjun.jiang <xinjun.jiang@daocloud.io>
@git-jxj

git-jxj commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

I compared the saved Linux and macOS configs. The six-minute run used the same sender and receiver settings as the macOS run, with generated paths and ports. Both used ACKs with a 60 s timeout, 64 KiB file chunks, four flush threads, and default compression. The Linux six-minute run used a soft/hard descriptor limit of 8,192/1,048,576. Configurations and workload settings

Linux revision Drain time, 65,536 records Sender FDs, peak during drain → after Sender RSS, peak during drain → after Online throughput, min / median / max (records/s, 6 trials)
PR as tested (bb0794c) 4.632 s 621 → 11 62.9 → 63.4 MiB 9,806 / 11,539 / 18,022
Exact base (6a48ae6) 4.216 s 2,589 → 11 65.0 → 65.0 MiB 9,648 / 11,558 / 15,216
Then-current master (e1732e8) 3.725 s 2,109 → 11 90.2 → 90.5 MiB 9,578 / 10,600 / 14,206

For the earlier 128-FD run, the effective soft/hard limits were 128/1,048,576. The harness used the daemon command below for each launch, with Ruby 3.3.6 and a 5 s ACK timeout. At the restart boundary the PR had 225 queued chunks and 11 open FDs. All 8,192 IDs arrived intact without duplicates. The sender logged two socket(2) EMFILE failures and recovered. The one-second sampler missed the FD tables at both errors. The mix of sockets and chunk files at those two instants remains unknown.

ulimit -Sn 128
ruby -S bundle exec ruby -I "$source/lib" "$source/bin/fluentd" --no-supervisor \
  -c "$config" -o "$log"

I also ran the revised head (2637b3d) against the exact base (6a48ae6) on Linux using separate sender and receiver processes. In the timed restart, the receiver had observed 128 records and 912 PR / 907 base chunks remained queued when I stopped the sender. Both revisions eventually delivered all 29,184 unique IDs with intact payloads. The PR had 2,430 extra duplicate records and the base had 20,436. This was one trial per revision.

With compress gzip in the file buffer, leaving out_forward compression at its default, both revisions had 684 gzip chunks on disk and delivered all 29,184 IDs without duplicates. With 8 MiB chunks, total_limit_size 22m and overflow_action drop_oldest_chunk, both revisions purged queued files while another chunk was being read. Of 36,330 input IDs in each trial, 20,760 were accounted for by the dropped chunks. All other 15,570 arrived intact without duplicates.

On Windows Server 2025 with Ruby 3.4.12, both revisions completed three paired runs at 64 records/s online with 6,144 records queued during the outage, 64 KiB chunks, two flush threads, a 0.8 s flush burst interval and a 120 s ACK timeout. Each revision delivered all 13,312 IDs per run without duplicates. Backlog drain times were 77.547 / 77.562 / 79.156 s for the base and 76.094 / 76.234 / 78.328 s for the PR (min / median / max). Sender handles peaked at 685–697 vs 314 offline and 496–501 vs 312–313 during drain, then settled at 307 vs 307–308. The online runs were capped at 64 records/s. In the earlier higher-burst profile, both revisions timed out during all three drains of the 12,288-record backlog. Paced Windows runs · Higher-burst Windows runs

On macOS, both revisions delivered all IDs without duplicates in four paired runs. The base took 6.447 / 9.552 / 13.172 s (min / median / max) to drain 65,536 records. The PR took 2.672 / 13.507 / 14.352 s and was slower in three of the four pairs. The paired drain times varied widely. Sender FD peaks during drain were 709–2,897 for the base and 112–591 for the PR, and both settled at 10. Online throughput across 12 bursts per revision was 9,201 / 11,202 / 16,883 records/s for the base and 10,091 / 11,461 / 18,141 for the PR (min / median / max). macOS reruns

The three-hour Linux runs are in progress at a target of 3 MB/s with 64 KiB and 8 MiB chunks, each with a 2 GiB buffer. I’ll post the per-cycle FD and RSS figures and final delivery checks once they finish. The native hosted runs above cover the shorter paired workload.

Could you approve the upstream Test workflow for this head? Test run

@Watson1978

Watson1978 commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the detailed numbers and the reruns.

For the three-hour runs, could you attach graphs over time, not only the peaks and the final values? For each revision, please plot these:

  • Sender FDs (handles on Windows) and RSS
  • Queued chunks
  • Records accepted and delivered

Please mark the outages, restarts and recoveries, and show the two revisions side by side on the same scale. Please also attach the raw samples (samples.csv), so that we can check the graphs.

If it is easy, graphs of the runs you already posted would help too. Their workflow artifacts already have samples.csv with a sample every two seconds.

For the next update, a few things would make the results easier to review:

  • Start with a short summary of what the results show and what is still running.
  • Then go through the items of my review in the same order. For each one, say whether it is done, still running, or not possible.
  • For each run, state the revisions, the Ruby version and any settings that differ from the main workload.
  • When a result looks worse for the PR, such as the slower macOS drains, please say whether you think it is noise or a real cost, and why.

One more question: in the compress gzip and drop_oldest_chunk runs, was the PR revision bb0794c or 2637b3d?

@git-jxj

git-jxj commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

All four three-hour Linux runs finished and delivered 21,093,750 unique IDs each, with zero missing or malformed records. The revised 64 KiB run had 63 extra deliveries during the first recovery. The other three runs had zero duplicates. Queued-buffer FD use fell sharply on the PR, and the 64 KiB runs showed an RSS increase after successive recoveries on both revisions. The endurance and short-run charts and samples are complete. Charts and data

  1. Configuration. Done. The original Linux outage run (6a48ae6 / bb0794c, Ruby 3.3.14) used the same forwarding settings as the macOS workload, with 64 KiB chunks, four flush threads, a 5 ms flush burst interval and 60 s ACKs. Its soft/hard descriptor limits were 8,192/1,048,576. The 128-FD runs used Ruby 3.3.6, 5 s ACKs and a soft/hard limit of 128/1,048,576. The exact daemon arguments and settings are in the previous comment. Configuration and commands

  2. Several-hour run. Done. The four Linux runs compared 6a48ae6 and 2637b3d on Ruby 3.3.14, with one run per revision and chunk size. Each used four abrupt receiver outages and kept its sender running while publishing. The outages were staggered across the four runs. The charts use common axes and show sender FD, RSS, queued chunks, TCP writes as the input measure, and receiver ID counts. The restart markers refer to the receiver. 64 KiB chart · 8 MiB chart · Raw samples.csv files · Event timings

  3. During and after drain. Done. Before recovery from the 180 s outages, 64 KiB chunks used 22,000–22,026 FDs at base and 14 on the PR. With 8 MiB chunks that was 152 and 14. Sampled peak FDs during recovery were 22,150 / 847 for 64 KiB and 158 / 36 for 8 MiB. The 64 KiB PR peak included 837 sockets and two buffer FDs. After the final drain all four runs had 11 FDs and empty queues. The 64 KiB PR had 95.5, 148.1, 161.5 and 162.0 MiB of RSS sampled at least a minute after the four recoveries. Base values were 127.3, 156.8, 158.6 and 158.6 MiB. The 8 MiB runs were around 83 MiB. The earlier 128-FD run’s one-second sampler missed both socket(2) EMFILE instants. The descriptor types at those instants remain unknown. Earlier Linux drain chart

  4. Sender restart during drain. Done. On Linux with Ruby 3.3.14, 64 KiB chunks and about 3 MB/s of input, I killed and restarted the sender after 128 records arrived, with 907 base and 912 PR chunks still queued. Both revisions delivered all 29,184 unique IDs. There were 20,436 extra deliveries on 6a48ae6 and 2,430 on 2637b3d, one run each. Sender restart chart

  5. Gzip and drop-oldest. Done. Both ran 2637b3d against 6a48ae6, using Ruby 3.3.14. With compress gzip in the 64 KiB file buffer and default forwarding compression, both delivered all 29,184 IDs without duplicates. With 8 MiB chunks, total_limit_size 22m and overflow_action drop_oldest_chunk, both runs dropped all 20,760 expected records while other chunks were read. The other 15,570 IDs arrived intact without duplicates. Linux scenario charts and samples

  6. Windows. Done for the paced comparison. All three 6a48ae6 / 2637b3d pairs on Ruby 3.4.12 delivered every ID without duplicates at the 64 records/s online cap. This profile used 64 KiB chunks, two flush threads, a 0.8 s flush burst interval and 120 s ACKs. All three pairs at the higher-burst setting timed out during drain on both revisions. Windows charts and samples

  7. Throughput and macOS drain time. Done. The original Linux throughput table has the min, median and max of six trials per revision. On macOS, 6a48ae6 and 2637b3d used Ruby 3.4.12 and the original 65,536-record, 64 KiB workload. The candidate was slower in three of four drain pairs, with a paired median increase of 12.2%. Individual changes ranged from −64.7% to +112.3%. I’d treat this as a possible cost because the PR opens queued data on demand. The hosted drain timer also includes receiver startup. With four pairs and variation of that size, the measurements leave the cause and size of any cost unresolved. Linux throughput table · macOS charts and samples

  8. Production-rate input and larger chunks. Done on Linux. Each workload averaged 3.000 MB/s over three hours. During the first 64 KiB PR recovery, TCP input dipped to 1.78 MB/s for one minute and caught up at 4.21 MB/s the next. The endurance sender had a 2 GiB buffer, a 32,768 queued-chunk ceiling and soft and hard FD limits of 65,536. It used 1 s flushing for 64 KiB chunks and 4 s for 8 MiB chunks. Both sizes used 60 s ACKs, four flush threads and a 5 ms flush burst interval. The macOS and Windows graphs cover the shorter native-runner trials.

@Watson1978

Copy link
Copy Markdown
Contributor

Thanks, this report is much easier to follow, and the charts help a lot.

Could you attach the charts and the result files to a comment in this PR, instead of only linking to your fork? If the fork or the commit goes away later, the links stop working, and we would like to refer to these results later. GitHub accepts images and .zip files as attachments, so the samples.csv files, events.csv and the other results can go in one .zip.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

buf_file: queued file chunks keep FDs open until shutdown; resume opens all chunks — EMFILE death spiral on slow output

2 participants