Skip to content
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

Replace wrapTransversable generators to prevent memory leaks #2709

Merged
merged 4 commits into from
Dec 19, 2024

Conversation

GromNaN
Copy link
Member

@GromNaN GromNaN commented Dec 18, 2024

Q A
Type bug
BC Break no
Fixed issues #2105

Problem

A non-static generator created with a method of a class instance holds the reference to this instance. When assigned to a property of this instance, this creates a circular reference (instance -> generator -> instance). The reference is destroyed only when the generator is exhausted.

Most of the time, when the memory limit is sufficient, this is not an issue. The garbage collector should remove this circular references, but it runs automatically only when reaching the GC_THRESHOLD_DEFAULT.

When working with a MongoDB Cursor, this is a single object which can fill up a lot of memory, that explains why gc_collect_cycles() is not run automatically.

Solution

Using IteratorIterator instead of Generator, we remove this circular reference . Also, in find the code simpler.
Same as mongodb/mongo-php-library#694

Demonstration

In the following example, if gc_collect_cycles() is not called in the loop, we can see the memory leak. When calling gc_collect_cycles() explicitly, we can see 300 "collected" references. The memory leak disappears when the Generator is replaced by an IteratorIterator.

Source code
<?php

namespace Hell;

class Iterator implements \Iterator
{
    private iterable $iterator;

    public function __construct(\Traversable $data)
    {
        $this->iterator = $this->wrapTraversable($data);
        //$this->iterator = new \IteratorIterator($data);
    }

    public function current(): mixed
    {
        return $this->iterator->current();
    }

    public function next(): void
    {
        $this->iterator->next();
    }

    public function key(): mixed
    {
        return $this->iterator->key();
    }

    public function valid(): bool
    {
        return $this->iterator->valid();
    }

    public function rewind(): void
    {
        $this->iterator->rewind();
    }

    private function wrapTraversable(iterable $data): \Generator
    {
        foreach ($data as $key => $value) {
            yield $key => $value;
        }
    }
}

foreach (range(0, 100) as $i) {
    $data = new \ArrayObject(array_fill(0, 1_000_00, bin2hex(random_bytes(1_000))));
    $iterator = new Iterator($data);
    $iterator->next();
    unset($data);
    echo (memory_get_usage()).PHP_EOL;
}

gc_collect_cycles();
print_r(gc_status());


private bool $iteratorAdvanced = false;

private bool $iteratorExhausted = false;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced by setting $iterator = null, as it's already done for UnrewindableIterator

$this->storeCurrentItem();
$this->iterator = new IteratorIterator($iterator);
$this->iterator->rewind();
if ($this->iterator->valid()) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This checks for a dead cursor.

Copy link
Member

@alcaeus alcaeus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work refactoring this. I've left a suggestion to refactor storeCurrentItems to consolidate some logic, but LGTM aside from that.

@alcaeus alcaeus added this to the 2.9.1 milestone Dec 19, 2024
@GromNaN GromNaN merged commit ad7827c into doctrine:2.9.x Dec 19, 2024
16 checks passed
@GromNaN GromNaN deleted the generator-mem-leak branch December 19, 2024 09:54
@GromNaN GromNaN added the Bug label Dec 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants