Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Python 3 stable ABI to allow mixed version interoperatbility #12032

Closed
wants to merge 12 commits into from

Conversation

ychin
Copy link
Contributor

@ychin ychin commented Feb 20, 2023

Vim currently supports embedding Python for use with plugins, and the "dynamic" linking option allows the user to specify a locally installed version of Python by setting pythonthreedll. However, one caveat is that the Python 3 libs are not binary compatible across minor versions, and mixing versions can potentially be dangerous (e.g. let's say Vim was linked against the Python 3.10 SDK, but the user sets pythonthreedll to a 3.11 lib). Usually, nothing bad happens, but in theory this could lead to crashes, memory corruption, and other unpredictable behaviors. It's also difficult for the user to tell something is wrong because Vim has no way of reporting what Python 3 version Vim was linked with.

For Vim installed via a package manager, this usually isn't an issue because all the dependencies would already be figured out. For prebuilt Vim binaries like MacVim (my motivation for working on this), AppImage (Edit: seems like AppImage uses static linkage so maybe not an issue but it does mean it can't use different Python versions) (Edit 2: Nvm I was wrong, AppImage uses Python 2+3 so it has to be dynamic, see issues like vim/vim-appimage#35), and Win32 installer this could potentially be an issue as usually a single binary is distributed. This is more tricky when a new Python version is released, as there's a chicken-and-egg issue with deciding what Python version to build against and hard to keep in sync when a new Python version just drops and we have a mix of users of different Python versions, and a user just blindly upgrading to a new Python could lead to bad interactions with Vim.

Python 3 does have a solution for this problem: stable ABI / limited API (see https://docs.python.org/3/c-api/stable.html). The C SDK limits the API to a set of functions that are promised to be stable across versions. This pull request adds an ifdef config that allows us to turn it on when building Vim. Vim binaries built with this option should be safe to freely link with any Python 3 libraies without having the constraint of having to use the same minor version.

Note: Python 2 has no such concept and this doesn't change how Python 2 integration works (not that there is going to be a new version of Python 2 that would cause compatibility issues in the future anyway).


Technical details:

The stable ABI can be accessed when we compile with the Python 3 limited API (by defining Py_LIMITED_API). The Python 3 code (in if_python3.c and if_py_both.h) would now handle this and switch to limited API mode. Without it set, Vim will still use the full API as before so this is an opt-in change.

The main difference is that PyType_Object is now an opaque struct that we can't directly create "static types" out of, and we have to create type objects as "heap types" instead. This is because the struct is not stable and changes from version to version (e.g. 3.8 added a tp_vectorcall field to it). I had to change all the types to be allocated on the heap instead with just a pointer to them.

Other functions are also simply missing in limited API, or they are introduced too late (e.g. PyUnicode_AsUTF8AndSize in 3.10) to it that we need some other ways to do the same thing, so I had to abstract a few things into macros, and sometimes re-implement functions like PyObject_NEW.

One caveat is that in limited API, OutputType (used for replacing sys.stdout) no longer inherits from PyStdPrinter_Type which I don't think has any real issue other than minor differences in how they convert to a string and missing a couple functions like mode() and fileno().

Also fixed an existing bug where tp_basicsize was set incorrectly for BufferObject, TabListObject, WinListObject.

Technically, there could be a small performance drop, as there is a little more indirection with accessing type objects, and some APIs like PyUnicode_AsUTF8AndSize are missing, but in practice I didn't see any difference, and any well-written Python plugin should try to avoid excessing callbacks to the vim module in Python anyway.

I only tested limited API mode down to Python 3.7, which seemes to compile and work fine. I haven't tried earlier Python versions.

Note: On Windows, according to the docs linked above, I think you need to set pythonthreedll to python3.dll rather than a version-specific one like python3.9.dll.

WIP Done:

I marked this as WIP because there are a few things that I want to finish up, but wanted to gather some feedbacks on this PR first.

  • (Done) Add way to set Py_LIMITED_API. Probably a configure.ac option.
  • (Done) Add has() / :version indicator that a Python build has been built with stable ABI. I'm not sure if :version really need to be changed, but I'm imagining +python3/dyn-stable.
  • (Done) Add documentation to explain this, and also how to use has() to query.
  • (Done) Add CI coverage to exercise this. (Also need to think about Windows)
  • Test out popular Vim plugins written in Python (see below, I would welcome some suggestions) to make sure they still work.
  • (Done) Maybe: Add a v:python3_version? This can help the user tell what version of Python Vim was built against. Useful esp for non-stable-ABI mode. Can also use this to write Vim script to automatically set pythonthreedll.
  • Maybe: In the old non-stable-ABI mode, throw a warning when loading a Python 3 DLL that's a different version from the one Vim expects? I may punt on this.
    • Update: Probably not. The reason for that is the Py_Version variable is only exposed in 3.11 (which was released recently). Before that it was somewhat hard to tell what version a Python library is from the C SDK unless you manually call sys.version in Python. Seems like not worth the trouble.

I only tested on macOS, down to Python 3.7, with both static and dynamic linking. If other people want to try this on Windows and Linux that would be appreciated. I ran a couple Python plugins and they seemed to work fine (e.g. Ultisnips), but I personally don't use any plugins that use Python so I may not be running into much edge cases.

Note: If you want to test this, just pull the PR and build. You can comment out the #define Py_LIMITED_API 0x03080000 line on the top of if_python3.c to get back the full API behavior. It should pass all tests and run Python plugins just like before. One way to know you are running in limited mode is to run :py3 print(sys.stdout) which looks a little different.

@ychin
Copy link
Contributor Author

ychin commented Feb 20, 2023

Just for reference, I found this thread where some developers were discussing potentially deprecating certain aspects of the stable ABI (https://discuss.python.org/t/lets-get-rid-of-the-stable-abi-but-keep-the-limited-api/18458), but seems like it would be quite controversial so it didn't go anywhere or at least won't be done any time soon. The main contention is that right now, even under limited API, the PyObject struct is not opaque and exposes inner workings of CPython (since otherwise it could make the limited API quite inefficient as you have to marshal everything to functions instead of just managing the struct yourself).

@ychin ychin changed the title Support Python 3 stable ABI to allow mixed version interoperatbility WIP: Support Python 3 stable ABI to allow mixed version interoperatbility Feb 20, 2023
@ychin
Copy link
Contributor Author

ychin commented Feb 24, 2023

I added a --with-python3-stable-abi flag to the configure script (I didn't regenerate auto/configure though) so it won't use limited API by default now, and you have to specify that during configure. Also added :version / has('python_stable') for runtime query.

I may stop for now to see if I hear any feedbacks first. The other stuff are more easily ironed out afterwards.

For :version output I'm currently using +python3/dyn-stable but now I'm wondering if there are people relying on checking the version output of Vim and explicitly searching for +python3/dyn. We could remove it if we want to.

For CI, seems like right now Linux builds only test non-dynamic builds, whereas Windows test dynamic Python linkage. Not sure where to slot this in. Also, for Windows, the configuration needs to be modified so that it knows to use python3.dll instead of something like python311.dll (this is just how the Python 3 stable ABI works on Windows).

@codecov
Copy link

codecov bot commented Feb 24, 2023

Codecov Report

Merging #12032 (86ca038) into master (5b0889b) will increase coverage by 3.82%.
The diff coverage is 90.27%.

❗ Current head 86ca038 differs from pull request most recent head 12825f9. Consider uploading reports for the commit 12825f9 to get more accurate results

@@            Coverage Diff             @@
##           master   #12032      +/-   ##
==========================================
+ Coverage   78.10%   81.93%   +3.82%     
==========================================
  Files         150      164      +14     
  Lines      151954   194317   +42363     
  Branches    39196    43869    +4673     
==========================================
+ Hits       118677   159204   +40527     
- Misses      21020    22254    +1234     
- Partials    12257    12859     +602     
Flag Coverage Δ
huge-clang-none 82.64% <91.30%> (?)
huge-gcc-none 53.84% <40.00%> (?)
huge-gcc-testgui 51.94% <40.00%> (?)
huge-gcc-unittests 0.29% <4.87%> (?)
linux 82.36% <88.19%> (?)
mingw-x64-HUGE 76.54% <90.00%> (+0.02%) ⬆️
mingw-x86-HUGE 77.02% <88.49%> (+0.01%) ⬆️
windows 78.14% <88.88%> (+0.04%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files Changed Coverage Δ
src/evalfunc.c 90.40% <ø> (+0.79%) ⬆️
src/version.c 85.24% <ø> (+6.35%) ⬆️
src/if_python3.c 74.39% <76.92%> (+3.35%) ⬆️
src/if_py_both.h 77.45% <91.53%> (+1.25%) ⬆️
src/evalvars.c 91.39% <100.00%> (+1.24%) ⬆️

... and 153 files with indirect coverage changes

@brammool
Copy link
Contributor

brammool commented Feb 26, 2023 via email

@ychin
Copy link
Contributor Author

ychin commented Feb 27, 2023

I hope a few users who use the Python interface can try this out.

FWIW, I tried out ultisnips and black (Python code formatter library / Vim plugin which is also implemented in Python). They both seem to work fine. Using Black to format a really big Python file also resulted in similar performance (which makes sense since most of the work is done in Python, but just sanity checking).

I would have wanted to do some testing with Powerline and YouCompleteMe but the setup for those plugins are complicated enough that I didn't really want to go through with it. I personally don't foresee any issues though.

Can we keep this short? E.g. python3/stable or python3/abi ? It will be good to be able to see how Vim was compiled, especially if someone has a problem with the Python interface.

What about something like "python3/dyn/stb" or "python3/dyn+stb"? I feel like the "/dyn" have very specific meaning. You can do :help /dyn and it's important for the user to know that it's dynamically linked in (since that means you need to set up the correct pythonthreedll setting and so on). Maybe we could use a short form for "stable" like "stb"?

It would be good to have a test in the CI. Any change in the Python interface should be tried with the stable ABI to make sure it doesn't break. This doesn't have to cover every combination of choices, perhaps just one configuration with this feature.

I can play around with the CI matrix and make sure we have at least one that use this.

@brammool
Copy link
Contributor

brammool commented Feb 28, 2023 via email

@ychin
Copy link
Contributor Author

ychin commented Mar 1, 2023

If someone searches for +python3/dyn in the output of :version it would match "python3/dyn/stb" as well. Not sure if that matters.

Right, that was my intention / proposal. This way someone who only wants to know if Python 3 linkage is dynamic to begin with still has a baseline, and the "stable ABI" part is more an additional detail. I personally don't care too much about this, but I do think it's nice to have the /dyn part in it.

Otherwise I just pushed a new commit with CI coverage for both Linux and Windows (it will now test both python 3 full API and stable ABI in the matrix, and we can confirm that in the "Check Version" part of the CI since it prints the version output). Also added a drive-by change to test other scripting languages in both dynamic and static as well (previously all matrices only exercised static linkage).

Other than that I still have v:python3_version to implement, if we want that feature to be able to quickly query the compiled version of Python 3 for the user to confirm (in stable ABI I plan to have it be the limited API version, aka the mininum version the user needs to have).

@ychin
Copy link
Contributor Author

ychin commented Mar 2, 2023

Ok, I just committed support for v:python3_version which provides a way for the user to query what Python 3 version Vim was built against (which will be useful with or without stable ABI).

I think I have mostly implemented all the things I wanted to. I can rename python3/dyn-stable to whatever name we decide on as well.

If there are people watching this thread and use a lot of Python plugins please give this a try! It will make your life easier if you are using dynamic Python loading :)

@ychin ychin changed the title WIP: Support Python 3 stable ABI to allow mixed version interoperatbility Support Python 3 stable ABI to allow mixed version interoperatbility Mar 2, 2023
@ychin ychin force-pushed the python3-stable-abi branch 2 times, most recently from 7407c58 to fdf9462 Compare March 2, 2023 07:42
@eirnym
Copy link

eirnym commented Mar 20, 2023

I'd love this patch to be merged. I work with different versions of python and this would quite help to work on my set of versions.

@ychin
Copy link
Contributor Author

ychin commented Mar 22, 2023

I have been using a few Python plugins and it seems pretty stable so far. I also installed YouCompleteMe, one of the most popular Python-based Vim plugin and it seems to work with no issue.

I did discover some issues when stable ABI target is Python 3.7 (or anything below 3.8), so I fixed those up in my recent push.

Fundamentally, Python 3.7 or below has an issue that PyIter_Check is not supported. That means we don't have an easy way to pass an iterator from Python code to Vim. My previous commit tried to work around it by making a custom implementation but it doesn't really work well, so I just replaced it to just return FALSE for now. It does mean building Vim with stable ABI < 3.8 is not advised as you lose this functionality. Note that we could fix it by allowing PyIter_Check loading to optionally fail when loading it in py3_runtime_link_init, so we can use that to optionally call PyIter_Check when running against Python 3.8 runtime libs, but don't call it when running against 3.7 runtime. I decided against implementing that for now as it adds some complexity and also seems to defeat the "stable ABI" promise.

Summary: It's best to tell people to compile stable ABI >= 3.8, but if we want to I can add support for dynamically deciding whether to call PyIter_Check if there's enough demand for compatibility with 3.7.


Other than that, is there anything else you would like to see @brammool ? I think this is the kind of thing where a lot of Python plugin users may not think too much because usually mixing versions kind of work, even though it's definitely not advised or supported by CPython explicitly and has danger of memory corruption issues.

@brammool
Copy link
Contributor

brammool commented Mar 31, 2023 via email

@eirnym
Copy link

eirnym commented Apr 1, 2023

As a Python developer I use vim/MacVim with Python all the time. I use YCM and few other plugins to support my editing capabilities in Vim.

I use a lot of native libraries such as asyncpg, OpenCV, pandas and other scientific libraries. I use virtual environments to enclose my libraries for a project/set of projects and often edit for different version of python for different projects. Why I can't just install binary packages? Because of few binary dependencies shared in company's PyPi server we have no access to source code for.

@brammool I generally agree with you for new projects, but in some parts of my company's software we use Python 3.7 and I have to comply to it as well.

And it's a "Russian roulette" if it comes to having no errors on other versions of Python than Vim is compiled with.

My current solution which works with MacVim is to have a few versions installed simultaneously compiled for different Python versions if I want to have a guaranteed full compliance. This includes several .vim folders for them as well.

@ychin
Copy link
Contributor Author

ychin commented Apr 2, 2023

My current solution which works with MacVim is to have a few versions installed simultaneously compiled for different Python versions if I want to have a guaranteed full compliance. This includes several .vim folders for them as well.

Why couldn't you just use an updated Python (e.g. 3.10) just for Vim usage? Even if you have internal software that relies on 3.7 and whatnot, Vim doesn't need to really interface with them if you are using YCM and whatnot. Vim doesn't need to use the exact installation of Python as your other usages.

As for 3.7, it just doesn't support the iterator APIs that Vim is using right now. I think having subtle behavior changes is a little annoying so I'm leaning towards just not supporting it for stable ABI.

ychin added a commit to ychin/macvim that referenced this pull request Jul 9, 2023
Also, refactor CI configs to only specify the Python 3 and Perl versions
in one place, so we don't have to multiple lines in the config file.
Additionally, add checks to make sure the Homebrew Python 3 version
matches the configured one, so we will have a failed build and be
notified this way instead of silently building against an old version of
Python in CI, which would still work as GitHub CI has older versions of
Python installed.

Note that if vim/vim#12032 is merged, this will
be less painful in the future as stable ABI should mean we don't have to
care as much about the exact Python version.
ychin added a commit to ychin/macvim that referenced this pull request Jul 9, 2023
Also, refactor CI configs to only specify the Python 3 and Perl versions
in one place, so we don't have to multiple lines in the config file.
Additionally, add checks to make sure the Homebrew Python 3 version
matches the configured one, so we will have a failed build and be
notified this way instead of silently building against an old version of
Python in CI, which would still work as GitHub CI has older versions of
Python installed.

Note that if vim/vim#12032 is merged, this will
be less painful in the future as stable ABI should mean we don't have to
care as much about the exact Python version.
@yegappan
Copy link
Member

Can you update and rebase this PR to the latest?

@yegappan yegappan added this to the vim-9.1 milestone Aug 13, 2023
Vim currently supports embedding Python for use with plugins, and the
"dynamic" linking option allows the user to specify a locally installed
version of Python by setting `pythonthreedll`. However, one caveat is
that the Python 3 libs are not binary compatible across minor versions,
and mixing versions can potentially be dangerous (e.g. let's say Vim was
linked against the Python 3.10 SDK, but the user sets `pythonthreedll`
to a 3.11 lib). Usually, nothing bad happens, but in theory this could
lead to crashes, memory corruption, and other unpredictable behaviors.
It's also difficult for the user to tell something is wrong because Vim
has no way of reporting what Python 3 version Vim was linked with.

For Vim installed via a package manager, this usually isn't an issue
because all the dependencies would already be figured out. For prebuilt
Vim binaries like MacVim (my motivation for working on this), AppImage,
and Win32 installer this could potentially be an issue as usually a
single binary is distributed. This is more tricky when a new Python
version is released, as there's a chicken-and-egg issue with deciding
what Python version to build against and hard to keep in sync when a new
Python version just drops and we have a mix of users of different Python
versions, and a user just blindly upgrading to a new Python could lead to
bad interactions with Vim.

Python 3 does have a solution for this problem: stable ABI / limited API
(see https://docs.python.org/3/c-api/stable.html). The C SDK limits the
API to a set of functions that are promised to be stable across
versions. This pull request adds an ifdef config that allows us to turn
it on when building Vim. Vim binaries built with this option should be
safe to freely link with any Python 3 libraies without having the
constraint of having to use the same minor version.

Note: Python 2 has no such concept and this doesn't change how Python 2
integration works (not that there is going to be a new version of Python
2 that would cause compatibility issues in the future anyway).

---

Technical details:
======

The stable ABI can be accessed when we compile with the Python 3 limited
API (by defining `Py_LIMITED_API`). The Python 3 code (in `if_python3.c`
and `if_py_both.h`) would now handle this and switch to limited API
mode. Without it set, Vim will still use the full API as before so this
is an opt-in change.

The main difference is that `PyType_Object` is now an opaque struct that
we can't directly create "static types" out of, and we have to create
type objects as "heap types" instead. This is because the struct is not
stable and changes from version to version (e.g. 3.8 added a
`tp_vectorcall` field to it). I had to change all the types to be
allocated on the heap instead with just a pointer to them.

Other functions are also simply missing in limited API, or they are
introduced too late (e.g. `PyUnicode_AsUTF8AndSize` in 3.10) to it that
we need some other ways to do the same thing, so I had to abstract a few
things into macros, and sometimes re-implement functions like
`PyObject_NEW`.

One caveat is that in limited API, `OutputType` (used for replacing
`sys.stdout`) no longer inherits from `PyStdPrinter_Type` which I don't
think has any real issue other than minor differences in how they
convert to a string and missing a couple functions like `mode()` and
`fileno()`.

Also fixed an existing bug where `tp_basicsize` was set incorrectly for
`BufferObject`, `TabListObject, `WinListObject`.

Technically, there could be a small performance drop, there is a little
more indirection with accessing type objects, and some APIs like
`PyUnicode_AsUTF8AndSize` are missing, but in practice I didn't see any
difference, and any well-written Python plugin should try to avoid
excessing callbacks to the `vim` module in Python anyway.

I only tested limited API mode down to Python 3.7, which seemes to
compile and work fine. I haven't tried earlier Python versions.

WIP:
======

I marked this as WIP because there are a few things that I want to
finish up, but wanted to gather some feedbacks on this PR first.

- Add way to set `Py_LIMITED_API`. Probably a configure.ac option.
- Add `has()` / `:version` indicator that a Python build has been built
  with stable ABI. I'm not sure if `:version` really need to be changed,
  but I'm imagining `+python3/dyn-stable`.
- Add documentation to explain this, and also how to use `has()` to
  query.
- Add CI coverage to exercise this.
- Test out popular Vim plugins written in Python (see below, I would
  welcome some suggestions) to make sure they still work.
- *Maybe*: Add a `v:python3_version`? This can help the user tell what
  version of Python Vim was built against. Useful esp for non-stable-ABI
  mode.
- *Maybe*: In the old non-stable-ABI mode, throw a warning when loading a
  Python 3 DLL that's a different version from the one Vim expects? I
  may punt on this.

---

I only tested on macOS, down to Python 3.7, with both static and dynamic
linking. If other people want to try this on Windows and Linux that
wouldl be appreciated. I ran a couple Python plugins and they seemed to
work fine (e.g. Ultisnips), but I personally don't use any plugins that
use Python so I may not be running into much edge cases.

Note: If you want to test this, just pull the PR and build. You can comment out the `#define
Py_LIMITED_API 0x03080000` line on the top of if_python3.c to get back
the full API behavior. It should pass all tests and run Python plugins
just like before. One way to know you are running in limited mode is to
run `:py3 print(sys.stdout)` which looks a little different.
For PyIter_Check, older versions exposed them as either macros (used in
full API), or a function (for use in limited API). A previous change
exposed PyIter_Check to the dynamic build because Python just moved it
to function-only in 3.10 anyway. Because of that, just make sure we
always grab the function in dynamic builds in earlier versions since
that's what Python eventually did anyway.
Can now use --with-python-stable-abi flag to customize what stable ABI
version to target. Can also use an env var to do so as well.
Not sure if the "/dyn-stable" suffix would break things, or whether we
should do it another way. Or just don't show it in version and rely on
has() feature checking.
…ndows

This adds configurable options for Windows make files (both MinGW and
MSVC). CI will also now exercise both traditional full API and stable
ABI for Linux and Windows in the matrix for coverage.

Also added a "dynamic" option to Linux matrix as a drive-by change to
make other scripting languages like Ruby / Perl testable under both
static and dynamic builds.
Python's own docs are confusing but you don't actually want to use
`python3.dll` for the dynamic linkage.
This variable indicates the version of Python3 that Vim was built
against (PY_VERSION_HEX), and will be useful to check whether the Python
library you are loading in dynamically actually fits it. When built with
stable ABI, it will be the limited ABI version instead
(`Py_LIMITED_API`), which indicates the minimum version of Python 3 the
user should have, rather than the exact match. When stable ABI is used,
we won't be exposing PY_VERSION_HEX in this var because it just doesn't
seem necessary to do so (the whole point of stable ABI is the promise
that it will work across versions), and I don't want to confuse the user
with too many variables.

Also, cleaned up some documentation, and added help tags.
Fix a couple issues when using limited API < 3.8

- Crash on exit: In Python 3.7, if a heap-allocated type is destroyed
  before all instances are, it would cause a crash later. This happens
  when we destroyed `OptionsType` before calling `Py_Finalize` when
  using the limited API. To make it worse, later versions changed the
  semantics and now each instance has a strong reference to its own type
  and the recommendation has changed to have each instance de-ref its
  own type and have its type in GC traversal. To avoid dealing with
  these cross-version variations, we just don't free the heap type. They
  are static types in non-limited-API anyway and are designed to last
  through the entirety of the app, and we also don't restart the Python
  runtime and therefore do not need it to have absolutely 0 leaks.

  See:
  - https://docs.python.org/3/whatsnew/3.8.html#changes-in-the-c-api
  - https://docs.python.org/3/whatsnew/3.9.html#changes-in-the-c-api

- PyIter_Check: This function is not provided in limited APIs older than
  3.8. Previously I was trying to mock it out using manual
  PyType_GetSlot() but it was brittle and also does not actually work
  properly for static types (it will generate a Python error). Just
  return false. It does mean using limited API < 3.8 is not recommended
  as you lose the functionality to handle iterators, but from playing
  with plugins I couldn't find it to be an issue.

- Fix loading of PyIter_Check so it will be done when limited API < 3.8.
  Otherwise loading a 3.7 Python lib will fail even if limited API was
  specified to use it.
… API

We don't use this function unless limited API >= 3.10, but we were
loading it regardless. Usually it's ok in Unix-like systems where Python
just has a single lib that we load from, but in Windows where there is a
separate python3.dll this would not work as the symbol would not have
been exposed in this more limited DLL file. This makes it much clearer
under what condition is this function needed.
@ychin
Copy link
Contributor Author

ychin commented Aug 14, 2023

Ok done. Pushed and resolved conflicts.

@chrisbra chrisbra closed this in c13b3d1 Aug 20, 2023
@ychin ychin deleted the python3-stable-abi branch August 20, 2023 20:34
@ychin
Copy link
Contributor Author

ychin commented Aug 20, 2023

Thanks for merging! I'm willing to answer any questions if people have questions on how to configure this for their Vim builds.

@ychin
Copy link
Contributor Author

ychin commented Aug 20, 2023

One thing I noticed is that this results in a pretty giant commit message. I personally don't mind that as I like descriptive commits, but @chrisbra just wondering if you would have preferred if contributor polish up and squash their commits first? Or did you grab the description from the pull request description (which is where I kept my updated notes)? I know you are still probably working on the process but I think if there is a clear expectation it would be easy to follow.

@chrisbra
Copy link
Member

I would have hated to see those nice commit messages get lost. However at the same time, I did want to squash into a single commit, so that I can increase the patch number. So I thought squash it and merge the commit message (removing things which got resolved).

I am not sure this is the best way to do it, but at the same time, I wanted to keep your reasoning.

@ychin
Copy link
Contributor Author

ychin commented Aug 20, 2023

Yeah that's totally fine. I was just wondering where you got the final commit message from so I would know where to perform my edits in the future (if I have a typo, and whatnot, since Git commits are kind of forever 😅).

Konfekt pushed a commit to Konfekt/vim that referenced this pull request Aug 30, 2023
Problem:  No support for stable Python 3 ABI
Solution: Support Python 3 stable ABI

Commits:
1) Support Python 3 stable ABI to allow mixed version interoperatbility

Vim currently supports embedding Python for use with plugins, and the
"dynamic" linking option allows the user to specify a locally installed
version of Python by setting `pythonthreedll`. However, one caveat is
that the Python 3 libs are not binary compatible across minor versions,
and mixing versions can potentially be dangerous (e.g. let's say Vim was
linked against the Python 3.10 SDK, but the user sets `pythonthreedll`
to a 3.11 lib). Usually, nothing bad happens, but in theory this could
lead to crashes, memory corruption, and other unpredictable behaviors.
It's also difficult for the user to tell something is wrong because Vim
has no way of reporting what Python 3 version Vim was linked with.

For Vim installed via a package manager, this usually isn't an issue
because all the dependencies would already be figured out. For prebuilt
Vim binaries like MacVim (my motivation for working on this), AppImage,
and Win32 installer this could potentially be an issue as usually a
single binary is distributed. This is more tricky when a new Python
version is released, as there's a chicken-and-egg issue with deciding
what Python version to build against and hard to keep in sync when a new
Python version just drops and we have a mix of users of different Python
versions, and a user just blindly upgrading to a new Python could lead to
bad interactions with Vim.

Python 3 does have a solution for this problem: stable ABI / limited API
(see https://docs.python.org/3/c-api/stable.html). The C SDK limits the
API to a set of functions that are promised to be stable across
versions. This pull request adds an ifdef config that allows us to turn
it on when building Vim. Vim binaries built with this option should be
safe to freely link with any Python 3 libraies without having the
constraint of having to use the same minor version.

Note: Python 2 has no such concept and this doesn't change how Python 2
integration works (not that there is going to be a new version of Python
2 that would cause compatibility issues in the future anyway).

---

Technical details:
======

The stable ABI can be accessed when we compile with the Python 3 limited
API (by defining `Py_LIMITED_API`). The Python 3 code (in `if_python3.c`
and `if_py_both.h`) would now handle this and switch to limited API
mode. Without it set, Vim will still use the full API as before so this
is an opt-in change.

The main difference is that `PyType_Object` is now an opaque struct that
we can't directly create "static types" out of, and we have to create
type objects as "heap types" instead. This is because the struct is not
stable and changes from version to version (e.g. 3.8 added a
`tp_vectorcall` field to it). I had to change all the types to be
allocated on the heap instead with just a pointer to them.

Other functions are also simply missing in limited API, or they are
introduced too late (e.g. `PyUnicode_AsUTF8AndSize` in 3.10) to it that
we need some other ways to do the same thing, so I had to abstract a few
things into macros, and sometimes re-implement functions like
`PyObject_NEW`.

One caveat is that in limited API, `OutputType` (used for replacing
`sys.stdout`) no longer inherits from `PyStdPrinter_Type` which I don't
think has any real issue other than minor differences in how they
convert to a string and missing a couple functions like `mode()` and
`fileno()`.

Also fixed an existing bug where `tp_basicsize` was set incorrectly for
`BufferObject`, `TabListObject, `WinListObject`.

Technically, there could be a small performance drop, there is a little
more indirection with accessing type objects, and some APIs like
`PyUnicode_AsUTF8AndSize` are missing, but in practice I didn't see any
difference, and any well-written Python plugin should try to avoid
excessing callbacks to the `vim` module in Python anyway.

I only tested limited API mode down to Python 3.7, which seemes to
compile and work fine. I haven't tried earlier Python versions.

2) Fix PyIter_Check on older Python vers / type##Ptr unused warning

For PyIter_Check, older versions exposed them as either macros (used in
full API), or a function (for use in limited API). A previous change
exposed PyIter_Check to the dynamic build because Python just moved it
to function-only in 3.10 anyway. Because of that, just make sure we
always grab the function in dynamic builds in earlier versions since
that's what Python eventually did anyway.

3) Move Py_LIMITED_API define to configure script

Can now use --with-python-stable-abi flag to customize what stable ABI
version to target. Can also use an env var to do so as well.

4) Show +python/dyn-stable in :version, and allow has() feature query

Not sure if the "/dyn-stable" suffix would break things, or whether we
should do it another way. Or just don't show it in version and rely on
has() feature checking.

5) Documentation first draft. Still need to implement v:python3_version

6) Fix PyIter_Check build breaks when compiling against Python 3.8

