Skip to content

Pyarrow metadata RuntimeError in to_parquet #7977

Open

Description

@jrbourbeau

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 close

cc @rjzamora in case you've seen this before or have an idea of what might be causing this

Activity

  1. mrocklin commented on Aug 6, 2021

    @mrocklin
    Member
  2. rjzamora commented on Aug 6, 2021

    @rjzamora
    Member

    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.

  3. mrocklin commented on Aug 6, 2021

    @mrocklin
    Member
  4. ian-r-rose commented on Aug 6, 2021

    @ian-r-rose
    Collaborator

    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.2
    distributed==2021.7.2
    pyarrow==5.0.0

  5. jorisvandenbossche commented on Aug 6, 2021

    @jorisvandenbossche
    Member

    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=False eliminate the error?

  6. mrocklin commented on Aug 6, 2021

    @mrocklin
    Member
  7. kinghuang commented on Aug 7, 2021

    @kinghuang

    I'm also running into this problem. Setting write_metadata_file=False doesn't eliminate the error.

  8. kinghuang commented on Aug 7, 2021

    @kinghuang

    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
    df = dd.read_parquet("s3://HIDDEN", columns=[
    	"detail_id",
    	"invoice_id",
    	"line_item_desc",
    	"vendor_service_code",
    	"vendor_service_category",
    	"buyer_id",
    	"supplier_id",
    	"invoice_date",
    	"approved_date",
    	"line_item_subtotal",
    	"line_item_tax_total",
    	"line_item_total",
    	"coding_total_usd",
    	"uom",
    	"unit_price",
    	"quantity",
    	"category_name",
    	"category_method",
    	"ft_category",
    	"ft_percentage",
    	"sql_category",
    	"sql_id",
    	"ft_rule_category",
    	"ft_rule_id",
    	"sql_rule_category",
    	"sql_rule_id",
    	"year",
    	"month",
    ], filters=[[("year", "=", "2018"), ("month", "=", "3")]])
    df = df.drop_duplicates(subset=["detail_id"])
    df = df.repartition(npartitions=12, force=True)
    df = df.set_index("detail_id")
    df.to_parquet("s3://HIDDEN", partition_on=["year", "month"], write_metadata_file=False)
    
    
    Error traceback
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/local/lib/python3.8/site-packages/dask/dataframe/core.py", line 4389, in to_parquet
        return to_parquet(self, path, *args, **kwargs)
      File "/usr/local/lib/python3.8/site-packages/dask/dataframe/io/parquet/core.py", line 653, in to_parquet
        out = out.compute(**compute_kwargs)
      File "/usr/local/lib/python3.8/site-packages/dask/base.py", line 286, in compute
        (result,) = compute(self, traverse=False, **kwargs)
      File "/usr/local/lib/python3.8/site-packages/dask/base.py", line 568, in compute
        results = schedule(dsk, keys, **kwargs)
      File "/usr/local/lib/python3.8/site-packages/distributed/client.py", line 2704, in get
        results = self.gather(packed, asynchronous=asynchronous, direct=direct)
      File "/usr/local/lib/python3.8/site-packages/distributed/client.py", line 2018, in gather
        return self.sync(
      File "/usr/local/lib/python3.8/site-packages/distributed/client.py", line 859, in sync
        return sync(
      File "/usr/local/lib/python3.8/site-packages/distributed/utils.py", line 326, in sync
        raise exc.with_traceback(tb)
      File "/usr/local/lib/python3.8/site-packages/distributed/utils.py", line 309, in f
        result[0] = yield future
      File "/usr/local/lib/python3.8/site-packages/tornado/gen.py", line 762, in run
        value = future.result()
      File "/usr/local/lib/python3.8/site-packages/distributed/client.py", line 1883, in _gather
        raise exception.with_traceback(traceback)
      File "/usr/local/lib/python3.8/site-packages/dask/dataframe/io/parquet/arrow.py", line 869, in write_partition
        md_list = _write_partitioned(
      File "/usr/local/lib/python3.8/site-packages/dask/dataframe/io/parquet/arrow.py", line 119, in _write_partitioned
        pq.write_table(subtable, f, metadata_collector=md_list, **kwargs)
      File "/usr/local/lib/python3.8/site-packages/pyarrow/parquet.py", line 1817, in write_table
        writer.write_table(table, row_group_size=row_group_size)
      File "/usr/local/lib/python3.8/site-packages/pyarrow/parquet.py", line 662, in __exit__
        self.close()
      File "/usr/local/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 close
    
    pip list
    Package                Version
    ---------------------- -----------
    aiobotocore            1.3.3
    aiohttp                3.7.4.post0
    aioitertools           0.7.1
    alembic                1.6.5
    async-timeout          3.0.1
    attrs                  21.2.0
    blis                   0.7.4
    bokeh                  2.3.3
    boto3                  1.17.106
    botocore               1.20.106
    catalogue              2.0.4
    certifi                2021.5.30
    chardet                3.0.4
    charset-normalizer     2.0.1
    click                  7.1.2
    cloudpickle            1.6.0
    coloredlogs            14.0
    croniter               1.0.15
    cymem                  2.0.5
    dagster                0.12.1
    dagster-aws            0.12.1
    dagster-dask           0.12.1
    dagster-postgres       0.12.1
    dask                   2021.7.0
    dask-cloudprovider     2021.6.0
    distributed            2021.7.0
    docstring-parser       0.7.1
    fsspec                 2021.7.0
    future                 0.18.2
    greenlet               1.1.0
    grpcio                 1.38.1
    grpcio-health-checking 1.38.1
    HeapDict               1.0.1
    humanfriendly          9.2
    idna                   3.2
    Jinja2                 2.11.3
    jmespath               0.10.0
    joblib                 1.0.1
    locket                 0.2.1
    Mako                   1.1.4
    MarkupSafe             2.0.1
    msgpack                1.0.2
    multidict              5.1.0
    murmurhash             1.0.5
    nltk                   3.6.2
    numpy                  1.21.0
    packaging              21.0
    pandas                 1.3.0
    partd                  1.2.0
    pathy                  0.6.0
    pendulum               2.1.2
    Pillow                 8.3.1
    pip                    21.1.3
    preshed                3.0.5
    protobuf               3.17.3
    psutil                 5.8.0
    psycopg2-binary        2.8.6
    pyarrow                4.0.1
    pydantic               1.8.2
    pyenchant              3.2.1
    pyparsing              2.4.7
    python-dateutil        2.8.2
    python-editor          1.0.4
    pytz                   2021.1
    pytzdata               2020.1
    PyYAML                 5.4.1
    regex                  2021.7.6
    requests               2.26.0
    Rx                     1.6.1
    s3fs                   0.4.2
    s3transfer             0.4.2
    setuptools             57.0.0
    six                    1.16.0
    smart-open             5.1.0
    sortedcontainers       2.4.0
    spacy                  3.1.1
    spacy-legacy           3.0.8
    SQLAlchemy             1.4.21
    srsly                  2.4.1
    tabulate               0.8.9
    tblib                  1.7.0
    thinc                  8.0.8
    toolz                  0.11.1
    toposort               1.6
    tornado                6.1
    tqdm                   4.61.2
    typer                  0.3.2
    typing-compat          0.1.0
    typing-extensions      3.10.0.0
    urllib3                1.26.6
    wasabi                 0.8.2
    watchdog               2.1.3
    wheel                  0.36.2
    wordninja              2.0.0
    wrapt                  1.12.1
    yarl                   1.6.3
    zict                   2.0.0
    

    I have s3fs pinned to 0.4.2 due to #6782. Not sure if that has any impact here.

  9. rjzamora commented on Aug 7, 2021

    @rjzamora
    Member

    Does using write_metadata_file=False eliminate the error?

    I'm only getting this information second-hand, but my understanding is that
    no, this does not eliminate the error.

    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 the write_metadata_file=False-behavior on the Dask side.

  10. kinghuang commented on Aug 8, 2021

    @kinghuang

    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 RuntimeError went 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.

  11. jorisvandenbossche commented on Aug 9, 2021

    @jorisvandenbossche
    Member

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

  12. jorisvandenbossche commented on Aug 9, 2021

    @jorisvandenbossche
    Member

    I tried a small reproducer with a public S3 bucket for which I don't have write permissions:

    import pyarrow as pa
    import pyarrow.parquet as pq
    import s3fs
    
    table = pa.table({'a': [1, 2, 3]})
    fs = s3fs.S3FileSystem(anon=True)
    md_list = []
    
    with fs.open("ursa-labs-taxi-data/data.parquet", "wb") as f:
        with pq.ParquetWriter(f, table.schema, metadata_collector=md_list) as writer:
            writer.write_table(table)
            # small edit to the example, don't call metadata here, since we didn't yet close the writer this always error
            # meta = writer.writer.metadata

    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
    In [9]: with fs.open("ursa-labs-taxi-data/data.parquet", "wb") as f:
       ...:     with pq.ParquetWriter(f, table.schema) as writer:
       ...:         writer.write_table(table)
       ...:         meta = writer.writer.metadata
       ...: 
    ---------------------------------------------------------------------------
    RuntimeError                              Traceback (most recent call last)
    <ipython-input-9-60f024fa1700> in <module>
          3         writer.write_table(table)
    ----> 4         meta = writer.writer.metadata
          5 
    
    ~/scipy/repos/arrow/python/pyarrow/_parquet.pyx in pyarrow._parquet.ParquetWriter.metadata.__get__()
    
    RuntimeError: file metadata is only available after writer close
    
    During handling of the above exception, another exception occurred:
    
    ClientError                               Traceback (most recent call last)
    <ipython-input-9-60f024fa1700> in <module>
          2     with pq.ParquetWriter(f, table.schema) as writer:
          3         writer.write_table(table)
    ----> 4         meta = writer.writer.metadata
          5 
    
    ~/miniconda3/envs/arrow-dev/lib/python3.8/site-packages/fsspec/spec.py in __exit__(self, *args)
       1600 
       1601     def __exit__(self, *args):
    -> 1602         self.close()
    
    ~/miniconda3/envs/arrow-dev/lib/python3.8/site-packages/fsspec/spec.py in close(self)
       1567         else:
       1568             if not self.forced:
    -> 1569                 self.flush(force=True)
       1570 
       1571             if self.fs is not None:
    
    ~/miniconda3/envs/arrow-dev/lib/python3.8/site-packages/fsspec/spec.py in flush(self, force)
       1438                 raise
       1439 
    -> 1440         if self._upload_chunk(final=force) is not False:
       1441             self.offset += self.buffer.seek(0, 2)
       1442             self.buffer = io.BytesIO()
    
    ~/miniconda3/envs/arrow-dev/lib/python3.8/site-packages/s3fs/core.py in _upload_chunk(self, final)
       1250 
       1251         if self.autocommit and final:
    -> 1252             self.commit()
       1253         return not final
       1254 
    
    ~/miniconda3/envs/arrow-dev/lib/python3.8/site-packages/s3fs/core.py in commit(self)
       1265                 self.buffer.seek(0)
       1266                 data = self.buffer.read()
    -> 1267                 write_result = self._call_s3(
       1268                     self.fs.s3.put_object,
       1269                     Key=self.key, Bucket=self.bucket, Body=data, **self.kwargs
    
    ~/miniconda3/envs/arrow-dev/lib/python3.8/site-packages/s3fs/core.py in _call_s3(self, method, *kwarglist, **kwargs)
       1128 
       1129     def _call_s3(self, method, *kwarglist, **kwargs):
    -> 1130         return self.fs._call_s3(method, self.s3_additional_kwargs, *kwarglist,
       1131                                 **kwargs)
       1132 
    
    ~/miniconda3/envs/arrow-dev/lib/python3.8/site-packages/s3fs/core.py in _call_s3(self, method, *akwarglist, **kwargs)
        198         additional_kwargs = self._get_s3_method_kwargs(method, *akwarglist,
        199                                                        **kwargs)
    --> 200         return method(**additional_kwargs)
        201 
        202     def _get_s3_method_kwargs(self, method, *akwarglist, **kwargs):
    
    ~/miniconda3/envs/arrow-dev/lib/python3.8/site-packages/botocore/client.py in _api_call(self, *args, **kwargs)
        355                     "%s() only accepts keyword arguments." % py_operation_name)
        356             # The "self" in this scope is referring to the BaseClient.
    --> 357             return self._make_api_call(operation_name, kwargs)
        358 
        359         _api_call.__name__ = str(py_operation_name)
    
    ~/miniconda3/envs/arrow-dev/lib/python3.8/site-packages/botocore/client.py in _make_api_call(self, operation_name, api_params)
        674             error_code = parsed_response.get("Error", {}).get("Code")
        675             error_class = self.exceptions.from_code(error_code)
    --> 676             raise error_class(parsed_response, operation_name)
        677         else:
        678             return parsed_response
    
    ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
    

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

  13. 1 remaining item

  14. kinghuang commented on Aug 9, 2021

    @kinghuang

    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's AbstractBufferedFile context 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 an AccessDenied occurred on the PutObject operation. So the metadata is being accessed in the close() 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.

  15. kinghuang commented on Aug 9, 2021

    @kinghuang

    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 the close() method to only clean up and not attempt to collect metadata when an exception is raised.

  16. jorisvandenbossche commented on Aug 10, 2021

    @jorisvandenbossche
    Member

    I think it needs to tell the close() method to only clean up and not attempt to collect metadata when an exception is raised.

    Something like the following?

    --- a/python/pyarrow/parquet.py
    +++ b/python/pyarrow/parquet.py
    @@ -675,7 +675,7 @@ schema : arrow Schema
             return self
     
         def __exit__(self, *args, **kwargs):
    -        self.close()
    +        self.close(successful=args[0] is None)
             # return false since we want to propagate exceptions
             return False
     
    @@ -692,11 +692,11 @@ schema : arrow Schema
     
             self.writer.write_table(table, row_group_size=row_group_size)
     
    -    def close(self):
    +    def close(self, successful=True):
             if self.is_open:
                 self.writer.close()
                 self.is_open = False
    -            if self._metadata_collector is not None:
    +            if self._metadata_collector is not None and successful:
                     self._metadata_collector.append(self.writer.metadata)
             if self.file_handle is not None:
                 self.file_handle.close()

    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)

  17. kinghuang commented on Aug 10, 2021

    @kinghuang

    That looks reasonable. I'll monkeypatch a cluster with that change and see what happens.

  18. jrbourbeau commented on Aug 25, 2021

    @jrbourbeau
    MemberAuthor

    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 close error consistently. @kinghuang are you able to reproduce? Does Joris' patch help?

  19. jcrist commented on Mar 1, 2022

    @jcrist
    Member

    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?

  20. ian-r-rose commented on Mar 9, 2022

    @ian-r-rose
    Collaborator

    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.

  21. jorisvandenbossche commented on Apr 4, 2022

    @jorisvandenbossche
    Member

    @ian-r-rose were you able to get something reproducible?

  22. ian-r-rose commented on Apr 4, 2022

    @ian-r-rose
    Collaborator

    Unfortunately not, I thought I had it, and it went away again...

  23. ian-r-rose commented on Apr 28, 2022

    @ian-r-rose
    Collaborator

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

    dask==2022.4.1
    pandas==1.4.2
    pyarrow=7.0
    
    import pandas as pd
    import dask.dataframe as dd
    
    df = pd.DataFrame({"time": pd.date_range("2022-01-01", "2022-01-02", periods=500)})
    ddf = dd.from_pandas(df, chunksize=100)
    ddf.to_parquet(
        "tmp.parquet",
        engine="pyarrow",
        write_metadata_file=True,
        coerce_timestamps="us",
        allow_truncated_timestamps=False,
    )

    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 the ArrowInvalid error then makes its way to the user).

  24. self-assigned this
    on Apr 28, 2022
  25. ian-r-rose commented on May 17, 2022

    @ian-r-rose
    Collaborator

    Hi @jorisvandenbossche, any thoughts on whether we should apply your above patch?

  26. jorisvandenbossche commented on May 24, 2022

    @jorisvandenbossche
    Member

    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:

    import pandas as pd
    import pyarrow as pa
    import pyarrow.parquet as pq
    
    df = pd.DataFrame({"time": pd.date_range("2022-01-01", "2022-01-02", periods=500)})
    table = pa.table(df)
    
    metadata_collector = []
    
    with open("test_invalid.parquet", "wb") as fil:
        pq.write_table(table, fil, coerce_timestamps="us", allow_truncated_timestamps=False, metadata_collector=metadata_collector)
    

    (I get the correct error about "Casting from timestamp[ns] to timestamp[us] would lose data", and the metadata_collector actually 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.

  27. jonashaag commented on Feb 3, 2024

    @jonashaag

    I can reproduce this with PyArrow 14.0.2 alone (no Dask involved)

  28. added
    needs attention
    on Sep 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

dataframeioneeds attentionparquet

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions