[Python][C++] `ArrowKeyError: Attempted to register factory for scheme 'file'` when using pip-installed GDAL
Describe the bug, including details regarding any error messages, version, and platform.
As always, let me preface this with a thanks for this project and the help the arrow developers are giving to the community (which I have benefited from before).
Description
I've been tracking a more-than-likely install related bug. Here is a minimal reproducer
# file test.py
import osgeo
from pyarrow import fs
local = fs.LocalFileSystem()
and if I run it
$ python test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
local = fs.LocalFileSystem()
^^^^^^^^^^^^^^^^^^^^
File "pyarrow/_fs.pyx", line 1112, in pyarrow._fs.LocalFileSystem.__init__
File "pyarrow/error.pxi", line 155, in pyarrow.lib.pyarrow_internal_check_status
File "pyarrow/error.pxi", line 92, in pyarrow.lib.check_status
pyarrow.lib.ArrowKeyError: Attempted to register factory for scheme 'file' but that scheme is already registered.
Note that if I do not import osgeo there is no error.
Reproduce
The steps from scratch are the following
conda create -n test-arrow python=3.12
conda activate test-arrow
pip install pyarrow 'gdal==3.9.2'
Probably relevant is the fact that I have gdal libraries installed with homebrew (on MacOS)
$ brew info gdal
==> gdal: stable 3.9.2 (bottled), HEAD
Geospatial Data Abstraction Library
https://www.gdal.org/
Conflicts with:
avce00 (because both install a cpl_conv.h header)
cpl (because both install cpl_error.h)
Installed
/opt/homebrew/Cellar/gdal/3.9.2_1 (497 files, 35.9MB) *
Poured from bottle using the formulae.brew.sh API on 2024-09-27 at 14:14:44
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/g/gdal.rb
Workaround
Everything works if I conda install gdal instead of using pip (presumably, this also install the libraries and does not use the homebrew-installed gdal).
Component(s)
Python
Thanks for raising this. It seems like we are registering on the FileSystemFactoryRegistry the filesystem twice on this specific case. @bkietz I might try to investigate further but any clue on what might be happening here?
This is probably due to conflicting versions of libarrow in the same process (one from brew's gdal and one from conda's pyarrow). Each libarrow is registering different factories for the file:// scheme, which is raised as an error. Installing with just conda ensures that only a single version of libarrow is visible which ensures that only one set of factories is registered. @gbelouze Could you check if gdal and conda indeed have multiple libarrows?
Having multiple versions of libarrow in play seems like something we'd want to avoid in any case; more subtle errors could arise than this KeyError with filesystem registration. Maybe we should try to assert this at runtime?
Thanks for your response. I am a bit puzzled because in the steps to produce the errors I am not installing anything with conda, just using it as a python environment manager. Could you maybe point to how I should check for libarrows ?
I have
$ conda list ─╯
# packages in environment at /opt/homebrew/Caskroom/miniconda/base/envs/test-arrow:
#
# Name Version Build Channel
bzip2 1.0.8 h99b78c6_7 conda-forge
ca-certificates 2024.8.30 hf0a4a13_0 conda-forge
gdal 3.9.2 pypi_0 pypi
libexpat 2.6.4 h286801f_0 conda-forge
libffi 3.4.2 h3422bc3_5 conda-forge
libsqlite 3.47.0 hbaaea75_1 conda-forge
libzlib 1.3.1 h8359307_2 conda-forge
ncurses 6.5 h7bae524_1 conda-forge
openssl 3.4.0 h39f12f2_0 conda-forge
pip 24.3.1 pyh8b19718_0 conda-forge
pyarrow 18.0.0 pypi_0 pypi
python 3.12.7 h739c21a_0_cpython conda-forge
readline 8.2 h92ec313_1 conda-forge
setuptools 75.3.0 pyhd8ed1ab_0 conda-forge
tk 8.6.13 h5083fa2_1 conda-forge
tzdata 2024b hc8b5060_0 conda-forge
wheel 0.45.0 pyhd8ed1ab_0 conda-forge
xz 5.2.6 h57fd34a_0 conda-forge
If you're using conda, that will put libarrow.so in $CONDA_PREFIX/lib/
Brew is configurable. IIUC the default is /usr/opt/lib but you can get the exact location for a package with brew --prefix gdal
I expect you will see libarrow in both of those places in your error case
On Linux you can see which dynamic libraries are loaded at runtime with
>>> print(pathlib.Path("/proc/self/maps").read_text())
... but I don't know what the equivalent for macOS would be
I think in your case you're getting a statically-linked Arrow (via pyarrow, since it looks like it was installed from pypi) and a dynamically-linked Arrow (via pip install gdal, which I believe builds against your homebrew Arrow). I am wondering if that error would also occur if the versions were identical because of the static/dynamic mismatch.
Also possibly related: https://github.com/OSGeo/gdal/pull/10539
The basic question: Is it possible to install pyarrow in a way that doesn't include libarrow as a static bundle or otherwise tell it to use a system installed one?
Background: I am on a mac and using R & RStudio. Our R code uses many packages that use gdal and on Mac the natural way to get that is to use homebrew install which also installs the homebrew package apache-arrow which includes libarrow. But I'm also working with python code that calls out to R packages (using rpy2) which naturally loads the homebrew version of libarrow indirectly. I'm also using geopandas which in order to write out GeoDataFrame objects into parquet files requires pyarrow installed. And thus I hit this issue.
I can workaround it in a number of ways:
- round trip geopandas dataframes into R, then back to python pandas data frames and use
pandas.DataFram.to_parquetwithengine="fastparquet"(this maps the geometry column into WKT) - within python convert geopandas dataframes into pandas versions, manually converting the geometry column and then use pandas
to_parquet(as above). - rewrite any code that needs to write geopandas dataframes to parquet to avoid import of rpy2 (thus avoiding the R environment being loaded and thus loading system / homebrew libarrow).
But given that libarrow installed as part of pyarrow on disk is already 50MB and I have another one installed in the homebrew setup (same version even!) it would be nice to just have one installed.
mac use 16.1.0 is ok. , other version has error. 😂 pip3 install --upgrade pyarrow~=16.1.0
I've also run into this when building a custom GDAL wheel on Linux. I can make the issue go away by deleting the site-packages/pyarrow/libarrow.so.2000 and symlinking to site-packages/gdal.libs/libarrow-98814463.so.2000.0.0, but it's a horrible hack. Looking for a better solution!
As @shiweihappy said - v16.1.0 works for Linux users too. I guess 17.0 is when the problem started - this command worked for me:
pip install "pyarrow<17.0.0"
I hit the same issue on macOS, I use uv and wanted to be independent of conda. After some iterations, I fixed it by forcing pyogrio and pyarrow to build against the Homebrew-installed libraries.
With some rewrite from Copilot, this script should be working for someone in the same situation:
#!/usr/bin/env bash
# align_with_homebrew.sh — rebuild pyogrio & pyarrow against Homebrew libs on macOS
set -euo pipefail
need() { command -v "$1" >/dev/null 2>&1 || { echo "Missing required command: $1" >&2; exit 1; }; }
need brew
need uv
need jq
echo "Sync environment with uv…"
uv sync
echo "Aligning pyogrio with Homebrew GDAL…"
GDAL_PREFIX="$(brew --prefix gdal)"
uv pip uninstall pyogrio || true
CMAKE_PREFIX_PATH="$GDAL_PREFIX" uv pip install --no-binary=pyogrio pyogrio
echo "Aligning pyarrow with Homebrew Apache Arrow…"
ARROW_PREFIX="$(brew --prefix apache-arrow)"
ARROW_VER="$(brew info --json apache-arrow | jq -r '.[0].versions.stable')"
uv pip uninstall pyarrow || true
PKG_CONFIG_PATH="$ARROW_PREFIX/lib/pkgconfig" \
CMAKE_PREFIX_PATH="$ARROW_PREFIX" \
ARROW_HOME="$ARROW_PREFIX" \
uv pip install --no-binary=pyarrow "pyarrow==${ARROW_VER}"
echo "Done. pyogrio and pyarrow are now built against Homebrew's GDAL/Arrow."
I hope this is of help to someone.
Thanks for the amazing work on pyarrow 🙏
I have a similar issue on Python 3.14 and (which requires) pyarrow 22.0.0. I would like to avoid conda. Dropping a summary of my situation and a (hacky) patch to dodge the duble registraion.
DISCALIMER/I am aware of:
Having multiple versions of libarrow in play seems like something we'd want to avoid in any case; more subtle errors could arise than this KeyError with filesystem registration. Maybe we should try to assert this at runtime?
so this is just a workaround that seems to work for me so far.
Maybe it can be of help to someone - or let me know if it is misleading/strongly discouraged 😅
Environment
# System
$ sw_vers
ProductName: macOS
ProductVersion: 15.6
BuildVersion: 24G84
# Python
$ python --version
Python 3.14.0
# GDAL
$ gdal-config --version
3.11.5
# Python packages
$ pip list | grep -E "(pyarrow|rasterio|geopandas)"
geopandas 1.1.1
pyarrow 22.0.0
rasterio 1.4.3
Issue
When using PyArrow 22.0.0 alongside GDAL-based libraries (rasterio, fiona, pyogrio) on Python 3.14, we encounter:
ArrowKeyError: Attempted to register factory for scheme 'file' but that scheme is already registered.
Minimal Reproduction
# This fails:
import rasterio # or fiona, or pyogrio
from pyarrow import fs
local_fs = fs.LocalFileSystem() # ArrowKeyError
# This also fails:
from pyarrow import fs
local_fs1 = fs.LocalFileSystem() # OK
import rasterio
local_fs2 = fs.LocalFileSystem() # ArrowKeyError
The error occurs when:
- GDAL-based library is imported (registers
file://scheme) - PyArrow tries to create a
LocalFileSystem(also tries to registerfile://scheme)
Or vice versa - whichever tries to register second fails.
Hacky patch solution:
"""Patch for PyArrow 22.0.0 + GDAL compatibility issue.
This patches PyArrow's `_resolve_filesystem_and_path` function to reuse a cached
LocalFileSystem instance instead of creating new ones, which avoids the
"Attempted to register factory for scheme 'file' but that scheme is already registered"
error when using PyArrow alongside GDAL-based libraries (rasterio, fiona, pyogrio).
Root cause: PyArrow (from PyPI) and GDAL (from Homebrew on macOS) each bundle their
own libarrow library, and both try to register the 'file://' URI scheme handler.
Usage:
# At the top of your script or python session:
from <my_package>.pyarrow_gdal_patch import apply_patch
apply_patch()
It is also recommended to import and apply the patch in your package's root
`__init__.py` file to ensure it is applied before any other imports:
# Auto-apply PyArrow/GDAL compatibility patch. This must be imported before any other
# modules that use PyArrow or GDAL to avoid "Attempted to register factory for scheme
# 'file'" errors. See `pyarrow_gdal_patch.py` for details.
from <my_package>.pyarrow_gdal_patch import apply_patch
apply_patch()
"""
import pyarrow.fs as arrow_fs
from pyarrow._fs import FileSystem, LocalFileSystem
# Cache LocalFileSystem instances for both memory_map settings
# We create both upfront before any GDAL imports to avoid registration conflicts
_cached_local_fs_no_mmap: LocalFileSystem | None = None
_cached_local_fs_with_mmap: LocalFileSystem | None = None
# Store original function (in case we need to unpatch)
_original_resolve = arrow_fs._resolve_filesystem_and_path # type: ignore
def _patched_resolve_filesystem_and_path(
path, # type: ignore
filesystem=None, # type: ignore
*,
memory_map=False, # type: ignore
):
"""Patched version of PyArrow's _resolve_filesystem_and_path that reuses
cached LocalFileSystem instances to avoid re-registration conflicts.
We maintain two cached instances (one for memory_map=True, one for False)
that are created upfront before any GDAL imports. This allows us to respect
the memory_map parameter without triggering the 'file://' scheme registration
conflict with GDAL.
"""
global _cached_local_fs_no_mmap, _cached_local_fs_with_mmap
# Original logic from pyarrow/fs.py
if not arrow_fs._is_path_like(path): # type: ignore
if filesystem is not None:
raise ValueError(
"'filesystem' passed but the specified path is file-like, so"
" there is nothing to open with 'filesystem'."
)
return filesystem, path
if filesystem is not None:
filesystem = arrow_fs._ensure_filesystem(filesystem, use_mmap=memory_map) # type: ignore
if isinstance(filesystem, LocalFileSystem):
path = arrow_fs._stringify_path(path) # type: ignore
elif not isinstance(path, str):
raise TypeError(
"Expected string path; path-like objects are only allowed "
"with a local filesystem"
)
path = filesystem.normalize_path(path) # type: ignore
return filesystem, path
path = arrow_fs._stringify_path(path) # type: ignore
# PATCH: Reuse cached LocalFileSystem instead of creating a new one
# This is the key change - line 160 in the original creates:
# LocalFileSystem(use_mmap=memory_map)
# We use the appropriate cached instance based on memory_map parameter
if memory_map:
if _cached_local_fs_with_mmap is None:
_cached_local_fs_with_mmap = LocalFileSystem(use_mmap=True)
filesystem = _cached_local_fs_with_mmap
else:
if _cached_local_fs_no_mmap is None:
_cached_local_fs_no_mmap = LocalFileSystem(use_mmap=False)
filesystem = _cached_local_fs_no_mmap
try:
file_info = filesystem.get_file_info(path) # type: ignore
except ValueError:
file_info = None
exists_locally = False
else:
exists_locally = file_info.type != arrow_fs.FileType.NotFound # type: ignore
# If file doesn't exist locally, try parsing as URI
if not exists_locally:
try:
filesystem, path = FileSystem.from_uri(path) # type: ignore
except ValueError as e:
msg = str(e)
if "empty scheme" in msg or "Cannot parse URI" in msg:
# Neither URI nor locally existing path - will propagate file not found
pass
else:
raise e
else:
path = filesystem.normalize_path(path) # type: ignore
return filesystem, path
def apply_patch():
"""Apply the PyArrow/GDAL compatibility patch.
This creates both LocalFileSystem instances (memory_map=True and False)
upfront before any GDAL imports. This allows us to respect the memory_map
parameter while avoiding the 'file://' scheme registration conflict.
"""
global _cached_local_fs_no_mmap, _cached_local_fs_with_mmap
# Replace the function
arrow_fs._resolve_filesystem_and_path = _patched_resolve_filesystem_and_path
# Initialize BOTH cached LocalFileSystem instances before any GDAL imports
# This must happen before GDAL imports to claim the 'file://' scheme
from pyarrow import fs
if _cached_local_fs_no_mmap is None:
_cached_local_fs_no_mmap = fs.LocalFileSystem(use_mmap=False) # type: ignore
if _cached_local_fs_with_mmap is None:
_cached_local_fs_with_mmap = fs.LocalFileSystem(use_mmap=True) # type: ignore
We also struggle with this at pyopenms and would like to still offer wheels. We only want to use simple arrow array and parquet reading functionality. We do not register any filesystem manually. Libarrow seems to do this automatically. Can't the global state be made a bit more forgiving/compatible for conflicting libraries? I know it is not ideal but it seems to work for non-macOS and we would like to risk it for the sake of convenience. We will try the hacky workaround above now.