Skip to content

write_metadata in DataFrame.to_parquet kills worker #6600

Closed

Description

@mcguipat

While executing

df.to_parquet(
    path,
    engine="pyarrow",
    compression="gzip",
    partition_on=["part_col"],
    append=False,
    write_index=False,
)

on a dask.DataFrame, the write_metadata task repeated fails as it crashes the worker where it is executed and triggers a recalculation of any dask.delayed results held on that worker. After exceeding the retry limit, the function throws an exception.

The DataFrame is constructed from a set of 2500 dask.delayed partitions. The partitions all fit easily within memory; however, when the write_metadata task is submitted, it appears to kill the worker due to the memory limit being exceed. There is nothing explicitly logged when the worker dies in the worker or the scheduler as to what killed the worker. The target file system is s3; however, it does not seem like a likely explanation for this issue.

My expectation is that {"schema": t.schema, "meta": _meta} which is submitted to write_metadata is reasonably small; however, this does not seem to be the case. It doesn't seem like desirable behavior to pass the full list all a once when these could easily processed incrementally.

Activity

  1. TomAugspurger commented on Sep 8, 2020

    @TomAugspurger
    Member

    Do you have a reproducible example @mcguipat? See http://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports

    My expectation is that {"schema": t.schema, "meta": _meta}

    That's the intent (though I haven't verified that's how things are implemented).

    cc @rjzamora.

  2. rjzamora commented on Sep 14, 2020

    @rjzamora
    Member

    I'd be happy to look into this if I had a reproducer. Perhaps something that that demonstrates that {"schema": t.schema, "meta": _meta} is too large - even if it requires a print or pdb statement to actually observe the issue. I know it may be tricky to come up with something simple, but it would be super helpful.

  3. mcguipat commented on Oct 13, 2020

    @mcguipat
    Author

    I've spent some time here attempting to make a reproducible example; however, it's proving meaningfully more difficult than I had anticipated. The original issue is present when running against a KubeCluster; however, when attempting to execute against a LocalCluster of similar spec, it does not seem to occur. I'm continuing to try to find a way to reproduce/investigate the root cause.

    Is there any way to enable more detailed logging around specific task handling and/or worker termination events?

  4. gforsyth commented on Oct 15, 2020

    @gforsyth
    Contributor

    I just hit this in the last couple of days -- I suspect it's due to schema mismatch when using pyarrow

    @mcguipat -- does the same thing happen if you add schema='infer' to your to_parquet call?

  5. callumanoble commented on Oct 16, 2020

    @callumanoble
    Contributor

    @gforsyth I've been investigating this and have run into a potentially related issue.

    I don't see memory explosion as detailed in the original report but I've identified a bug whereby the pyarrow write_metadata implementation either throws or segfaults when empty dask dataframe partitions are processed.

    If a partition contains an empty data frame a "meta" value of None is returned from write_partition and results an exception/segfault depending on parameters/ordering of partitions

    I'm submitting a PR to remedy this shortly but it may be worth checking for these conditions in your application.

    Reproducible examples:

    from dask import delayed
    import dask.dataframe as dd
    import faulthandler
    import pandas as pd
    
    faulthandler.enable()
    
    path = "."
    
    df_a = delayed(pd.DataFrame.from_dict)({"x": [], "y": []}, dtype=("int", "int"))
    df_b = delayed(pd.DataFrame.from_dict)({"x": [1, 1, 2, 2], "y": [1, 0, 1, 0]})
    df_c = delayed(pd.DataFrame.from_dict)({"x": [1, 2, 1, 2], "y": [1, 0, 1, 0]})
    
    # 1. raises AttributeError
    df = dd.from_delayed([df_a, df_b, df_c])
    df.to_parquet(
        path,
        engine="pyarrow",
        partition_on=["x"],
        append=False,
        compute_kwargs={"scheduler": "synchronous"},
    )
    
    # 2. cores
    df = dd.from_delayed([df_b, df_c, df_a])
    df.to_parquet(
        path,
        engine="pyarrow",
        partition_on=["x"],
        append=False,
        compute_kwargs={"scheduler": "synchronous"},
    )
    
  6. callumanoble commented on Oct 21, 2020

    @callumanoble
    Contributor

    I just hit this in the last couple of days -- I suspect it's due to schema mismatch when using pyarrow

    @mcguipat -- does the same thing happen if you add schema='infer' to your to_parquet call?

    I've been looking into this further and I cannot get to_parquet to complete with the following job:

    Cluster:
    10 workers @ 15 procs, 1 thread, 2GB mem limit
    scheduler mem limit 20GB (grasping at straws here)

    Dataframe with 2529 partitions

    The issue is that the job makes progress until it's about 95% complete at which point it stalls indefinitely. You can see in the attached screenshot that the job makes progress then hangs for 6 hours... Worker memory usage increases continually as the job progresses and worker logs show lots of memory leak errors (which I expect is smoking gun).

    I have attempted this with schema as None, "infer" and explicitly passed. I've also tried with both pyarrow and fastparquet engines none of which make any difference...

    The only way I've managed to get the job to complete is to batch the partitions and call to_parquet repeatedly. Ideally we wouldn't just increase worker memory allowance.

    Re. pyarrow engine:

    I would expect that on each completion of a delayed write_partition call most memory would be released (loaded pyarrow table etc.) leaving only schema and meta objects on workers ready for write_metadata. I've also attempted pickling -> unpickling the schema and meta objects and returning those copies in write_partition on the off chance this would release any dangling references to mem in the underlying Cython classes, this had no effect.

    Apologies for not providing a reproducible example but this issue only occurs at scale, any thoughts would be much appreciated.

    ddf_to_parquet_fail

  7. dankerrigan commented on Nov 9, 2020

    @dankerrigan

    Working on a similar dataset to @gforsyth and experiencing the same apparent issue, the worker, performing the write_metadata task, using increasing amounts of memory until the worker OOM terminates and the worker and task restart. The dataset we originally encountered this issue with has thousands of columns, 10s of thousands of partitions, and millions of rows running on a cluster with TBs of memory (64GiB workers). We speculate the OOM issue is a function of the number of columns and the number of partitions. See reproducer below, where to_parquet succeeds if the dataframe with 2,000 columns has one partition (10,000 rows) but fails if it has 1,000 (10 rows/partition).

    dask version 2.30.0
    distributed version 2.30.1
    pyarrow version 1.0.1

    import os
    import shutil
    import pandas as pd
    
    os.environ['DASK_DISTRIBUTED__WORKER__MEMORY__TARGET'] = "False"
    os.environ['DASK_DISTRIBUTED__WORKER__MEMORY__SPILL'] = "False"
    os.environ['DASK_DISTRIBUTED__WORKER__MEMORY__PAUSE'] = "0.93"
    os.environ['DASK_DISTRIBUTED__WORKER__MEMORY__TERMINATE'] = "0.95"
    os.environ['DASK_DISTRIBUTED__SCHEDULER__ALLOWED_FAILURES'] = "20"
    os.environ['DASK_DISTRIBUTED__COMM__TIMEOUTS__CONNECT'] = "5"
    os.environ['DASK_DISTRIBUTED__COMM__RETRY__COUNT'] = "10"
    
    import dask
    import dask.dataframe as dd
    from distributed import Client, LocalCluster
    from sklearn.datasets import make_classification
    
    cluster = LocalCluster(
        n_workers=4,
        processes=True,
        threads_per_worker=1,
        memory_limit="3GiB"
    )
    
    c = Client(cluster)
    
    n_samples_list = [10_000]
    n_features_list = [2_000]
    npartitions_list = [1, 1_000]
    
    path = "./test.parquet"
    engine = "pyarrow"
    
    for n_samples in n_samples_list:
        for n_features in n_features_list:
            for npartitions in npartitions_list:
                print(f"Testing n_samples={n_samples} n_features={n_features} npartitions={npartitions}")
                print(f"Rows/partition={n_samples/npartitions}")
    
                print("Creating dataframe")
                X, _ = make_classification(n_samples=n_samples, n_features=n_features)
                df = pd.DataFrame(X, columns=[f"var{i}" for i in range(n_features)])
                ddf = dd.from_pandas(df, npartitions=npartitions)
                print("Created dataframe")
    
                print("Writing parquet")
                shutil.rmtree(path, ignore_errors=True)
                ddf.to_parquet(path, engine)
                shutil.rmtree(path, ignore_errors=True)
                print(f"Wrote {path}, removing")
    
                print("Restarting Dask Client\n")
                c.restart()
    

    Output follows:

    Testing n_samples=10000 n_features=2000 npartitions=1
    Rows/partition=10000.0
    Creating dataframe
    Created dataframe
    Writing parquet
    Wrote ./test.parquet, removing
    Restarting Dask Client
    
    Testing n_samples=10000 n_features=2000 npartitions=1000
    Rows/partition=10.0
    Creating dataframe
    Created dataframe
    Writing parquet
    distributed.nanny - WARNING - Worker exceeded 95% memory budget. Restarting
    distributed.nanny - WARNING - Restarting worker
    distributed.nanny - WARNING - Worker exceeded 95% memory budget. Restarting
    distributed.nanny - WARNING - Restarting worker
    

    Workers will restart until parent process is killed, as expected. The same behavior can be seen when using engine = "fastparquet"

  8. rjzamora commented on Nov 10, 2020

    @rjzamora
    Member

    Thanks for the reproducer @dankerrigan ! I get the same behavior on my machine. It certainly seems like the problem occurs when all the metadata is aggregated onto a single worker to write the "_metadata" file. I'll try to dig in and see if we are doing anything silly here.

  9. mmccarty commented on Nov 10, 2020

    @mmccarty
    Member

    Awesome! Thanks @dankerrigan
    @rjzamora I'm glad you can see the issue locally. Let us know if you need any help.

  10. rjzamora commented on Nov 12, 2020

    @rjzamora
    Member

    I'm glad you can see the issue locally. Let us know if you need any help.

    I don't have a solution yet, but I did poke around a bit. The failure in this reproducer is definitely due to the total size of the metadata being sent to the final write_metadata task.... Every write_partition is sending along a ~1.3MB object containing the schema as well as the parquet metadata for the row-groups written by that task. We can avoid sending the schema in this object (only one of the partitions is used to write the _common_metadata file anyway), but that still leaves about 940KB of metadata from each partition. Therefore, a 1000-partition write will need to result in a single task aggregating almost 1GB of data to write the _metadata file. This can easily cause issues on a memory-constrained system.

    Thoughts on possible solutions:

    • As already mentioned above, we can avoid sending the same schema from every write_partition task. This will not fix the general scaling issue, but will avoid some of the memory overhead.
    • Although the total parts list is ~1GB in size, the final metadata blob is about 4x smaller, because the metadata for every partition includes data that will be thrown away within _append_row_groups. This means we could probably reduce the memory pressure a bit further by using multiple intermediate tasks to aggregate the metadata.

    • I suspect that the only way to make metadata writing completely scalable is to work out a mechanism to append row-groups to the _metadata file without needing to aggregate them in memory first. This shouldn’t be too difficult, but may require changes in pyarrow.
  11. AashishJainData commented on Dec 28, 2020

    @AashishJainData

    I am also facing a similar issue with large files, do we have any plan to fix this.

  12. rhjmoore commented on May 13, 2021

    @rhjmoore
    Contributor

    I'm seeing this also, with 2,500 partitions of a 500 column 80m record dataset. Everything processes well within memory constraints until the final metadata write, which fails. Annoyingly there's plenty of memory on the server for this last job, just not within a single worker with its fixed proportion of the total server memory.
    I don't suppose there's a way of getting this to operate within a different memory constraint or on a dedicated, large memory worker as a temporary work-around?

  13. callumanoble commented on May 25, 2021

    @callumanoble
    Contributor

    We were never able to come up with an elegant solution for this. In terms of a workaround we resorted to batching over partitions and repeatedly calling to_parquet per comment above

  14. mrocklin commented on Jul 30, 2021

    @mrocklin
    Member

    So, I see a couple ways that we can solve this problem, neither is very hard:

    1. Add the ability to turn off writing metadata. This isn't strictly necessary for Parquet to work. It's just a convenience and results in some efficiencies when reading. We should have a flag to turn this off. This shouldn't be too hard to add
    2. Is the actual resulting metadata object huge, or is it just having a single task that has 1000's of dependencies? If the latter (which I hope) we should solve this with a tree reduction. We should accumulate the metadata in intermediate stages. I suspect that this will also help the scheduling heuristics.

    @rjzamora @jorisvandenbossche any thoughts on these?

  15. rjzamora commented on Jul 30, 2021

    @rjzamora
    Member
    1. Add the ability to turn off writing metadata. This isn't strictly necessary for Parquet to work. It's just a convenience and results in some efficiencies when reading. We should have a flag to turn this off. This shouldn't be too hard to add

    There is indeed a write_metadata_file option in to_parquet

    1. Is the actual resulting metadata object huge, or is it just having a single task that has 1000's of dependencies? If the latter (which I hope) we should solve this with a tree reduction. We should accumulate the metadata in intermediate stages. I suspect that this will also help the scheduling heuristics.

    Yes- this does help a little bit (note that the create_metadata_file utility uses a tree reduction). However, for very large-scale writes, the size of the metadata itself can be a real problem.

  16. mrocklin commented on Jul 30, 2021

    @mrocklin
    Member

    Looking here it looks like we drop everything into a single task

    if write_metadata_file:
    dsk[(final_name, 0)] = (
    apply,
    engine.write_metadata,
    [
    part_tasks,
    meta,
    fs,
    path,
    ],
    {"append": append, "compression": compression},
    )
    else:
    dsk[(final_name, 0)] = (lambda x: None, part_tasks)

    I do see the slick tree reduction code in create_metadata_file but that doesn't appear to be active in to_parquet? It looks like it's used in arrow when reading, if I understand correctly.

    I've cleaned up the graph structure a bit in the no write_parquet case in #7968 . Something there isn't right though, if you can take a look (or indeed take over that PR) @rjzamora I would appreciate it (no expectations though)

  17. rjzamora commented on Jul 30, 2021

    @rjzamora
    Member

    I do see the slick tree reduction code in create_metadata_file but that doesn't appear to be active in to_parquet? It looks like it's used in arrow when reading, if I understand correctly.

    Right - That code was a bit "experimental" at first, but the approach should likely be used more broadly.

    Something there isn't right though, if you can take a look (or indeed take over that PR)

    Cool - I'll take a look, but I probably can't "do" much in the short term

  18. mrocklin commented on Jul 30, 2021

    @mrocklin
    Member

    Cool - I'll take a look, but I probably can't "do" much in the short term

    In theory everything is done. However tests aren't passing, so I probably missed some key somewhere. I suspect that you are more capable of interpretting failed tests here than I am

  19. mrocklin commented on Jul 30, 2021

    @mrocklin
    Member

    While @rjzamora and I chat here, it's worth pointing out that anyone who runs into this problem can probably avoid most of the issue by setting write_metadata_file=False in the to_parquet call.

    df.to_parquet(write_metadata_file=False)
  20. jorisvandenbossche commented on Aug 3, 2021

    @jorisvandenbossche
    Member

    2. Is the actual resulting metadata object huge, or is it just having a single task that has 1000's of dependencies? ...

    ... for very large-scale writes, the size of the metadata itself can be a real problem.

    Indeed the actual metadata can get relatively large, if you have lots of row groups / columns. Small illustration:

    In [1]: table = pa.table(pd.DataFrame(np.random.randn(10000, 10), columns=list("abcdefghij")))
    
    In [2]: import pyarrow.parquet as pq
    
    In [3]: pq.write_table(table, "test_md_size.parquet")
    
    In [4]: !ls test_md_size.parquet -sh
    960K test_md_size.parquet
    
    In [5]: col = []
    
    In [6]: pq.write_table(table, "test_md_size.parquet", row_group_size=10, metadata_collector=col)
    
    In [7]: !ls test_md_size.parquet -sh
    3,6M test_md_size.parquet
    
    In [11]: col[-1].write_metadata_file("metadata_only.parquet")
    
    In [12]: !ls metadata_only.parquet -sh
    980K metadata_only.parquet
    

    So for 1000 row groups with 10 columns, you already get a 1 MB file, and the in-memory object will probably be several times bigger (and we need it in-memory to append them, as written Parquet files can't be appended).
    The size can be limited a bit by not writing statistics (write_statistics=False), but that of course also defeats part of the benefit of having a _metadata file.

    (it might be interesting to explore other "metadata" file formats that are more flexible (eg appendable), like Apache Iceberg)

  21. jcrist commented on May 13, 2022

    @jcrist
    Member

    With #8901, we no longer write _metadata files by default, which should remove this problem. There may be some upstream fixes in pyarrow that could improve the scalability limit of producing the _metadata file, but at some point the full dataset metadata will always become too large for a single worker to process. Other tools like spark have come to the same conclusion and made the same change. Closing.

  22. self-assigned this
    on May 13, 2022
  23. added a commit that references this issue on Feb 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions