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