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

Log: delete source from builder cache when finalize #14475

Conversation

ysbaddaden
Copy link
Contributor

@ysbaddaden ysbaddaden commented Apr 11, 2024

The cache of logs in Log::Builder is using a WeakRef for the Log object to not prevent the GC from collecting them, that would leak memory, but it keeps the hash entry, which also leaks, keeping strings (potentially dynamically allocated) along with entries in the hash (infinitely growing hash).

This patch adds a finalizer to Log, as suggested by @beta, to remove the log entry from the builder cache when a Log object is collected.

The runtime improvement for the sample from #14473 is dramatic. It looks almost flat with a mere 5s versus 67s for the current master at 100 000 iterations.

log_leak

Note: this is a workaround to fix the leak, that can be monkey-patched in applications that need it, not a proper solution to the problem.

The cache of logs in Log::Builder is using a WeakRef for the Log object
to not prevent the GC from collecting them, that would leak memory, but
it keeps the hash entry, which also leaks, keeping strings (potentially
dynamically allocated) along with entries in the hash (infinitely
growing hash).

This patch adds a finalizer to Log, as suggested by @beta, to remove the
log entry from the builder cache when a Log object is collected.
@ysbaddaden
Copy link
Contributor Author

ysbaddaden commented Apr 11, 2024

Oh, weird, the specs for log/spec broke...

The log instance may have been replaced, in which case we musn't delete
it from the cache.
@ysbaddaden
Copy link
Contributor Author

ysbaddaden commented Apr 11, 2024

Fixed: don't indiscriminately delete the log instances (oops) since it may have been replaced (of course).

I updated the chart but it doesn't show any visual difference.

@Blacksmoke16 Blacksmoke16 linked an issue Apr 12, 2024 that may be closed by this pull request
src/log/builder.cr Outdated Show resolved Hide resolved
@straight-shoota straight-shoota added this to the 1.13.0 milestone Apr 12, 2024
@straight-shoota straight-shoota merged commit 562fb7b into crystal-lang:master Apr 16, 2024
58 checks passed
@ysbaddaden ysbaddaden deleted the workaround/14473/log-hash-source-leak branch April 18, 2024 09:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Log stores keys (sources) indefinitively
2 participants