7) Add CI coverage stable ABI on Linux/Windows / make configurable on Windows

This adds configurable options for Windows make files (both MinGW and
MSVC). CI will also now exercise both traditional full API and stable
ABI for Linux and Windows in the matrix for coverage.

Also added a "dynamic" option to Linux matrix as a drive-by change to
make other scripting languages like Ruby / Perl testable under both
static and dynamic builds.

8) Fix inaccuracy in Windows docs

Python's own docs are confusing but you don't actually want to use
`python3.dll` for the dynamic linkage.

9) Add generated autoconf file

10) Add v:python3_version support

This variable indicates the version of Python3 that Vim was built
against (PY_VERSION_HEX), and will be useful to check whether the Python
library you are loading in dynamically actually fits it. When built with
stable ABI, it will be the limited ABI version instead
(`Py_LIMITED_API`), which indicates the minimum version of Python 3 the
user should have, rather than the exact match. When stable ABI is used,
we won't be exposing PY_VERSION_HEX in this var because it just doesn't
seem necessary to do so (the whole point of stable ABI is the promise
that it will work across versions), and I don't want to confuse the user
with too many variables.

Also, cleaned up some documentation, and added help tags.

11) Fix Python 3.7 compat issues

Fix a couple issues when using limited API < 3.8

- Crash on exit: In Python 3.7, if a heap-allocated type is destroyed
  before all instances are, it would cause a crash later. This happens
  when we destroyed `OptionsType` before calling `Py_Finalize` when
  using the limited API. To make it worse, later versions changed the
  semantics and now each instance has a strong reference to its own type
  and the recommendation has changed to have each instance de-ref its
  own type and have its type in GC traversal. To avoid dealing with
  these cross-version variations, we just don't free the heap type. They
  are static types in non-limited-API anyway and are designed to last
  through the entirety of the app, and we also don't restart the Python
  runtime and therefore do not need it to have absolutely 0 leaks.

  See:
  - https://docs.python.org/3/whatsnew/3.8.html#changes-in-the-c-api
  - https://docs.python.org/3/whatsnew/3.9.html#changes-in-the-c-api

- PyIter_Check: This function is not provided in limited APIs older than
  3.8. Previously I was trying to mock it out using manual
  PyType_GetSlot() but it was brittle and also does not actually work
  properly for static types (it will generate a Python error). Just
  return false. It does mean using limited API < 3.8 is not recommended
  as you lose the functionality to handle iterators, but from playing
  with plugins I couldn't find it to be an issue.

- Fix loading of PyIter_Check so it will be done when limited API < 3.8.
  Otherwise loading a 3.7 Python lib will fail even if limited API was
  specified to use it.

12) Make sure to only load `PyUnicode_AsUTF8AndSize` in needed in limited API

We don't use this function unless limited API >= 3.10, but we were
loading it regardless. Usually it's ok in Unix-like systems where Python
just has a single lib that we load from, but in Windows where there is a
separate python3.dll this would not work as the symbol would not have
been exposed in this more limited DLL file. This makes it much clearer
under what condition is this function needed.

closes: vim#12032

Signed-off-by: Christian Brabandt <cb@256bit.org>
Co-authored-by: Yee Cheng Chin <ychin.git@gmail.com>
chrisbra pushed a commit to chrisbra/vim that referenced this pull request Sep 22, 2023
Problem:  No support for stable Python 3 ABI
Solution: Support Python 3 stable ABI

Commits:
1) Support Python 3 stable ABI to allow mixed version interoperatbility

Vim currently supports embedding Python for use with plugins, and the
"dynamic" linking option allows the user to specify a locally installed
version of Python by setting `pythonthreedll`. However, one caveat is
that the Python 3 libs are not binary compatible across minor versions,
and mixing versions can potentially be dangerous (e.g. let's say Vim was
linked against the Python 3.10 SDK, but the user sets `pythonthreedll`
to a 3.11 lib). Usually, nothing bad happens, but in theory this could
lead to crashes, memory corruption, and other unpredictable behaviors.
It's also difficult for the user to tell something is wrong because Vim
has no way of reporting what Python 3 version Vim was linked with.

For Vim installed via a package manager, this usually isn't an issue
because all the dependencies would already be figured out. For prebuilt
Vim binaries like MacVim (my motivation for working on this), AppImage,
and Win32 installer this could potentially be an issue as usually a
single binary is distributed. This is more tricky when a new Python
version is released, as there's a chicken-and-egg issue with deciding
what Python version to build against and hard to keep in sync when a new
Python version just drops and we have a mix of users of different Python
versions, and a user just blindly upgrading to a new Python could lead to
bad interactions with Vim.

Python 3 does have a solution for this problem: stable ABI / limited API
(see https://docs.python.org/3/c-api/stable.html). The C SDK limits the
API to a set of functions that are promised to be stable across
versions. This pull request adds an ifdef config that allows us to turn
it on when building Vim. Vim binaries built with this option should be
safe to freely link with any Python 3 libraies without having the
constraint of having to use the same minor version.

Note: Python 2 has no such concept and this doesn't change how Python 2
integration works (not that there is going to be a new version of Python
2 that would cause compatibility issues in the future anyway).

---

Technical details:
======

The stable ABI can be accessed when we compile with the Python 3 limited
API (by defining `Py_LIMITED_API`). The Python 3 code (in `if_python3.c`
and `if_py_both.h`) would now handle this and switch to limited API
mode. Without it set, Vim will still use the full API as before so this
is an opt-in change.

The main difference is that `PyType_Object` is now an opaque struct that
we can't directly create "static types" out of, and we have to create
type objects as "heap types" instead. This is because the struct is not
stable and changes from version to version (e.g. 3.8 added a
`tp_vectorcall` field to it). I had to change all the types to be
allocated on the heap instead with just a pointer to them.

Other functions are also simply missing in limited API, or they are
introduced too late (e.g. `PyUnicode_AsUTF8AndSize` in 3.10) to it that
we need some other ways to do the same thing, so I had to abstract a few
things into macros, and sometimes re-implement functions like
`PyObject_NEW`.

One caveat is that in limited API, `OutputType` (used for replacing
`sys.stdout`) no longer inherits from `PyStdPrinter_Type` which I don't
think has any real issue other than minor differences in how they
convert to a string and missing a couple functions like `mode()` and
`fileno()`.

Also fixed an existing bug where `tp_basicsize` was set incorrectly for
`BufferObject`, `TabListObject, `WinListObject`.

Technically, there could be a small performance drop, there is a little
more indirection with accessing type objects, and some APIs like
`PyUnicode_AsUTF8AndSize` are missing, but in practice I didn't see any
difference, and any well-written Python plugin should try to avoid
excessing callbacks to the `vim` module in Python anyway.

I only tested limited API mode down to Python 3.7, which seemes to
compile and work fine. I haven't tried earlier Python versions.

2) Fix PyIter_Check on older Python vers / type##Ptr unused warning

For PyIter_Check, older versions exposed them as either macros (used in
full API), or a function (for use in limited API). A previous change
exposed PyIter_Check to the dynamic build because Python just moved it
to function-only in 3.10 anyway. Because of that, just make sure we
always grab the function in dynamic builds in earlier versions since
that's what Python eventually did anyway.

3) Move Py_LIMITED_API define to configure script

Can now use --with-python-stable-abi flag to customize what stable ABI
version to target. Can also use an env var to do so as well.

4) Show +python/dyn-stable in :version, and allow has() feature query

Not sure if the "/dyn-stable" suffix would break things, or whether we
should do it another way. Or just don't show it in version and rely on
has() feature checking.

5) Documentation first draft. Still need to implement v:python3_version

6) Fix PyIter_Check build breaks when compiling against Python 3.8

7) Add CI coverage stable ABI on Linux/Windows / make configurable on Windows

This adds configurable options for Windows make files (both MinGW and
MSVC). CI will also now exercise both traditional full API and stable
ABI for Linux and Windows in the matrix for coverage.

Also added a "dynamic" option to Linux matrix as a drive-by change to
make other scripting languages like Ruby / Perl testable under both
static and dynamic builds.

8) Fix inaccuracy in Windows docs

Python's own docs are confusing but you don't actually want to use
`python3.dll` for the dynamic linkage.

9) Add generated autoconf file

10) Add v:python3_version support

This variable indicates the version of Python3 that Vim was built
against (PY_VERSION_HEX), and will be useful to check whether the Python
library you are loading in dynamically actually fits it. When built with
stable ABI, it will be the limited ABI version instead
(`Py_LIMITED_API`), which indicates the minimum version of Python 3 the
user should have, rather than the exact match. When stable ABI is used,
we won't be exposing PY_VERSION_HEX in this var because it just doesn't
seem necessary to do so (the whole point of stable ABI is the promise
that it will work across versions), and I don't want to confuse the user
with too many variables.

Also, cleaned up some documentation, and added help tags.

11) Fix Python 3.7 compat issues

Fix a couple issues when using limited API < 3.8

- Crash on exit: In Python 3.7, if a heap-allocated type is destroyed
  before all instances are, it would cause a crash later. This happens
  when we destroyed `OptionsType` before calling `Py_Finalize` when
  using the limited API. To make it worse, later versions changed the
  semantics and now each instance has a strong reference to its own type
  and the recommendation has changed to have each instance de-ref its
  own type and have its type in GC traversal. To avoid dealing with
  these cross-version variations, we just don't free the heap type. They
  are static types in non-limited-API anyway and are designed to last
  through the entirety of the app, and we also don't restart the Python
  runtime and therefore do not need it to have absolutely 0 leaks.

  See:
  - https://docs.python.org/3/whatsnew/3.8.html#changes-in-the-c-api
  - https://docs.python.org/3/whatsnew/3.9.html#changes-in-the-c-api

- PyIter_Check: This function is not provided in limited APIs older than
  3.8. Previously I was trying to mock it out using manual
  PyType_GetSlot() but it was brittle and also does not actually work
  properly for static types (it will generate a Python error). Just
  return false. It does mean using limited API < 3.8 is not recommended
  as you lose the functionality to handle iterators, but from playing
  with plugins I couldn't find it to be an issue.

- Fix loading of PyIter_Check so it will be done when limited API < 3.8.
  Otherwise loading a 3.7 Python lib will fail even if limited API was
  specified to use it.

12) Make sure to only load `PyUnicode_AsUTF8AndSize` in needed in limited API

We don't use this function unless limited API >= 3.10, but we were
loading it regardless. Usually it's ok in Unix-like systems where Python
just has a single lib that we load from, but in Windows where there is a
separate python3.dll this would not work as the symbol would not have
been exposed in this more limited DLL file. This makes it much clearer
under what condition is this function needed.

closes: vim#12032

Signed-off-by: Christian Brabandt <cb@256bit.org>
Co-authored-by: Yee Cheng Chin <ychin.git@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

6 participants