You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am writing a snippet of code that reads netCDF files and convert them to a dask dataframe with the method read_nc_to_df().
When opening multiple netCDF files with open_dataset() and dask.delayed, the code fails with segmentation fault error. Some times the segmentation fault error is preceded by more information, like:
*** Error in 'python3': double free or corruption (fasttop): 0x0000000003448df0 *** (this happened only once)
[Errno -101] NetCDF: HDF error: 'path/to/file/output_00.nc' There are 28 HDF5 objects open! Report: open objects on 72057594037927944 (this happened multiple times)
Note that I simply re-execute the same code, and different error outputs might appear, the only constant being the segmentation fault line.
What did you expect to happen?
I expected the code to execute regularly, open the netcdf files, and eventually convert the multiple datasets into a dask dataframe.
Minimal Complete Verifiable Example
importxarrayasxrimportnumpyasnpimportdaskimportdask.dataframeasddimportpandasaspdimportthreading##########################################################################defcreate_nc():
# Create data arrays for each variable with different dimensionstime=np.arange(10)
lat=np.linspace(-90, 90, 180)
lon=np.linspace(-180, 180, 360)
forjinrange(3):
# Variable 1: 1D array (time)var1=xr.DataArray(np.random.rand(len(time)), dims=["time"], coords={"time": time})
# Variable 2: 2D array (lat, lon)var2=xr.DataArray(np.random.rand(len(lat), len(lon)), dims=["lat", "lon"], coords={"lat": lat, "lon": lon})
# Variable 3: 3D array (time, lat, lon)var3=xr.DataArray(np.random.rand(len(time), len(lat), len(lon)), dims=["time", "lat", "lon"], coords={"time": time, "lat": lat, "lon": lon})
# Combine data arrays into a datasetds=xr.Dataset({
"var1": var1,
"var2": var2,
"var3": var3
})
# Save the dataset to a NetCDF fileds.to_netcdf("output_"+str(j).zfill(2) +".nc")
return##########################################################################defread_nc_into_df(filename,engine,lock):
# Read the NetCDF file into an xarray datasetiflockisNone:
withxr.open_dataset(filename,cache=False,engine=engine) asds:
# Convert the dataset to a pandas dataframedf=ds.to_dataframe()
else:
withlock:
withxr.open_dataset(filename,cache=False,engine=engine) asds:
# Convert the dataset to a pandas dataframedf=ds.to_dataframe()
returndf############# READING WITHOUT DASK ######################defno_dask(filenames,engine):
# Read each NetCDF file into a pandas dataframedfs= []
forfinfilenames:
dfs.append( read_nc_into_df(f,engine,None) )
df=pd.concat(dfs)
print(df.sample(frac=0.000005, random_state=42))
return############# READING WITH DASK.DELAYED ######################defwith_dask_delayed(filenames, engine, lock):
df= [ dask.delayed(read_nc_into_df)(f, engine, lock) forfinfilenames ]
df=dd.from_delayed(df)
print(df.sample(frac=0.000005, random_state=42).compute())
return########################################################################if__name__=="__main__":
create_nc()
filenames= ["output_"+str(j).zfill(2) +".nc"forjinrange(3)]
engines= [
"h5netcdf",
"netcdf4"
]
forengineinengines:
print("no_dask()")
print(f"Engine: {engine}")
try:
no_dask(filenames,engine)
print(f"no_dask() + {engine}: ok")
exceptExceptionase:
print(f"Error during no_dask() with engine {engine}: {e}")
raiseprint()
forlockin [threading.Lock(),None]:
forengineinengines:
print("with_dask_delayed()")
print(f"Engine: {engine}")
print(f"Lock: {lock}")
try:
with_dask_delayed(filenames,engine,lock)
print(f"with_dask_delayed() + {engine} + {lock}: ok")
exceptExceptionase:
print(f"Error during with_dask_delayed() with engine {engine} and lock {lock}: {e}")
raiseprint()
MVCE confirmation
Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
Complete example — the example is self-contained, including all data and the text of any traceback.
Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
New issue — a search of GitHub Issues suggests this is not a duplicate.
Recent environment — the issue occurs with the latest version of xarray and its dependencies.
The same read_nc_to_df function works regularly when:
using engine='h5netcdf', or
if it contained within a with threading.Lock() statement, or
if executed without dask.
The example above illustrates these situations, too. The behaviour seems to contradict the documentation, which states that "By default, appropriate locks are chosen to safely read and write files with the currently active dask scheduler."
The same read_nc_to_df function does not work regularly when a lock is explicitly passed to open_dataset() through the backend_kwargs argument. This is not in the above example to keep it more coincise.
Environment
INSTALLED VERSIONS
commit: None
python: 3.9.10 (main, Feb 20 2022, 11:57:16)
[GCC 8.3.1 20190311 (Red Hat 8.3.1-3)]
python-bits: 64
OS: Linux
OS-release: 3.10.0-1160.76.1.el7.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: ('en_US', 'UTF-8')
libhdf5: 1.14.2
libnetcdf: 4.9.4-development
Thanks for opening your first issue here at xarray! Be sure to follow the issue template!
If you have an idea for a solution, we would really welcome a Pull Request with proposed changes.
See the Contributing Guide for more.
It may take us a while to respond here, but we really value your contribution. Contributors like you help make xarray better.
Thank you!
enrico-mi
changed the title
Segmentation fault due to improper locking during open_dataset() with dask and netcdf4
Segmentation fault during open_dataset() with dask and netcdf4
Nov 13, 2024
What happened?
I am writing a snippet of code that reads netCDF files and convert them to a dask dataframe with the method
read_nc_to_df()
.When opening multiple netCDF files with
open_dataset()
anddask.delayed
, the code fails withsegmentation fault
error. Some times the segmentation fault error is preceded by more information, like:*** Error in 'python3': double free or corruption (fasttop): 0x0000000003448df0 ***
(this happened only once)[Errno -101] NetCDF: HDF error: 'path/to/file/output_00.nc' There are 28 HDF5 objects open! Report: open objects on 72057594037927944
(this happened multiple times)Note that I simply re-execute the same code, and different error outputs might appear, the only constant being the
segmentation fault
line.What did you expect to happen?
I expected the code to execute regularly, open the netcdf files, and eventually convert the multiple datasets into a dask dataframe.
Minimal Complete Verifiable Example
MVCE confirmation
Relevant log output
Anything else we need to know?
The same
read_nc_to_df
function works regularly when:engine='h5netcdf'
, orwith threading.Lock()
statement, ordask
.The example above illustrates these situations, too. The behaviour seems to contradict the documentation, which states that "By default, appropriate locks are chosen to safely read and write files with the currently active dask scheduler."
The same
read_nc_to_df
function does not work regularly when a lock is explicitly passed toopen_dataset()
through thebackend_kwargs
argument. This is not in the above example to keep it more coincise.Environment
INSTALLED VERSIONS
commit: None
python: 3.9.10 (main, Feb 20 2022, 11:57:16)
[GCC 8.3.1 20190311 (Red Hat 8.3.1-3)]
python-bits: 64
OS: Linux
OS-release: 3.10.0-1160.76.1.el7.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: ('en_US', 'UTF-8')
libhdf5: 1.14.2
libnetcdf: 4.9.4-development
xarray: 2024.2.0
pandas: 2.2.2
numpy: 1.26.4
scipy: 1.13.1
netCDF4: 1.7.2
pydap: None
h5netcdf: 1.4.1
h5py: 3.12.1
Nio: None
zarr: None
cftime: 1.6.4.post1
nc_time_axis: None
iris: None
bottleneck: None
dask: 2024.7.1
distributed: 2024.7.1
matplotlib: 3.9.2
cartopy: None
seaborn: None
numbagg: None
fsspec: 2023.10.0
cupy: None
pint: None
sparse: None
flox: None
numpy_groupies: None
setuptools: 69.5.1
pip: 24.3.1
conda: None
pytest: None
mypy: None
IPython: 8.18.1
sphinx: None
The text was updated successfully, but these errors were encountered: