Patching NixOS module on-the-fly

Hello. I’d like to patch/edit some module before using it. Something like this:

{ modulesPath, config, lib, pkgs, ... }:

let
  patched-sd-image = pkgs.runCommand "patch-sd-image" { } ''
    cp "${modulesPath}/installer/sd-card/sd-image.nix" ./
    # TODO do some patching
    mkdir $out
    cp sd-image.nix $out/
  '';
in
{
  imports = [
    "${modulesPath}/profiles/base.nix"
    # "${modulesPath}/installer/sd-card/sd-image.nix"
    (import "${patched-sd-image}/sd-image.nix")
  ];
  ...
}

but I’m getting

error: infinite recursion encountered
       at /nix/store/d5znc1xk7glin7q5i97qnv75y7jzl7ph-source/lib/modules.nix:507:28:

I don’t get where the recursion is coming from (and --show-trace is of no help unless I want to study the whole evaluation logic of NixOS modules).

Does anybody have an idea why/where there is the infinite recursion? Thanks
(I can dump the whole code to github if it helps.)

I think this is because pkgs depends on overlays. Overlays can be defined in modules. That means modules needs to be fully evaluated before pkgs.

Does it help to mypkgs = import <nixpkgs> { }?

You cannot have an expression that depends on config nor pkgs in imports.I’ve spent too much tears on that specific papercut.