Skip to content

Inconsistent Schema with partitioned pyarrow files #4194

Closed

Description

@c-thiel

When writing partitoned Datasets to parquet files, and it so happens that there are is a partition where one column has no values, inconsistent schemas are written to the parquet file so that reading is prevented later:

import dask as da
import dask.dataframe as dd
import pandas as pd
import numpy as np
import os
import shutil

PATH_DASK = '/tmp/dask.pa'

if os.path.exists(PATH_DASK):
    shutil.rmtree(PATH_DASK)

arrays = np.array([np.array([0, 1, 2]), np.array([3, 4]), np.nan, np.nan])
strings = np.array(['a', 'b', np.nan, np.nan])

df = pd.DataFrame([0, 0, 1, 1], columns=['partition_column'])
df['arrays'] = pd.Series(arrays)
df['strings'] = pd.Series(strings)

da_df = dd.from_pandas(df, npartitions=2)
da_df.to_parquet(PATH_DASK, partition_on=['partition_column'])
dd.read_parquet(PATH_DASK)

Fails with:

ValueError: Schema in partition[partition_column=1] /tmp/dask.pa/partition_column=1/4cd3552267d84d66a5ec8764f869a13b.parquet was different. 
arrays: null
strings: string
__index_level_0__: int64
metadata
--------
...

vs

arrays: list<item: int64>
  child 0, item: int64
strings: string
__index_level_0__: int64
metadata
--------

I found #3454 relating to https://issues.apache.org/jira/browse/ARROW-2860. However the Pyarrow Issue only relates to reading files with different schemas. However Pyarrow in it self doesn't even suffer this Bug, as Pyarrow itself would't even write those different schemas in the first place:

import pyarrow as pa
import pyarrow.parquet as pq
import pandas as pd
import os
import shutil

PATH_PYARROW = '/tmp/pyarrow.pa'

if os.path.exists(PATH_PYARROW):
    shutil.rmtree(PATH_PYARROW)

arrays = np.array([np.array([0, 1, 2]), np.array([3, 4]), np.nan, np.nan])
strings = np.array([np.nan, np.nan, 'a', 'b'])

df = pd.DataFrame([0, 0, 1, 1], columns=['partition_column'])
df['arrays'] = pd.Series(arrays)
df['strings'] = pd.Series(strings)

table = pa.Table.from_pandas(df)

pq.write_to_dataset(table, root_path=PATH_PYARROW, partition_cols=['partition_column'])

dataset = pq.ParquetDataset(PATH_PYARROW)
df_read = dataset.read().to_pandas()
df_read

Works perfectly fine. Even reading the Pyarrow Files with Dask now works perfectly fine:
dd.read_parquet(PATH_PYARROW).compute()

This is simply due to the reason that Pyarrow still uses the same schema accross partitions even if ther is missing data:

import os
files = [val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk(PATH_PYARROW)] for val in sublist]
for file in files:
    dataset_part = pq.ParquetDataset(file)    
    print(file)
    print(dataset_part.schema)
    print(dataset_part.read().to_pandas())

Outputs:

/tmp/pyarrow.pa/partition_column=0/f32bf0bfedcc4312829e7c4371e544e6.parquet
<pyarrow._parquet.ParquetSchema object at 0x7fdd1c103eb8>
arrays.list.item: INT64
strings: BYTE_ARRAY UTF8
__index_level_0__: INT64
 
      arrays strings
0  [0, 1, 2]     nan
1     [3, 4]     nan
/tmp/pyarrow.pa/partition_column=1/044dd125e0b5472db23bff9a954a1bff.parquet
<pyarrow._parquet.ParquetSchema object at 0x7fdd1c1034e0>
arrays.list.item: INT64
strings: BYTE_ARRAY UTF8
__index_level_0__: INT64
 
  arrays strings
2   None       a
3   None       b

