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
As far as I understand, there are currently two ways to close a memmap "file"; del fp or fp._mmap.close(). However, the former only closes the file if fp is the only reference to the memmap and the latter crashes the python interpreter if there exists another reference to the memmap.
Are there any plans of implementing a close method i.e. fp.close()? It would be much appreciated.
Reacted by Dieter Weber, Evgenii Mozharovskii, Han Xiao, Anar Z. Yusifov, Gus Pozuelo, Pablo Dumas, Dominik Kutra, Gattocrucco, TsiVit, Miguel de Benito Delgado and 1 more
What would you expect to happen if the memmap is held by more than one np.memmap? Should it somehow be aware of the other instance and not close the resource?
I agree we should definitely not segfault, that is rarely expected behaviour
Having mmap.close() count the number of referrers to the underlying data, and throw an exception if it's not zero. This prevents memoryview(x) objects outliving the mmap
Making all of the methods of mmap raise ValueError once it is closed.
We could emulate the first one, but given that np.memmap inherits from np.ndarray which has C-level attributes, there's no way to achieve the second. To make this work, we'd need to switch np.memmap from being a subclass to an array_like.
I would expect the other references to be instances of a closedmmap, and that all methods and attributes to be unavailable. At least it should not be read/writable after closing. Throwing an error if the refcount is not zero is better behavior than the present one, but I think a more natural behavior would be to throw the error when the reference actually tries to reach the data ala:
A close() method turns out to be important for Windows when renaming files. This seems to be a timing issue between del and renaming if threads are active. We experienced the problem mainly if a Dask.distributed client had been started before, not under simple circumstances.
This code snippet can trigger failures since the mmap object may not be closed yet:
self._dest.flush() # msync# to make Windows™ happy:self._tmp_file.close()
delself._dest# self._dest is a numpy.memmap object# os.rename() can fail with# PermissionError: [WinError 32] The process cannot access the file because it is being used by another processos.rename(self._tmp_file.name, self._path)
dest_dir=os.path.dirname(self._path)
self.sync_dir(dest_dir)
self._tmp_file=Noneself._dest=None
Closing the _mmap object fixes the error:
self._dest.flush() # msync# to make Windows™ happy:self._tmp_file.close()
# self._dest is a numpy.memmap objectmm=self._dest._mmapifmmisnotNone:
mm.close()
os.rename(self._tmp_file.name, self._path)
dest_dir=os.path.dirname(self._path)
self.sync_dir(dest_dir)
self._tmp_file=Noneself._dest=None
Under these circumstances it would be great to have an explicit close() method instead of using internals of numpy.memmap.
Thanks for the quick response. Do you happen to remember what you meant by "crashes the python interpreter"? Did you mean that a python exception was thrown, or that the interpreter exited / segfaulted?
We may be able to trick Python, which has some more elaborate scheme for memoryview (a second reference counting for memory buffers). I am not sure how that works together with mmap objects, so maybe we could hook into it. But:
with open("/tmp/hello.txt", "r+b") as f:
a = np.memmap(f)
mview = memoryview(a._mmap)
b = a.view()
a._mmap.close()
simply making the base arr.base = memoryview(...) might actually be enough to solve the issue?
EDIT: Sorry, should have looked through the history, I see you already brought that up.
Making the base object memoryview solves half the issue (it makes the crash impossible) - but it also makes close() throw an exception saying that references are still alive.
Now I see the problem that you mentioned, as I did not realize there were new update you.
I think np.memmap() should handle filename which is a string rather than an IO buffer. The IO buffer is opened by something else and np.memmap() has no control to prevent the IO buffer from being closed.
Also cannot prevent other to keep a reference to the memory which was already released.
Very different from mmap()
importmmap# write a simple example filewithopen("hello.txt", "wb") asf:
f.write(b"Hello Python!\n")
withopen("hello.txt", "r+b") asf:
mm=mmap.mmap(f.fileno(), 0)
print(mm.readline())
mm.close()
print(mm)
Activity
mattip commentedon May 8, 2019
What would you expect to happen if the memmap is held by more than one
np.memmap? Should it somehow be aware of the other instance and not close the resource?I agree we should definitely not segfault, that is rarely expected behaviour
eric-wieser commentedon May 9, 2019
Python solves this problem by:
mmap.close()count the number of referrers to the underlying data, and throw an exception if it's not zero. This preventsmemoryview(x)objects outliving the mmapmmapraise ValueError once it is closed.We could emulate the first one, but given that
np.memmapinherits fromnp.ndarraywhich has C-level attributes, there's no way to achieve the second. To make this work, we'd need to switchnp.memmapfrom being a subclass to an array_like.lepmik commentedon May 9, 2019
I would expect the other references to be instances of a
closedmmap, and that all methods and attributes to be unavailable. At least it should not be read/writable after closing. Throwing an error if the refcount is not zero is better behavior than the present one, but I think a more natural behavior would be to throw the error when the reference actually tries to reach the data ala:eric-wieser commentedon May 9, 2019
The mmap example I'm thinking of is:
So there's a distinction between the direct refcount of the map object itself, and the number of "view" objects that are pointing to it.
uellue commentedon Nov 11, 2019
A
close()method turns out to be important for Windows when renaming files. This seems to be a timing issue betweendeland renaming if threads are active. We experienced the problem mainly if a Dask.distributed client had been started before, not under simple circumstances.This code snippet can trigger failures since the mmap object may not be closed yet:
Closing the _mmap object fixes the error:
Under these circumstances it would be great to have an explicit
close()method instead of using internals ofnumpy.memmap.Fixed renaming issue on Windows
Fixed renaming issue on Windows
Fix hang when saving to file that has been opened as a memmap file
mattip commentedon May 19, 2020
This is important for supporting non-refcount GC strategies like in PyPy, where it is not clear when if at all
fpwill be freed after callingdel fp.yoonghm commentedon Dec 6, 2020
I have created pull request in #17939
eric-wieser commentedon Dec 8, 2020
@lepmik:
Do you have an example of this crash?
BvB93 commentedon Dec 8, 2020
This might beyond the scope of this issue, but if we're adding
np.memmap.closethen I'd say there is also an argument for adding:__enter__&__exit__so that it can be used as a context manager.closed, the latter being a property that returns whether or not thenp.memmapis closed.Note that aforementioned methods/properties already exist in
mmap.mmap.lepmik commentedon Dec 8, 2020
eric-wieser commentedon Dec 8, 2020
Thanks for the quick response. Do you happen to remember what you meant by "crashes the python interpreter"? Did you mean that a python exception was thrown, or that the interpreter exited / segfaulted?
BvB93 commentedon Dec 9, 2020
See below for a minimal example.
Upon reaching the
print(b)statement python just crashes without any further error message.eric-wieser commentedon Dec 9, 2020
Thanks for that @BvB93. I think that means we can't merge the PR that exposes this behavior?
BvB93 commentedon Dec 9, 2020
I don't suppose that it is possible to somehow gather (and close) all views of a given array?
mattip commentedon Dec 9, 2020
The problem is not just ndarrays. Anyone can create another reference to a memmap object. Once one user closes the mmap, no other user can index it.
eric-wieser commentedon Dec 9, 2020
The only way I can think of to make this work is:
_mmapand_arraymember_arraymember frommemoryview(_mmap). This prevents any crashes__getattr__to proxy all operations to_arrayclose()clear the array member, so that_mmap.close()doesn't throw an exceptionseberg commentedon Dec 9, 2020
We may be able to trick Python, which has some more elaborate scheme for
memoryview(a second reference counting for memory buffers). I am not sure how that works together with mmap objects, so maybe we could hook into it. But:simply making the base
arr.base = memoryview(...)might actually be enough to solve the issue?EDIT: Sorry, should have looked through the history, I see you already brought that up.
eric-wieser commentedon Dec 9, 2020
Making the base object
memoryviewsolves half the issue (it makes the crash impossible) - but it also makesclose()throw an exception saying that references are still alive.lepmik commentedon Dec 10, 2020
yoonghm commentedon Dec 10, 2020
Now I see the problem that you mentioned, as I did not realize there were new update you.
I think
np.memmap()should handlefilenamewhich is a string rather than an IO buffer. The IO buffer is opened by something else andnp.memmap()has no control to prevent the IO buffer from being closed.Also cannot prevent other to keep a reference to the memory which was already released.
Very different from
mmap()