Fix intermittent failures in the LeakTracer on 5.18+, remove all workarounds
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest / Util / LeakTracer.pm
CommitLineData
218b7c12 1package DBICTest::Util::LeakTracer;
2
3use warnings;
4use strict;
5
6use Carp;
96577657 7use Scalar::Util qw(isweak weaken blessed reftype);
8433421f 8use DBIx::Class::_Util qw(refcount hrefaddr refdesc);
556c4fe6 9use DBIx::Class::Optional::Dependencies;
96577657 10use Data::Dumper::Concise;
218b7c12 11use DBICTest::Util 'stacktrace';
556c4fe6 12use constant {
13 CV_TRACING => DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks_heavy'),
14};
218b7c12 15
16use base 'Exporter';
bf302897 17our @EXPORT_OK = qw(populate_weakregistry assert_empty_weakregistry visit_refs);
218b7c12 18
19my $refs_traced = 0;
96577657 20my $leaks_found = 0;
218b7c12 21my %reg_of_regs;
22
23sub populate_weakregistry {
96577657 24 my ($weak_registry, $target, $note) = @_;
218b7c12 25
26 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
27 croak 'Target is not a reference' unless length ref $target;
28
96577657 29 my $refaddr = hrefaddr $target;
8fa57d17 30
96577657 31 # a registry could be fed to itself or another registry via recursive sweeps
32 return $target if $reg_of_regs{$refaddr};
218b7c12 33
85ad63df 34 weaken( $reg_of_regs{ hrefaddr($weak_registry) } = $weak_registry )
35 unless( $reg_of_regs{ hrefaddr($weak_registry) } );
36
37 # an explicit "garbage collection" pass every time we store a ref
38 # if we do not do this the registry will keep growing appearing
39 # as if the traced program is continuously slowly leaking memory
40 for my $reg (values %reg_of_regs) {
41 (defined $reg->{$_}{weakref}) or delete $reg->{$_}
42 for keys %$reg;
43 }
44
96577657 45 if (! defined $weak_registry->{$refaddr}{weakref}) {
46 $weak_registry->{$refaddr} = {
8fa57d17 47 stacktrace => stacktrace(1),
96577657 48 weakref => $target,
8fa57d17 49 };
96577657 50 weaken( $weak_registry->{$refaddr}{weakref} );
8fa57d17 51 $refs_traced++;
218b7c12 52 }
53
8433421f 54 my $desc = refdesc $target;
96577657 55 $weak_registry->{$refaddr}{slot_names}{$desc} = 1;
56 if ($note) {
57 $note =~ s/\s*\Q$desc\E\s*//g;
58 $weak_registry->{$refaddr}{slot_names}{$note} = 1;
59 }
60
218b7c12 61 $target;
62}
63
96577657 64# Regenerate the slots names on a thread spawn
218b7c12 65sub CLONE {
66 my @individual_regs = grep { scalar keys %{$_||{}} } values %reg_of_regs;
67 %reg_of_regs = ();
68
69 for my $reg (@individual_regs) {
96577657 70 my @live_slots = grep { defined $_->{weakref} } values %$reg
218b7c12 71 or next;
cf8fa286 72
cf8fa286 73 $reg = {}; # get a fresh hashref in the new thread ctx
96577657 74 weaken( $reg_of_regs{hrefaddr($reg)} = $reg );
218b7c12 75
96577657 76 for my $slot_info (@live_slots) {
77 my $new_addr = hrefaddr $slot_info->{weakref};
8fa57d17 78
96577657 79 # replace all slot names
80 $slot_info->{slot_names} = { map {
81 my $name = $_;
82 $name =~ s/\(0x[0-9A-F]+\)/sprintf ('(%s)', $new_addr)/ieg;
83 ($name => 1);
84 } keys %{$slot_info->{slot_names}} };
218b7c12 85
96577657 86 $reg->{$new_addr} = $slot_info;
218b7c12 87 }
88 }
89}
90
556c4fe6 91sub visit_refs {
92 my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
93
94 $args->{seen_refs} ||= {};
95
96 my $visited_cnt = '0E0';
97 for my $i (0 .. $#{$args->{refs}} ) {
556c4fe6 98
a42634cd 99 next unless length ref $args->{refs}[$i]; # not-a-ref
556c4fe6 100
a42634cd 101 my $addr = hrefaddr $args->{refs}[$i];
556c4fe6 102
6ae62c5c 103 # no diving into weakregistries
a42634cd 104 next if $reg_of_regs{$addr};
556c4fe6 105
a42634cd 106 next if $args->{seen_refs}{$addr}++;
556c4fe6 107 $visited_cnt++;
a42634cd 108
109 my $r = $args->{refs}[$i];
110
556c4fe6 111 $args->{action}->($r) or next;
112
6ae62c5c 113 # This may end up being necessarry some day, but do not slow things
114 # down for now
115 #if ( defined( my $t = tied($r) ) ) {
116 # $visited_cnt += visit_refs({ %$args, refs => [ $t ] });
117 #}
118
a42634cd 119 my $type = reftype $r;
120
7664b1a0 121 local $@;
122 eval {
7664b1a0 123 if ($type eq 'HASH') {
124 $visited_cnt += visit_refs({ %$args, refs => [ map {
125 ( !isweak($r->{$_}) ) ? $r->{$_} : ()
126 } keys %$r ] });
127 }
128 elsif ($type eq 'ARRAY') {
129 $visited_cnt += visit_refs({ %$args, refs => [ map {
130 ( !isweak($r->[$_]) ) ? $r->[$_] : ()
131 } 0..$#$r ] });
132 }
133 elsif ($type eq 'REF' and !isweak($$r)) {
134 $visited_cnt += visit_refs({ %$args, refs => [ $$r ] });
135 }
136 elsif (CV_TRACING and $type eq 'CODE') {
137 $visited_cnt += visit_refs({ %$args, refs => [ map {
138 ( !isweak($_) ) ? $_ : ()
627d2b3d 139 } values %{ scalar PadWalker::closed_over($r) } ] }); # scalar due to RT#92269
7664b1a0 140 }
141 1;
8433421f 142 } or warn "Could not descend into @{[ refdesc $r ]}: $@\n";
556c4fe6 143 }
144 $visited_cnt;
145}
146
a42634cd 147sub visit_namespaces {
148 my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
556c4fe6 149
a42634cd 150 my $visited = 1;
218b7c12 151
a42634cd 152 $args->{package} ||= '::';
153 $args->{package} = '::' if $args->{package} eq 'main';
de4705b7 154
a42634cd 155 if ( $args->{action}->($args->{package}) ) {
218b7c12 156
a42634cd 157 my $base = $args->{package};
158 $base = '' if $base eq '::';
218b7c12 159
218b7c12 160
a42634cd 161 $visited += visit_namespaces({ %$args, package => $_ }) for map
8d73fcd4 162 { $_ =~ /(.+?)::$/ ? "${base}::$1" : () }
a42634cd 163 grep
164 { $_ =~ /(?<!^main)::$/ }
165 do { no strict 'refs'; keys %{ $base . '::'} }
96577657 166 }
218b7c12 167
a42634cd 168 return $visited;
169}
170
171# compiles a list of addresses stored as globals (possibly even catching
172# class data in the form of method closures), so we can skip them further on
173sub symtable_referenced_addresses {
174
175 my $refs_per_pkg;
176
a42634cd 177 my $seen_refs = {};
178 visit_namespaces(
179 action => sub {
556c4fe6 180
556c4fe6 181 no strict 'refs';
556c4fe6 182
a42634cd 183 my $pkg = shift;
184 $pkg = '' if $pkg eq '::';
185 $pkg .= '::';
186
556c4fe6 187 # the unless regex at the end skips some dangerous namespaces outright
188 # (but does not prevent descent)
a42634cd 189 $refs_per_pkg->{$pkg} += visit_refs (
556c4fe6 190 seen_refs => $seen_refs,
a42634cd 191
627d2b3d 192 action => sub { 1 },
a42634cd 193
556c4fe6 194 refs => [ map { my $sym = $_;
195 # *{"$pkg$sym"}{CODE} won't simply work - MRO-cached CVs are invisible there
196 ( CV_TRACING ? Class::MethodCache::get_cv("${pkg}$sym") : () ),
197
198 ( defined *{"$pkg$sym"}{SCALAR} and length ref ${"$pkg$sym"} and ! isweak( ${"$pkg$sym"} ) )
199 ? ${"$pkg$sym"} : ()
200 ,
a42634cd 201
556c4fe6 202 ( map {
203 ( defined *{"$pkg$sym"}{$_} and ! isweak(defined *{"$pkg$sym"}{$_}) )
204 ? *{"$pkg$sym"}{$_}
205 : ()
206 } qw(HASH ARRAY IO GLOB) ),
a42634cd 207
556c4fe6 208 } keys %$pkg ],
209 ) unless $pkg =~ /^ :: (?:
210 DB | next | B | .+? ::::ISA (?: ::CACHE ) | Class::C3
211 ) :: $/x;
a42634cd 212 }
213 );
556c4fe6 214
a42634cd 215# use Devel::Dwarn;
216# Ddie [ map
217# { { $_ => $refs_per_pkg->{$_} } }
218# sort
219# {$refs_per_pkg->{$a} <=> $refs_per_pkg->{$b} }
220# keys %$refs_per_pkg
221# ];
222
223 $seen_refs;
224}
225
226sub assert_empty_weakregistry {
227 my ($weak_registry, $quiet) = @_;
228
8d73fcd4 229 Sub::Defer::undefer_all();
230
a42634cd 231 # in case we hooked bless any extra object creation will wreak
232 # havoc during the assert phase
233 local *CORE::GLOBAL::bless;
234 *CORE::GLOBAL::bless = sub { CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() ) };
235
236 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
237
238 defined $weak_registry->{$_}{weakref} or delete $weak_registry->{$_}
239 for keys %$weak_registry;
240
241 return unless keys %$weak_registry;
8fa57d17 242
a42634cd 243 my $tb = eval { Test::Builder->new }
244 or croak "Calling assert_empty_weakregistry in $0 without a loaded Test::Builder makes no sense";
8fa57d17 245
a42634cd 246 for my $addr (keys %$weak_registry) {
247 $weak_registry->{$addr}{display_name} = join ' | ', (
248 sort
249 { length $a <=> length $b or $a cmp $b }
250 keys %{$weak_registry->{$addr}{slot_names}}
251 );
252
253 $tb->BAILOUT("!!!! WEAK REGISTRY SLOT $weak_registry->{$addr}{display_name} IS NOT A WEAKREF !!!!")
254 if defined $weak_registry->{$addr}{weakref} and ! isweak( $weak_registry->{$addr}{weakref} );
255 }
256
8d73fcd4 257 # the symtable walk is very expensive
258 # if we are $quiet (running in an END block) we do not really need to be
259 # that thorough - can get by with only %Sub::Quote::QUOTED
260 delete $weak_registry->{$_} for $quiet
261 ? do {
262 my $refs = {};
263 visit_refs (
264 # only look at the closed over stuffs
265 refs => [ grep { length ref $_ } map { values %{$_->[2]} } grep { ref $_ eq 'ARRAY' } values %Sub::Quote::QUOTED ],
266 seen_refs => $refs,
267 action => sub { 1 },
268 );
269 keys %$refs;
270 }
271 : (
272 # full sumtable walk, starting from ::
273 keys %{ symtable_referenced_addresses() }
274 )
275 ;
556c4fe6 276
96577657 277 for my $addr (sort { $weak_registry->{$a}{display_name} cmp $weak_registry->{$b}{display_name} } keys %$weak_registry) {
278
1a44a267 279 next if ! defined $weak_registry->{$addr}{weakref};
280
5dc4301c 281 $leaks_found++ unless $tb->in_todo;
ee20ecfc 282 $tb->ok (0, "Expected garbage collection of $weak_registry->{$addr}{display_name}");
1a44a267 283
284 my $diag = do {
285 local $Data::Dumper::Maxdepth = 1;
286 sprintf "\n%s (refcnt %d) => %s\n",
287 $weak_registry->{$addr}{display_name},
288 refcount($weak_registry->{$addr}{weakref}),
289 (
290 ref($weak_registry->{$addr}{weakref}) eq 'CODE'
291 and
292 B::svref_2object($weak_registry->{$addr}{weakref})->XSUB
293 ) ? '__XSUB__' : Dumper( $weak_registry->{$addr}{weakref} )
294 ;
218b7c12 295 };
1a44a267 296
5dc4301c 297 # FIXME - need to add a circular reference seeker based on the visitor
298 # (will need a bunch of modifications, punting with just a stub for now)
299
556c4fe6 300 $diag .= Devel::FindRef::track ($weak_registry->{$addr}{weakref}, 50) . "\n"
1a44a267 301 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
302
303 $diag =~ s/^/ /mg;
304
305 if (my $stack = $weak_registry->{$addr}{stacktrace}) {
306 $diag .= " Reference first seen$stack";
307 }
308
309 $tb->diag($diag);
6ae62c5c 310
311# if ($leaks_found == 1) {
312# # using the fh dumper due to intermittent buffering issues
313# # in case we decide to exit soon after (possibly via _exit)
314# require Devel::MAT::Dumper;
315# local $Devel::MAT::Dumper::MAX_STRING = -1;
316# open( my $fh, '>:raw', "leaked_${addr}_pid$$.pmat" ) or die $!;
317# Devel::MAT::Dumper::dumpfh( $fh );
318# close ($fh) or die $!;
319#
320# use POSIX;
321# POSIX::_exit(1);
322# }
1a44a267 323 }
324
5dc4301c 325 if (! $quiet and !$leaks_found and ! $tb->in_todo) {
1a44a267 326 $tb->ok(1, sprintf "No leaks found at %s line %d", (caller())[1,2] );
218b7c12 327 }
328}
329
330END {
b77a61d8 331 if (
332 $INC{'Test/Builder.pm'}
333 and
334 my $tb = do {
335 local $@;
336 my $t = eval { Test::Builder->new }
337 or warn "Test::Builder->new failed:\n$@\n";
338 $t;
339 }
340 ) {
218b7c12 341 # we check for test passage - a leak may be a part of a TODO
342 if ($leaks_found and !$tb->is_passing) {
343
344 $tb->diag(sprintf
345 "\n\n%s\n%s\n\nInstall Devel::FindRef and re-run the test with set "
346 . '$ENV{TEST_VERBOSE} (prove -v) to see a more detailed leak-report'
347 . "\n\n%s\n%s\n\n", ('#' x 16) x 4
348 ) if ( !$ENV{TEST_VERBOSE} or !$INC{'Devel/FindRef.pm'} );
349
350 }
351 else {
352 $tb->note("Auto checked $refs_traced references for leaks - none detected");
353 }
cbd7f87a 354
cbd7f87a 355 # also while we are here and not in plain runmode: make sure we never
356 # loaded any of the strictures XS bullshit (it's a leak in a sense)
8ab47674 357 unless (
358 $ENV{MOO_FATAL_WARNINGS}
359 or
360 # FIXME - SQLT loads strictures explicitly, /facedesk
361 # remove this INC check when 0fb58589 and 45287c815 are rectified
362 $INC{'SQL/Translator.pm'}
363 or
364 DBICTest::RunMode->is_plain
365 ) {
cbd7f87a 366 for (qw(indirect multidimensional bareword::filehandles)) {
367 exists $INC{ Module::Runtime::module_notional_filename($_) }
368 and
ee20ecfc 369 $tb->ok(0, "$_ load should not have been attempted!!!" )
cbd7f87a 370 }
371 }
218b7c12 372 }
373}
374
3751;