Skip to content

lib/modules: avoid redundant bothHave closure and opt.options - #582387

Merged
philiptaron merged 2 commits into
NixOS:masterfrom
tomberek:tomberek/bothHave_opt
Nov 4, 2026
Merged

philiptaron merged 2 commits into
NixOS:masterfrom
tomberek:tomberek/bothHave_opt

Conversation

@tomberek

@tomberek tomberek commented Nov 2, 2026

Copy link
Copy Markdown
Contributor
  • bothHave was a fresh closure re-allocated on each declaration
  • opt.options was selected multiple times per fold step; bound once to optOptions and reuse

Performance benefit is in the 1-4% range over various metrics which seems enough to justify a bit of inlining and non-DRY in such a core location impacting every module eval.

  • nrFunctionCalls -2.35%
  • Envs -1.98% (-1.58% bytes)
  • cpuTime -3.53%
  • GC totalBytes -0.27%

There should be no rebuilds (other than if docs/modules refer to the ./lib directory as a source). Not aware of any behavioral differences.

Assisted-by: Claude Sonnet 5 [email protected]

Things done

  • Fits [CONTRIBUTING.md], [pkgs/README.md], [maintainers/README.md] and other READMEs.
  • Follows the [automation/AI policy].
  • Built on platform:
    • x86_64-linux
    • aarch64-linux
    • aarch64-darwin
  • Tested, as applicable:
    • Ran nixpkgs-review on this PR. See [nixpkgs-review usage].
    • [NixOS tests] in [nixos/tests].
    • Tests in [lib/tests] or [pkgs/test] for functions and "core" functionality. (lib/tests/modules.sh)

…ionDecls

Inline the bothHave closure into 4 direct checks, and bind opt.options
once instead of reselecting it 8 times per fold step.

Measured on a real NixOS+Plasma eval, output byte-identical:
nrFunctionCalls -2.35%, Envs -1.98% (-1.58% bytes), cpuTime -3.53%,
GC totalBytes -0.27%.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Assisted-by: Claude Sonnet 5 <[email protected]>
@nixpkgs-ci nixpkgs-ci Bot added 10.rebuild-linux: 1-10 This PR causes between 1 and 10 packages to rebuild on Linux. 10.rebuild-darwin: 1-10 This PR causes between 1 and 10 packages to rebuild on Darwin. llm-assisted Contributions that include code generation with LLMs 6.topic: module system About "NixOS" module system internals 6.topic: lib The Nixpkgs function library labels Nov 2, 2026
@llakala

llakala commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude's favorite word (byte-identical) spotted in the commit message. I was aware that this could be cleaned up, but hadn't inlined it myself yet.

Diff looks fine, although I wonder if this function should instead be defined with something like zipAttrsWith, because these repeated merges have a really bad time complexity. Using a foldl' for single-element lists also seems like a bad idea.

While I'm here, here's another small cleanup patch:

From 5d2ed103758ed26c861c5ae6e5faff00f05d181f Mon Sep 17 00:00:00 2001
From: Eman Resu <[email protected]>
Date: Mon, 2 Nov 2026 16:59:18 -0500
Subject: [PATCH] lib/modules: use a single let binding for mergeOptionDecls

---
 lib/modules.nix | 15 ++++++---------
 1 file changed, 6 insertions(+), 9 deletions(-)

diff --git a/lib/modules.nix b/lib/modules.nix
index 3c4cbf750b86..95a5ef065eba 100644
--- a/lib/modules.nix
+++ b/lib/modules.nix
@@ -1072,7 +1072,12 @@ let
                   "The option `${showOption loc}' in `${opt._file}' is already declared in ${showFiles res.declarations}."
             else
               { };
-
+          getSubModules = optOptions.type.getSubModules or null;
+          submodules =
+            if getSubModules != null then
+              map (setDefaultModuleLocation opt._file) getSubModules ++ res.options
+            else
+              res.options;
         in
         if
           (res ? default && optOptions ? default)
