Repository navigation
Open
Labels
dataframeioneeds attentionIt's been a while since this was pushed on. Needs attention from the owner or a maintainer.parquet
Description
Offline a user reported getting RuntimeError: file metadata is only available after writer close when writing a Dask DataFrame to parquet with our pyarrow engine. The traceback they were presented with was:
Traceback (most recent call last):
File "example.py", line 349, in <module>
main(date_dict, example_conf)
File "example.py", line 338, in main
make_example_datasets(
File "example.py", line 311, in make_example_datasets
default_to_parquet(sub_ddf, v["path"], engine="pyarrow", overwrite=True)
File "example.py", line 232, in default_to_parquet
ddf.to_parquet(path=path, engine=engine, overwrite=overwrite, write_metadata_file=False)
File "/opt/conda/lib/python3.8/site-packages/dask/dataframe/core.py", line 4453, in to_parquet
return to_parquet(self, path, *args, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/dask/dataframe/io/parquet/core.py", line 721, in to_parquet
out = out.compute(**compute_kwargs)
File "/opt/conda/lib/python3.8/site-packages/dask/base.py", line 286, in compute
(result,) = compute(self, traverse=False, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/dask/base.py", line 568, in compute
results = schedule(dsk, keys, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/distributed/client.py", line 2743, in get
results = self.gather(packed, asynchronous=asynchronous, direct=direct)
File "/opt/conda/lib/python3.8/site-packages/distributed/client.py", line 2020, in gather
return self.sync(
File "/opt/conda/lib/python3.8/site-packages/distributed/client.py", line 861, in sync
return sync(
File "/opt/conda/lib/python3.8/site-packages/distributed/utils.py", line 326, in sync
raise exc.with_traceback(tb)
File "/opt/conda/lib/python3.8/site-packages/distributed/utils.py", line 309, in f
result[0] = yield future
File "/opt/conda/lib/python3.8/site-packages/tornado/gen.py", line 762, in run
value = future.result()
File "/opt/conda/lib/python3.8/site-packages/distributed/client.py", line 1885, in _gather
raise exception.with_traceback(traceback)
File "/opt/conda/lib/python3.8/site-packages/dask/dataframe/io/parquet/arrow.py", line 947, in write_partition
pq.write_table(
File "/opt/conda/lib/python3.8/site-packages/pyarrow/parquet.py", line 1817, in write_table
writer.write_table(table, row_group_size=row_group_size)
File "/opt/conda/lib/python3.8/site-packages/pyarrow/parquet.py", line 662, in __exit__
self.close()
File "/opt/conda/lib/python3.8/site-packages/pyarrow/parquet.py", line 684, in close
self._metadata_collector.append(self.writer.metadata)
File "pyarrow/_parquet.pyx", line 1434, in pyarrow._parquet.ParquetWriter.metadata.__get__
RuntimeError: file metadata is only available after writer closecc @rjzamora in case you've seen this before or have an idea of what might be causing this
Reacted by King Chung Huang
Metadata
Metadata
Assignees
Labels
dataframeioneeds attentionIt's been a while since this was pushed on. Needs attention from the owner or a maintainer.parquet
Activity
mrocklin commentedon Aug 6, 2021
cc also @jorisvandenbossche
rjzamora commentedon Aug 6, 2021
Any other information about the case that is failing here (e.g. pyarrow version, dask version, data properties)? I cannot reproduce with the first few simple examples I tried.
mrocklin commentedon Aug 6, 2021
cc @ian-r-rose
ian-r-rose commentedon Aug 6, 2021
I've seen this, but only on large dataframes (hundreds of millions of rows, hundreds of columns, and thousands of partitions). I'll see if I can come up with a public reproducer, but the versions I was using are:
dask==2021.7.2distributed==2021.7.2pyarrow==5.0.0jorisvandenbossche commentedon Aug 6, 2021
The error comes from here while "closing" the ParquetWriter: https://github.com/apache/arrow/blob/227a718efc6dbf57b0cec41a9b8cc432cd849566/python/pyarrow/parquet.py#L697-L700, which accesses the metadata after having closed the file. The metadata property is defined here: https://github.com/apache/arrow/blob/227a718efc6dbf57b0cec41a9b8cc432cd849566/python/pyarrow/_parquet.pyx#L1443-L1454. So it seems that the error might also mask anything that went wrong with creating the metadata.
Does using
write_metadata_file=Falseeliminate the error?mrocklin commentedon Aug 6, 2021
kinghuang commentedon Aug 7, 2021
I'm also running into this problem. Setting
write_metadata_file=Falsedoesn't eliminate the error.kinghuang commentedon Aug 7, 2021
Here's some details for my case. The dataframe to be written has 3.5 million rows, 27 columns, and 12 partitions. Source and destination are on S3. The Dask cluster is running on ECS.
Main part of the code
Error traceback
pip list
I have
s3fspinned to0.4.2due to #6782. Not sure if that has any impact here.rjzamora commentedon Aug 7, 2021
It looks like we are always collecting the metadata from pyarrow (even when
write_metadata_file=False). I'd like to know what is causing the problem in pyarrow, but it should be easy to change thewrite_metadata_file=False-behavior on the Dask side.kinghuang commentedon Aug 8, 2021
I've been able to find the underlying cause of the error for my case! The Dask workers lacked permissions to put objects to the target S3 bucket. The
RuntimeErrorwent away once that was corrected.I'm guessing there's an underlying error being gobbled up in PyArrow when it's writing a table. The metadata thing is likely a red herring.
jorisvandenbossche commentedon Aug 9, 2021
Ah, good catch! That aligns with my observation from above (#7977 (comment)) that the current code in pyarrow might mask any other error that prevented the metadata file from being created.
Although with lacking write permissions, I would have expected that it would only error when writing it and not yet when creating the metadata object in the attribute.
When trying to reproduce this locally (with a local filesystem with a read-only directory), the
pq.write_table(subtable, f, metadata_collector=md_list, **kwargs)already fails when creatingf(with fs.open(.., "wb") as f)), so you never get to the metadata error. But maybe with s3fs, depending on your authentication, it only gives a permission error when closing the OpenFile context?(having a reproducer would help to check if we can improve this error message on the pyarrow side)
jorisvandenbossche commentedon Aug 9, 2021
I tried a small reproducer with a public S3 bucket for which I don't have write permissions:
for the latest s3fs that gives a "PermissionError: Access Denied" / "ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied".
But trying the older s3fs 0.4.2 as you listed, I see the RuntimeError as well (although also AccessDenied).
Full traceback
@kinghuang could you try with a more recent version of s3fs to see if that gives a more informative error message? You mentioned #6782 as a reason to have pinned s3fs to 0.4.2, but I think those issues should be resolved in the latest versions of s3fs / fsspec / pyarrow.
1 remaining item
kinghuang commentedon Aug 9, 2021
I suspect the problem lies in one of the context managers, though I'm not sure if it's the file's context manager or the
ParquetWriter's context manager. fsspec'sAbstractBufferedFilecontext manager doesn't consider whether an exception was thrown. PyArrow's ParquetWriter context manager explicitly propagates.Overall, this means that
ParquetWriter.close()is being called without considering that anAccessDeniedoccurred on thePutObjectoperation. So the metadata is being accessed in theclose()even though the write didn't succeed in the first place.The documentation for
object.__exit__describes how the exception is passed if the context was exited because of an exception, which is processed after the exit completes if it returns a non-true value.kinghuang commentedon Aug 9, 2021
Looking at it some more, I'm pretty sure it's the PyArrow ParquetWriter context manager that needs to explicitly consider whether an exception was thrown in
__exit__(), in addition to propagating it. I think it needs to tell theclose()method to only clean up and not attempt to collect metadata when an exception is raised.jorisvandenbossche commentedon Aug 10, 2021
Something like the following?
I still can't reproduce it locally (so difficult to check the above patch). With my small test (with a read-only bucket and anonymous access, this might certainly be different), the Permission error only happens after the closing of the ParquetWriter context (ParquetWriter itself doesn't error, and thus can also access the metadata fine, it's only the closing of the s3fs open context that gives a PermissionError)
kinghuang commentedon Aug 10, 2021
That looks reasonable. I'll monkeypatch a cluster with that change and see what happens.
jrbourbeau commentedon Aug 25, 2021
Thanks for working through things here @kinghuang @jorisvandenbossche. I tried but am not able to reproduce the
RuntimeError: file metadata is only available after writer closeerror consistently. @kinghuang are you able to reproduce? Does Joris' patch help?jcrist commentedon Mar 1, 2022
Just checking in here, @kinghuang were you able to retest with Joris's patch? Was any work ever done upstream in pyarrow to resolve this?
ian-r-rose commentedon Mar 9, 2022
I ran into this again today -- not sure if I'll be able to reproduce it reliably, but if I can I'll try the above patch.
jorisvandenbossche commentedon Apr 4, 2022
@ian-r-rose were you able to get something reproducible?
ian-r-rose commentedon Apr 4, 2022
Unfortunately not, I thought I had it, and it went away again...
ian-r-rose commentedon Apr 28, 2022
Okay, I finally have a snippet that reproduces the above error, though I have no idea how close it is to the original error. The trick is to create an invalid arrow dataset (in this case by not allowing timestamp coercion):
Produces:
Traceback
--------------------------------------------------------------------------- ArrowInvalid Traceback (most recent call last) ~/miniconda3/envs/dask/lib/python3.8/site-packages/pyarrow/parquet.py in write_table(table, where, row_group_size, version, use_dictionary, compression, write_statistics, use_deprecated_int96_timestamps, coerce_timestamps, allow_truncated_timestamps, data_page_size, flavor, filesystem, compression_level, use_byte_stream_split, column_encoding, data_page_version, use_compliant_nested_type, **kwargs) 2091 **kwargs) as writer: -> 2092 writer.write_table(table, row_group_size=row_group_size) 2093 except Exception: ~/miniconda3/envs/dask/lib/python3.8/site-packages/pyarrow/parquet.py in write_table(self, table, row_group_size) 753 --> 754 self.writer.write_table(table, row_group_size=row_group_size) 755 ~/miniconda3/envs/dask/lib/python3.8/site-packages/pyarrow/_parquet.pyx in pyarrow._parquet.ParquetWriter.write_table() ~/miniconda3/envs/dask/lib/python3.8/site-packages/pyarrow/error.pxi in pyarrow.lib.check_status() ArrowInvalid: Casting from timestamp[ns] to timestamp[us] would lose data: 1641064458517034068 During handling of the above exception, another exception occurred: RuntimeError Traceback (most recent call last) /tmp/ipykernel_768746/3301203153.py in <module> 4 df = pd.DataFrame({"time": pd.date_range("2022-01-01", "2022-01-02", periods=500)}) 5 ddf = dd.from_pandas(df, chunksize=100) ----> 6 ddf.to_parquet( 7 "tmp.parquet", 8 engine="pyarrow", ~/dask/dask/dask/dataframe/core.py in to_parquet(self, path, *args, **kwargs) 4988 from dask.dataframe.io import to_parquet 4989 -> 4990 return to_parquet(self, path, *args, **kwargs) 4991 4992 def to_orc(self, path, *args, **kwargs): ~/dask/dask/dask/dataframe/io/parquet/core.py in to_parquet(df, path, engine, compression, write_index, append, overwrite, ignore_divisions, partition_on, storage_options, custom_metadata, write_metadata_file, compute, compute_kwargs, schema, name_function, **kwargs) 884 885 if compute: --> 886 out = out.compute(**compute_kwargs) 887 888 # Invalidate the filesystem listing cache for the output path after write. ~/dask/dask/dask/base.py in compute(self, **kwargs) 290 dask.base.compute 291 """ --> 292 (result,) = compute(self, traverse=False, **kwargs) 293 return result 294 ~/dask/dask/dask/base.py in compute(traverse, optimize_graph, scheduler, get, *args, **kwargs) 573 postcomputes.append(x.__dask_postcompute__()) 574 --> 575 results = schedule(dsk, keys, **kwargs) 576 return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)]) 577 ~/dask/dask/dask/threaded.py in get(dsk, result, cache, num_workers, pool, **kwargs) 79 pool = MultiprocessingPoolExecutor(pool) 80 ---> 81 results = get_async( 82 pool.submit, 83 pool._max_workers, ~/dask/dask/dask/local.py in get_async(submit, num_workers, dsk, result, cache, get_id, rerun_exceptions_locally, pack_exception, raise_exception, callbacks, dumps, loads, chunksize, **kwargs) 506 _execute_task(task, data) # Re-execute locally 507 else: --> 508 raise_exception(exc, tb) 509 res, worker_id = loads(res_info) 510 state["cache"][key] = res ~/dask/dask/dask/local.py in reraise(exc, tb) 314 if exc.__traceback__ is not tb: 315 raise exc.with_traceback(tb) --> 316 raise exc 317 318 ~/dask/dask/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception) 219 try: 220 task, data = loads(task_info) --> 221 result = _execute_task(task, data) 222 id = get_id() 223 result = dumps((result, id)) ~/dask/dask/dask/core.py in _execute_task(arg, cache, dsk) 117 # temporaries by their reference count and can execute certain 118 # operations in-place. --> 119 return func(*(_execute_task(a, cache) for a in args)) 120 elif not ishashable(arg): 121 return arg ~/dask/dask/dask/optimization.py in __call__(self, *args) 988 if not len(args) == len(self.inkeys): 989 raise ValueError("Expected %d args, got %d" % (len(self.inkeys), len(args))) --> 990 return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args))) 991 992 def __reduce__(self): ~/dask/dask/dask/core.py in get(dsk, out, cache) 147 for key in toposort(dsk): 148 task = dsk[key] --> 149 result = _execute_task(task, cache) 150 cache[key] = result 151 result = _execute_task(out, cache) ~/dask/dask/dask/core.py in _execute_task(arg, cache, dsk) 117 # temporaries by their reference count and can execute certain 118 # operations in-place. --> 119 return func(*(_execute_task(a, cache) for a in args)) 120 elif not ishashable(arg): 121 return arg ~/dask/dask/dask/dataframe/io/parquet/core.py in __call__(self, df, block_index) 148 149 # Write out data --> 150 return self.engine.write_partition( 151 df, 152 self.path, ~/dask/dask/dask/dataframe/io/parquet/arrow.py in write_partition(cls, df, path, fs, filename, partition_on, return_metadata, fmd, compression, index_cols, schema, head, custom_metadata, **kwargs) 706 md_list = [] 707 with fs.open(fs.sep.join([path, filename]), "wb") as fil: --> 708 pq.write_table( 709 t, 710 fil, ~/miniconda3/envs/dask/lib/python3.8/site-packages/pyarrow/parquet.py in write_table(table, where, row_group_size, version, use_dictionary, compression, write_statistics, use_deprecated_int96_timestamps, coerce_timestamps, allow_truncated_timestamps, data_page_size, flavor, filesystem, compression_level, use_byte_stream_split, column_encoding, data_page_version, use_compliant_nested_type, **kwargs) 2090 use_compliant_nested_type=use_compliant_nested_type, 2091 **kwargs) as writer: -> 2092 writer.write_table(table, row_group_size=row_group_size) 2093 except Exception: 2094 if _is_path_like(where): ~/miniconda3/envs/dask/lib/python3.8/site-packages/pyarrow/parquet.py in __exit__(self, *args, **kwargs) 692 693 def __exit__(self, *args, **kwargs): --> 694 self.close(successful=args[0] is None) 695 # return false since we want to propagate exceptions 696 return False ~/miniconda3/envs/dask/lib/python3.8/site-packages/pyarrow/parquet.py in close(self, successful) 759 self.is_open = False 760 if self._metadata_collector is not None: # and successful: --> 761 self._metadata_collector.append(self.writer.metadata) 762 if self.file_handle is not None: 763 self.file_handle.close() ~/miniconda3/envs/dask/lib/python3.8/site-packages/pyarrow/_parquet.pyx in pyarrow._parquet.ParquetWriter.metadata.__get__() RuntimeError: file metadata is only available after writer close@jorisvandenbossche I can confirm that your patch above does fix the
RuntimeError(though of course theArrowInvaliderror then makes its way to the user).ian-r-rose commentedon May 17, 2022
Hi @jorisvandenbossche, any thoughts on whether we should apply your above patch?
jorisvandenbossche commentedon May 24, 2022
Thanks for the reproducer! I can reproduce it with the above dask example, but if I try to extract the relevant pyarrow example, I don't see the failure:
(I get the correct error about "Casting from timestamp[ns] to timestamp[us] would lose data", and the
metadata_collectoractually gets filled with a FileMetaData object)Would the fact that it is executed in threads when using dask influence it somehow?
So if it fixes the error for you, we can certainly apply the patch. But it would be nice to have a reproducer for our own test suite as well that doesn't rely on dask.
jonashaag commentedon Feb 3, 2024
I can reproduce this with PyArrow 14.0.2 alone (no Dask involved)