So summing it up: In Pyarrow the pyarrow.parquet.write_to_dataset wrapper around pyarrow.parquet.write_table takes care that the schema in individual files doesn't get screwed up. Dask blindly uses pyarrow.parquet.write_table on each partition and hence ends up with a wrong schema.

This means that even if https://issues.apache.org/jira/browse/ARROW-2860 is fixed, loading of these wrong schemas might work, but they are still written wrongly to the file in the first place.

I believe that fixing this in dask is probably going to be hard but might still be worth a try. Maybe one simple but not ideal solution would be to to stick to the schema the first written partition produces and raise an error otherwise. At least we should make sure, that after all partitions are written to file, the schemas match. Otherwise people will save their files without an error raised and notice later on that opening is no longer possible.

Activity

  1. mrocklin commented on Nov 9, 2018

    @mrocklin
    Member

    cc @xhochy @pitrou thoughts on the best way to handle this?

  2. pitrou commented on Nov 9, 2018

    @pitrou
    Member

    I'm not a Parquet expert so it's hard to say for sure. Intuitively, I'd say all files in a Parquet partition had better have the same schema, but perhaps there's a specification somewhere that spells it out?

  3. pitrou commented on Nov 9, 2018

    @pitrou
    Member

    To answer a bit more concretely, ideally you may use the Array.cast method to homogenize datatypes accross columns.

    However, it doesn't support all types (yet?):

    >>> a = pa.array([None, None])                                                            
    >>> a                                                                                     
    <pyarrow.lib.NullArray object at 0x7fd924b7d228>
    2 nulls
    >>> a.cast(pa.int64())                                                                    
    <pyarrow.lib.Int64Array object at 0x7fd924af03b8>
    [
      null,
      null
    ]
    >>> a.cast(pa.list_(pa.int64()))                                                          
    Traceback (most recent call last):
      File "<ipython-input-4-a5483e3f21af>", line 1, in <module>
        a.cast(pa.list_(pa.int64()))
      File "pyarrow/array.pxi", line 413, in pyarrow.lib.Array.cast
      File "pyarrow/error.pxi", line 89, in pyarrow.lib.check_status
    ArrowNotImplementedError: No cast implemented from null to list<item: int64>
  4. martindurant commented on Nov 9, 2018

    @martindurant
    Member

    It is certainly much much better to have the same schema throughout. In some circumstances and some parquet frameworks, schema evolution is allowed, but that is not in the official spec.

  5. pitrou commented on Nov 9, 2018

    @pitrou
    Member

    That said, we could add such a facility in PyArrow. Homogenizing arrays may be needed for other purposes at some point. @wesm

  6. wesm commented on Nov 9, 2018

    @wesm
    Contributor

    We've already had several bug reports about this, here is one:

    https://issues.apache.org/jira/browse/ARROW-2860

    Here is my comment from 15th September

    There's other issues reported about this. We should handle schema normalization across components of a dataset. I don't have time to work on this for 0.11 but I hope that someone else can take a look soon

    In general, we need more help on Parquet support in Apache Arrow. I think this issue can be completely solved in Python code without touching any C++

  7. wesm commented on Nov 9, 2018

    @wesm
    Contributor

    That being said, we should probably implement concatenation with schema normalization in C++ so it doesn't have to be redone for R and Ruby. Ruby already has Parquet support and R is not far behind

  8. rafonseca commented on Feb 1, 2019

    @rafonseca

    I've just run into the same problem. I understand that I can use pyarrow.parquet.write_to_dataset as a workaround, right?
    But I would like to do it properly using dask API. Is someone working in this issue? Can I help?

  9. mmccarty commented on Mar 25, 2019

    @mmccarty
    Member

    @mrocklin @wesm Any movement on this issue? We are running into it as well. Please let me know if you need help.

  10. wesm commented on Mar 25, 2019

    @wesm
    Contributor

    Not yet. It would be great if someone could write a patch for this or contact me about paying for development work on the project. Absent these things I don't know when it will get fixed

  11. birdsarah commented on Apr 20, 2019

    @birdsarah
    Contributor

    I was having this problem too and the following, not very elegant, patch fixes it for my data:

    From 396492823960544fbf7632450562908d516df069 Mon Sep 17 00:00:00 2001
    From: Sarah Bird <[email protected]>
    Date: Sat, 20 Apr 2019 03:12:51 -0500
    Subject: [PATCH 1/1] First hack to pass in schema
    
    ---
     dask/dataframe/io/parquet.py | 9 +++++++--
     1 file changed, 7 insertions(+), 2 deletions(-)
    
    diff --git a/dask/dataframe/io/parquet.py b/dask/dataframe/io/parquet.py
    index 81e2a846..8015dba9 100644
    --- a/dask/dataframe/io/parquet.py
    +++ b/dask/dataframe/io/parquet.py
    @@ -958,7 +958,7 @@ def _read_pyarrow_parquet_piece(fs, piece, columns, index_cols, is_series,
     
     _pyarrow_write_table_kwargs = {'row_group_size', 'version', 'use_dictionary',
                                    'compression', 'use_deprecated_int96_timestamps',
    -                               'coerce_timestamps', 'flavor', 'chunk_size'}
    +                               'coerce_timestamps', 'flavor', 'chunk_size', 'pyarrow_schema'}
     
     _pyarrow_write_metadata_kwargs = {'version', 'use_deprecated_int96_timestamps',
                                       'coerce_timestamps'}
    @@ -1000,7 +1000,12 @@ def _write_partition_pyarrow(df, path, fs, filename, write_index,
                                  partition_on, metadata_path=None, **kwargs):
         import pyarrow as pa
         from pyarrow import parquet
    -    t = pa.Table.from_pandas(df, preserve_index=write_index)
    +
    +    if 'pyarrow_schema' in kwargs:
    +        pyarrow_schema = kwargs.pop('pyarrow_schema')
    +        t = pa.Table.from_pandas(df, preserve_index=write_index, schema=pyarrow_schema)
    +    else:
    +        t = pa.Table.from_pandas(df, preserve_index=write_index)
     
         if partition_on:
             parquet.write_to_dataset(t, path, partition_cols=partition_on,
    -- 
    2.20.1

    I then manually create a pyarrow schema and pass it in:

    df.to_parquet(
        path='out.parquet',
        engine='pyarrow',
        pyarrow_schema=pa.schema([
            ('field_1', pa.string()),
            ('field_2', pa.int64()),
        ])
  12. mmccarty commented on Apr 20, 2019

    @mmccarty
    Member

    Thanks @birdsarah ! This isn't too terrible. Do others think it would be reasonable fix this in Dask until we can get a solution at the lower level?

    Wes, I'm working on making open source contributions possible for my team. Unfortunately, it is an uphill battle, however I am making progress. Stay tuned! I have folks, including myself, that would love to help out!

  13. martindurant commented on Apr 22, 2019

    @martindurant
    Member

    Probably the thing to do is produce the pyarrow schema from the meta? Or does that not produce a useful schema for an empty dataframe, is that the problem?
    Being allowed to explicitly specify the schema does seem like a useful option in any case.

  14. birdsarah commented on Apr 22, 2019

    @birdsarah
    Contributor

    Probably the thing to do is produce the pyarrow schema from the meta

    @martindurant I think that sounds right.

    I'm not having an empty dataframe problem so I can't speak to that. The problem I'm having is that the schema is inferrred each time from each partition of data and attempts to specify the meta have been ignored. I have a string field that's sometimes all null for a given partition, then my individual partitions are written with different schemas and I can't read back.

    I was surprised to see the meta not being used, but I also didn't know how to make a pyarrow schema from the meta data, which is why i'm hard coding the pyarrow schema. I'm already making the meta data schema and I'd prefer to not make the schema twice.

    That said, I had specified the meta data. Are there were cases where you'd get to line ~1000 above and the df would not have _meta on it.

  15. martindurant commented on Apr 22, 2019

    @martindurant
    Member

    I'm not having an empty dataframe problem

    So although a dataframe should always have one, the meta is usually empty, so calling pyarrow on it directly to make a schema would produce exactly the wrong thing :| I suppose you could always make the schema from a partition of the data that you know to be sound.
    fastparquet has this problem too, and you need to, in the general case, specify how you want to interpret object columns.

  16. 19 remaining items

  17. martindurant commented on Apr 30, 2019

    @martindurant
    Member

    I guess make a dask dataframe with a zoned datetime column and no rows (or only NaT) in one partition.

  18. birdsarah commented on Apr 30, 2019

    @birdsarah
    Contributor

    The original issue here has nothing to do with datetime. That whole discussion only arised out of trying to build a shortcut and i would say it's separate if we're not going to try and infer the pyarrow schema from the already provided data to meta.

  19. martindurant commented on Apr 30, 2019

    @martindurant
    Member

    OK, just thought datetime was the most complex case; the simplest case (int?) would do.

    if we're not going to try and infer the pyarrow schema

    Right, so it seems this isn't as simple to do as I had originally hoped. It it were straight-forward, no extra options would be needed.

  20. birdsarah commented on Apr 30, 2019

    @birdsarah
    Contributor

    There's also array cases and other datatypes which i feel like i don't know enough about pyarrow to make sure are properly covered. Providing your own pyarrow schema bypasses any attempts to be clever that could fail.

  21. jorisvandenbossche commented on May 2, 2019

    @jorisvandenbossche
    Member

    So trying to summarize the different threads from the discussion above:

    • Provide a schema= keyword to to_parquet for the pyarrow branch as one of the arbitrary kwargs that gets passed to the partition-writing tasks (and we might want to do something similar in pandas' to_parquet).
      This can be used as a work-around to ensure consistent schema's across partitions / multiple writes.
    • On the Arrow side, schema evolution / normalization can help with dealing with such situations when reading parquet files with inconsistent schema's (https://issues.apache.org/jira/browse/ARROW-2659 and related issues).
    • To prevent that dask writes parquet datasets with inconsistent schema's, it should somehow infer the schema for the whole dask.dataframe, so it can enforce that when writing each partition. This, however, is not that simple to solve (the empty meta dataframe alone is not enough to reliably create a schema):
      • In fastparquet, this is somewhat tackled with the object_encoding keyword, to specify how to interpret object dtype columns (as all other column dtypes can faithfully be mapped to arrow / parquet types)

    Does that sound correct? Other items?

  22. martindurant commented on May 2, 2019

    @martindurant
    Member

    That sounds like a fair summary to me. The first point should not be required if we can tackle the third (or ameliorated by the second), although maybe it's possible to get such inconsistent schemas from elsewhere.

  23. mmccarty commented on May 20, 2019

    @mmccarty
    Member

    I can take a stab at the Dask related parts summarized above, but I wanted to check first. Is anyone else working on this?

  24. birdsarah commented on May 20, 2019

    @birdsarah
    Contributor

    I'm not. I don't currently have time, but would LOVE to see this happen. Thanks!

  25. iyawnis commented on Oct 14, 2019

    @iyawnis

    I have this issue with dask==2.5.2, pyarrow==0.15.0. Fastparquet does not have this problem, although I am guessing its down to the way it handles partitions.

    Is there anything more clever / reliable to do than manually mapping numpy.dtypes to pa DataTypes like the following?:

    104     type_dict = {
    105         "object": pa.string()
    106     }
    107
    108     def type_map(t):
    109         return type_dict[t.name] if t.name in type_dict else getattr(pa, t.name)()
    110     pyarrow_types = pa.schema([(k, type_map(v)) for k, v in df.dtypes.items()])
    
  26. TomAugspurger commented on Oct 14, 2019

    @TomAugspurger
    Member

    @latusaki you could likely construct / extract a DataFrame with the correct schema and make a pyarrow.Table from that.

  27. iyawnis commented on Oct 15, 2019

    @iyawnis

    @TomAugspurger sadly enough, table.head() and table.tail() have different schema on my example dataframe that reproduces this issue

  28. ldacey commented on Apr 2, 2020

    @ldacey

    I have something similar @latusaki. I needed to also fix my category columns and I wanted dates to be saved as pa.date32()

    def create_pyarrow_schema(df, date_columns):
        dtypes = {
            'object': pa.string(),
            'category': pa.dictionary(index_type=pa.int16(), value_type=pa.string(), ordered=False),
            'datetime64[ns]': pa.timestamp('ns'),
            'Int64': pa.int64(),
        }
    
        def type_map(t):
            return dtypes[t.name] if t.name in dtypes else getattr(pa, t.name)()
        
        fields = []
        for col, dtype in df.dtypes.items():
    
            if col in date_columns:
                fields.append(pa.field(col, pa.date32()))
            
            if df[col].isnull().all():
                fields.append(pa.field(col, pa.string()))
    
            else:
                fields.append(pa.field(col, type_map(dtype)))
                
        return pa.schema(fields)
    

    How can I save this to a file or something though? I want to reuse it when I read in a new file every day without reading a 'correct' version of the file first (ideally). The function above returns:

    year: dictionary<values=string, indices=int16, ordered=0>
    month: dictionary<values=string, indices=int16, ordered=0>
    date: date32[day]
    date: string
    ntid: string
    

    Can I save this to a file or print it out in a format like this which I can save in my script and edit if needed? There are a few columns I need to change (they are double instead of string, or string instead of date32[day].

    pyarrow_schema = pa.schema([
        ('argument_0', pa.string()),
        ('argument_1', pa.string()),
        ('argument_2', pa.string()),])
    
  29. jrbourbeau commented on Apr 2, 2020

    @jrbourbeau
    Member

    @ldacey I would suggest looking through the pyarrow documentation to see if there's a supported API for saving schema objects

  30. ldacey commented on Apr 2, 2020

    @ldacey

    FYI, thanks @jorisvandenbossche for pointing out that we can use .set() to change the data type of a field. Here is a working example:

    with io.BytesIO() as input_io:
        blob_service.get_blob_to_stream(container_name=container
                                                             blob_name=file_path,
                                                             stream=input_io)
        pyarrow_schema = pq.read_schema(where=input_io).remove_metadata()
    
    def modify_schema(schema, column, new_type):
        """
        :param schema: The original pyarrow schema
        :param column: The column name which needs to be assigned a different data type.
        :param column: The new pyarrow data type (ex. pa.string())              
    
        """
        pos = 0
        for col in schema:
            if col.name == column:
                print(f'Changing {col.name} from {col.type} to {new_type}')
                schema = schema.set(pos, pa.field(column, new_type))
            pos += 1
            
        schema = schema.remove_metadata()
    
        return schema
    
    
    dtype_dict = {
        'year': pa.string(),
        'month': pa.string(),
    }
    
    for name, dtype in dtype_dict.items():
        pyarrow_schema = modify_schema(schema=pyarrow_schema, 
                                       column=name, 
                                       new_type=dtype)
    
    

    I'll probably just tweak that to work based off of a dictionary of columns which might need to be changed instead of changing them one by one.

    I think this suffices for now but it would be nice to be able to generate a dict or list of column: pyarrow_type that could be saved externally:

    # Output of pa.Schema.from_pandas() which could be saved to a file and edited:
    
    schema = {
        'date': pa.date32(),
        'name': pa.string(),
        'is_current': pa.bool_(),
        'status': pa.dictionary(index_type=pa.int16(), value_type=pa.string(), ordered=False)),
        'effective_timestamp': pa.timestamp('ns')
    }
    
    # Turn the dict of pyarrow types into a schema to be used when writing data
    
    fields = [pa.field(x, y) for x, y in schema.items()]
    schema = pa.schema(fields)
    
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