Visitar URL original
Potential memory leak from `TextIOWrapper` which would hold unnecessary number of arenas · Issue #104954 · python/cpython · GitHub
The Wayback Machine - https://web.archive.org/web/20250509015126/https://github.com/python/cpython/issues/104954
Skip to content

Potential memory leak from TextIOWrapper which would hold unnecessary number of arenas #104954

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
itachaaa opened this issue May 26, 2023 · 16 comments
Labels
topic-IO type-bug An unexpected behavior, bug, or error

Comments

@itachaaa
Copy link

itachaaa commented May 26, 2023 •

sample code:

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import json
import time


def loads_json_from_file(content):
    if not content:
        return None
    return json.loads(content)


def generate():
    members = []
    for i in range(200):
        with open("./2.json", 'r') as fb:
            member = loads_json_from_file(fb.read())
        members.append(member)
    del members
    import gc; gc.collect()


if __name__ == '__main__':
    generate()
    while 1:
        time.sleep(10)

Use python -m memray run json_rep.py to generate flamefile:
image

Bug report

Theoretically, the del variables should not occupy any memory. However, the printed flame chart shows that the memory applied for by json.loads is not released, which seems to cause memory leakage.

Your environment

env:
└─$ uname -a
Linux DESKTOP-IEKI9L0 5.15.90.1-microsoft-standard-WSL2 #1 SMP Fri Jan 27 02:56:13 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux
└─$ python --version
Python 3.10.6

  • CPython versions tested on: Python 3.10.6
  • Operating system and architecture: Linux DESKTOP-IEKI9L0 5.15.90.1-microsoft-standard-WSL2 Support "bpo-" in Misc/NEWS #1 SMP Fri Jan 27 02:56:13 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux
@itachaaa itachaaa added the type-bug An unexpected behavior, bug, or error label May 26, 2023
@gaogaotiantian
Copy link
Member

gaogaotiantian commented May 26, 2023 •

I was wondering if this is an inaccurate(delayed) report from memray. Can you run this program for a long time and see if the memory it actually allocated is increasing over time? Using ps or any tool you prefer. The memory allocation mechanism in Python is not trivial so we better make sure this is a valid leak.

@hauntsaninja
Copy link
Contributor

Could you also try del member or move the gc.collect() into your main code instead of inside generate?

@itachaaa
Copy link
Author

I was wondering if this is an inaccurate(delayed) report from memray. Can you run this program for a long time and see if the memory it actually allocated is increasing over time? Using ps or any tool you prefer. The memory allocation mechanism in Python is not trivial so we better make sure this is a valid leak.

  1. For a long time see if the memory increasing. This won't happen, for there is no other action other than sleep. It looks more like the memory requested when using json.loads is not freed, and that's it.I was running it from 12:00 to 14:00, and I can see that the memory has not been released over time.The flame map was collected at 14 o'clock.
    image
    image
    image

@itachaaa
Copy link
Author

And I tried another way:
Run the preceding two .py scripts. One file is large and the other is small. Theoretically, the memory occupied by the two programs should be consistent with the memory reclaiming after a period of time. Actually, the memory occupied by the two programs is still high and the memory occupied by the two programs is low. By the way, I used ps -aux to observe the memory usage of both processes.

@itachaaa
Copy link
Author

Could you also try del member or move the gc.collect() into your main code instead of inside generate?

There doesn't seem to be much difference in memory usage, just some differences in the stacks on the flame chart.
image
image

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import json
import time


def loads_json_from_file(content):
    if not content:
        return None
    return json.loads(content)


def generate():
    members = []
    for i in range(200):
        with open("./2.json", 'r') as fb:
            member = loads_json_from_file(fb.read())
        members.append(member)
    del members


if __name__ == '__main__':
    generate()
    import gc; gc.collect()
    while 1:
        time.sleep(10)

@gaogaotiantian
Copy link
Member

@gaogaotiantian member and members arent the same variable.

Ah that was my fault! Thanks!

@gaogaotiantian
Copy link
Member

And I tried another way: Run the preceding two .py scripts. One file is large and the other is small. Theoretically, the memory occupied by the two programs should be consistent with the memory reclaiming after a period of time.

Well actually no. Like I said, memory management in CPython is complicated. If I understand correctly, CPython has an extra layer of internal memory management system for small objects(I think the threashold is 512 bytes but I might be wrong). Instead of allocating/freeing memory frequently on small objects, CPython allocates a large chunk of memory from the OS and distribute them internally. For json.load, it would create a lot of small objects with different sizes - CPython will have "pools" for them, but when they are "deallocated", the memory is not "freed"(sorry for so many quotes) to the OS - CPython still has control over it.

This is a bit over-complicated than what we need here - the point is, if you load a large json file vs a small one, it's expected that even after all the objects are "freed", the process with the large one takes more memory than the one with the small one. However, it should not still take the same amount of memory before it deallocates the json object.

I'll do some experiment myself and see if I can find anything interesting.

@itachaaa
Copy link
Author

And I tried another way: Run the preceding two .py scripts. One file is large and the other is small. Theoretically, the memory occupied by the two programs should be consistent with the memory reclaiming after a period of time.

