Skip to content

wrapPythonProgram: use site.addsitedir instead of PYTHONPATH - #17749

Merged
abbradar merged 6 commits into
NixOS:stagingfrom
abbradar:python-set
Aug 19, 2016
Merged

abbradar merged 6 commits into
NixOS:stagingfrom
abbradar:python-set

Conversation

@abbradar

Copy link
Copy Markdown
Member
Motivation for this change

Consider two applications, "a" and "b". "a" uses Python 2.7 and enum34, which exports enum module. It calls "b" via exec, which uses Python 3.5. In this Python there's its own enum module, but it's overridden by enum34 because it's in PYTHONPATH. As a result enum module doesn't work and there are weird errors.

Real life example: gajim calls qutebrowser to open an URL, which crashes instead.

I don't know any better solution to this problem than the proposed patch. It looks good to me but it can potentially break some workflows which somehow rely on PYTHONPATH postfixes.

Things done
  • Tested using sandboxing
    (nix.useChroot on NixOS,
    or option build-use-chroot in nix.conf
    on non-NixOS)
  • Built on platform(s)
    • NixOS
    • OS X
    • Linux
  • Tested compilation of all pkgs that depend on this change using nix-shell -p nox --run "nox-review wip"
  • Tested execution of all binary files (usually in ./result/bin/)
  • Fits CONTRIBUTING.md.

cc @domenkozar

@abbradar abbradar added 0.kind: bug Something is broken 6.topic: python Python is a high-level, general-purpose programming language. 1.severity: mass-rebuild labels Aug 15, 2016
@mention-bot

Copy link
Copy Markdown

@abbradar, thanks for your PR! By analyzing the annotation information on this pull request, we identified @mbakke, @adnelson and @edolstra to be potential reviewers

@FRidh

FRidh commented Aug 15, 2016

Copy link
Copy Markdown
Member

@abbradar I think the problem you describe is basically #11423.
#11423 (comment) works well for that.

@garbas, you proposed this solution as well, right?

@abbradar

Copy link
Copy Markdown
Member Author

@FRidh I think the problem is somewhat different. The problem that is described there IIUC is that when you put a derivation into propagatedBuildInputs, you get not only its binaries but also its Python modules in your PYTHONPATH. buildEnv works nicely to isolate that. This one is messier -- inside any Python executable PYTHONPATH is set to its dependencies closure, and when it tries to exec another Python executable, the other one prefixes its PYTHONPATH to the first one, and hilarity ensues.

@FRidh

FRidh commented Aug 15, 2016

Copy link
Copy Markdown
Member

Therefore I think we shouldn't set/prefix PYTHONPATH at all, and use buildEnv with --set PYTHONHOME. It requires a lot of work though; a solution would have to be found for the checkPhase and all the code outside python-packages.nix that sets PYTHONPATH would have to use python.buildEnv.

Anyway, until then I think I am fine with this change as I don't add anything to PYTHONPATH.

@abbradar

abbradar commented Aug 15, 2016 •

Copy link
Copy Markdown
Member Author

Oh, I got it now -- yes, it would help. BTW this patch can be a small preparation step -- if anything relies on prefixing PYTHONPATH it would not work with your idea easily, and others who set it can be probably converted into buildEnv much more straightforwardly. This patch would force us to fix the first cases, if any.

EDIT: after more thoughts -- nah, it wouldn't, only a sub-case of people setting PYTHONPATH before running wrapped Python binaries.

@FRidh

FRidh commented Aug 15, 2016

Copy link
Copy Markdown
Member

On second thought, while I don't set or append/prepend to PYTHONPATH myself, I think it is an important enough feature that we shouldn't break that possibility, and therefore shouldn't use --set PYTHONPATH.

@garbas

garbas commented Aug 15, 2016 •

Copy link
Copy Markdown
Member

i consider usage of -prefix a bug. some programs will break or behave differently just because somewhere in environment there is a PYTHONPATH defined. i'm strongly about merging this asap.

we should never allow to extend PYTHONPATH this way but provide a way (eg. via buildEnv) to create custom python environments.

@FRidh

FRidh commented Aug 15, 2016 •

Copy link
Copy Markdown
Member

some programs will break or behave differently just because somewhere in environment there is a PYTHONPATH defined.

Agreed. And therefore we should solve the root of the problem: stop using PYTHONPATH in our wrappers to find Python modules.

we should never allow to extend PYTHONPATH this way

PYTHONPATH is a Python feature. People will want to be able to use it. Using --set completely takes away that possibility.

but provide a way (eg. via buildEnv) to create custom python environments.

We can add an option to buildEnv to modify PYTHONPATH, either on a per-application basis, or for the whole environment. We let buildEnv set or unset PYTHONPATH.

Edit:

Maybe we should, in general, use wrappers only in environments and not inside derivations that build packages. cc @bennofs

@adnelson

Copy link
Copy Markdown
Contributor

This LGTM and would fix some issues I've had. Agreed that a better solution would be nice.

@garbas

garbas commented Aug 16, 2016

Copy link
Copy Markdown
Member

for me this is a quick improvement over currently (for me) broken way how we handle python binaries. i got bitten by this bug many times and in all my projects i've been using --set instead of --prefix for exactly this reason.

this PR wont fix everything in python but it for sure will make python stuff more reproducible across machines.

i would like to merge this, but i would also like some comments on this subject from @domenkozar and @bennofs

@bennofs

bennofs commented Aug 16, 2016 •

Copy link
Copy Markdown
Contributor

100% agree with this patch. I didn't know it used --prefix before, that seems like madness to me! Python applications' PYTHONPATH should not depend on the environment they run in.

People can still use PYTHONPATH, they just can't mix it with nix-built packages. I think this is similar to how we handle LD_LIBRARY_PATH, that also is not really supported for nix built packages (we don't override it, but I think there were some weird interactions).

@garbas

garbas commented Aug 16, 2016

Copy link
Copy Markdown
Member

also another thing. is this triggering a mass-rebuild? i think we could easily apply this directly to master. yes quite few packages will need to be rebuilt but nothing than hydra can not handle. @domenkozar you thoughts on this?

@domenkozar

Copy link
Copy Markdown
Member

I don't see a reason from top of my head where --prefix would be useful, so +1 from me.

@FRidh

FRidh commented Aug 16, 2016 •

Copy link
Copy Markdown
Member

I think this breaks

nix-shell -p pythonPackages.ipython pythonPackages.numpy --run "ipython -c 'import numpy'"

because ipython won't be able to find numpy since the hook adds to PYTHONPATH. Testing now.

(Note that I anyway think we should replace this kind of usage with buildEnv)

@FRidh

FRidh commented Aug 16, 2016 •

Copy link
Copy Markdown
Member

invoking pytest in a checkPhase already fails

edit: that's because in the installPhase we append to PYTHONPATH but by using --set the modules that need to be tested during the installCheckPhase cannot be found.

I think we need to separate building and installing into two derivations, with the wheel a buildInput to the other, and that when tests are enabled we build an env with a first installation of the wheel.

@abbradar

Copy link
Copy Markdown
Member Author

Hm, I'll try to test this more extensively and see what happens (I haven't built anything big with this because of lack of CPU time. I don't even remember what exactly, I think maybe pip).

@adnelson

adnelson commented Aug 16, 2016 •

Copy link
Copy Markdown
Contributor

ipython is certainly one case where you wouldn't want an executable to set their own (complete) pythonpath. But they're in the minority for sure... maybe an opt-in pythonpath prefix would be better? It would be simple to make it an option in buildPythonPackage.

EDIT: there's also nosetests... seems like really the question is, is whatever executable that's being run meant to interact with a python environment, or is it just meant to be a self-contained executable?

@abbradar

Copy link
Copy Markdown
Member Author

Hm, indeed, IPython is a special case. I'm now trying an alternative patch which removes all meddling with $PYTHONPATH at all and instead inserts needed paths to sys.path. This gives us absence of dreaded $PYTHONPATH propagation while not disabling it completely. A downside is further complication of The Magical sed Expression. IPython seems to work with this.

@adnelson

adnelson commented Aug 16, 2016 •

Copy link
Copy Markdown
Contributor

We could also skip using PYTHONPATH and use PYTHONHOME instead. PYTHONHOME would point to what PYTHONPATH currently points to, and then PYTHONPATH could be set at runtime to whatever.

                 local -a wrap_args=("$f"
                                 --set PYTHONHOME ':' "$program_PYTHONPATH"
                                 --prefix PATH ':' "$program_PATH:$dir/bin")

I haven't tested this out yet but it seems perhaps promising?

@FRidh

FRidh commented Aug 16, 2016 •

Copy link
Copy Markdown
Member

@adnelson and now you've broken python.buildEnv, because it cannot use --set PYTHONHOME anymore.

Unless we're willing to use PYTHONPATH with buildEnv, but then you're back.

@abbradar

Copy link
Copy Markdown
Member Author

I thought that PYTHONHOME should be one path which point to Python "home", that is binaries and libraries. @FRidh proposed to build environments with all dependencies and set PYTHONHOME to them but without such an environment I don't think it can be used...

@adnelson

Copy link
Copy Markdown
Contributor

@FRidh I haven't broken anything yet 😉 I didn't realize that's what buildEnv did, good call

@abbradar

Copy link
Copy Markdown
Member Author

BTW to clarify my thoughts towards @FRidh proposition: I like it much more than the current situation, and I think we probably should go there in the long run. However, I experience a broken browser when called from my IM client right now and I suspect that there are more breakages like this in the wild. buildEnv proposition requires a lot of work (grep for PYTHONPATH to get a rough estimate) and we need something to plug the leak now...

@bennofs

bennofs commented Aug 16, 2016

Copy link
Copy Markdown
Contributor

I actually think that using PYTHONHOME is not such a bad idea: you could establish the convention that PYTHONHOME is to be used for the "application-dependencies", i.e. things that for example ipython itself depends on. The PYTHONPATH would be used to add any additional dependencies then, like plugins etc.

@adnelson

Copy link
Copy Markdown
Contributor

So couldn't we point PYTHONHOME to a call to buildEnv on the propagatedBuildInputs?

Something (conceptually, cuz I have no idea) along the lines of

mkDerivation {
  postInstall = ''
    for bin_file in $out/bin; do
      makeWrapper $bin_file \
        --set PYTHONHOME ${buildEnv {paths = propagatedBuildInputs;}}
  '';
}

@FRidh

FRidh commented Aug 16, 2016

Copy link
Copy Markdown
Member

@adnelson and what is that derivation? It cannot be the actual package, it has to be outside of that or it wouldn't be a DAG. Here we're back to my suggestion of #16672. It's really easy actually, as you see in the implementation. And we could choose for now to keep wrapPythonPrograms.

@bennofs Do you mean adding to PYTHONPATH with Nix, or outside of Nix?

@abbradar

Copy link
Copy Markdown
Member Author

Sadly I don't think so (this doesn't affect nix-shell). However, in case of tox I think we can wrap it to unset PYTHONPATH. Because now it has all the dependencies patched in it should work -- I'm not sure this won't break any usecases though.

@RonnyPfannschmidt

Copy link
Copy Markdown
Contributor

atm tox is broken because it puts packages from its environment into the virtualenvs at setup time and then isolates them away at the other level

tox would work fine if it was not wrapped by the pythonpath thing

@abbradar

Copy link
Copy Markdown
Member Author

This shouldn't be a problem already I think because there's no PYTHONPATH set for Tox itself now. I was rather talking about case when it's called from nix-shell which sets its own PYTHONPATH.

@RonnyPfannschmidt

Copy link
Copy Markdown
Contributor

will this change hit 16-09 ?? - i just did a nix-env -i for tox and it has a wrapper

@abbradar

Copy link
Copy Markdown
Member Author

It should have, a long time ago.

@RonnyPfannschmidt

Copy link
Copy Markdown
Contributor

i am on a 16.09 channel, just updated my channels and installed tox

@RonnyPfannschmidt

Copy link
Copy Markdown
Contributor

same for unstable channel

@abbradar

Copy link
Copy Markdown
Member Author
 nixpkgs git:(master) ✗ nix-build -A pythonPackages.tox
ca/nix/store/bm5hyq5rhhrjrs85alai3gph1kq1yb53-python2.7-tox-2.3.1
 nixpkgs git:(master) ✗ cat result/bin/tox
#! /nix/store/nyj6xd7s1n1w8c0xdwk5ddhi7bjcyi9x-bash-4.3-p46/bin/bash -e
export PATH=/nix/store/hdny4a03ys50hh56k6z1w3z8sl0hf2ym-python-2.7.12/bin:/nix/store/bm5hyq5rhhrjrs85alai3gph1kq1yb53-python2.7-tox-2.3.1/bin:/nix/store/p5n1lbm3rs3d4bkpq249fg5rs2iw8kp2-python2.7-setuptools-26.1.1/bin:/nix/store/yk4qqqxq91gjd7jp2i114dywh1f2xfaw-python2.7-virtualenv-15.0.3/bin${PATH:+:}$PATH
exec -a "$0" /nix/store/bm5hyq5rhhrjrs85alai3gph1kq1yb53-python2.7-tox-2.3.1/bin/.tox-wrapped "${extraFlagsArray[@]}" "$@"
 nixpkgs git:(master) ✗ 

So it's in master at least, and given that the change was merged long before release-16.09 fork it should be there, too.

@RonnyPfannschmidt

Copy link
Copy Markdown
Contributor

@domenkozar any chance to see this in 16.09?

@abbradar

abbradar commented Sep 16, 2016 •

Copy link
Copy Markdown
Member Author

@RonnyPfannschmidt As I've said it should be in 16.09 already but just to be sure I checked:

 nixpkgs git:(release-16.09) ✗ nix-build -A pythonPackages.tox
/nix/store/d1ri3241dnyl17hk2rqcbp3s5s740ng2-python2.7-tox-2.3.1
 nixpkgs git:(release-16.09) ✗ cat result/bin/tox
#! /nix/store/migghb7advw9a6hxi3vhyw2kyyxlyihx-bash-4.3-p46/bin/bash -e
export PATH=/nix/store/1940biik22bz5kc5fv1mnd2nzhc58k6m-python-2.7.12/bin:/nix/store/d1ri3241dnyl17hk2rqcbp3s5s740ng2-python2.7-tox-2.3.1/bin:/nix/store/agx8kbmp982gcbqcsxx3iy4s1n52z8pb-python2.7-setuptools-26.1.1/bin:/nix/store/x32przfwf4cl3wgybm2dpr5dvx588wp9-python2.7-virtualenv-15.0.3/bin${PATH:+:}$PATH
exec -a "$0" /nix/store/d1ri3241dnyl17hk2rqcbp3s5s740ng2-python2.7-tox-2.3.1/bin/.tox-wrapped "${extraFlagsArray[@]}" "$@"
 nixpkgs git:(release-16.09) ✗ 

@domenkozar

Copy link
Copy Markdown
Member

@RonnyPfannschmidt does this fix the tox issue for you on master?

@FRidh any reason not to backport this to 16.09? It's quote late for such big python change..

@abbradar

Copy link
Copy Markdown
Member Author

@domenkozar Again, this is already in 16.09 -- see also for example db31282 (notice 16.09-beta tag).

@RonnyPfannschmidt

Copy link
Copy Markdown
Contributor
nix-channel --update
downloading Nix expressions from ‘https://nixos.org/releases/nixos/16.09/nixos-16.09beta264.aadcffc//nixexprs.tar.xz’...
downloading ‘https://nixos.org/releases/nixos/16.09/nixos-16.09beta264.aadcffc//nixexprs.tar.xz’... [3776/8658 KiB, 3355.2 KiB/s]
downloading Nix expressions from ‘https://nixos.org/releases/nixpkgs/nixpkgs-17.03pre91280.b32252d//nixexprs.tar.xz’...
downloading ‘https://nixos.org/releases/nixpkgs/nixpkgs-17.03pre91280.b32252d//nixexprs.tar.xz’... [3520/7663 KiB, 3355.2 KiB/s]
unpacking channels...

is this perhaps an issue with the channel lagging behind the branch?

@abbradar

Copy link
Copy Markdown
Member Author

Hm, I think you have an old tox in your PATH somehow. Try running nix-build -A pythonPackages.tox '<nixpkgs>' and see what you have in result.

@RonnyPfannschmidt

Copy link
Copy Markdown
Contributor
$ git branch
  gnome-online-account-wrapGAppsHook
  gnome-onlineaccoutns-use-wrapGAppsHook
* master
  nixos-unstable
  nixpkgs-unstable
  release-16.03
  wrapGAppsHook
