Skip to content

to_parquet failing on pyarrow master when different partitions result in different parquet schema #6243

Closed

Description

@jorisvandenbossche

In pyarrow master, we made a change to append_row_groups to require equal schema's when appending (https://issues.apache.org/jira/browse/ARROW-8062,
apache/arrow#7180). But that apparently causes test failures in the dask test suite:

Details
2020-05-26T06:57:29.5507643Z =================================== FAILURES ===================================
2020-05-26T06:57:29.5509731Z _ test_to_parquet_pyarrow_w_inconsistent_schema_by_partition_fails_by_default __
2020-05-26T06:57:29.5509974Z 
2020-05-26T06:57:29.5512116Z tmpdir = local('/tmp/pytest-of-root/pytest-0/test_to_parquet_pyarrow_w_inco0')
2020-05-26T06:57:29.5512377Z 
2020-05-26T06:57:29.5514934Z     def test_to_parquet_pyarrow_w_inconsistent_schema_by_partition_fails_by_default(tmpdir):
2020-05-26T06:57:29.5515252Z         check_pyarrow()
2020-05-26T06:57:29.5515584Z     
2020-05-26T06:57:29.5515752Z         df = pd.DataFrame(
2020-05-26T06:57:29.5515998Z             {"partition_column": [0, 0, 1, 1], "strings": ["a", "b", None, None]}
2020-05-26T06:57:29.5516182Z         )
2020-05-26T06:57:29.5516369Z     
2020-05-26T06:57:29.5516616Z         ddf = dd.from_pandas(df, npartitions=2)
2020-05-26T06:57:29.5516806Z >       ddf.to_parquet(str(tmpdir), engine="pyarrow", partition_on=["partition_column"])
2020-05-26T06:57:29.5516894Z 
2020-05-26T06:57:29.5519255Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/dataframe/io/tests/test_parquet.py:965: 
2020-05-26T06:57:29.5519532Z _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
2020-05-26T06:57:29.5520327Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/dataframe/core.py:3811: in to_parquet
2020-05-26T06:57:29.5525402Z     return to_parquet(self, path, *args, **kwargs)
2020-05-26T06:57:29.5528566Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/dataframe/io/parquet/core.py:461: in to_parquet
2020-05-26T06:57:29.5529800Z     out = out.compute(**compute_kwargs)
2020-05-26T06:57:29.5530394Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/base.py:166: in compute
2020-05-26T06:57:29.5530739Z     (result,) = compute(self, traverse=False, **kwargs)
2020-05-26T06:57:29.5531158Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/base.py:444: in compute
2020-05-26T06:57:29.5539865Z     results = schedule(dsk, keys, **kwargs)
2020-05-26T06:57:29.5543266Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/threaded.py:84: in get
2020-05-26T06:57:29.5545361Z     **kwargs
2020-05-26T06:57:29.5547293Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/local.py:486: in get_async
2020-05-26T06:57:29.5549251Z     raise_exception(exc, tb)
2020-05-26T06:57:29.5550734Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/local.py:316: in reraise
2020-05-26T06:57:29.5552431Z     raise exc
2020-05-26T06:57:29.5553073Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/local.py:222: in execute_task
2020-05-26T06:57:29.5553366Z     result = _execute_task(task, data)
2020-05-26T06:57:29.5553764Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/core.py:121: in _execute_task
2020-05-26T06:57:29.5553938Z     return func(*(_execute_task(a, cache) for a in args))
2020-05-26T06:57:29.5554268Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/utils.py:30: in apply
2020-05-26T06:57:29.5554462Z     return func(*args, **kwargs)
2020-05-26T06:57:29.5554815Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/dataframe/io/parquet/arrow.py:763: in write_metadata
2020-05-26T06:57:29.5554989Z     _meta.append_row_groups(parts[i][0]["meta"])
2020-05-26T06:57:29.5555156Z _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
2020-05-26T06:57:29.5555299Z 
2020-05-26T06:57:29.5555451Z >   ???
2020-05-26T06:57:29.5555610Z E   RuntimeError: AppendRowGroups requires equal schemas.
2020-05-26T06:57:29.5555722Z 
2020-05-26T06:57:29.5555859Z pyarrow/_parquet.pyx:687: RuntimeError
2020-05-26T06:57:29.5556038Z ___________________ test_timeseries_nulls_in_schema[pyarrow] ___________________
2020-05-26T06:57:29.5556155Z 
2020-05-26T06:57:29.5556469Z tmpdir = local('/tmp/pytest-of-root/pytest-0/test_timeseries_nulls_in_schem0')
2020-05-26T06:57:29.5556765Z engine = 'pyarrow'
2020-05-26T06:57:29.5556881Z 
2020-05-26T06:57:29.5557045Z     def test_timeseries_nulls_in_schema(tmpdir, engine):
2020-05-26T06:57:29.5557218Z         # GH#5608: relative path failing _metadata/_common_metadata detection.
2020-05-26T06:57:29.5557373Z         tmp_path = str(tmpdir.mkdir("files"))
2020-05-26T06:57:29.5557554Z         tmp_path = os.path.join(tmp_path, "../", "files")
2020-05-26T06:57:29.5557698Z     
2020-05-26T06:57:29.5557871Z         ddf2 = (
2020-05-26T06:57:29.5558194Z             dask.datasets.timeseries(start="2000-01-01", end="2000-01-03", freq="1h")
2020-05-26T06:57:29.5558363Z             .reset_index()
2020-05-26T06:57:29.5558526Z             .map_partitions(lambda x: x.loc[:5])
2020-05-26T06:57:29.5558701Z         )
2020-05-26T06:57:29.5558847Z         ddf2 = ddf2.set_index("x").reset_index().persist()
2020-05-26T06:57:29.5559172Z         ddf2.name = ddf2.name.where(ddf2.timestamp == "2000-01-01", None)
2020-05-26T06:57:29.5559356Z     
2020-05-26T06:57:29.5559509Z >       ddf2.to_parquet(tmp_path, engine=engine)
2020-05-26T06:57:29.5559623Z 
2020-05-26T06:57:29.5560119Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/dataframe/io/tests/test_parquet.py:2011: 
2020-05-26T06:57:29.5560347Z _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
2020-05-26T06:57:29.5560754Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/dataframe/core.py:3811: in to_parquet
2020-05-26T06:57:29.5561517Z     return to_parquet(self, path, *args, **kwargs)
2020-05-26T06:57:29.5562388Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/dataframe/io/parquet/core.py:461: in to_parquet
2020-05-26T06:57:29.5562518Z     out = out.compute(**compute_kwargs)
2020-05-26T06:57:29.5562799Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/base.py:166: in compute
2020-05-26T06:57:29.5562906Z     (result,) = compute(self, traverse=False, **kwargs)
2020-05-26T06:57:29.5563189Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/base.py:444: in compute
2020-05-26T06:57:29.5563309Z     results = schedule(dsk, keys, **kwargs)
2020-05-26T06:57:29.5563699Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/threaded.py:84: in get
2020-05-26T06:57:29.5563815Z     **kwargs
2020-05-26T06:57:29.5564074Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/local.py:486: in get_async
2020-05-26T06:57:29.5564193Z     raise_exception(exc, tb)
2020-05-26T06:57:29.5564468Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/local.py:316: in reraise
2020-05-26T06:57:29.5564589Z     raise exc
2020-05-26T06:57:29.5564881Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/local.py:222: in execute_task
2020-05-26T06:57:29.5565003Z     result = _execute_task(task, data)
2020-05-26T06:57:29.5565286Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/core.py:121: in _execute_task
2020-05-26T06:57:29.5565410Z     return func(*(_execute_task(a, cache) for a in args))
2020-05-26T06:57:29.5565688Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/utils.py:30: in apply
2020-05-26T06:57:29.5565789Z     return func(*args, **kwargs)
2020-05-26T06:57:29.5566173Z opt/conda/envs/arrow/lib/python3.7/site-packages/dask/dataframe/io/parquet/arrow.py:763: in write_metadata
2020-05-26T06:57:29.5566299Z     _meta.append_row_groups(parts[i][0]["meta"])
2020-05-26T06:57:29.5566410Z _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
2020-05-26T06:57:29.5566474Z 
2020-05-26T06:57:29.5566570Z >   ???
2020-05-26T06:57:29.5566675Z E   RuntimeError: AppendRowGroups requires equal schemas.
2020-05-26T06:57:29.5566733Z 
2020-05-26T06:57:29.5566831Z pyarrow/_parquet.pyx:687: RuntimeError

I when doing FileMetadata.append_row_groups, it seems to make sense that we require the schemas to be the same, because afterwards there is only a single schema.

Looking at the failures in dask, it are cases where the different partitions of the dask dataframe result in a different pyarrow/parquet schema (and specifically a partition with all nulls in an object dtype (string) column).

Do you see a solution for this on the dask side? (in principle there is the meta dtypes, but here of course it's the typical problem that "object" dtype is not specific enough ..).

Or should we revert back to being less strict on Arrow's side?

cc @rjzamora @martindurant

Activity

  1. martindurant commented on May 26, 2020

    @martindurant
    Member

    How are the schemas different, are the equivalent from pandas' point of view? The file metadata should contain the original pandas schema, which may be more precise than the parquet one, but maybe doesn't map perfectly to arrow's types, especially for object/str.

  2. jorisvandenbossche commented on May 26, 2020

    @jorisvandenbossche
    MemberAuthor

    For example the first failing test does this:

        df = pd.DataFrame(
            {"partition_column": [0, 0, 1, 1], "strings": ["a", "b", None, None]}
        )
    
        ddf = dd.from_pandas(df, npartitions=2)
        ddf.to_parquet(str(tmpdir), engine="pyarrow", partition_on=["partition_column"])
    

    So the first partition converts to pyarrow with a string-type column, the second with a null-type columns (because pyarrow infers a all-None object array as null type).
    So to_parquet is writing parquet files with two different schema's, and when combining those into a single _metadata object, we ignored this mismatch before, but now started to raise on this (FileMetadata.append_row_groups(other_file_metadata) now checks the schema to be equal).

  3. jorisvandenbossche commented on May 26, 2020

    @jorisvandenbossche
    MemberAuthor

    So in practice this will only happen with object dtype columns (I think), but given that strings are stored in object dtype, quite an important use case ...

  4. rjzamora commented on May 26, 2020

    @rjzamora
    Member

    Hopefully there is no failure if the desired schema is passed as a kwarg directly to the to_parquet call in dask? (If it is not easy for you to try, I will give it a go as soon as I am set up)

  5. martindurant commented on May 26, 2020

    @martindurant
    Member

    So in the pandas schema, both parts just get "object" anyway... When do we get nullable string columns in pandas by default? :)

  6. jorisvandenbossche commented on May 26, 2020

    @jorisvandenbossche
    MemberAuthor

    Hopefully there is no failure if the desired schema is passed as a kwarg directly to the to_parquet call in dask?

    Yes that still works. But it is a bit awkward to need to pass this ...

    Now, I suppose this is not really solvable from dask's side when you have such all-missing object-dtype partitions. Unless you would assume that object dtype always means string, but that will for sure also break people's code.

    When do we get nullable string columns in pandas by default? :)

    When more people start contributing to that part of pandas ;) (otherwise it will still take a while)

  7. jorisvandenbossche commented on May 26, 2020

    @jorisvandenbossche
    MemberAuthor

    Regarding the nullable string dtype -> that's acually an easier workaround for users to do than specifying the full schema (they can convert the object column to string dtype, and then all should work).

  8. dhirschfeld commented on May 26, 2020

    @dhirschfeld

    the first partition converts to pyarrow with a string-type column, the second with a null-type columns (because pyarrow infers a all-None object array as null type).

    Maybe if a schema isn't passed dask could infer a common schema from the first few partitions? Similar to the csv.Sniffer class? I think an inferred null type column would be a pretty good indicator of an incorrect type in ~all cases.

  9. dhirschfeld commented on May 26, 2020

    @dhirschfeld

    ...or maybe there could be a post-processing step where all partitions are cast to the common schema before being concatenated.

    Or pyarrow allow a cast_null=True argument to coerce any null-type columns.

  10. TomAugspurger commented on May 27, 2020

    @TomAugspurger
    Member

    Why isn't dask writing the file with the correct schema? Dask knows the correct dtypes for all columns, can that be specified when writing?

  11. rjzamora commented on May 27, 2020

    @rjzamora
    Member

    Why isn't dask writing the file with the correct schema? Dask knows the correct dtypes for all columns, can that be specified when writing?

    The pandas dtypes should all be the same. The problem is that the arrow type for a pandas "object" column depends on the null content. The user can specify the schema when calling to_parquet, but I agree we should probably be able to handle inconsistent schemas in a more automated way.

  12. jorisvandenbossche commented on May 27, 2020

    @jorisvandenbossche
    MemberAuthor

    the arrow type for a pandas "object" column depends on the null content.

    It actually depends on the full content, not only of nulls, as you could in principle also have integers or other objects in an object dtype column. But the nulls issue with strings is probably the most common.

    @dhirschfeld's suggestion to "infer" a schema from a small part of the dask.dataframe in case no schema is otherwise specified by the user, could be a possible solution.
    Dask could eg convert the first x rows to a pyarrow table to get the schema, and then specify that same schema for writing all partitions to parquet.

    Or more sophisticated, it could in principle only infer it for the object dtype columns, as all other columns should have a non-ambiguous mapping to arrow types (and for those you can create a schema from the empty meta dataframe).

    Of course, if you would then have a string column that starts with a lot of nulls, you would still run into troubles.

  13. martindurant commented on May 27, 2020

    @martindurant
    Member

    The ultra-cautious approach would be to get the arrow schema from every partition and find the common denominator before writing, but that could cause two passes through the whole of the input data.

  14. 15 remaining items

  15. rjzamora commented on Jun 16, 2020

    @rjzamora
    Member

    I think we just use DataFrame._meta_nonempty to get the dtypes. That seems most consistent with the rest of Dask. If it's incorrect then the user has the option of providing the schema explicitly.

    I am also thinking we may need to "do our best" with _meta_nonempty, and require the user to be more explicit if it fails. I'd rather avoid the need to parse any real file data (by default, at least).

  16. martindurant commented on Jun 16, 2020

    @martindurant
    Member

    An object_encoding parameter that takes a dict of column name to dtype seems fine.

    You mean arrow or parquet type?

  17. TomAugspurger commented on Jun 16, 2020

    @TomAugspurger
    Member
  18. martindurant commented on Jun 16, 2020

    @martindurant
    Member

    The fastparquet method was to pick explicitly from the parquet encodings; this is the most exact, but I'm not sure that arrow would make it easy. Mapping to arrow types is probably more obvious for the user that knows little about the vagaries of parquet; I don't know what you would loose. Since we are proposing a way around making whole arrow schemas, this latter way, {col: arrow_type} seems fairly straight-forward.

    My point was, really, that "dtype" (in the pandas sense) isn't enough.

  19. jorisvandenbossche commented on Jun 16, 2020

    @jorisvandenbossche
    MemberAuthor

    An object_encoding parameter that takes a dict of column name to dtype seems fine.

    You mean arrow or parquet type?

    It would indeed need to be an arrow type, because 1) that's what is needed for the intermediate pandas->pyarrow.Table conversion and 2) pyarrow doesn't have a way to specify a certain parquet type when writing a pyarrow Table AFAIK.


    Now, I am having a possible "insight" (not fully sure yet I am not missing something ;-)). So one of the tests that is failing, is actually testing that the written parquet dataset is failing on read. The reason this test is failing, is because it is now already failing on write.
    But so that in itself is not necessarily a bad change?

    Failing test:

    Details

    def test_to_parquet_pyarrow_w_inconsistent_schema_by_partition_fails_by_default(tmpdir):
    check_pyarrow()
    df = pd.DataFrame(
    {"partition_column": [0, 0, 1, 1], "strings": ["a", "b", None, None]}
    )
    ddf = dd.from_pandas(df, npartitions=2)
    ddf.to_parquet(str(tmpdir), engine="pyarrow", partition_on=["partition_column"])
    # Test that read fails because of default behavior when schema not provided
    with pytest.raises(ValueError) as e_info:
    dd.read_parquet(
    str(tmpdir),
    engine="pyarrow",
    gather_statistics=False,
    dataset={"validate_schema": True},
    ).compute()
    assert e_info.message.contains("ValueError: Schema in partition")
    assert e_info.message.contains("was different")

  20. rjzamora commented on Jun 16, 2020

    @rjzamora
    Member

    But so that in itself is not necessarily a bad change?

    Good point - The test is expected to fail when reading back an inconsistent schema. If pyarrow is now preventing the user from writing the inconsistent schema to begin with, there is really no loss in functionality here :)

  21. martindurant commented on Jun 16, 2020

    @martindurant
    Member

    Agree that that test should be failing on write, so long as we make sure the schemas are inconsistent (before implementing any suggestions here)

  22. jorisvandenbossche commented on Jun 16, 2020

    @jorisvandenbossche
    MemberAuthor

    Now, I am certainly still missing something. As the second that test is failing, is actually testing that such an inconsistently written dataset can be read. But I don't yet fully understand what the difference is between both tests (why it asserts is fails in the one case and it works in the other case).

    Second failing test:

    Details

    def test_timeseries_nulls_in_schema(tmpdir, engine):
    # GH#5608: relative path failing _metadata/_common_metadata detection.
    tmp_path = str(tmpdir.mkdir("files"))
    tmp_path = os.path.join(tmp_path, "../", "files")
    ddf2 = (
    dask.datasets.timeseries(start="2000-01-01", end="2000-01-03", freq="1h")
    .reset_index()
    .map_partitions(lambda x: x.loc[:5])
    )
    ddf2 = ddf2.set_index("x").reset_index().persist()
    ddf2.name = ddf2.name.where(ddf2.timestamp == "2000-01-01", None)
    ddf2.to_parquet(tmp_path, engine=engine)
    ddf_read = dd.read_parquet(tmp_path, engine=engine)
    assert_eq(ddf_read, ddf2, check_divisions=False, check_index=False)
    # Can force schema validation on each partition in pyarrow
    if engine == "pyarrow":
    # The schema mismatch should raise an error
    with pytest.raises(ValueError):
    ddf_read = dd.read_parquet(
    tmp_path, dataset={"validate_schema": True}, engine=engine
    )

  23. jorisvandenbossche commented on Jun 16, 2020

    @jorisvandenbossche
    MemberAuthor

    So the first test is specifying a dataset={"validate_schema": True}, in read_parquet, and the second test is not. So that clarifies the difference.

    Thus, forget my "insight" from above. Such datasets written with incosistent schemas in the different parquet files, right now read fine by default. This was actually fixed by @rjzamora in #5307, by ensuring to pass validate_schema=False when not specified by the user (with similar comments about the problem of object dtype partitions with all nulls .. #5307 (comment))

  24. mrocklin commented on Aug 4, 2020

    @mrocklin
    Member

    FWIW this is an issue when converting the NYCTaxi dataset to Parquet

    import dask.dataframe as dd
    df = dd.read_csv(
        "s3://nyc-tlc/trip data/yellow_tripdata_2019-*.csv", 
        parse_dates=["tpep_pickup_datetime", "tpep_dropoff_datetime"],
        dtype={
            "VendorID": "UInt8",
            "passenger_count": "UInt8",
            "RatecodeID": "UInt8",
            "store_and_fwd_flag": "category",
            "PULocationID": "UInt16",
            "DOLocationID": "UInt16",
            "payment_type": "UInt8",
        },
    )
    
    df.to_parquet("foo.parquet")
  25. jorloplaz commented on Aug 5, 2020

    @jorloplaz
    Contributor

    FYI, this also happens when reading a dataframe with some empty partition. Something like this:

    from dask import from_pandas
    from pandas import DataFrame, to_datetime
    
    df = DataFrame({
         "index": ["1", "2", "3", "2", "3", "1", "4"],
         "date":  to_datetime(["2017-01-01", "2017-01-01", "2017-01-01", "2017-01-02", "2017-01-02", 
                                                "2017-01-06", "2017-01-09"]),
         "amount": [100, 200, 300, 400, 500, 600, 700]
    })
    df = from_pandas(df, npartitions=2).set_index("index")
    

    If from_pandas doesn't actually partition this into 2 partitions (BTW, why isn't this guaranteed?), which can be checked with df.map_partitions(len).compute(), the above error with AppendRowGroups is also raised.

    With npartitions=1 it goes fine of course, but maybe it's related. Hope this helps.

  26. mrocklin commented on Aug 5, 2020

    @mrocklin
    Member

    That is a much nicer reproducer :) Thanks @jorloplaz

  27. martindurant commented on Aug 5, 2020

    @martindurant
    Member

    BTW, why isn't this guaranteed?

    I believe the sequence of operations went like:

    • Dask partitioned the original data equally, with two partitions of length 4 and 3
    • To find the partitions after reindex, Dask did "approximate quantiles" on the index column (which is text type), and found (min, median, max) = ("1", "1", "4"). I'm not sure how these values arise
    • Then the data was repartitioned, the first partition getting rows "1" <= index < "1" (i.e., none of them)
  28. rjzamora commented on Aug 6, 2020

    @rjzamora
    Member

    I submitted #6490 to address this, where I make sampling-based schema inference the default. Given that sampling requires obvious overhead (which may be unnecessary), does it sound reasonable to make it the default behaviour to avoid sampliing/inference? Would it be convenient enough for users to pass in schema="infer" to handle cases like NYCTaxi?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions