Repository navigation
Conversation
Signed-off-by: xinjun.jiang <xinjun.jiang@daocloud.io>
Watson1978
left a comment
There was a problem hiding this comment.
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.
| # 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) |
There was a problem hiding this comment.
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.
| # 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
endThere was a problem hiding this comment.
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.
|
|
||
| # 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 |
There was a problem hiding this comment.
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)
endThere was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| output = StringIO.new | |
| output = StringIO.new | |
| output.set_encoding(Encoding::ASCII_8BIT) |
There was a problem hiding this comment.
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>
|
Could a maintainer approve the Test workflow for |
Watson1978
left a comment
There was a problem hiding this comment.
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.
|
|
||
| # 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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? |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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>
|
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:
If you did not check something, please say so. |
|
@Watson1978 I reran the checks from your comment on Full suite I ran the full suite from separate clean checkouts at ruby -S bundle exec rake test TESTOPTS="-v --report-slow-tests --no-show-detail-immediately"
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
In the replay commands, |
|
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 |
|
@Watson1978 I reran the stress test with separate Fluentd sender and receiver processes and a file buffer using
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. |
Watson1978
left a comment
There was a problem hiding this comment.
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.pyon your validation branch. They useout_forwardwithrequire_ack_responseand a file buffer withchunk_limit_size 64kandflush_thread_count 4, withoutcompress. 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 gzipin<buffer>(and the defaultcompressinout_forward, so the chunks are decompressed when read). Please also run withtotal_limit_sizeandoverflow_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.
| 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) |
There was a problem hiding this comment.
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 withErrno::EACCES. On master, the restore stopped withErrno::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 withErrno::EACCESand 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.
There was a problem hiding this comment.
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>
|
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
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 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 ( With 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 |
|
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:
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 ( If it is easy, graphs of the runs you already posted would help too. Their workflow artifacts already have For the next update, a few things would make the results easier to review:
One more question: in the |
|
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
|
|
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 |
Which issue(s) this PR fixes:
Fixes #5494
Refs #3040
What this PR does / why we need it:
A
filebuffer 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
EMFILEwhile 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.