Well actually no. Like I said, memory management in CPython is complicated. If I understand correctly, CPython has an extra layer of internal memory management system for small objects(I think the threashold is 512 bytes but I might be wrong). Instead of allocating/freeing memory frequently on small objects, CPython allocates a large chunk of memory from the OS and distribute them internally. For json.load, it would create a lot of small objects with different sizes - CPython will have "pools" for them, but when they are "deallocated", the memory is not "freed"(sorry for so many quotes) to the OS - CPython still has control over it.

This is a bit over-complicated than what we need here - the point is, if you load a large json file vs a small one, it's expected that even after all the objects are "freed", the process with the large one takes more memory than the one with the small one. However, it should not still take the same amount of memory before it deallocates the json object.

I'll do some experiment myself and see if I can find anything interesting.

Well, I see what you mean. The memory applied for in the early stage is maintained in the memory pool. If this is normal, is there any method to forcibly release the memory?

@gaogaotiantian
Copy link
Member

Well, I see what you mean. The memory applied for in the early stage is maintained in the memory pool. If this is normal, is there any method to forcibly release the memory?

There's still something wrong with it, I'm trying to investigate now - but it's not about json.loads, it's about open(). Could you try to move your open() function outside of your for loop - only read the raw string from file once, but still do json.loads to parse it in the loop - and see if you have the same experience?

To answer your question - there's no way to forcibly free the memory, but if everything works properly, the memory residue should be significantly smaller.

@itachaaa
Copy link
Author

Indeed, if I open a larger file and put open out of the loop, the memory does drop off a bit. However, if I open a different file each time, I can't put it outside the loop, and the memory is still high.

@gaogaotiantian
Copy link
Member

gaogaotiantian commented May 26, 2023 •

I spent a couple of hours on this and hit a dead end - I'm out of ideas now but I do have some findings. I'll share my findings and hopefully help others to solve this.

First of all, this is not gaslighting, it's a real issue.

If you track the arenas left after the code ends(when it hits the infinite loop), you'll find that the number of arenas will be increasing about linearly with the number of loops above(where it opens a file and does a (json.loads)). This (I think) is an indicator that a very small piece of memory is leaked every loop. To load the json object, we need a lot of arenas, and one of them has the leaked(not untracked) piece of memory and can't be freed when the json object is deallocated.

The problem is not json.loads, it's just a good environment where a lot of small objects are created. The problem is open(), to be more specific, TextIOWrapper. You can reproduce this issue with the code below:

def generate():
    members = []
    with open("./test.json", 'r') as fb:
        content = fb.read()
    for i in range(50):
        # Notice that without TextIOWrapper, the problem won't reproduce
        a = io.TextIOWrapper(io.BufferedReader(io.StringIO("abc")))
        members.append(json.loads(content))
    del members

I digged into the code of TextIOWrapper, and found the holy switch to toggle the behavior reliably - codecs.c:277.

If you set the error and return -1 before this line, the issue is gone. If you set the error, DECREF the variable and return -1 after this line, the issue happens again. Of course, you'll need some mechanism to make sure in all other cases this function works.

Unfortunately, this indicates that one of the following things are happening:

  1. We have some weird memory leaking issue in GetAttrString in some rare cases(feels very unlikely as it's super widely used)
  2. Executing this line has some side effects which leads to a memory leak, which is hard to image for me.

The only remotely interesting fact about codec_info is that it's a derived tuple - but I don't see a difference there - it still uses PyObject_GenericGetAttr.

Even though I'd like to solve this issue, I ran out of ideas. It's hard for me to even come up with a theory. So, any help is welcome!

@terryjreedy
Copy link
Member

From the comment above, it seems the title should be changed.

@itachaaa
Copy link
Author

I tested it, and if you add

libc = ctypes.CDLL("libc.so.6")
return libc.malloc_trim(0)

The memory can be forcibly reclaimed, and the residual memory is reduced to a relatively low level.
Is this code available? Or if there's any risk

@gaogaotiantian
Copy link
Member

I tested it, and if you add

libc = ctypes.CDLL("libc.so.6")
return libc.malloc_trim(0)

The memory can be forcibly reclaimed, and the residual memory is reduced to a relatively low level. Is this code available? Or if there's any risk

I'm not 100% sure but I believe that equivalently reorganized the memory - the leaked memory is still there, but the impact is reduced. So you did not forcibly reclaim the memory, you just squeezed some potential available memory out from the heap(which might be there because of the leaking memory of course).

I can't tell about the risk either, it's a pretty low level API. In theory it should be safe. We still have the mystery to solve though, but this might relieve your practical issue.

@gaogaotiantian gaogaotiantian changed the title json.loads mem doen not release Potential memory leak from TextIOWrapper which would hold unnecessary number of arenas May 27, 2023
@sunmy2019
Copy link
Member

The memory can be forcibly reclaimed, and the residual memory is reduced to a relatively low level.
Is this code available?

What if memory is needed elsewhere in the program?

Also, what are in your guy's JSON files? I cannot reproduce with an empty JSON file.

@gaogaotiantian
Copy link
Member

I randomly created one - I believe the essential thing is to create a JSON file that will generate objects with different sizes, so I just created a JSON file with random size strings as keys and values and it worked.

It's possible that this is a corner case issue for arenas - I should confirm whether the left arenas are empty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic-IO type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

6 participants