Skip to content

Method to explicitly close memmap #13510

Open

Description

@lepmik

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.

Activity

  1. mattip commented on May 8, 2019

    @mattip
    Member

    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

  2. eric-wieser commented on May 9, 2019

    @eric-wieser
    Member

    Python solves this problem by:

    • 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.

  3. lepmik commented on May 9, 2019

    @lepmik
    Author

    I would expect the other references to be instances of a closed mmap, 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:

    image

  4. eric-wieser commented on May 9, 2019

    @eric-wieser
    Member

    The mmap example I'm thinking of is:

    with open('testfile', 'r+') as f:
        m = mmap.mmap(f.fileno(), 0)
    
    mv = memoryview(m)
    
    m.close()  # fails, because `mv` is still alive
    del mv
    m.close()  # ok

    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.

  5. uellue commented on Nov 11, 2019

    @uellue

    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()
    del self._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 process
    os.rename(self._tmp_file.name, self._path)
    
    dest_dir = os.path.dirname(self._path)
    self.sync_dir(dest_dir)
    self._tmp_file = None
    self._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 object
    mm = self._dest._mmap
    if mm is not None:
        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 = None
    self._dest = None

    Under these circumstances it would be great to have an explicit close() method instead of using internals of numpy.memmap.

  6. added a commit that references this issue on Nov 11, 2019
  7. added a commit that references this issue on Nov 11, 2019
  8. mattip commented on May 19, 2020

    @mattip
    Member

    This is important for supporting non-refcount GC strategies like in PyPy, where it is not clear when if at all fp will be freed after calling del fp.

  9. yoonghm commented on Dec 6, 2020

    @yoonghm

    I have created pull request in #17939

  10. eric-wieser commented on Dec 8, 2020

    @eric-wieser
    Member

    @lepmik:

    and the latter crashes the python interpreter if there exists another reference to the memmap.

    Do you have an example of this crash?

  11. BvB93 commented on Dec 8, 2020

    @BvB93
    Member

    This might beyond the scope of this issue, but if we're adding np.memmap.close then 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 the np.memmap is closed.

    Note that aforementioned methods/properties already exist in mmap.mmap.

  12. lepmik commented on Dec 8, 2020

    @lepmik
    Author
  13. eric-wieser commented on Dec 8, 2020

    @eric-wieser
    Member

    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?

  14. BvB93 commented on Dec 9, 2020

    @BvB93
    Member

    See below for a minimal example.
    Upon reaching the print(b) statement python just crashes without any further error message.

    >>> import numpy as np
    
    >>> with open("hello.txt", "wb") as f:
    ...     f.write(b"Hello Python!\n")
    
    >>> with open("hello.txt", "r+b") as f:
    ...     a = np.memmap(f)
    ...     b = a.view()
    ...
    ...     a._mmap.close()
    ...     print(b)  # python hard-crashes here
  15. eric-wieser commented on Dec 9, 2020

    @eric-wieser
    Member

    Thanks for that @BvB93. I think that means we can't merge the PR that exposes this behavior?

  16. BvB93 commented on Dec 9, 2020

    @BvB93
    Member

    I don't suppose that it is possible to somehow gather (and close) all views of a given array?

  17. mattip commented on Dec 9, 2020

    @mattip
    Member

    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.

  18. eric-wieser commented on Dec 9, 2020

    @eric-wieser
    Member

    The only way I can think of to make this work is:

    • Completely overhaul memmap to be a proxy object, holding a _mmap and _array member
    • Construct the _array member from memoryview(_mmap). This prevents any crashes
    • Implement __getattr__ to proxy all operations to _array
    • Have close() clear the array member, so that _mmap.close() doesn't throw an exception
  19. seberg commented on Dec 9, 2020

    @seberg
    Member

    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.

  20. eric-wieser commented on Dec 9, 2020

    @eric-wieser
    Member

    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.

  21. lepmik commented on Dec 10, 2020

    @lepmik
    Author
  22. yoonghm commented on Dec 10, 2020

    @yoonghm

    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()

    import mmap
    
    # write a simple example file
    with open("hello.txt", "wb") as f:
        f.write(b"Hello Python!\n")
    
    with open("hello.txt", "r+b") as f:
        mm = mmap.mmap(f.fileno(), 0)
        print(mm.readline())
        mm.close()
        print(mm)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions