Skip to content

Fix race condition in Value::isTrivial() - #192

Merged
edolstra merged 1 commit into
mainfrom
fix-isTrivial
Sep 4, 2025
Merged

edolstra merged 1 commit into
mainfrom
fix-isTrivial

Conversation

@edolstra

@edolstra edolstra commented Sep 4, 2025 •

Copy link
Copy Markdown
Collaborator

Motivation

The use of thunk() is racy since the value might stop being a thunk while we're accessing it.

This is unlikely to happen in practice, but can occur with test cases like

with builtins;
let
  range = first: last: if first > last then [ ] else genList (n: first + n) (last - first + 1);
in
builtins.listToAttrs
  (map
    (n: {
      name = "n${toString n}";
      value = (builtins.getFlake "github:NixOS/hydra/8481acda2fa07b353ef716e4933c5f213cdd6f45").nixosConfigurations.container.config.system.build.toplevel.drvPath;
    })
    (range 0 7))

where we're evaluating the same flake multiple times in parallel, leading to segfaults or errors like

error: expected a set but got a set at /nix/store/aj913djlr9z5f6kkzawl8q4cnblm0wma-source/flake.nix:6:3

Context

Summary by CodeRabbit

  • Improvements

    • Broader detection of "trivial" values and more aggressive auto-forcing, improving evaluation responsiveness.
    • More consistent behavior under concurrency to reduce stalls.
    • Slightly clearer and more accurate type error messages.
  • Refactor

    • Trivial-value detection reworked to be more precise and thread-aware.
  • Chores

    • Public API adjusted to expose triviality checks at storage level while preserving user-facing behavior.

@coderabbitai

coderabbitai Bot commented Sep 4, 2025 •

Copy link
Copy Markdown

Walkthrough

Refactors triviality detection from Value to a ValueStorage<sizeof(void *)> specialization using pointer-tagged state and acquire-load synchronization; updates flake logic to force any value reported trivial and caches value.type() in expectType.

Changes

Cohort / File(s) Summary
Eval triviality refactor
src/libexpr/eval.cc, src/libexpr/include/nix/expr/value.hh
Moves isTrivial() from Value to an explicit ValueStorage<sizeof(void *)>::isTrivial() specialization; implements an acquire-load pointer-tag discriminator path that treats thunk/pending/awaited states specially, unwraps Expr* via untagPointer, and checks for ExprAttrs (empty dynamicAttrs), ExprLambda, or ExprList. Removes Value::isTrivial() declaration and adds ValueStorage<ptrSize>::isTrivial() declaration/specialization.
Flake forcing and type check tweak
src/libflake/flake.cc
forceTrivialValue now forces when value.isTrivial() is true (removed finished-guard). expectType caches value.type() into a local variable before comparison and using in error message. No public signatures changed.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant Flake as Flake logic
  participant V as ValueStorage
  participant Eval as Eval internals

  Caller->>Flake: forceTrivialValue(value)
  Flake->>V: isTrivial()
  Note over V,Eval: atomic load p0 (acquire), read p1, derive PrimaryDiscriminator
  alt Thunk/Pending/Awaited
    alt Application tagged
      V-->>Flake: false
    else Not application
      V->>Eval: untagPointer(p1) → Expr*
      Eval-->>V: check Expr: Attrs(empty dyn)/Lambda/List?
      V-->>Flake: true/false
    end
  else Non-thunk-like
    V-->>Flake: true
  end
  alt isTrivial == true
    Flake->>Eval: force(value)
    Eval-->>Flake: forced result
    Flake-->>Caller: return
  else
    Flake-->>Caller: no-op
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I twitch my whiskers, sniff the tags,
Untagged pointers, tiny flags.
If lambda, list, or attr-set bare,
I hop to force with gentle care.
Concurrency-safe — I bound and brag. 🥕


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 31f255e and 7ccfc62.

