Fix long standing issue with resultset growth on repeated execution (GHPR#29)
[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);
dac7972a 8use DBIx::Class::_Util 'refcount';
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'),
10635a06 14 SKIP_SCALAR_REFS => ( $] > 5.017 ) ? 1 : 0,
556c4fe6 15};
218b7c12 16
17use base 'Exporter';
21aa86aa 18our @EXPORT_OK = qw(populate_weakregistry assert_empty_weakregistry hrefaddr visit_refs);
218b7c12 19
20my $refs_traced = 0;
96577657 21my $leaks_found = 0;
218b7c12 22my %reg_of_regs;
23
96577657 24sub hrefaddr { sprintf '0x%x', &Scalar::Util::refaddr }
25
26# so we don't trigger stringification
27sub _describe_ref {
28 sprintf '%s%s(%s)',
29 (defined blessed $_[0]) ? blessed($_[0]) . '=' : '',
30 reftype $_[0],
31 hrefaddr $_[0],
32 ;
33}
34
218b7c12 35sub populate_weakregistry {
96577657 36 my ($weak_registry, $target, $note) = @_;
218b7c12 37
38 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
39 croak 'Target is not a reference' unless length ref $target;
40
96577657 41 my $refaddr = hrefaddr $target;
8fa57d17 42
96577657 43 # a registry could be fed to itself or another registry via recursive sweeps
44 return $target if $reg_of_regs{$refaddr};
218b7c12 45
85ad63df 46 weaken( $reg_of_regs{ hrefaddr($weak_registry) } = $weak_registry )
47 unless( $reg_of_regs{ hrefaddr($weak_registry) } );
48
49 # an explicit "garbage collection" pass every time we store a ref
50 # if we do not do this the registry will keep growing appearing
51 # as if the traced program is continuously slowly leaking memory
52 for my $reg (values %reg_of_regs) {
53 (defined $reg->{$_}{weakref}) or delete $reg->{$_}
54 for keys %$reg;
55 }
56
10635a06 57 # FIXME/INVESTIGATE - something fishy is going on with refs to plain
58 # strings, perhaps something to do with the CoW work etc...
59 return $target if SKIP_SCALAR_REFS and reftype($target) eq 'SCALAR';
60
96577657 61 if (! defined $weak_registry->{$refaddr}{weakref}) {
62 $weak_registry->{$refaddr} = {
8fa57d17 63 stacktrace => stacktrace(1),
96577657 64 weakref => $target,
8fa57d17 65 };
96577657 66 weaken( $weak_registry->{$refaddr}{weakref} );
8fa57d17 67 $refs_traced++;
218b7c12 68 }
69
96577657 70 my $desc = _describe_ref($target);
71 $weak_registry->{$refaddr}{slot_names}{$desc} = 1;
72 if ($note) {
73 $note =~ s/\s*\Q$desc\E\s*//g;
74 $weak_registry->{$refaddr}{slot_names}{$note} = 1;
75 }
76
218b7c12 77 $target;
78}
79
96577657 80# Regenerate the slots names on a thread spawn
218b7c12 81sub CLONE {
82 my @individual_regs = grep { scalar keys %{$_||{}} } values %reg_of_regs;
83 %reg_of_regs = ();
84
85 for my $reg (@individual_regs) {
96577657 86 my @live_slots = grep { defined $_->{weakref} } values %$reg
218b7c12 87 or next;
cf8fa286 88
cf8fa286 89 $reg = {}; # get a fresh hashref in the new thread ctx
96577657 90 weaken( $reg_of_regs{hrefaddr($reg)} = $reg );
218b7c12 91
96577657 92 for my $slot_info (@live_slots) {
93 my $new_addr = hrefaddr $slot_info->{weakref};
8fa57d17 94
96577657 95 # replace all slot names
96 $slot_info->{slot_names} = { map {
97 my $name = $_;
98 $name =~ s/\(0x[0-9A-F]+\)/sprintf ('(%s)', $new_addr)/ieg;
99 ($name => 1);
100 } keys %{$slot_info->{slot_names}} };
218b7c12 101
96577657 102 $reg->{$new_addr} = $slot_info;
218b7c12 103 }
104 }
105}
106
556c4fe6 107sub visit_refs {
108 my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
109
110 $args->{seen_refs} ||= {};
111
112 my $visited_cnt = '0E0';
113 for my $i (0 .. $#{$args->{refs}} ) {
114 next if isweak($args->{refs}[$i]);
115
116 my $r = $args->{refs}[$i];
117
118 next unless length ref $r;
119
6ae62c5c 120 # no diving into weakregistries
121 next if $reg_of_regs{hrefaddr $r};
122
556c4fe6 123 next if $args->{seen_refs}{my $dec_addr = Scalar::Util::refaddr($r)}++;
124
125 $visited_cnt++;
126 $args->{action}->($r) or next;
127
6ae62c5c 128 # This may end up being necessarry some day, but do not slow things
129 # down for now
130 #if ( defined( my $t = tied($r) ) ) {
131 # $visited_cnt += visit_refs({ %$args, refs => [ $t ] });
132 #}
133
556c4fe6 134 my $type = reftype $r;
135 if ($type eq 'HASH') {
136 $visited_cnt += visit_refs({ %$args, refs => [ map {
137 ( !isweak($r->{$_}) ) ? $r->{$_} : ()
138 } keys %$r ] });
139 }
140 elsif ($type eq 'ARRAY') {
141 $visited_cnt += visit_refs({ %$args, refs => [ map {
142 ( !isweak($r->[$_]) ) ? $r->[$_] : ()
143 } 0..$#$r ] });
144 }
145 elsif ($type eq 'REF' and !isweak($$r)) {
146 $visited_cnt += visit_refs({ %$args, refs => [ $$r ] });
147 }
148 elsif (CV_TRACING and $type eq 'CODE') {
149 $visited_cnt += visit_refs({ %$args, refs => [ map {
150 ( !isweak($_) ) ? $_ : ()
151 } scalar PadWalker::closed_over($r) ] }); # scalar due to RT#92269
152 }
153 }
154 $visited_cnt;
155}
156
218b7c12 157sub assert_empty_weakregistry {
158 my ($weak_registry, $quiet) = @_;
159
556c4fe6 160 # in case we hooked bless any extra object creation will wreak
161 # havoc during the assert phase
162 local *CORE::GLOBAL::bless;
163 *CORE::GLOBAL::bless = sub { CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() ) };
164
218b7c12 165 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
166
167 return unless keys %$weak_registry;
168
169 my $tb = eval { Test::Builder->new }
556c4fe6 170 or croak "Calling assert_empty_weakregistry in $0 without a loaded Test::Builder makes no sense";
218b7c12 171
96577657 172 for my $addr (keys %$weak_registry) {
173 $weak_registry->{$addr}{display_name} = join ' | ', (
174 sort
175 { length $a <=> length $b or $a cmp $b }
176 keys %{$weak_registry->{$addr}{slot_names}}
177 );
218b7c12 178
96577657 179 $tb->BAILOUT("!!!! WEAK REGISTRY SLOT $weak_registry->{$addr}{display_name} IS NOT A WEAKREF !!!!")
180 if defined $weak_registry->{$addr}{weakref} and ! isweak( $weak_registry->{$addr}{weakref} );
181 }
218b7c12 182
556c4fe6 183 # compile a list of refs stored as globals (possibly even catching
184 # class data in the form of method closures), so we can skip them
185 # further on
186 my ($seen_refs, $classdata_refs) = ({}, undef);
187
188 # the walk is very expensive - if we are $quiet (running in an END block)
189 # we do not really need to be too thorough
190 unless ($quiet) {
191 my ($symwalker, $symcounts);
192 $symwalker = sub {
193 no strict 'refs';
194 my $pkg = shift || '::';
195
196 # any non-weak globals are "clasdata" in all possible sense
197 #
198 # the unless regex at the end skips some dangerous namespaces outright
199 # (but does not prevent descent)
200 $symcounts->{$pkg} += visit_refs (
201 seen_refs => $seen_refs,
202 action => sub { ++$classdata_refs->{hrefaddr $_[0]} },
203 refs => [ map { my $sym = $_;
204 # *{"$pkg$sym"}{CODE} won't simply work - MRO-cached CVs are invisible there
205 ( CV_TRACING ? Class::MethodCache::get_cv("${pkg}$sym") : () ),
206
207 ( defined *{"$pkg$sym"}{SCALAR} and length ref ${"$pkg$sym"} and ! isweak( ${"$pkg$sym"} ) )
208 ? ${"$pkg$sym"} : ()
209 ,
210 ( map {
211 ( defined *{"$pkg$sym"}{$_} and ! isweak(defined *{"$pkg$sym"}{$_}) )
212 ? *{"$pkg$sym"}{$_}
213 : ()
214 } qw(HASH ARRAY IO GLOB) ),
215 } keys %$pkg ],
216 ) unless $pkg =~ /^ :: (?:
217 DB | next | B | .+? ::::ISA (?: ::CACHE ) | Class::C3
218 ) :: $/x;
219
220 $symwalker->("${pkg}$_") for grep { $_ =~ /(?<!^main)::$/ } keys %$pkg;
221 };
8fa57d17 222
223 $symwalker->();
224
556c4fe6 225# use Devel::Dwarn;
226# Ddie [ map
227# { { $_ => $symcounts->{$_} } }
228# sort
229# {$symcounts->{$a} <=> $symcounts->{$b} }
230# keys %$symcounts
231# ];
8fa57d17 232 }
233
556c4fe6 234 delete $weak_registry->{$_} for keys %$classdata_refs;
235
96577657 236 for my $addr (sort { $weak_registry->{$a}{display_name} cmp $weak_registry->{$b}{display_name} } keys %$weak_registry) {
237
1a44a267 238 next if ! defined $weak_registry->{$addr}{weakref};
239
5dc4301c 240 $leaks_found++ unless $tb->in_todo;
1a44a267 241 $tb->ok (0, "Leaked $weak_registry->{$addr}{display_name}");
242
243 my $diag = do {
244 local $Data::Dumper::Maxdepth = 1;
245 sprintf "\n%s (refcnt %d) => %s\n",
246 $weak_registry->{$addr}{display_name},
247 refcount($weak_registry->{$addr}{weakref}),
248 (
249 ref($weak_registry->{$addr}{weakref}) eq 'CODE'
250 and
251 B::svref_2object($weak_registry->{$addr}{weakref})->XSUB
252 ) ? '__XSUB__' : Dumper( $weak_registry->{$addr}{weakref} )
253 ;
218b7c12 254 };
1a44a267 255
5dc4301c 256 # FIXME - need to add a circular reference seeker based on the visitor
257 # (will need a bunch of modifications, punting with just a stub for now)
258
556c4fe6 259 $diag .= Devel::FindRef::track ($weak_registry->{$addr}{weakref}, 50) . "\n"
1a44a267 260 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
261
262 $diag =~ s/^/ /mg;
263
264 if (my $stack = $weak_registry->{$addr}{stacktrace}) {
265 $diag .= " Reference first seen$stack";
266 }
267
268 $tb->diag($diag);
6ae62c5c 269
270# if ($leaks_found == 1) {
271# # using the fh dumper due to intermittent buffering issues
272# # in case we decide to exit soon after (possibly via _exit)
273# require Devel::MAT::Dumper;
274# local $Devel::MAT::Dumper::MAX_STRING = -1;
275# open( my $fh, '>:raw', "leaked_${addr}_pid$$.pmat" ) or die $!;
276# Devel::MAT::Dumper::dumpfh( $fh );
277# close ($fh) or die $!;
278#
279# use POSIX;
280# POSIX::_exit(1);
281# }
1a44a267 282 }
283
5dc4301c 284 if (! $quiet and !$leaks_found and ! $tb->in_todo) {
1a44a267 285 $tb->ok(1, sprintf "No leaks found at %s line %d", (caller())[1,2] );
218b7c12 286 }
287}
288
289END {
290 if ($INC{'Test/Builder.pm'}) {
291 my $tb = Test::Builder->new;
292
293 # we check for test passage - a leak may be a part of a TODO
294 if ($leaks_found and !$tb->is_passing) {
295
296 $tb->diag(sprintf
297 "\n\n%s\n%s\n\nInstall Devel::FindRef and re-run the test with set "
298 . '$ENV{TEST_VERBOSE} (prove -v) to see a more detailed leak-report'
299 . "\n\n%s\n%s\n\n", ('#' x 16) x 4
300 ) if ( !$ENV{TEST_VERBOSE} or !$INC{'Devel/FindRef.pm'} );
301
302 }
303 else {
304 $tb->note("Auto checked $refs_traced references for leaks - none detected");
305 }
306 }
307}
308
3091;