@@ -1084,14 +1089,6 @@ let
           throw
             "The option `${showOption loc}' in `${opt._file}' is already declared in ${showFiles res.declarations}."
         else
-          let
-            getSubModules = optOptions.type.getSubModules or null;
-            submodules =
-              if getSubModules != null then
-                map (setDefaultModuleLocation opt._file) getSubModules ++ res.options
-              else
-                res.options;
-          in
           optOptions
           // res
           // {
-- 
2.56.0

@llakala

llakala commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Tried out inlining for length == 1. Seems to be very meaningful for my config.

{
  "attrset": {
    "lookups": "-0.01%",
    "merges": "-6.07%",
    "mergeCopies": "-0.95%"
  },
  "list": {
    "concats": "-0.1%"
  },
  "parser": {
    "expressions": "+0%"
  },
  "memoryBytes": {
    "envs": "-1.27%",
    "list": null,
    "sets": "-1.24%",
    "symbols": null,
    "values": "-1.18%",
    "total": "-1.2%"
  },
  "speed": {
    "primops": "+0%",
    "functionCalls": "-1.68%",
    "thunksMade": "-1.06%",
    "thunksAvoided": "-0.83%"
  }
}

Here's the patch:

From 361005b4ed1093223e37b6bde6f3ca3705445a10 Mon Sep 17 00:00:00 2001
From: Eman Resu <[email protected]>
Date: Mon, 2 Nov 2026 17:17:08 -0500
Subject: [PATCH] lib/modules: special-case a single declaration for
 mergeOptionDecls

---
 lib/modules.nix | 162 ++++++++++++++++++++++++++++--------------------
 1 file changed, 94 insertions(+), 68 deletions(-)

diff --git a/lib/modules.nix b/lib/modules.nix
index 95a5ef065eba..ec808c86bc00 100644
--- a/lib/modules.nix
+++ b/lib/modules.nix
@@ -1051,75 +1051,101 @@ let
     : 2\. Function argument
   */
   mergeOptionDecls =