$ nix-build . -A pythonPackages.tox
/nix/store/bm5hyq5rhhrjrs85alai3gph1kq1yb53-python2.7-tox-2.3.1
$ cat result/bin/tox
#! /nix/store/nyj6xd7s1n1w8c0xdwk5ddhi7bjcyi9x-bash-4.3-p46/bin/bash -e
export PATH=/nix/store/hdny4a03ys50hh56k6z1w3z8sl0hf2ym-python-2.7.12/bin:/nix/store/bm5hyq5rhhrjrs85alai3gph1kq1yb53-python2.7-tox-2.3.1/bin:/nix/store/p5n1lbm3rs3d4bkpq249fg5rs2iw8kp2-python2.7-setuptools-26.1.1/bin:/nix/store/yk4qqqxq91gjd7jp2i114dywh1f2xfaw-python2.7-virtualenv-15.0.3/bin${PATH:+:}$PATH
exec -a "$0" /nix/store/bm5hyq5rhhrjrs85alai3gph1kq1yb53-python2.7-tox-2.3.1/bin/.tox-wrapped "${extraFlagsArray[@]}" "$@"
$ git describe
16.09-beta-944-ga0b643e

@abbradar

Copy link
Copy Markdown
Member Author

This already does contain this change (notice absence of PYTHONPATH exports). Maybe the problem is with something else...

@RonnyPfannschmidt

Copy link
Copy Markdown
Contributor

nm, i missed that detail

on the 16.09 branch i get the same output - i was confused by the different output path

the behaviour is indeed correct
now for tools like tox it would be nice if they either had no PATH at all or used it differently

but thats something that can change in future

as far as i can tell your change correctly and nicely fixes the 2 issues i posted

@RonnyPfannschmidt

Copy link
Copy Markdown
Contributor

oh, wait ,not completely

tox is fixed, PYTHONPATH is still leaking into nix-shell

@abbradar

Copy link
Copy Markdown
Member Author

Can you perhaps submit a PR for this? The workaround should be quite simple -- you need to add --set PYTHONPATH "" to makeWrapperArgs for the tox derivation.

@RonnyPfannschmidt

Copy link
Copy Markdown
Contributor

imho there should be a default decision on what nix python programs do wrt inheriting pythonpath

users tend to use it, so its certainly valid - a tool in nix that does filter nix store paths out of env vars in wrappers might be whats helpfull

@FRidh

FRidh commented Sep 17, 2016

Copy link
Copy Markdown
Member

PYTHONPATH in nix-shell is set with a setup hook, and has a different purpose. I hope with nix use setup hooks won't be run, and PYTHONPATH therefore won't be set.

@RonnyPfannschmidt

Copy link
Copy Markdown
Contributor

@FRidh sounds perfect, i'd like to be free of nix-shell, from my POV its a tool for developing nix packages, not using them in develpment environments

@FRidh

FRidh commented Feb 7, 2017

Copy link
Copy Markdown
Member

Currently we add the following to scripts

preamble = ''
          import sys
          import site
          import functools
          sys.argv[0] = '"'$(readlink -f "$f")'"'
          functools.reduce(lambda k, p: site.addsitedir(p, k), ['"$([ -n "$program_PYTHONPATH" ] && (echo "'$program_PYTHONPATH'" | sed "s|:|','|g") || true)"'], site._init_pathinfo())
        '';

and we also create a wrapper. I don't think we should do both. In case of Python code, we should add this code, and in the case of a non-Python program, we should create a wrapper.

The wrappers can be problematic, e.g. when the program that is wrapped calls itself using python program args instead of ./program args.

I would like to make the following change:

  1. in case of Python code, we patch the shebang and optionally add the preamble. Python applications will be able to find the modules they require if the preamble is added. They can find the interpreter because we patched the shebang, but they cannot find additional scripts provided by the application or dependencies because they're not on PATH. In the long run we might want to get rid of the preamble.
  2. we do not create wrappers in Python package derivations, but, a bit like with KDE, we have a ${name}-${version}-wrapped. Here we use either the wrappers as we have now, or my buildEnv approach. Any manual wrapping would also be done here in the fixupPhase. We add wrapped and unwrapped attributes.

Important is that ${name}-${version}-wrapped doesn't set pythonPath so its site-packages isn't added by the setup-hook.

@nixos-discourse

Copy link
Copy Markdown

This pull request has been mentioned on NixOS Discourse. There might be relevant details there:

https://discourse.nixos.org/t/terminal-emulator-leaks-environment-variables-to-shell/33673/11

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

Labels

0.kind: bug Something is broken 6.topic: python Python is a high-level, general-purpose programming language.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants