Repository navigation
Closed as duplicate
Description
While upgrading our application to use pyarrow 2.0.0 instead of 0.12.1, we observed a memory leak in the read_table and to_pandas methods. See below for sample code to reproduce it. Memory does not seem to be returned after deleting the table and df as it was in pyarrow 0.12.1.
Sample Code
import io
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from memory_profiler import profile
@profile
def read_file(f):
table = pq.read_table(f)
df = table.to_pandas(strings_to_categorical=True)
del table
del df
def main():
rows = 2000000
df = pd.DataFrame({
"string": ["test"] * rows,
"int": [5] * rows,
"float": [2.0] * rows,
})
table = pa.Table.from_pandas(df, preserve_index=False)
parquet_stream = io.BytesIO()
pq.write_table(table, parquet_stream)
for i in range(3):
parquet_stream.seek(0)
read_file(parquet_stream)
if __name__ == '__main__':
main()Python 3.8.5 (conda), pyarrow 2.0.0 (pip), pandas 1.1.2 (pip) Logs
Filename: C:/run_pyarrow_memoy_leak_sample.py
Line # Mem usage Increment Occurences Line Contents
============================================================
9 161.7 MiB 161.7 MiB 1 @profile
10 def read_file(f):
11 212.1 MiB 50.4 MiB 1 table = pq.read_table(f)
12 258.2 MiB 46.1 MiB 1 df = table.to_pandas(strings_to_categorical=True)
13 258.2 MiB 0.0 MiB 1 del table
14 256.3 MiB -1.9 MiB 1 del df
Filename: C:/run_pyarrow_memoy_leak_sample.py
Line # Mem usage Increment Occurences Line Contents
============================================================
9 256.3 MiB 256.3 MiB 1 @profile
10 def read_file(f):
11 279.2 MiB 23.0 MiB 1 table = pq.read_table(f)
12 322.2 MiB 43.0 MiB 1 df = table.to_pandas(strings_to_categorical=True)
13 322.2 MiB 0.0 MiB 1 del table
14 320.3 MiB -1.9 MiB 1 del df
Filename: C:/run_pyarrow_memoy_leak_sample.py
Line # Mem usage Increment Occurences Line Contents
============================================================
9 320.3 MiB 320.3 MiB 1 @profile
10 def read_file(f):
11 326.9 MiB 6.5 MiB 1 table = pq.read_table(f)
12 361.7 MiB 34.8 MiB 1 df = table.to_pandas(strings_to_categorical=True)
13 361.7 MiB 0.0 MiB 1 del table
14 359.8 MiB -1.9 MiB 1 del dfPython 3.5.6 (conda), pyarrow 0.12.1 (pip), pandas 0.24.1 (pip) Logs
Filename: C:/run_pyarrow_memoy_leak_sample.py
Line # Mem usage Increment Occurences Line Contents
============================================================
9 138.4 MiB 138.4 MiB 1 @profile
10 def read_file(f):
11 186.2 MiB 47.8 MiB 1 table = pq.read_table(f)
12 219.2 MiB 33.0 MiB 1 df = table.to_pandas(strings_to_categorical=True)
13 171.7 MiB -47.5 MiB 1 del table
14 139.3 MiB -32.4 MiB 1 del df
Filename: C:/run_pyarrow_memoy_leak_sample.py
Line # Mem usage Increment Occurences Line Contents
============================================================
9 139.3 MiB 139.3 MiB 1 @profile
10 def read_file(f):
11 186.8 MiB 47.5 MiB 1 table = pq.read_table(f)
12 219.2 MiB 32.4 MiB 1 df = table.to_pandas(strings_to_categorical=True)
13 171.5 MiB -47.7 MiB 1 del table
14 139.1 MiB -32.4 MiB 1 del df
Filename: C:/run_pyarrow_memoy_leak_sample.py
Line # Mem usage Increment Occurences Line Contents
============================================================
9 139.1 MiB 139.1 MiB 1 @profile
10 def read_file(f):
11 186.8 MiB 47.7 MiB 1 table = pq.read_table(f)
12 219.2 MiB 32.4 MiB 1 df = table.to_pandas(strings_to_categorical=True)
13 171.8 MiB -47.5 MiB 1 del table
14 139.3 MiB -32.4 MiB 1 del dfReporter: Michael Peleshenko
Assignee: Weston Pace / @westonpace
Related issues:
- [Python] Add environment variable to elect default usage of system memory allocator instead of jemalloc/mimalloc (is related to)
Original Issue Attachments:
Note: This issue was originally created as ARROW-11007. Please see the migration documentation for further details.
Reacted by Johannes E. M. Mosig
Activity
asfimport commentedon Dec 22, 2020
Weston Pace / @westonpace:
Hello, thank you for writing up this analysis. Pyarrow uses jemalloc, a custom memory allocator which does its best to hold onto memory allocated from the OS (since this can be an expensive operation). Unfortunately, this makes it difficult to track line by line memory usage with tools like memory_profiler. There are a couple of options:
You could use https://arrow.apache.org/docs/python/generated/pyarrow.total_allocated_bytes.html#pyarrow.total_allocated_bytes to track allocation instead of using memory_profiler (it might be interesting to see if there is a way to get memory_profile to use this function instead of kernel statistics).
You can also put the following line at the top of your script, this will configure jemalloc to release memory immediately instead of holding on to it (this will likely have some performance implications):
pa.jemalloc_set_decay_ms(0)
The behavior you are seeing is pretty typical for jemalloc. For further reading, in addition to reading up on jemalloc itself, I encourage you to take a look at these other issues for more discussions and examples of jemalloc behaviors:
https://issues.apache.org/jira/browse/ARROW-6910
https://issues.apache.org/jira/browse/ARROW-7305
I have run your test read 10,000 times and it seems that memory usage does predictably stabilize. In addition, total_allocated_bytes is behaving exactly as expected. So I do not believe there is any evidence of a memory leak in this script.
asfimport commentedon Dec 22, 2020
Michael Peleshenko:
@westonpace Thanks for the detailed comment. I tried adding pa.jemallic_set_decay_ms(0), but I ran into the below error which seems to indicate jemalloc is not being used. I suspect this is because I am running on Windows 10.
asfimport commentedon Dec 22, 2020
Wes McKinney / @wesm:
Depending on how you obtained pyarrow, it may be using mimalloc rather than the system allocator. We've done comparatively much less analysis of memory usage behaviors when using mimalloc, but we do know empirically that mimalloc improves application performance on Windows.
asfimport commentedon Dec 28, 2020
Antoine Pitrou / @pitrou:
Also note that "does not return memory immediately" is different from "memory leak". The allocator (mimalloc and/or the system allocator, here) may opt to cache deallocated blocks instead of returning them to the system, because returning them is costly (it's a system call), and allocations often happen in a repeated fashion.
If you're merely worried about a potential memory leak, the way to check for it is to run your function in a loop and check whether memory occupation is constantly increasing, or if it quickly reaches a stable plateau.
asfimport commentedon Jan 4, 2021
Joris Van den Bossche / @jorisvandenbossche:
Given that this comes up from time to time, it might be useful to document this to some extent: expectations around watching memory usage (explaining that the deallocated memory might be cached by the memory allocator etc), how you can actually see how much memory is used (total_allocated_bytes), how you can check if high "apparent" memory usage is indeed related to this and not caused by a memory leak (use pa.jemalloc_set_decay_ms(0); run your function many times in a loop and see it stabilizes or keeps constantly growing), ..
asfimport commentedon Feb 5, 2021
Dmitry Kashtanov:
I have a somewhat similar issue observed both on
pyarrowv1.0.0 and v3.0.0 in Linux (within Docker containers,python:3.8-slim-based image, local and AWS Fargate). The issue is with reading from BigQuery with BigQuery Storage API using ARROW data format. Under the hood it downloads a set of RecordBatches and combines them into a Table. After this in my code the Table is converted to a pandas DataFrame and then deleted, but the Table's memory is not released to OS.This behavior remains also if I use
mimallocorsystem-based pools set either in code or viaARROW_DEFAULT_MEMORY_POOLenvironment variable.Also after that I drop a referenced column (not copied) from that pandas DataFrame, this results in DataFrame data copy and the memory from the original DataFrame is also not released to OS. The subsequent transformations of the DataFrame release memory as expected.
The exactly same code with exactly same Python (3.8.7) and packages versions on MacOS releases memory to OS as expected (also will all kinds of the memory pool).
The very first lines of the script are:
Mac OS:
Linux (python:3.8-slim``-based image):A case with dropping a referenced (not copied) column:
Package versions:
asfimport commentedon Feb 5, 2021
Antoine Pitrou / @pitrou:
As you can see, the memory was returned to the allocator ("0 allocated"). The allocator is then free to return those pages to the OS or not.
Also, how is "Mem usage" measured in your script?
asfimport commentedon Feb 5, 2021
Dmitry Kashtanov:
"Mem usage" is by
memory_profiler.And as we may see, the following line doesn't help.
pyarrow.jemalloc_set_decay_ms(0)
asfimport commentedon Feb 5, 2021
Antoine Pitrou / @pitrou:
That doesn't really answer the question: what does it measure? RSS? Virtual memory size?
Perhaps, but I still don't see what Arrow could do, or even if there is an actual problem.
Can you run "bqs_stream_to_pandas" in a loop and see whether memory usage increases? Or does it stay stable as its initial peak value?
asfimport commentedon Feb 5, 2021
Dmitry Kashtanov:
Specifying the above environment variable also doesn't help for jemalloc.
The suspicious things are that everything works in MacOS and that also that all allocators behave similarly.
asfimport commentedon Feb 5, 2021
Dmitry Kashtanov:
It looks like
memory_profileruses the first item from the tuple returned bypsutil.Process().memory_info()which isrss.PSB. It doesn't increase (almost).
Interestingly, the first chunk of memory is freed when gRPC connection/session (may call it incorrecty) is reset:
If a
messageisgoogle.protobufmessage and a batch is created like below, will it be a zero-copy operation?asfimport commentedon Feb 5, 2021
Antoine Pitrou / @pitrou:
Ah, I didn't know that gRPC was involved. Since Arrow returned all the memory it had allocated, it's quite possible that the memory is held at the gRPC level.
Hmm... I guess it probably should? But I think you may find more expertise about this by asking the BigQuery developers / community.
asfimport commentedon Feb 6, 2021
Dmitry Kashtanov:
It looks like it's a zero-copy operation since after
pyarrow.Tablecreation and beforepandas.DataFramecreation, pyarrow reports zero prior memory allocation (both in Linux and MacOS):So with this, it looks like we have the following container sequence:
a list of
pyarrow.RecordBatches backed by memory allocated bygoogle.protobufpyarrow.Tablebacked by (most likely, exactly the same) memory allocated bygoogle.protobufthen,
pandas.DataFramebacked by memory allocated bypyarrowthen, after a column drop,
pandas.DataFramebacked by memory allocated bypandas/numpySo my current assumption is that
google.protobufuses a memory allocator for Linux, different from the one used for MacOS. The former one can be Google's TCMalloc (which is Linux only).asfimport commentedon Mar 3, 2021
shadowdsp:
I have the similar issue in
nested dataon Ubuntu16.04 pyarrow v3.0, even if I setpa.jemalloc_set_decay_ms(0). Butnon-nested datacan work well.Here is my script:
Output:
dfandtablecannot fully release in this case.pkg info
asfimport commentedon Mar 4, 2021
Weston Pace / @westonpace:
[~shadowdsp]Thanks for the great reproducible test case. I worked on this today and believe it is different than the problem described earlier in this issue. I have created ARROW-11855 to track your bug.4 remaining items
asfimport commentedon Aug 17, 2022
Antoine Pitrou / @pitrou:
[~skorepaj]Can you try callingpa.jemalloc_memory_pool().release_unused()after each call toload_parquet_to_table?asfimport commentedon Aug 17, 2022
Jan Skorepa:
@pitrou Thanks for your fast reply. Unfortunately it has no effect.
asfimport commentedon Aug 17, 2022
Ninh Chu:
Hi, I also encounter memory problem in v9.0.0. But in my case, the memory pool is scaled with dataset size, even I tried to limit batch size. Based on the document, RecordBatchReader is the safe way to read dataset big dataset. But in my case, if the memory scales with dataset size, it counters the purpose of Dataset and RecordBatchReader.
I'm running on Ubuntu20.04 / WSL2
The results are interesting:
Small dataset
Big dataset created by duplicating the same file 4 times
If load all the data in dataset into Table:
asfimport commentedon Nov 9, 2022
Julius Uotila:
Hi,
I am having the exact same issue as Jan Skorepa, but with Windows/Windows Server.
I have a process building a dataset overnight from SQL database to .parquet with a predefined save interval (does 30+ saves a night) and limited memory. Each save is slowly creeping up memory until process crashes.
python 3.9.12
pyarrow 9.0.0
Windows Server 2019
Windows 10
Many thanks,
Julius
asfimport commentedon Nov 9, 2022
wondertx:
Also encountered memory leak when using
pyarrow.fs.HadoopFileSystem.open_input_streamdxe4 commentedon Feb 8, 2023
hi, i was profiling this and i spotted that in
pyarrow/array.pxideduplicate_objects has a default value set to true but the docs say its false. so what is the expected default?arrow/python/pyarrow/array.pxi
Line 724 in fc1f9eb
arrow/python/pyarrow/array.pxi
Line 690 in fc1f9eb
the memory goes down when its false.
westonpace commentedon Feb 9, 2023
@dxe4 this is a rather old issue (perhaps we should close it) and not necessarily getting much attention. It's also not clear this issue is related to deduplicate_objects. Can you open a new issue, specific to your deduplicate_objects question?
ales-vilchytski commentedon Feb 26, 2024
Encountered highly likely same issue
Our use case:
I can't provide our data or code, but I created a repository with smallest possible scripts to reproduce issue, it can be found here: https://github.com/ales-vilchytski/pyarrow-parquet-memory-leak-demo. Repository includes scripts to generate parquet file and to reproduce OOM, Dockerfile and instructions how to run it.
Issue reproduces on pyarrow (13, 14) and pandas 2+, different docker images, native MacOS ARM 13, different python version (3.10, 3.11, 3.12).
Core thing (https://github.com/ales-vilchytski/pyarrow-parquet-memory-leak-demo/blob/main/src/mem_leak.py#L10):
As example:
With 12GB memory limit script iterates about 5 times before get killed by OOM (Docker, WSL2 Ubuntu 22.04 with 16GB memory)
Also I experimented with jemalloc settings and found that
JE_ARROW_MALLOC_CONF=abort_conf:true,confirm_conf :true,retain:false,background_thread:true,dirty_decay_ms:0,muzzy_decay_ms:0,lg_extent_max_active_fit:2works a bit better.Parquet file in example is written with
objecttypes by default (https://github.com/ales-vilchytski/pyarrow-parquet-memory-leak-demo/blob/main/src/gen_parquet.py) but writingstringexplicitly delays OOM slightly.Any attempt to fix things by triggering GC, clearing memory pools or switching to system memory allocator failed. It still gets OOM but just earlier or later.
kyle-ip commentedon Mar 23, 2024
Hi @ales-vilchytski ,
Have you fixed this yet? I encountered similar issue.
Every time I used pyarrow.parquet.ParquetDataset to load parquet file from S3, the memory usage of the service continued to increase and cannot be released, so I used release_unused after the I/O operations.
However, the occupied memory cannot be released immediately until the next time I executed an I/O operation.
On the other hand, it’s not sure how much memory can be released.
I was wondering if you have a solution? Thanks.
ales-vilchytski commentedon Mar 25, 2024
Hello @kyle-ip.
Unfortunately we've found workarounds only: use explicit
stringtype instead ofobjectwhere possible, split large files and process data chunk by chunk, process chunks in separate processes (e.g. multiprocessing) if possible.It makes things harder to implement, but works in our case (at least for now)
JEM-Mosig commentedon Jul 15, 2024
Are people still working on this? It is preventing us from even considering parquet as a file format, even though in theory it'd be perfect for our needs.
kellyyke commentedon Jul 24, 2025
what fixed it for me was based on this issue: #45504 (comment)
Setting
ARROW_DEFAULT_MEMORY_POOL=jemallocand thenpa.jemalloc_set_decay_ms(0)AlenkaF commentedon Jul 1, 2026
There are quite some issues opened on memory leak/memory allocation connected to Arrow and Parquet. I think the best thread to help one understand the topic and to keep open is #44599. I will close others as duplicate. Feel free to comment and I will re-open if we see I was mistaken and the issues are different.