-    loc:
-    foldl'
-      (
-        res: opt:
-        let
-          optOptions = opt.options;
-          typeSet =
-            if res ? type && optOptions ? type then
-              let
-                mergedType = res.type.typeMerge optOptions.type.functor;
-              in
-              if mergedType != null then
-                {
-                  type = mergedType;
-                }
-              else
-                # Keep in sync with the same error below!
-                throw
-                  "The option `${showOption loc}' in `${opt._file}' is already declared in ${showFiles res.declarations}."
-            else
-              { };
-          getSubModules = optOptions.type.getSubModules or null;
-          submodules =
-            if getSubModules != null then
-              map (setDefaultModuleLocation opt._file) getSubModules ++ res.options
-            else
-              res.options;
-        in
-        if
-          (res ? default && optOptions ? default)
-          || (res ? example && optOptions ? example)
-          || (res ? description && optOptions ? description)
-          || (res ? apply && optOptions ? apply)
-        then
-          # Keep in sync with the same error above!
-          throw
-            "The option `${showOption loc}' in `${opt._file}' is already declared in ${showFiles res.declarations}."
-        else
-          optOptions
-          // res
-          // {
-            declarations = res.declarations ++ [ opt._file ];
-            # In the case of modules that are generated dynamically, we won't
-            # have exact declaration lines; fall back to just the file being
-            # evaluated.
-            declarationPositions =
-              res.declarationPositions
-              ++ (
-                if opt.pos != null then
-                  [ opt.pos ]
-                else
-                  [
-                    {
-                      file = opt._file;
-                      line = null;
-                      column = null;
-                    }
-                  ]
-              );
-            options = submodules;
-          }
-          // typeSet
-      )
-      {
+    loc: decls:
+    if length decls == 1 then
+      let
+        opt = head decls;
+        optOptions = opt.options;
+        getSubModules = optOptions.type.getSubModules or null;
+      in
+      optOptions
+      // {
         inherit loc;
-        declarations = [ ];
-        declarationPositions = [ ];
-        options = [ ];
-      };
+        declarations = [ opt._file ];
+        declarationPositions =
+          if opt.pos != null then
+            [ opt.pos ]
+          else
+            [
+              {
+                file = opt._file;
+                line = null;
+                column = null;
+              }
+            ];
+        options =
+          if getSubModules != null then map (setDefaultModuleLocation opt._file) getSubModules else [ ];
+      }
+    else
+      foldl'
+        (
+          res: opt:
+          let
+            optOptions = opt.options;
+            typeSet =
+              if res ? type && optOptions ? type then
+                let
+                  mergedType = res.type.typeMerge optOptions.type.functor;
+                in
+                if mergedType != null then
+                  {
+                    type = mergedType;
+                  }
+                else
+                  # Keep in sync with the same error below!
+                  throw
+                    "The option `${showOption loc}' in `${opt._file}' is already declared in ${showFiles res.declarations}."
+              else
+                { };
+            getSubModules = optOptions.type.getSubModules or null;
+            submodules =
+              if getSubModules != null then
+                map (setDefaultModuleLocation opt._file) getSubModules ++ res.options
+              else
+                res.options;
+          in
+          if
+            (res ? default && optOptions ? default)
+            || (res ? example && optOptions ? example)
+            || (res ? description && optOptions ? description)
+            || (res ? apply && optOptions ? apply)
+          then
+            # Keep in sync with the same error above!
+            throw
+              "The option `${showOption loc}' in `${opt._file}' is already declared in ${showFiles res.declarations}."
+          else
+            optOptions
+            // res
+            // {
+              declarations = res.declarations ++ [ opt._file ];
+              # In the case of modules that are generated dynamically, we won't
+              # have exact declaration lines; fall back to just the file being
+              # evaluated.
+              declarationPositions =
+                res.declarationPositions
+                ++ (
+                  if opt.pos != null then
+                    [ opt.pos ]
+                  else
+                    [
+                      {
+                        file = opt._file;
+                        line = null;
+                        column = null;
+                      }
+                    ]
+                );
+              options = submodules;
+            }
+            // typeSet
+        )
+        {
+          inherit loc;
+          declarations = [ ];
+          declarationPositions = [ ];
+          options = [ ];
+        }
+        decls;
 
   /**
     Merge all the definitions of an option to produce the final
-- 
2.56.0

@tomberek

tomberek commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

side-note: I'm finding that such inlining, specializations and micro-optimizations might be better in Nixpkgs than trying to shoe-horn them into generic Nix evaluator. But it also makes Nixpkgs more unwieldy and complicated.

@llakala

llakala commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

side-note: I'm finding that such inlining, specializations and micro-optimizations might be better in Nixpkgs than trying to shoe-horn them into generic Nix evaluator. But it also makes Nixpkgs more unwieldy and complicated.

Sure - but there are functions like applyModuleArgs that we can't write performantly with CppNix as it stands:

  applyModuleArgs =
    args@{ config, ... }:
    key: f:
    let
      # Module arguments are resolved in a strict manner when attribute set
      # deconstruction is used.  As the arguments are now defined with the
      # config._module.args option, the strictness used on the attribute
      # set argument would cause an infinite loop, if the result of the
      # option is given as argument.
      #
      # To work-around the strictness issue on the deconstruction of the
      # attributes set argument, we create a new attribute set which is
      # constructed to satisfy the expected set of attributes.  Thus calling
      # a module will resolve strictly the attributes used as argument but
      # not their values.  The values are forwarding the result of the
      # evaluation of the option.
      extraArgs = mapAttrs (
        name: _:
        addErrorContext ''while evaluating the module argument `${name}' in "${key}":'' (
          args.${name} or (addErrorContext
            "noting that argument `${name}` is not externally provided, so querying `_module.args` instead, requiring `config`"
            config._module.args.${name}
          )
        )
      ) (functionArgs f);

      # Note: we append in the opposite order such that we can add an error
      # context on the explicit arguments of "args" too. This update
      # operator is used to make the "args@{ ... }: with args.lib;" notation
      # works.
    in
    f (args // extraArgs);

This function consistently pops up at the top when I profile, and something like NixOS/nix#9159 would go a long way. The same is true for new builtins, like NixOS/nix#11888, or faster parsing (just parsing haskell-modules ends up as a meaningful percentage of eval).

@tomberek

tomberek commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

While I'm here, here's another small cleanup patch:

Merged the cleanup patch.

Let's do the length specialization separate.

applyModuleArgs: i've been interested in some sort of lazy-attr/proxy (NixOS/nix@master...flox:nix:dynamic_select was a quick hack that seemed powerful)

haskell-modules: also yup, can we mitigate that one by breaking it up into smaller pieces, only forced as needed?

@roberth

roberth commented Nov 3, 2026

Copy link
Copy Markdown
Member

functions like applyModuleArgs that we can't write performantly

As a maintainer of both projects I wouldn't mind a primop like builtins.callPerAttr f a fContextStr that behaves like that, and which could do some serious short-circuiting.
The right answer is to never use strict lambdas as modules in the first place, not even just for this reason, but that ship might have sailed.
Or has it... We could just extend function reflection, and short-circuit into a completely regular simple call when the module is not a strict function but a simple lazy lambda like sys: { }.
This would then also solve the shadowing issue when nesting:

sys: {
  config.grub.enable = !sys.config.systemd-boot.enable;
  config.specialisations.foo.config =
    foo: {
      config.bar = foo.config.qux * sys.config.qux;
      # referencing both systems would have required a `let` dance
      # as `config` collides with `config`.
    };
}

and frankly the above looks more intuitive anyway.

@roberth

roberth commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

How could I forget specialArgs! The above wouldn't support those unless we also add the proxy objects to bring them back. One such proxy object per submodule seems cheap. (They wouldn't be very expensive, I assume, but might as well as far as this use case is concerned)

Short of doing that, it might be a reasonable concession to require { arg }: for retrieving specialArgs.arg and/or _module.args.arg. Also having _module.specialArgs helps.
It's just not the 1:1 translation one might hope for.

@nixpkgs-ci nixpkgs-ci Bot added the 12.approvals: 1 This PR was reviewed and approved by one person. label Nov 3, 2026
@tomberek tomberek mentioned this pull request Nov 3, 2026
2 of 13 tasks
@philiptaron
philiptaron added this pull request to the merge queue Nov 4, 2026
Merged via the queue into NixOS:master with commit 87c3b8b Nov 4, 2026
29 checks passed
@llakala

llakala commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Will PR a few changes based on top on this PR either tonight or tomorrow. Stats for my config:

{
  "attrset": {
    "lookups": "-1.73%",
    "merges": "-6.07%",
    "mergeCopies": "-0.95%"
  },
  "list": {
    "concats": "-0.1%"
  },
  "parser": {
    "expressions": "+0%"
  },
  "memoryBytes": {
    "envs": "-4.12%",
    "list": "-0.88%",
    "sets": "-1.24%",
    "symbols": "+0%",
    "values": "-1.83%",
    "total": "-1.94%"
  },
  "speed": {
    "primops": "-1.15%",
    "functionCalls": "-4.85%",
    "thunksMade": "-1.83%",
    "thunksAvoided": "-2.93%"
  }
}

@philiptaron

philiptaron commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Ping me on it, @llakala.

Claude and I are working on a couple more things in this area

Here's my slop (as in -- I'm not putting this up for review, just collaboration) which I think gets down to 3.7% fewer instructions:

@llakala

llakala commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

I'll skip the slop - you can commit those on your own time.

@llakala

llakala commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Put up #583020.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

6.topic: lib The Nixpkgs function library 6.topic: module system About "NixOS" module system internals 10.rebuild-darwin: 1-10 This PR causes between 1 and 10 packages to rebuild on Darwin. 10.rebuild-linux: 1-10 This PR causes between 1 and 10 packages to rebuild on Linux. 12.approvals: 1 This PR was reviewed and approved by one person. llm-assisted Contributions that include code generation with LLMs

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants