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

unnecessary copying of memoryview in gzip.GzipFile.write? #67876

Closed
wm75 mannequin opened this issue Mar 17, 2015 · 31 comments
Closed

unnecessary copying of memoryview in gzip.GzipFile.write? #67876

wm75 mannequin opened this issue Mar 17, 2015 · 31 comments
Assignees
Labels
performance Performance or resource usage stdlib Python modules in the Lib dir

Comments

@wm75
Copy link
Mannequin

wm75 mannequin commented Mar 17, 2015

BPO 23688
Nosy @vstinner, @skrah, @vadmium, @serhiy-storchaka, @wm75
Files
  • memoryview_write.patch
  • test_memoryview_write.patch
  • write_bytes_like_objects.patch
  • write_bytes_like_objects_v2.patch
  • write_bytes_like_objects_v3.patch
  • gzip_write_noncontiguous.patch
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = 'https://github.com/serhiy-storchaka'
    closed_at = <Date 2015-03-23.13:32:26.028>
    created_at = <Date 2015-03-17.14:26:04.343>
    labels = ['library', 'performance']
    title = 'unnecessary copying of memoryview in gzip.GzipFile.write?'
    updated_at = <Date 2015-03-23.14:59:32.704>
    user = 'https://github.com/wm75'

    bugs.python.org fields:

    activity = <Date 2015-03-23.14:59:32.704>
    actor = 'serhiy.storchaka'
    assignee = 'serhiy.storchaka'
    closed = True
    closed_date = <Date 2015-03-23.13:32:26.028>
    closer = 'serhiy.storchaka'
    components = ['Library (Lib)']
    creation = <Date 2015-03-17.14:26:04.343>
    creator = 'wolma'
    dependencies = []
    files = ['38521', '38526', '38600', '38639', '38650', '38656']
    hgrepos = []
    issue_num = 23688
    keywords = ['patch']
    message_count = 31.0
    messages = ['238294', '238295', '238300', '238301', '238304', '238305', '238307', '238308', '238315', '238329', '238344', '238350', '238376', '238385', '238666', '238946', '239006', '239015', '239019', '239020', '239024', '239027', '239029', '239030', '239031', '239032', '239033', '239034', '239035', '239036', '239037']
    nosy_count = 6.0
    nosy_names = ['vstinner', 'skrah', 'python-dev', 'martin.panter', 'serhiy.storchaka', 'wolma']
    pr_nums = []
    priority = 'normal'
    resolution = 'fixed'
    stage = 'resolved'
    status = 'closed'
    superseder = None
    type = 'performance'
    url = 'https://bugs.python.org/issue23688'
    versions = ['Python 3.5']

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 17, 2015

    I thought I'd go back to work on a test patch for bpo-21560 today, but now I'm puzzled by the explicit handling of memoryviews in gzip.GzipFile.write.
    The method is defined as:

        def write(self,data):
            self._check_closed()
            if self.mode != WRITE:
                import errno
                raise OSError(errno.EBADF, "write() on read-only GzipFile object")
    
            if self.fileobj is None:
                raise ValueError("write() on closed GzipFile object")
    
            # Convert data type if called by io.BufferedWriter.
            if isinstance(data, memoryview):
                data = data.tobytes()
    
            if len(data) > 0:
                self.size = self.size + len(data)
                self.crc = zlib.crc32(data, self.crc) & 0xffffffff
                self.fileobj.write( self.compress.compress(data) )
                self.offset += len(data)
    
            return len(data)

    So for some reason, when it gets passed data as a meoryview it will first copy its content to a bytes object and I do not understand why.
    zlib.crc32 and zlib.compress seem to be able to deal with memoryviews so the only sepcial casing that seems required here is in determining the byte length of the data, which I guess needs to use memoryview.nbytes. I've prepared a patch (overlapping the one for bpo-21560) that avoids copying the data and seems to work fine.

    Did I miss something about the importance of the tobytes conversion ?

    @wm75 wm75 mannequin added performance Performance or resource usage stdlib Python modules in the Lib dir labels Mar 17, 2015
    @vstinner
    Copy link
    Member

    The patch looks good to be me, but it lacks an unit test. Can you please add a simple unit test to ensure that it's possible to memoryview to write(), and that the result is correct? (ex: uncompress and ensure that you get the same content)

    @vstinner vstinner added performance Performance or resource usage and removed performance Performance or resource usage labels Mar 17, 2015
    @serhiy-storchaka
    Copy link
    Member

    Better way is data = data.cast('B').

    @vstinner
    Copy link
    Member

    Better way is data = data.cast('B').

    Why is this cast required? Can you please elaborate? If some memoryview must be rejected, again, we need more unit tests.

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 17, 2015

    Here is a patch with memoryview tests.
    Are tests and code patches supposed to go in one file or separate ones ?

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 17, 2015

    @serhiy:
    Why would data = data.cast('B') be required ? When would the memoryview not be in 'B' format already ?

    @serhiy-storchaka
    Copy link
    Member

    memoryview is converted to bytes because len() for memoryview returns a size of first dimension (a number of items for one-dimension view), not a number of bytes.

    >>> m = memoryview(array.array('I', [1, 2, 3]))
    >>> len(m)
    3
    >>> len(m.tobytes())
    12
    >>> len(m.cast('B'))
    12

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 17, 2015

    memoryview is converted to bytes because len() for memoryview returns a size of first dimension (a number of items for one-dimension view), not a number of bytes.

    >>> m = memoryview(array.array('I', [1, 2, 3]))
    >>> len(m)
    3
    >>> len(m.tobytes())
    12
    >>> len(m.cast('B'))
    12

    Right, I was aware of this. But are you saying that my proposed solution (using memoryview.nbytes) is wrong ? If so, then cast is certainly an option and should still outperform tobytes.

    @vstinner
    Copy link
    Member

    Are tests and code patches supposed to go in one file or separate ones ?

    It's more convinient to have a single patch with both changes.

    @serhiy-storchaka
    Copy link
    Member

    You patch is correct Wolfgang, but with cast('B') the patch would be smaller (no need to replace len(data) to nbytes).

    While we are here, it is possible to add the support of general byte-like objects.

    if not isinstance(data, bytes):
        data = memoryview(data).cast('B')

    isinstance() check is just for optimization, it can be omitted if doesn't affect a performance.

    @vstinner
    Copy link
    Member

    While we are here, it is possible to add the support of general byte-like objects.

    With and without the patch, write() accepts bytes, bytearray and memoryview. Which other byte-like types do you know?

    writeframesraw() method of aifc, sunau and wave modules use this pattern:

        if not isinstance(data, (bytes, bytearray)):
            data = memoryview(data).cast('B')

    We can maybe reuse it in gzip module?

    @serhiy-storchaka
    Copy link
    Member

    With and without the patch, write() accepts bytes, bytearray and memoryview.
    Which other byte-like types do you know?

    The "bytes-like object" term is used as an alias of "an instance of type that
    supports buffer protocol". Besides bytes, bytearray and memoryview, this is
    array.array and NumPy arrays. file.write() supports arbitrary bytes-like
    objects, including array.array and NumPy arrays.

    writeframesraw() method of aifc, sunau and wave modules use this pattern:

    Yes, I wrote this code, if I remember correct.

    @serhiy-storchaka serhiy-storchaka changed the title unnecessary copying of memoryview in gzip.GzipFile.write ? unnecessary copying of memoryview in gzip.GzipFile.write? Mar 17, 2015
    @vadmium
    Copy link
    Member

    vadmium commented Mar 18, 2015

    I would say that the current patch looks correct enough, in that it would still get the correct lengths when a memoryview() object is passed in. The zlib module’s crc32() function and compress() method already seem to support arbitrary bytes-like objects.

    But to make GzipFile.write() also accept arbitrary bytes-like objects, you probably only need to change the code calculating the length to something like:

    with memoryview(data) as view:
        length = view.nbytes

    # Go on to call compress(data) and crc32(data)

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 18, 2015

    Thanks everyone for the lively discussion !

    I like Serhiy's idea of making write work with arbitrary objects supporting the buffer protocol. In fact, I noticed before that GzipFile.write misbehaves with array.array input. It pretends to accept that, but it'll use len(data) for calculating the zip file metadata so reading from the file will later fail. I was assuming then that fixing that would be too complicated for a rather exotic usecase, but now that I see how simple it really is I think it should be done.

    As for the concrete implementation, I guess an isinstance(data, bytes) check to speed up treatment of the most common input is a good idea, but I am not convinced that bytearray deserves the same attention.

    Regarding memoryview.cast('B') vs memoryview.nbytes, I see Serhiy's point of keeping the patch size smaller. Personally though, I find use of nbytes much more self-explanatory than cast('B') the purpose of which was not immediately obvious to me. So I would opt for better readability of the final code rather than optimizing patch size, but I would be ok with either solution since it is not about the essence of the patch anyway.

    Finally, the bug I report in bpo-21560 would be fixed as a side-effect of this patch here (because trying to get a memoryview from str would throw an early TypeError). Still, I think it would be a good idea to try to write to the wrapped fileobj *before* updating self.size and self.crc to be protected from unforeseen errors. So maybe we could include that change in the patch here ?

    With all that the final code section could look like this:

            if isinstance(data, bytes):
                length = len(data)
            else:
                data = memoryview(data)
                length = data.nbytes
    
            if length > 0:
                self.fileobj.write( self.compress.compress(data) )
                self.size = self.size + length
                self.crc = zlib.crc32(data, self.crc) & 0xffffffff
                self.offset += length
    
            return length

    One remaining detail then would be whether one would want to catch the TypeError possibly raised by the memoryview constructor to turn it into something less confusing (after all many users will not know what a memoryview has to do with all this). The above code would throw (with str input for example):

    Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
      File "/home/wolma/gzip-bug/Lib/gzip.py", line 340, in write
        data = memoryview(data)
    TypeError: memoryview: a bytes-like object is required, not 'str'

    Maybe, this could be turned into:

    TypeError: must be bytes / bytes-like object, not 'str' ?

    to be consistent with the corresponding error in 'wt' mode ?

    Let me know which of the above options you favour and I'll provide a new patch.

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 20, 2015

    ok, I've prepared a patch including tests based on my last suggestion, which I think is ready for getting reviewed.

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 22, 2015

    Here is a revised version of my patch addressing Serhiy's review comments.

    @serhiy-storchaka
    Copy link
    Member

    In general the patch LGTM.

    @serhiy-storchaka serhiy-storchaka self-assigned this Mar 23, 2015
    @python-dev
    Copy link
    Mannequin

    python-dev mannequin commented Mar 23, 2015

    New changeset 4dc69e5124f8 by Serhiy Storchaka in branch 'default':
    Issue bpo-23688: Added support of arbitrary bytes-like objects and avoided
    https://hg.python.org/cpython/rev/4dc69e5124f8

    @skrah
    Copy link
    Mannequin

    skrah mannequin commented Mar 23, 2015

    I think there's a behavior change: Before you could gzip non-contiguous
    views directly, now that operation raises BufferError.

    @serhiy-storchaka
    Copy link
    Member

    Could you provide an example?

    @skrah
    Copy link
    Mannequin

    skrah mannequin commented Mar 23, 2015

    Sure:

    import gzip
    x = memoryview(b'x' * 10)
    y = x[::-1]
    with gzip.GzipFile("xxxxx", 'w') as f:
        f.write(y)

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 23, 2015

    ouch. haven't thought of this.

    OTOH, just plain io with your example:

    with open('xy', 'wb') as f:
        f.write(y)
    Traceback (most recent call last):
      File "<pyshell#29>", line 2, in <module>
        f.write(y)
    BufferError: memoryview: underlying buffer is not C-contiguous

    fails too and after all that's not too surprising.

    In a sense, the old behavior was an artefact of silently copying the memoryview to bytes. You never used it *directly*.
    But, yes, it is a change in (undocumented) behavior :(

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 23, 2015

    to preserve compatibility:

    there is the memoryview.c_contiguous flag. Maybe we should just check it and if it is False fall back to the old copying behavior ?

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 23, 2015

    something like:

        def write(self,data):
            self._check_closed()
            if self.mode != WRITE:
                import errno
                raise OSError(errno.EBADF, "write() on read-only GzipFile object")
    
            if self.fileobj is None:
                raise ValueError("write() on closed GzipFile object")
    
            if isinstance(data, bytes):
                length = len(data)
            elif isinstance(data, memoryview) and not data.c_contiguous:
                data = data.tobytes()
                length = len(data)
            else:
                # accept any data that supports the buffer protocol
                data = memoryview(data)
                length = data.nbytes
    
            if length > 0:
                self.fileobj.write(self.compress.compress(data))
                self.size += length
                self.crc = zlib.crc32(data, self.crc) & 0xffffffff
                self.offset += length
    
            return length

    @serhiy-storchaka
    Copy link
    Member

    Here is a patch that restores support on non-contiguous memoryviews.

    It would be better to drop support of non-contiguous data, because it worked
    only by accident. Needed support of only bytes-like memoryviews written by
    BufferedWriter.

    @skrah
    Copy link
    Mannequin

    skrah mannequin commented Mar 23, 2015

    In a sense, the old behavior was an artefact of silently copying the memoryview to bytes.

    It likely wasn't intentional, but tobytes() *is* used to serialize
    weird arrays to their C-contiguous representation (following the
    logical structure of the array rather than the physical one).

    Since the gzip docs don't help much, I guess the new behavior is
    probably okay.

    @skrah
    Copy link
    Mannequin

    skrah mannequin commented Mar 23, 2015

    I just see that non-contiguous arrays didn't work in 2.7 either,
    so that was probably the original intention.

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 23, 2015

    Serhiy:

    I think I saw that you committed this also to the 2.7 branch, but that would not work since memoryviews do not have the nbytes attribute (they do not seem to have cast either). One would have to calculate the length instead from other properties.
    Tests would fail too I think.

    If I'm mistaken, then sorry for the noise.

    @serhiy-storchaka
    Copy link
    Member

    OK, so left it as is if nobody complains.

    @wm75
    Copy link
    Mannequin Author

    wm75 mannequin commented Mar 23, 2015

    I see now that it is just bpo-21560 that went into 2.7 and that's fine.
    As I said: sorry for the noise

    @serhiy-storchaka
    Copy link
    Member

    I think I saw that you committed this also to the 2.7 branch,

    I committed only working tests and a fix from bpo-21560.

    @ezio-melotti ezio-melotti transferred this issue from another repository Apr 10, 2022
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    performance Performance or resource usage stdlib Python modules in the Lib dir
    Projects
    None yet
    Development

    No branches or pull requests

    3 participants