Skip to content

chore: small fixes post #605 - #607

Merged
romange merged 1 commit into
masterfrom
Pr2
Jul 6, 2026
Merged

chore: small fixes post #605#607
romange merged 1 commit into
masterfrom
Pr2

Conversation

@romange

@romange romange commented Jul 6, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • Bug Fixes
    • Improved stability in fiber queue processing by handling unexpected exceptions more safely.
    • Added more accurate tracking for blocked task submitters, reducing the chance of submit/wait issues under load.

@romange
romange requested a review from glevkovich July 6, 2026 11:23
@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

FiberQueue::Run() now wraps its dequeue/execute loop in a try/catch that fatally logs on std::exception. FiberQueue::blocked_submitters() changed from an instance const method to static. FiberQueueThreadPool::Add() now increments/decrements blocked_submitters_ around the push_ec_ wait.

Changes

FiberQueue reliability and accounting

Layer / File(s) Summary
Exception handling in Run loop
util/fibers/fiberqueue_threadpool.cc
The dequeue/execute loop is wrapped in try/catch(std::exception&), calling LOG(FATAL) with the exception message instead of letting it propagate.
Blocked submitters accessor and accounting
util/fibers/fiberqueue_threadpool.h
blocked_submitters() becomes a static method, and FiberQueueThreadPool::Add increments/decrements blocked_submitters_ around the push_ec_ wait.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • romange/helio#605: Both PRs modify FiberQueue's blocked_submitters_ accounting around the push_ec_ wait path and the blocked_submitters() accessor.

Suggested reviewers: glevkovich, BorysTheDev

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title is too vague to convey the main change, describing only generic post-#605 fixes. Use a specific title that names the primary change, such as FiberQueue exception handling or blocked submitter accounting.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch Pr2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Harden FiberQueueThreadPool worker loop and blocked-submitter tracking

🐞 Bug fix 🕐 10-20 Minutes

Grey Divider

AI Description

• Prevent silent worker-thread termination by catching exceptions in FiberQueue::Run().
• Expose blocked-submitter metric as a static accessor for TLS-backed state.
• Track blocked submitters in FiberQueueThreadPool::Add() when waiting for queue capacity.
Diagram

graph TD
  A["Producers (callers)"] --> B["FiberQueueThreadPool::Add()"] --> C["FiberQueue (per worker)"] --> D[("Bounded task queue")]
  C --> E["EventCount (pull/push)"]
  B -->|"wait when full"| E -->|"notifyAll"| B
  F["Worker thread"] --> G["FiberQueue::Run() (try/catch)"] --> E
  G --> H["Execute tasklets"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Catch exceptions per-task instead of per-loop
  • ➕ One bad task doesn't necessarily kill the entire worker loop
  • ➕ Allows logging task-specific context (if available) and continuing to drain the queue
  • ➖ Adds overhead on the hot path (per callback)
  • ➖ Can mask systemic failures if tasks repeatedly throw
2. Catch-all (catch (...)) with logging/termination policy
  • ➕ Prevents non-std exceptions from escaping the thread entry point
  • ➕ Makes failure mode explicit and consistent across exception types
  • ➖ Harder to preserve exception details beyond 'unknown exception'
  • ➖ Still requires a policy choice: abort vs continue vs quarantine worker

Recommendation: If the intended policy is fail-fast on any task exception, the current loop-level try/catch + LOG(FATAL) is reasonable and avoids silent worker death. Consider broadening to catch (...) as well to avoid termination on non-std exceptions, and (optionally) moving the try/catch inside the per-task invocation if continuing after a single task failure is desirable for this system.

Files changed (2) +18 / -12

Bug fix (1) +15 / -11
fiberqueue_threadpool.ccWrap FiberQueue::Run loop with fail-fast exception handling +15/-11

Wrap FiberQueue::Run loop with fail-fast exception handling

• Wraps the consumer loop in FiberQueue::Run() with a try/catch for std::exception and logs a fatal error on exception. This makes task exceptions visible and avoids silent termination of the worker thread while draining batches.

util/fibers/fiberqueue_threadpool.cc

Refactor (1) +3 / -1
fiberqueue_threadpool.hMake blocked_submitters accessor static and track pool-side blocking +3/-1

Make blocked_submitters accessor static and track pool-side blocking

• Changes blocked_submitters() to a static accessor (matching the TLS-backed static counter). Also increments/decrements blocked_submitters_ in FiberQueueThreadPool::Add() around the push EventCount wait, so producer blocking is counted even when the pool blocks outside FiberQueue::Add().

util/fibers/fiberqueue_threadpool.h

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (1) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 11 rules
✅ Cross-repo context
  Explored: repo: dragonflydb/dragonfly (sha: bc82e529)

Grey Divider


Informational

1. FiberQueue::Run() catches std::exception 📘 Rule violation ⚙ Maintainability
Description
FiberQueue::Run() wraps internal queue/task execution in a try/catch and converts any
std::exception into a fatal log, which is not limited to third-party interoperability boundaries.
This violates the policy of restricting exceptions to third-party boundaries and translating them
into the project’s preferred error representation.
Code

util/fibers/fiberqueue_threadpool.cc[R41-61]

+  try {
+    while (true) {
+      pull_ec_.await(cb);

-    if (is_closed)
-      break;
+      if (is_closed)
+        break;

-    while (count < kBatchSize && queue_.try_dequeue_sc(batch[count])) {
-      ++count;
-    }
+      while (count < kBatchSize && queue_.try_dequeue_sc(batch[count])) {
+        ++count;
+      }

-    push_ec_.notifyAll();
+      push_ec_.notifyAll();

-    for (unsigned i = 0; i < count; ++i) {
-      batch[i]();
+      for (unsigned i = 0; i < count; ++i) {
+        batch[i]();
+      }
+      count = 0;
    }
-    count = 0;
+  } catch (const std::exception& ex) {
+    LOG(FATAL) << "Exception " << ex.what();
  }
Relevance

⭐ Low

PR #605 removed std::exception catch from FiberQueue::Run(); team moved away from internal
try/catch+LOG(FATAL).

PR-#605
PR-#599

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 1535202 restricts try/catch usage to third-party interoperability boundaries.
The changed code adds a broad try/catch (const std::exception&) around the internal worker loop
and task execution in FiberQueue::Run(), without indicating a third-party boundary or translating
to a non-exception error type.

Rule 1535202: Restrict exception usage to third-party interoperability boundaries
util/fibers/fiberqueue_threadpool.cc[41-61]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`FiberQueue::Run()` catches `std::exception` around internal logic, which violates the rule that exceptions should be restricted to third-party interoperability boundaries.

## Issue Context
The current code catches any `std::exception` thrown from `pull_ec_.await(cb)` / task execution (`batch[i]()`), and then calls `LOG(FATAL)`. If exceptions must be handled here, they should be confined to a clearly documented boundary case and translated to the project’s non-exception error handling strategy.

## Fix Focus Areas
- util/fibers/fiberqueue_threadpool.cc[41-61]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Unhandled non-std exceptions 🐞 Bug ◔ Observability
Description
FiberQueue::Run() only catches std::exception, so if a queued Tasklet throws a non-std exception
type it will bypass the handler and hit std::terminate without the intended LOG(FATAL) message. This
reduces crash diagnosability for failures originating from queued tasks.
Code

util/fibers/fiberqueue_threadpool.cc[R41-61]

+  try {
+    while (true) {
+      pull_ec_.await(cb);

-    if (is_closed)
-      break;
+      if (is_closed)
+        break;

-    while (count < kBatchSize && queue_.try_dequeue_sc(batch[count])) {
-      ++count;
-    }
+      while (count < kBatchSize && queue_.try_dequeue_sc(batch[count])) {
+        ++count;
+      }

-    push_ec_.notifyAll();
+      push_ec_.notifyAll();

-    for (unsigned i = 0; i < count; ++i) {
-      batch[i]();
+      for (unsigned i = 0; i < count; ++i) {
+        batch[i]();
+      }
+      count = 0;
    }
-    count = 0;
+  } catch (const std::exception& ex) {
+    LOG(FATAL) << "Exception " << ex.what();
  }
Relevance

⭐ Low

Given PR #605 removed exception catching entirely in Run(), adding catch(...) for non-std exceptions
is unlikely accepted.

PR-#605

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The worker loop is wrapped in a try/catch that only matches std::exception, while Tasklet is an
unconstrained callable wrapper (void() signature), so non-std exceptions from queued tasks will not
be caught/logged by this change.

util/fibers/fiberqueue_threadpool.cc[41-61]
util/fibers/fiberqueue_threadpool.h[27-36]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`FiberQueue::Run()` catches only `const std::exception&`, so exceptions not derived from `std::exception` will not be logged via the new `LOG(FATAL)` path.

### Issue Context
Tasks executed from `batch[i]()` are stored as `Tasklet` (`fu2::function_base<..., void()>`) and can wrap arbitrary callables, so non-`std::exception` throws are possible.

### Fix Focus Areas
- util/fibers/fiberqueue_threadpool.cc[41-61]

### Suggested fix
Add a follow-up handler:
- `catch (const std::exception& ex) { LOG(FATAL) << ...; }`
- `catch (...) { LOG(FATAL) << "Unknown exception"; }`

Optionally include additional context (worker thread/name) in the log message.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (3)
util/fibers/fiberqueue_threadpool.cc (1)

41-61: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add a catch (...) fallback alongside catch (const std::exception&).

Verified Tasklet's IsThrowing=false template parameter only governs behavior on empty-callable invocation (abort vs. fu2::bad_function_call), not whether a valid, non-empty callable's thrown exception propagates — so this try/catch does correctly intercept exceptions thrown from batch[i](). However, only std::exception-derived types are caught; anything else (e.g., a non-standard thrown type) will escape Run() with no handler up the call stack in WorkerFunction, leading to an opaque std::terminate() with no diagnostic log, unlike the intended LOG(FATAL) path.

🛡️ Proposed fix
   } catch (const std::exception& ex) {
     LOG(FATAL) << "Exception " << ex.what();
+  } catch (...) {
+    LOG(FATAL) << "Unknown exception in FiberQueue::Run";
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@util/fibers/fiberqueue_threadpool.cc` around lines 41 - 61, Add a
non-standard exception fallback in fiberqueue_threadpool.cc so
FiberQueueThreadPool::Run does not let unknown thrown types escape
WorkerFunction; keep the existing catch (const std::exception&) path for
diagnostics and add a catch-all handler alongside it that logs a fatal error
before terminating, using the existing LOG(FATAL) reporting pattern around
batch[i]().
util/fibers/fiberqueue_threadpool.h (2)

176-178: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Duplicate blocking-wait accounting pattern; consider a shared RAII guard.

This increment/wait/decrement sequence is identical to the existing pattern in FiberQueue::Add (lines 74-77). Extracting a small RAII guard (e.g., via absl::Cleanup) would remove the duplication and also make the decrement exception-safe if push_ec_.wait() ever throws. As per coding guidelines, "Use smart pointers (std::unique_ptr) and RAII (absl::Cleanup) for resource management."

♻️ Proposed refactor sketch
-      main_w.q->blocked_submitters_++;
-      main_w.q->push_ec_.wait(key.epoch());
-      main_w.q->blocked_submitters_--;
+      main_w.q->blocked_submitters_++;
+      absl::Cleanup dec = [&] { main_w.q->blocked_submitters_--; };
+      main_w.q->push_ec_.wait(key.epoch());
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@util/fibers/fiberqueue_threadpool.h` around lines 176 - 178, The
blocked_submitters_ increment/wait/decrement sequence in FiberQueue::Add and the
matching path in FiberQueue::FiberQueueThreadPool should be deduplicated and
made exception-safe. Introduce a small RAII guard, preferably using
absl::Cleanup, around the push_ec_.wait(key.epoch()) call so the decrement
always runs even if waiting throws, and reuse the same helper/pattern in both
FiberQueue::Add and the threadpool blocking path.

Source: Coding guidelines


111-113: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document the thread-local scope of blocked_submitters()
It returns the calling thread’s blocked_submitters_, not per-FiberQueue state; a short comment or clearer name would make that explicit.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@util/fibers/fiberqueue_threadpool.h` around lines 111 - 113, The
blocked_submitters() accessor currently reads thread-local blocked_submitters_
but its name and declaration do not make that scope explicit. Update the
FiberQueueThreadPool API by adding a short comment or renaming
blocked_submitters() to clearly indicate it returns the calling thread’s value,
not per-FiberQueue state. Keep the change close to the blocked_submitters()
method and the blocked_submitters_ member so the thread-local behavior is
obvious to callers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@util/fibers/fiberqueue_threadpool.cc`:
- Around line 41-61: Add a non-standard exception fallback in
fiberqueue_threadpool.cc so FiberQueueThreadPool::Run does not let unknown
thrown types escape WorkerFunction; keep the existing catch (const
std::exception&) path for diagnostics and add a catch-all handler alongside it
that logs a fatal error before terminating, using the existing LOG(FATAL)
reporting pattern around batch[i]().

In `@util/fibers/fiberqueue_threadpool.h`:
- Around line 176-178: The blocked_submitters_ increment/wait/decrement sequence
in FiberQueue::Add and the matching path in FiberQueue::FiberQueueThreadPool
should be deduplicated and made exception-safe. Introduce a small RAII guard,
preferably using absl::Cleanup, around the push_ec_.wait(key.epoch()) call so
the decrement always runs even if waiting throws, and reuse the same
helper/pattern in both FiberQueue::Add and the threadpool blocking path.
- Around line 111-113: The blocked_submitters() accessor currently reads
thread-local blocked_submitters_ but its name and declaration do not make that
scope explicit. Update the FiberQueueThreadPool API by adding a short comment or
renaming blocked_submitters() to clearly indicate it returns the calling
thread’s value, not per-FiberQueue state. Keep the change close to the
blocked_submitters() method and the blocked_submitters_ member so the
thread-local behavior is obvious to callers.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 73cbed0f-3944-4a01-ae86-45fe4043c481

📥 Commits

Reviewing files that changed from the base of the PR and between 0c32978 and bd456c2.

📒 Files selected for processing (2)
  • util/fibers/fiberqueue_threadpool.cc
  • util/fibers/fiberqueue_threadpool.h

@glevkovich glevkovich left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@romange
romange merged commit 585aa6b into master Jul 6, 2026
11 checks passed
@romange
romange deleted the Pr2 branch July 6, 2026 12:30
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