Skip to content

Fix infinite recursion detection - #213

Merged
edolstra merged 1 commit into
mainfrom
detect-infinite-recursion-v2
Sep 26, 2025
Merged

edolstra merged 1 commit into
mainfrom
detect-infinite-recursion-v2

Conversation

@edolstra

@edolstra edolstra commented Sep 25, 2025 •

Copy link
Copy Markdown
Collaborator

Motivation

This detects infinite recursion within the same thread (i.e. when a thread waits on a thunk that it's already evaluating). This is done by storing a thread ID in pending/awaited values.

It does not detect cycles between threads, e.g. in rec { x = y; y = x; } if x and y are marked as pending by different threads. But those are much less likely in practice.

Context

Summary by CodeRabbit

  • New Features
    • Improved multi-threaded evaluation with per-thread tracking to prevent self-deadlocks.
  • Performance
    • More efficient synchronization when multiple threads evaluate the same expression, improving parallel performance.
  • Bug Fixes
    • Fixed rare deadlocks and infinite recursion during evaluation under heavy concurrency.
    • Corrected handling of pending/awaited states to avoid stalls and spurious waits.
  • Reliability
    • Enhanced stability in parallel builds by tightening state transitions and early-exit conditions during waits.
    • Reduced race conditions when finalizing values under contention.

This detects infinite recursion within the same thread (i.e. when a
thread waits on a thunk that it's already evaluating). This is done by
storing a thread ID in pending/awaited values.

It does not detect cycles between threads, e.g. in `rec { x = y; y =
x; }` if `x` and `y` are marked as pending by different threads. But
those are much less likely in practice.
@edolstra edolstra added the flake-regression-test Run the flake regressions test suite on this PR label Sep 25, 2025
@coderabbitai

coderabbitai Bot commented Sep 25, 2025 •

Copy link
Copy Markdown

Walkthrough

Introduces per-eval-thread identifiers and propagates them through thunk waiting. Updates waitOnThunk’s signature to take a PackedPointer instead of a boolean, revises atomic pending/awaited transitions to include thread tags, and adjusts call sites and control flow accordingly across header and implementation.

Changes

Cohort / File(s) Summary
API/signature update: waitOnThunk
src/libexpr/include/nix/expr/value.hh, src/libexpr/parallel-eval.cc
Changes waitOnThunk signature from (EvalState&, bool awaited) to (EvalState&, PackedPointer p0/expectedP0). Updates specialization declaration and implementation; call sites now pass the current p0 instead of a boolean.
Per-thread evaluation identifiers
src/libexpr/include/nix/expr/eval-inline.hh, src/libexpr/parallel-eval.cc
Adds thread-local eval thread ID: extern declaration in header and definition/initialization via nextEvalThreadId/myEvalThreadId in implementation for deadlock/recursion detection and tagging pending states.
Thunk pending/awaited control-flow and tagging
src/libexpr/include/nix/expr/eval-inline.hh, src/libexpr/parallel-eval.cc
Atomic CAS now encodes pdPending with the current thread ID in discriminator bits. Updated branches pass p0_ to waitOnThunk, preserve discriminator-derived state, add early-exit checks, and incorporate thread-id comparisons to avoid infinite recursion.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor T as Eval Thread
  participant VS as ValueStorage (Value)
  participant WT as waitOnThunk(...)
  participant D as Domain/CondVar

  T->>VS: Force value / CAS to pending
  note right of VS: Set pdPending | (myEvalThreadId << discriminatorBits)

  T->>WT: waitOnThunk(state, expectedP0 = p0)
  WT->>WT: Decode PrimaryDiscriminator from expectedP0
  alt Already advanced/finalized
    WT-->>T: Return current p0
  else Pending/awaited
    WT->>WT: Compare threadId in p0 vs myEvalThreadId
    opt Detect recursion / self-wait
      WT-->>T: Early return / avoid infinite recursion
    end
    WT->>D: Wait on condvar for completion
    D-->>WT: Notified (completed or state changed)
    WT-->>T: Return updated p0
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • cole-h

Poem

I thump my paw—await, not long!
Threads now wear tags, a careful throng.
Packed bits whisper, “Pending—mine!”
No deadlock burrow, clean design.
When thunks awaken, hops ensue—
A hare’s fast path from wait to do. 🐇✨

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 succinctly summarizes the primary purpose of the changeset by stating that infinite recursion detection is being fixed, which directly aligns with the PR objectives and code modifications. It is concise, clear, and specific enough for a reviewer scanning the history to understand the main focus without extraneous details. The phrasing is precise and avoids vagueness or unrelated terms while accurately reflecting the scope of changes. Therefore, it meets the guidelines for a well-formed pull request title.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch detect-infinite-recursion-v2

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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

@github-actions

Copy link
Copy Markdown

@github-actions
github-actions Bot temporarily deployed to pull request September 25, 2025 14:12 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: 0

🧹 Nitpick comments (4)
src/libexpr/include/nix/expr/value.hh (2)

808-809: Rename param to avoid shadowing class member and to match definition.

The parameter name ‘p0’ shadows the class member ‘p0’ and doesn’t match the implementation (‘expectedP0’). Rename for clarity.

Apply this diff:

-    PackedPointer waitOnThunk(EvalState & state, PackedPointer p0);
+    PackedPointer waitOnThunk(EvalState & state, PackedPointer expectedP0);

820-822: Keep parameter name consistent with implementation.

Mirror the implementation name to reduce confusion.

Apply this diff:

-ValueStorage<sizeof(void *)>::waitOnThunk(EvalState & state, PackedPointer p0);
+ValueStorage<sizeof(void *)>::waitOnThunk(EvalState & state, PackedPointer expectedP0);
src/libexpr/include/nix/expr/eval-inline.hh (1)

113-117: Use acq_rel on successful CAS when transitioning to pending.

Use release semantics on success to follow the “p1 before p0” publishing rule and match other transitions.

Apply this diff:

-            if (!p0.compare_exchange_strong(
+            if (!p0.compare_exchange_strong(
                     p0_,
                     pdPending | (myEvalThreadId << discriminatorBits),
-                    std::memory_order_acquire,
+                    std::memory_order_acq_rel,
                     std::memory_order_acquire)) {
src/libexpr/parallel-eval.cc (1)

201-233: Use acq_rel on successful CAS when marking awaited.

Release semantics on success better document intent and align with other state transitions.

Apply this diff:

-        PackedPointer p0_ = expectedP0;
-        if (!p0.compare_exchange_strong(
-                p0_,
-                pdAwaited | (threadId << discriminatorBits),
-                std::memory_order_acquire,
-                std::memory_order_acquire)) {
+        PackedPointer p0_ = expectedP0;
+        if (!p0.compare_exchange_strong(
+                p0_,
+                pdAwaited | (threadId << discriminatorBits),
+                std::memory_order_acq_rel,
+                std::memory_order_acquire)) {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 823eed1 and aca3fae.

📒 Files selected for processing (3)
  • src/libexpr/include/nix/expr/eval-inline.hh (3 hunks)
  • src/libexpr/include/nix/expr/value.hh (2 hunks)
  • src/libexpr/parallel-eval.cc (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
src/libexpr/parallel-eval.cc (1)
src/libexpr/include/nix/expr/value.hh (11)
  • waitOnThunk (821-821)
  • state (156-157)
  • state (169-169)
  • state (174-181)
  • state (799-799)
  • state (808-808)
  • state (1036-1036)
  • static_cast (514-517)
  • p0_ (524-540)
  • p0_ (524-524)
  • p0 (794-797)
src/libexpr/include/nix/expr/eval-inline.hh (2)
src/libexpr/include/nix/expr/value.hh (12)
  • p0 (794-797)
  • p0_ (524-540)
  • p0_ (524-524)
  • pd (596-619)
  • static_cast (514-517)
  • waitOnThunk (821-821)
  • state (156-157)
  • state (169-169)
  • state (174-181)
  • state (799-799)
  • state (808-808)
  • state (1036-1036)
src/libexpr/parallel-eval.cc (2)
  • waitOnThunk (194-261)
  • waitOnThunk (195-195)
src/libexpr/include/nix/expr/value.hh (1)
src/libexpr/parallel-eval.cc (2)
  • waitOnThunk (194-261)
  • waitOnThunk (195-195)
⏰ 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). (2)
  • GitHub Check: build_aarch64-darwin / build
  • GitHub Check: build_x86_64-linux / build
🔇 Additional comments (6)
src/libexpr/include/nix/expr/eval-inline.hh (3)

122-123: Call-site update looks correct.

Passing the observed p0_ to waitOnThunk preserves the owner thread tag.

Consider edge-cases where p0_ is stale; the implementation handles this via CAS/early-exit under the domain lock. No action needed.


148-149: Call-site update LGTM.

Consistent with the new waitOnThunk contract.


91-97: Single definition of myEvalThreadId confirmed
Definition only in parallel-eval.cc; extern declaration in eval-inline.hh is correct.

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

194-196: Signature specialization update matches header and call sites.

Good alignment across declaration, definition, and usage.


236-239: Infinite recursion detection within the same thread: LGTM.

Correctly compares owner thread tag with current thread.


190-192: Thread-local ID initialization verified
Search shows myEvalThreadId is only referenced in parallel-eval.cc and eval-inline.hh; every evaluation path (including the main thread) odr-uses it, triggering its initialization. No changes needed.

@cole-h cole-h left a comment

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.

Adequately detected infrec in a few cases I've run into recently. Nice!

@edolstra
edolstra added this pull request to the merge queue Sep 26, 2025
Merged via the queue into main with commit 74f2dcc Sep 26, 2025
@edolstra
edolstra deleted the detect-infinite-recursion-v2 branch September 26, 2025 09:28
@KiaraGrouwstra KiaraGrouwstra mentioned this pull request Sep 26, 2025
5 of 19 tasks

This branch was previously deployed

1 inactive deployment
pull request — aca3fae1 Deployed Sep 25, 2025 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

flake-regression-test Run the flake regressions test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants