Skip to content

Fix asynchronous sink flush hangs and incomplete flushes - #259

Closed
dchristle wants to merge 1 commit into
boostorg:developfrom
dchristle:fix/async-flush-completion
Closed

dchristle wants to merge 1 commit into
boostorg:developfrom
dchristle:fix/async-flush-completion

Conversation

@dchristle

@dchristle dchristle commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

asynchronous_sink::flush() can leave logging blocked or return before queued records have been processed:

  • If record processing throws while the calling thread drains the queue during flush(), the flush-requested flag remains set. Later consume() calls block indefinitely, and try_consume() rejects records.
  • With caller-driven feeding (start_thread=false), flush() can wait indefinitely if the feeding call exits or throws while a flush request is pending. Producers also remain blocked.
  • With an ordering queue, try_dequeue_ready() can return false while records remain inside the ordering window. If a flush request arrives after the feeder chooses that ready-only check, the original code can leave the dequeue loop and flush the backend without first draining those records.

Retry with try_dequeue() when a flush arrives during a failed ready-record check. Keep later requests pending until a feeding operation can drain them. Let waiting flush callers take over when feeding ends, preserve pending requests across feeder changes, and clear abandoned requests so exceptions during caller-driven flushing do not leave producers blocked.

Four separate regression executables cover feeder exceptions, incomplete ordering-queue flushes, logging after a failed flush, and feeder replacement. Against the original code, controlled queue and backend pauses demonstrate a flush exceeding its deadline, an ordering queue delivering 0 of 1 records, and producers remaining blocked after a drain exception. These cases pass with the fix.

The feeder-replacement case guards against a regression the cleanup could introduce. Each executable has a ten-second process watchdog so a deadlock fails its own test without hanging the remaining cases. All four tests and the existing #255 regression test pass on macOS with C++11.

Comment on lines +532 to +582
while (!m_StopRequested.load(boost::memory_order_acquire))
while (!m_StopRequested.load(boost::memory_order_acquire) && !m_FlushRequested.load(boost::memory_order_acquire))
{
record_view rec;
bool dequeued = false;
if (BOOST_LIKELY(!m_FlushRequested.load(boost::memory_order_acquire)))
dequeued = queue_base_type::try_dequeue_ready(rec);
else
dequeued = queue_base_type::try_dequeue(rec);

if (dequeued)
if (queue_base_type::try_dequeue_ready(rec))
base_type::feed_record(rec, m_BackendMutex, *m_pBackend);
else
break;
}

if (BOOST_UNLIKELY(m_FlushRequested.load(boost::memory_order_acquire)))
{
while (!m_StopRequested.load(boost::memory_order_acquire))
{
record_view rec;
if (queue_base_type::try_dequeue(rec))
base_type::feed_record(rec, m_BackendMutex, *m_pBackend);
else
break;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this change necessary? It doesn't seem to change the behavior, but only introduces code duplication.

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.

👍🏻 I've put this back into one loop. The behavior change is that it tracks which dequeue mode was actually used.

If a flush arrives during a failed ready-record check, the loop retries with try_dequeue(), which ignores the ordering window. A request arriving after the final check stays pending rather than being cleared as though the queue had been drained.

Comment on lines +274 to +275
//! Flush callers waiting for the active feeding operation
unsigned int m_FlushWaiters;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think I understand the logic behind the added m_FlushWaiters member. It seems redundant with m_FlushRequested and I don't see how it changes the existing behavior.

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.

My understanding here is that the flag can be true without another caller waiting: a thread doing its own flush() also sets it. So, if that flush throws while draining records, cleanup needs to clear the abandoned request so producers can continue.

But clearing it unconditionally can lose a waiting caller's request. A replacement feeder can start before that caller reacquires the mutex. The caller then sees an active feeder and a cleared flag and returns without the flush having happened.

The count distinguishes those cases. It lets cleanup clear an abandoned request while preserving one that a waiting caller or replacement feeder still needs to finish. The restart test guards that cleanup behavior.

@Lastique Lastique Nov 9, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

My understanding here is that the flag can be true without another caller waiting

No, that is not the intention. m_FlushRequested is supposed to indicate that there is a thread that has requested a flush. The thread that requested the flush must not return (successfully) until the records that have been enqueued before the flush was requested are dispatched. New records may or may not be enqueued during the flush (the API does not specify that), but in either case the new records do not participate in the flush, which means the flush must always have a limited amount of work to do. The current implementation blocks until the flush is complete, which may be suboptimal from the caller's perspective, but acceptable, given that flush is supposed to be infrequent and may be expensive.

If the flush fails due to an exception (i.e. flush happens synchronously and it throws an exception), it is considered as completed, i.e. the state is "there is no thread that is currently requesting a flush". In this case, whatever records are left in the queue are left as they are, and new records that were blocked for enqueueing are unblocked and enqueued. The user may then call flush again and the whole procedure repeats, with the then-current set of enqueued log records.

So, put simply, m_FlushRequested must be true when a thread is in flush and false otherwise. If multiple threads call flush concurrently, they must be serialized; each such thread returns when at least one flush attempt is complete. From the API perspective, it is unspecified whether the records that arrive during this concurrent combined flush operation participate in the flush. From the implementation perspective, whatever implementation is most efficient and simplest is fine; currently, the records do not participate since enqueuers are blocked.

Given the above, I can see that m_FlushRequested is not being reset correctly if feeding a record during the synchronous flush fails with an exception. This is a bug that needs fixing.

The asynchronous flush case is a bit different. In this case, if the exception happens in the feeding thread, the flushing thread does not receive it and remains blocked until either the flush completes somehow (e.g. if the feeding thread recovers and resumes feeding records; worth noting that the built-in feeding thread does not recover and terminates the process) or the sink is stopped (stop called). In the latter case, the flusher will unblock and perform a synchronous flush, which may or may not succeed, and behaves as described above. In any case, the new records are blocked until the flush completes. Unless I'm missing something, and barring the missing m_FlushRequested reset I mentioned above, the current code should behave as described in the async case.

Comment on lines +551 to +553
// A replacement feeding operation must honor flush callers that are still waiting.
if (m_FlushWaiters == 0u)
m_FlushRequested.store(false, boost::memory_order_relaxed);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

According to the change in flush, when a feeding thread returns from run or other feeding operation, one of the threads blocked in flush should take over and do the flush synchronously. So I don't understand why this change here is needed.

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.

Yes, that's right when another caller is already waiting in flush(). The separate case here is a caller-driven flush with nobody else waiting.

If record processing throws during the drain, it happens before the flag-reset guard around flush_backend() is constructed. The feeding operation becomes idle, but the request remains set, so later consume() calls block indefinitely.

My cleanup clears that abandoned request. When another flush caller is waiting, it leaves the request pending for takeover.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think, conceptually, m_FlushRequested needs to be cleared when the flush operation completes (successfully or not) and not when any feeding operation completes. The only case where there is a difference is when the feeding happens in a separate thread asynchronously and feeding fails with an exception. Currently, the behavior is to keep flush pending, in the anticipation that either feeding resumes or the sink is stopped. So flush may remain pending while there is no feeding in progress.

With your change, flush unblocks if the feeder fails with an exception. I'm not sure if this change is for the better. I'll need to think about this.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ok, let's do it this way. If a feeding operation is active (i.e. run or feed_records is being called), flush should block until the feeding thread indicates that the flush is complete. If the feeding operation fails with an exception, that should also unblock flush, which may then attempt to flush the remaining records synchronously. If no feeding operation is in flight, flush does not block and performs a synchronous flush.

This is different from the previous behavior, where flush would remain blocked. The previous design is intentional and followed from the intent that all log records are passed to the sink backend in the feeding thread, as documented here. However, this promise is not always kept because flush has to work when the sink is stopped too, as shown in the example later in the docs. So flush has to work both synchronously and asynchronously. We might as well make the behavior more predictable and conditional on whether the feeding operation is in progress at the point of the call.

This, however, does not change the fact that resetting m_FlushRequested to false should not happen in complete_feeding_operation. If the feeding operation fails with an exception, it should wake up the blocked flushing thread (which it does, after you added the m_ActiveOperation check), which should go on with the synchronous flush, and only when that completes (successfully or not) the flag should be reset. This is needed so that the blocked new records are kept blocked during this handoff between threads.

Comment thread test/run/sink_async_flush.cpp Resolved
@Lastique

Lastique commented Nov 8, 2026

Copy link
Copy Markdown
Member
  • With an ordering queue, a flush request arriving during the feeder's final ready-record check can cause the backend to be flushed while records remain inside the ordering window.

Sorry, I don't think I understand what you mean here. Could you elaborate, perhaps with a step-by-step of what happens and what the problem is?

@dchristle
dchristle force-pushed the fix/async-flush-completion branch from 2726214 to a023cdb Compare November 8, 2026 20:59
@dchristle

Copy link
Copy Markdown
Contributor Author
  • With an ordering queue, a flush request arriving during the feeder's final ready-record check can cause the backend to be flushed while records remain inside the ordering window.

Sorry, I don't think I understand what you mean here. Could you elaborate, perhaps with a step-by-step of what happens and what the problem is?

Sure -- no problem -- the distinction here is that try_dequeue_ready() returning false doesn't necessarily mean the queue is empty. A record can still be inside the ordering window.

The sequence in the original code is:

  1. A record is queued but isn't old enough to be ready.
  2. The feeder reads m_FlushRequested == false and chooses try_dequeue_ready().
  3. The ready check decides there is nothing ready to return.
  4. Another thread sets m_FlushRequested.
  5. The feeder leaves the dequeue loop, sees the request in the final check, and calls flush_backend() without draining that record.
  6. The request is cleared and flush() returns with the record still queued.

The test pauses the feeder after the ready check and requests a flush from another thread. The original code delivers 0 of 1 records when flush() returns; the revised code delivers the record before returning.

Exceptions while draining records can leave later producers blocked,
and flush callers can wait forever when a feeding operation exits.
Ordering queues can also acknowledge a flush without draining records
inside the ordering window.

Retry dequeueing without the ordering window when a flush arrives during
a ready-record check. Preserve pending requests across feeder changes.
Clear abandoned requests so caller-driven failures release producers.

Isolate potentially blocking regressions in separate executables with
shared process deadlines so failures cannot hang the remaining cases.
@dchristle
dchristle force-pushed the fix/async-flush-completion branch from a023cdb to 4aa8f24 Compare November 8, 2026 21:20
//! The record feeding loop
void do_feed_records()
{
bool flush_requested = m_FlushRequested.load(boost::memory_order_acquire);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This can be = false. flush_requested is initialized in the loop below. And if m_StopRequested is true, we're not flushing any records anyway and break from the loop immediately, so might as well skip the backend flushing.

Comment on lines +577 to +578
else if (!flush_requested && m_FlushRequested.load(boost::memory_order_acquire))
continue;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think this should be needed. Either feed_records will be called again or run has to retry.

Now, run does not check if flush was requested in order to re-enter do_feed_records so that non-ready records are flushed, but I think it should be fixed there rather than worked around here.

@Lastique

Lastique commented Nov 9, 2026

Copy link
Copy Markdown
Member

Sure -- no problem -- the distinction here is that try_dequeue_ready() returning false doesn't necessarily mean the queue is empty.

Thanks for the explanation. Yes, this is a possible scenario. It seems to be a separate issue and could use a separate PR. But since it's already here, we can work on the combined PR.

Lastique added a commit that referenced this pull request Nov 20, 2026
If flush() was called just after the feeding thread in do_feed_records()
has checked for m_FlushRequested == false, and there are no ready records
in the queue, the feeding thread would exit the draining loop even if
there could be non-ready records in the queue, and proceed to flush the
backend. This would result in flush() not draining the non-ready records
that could still be present in an ordering queue.

To avoid this, separate draining non-ready records from the ready ones
into a separate loop that is conditioned on m_FlushRequested == true,
which executes after all ready records have been drained.

Reported and suggested in #259.
Lastique added a commit that referenced this pull request Nov 20, 2026
If the feeding operation fails with an exception (e.g. thrown from the
sink backend when it processes a record) before it enters the flushing
loop, the threads blocked in flush() remained blocked, waiting for the
flush to complete. Unblock them when the feeding operation ends, and
m_ActiveOperation becomes idle, so that the flush is performed
synchronously.

Reported and suggested in #259.
Lastique added a commit that referenced this pull request Nov 20, 2026
If a log record processing throws during a synchronous flush, before
the flushing loop was entered in do_feed_records(), the m_FlushRequested
flag would remain set to true. As a result, the threads blocked in
consume() would remain blocked until the next successful call to flush()
that would reset the flag to false. Similarly, try_consume() would
continuously return false.

Reset m_FlushRequested to false in complete_feeding_operation, but only
(a) when it is called from flush() (which is indicated by
m_ActiveOperation == flushing) and (b) when there are no other threads
blocked in flush(). The latter is indicated by a new m_FlushWaiters
counter, which is updated by flush(), before and after the method is
waiting for the feeder thread to perform the flush. This is needed to
maintain m_FlushRequested set to true if the synchronous flush() fails
with an exception, when there are other blocked flushers. Otherwise,
a new feeding operation could be started just before the blocked flusher
reacquires the mutex. That feeding operation would observe
m_FlushRequested == false and not perform a flush, and the woken up
flusher would observe m_ActiveOperation != idle and assume the flush has
been done; therefore the flush would be lost.

Additionally, remove the scope guard in do_feed_records() to reset
m_FlushRequested to false and instead only reset it when the flushing
loop completes successfully. This way, in case of an exception, the flag
remains set to true, so that the blocked flusher attempts to perform a
synchronous flush when it wakes up and observes m_ActiveOperation == idle.

In flush(), remove the check for m_StopRequested in the waiting loop.
This check was redundant, since stop() would cause the feeding operation
to complete, which would set m_ActiveOperation to idle and cause the
waiting loop terminate anyway.

Lastly, change all memory order semantics for operations on
m_FlushRequested to relaxed since no actual data synchronization happens
through that flag. The flag is only atomic to avoid formal race condition
from concurrent accesses in different threads.

Reported and partly suggested in #259.
@Lastique

Copy link
Copy Markdown
Member

Thank you for the report and the PR. This should be fixed in develop now.

@Lastique Lastique closed this Nov 20, 2026
@dchristle
dchristle deleted the fix/async-flush-completion branch November 21, 2026 00:22
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.

2 participants