Skip to content

XML parsing error when trying to delete lots of objects on s3 #484

Closed

Description

@d-v-b

When I open a zarr-like array on s3 with w mode (i.e., I want to delete the original objects), I occasionally get an xml parsing error:

Long traceback --------------------------------------------------------------------------- ParseError Traceback (most recent call last) ~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/botocore/parsers.py in _parse_xml_string_to_dom(self, xml_string) 451 parser.feed(xml_string) --> 452 root = parser.close() 453 except XMLParseError as e:

ParseError: no element found: line 2, column 0

During handling of the above exception, another exception occurred:

ResponseParserError Traceback (most recent call last)
in
3 source_arrays = dict(source_group.arrays())
4 create_success = False
----> 5 target_group, target_arrays = initialize_group(dest_store_path,
6 source_group.path,
7 arrays=list(source_arrays.values()),

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/fibsem_tools/io/io.py in initialize_group(container_path, group_path, arrays, array_paths, chunks, group_attrs, compressor, array_attrs, mode, **kwargs)
295 ) -> Tuple[zarr.hierarchy.group, Tuple[zarr.core.Array]]:
296
--> 297 zgroup = access(
298 os.path.join(container_path, group_path), mode=mode, attrs=group_attrs, **kwargs
299 )

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/fibsem_tools/io/io.py in access(path, mode, **kwargs)
157
158 if is_container:
--> 159 return accessor(path_outer, path_inner, mode=mode, **kwargs)
160 else:
161 return accessor(path_outer, mode=mode, **kwargs)

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/fibsem_tools/io/zarr.py in access_n5(dir_path, container_path, **kwargs)
165 ) -> Any:
166 dir_path = N5FSStore(dir_path, **kwargs.get("storage_options", {}))
--> 167 return access_zarr(dir_path, container_path, **kwargs)
168
169

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/fibsem_tools/io/zarr.py in access_zarr(dir_path, container_path, **kwargs)
155 ):
156 delete_zbranch(tmp)
--> 157 array_or_group = zarr.open(dir_path, path=str(container_path), **kwargs)
158 if kwargs.get("mode") != "r" and len(attrs) > 1:
159 array_or_group.attrs.update(attrs)

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/zarr/convenience.py in open(store, mode, **kwargs)
84 return open_array(store, mode=mode, **kwargs)
85 else:
---> 86 return open_group(store, mode=mode, **kwargs)
87
88 elif mode == "a":

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/zarr/hierarchy.py in open_group(store, mode, cache_attrs, synchronizer, path, chunk_store, storage_options)
1169
1170 elif mode == 'w':
-> 1171 init_group(store, overwrite=True, path=path, chunk_store=chunk_store)
1172
1173 elif mode == 'a':

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/zarr/storage.py in init_group(store, overwrite, path, chunk_store)
486
487 # initialise metadata
--> 488 _init_group_metadata(store=store, overwrite=overwrite, path=path,
489 chunk_store=chunk_store)
490

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/zarr/storage.py in _init_group_metadata(store, overwrite, path, chunk_store)
500 if overwrite:
501 # attempt to delete any pre-existing items in store
--> 502 rmdir(store, path)
503 if chunk_store is not None:
504 rmdir(chunk_store, path)

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/zarr/storage.py in rmdir(store, path)
120 if hasattr(store, 'rmdir'):
121 # pass through
--> 122 store.rmdir(path)
123 else:
124 # slow version, delete one key at a time

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/fibsem_tools/io/storage.py in rmdir(self, path)
209 store_path = self.dir_path(path)
210 if self.fs.isdir(store_path):
--> 211 self.fs.rm(store_path, recursive=True)
212
213 def getsize(self, path=None):

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/fsspec/asyn.py in wrapper(*args, **kwargs)
70 def wrapper(*args, **kwargs):
71 self = obj or args[0]
---> 72 return sync(self.loop, func, *args, **kwargs)
73
74 return wrapper

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/fsspec/asyn.py in sync(loop, func, timeout, *args, **kwargs)
51 event.wait(timeout)
52 if isinstance(result[0], BaseException):
---> 53 raise result[0]
54 return result[0]
55

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/fsspec/asyn.py in _runner(event, coro, result, timeout)
18 coro = asyncio.wait_for(coro, timeout=timeout)
19 try:
---> 20 result[0] = await coro
21 except Exception as ex:
22 result[0] = ex

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/s3fs/core.py in _rm(self, path, recursive, **kwargs)
1508 dirs = [p for p in paths if not self.split_path(p)[1]]
1509 # TODO: fails if more than one bucket in list
-> 1510 await asyncio.gather(
1511 *[
1512 self._bulk_delete(files[i : i + 1000])

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/s3fs/core.py in _bulk_delete(self, pathlist, **kwargs)
1496 for path in pathlist:
1497 self.invalidate_cache(self._parent(path))
-> 1498 await self._call_s3("delete_objects", kwargs, Bucket=bucket, Delete=delete_keys)
1499
1500 async def _rm(self, path, recursive=False, **kwargs):

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/s3fs/core.py in _call_s3(self, method, *akwarglist, **kwargs)
250 except Exception as e:
251 err = e
--> 252 raise translate_boto_error(err)
253
254 call_s3 = sync_wrapper(_call_s3)

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/s3fs/core.py in _call_s3(self, method, *akwarglist, **kwargs)
231 for i in range(self.retries):
232 try:
--> 233 out = await method(**additional_kwargs)
234 return out
235 except S3_RETRYABLE_ERRORS as e:

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/aiobotocore/client.py in _make_api_call(self, operation_name, api_params)
138 http, parsed_response = event_response
139 else:
--> 140 http, parsed_response = await self._make_request(
141 operation_model, request_dict, request_context)
142

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/aiobotocore/client.py in _make_request(self, operation_model, request_dict, request_context)
158 async def _make_request(self, operation_model, request_dict, request_context):
159 try:
--> 160 return await self._endpoint.make_request(operation_model, request_dict)
161 except Exception as e:
162 await self.meta.events.emit(

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/aiobotocore/endpoint.py in _send_request(self, request_dict, operation_model)
85 request = await self.create_request(request_dict, operation_model)
86 context = request_dict['context']
---> 87 success_response, exception = await self._get_response(
88 request, operation_model, context)
89 while await self._needs_retry(attempts, operation_model,

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/aiobotocore/endpoint.py in _get_response(self, request, operation_model, context)
118 # If an exception occurs then the success_response is None.
119 # If no exception occurs then exception is None.
--> 120 success_response, exception = await self._do_get_response(
121 request, operation_model)
122 kwargs_to_emit = {

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/aiobotocore/endpoint.py in _do_get_response(self, request, operation_model)
178 protocol = operation_model.metadata['protocol']
179 parser = self._response_parser_factory.create_parser(protocol)
--> 180 parsed_response = parser.parse(
181 response_dict, operation_model.output_shape)
182 if http_response.status_code >= 300:

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/botocore/parsers.py in parse(self, response, shape)
243 parsed = self._do_error_parse(response, shape)
244 else:
--> 245 parsed = self._do_parse(response, shape)
246
247 # We don't want to decorate event stream responses with metadata

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/botocore/parsers.py in _do_parse(self, response, shape)
807 final_parsed['ResponseMetadata'] = self._populate_response_metadata(
808 response)
--> 809 self._add_modeled_parse(response, shape, final_parsed)
810 return final_parsed
811

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/botocore/parsers.py in _add_modeled_parse(self, response, shape, final_parsed)
816 self._parse_non_payload_attrs(response, shape,
817 member_shapes, final_parsed)
--> 818 self._parse_payload(response, shape, member_shapes, final_parsed)
819
820 def _do_modeled_error_parse(self, response, shape):

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/botocore/parsers.py in _parse_payload(self, response, shape, member_shapes, final_parsed)
856 body_shape, original_parsed)
857 else:
--> 858 original_parsed = self._initial_body_parse(response['body'])
859 body_parsed = self._parse_shape(shape, original_parsed)
860 final_parsed.update(body_parsed)

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/botocore/parsers.py in _initial_body_parse(self, xml_string)
942 if not xml_string:
943 return ETree.Element('')
--> 944 return self._parse_xml_string_to_dom(xml_string)
945
946 def _do_error_parse(self, response, shape):

~/miniconda3/envs/cosem-flows/lib/python3.8/site-packages/botocore/parsers.py in _parse_xml_string_to_dom(self, xml_string)
452 root = parser.close()
453 except XMLParseError as e:
--> 454 raise ResponseParserError(
455 "Unable to parse response (%s), "
456 "invalid XML received. Further retries may succeed:\n%s" %

ResponseParserError: Unable to parse response (no element found: line 2, column 0), invalid XML received. Further retries may succeed:
b'\n'

The TL;DR is that this operation: await self._call_s3("delete_objects", kwargs, Bucket=bucket, Delete=delete_keys) for a lot of objects (100k+) leads to this exception: ResponseParserError: Unable to parse response (no element found: line 2, column 0), invalid XML received. Further retries may succeed: b'<?xml version="1.0" encoding="UTF-8"?>\n'

My guess is that this is a side-effect of hitting some API request rate limit, but it seems like that phenomenon should manifest as something a little more explicit than an XML parsing error.

s3fs==2021.4.0 in case that matters

Activity

  1. ajkerrigan commented on Aug 25, 2021

    @ajkerrigan
    Collaborator

    I wonder if this issue is tangentially related to fsspec/filesystem_spec#690, or at least if the suggested mitigation there might avoid this issue also?

    I've seen some mentions of ResponseParserError issues in other repos, and it seems like in some cases it can come from intermediate/proxy servers generating non-XML (or truncated) responses when there's an error upstream. In any case, I can't think of a way for s3fs to avoid it aside from including ResponseParserError in S3_RETRYABLE_ERRORS which seems likely to do more harm than good. Catching and inspecting that error in your own code, and optionally retrying the deletion might be another option.

  2. martindurant commented on Aug 25, 2021

    @martindurant
    Member

    I do think we should probably deal with these, because if we catch errors and return them, we're probably keeping a lot of objects alive in memory, potentially with circular references in the tracebacks objects. This is going to be a problem across the stack! Probably a construct like

                except S3_RETRYABLE_ERRORS as e:
                    logger.debug("Retryable error: %s", e)
                    err = e
                    await asyncio.sleep(min(1.7 ** i * 0.1, 15))

    could always be handled better. But notice that in the aiobotocore case, this cometimes contains a coroutine that must be awaited, so it's complicated! For example, the following explicitly breaks the exception reference cycle

    --- a/s3fs/core.py
    +++ b/s3fs/core.py
    @@ -262,7 +262,8 @@ class S3FileSystem(AsyncFileSystem):
                     await tb.tb_frame.f_locals["response"]
                 except Exception as e:
                     err = e
    -        raise translate_boto_error(err)
    +        err = translate_boto_error(err)
    +        raise err

    Unfortunately, I never see these exceptions, so it's hard for me to instrument which of these ideas really makes a difference!

  3. martindurant commented on Sep 24, 2021

    @martindurant
    Member

    ping: do you intend to chase this or try my suggestion, @d-v-b ?

  4. d-v-b commented on Sep 24, 2021

    @d-v-b
    Author

    I wasn't planning on it, since I don't think I understand your proposed fix at all :)

  5. martindurant commented on Sep 24, 2021

    @martindurant
    Member

    Maybe the simpler fix, is making use of asyn._run_coros_in_chunks in rm as put and get already do.

  6. ian-r-rose commented on Apr 29, 2022

    @ian-r-rose
    Contributor

    I've been investigating rate-limiting behavior with s3, and have come up with a pretty reliable reproducer for this. It does seem to be related to rate-limiting: there tend to be a lot of concurrent errors in the other delete_object() that ask me to SlowDown. But sometimes the errors response sent by AWS is invalid XML, in that it only has a header element.

    My reproducer clearly isn't perfect, since it relies on a non-public image and s3 bucket, but I think it's still decent. I'm using coiled and dask to create a large number of small files (~180K), but that's not actually the important part: the error all happens on the client side:

    from dask.distributed import Client
    import distributed
    import dask.dataframe as dd
    import coiled
    import s3fs
    
    cluster=coiled.Cluster(
        name="rate-limit",
        software="ian-r-rose/parquet",   # pretty standard dask + s3fs image
        n_workers=100,
        worker_vm_types=["t3.medium"],
        scheduler_vm_types=["t3.medium"],
    )
    client = distributed.Client(cluster)
    
    df.to_parquet(
        "s3://dask-io/ian-many-partitions.parquet",
        engine="pyarrow-dataset",
        overwrite=True,
        write_metadata_file=False,
        compute=False,
        compression="snappy",
    ).compute()
    
    # And here we run into troubles
    fs = s3fs.S3FileSystem()
    fs.rm("s3://dask-io/ian-many-partitions.parquet", recursive=True)

    s3fs == 0.8.1
    dask == 2022.4.1
    distributed == 2022.4.1

  7. martindurant commented on Apr 29, 2022

    @martindurant
    Member

    Thanks for the reporducer, @ian-r-rose

    So do you think it would be enough to add this XML decode error to the list of retriable ones, since those retries have an exponential backoff policy? Did you try my suggestion of batching coroutines?

  8. ian-r-rose commented on Apr 29, 2022

    @ian-r-rose
    Contributor

    So do you think it would be enough to add this XML decode error to the list of retriable ones, since those retries have an exponential backoff policy?

    It might be, I can give this a shot. I suppose there is a chance for false positives there, but it's probably not too harmful.

    Did you try my suggestion of batching coroutines?

    Yes, I was actually about to submit a PR with my own hand-rolled proposal for batching them when I saw this issue. I'm not certain if _run_coros_in_chunks exactly fits my needs. I'll open it for discussion now.

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