Skip to content

Make threads waiting on thunks interruptible - #206

Merged
edolstra merged 2 commits into
mainfrom
make-waiters-interruptible
Sep 17, 2025
Merged

edolstra merged 2 commits into
mainfrom
make-waiters-interruptible

Conversation

@edolstra

@edolstra edolstra commented Sep 17, 2025 •

Copy link
Copy Markdown
Collaborator

Motivation

In particular, this makes Ctrl-C work in case of infinite recursion.

Context

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of cancellation/interrupts during evaluation so waiting tasks are reliably and promptly awakened, reducing hangs and delayed responses.
    • Better handling of spurious wakeups to ensure interrupts are processed consistently.
  • New Features

    • Interrupt-driven wakeups now operate across all evaluation domains, improving responsiveness when stopping or cancelling operations.
  • Notes

    • No user-facing API changes.

@coderabbitai

coderabbitai Bot commented Sep 17, 2025 •

Copy link
Copy Markdown

Walkthrough

Adds an Executor interruptCallback, centralizes per-domain waiter storage and interrupt-driven notify_all, invokes checkInterrupt() during slow wait wakeups, and replaces GCC-specific alignment attributes with standard C++ alignas on cache-aligned types.

Changes

Cohort / File(s) Change Summary
Executor public layout
src/libexpr/include/nix/expr/parallel-eval.hh
Added public field: const std::unique_ptr<InterruptCallback> interruptCallback; to struct Executor. No other member/interface changes in this snippet.
Waiter domains & interrupt integration
src/libexpr/parallel-eval.cc
Introduced WaiterDomain (64-byte aligned) and a global static array waiterDomains of Sync<WaiterDomain> (size 128). Centralized declarations at top of the TU, removed duplicate later. Executor construction now wires an interruptCallback that iterates domains and calls notify_all(); waitOnThunk now calls checkInterrupt() after wakeups.
Alignment modernizations
src/libexpr/include/nix/expr/counter.hh, src/libexpr/include/nix/expr/symbol-table.hh
Replaced GCC __attribute__((aligned(64))) with standard C++ alignas(64) for Counter and for ContiguousArena::size (std::atomic<size_t>). Added a comment about cache-line alignment for Counter. Initialization values unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Exec as Executor
  participant IC as InterruptCallback
  participant Domains as WaiterDomains[128]
  participant Worker as WorkerThread
  participant Wait as waitOnThunk

  User->>Exec: construct(..., interruptCallback)
  Exec->>IC: store const unique_ptr

  Worker->>Wait: wait (domain cv wait)
  Wait-->>Worker: wake (spurious/regular)
  Wait->>Exec: checkInterrupt()

  IC-->>Domains: for each domain: notify_all()
  Domains-->>Worker: wake waiting threads
  Worker->>Exec: on wake, checkInterrupt()
  alt interrupt pending
    Exec-->>Worker: handle/propagate interrupt
  else
    Worker-->>Exec: resume evaluation
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I thump a note—an interrupt cry,
Wake every sleeper, far and nigh.
Domains aligned in tidy rows,
CVs clap, and onward goes.
I check, I nudge, then off we hop—
No more long naps; the work won't stop. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "Make threads waiting on thunks interruptible" is a concise, single-sentence summary that captures the PR's primary objective. The provided summaries and PR description show concrete changes to make waiters interruptible (per-domain waiter structures, wiring an Executor interruptCallback, and adding interrupt checks in the wait path) to allow Ctrl-C to interrupt infinite recursion. Therefore the title accurately reflects and is fully related to the main change.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch make-waiters-interruptible

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

In particular, this makes Ctrl-C work in case of infinite recursion.
@edolstra
edolstra force-pushed the make-waiters-interruptible branch from 0f9c55e to 745d9c6 Compare September 17, 2025 17:30
@github-actions

github-actions Bot commented Sep 17, 2025 •

Copy link
Copy Markdown

@github-actions
github-actions Bot temporarily deployed to pull request September 17, 2025 17:32 Inactive
@github-actions
github-actions Bot temporarily deployed to pull request September 17, 2025 17:41 Inactive

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/libexpr/parallel-eval.cc (1)

236-249: Balance waiting counters and time accounting on interrupt throw

If checkInterrupt() throws, state.currentlyWaiting isn’t decremented and microsecondsWaiting isn’t updated. This skews metrics and can affect diagnostics.

Apply:

-    auto now1 = std::chrono::steady_clock::now();
- 
-    while (true) {
-        domain.wait(domain->cv);
-        auto p0_ = p0.load(std::memory_order_acquire);
-        auto pd = static_cast<PrimaryDiscriminator>(p0_ & discriminatorMask);
-        if (pd != pdAwaited) {
-            assert(pd != pdThunk && pd != pdPending);
-            auto now2 = std::chrono::steady_clock::now();
-            state.microsecondsWaiting += std::chrono::duration_cast<std::chrono::microseconds>(now2 - now1).count();
-            state.currentlyWaiting--;
-            return p0_;
-        }
-        state.nrSpuriousWakeups++;
-        checkInterrupt();
-    }
+    auto waitStart = std::chrono::steady_clock::now();
+    try {
+        while (true) {
+            domain.wait(domain->cv);
+            auto p0_ = p0.load(std::memory_order_acquire);
+            auto pd = static_cast<PrimaryDiscriminator>(p0_ & discriminatorMask);
+            if (pd != pdAwaited) {
+                assert(pd != pdThunk && pd != pdPending);
+                auto now2 = std::chrono::steady_clock::now();
+                state.microsecondsWaiting += std::chrono::duration_cast<std::chrono::microseconds>(now2 - waitStart).count();
+                state.currentlyWaiting--;
+                return p0_;
+            }
+            state.nrSpuriousWakeups++;
+            checkInterrupt();
+        }
+    } catch (...) {
+        auto now2 = std::chrono::steady_clock::now();
+        state.microsecondsWaiting += std::chrono::duration_cast<std::chrono::microseconds>(now2 - waitStart).count();
+        state.currentlyWaiting--;
+        throw;
+    }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9f8a904 and 745d9c6.

📒 Files selected for processing (2)
  • src/libexpr/include/nix/expr/parallel-eval.hh (1 hunks)
  • src/libexpr/parallel-eval.cc (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build_x86_64-linux / vm_tests_smoke
🔇 Additional comments (2)
src/libexpr/include/nix/expr/parallel-eval.hh (1)

44-45: Public layout change: confirm ABI compatibility expectations

Adding a new public data member changes the struct layout. If libexpr is a stable ABI for downstreams/plugins, this is a breaking change; otherwise fine.

Would you prefer to hide this behind pImpl if ABI stability is required?

src/libexpr/parallel-eval.cc (1)

25-28: Resolved — callback runs in sigwait thread (not an async-signal handler)
createInterruptCallback callbacks are invoked from the sigwait-based signalHandlerThread (src/libutil/unix/signals.cc) and the header documents they run "in a non-signal context", so locking and calling condition_variable::notify_all() in the lambda is safe.

Comment on lines +44 to +45
const std::unique_ptr<InterruptCallback> interruptCallback;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add the missing include for unique_ptr

Header should include what it uses; relying on transitive includes is brittle and can break builds.

Apply this patch near the other STL includes:

 #include <functional>
 #include <queue>
 #include <future>
 #include <random>
+#include <memory>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const std::unique_ptr<InterruptCallback> interruptCallback;
#include <functional>
#include <queue>
#include <future>
#include <random>
#include <memory>
🤖 Prompt for AI Agents
In src/libexpr/include/nix/expr/parallel-eval.hh around lines 44 to 45, the
header declares a std::unique_ptr but does not directly include <memory>; add
#include <memory> near the other STL includes so the header "includes what it
uses" and avoids relying on transitive includes that can break builds.

Comment thread src/libexpr/parallel-eval.cc Outdated
Comment on lines +8 to +14
struct WaiterDomain
{
std::condition_variable cv;
} __attribute__((aligned(64))); // cache line alignment to prevent false sharing

static std::array<Sync<WaiterDomain>, 128> waiterDomains;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Include explicitly and prefer standard alignment

  • std::array is used without including .
  • Prefer alignas(64) over GCC-specific attribute for portability.

Apply:

-#include "nix/expr/primops.hh"
+#include "nix/expr/primops.hh"
+#include <array>
-struct WaiterDomain
-{
-    std::condition_variable cv;
-} __attribute__((aligned(64))); // cache line alignment to prevent false sharing
+struct alignas(64) WaiterDomain {
+    std::condition_variable cv;
+}; // cache line alignment to prevent false sharing
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
struct WaiterDomain
{
std::condition_variable cv;
} __attribute__((aligned(64))); // cache line alignment to prevent false sharing
static std::array<Sync<WaiterDomain>, 128> waiterDomains;
#include "nix/expr/primops.hh"
#include <array>
struct alignas(64) WaiterDomain {
std::condition_variable cv;
}; // cache line alignment to prevent false sharing
static std::array<Sync<WaiterDomain>, 128> waiterDomains;
🤖 Prompt for AI Agents
In src/libexpr/parallel-eval.cc around lines 8 to 14, the code uses std::array
without including <array> and uses the GCC-specific
__attribute__((aligned(64))); add an explicit #include <array> at the top of the
file and replace the attribute with the standard C++ alignment specifier
alignas(64) (apply it to the struct definition or the variable declaration) to
ensure portability and correct cache-line alignment.

@edolstra
edolstra enabled auto-merge September 17, 2025 17:46
@edolstra
edolstra added this pull request to the merge queue Sep 17, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/libexpr/include/nix/expr/symbol-table.hh (1)

32-36: Switch to standard alignas is good; consider a portable cache-line constant and encode invariants.

alignas(64) is fine; to future‑proof across architectures, consider using std::hardware_destructive_interference_size and add static_asserts to document the “separate cache line” intent.

Within this hunk:

-    alignas(64) std::atomic<size_t> size{0};
+    alignas(std::hardware_destructive_interference_size) std::atomic<size_t> size{0};

Outside this hunk (supporting changes):

// add once in a common header or here
#include <new> // std::hardware_destructive_interference_size
#include <cstddef> // std::offsetof

static_assert(alignof(nix::ContiguousArena) >= std::hardware_destructive_interference_size);
static_assert(offsetof(nix::ContiguousArena, size) % std::hardware_destructive_interference_size == 0);
static_assert(sizeof(nix::ContiguousArena) % std::hardware_destructive_interference_size == 0);
src/libexpr/include/nix/expr/counter.hh (1)

8-10: Cache-line alignment change LGTM; consider using the standard interference size and guarding it with asserts.

This aligns the whole Counter to 64 bytes, which avoids false sharing in arrays. For portability, prefer std::hardware_destructive_interference_size and assert the intended layout.

Within this hunk:

-struct alignas(64) Counter
+struct alignas(std::hardware_destructive_interference_size) Counter

Outside this hunk (supporting changes):

#include <new> // std::hardware_destructive_interference_size
static_assert(alignof(nix::Counter) >= std::hardware_destructive_interference_size);
static_assert(sizeof(nix::Counter) % std::hardware_destructive_interference_size == 0);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 745d9c6 and 167edd6.

📒 Files selected for processing (3)
  • src/libexpr/include/nix/expr/counter.hh (2 hunks)
  • src/libexpr/include/nix/expr/symbol-table.hh (1 hunks)
  • src/libexpr/parallel-eval.cc (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/libexpr/parallel-eval.cc

Merged via the queue into main with commit 4086731 Sep 17, 2025
@edolstra
edolstra deleted the make-waiters-interruptible branch September 17, 2025 18:11

This branch was previously deployed

1 inactive deployment
pull request — 167edd64 Deployed Sep 17, 2025 by github-actions[bot]
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