📒 Files selected for processing (3)
  • src/libexpr/eval.cc (1 hunks)
  • src/libexpr/include/nix/expr/value.hh (2 hunks)
  • src/libflake/flake.cc (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/libflake/flake.cc
  • src/libexpr/include/nix/expr/value.hh
  • src/libexpr/eval.cc
⏰ 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_aarch64-darwin / build
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-isTrivial

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions

github-actions Bot commented Sep 4, 2025 •

Copy link
Copy Markdown

@github-actions
github-actions Bot temporarily deployed to pull request September 4, 2025 17:04 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: 1

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

780-789: API surface note: isTrivial() is only declared on the bit-packed specialization.

On 32-bit or non-bitpacked builds, ValueStorage<ptrSize, void> does not declare isTrivial(), which will break call sites like value.isTrivial(). If 32-bit is unsupported, that’s fine; otherwise, add a conservative fallback on the generic ValueStorage (e.g., return isFinished(getInternalType())).

Apply this minimal fallback in the non-bitpacked variant:

 class ValueStorage : public detail::ValueBase
 {
   ...
+public:
+  // Fallback for non-bitpacked builds.
+  bool isTrivial() const noexcept { return nix::isFinished(getInternalType()); }
 };

Please confirm whether non-64-bit builds are still supported in this repo’s CI matrix.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 869a589 and 31f255e.

📒 Files selected for processing (3)
  • src/libexpr/eval.cc (1 hunks)
  • src/libexpr/include/nix/expr/value.hh (3 hunks)
  • src/libflake/flake.cc (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
src/libflake/flake.cc (2)
src/libexpr/eval.cc (6)
  • state (1143-1166)
  • state (1143-1143)
  • showType (107-137)
  • showType (107-107)
  • showType (139-161)
  • showType (139-139)
src/libexpr/include/nix/expr/value.hh (9)
  • state (159-160)
  • state (172-172)
  • state (177-184)
  • state (802-802)
  • state (811-811)
  • state (1038-1038)
  • pos (1253-1253)
  • t (1060-1064)
  • showType (1013-1013)
src/libexpr/eval.cc (1)
src/libexpr/include/nix/expr/value.hh (8)
  • p1 (790-794)
  • p0_ (527-543)
  • p0_ (527-527)
  • p0 (797-800)
  • pd (599-622)
  • static_cast (517-520)
  • untagPointer (512-515)
  • untagPointer (512-512)
src/libexpr/include/nix/expr/value.hh (1)
src/libexpr/eval.cc (2)
  • isTrivial (182-200)
  • isTrivial (182-182)
⏰ 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 (4)
src/libflake/flake.cc (2)

31-33: Good: force trivial values unconditionally (thread-safe and simpler).

Using value.isTrivial() alone is correct with the new storage-aware implementation; forcing finished values is a no-op and avoids the prior racy thunk check.


38-41: Minor clarity/perf win in expectType.

Caching value.type() and using showType(t) in the message is cleaner and avoids double computation.

src/libexpr/include/nix/expr/value.hh (2)

22-24: Forward declarations look right.

These match the uses in the new triviality check logic and avoid header include churn.


825-827: Explicit specialization declaration is appropriate.

Matches the out-of-line definition in eval.cc and keeps ODR tidy.

Comment thread src/libexpr/eval.cc
Comment on lines +181 to 200
template<>
bool ValueStorage<sizeof(void *)>::isTrivial() const
{
return isFinished()
|| (isa<tThunk>()
&& ((dynamic_cast<ExprAttrs *>(thunk().expr) && ((ExprAttrs *) thunk().expr)->dynamicAttrs.empty())
|| dynamic_cast<ExprLambda *>(thunk().expr) || dynamic_cast<ExprList *>(thunk().expr)));
auto p1_ = p1; // must acquire before reading p0, since thunks can change
auto p0_ = p0.load(std::memory_order_acquire);

auto pd = static_cast<PrimaryDiscriminator>(p0_ & discriminatorMask);

if (pd == pdThunk || pd == pdPending || pd == pdAwaited) {
bool isApp = p1_ & discriminatorMask;
if (isApp)
return false;
auto expr = untagPointer<Expr *>(p1_);
return (dynamic_cast<ExprAttrs *>(expr) && ((ExprAttrs *) expr)->dynamicAttrs.empty())
|| dynamic_cast<ExprLambda *>(expr) || dynamic_cast<ExprList *>(expr);
}

else
return true;
}

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

Fix acquire/load ordering bug when reading p0/p1 (data race risk).

You read p1 before the acquire load of p0. To pair with finish()’s release store (which writes p1 then p0), readers must load p0 with acquire first, then read p1. Otherwise p1_ can be observed stale or mismatched to p0_.

Apply:

-    auto p1_ = p1; // must acquire before reading p0, since thunks can change
-    auto p0_ = p0.load(std::memory_order_acquire);
+    auto p0_ = p0.load(std::memory_order_acquire); // acquire before reading p1, since thunks can change
+    auto p1_ = p1;

Optional readability nit: avoid the C-style cast when checking ExprAttrs:

-        return (dynamic_cast<ExprAttrs *>(expr) && ((ExprAttrs *) expr)->dynamicAttrs.empty())
+        if (auto attrs = dynamic_cast<ExprAttrs *>(expr); attrs && attrs->dynamicAttrs.empty())
+            return true;
+        return dynamic_cast<ExprLambda *>(expr) || dynamic_cast<ExprList *>(expr);
📝 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
template<>
bool ValueStorage<sizeof(void *)>::isTrivial() const
{
return isFinished()
|| (isa<tThunk>()
&& ((dynamic_cast<ExprAttrs *>(thunk().expr) && ((ExprAttrs *) thunk().expr)->dynamicAttrs.empty())
|| dynamic_cast<ExprLambda *>(thunk().expr) || dynamic_cast<ExprList *>(thunk().expr)));
auto p1_ = p1; // must acquire before reading p0, since thunks can change
auto p0_ = p0.load(std::memory_order_acquire);
auto pd = static_cast<PrimaryDiscriminator>(p0_ & discriminatorMask);
if (pd == pdThunk || pd == pdPending || pd == pdAwaited) {
bool isApp = p1_ & discriminatorMask;
if (isApp)
return false;
auto expr = untagPointer<Expr *>(p1_);
return (dynamic_cast<ExprAttrs *>(expr) && ((ExprAttrs *) expr)->dynamicAttrs.empty())
|| dynamic_cast<ExprLambda *>(expr) || dynamic_cast<ExprList *>(expr);
}
else
return true;
}
template<>
bool ValueStorage<sizeof(void *)>::isTrivial() const
{
auto p0_ = p0.load(std::memory_order_acquire); // acquire before reading p1, since thunks can change
auto p1_ = p1;
auto pd = static_cast<PrimaryDiscriminator>(p0_ & discriminatorMask);
if (pd == pdThunk || pd == pdPending || pd == pdAwaited) {
bool isApp = p1_ & discriminatorMask;
if (isApp)
return false;
auto expr = untagPointer<Expr *>(p1_);
if (auto attrs = dynamic_cast<ExprAttrs *>(expr); attrs && attrs->dynamicAttrs.empty())
return true;
return dynamic_cast<ExprLambda *>(expr) || dynamic_cast<ExprList *>(expr);
} else {
return true;
}
}
🤖 Prompt for AI Agents
In src/libexpr/eval.cc around lines 181 to 200, the reader currently reads p1
before performing the acquire load of p0 which can observe a stale/mismatched p1
vs p0; to fix, perform the acquire load of p0 first, compute the primary
discriminator from that p0_, then read p1 (non-atomic) into p1_ so the
load-order pairs with finish()’s release store (which writes p1 then p0); also
replace the C-style cast when checking ExprAttrs with a safer dynamic_cast usage
for clarity.

@edolstra
edolstra added this pull request to the merge queue Sep 4, 2025
The use of thunk() is racy since the value might stop being a thunk
while we're accessing it.
@edolstra
edolstra removed this pull request from the merge queue due to a manual request Sep 4, 2025
@edolstra
edolstra enabled auto-merge September 4, 2025 19:53
@github-actions
github-actions Bot temporarily deployed to pull request September 4, 2025 20:08 Inactive
@edolstra
edolstra added this pull request to the merge queue Sep 4, 2025
Merged via the queue into main with commit 525acde Sep 4, 2025
@edolstra
edolstra deleted the fix-isTrivial branch September 4, 2025 20:39

This branch was previously deployed

1 inactive deployment
pull request — 7ccfc62b Deployed Sep 4, 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