Add an explicit deduplication of identical condition in cond normalizer
[dbsrgits/DBIx-Class.git] / t / 52leaks.t
1 BEGIN { do "./t/lib/ANFANG.pm" or die ( $@ || $! ) }
2
3 # work around brain damage in PPerl (yes, it has to be a global)
4 $SIG{__WARN__} = sub {
5   warn @_ unless $_[0] =~ /\QUse of "goto" to jump into a construct is deprecated/
6 } if ($ENV{DBICTEST_IN_PERSISTENT_ENV});
7
8 # the persistent environments run with this flag first to see if
9 # we will run at all (e.g. it will fail if $^X doesn't match)
10 exit 0 if $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY};
11
12 # Do the override as early as possible so that CORE::bless doesn't get compiled away
13 # We will replace $bless_override only if we are in author mode
14 my $bless_override;
15 BEGIN {
16   $bless_override = sub {
17     CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() );
18   };
19   *CORE::GLOBAL::bless = sub { goto $bless_override };
20 }
21
22 use strict;
23 use warnings;
24 use Test::More;
25
26 BEGIN {
27   require DBICTest::Util;
28   plan skip_all => "Your perl version $] appears to leak like a sieve - skipping test"
29     if DBICTest::Util::PEEPEENESS();
30 }
31
32 use DBICTest::RunMode;
33 use DBICTest::Util::LeakTracer qw(populate_weakregistry assert_empty_weakregistry visit_refs);
34 use Scalar::Util qw(weaken blessed reftype);
35 use DBIx::Class::_Util qw(hrefaddr sigwarn_silencer modver_gt_or_eq modver_gt_or_eq_and_lt);
36 use DBIx::Class::Optional::Dependencies;
37
38 my $TB = Test::More->builder;
39 if ($ENV{DBICTEST_IN_PERSISTENT_ENV}) {
40   # without this explicit close TB warns in END after a ->reset
41   close ($TB->$_) for qw(output failure_output todo_output);
42
43   # newer TB does not auto-reopen handles
44   if ( modver_gt_or_eq( 'Test::More', '1.200' ) ) {
45     open ($TB->$_, '>&', *STDERR)
46       for qw( failure_output todo_output );
47     open ($TB->output, '>&', *STDOUT);
48   }
49
50   # so done_testing can work on every persistent pass
51   $TB->reset;
52 }
53
54 # this is what holds all weakened refs to be checked for leakage
55 my $weak_registry = {};
56
57 # whether or to invoke IC::DT
58 my $has_dt;
59
60 # Skip the heavy-duty leak tracing when just doing an install
61 # or when having Moose crap all over everything
62 # FIXME - remove when Replicated gets off Moose
63 if ( !$ENV{DBICTEST_VIA_REPLICATED} and !DBICTest::RunMode->is_plain ) {
64
65   # redefine the bless override so that we can catch each and every object created
66   no warnings qw/redefine once/;
67   no strict qw/refs/;
68
69   $bless_override = sub {
70
71     my $obj = CORE::bless(
72       $_[0], (@_ > 1) ? $_[1] : do {
73         my ($class, $fn, $line) = caller();
74         fail ("bless() of $_[0] into $class without explicit class specification at $fn line $line")
75           if $class =~ /^ (?: DBIx\:\:Class | DBICTest ) /x;
76         $class;
77       }
78     );
79
80     # unicode is tricky, and now we happen to invoke it early via a
81     # regex in connection()
82     return $obj if (ref $obj) =~ /^utf8/;
83
84     # Test Builder is now making a new object for every pass/fail (que bloat?)
85     # and as such we can't really store any of its objects (since it will
86     # re-populate the registry while checking it, ewwww!)
87     return $obj if (ref $obj) =~ /^TB2::|^Test::Stream/;
88
89     # populate immediately to avoid weird side effects
90     return populate_weakregistry ($weak_registry, $obj );
91   };
92
93   require Try::Tiny;
94   for my $func (qw/try catch finally/) {
95     my $orig = \&{"Try::Tiny::$func"};
96     *{"Try::Tiny::$func"} = sub (&;@) {
97       populate_weakregistry( $weak_registry, $_[0] );
98       goto $orig;
99     }
100   }
101
102   # Some modules are known to install singletons on-load
103   # Load them and empty the registry
104
105   # this loads the DT armada
106   $has_dt = DBIx::Class::Optional::Dependencies->req_ok_for([qw( test_rdbms_sqlite ic_dt )]);
107
108   require DBI;
109   require DBD::SQLite;
110   require Moo;
111   require Math::BigInt;
112
113   %$weak_registry = ();
114 }
115
116 {
117   use_ok ('DBICTest');
118
119   my $schema = DBICTest->init_schema;
120   my $rs = $schema->resultset ('Artist');
121   my $storage = $schema->storage;
122
123   my $row_obj = $rs->search({}, { rows => 1})->next;  # so that commits/rollbacks work
124   ok ($row_obj, 'row from db');
125
126   # txn_do to invoke more codepaths
127   my ($mc_row_obj, $pager, $pager_explicit_count) = $schema->txn_do (sub {
128
129     my $artist = $schema->resultset('Artist')->create ({
130       name => 'foo artist',
131       cds => [{
132         title => 'foo cd',
133         year => 1984,
134         tracks => [
135           { title => 't1' },
136           { title => 't2' },
137         ],
138         genre => { name => 'mauve' },
139       }],
140     });
141
142     my $pg = $rs->search({}, { rows => 1})->page(2)->pager;
143
144     my $pg_wcount = $rs->page(4)->pager->total_entries (66);
145
146     return ($artist, $pg, $pg_wcount);
147   });
148
149   # more codepaths - error handling in txn_do
150   {
151     eval { $schema->txn_do ( sub {
152       $storage->_dbh->begin_work;
153       fail ('how did we get so far?!');
154     } ) };
155
156     eval { $schema->txn_do ( sub {
157       $schema->txn_do ( sub {
158         die "It's called EXCEPTION";
159         fail ('how did we get so far?!');
160       } );
161       fail ('how did we get so far?!');
162     } ) };
163     like( $@, qr/It\'s called EXCEPTION/, 'Exception correctly propagated in nested txn_do' );
164   }
165
166   # dbh_do codepath
167   my ($rs_bind_circref, $cond_rowobj) = $schema->storage->dbh_do ( sub {
168     my $row = $_[0]->schema->resultset('Artist')->new({});
169     my $rs = $_[0]->schema->resultset('Artist')->search({
170       name => $row,  # this is deliberately bogus, see FIXME below!
171     });
172     return ($rs, $row);
173   });
174
175   is ($pager->next_page, 3, 'There is one more page available');
176
177   # based on 66 per 10 pages
178   is ($pager_explicit_count->last_page, 7, 'Correct last page');
179
180   # do some population (invokes some extra codepaths)
181   # also exercise the guard code and the manual txn control
182   {
183     my $guard = $schema->txn_scope_guard;
184     # populate with bindvars
185     $rs->populate([{ name => 'James Bound' }]);
186     $guard->commit;
187
188     $schema->txn_begin;
189     # populate mixed
190     $rs->populate([{ name => 'James Rebound', rank => \ '11'  }]);
191     $schema->txn_commit;
192
193     $schema->txn_begin;
194     # and without bindvars
195     $rs->populate([{ name => \ '"James Unbound"' }]);
196     $schema->txn_rollback;
197   }
198
199   # prefetching
200   my $cds_rs = $schema->resultset('CD');
201   my $cds_with_artist = $cds_rs->search({}, { prefetch => 'artist' });
202   my $cds_with_tracks = $cds_rs->search({}, { prefetch => 'tracks' });
203   my $cds_with_stuff = $cds_rs->search({}, { prefetch => [ 'genre', { artist => { cds => { tracks => 'cd_single' } } } ] });
204
205   # implicit pref
206   my $cds_with_impl_artist = $cds_rs->search({}, { columns => [qw/me.title artist.name/], join => 'artist' });
207
208   # get_column
209   my $getcol_rs = $cds_rs->get_column('me.cdid');
210   my $pref_getcol_rs = $cds_with_stuff->get_column('me.cdid');
211
212   my $base_collection = {
213     resultset => $rs,
214
215     pref_precursor => $cds_rs,
216
217     pref_rs_single => $cds_with_artist,
218     pref_rs_multi => $cds_with_tracks,
219     pref_rs_nested => $cds_with_stuff,
220
221     pref_rs_implicit => $cds_with_impl_artist,
222
223     pref_row_single => $cds_with_artist->next,
224     pref_row_multi => $cds_with_tracks->next,
225     pref_row_nested => $cds_with_stuff->next,
226
227     # even though this does not leak Storable croaks on it :(((
228     #pref_row_implicit => $cds_with_impl_artist->next,
229
230     get_column_rs_plain => $getcol_rs,
231     get_column_rs_pref => $pref_getcol_rs,
232
233     # twice so that we make sure only one H::M object spawned
234     chained_resultset => $rs->search_rs ({}, { '+columns' => { foo => 'artistid' } } ),
235     chained_resultset2 => $rs->search_rs ({}, { '+columns' => { bar => 'artistid' } } ),
236
237     row_object => $row_obj,
238
239     mc_row_object => $mc_row_obj,
240
241     result_source => $rs->result_source,
242
243     result_source_handle => $rs->result_source->handle,
244
245     pager_explicit_count => $pager_explicit_count,
246
247     leaky_resultset => $rs_bind_circref,
248     leaky_resultset_cond => $cond_rowobj,
249   };
250
251   # fire all resultsets multiple times, once here, more below
252   # some of these can't find anything (notably leaky_resultset)
253   my @rsets = grep {
254     blessed $_
255       and
256     (
257       $_->isa('DBIx::Class::ResultSet')
258         or
259       $_->isa('DBIx::Class::ResultSetColumn')
260     )
261   } values %$base_collection;
262
263
264   my $fire_resultsets = sub {
265     local $ENV{DBIC_COLUMNS_INCLUDE_FILTER_RELS} = 1;
266     local $SIG{__WARN__} = sigwarn_silencer(
267       qr/Unable to deflate 'filter'-type relationship 'artist'.+related object primary key not retrieved/
268     );
269
270     map
271       { $_, (blessed($_) ? { $_->get_columns } : ()) }
272       map
273         { $_->all }
274         @rsets
275     ;
276   };
277
278   push @{$base_collection->{random_results}}, $fire_resultsets->();
279
280   # FIXME - something throws a Storable for a spin if we keep
281   # the results in-collection. The same problem is seen above,
282   # swept under the rug back in 0a03206a, damned lazy ribantainer
283 {
284   local $base_collection->{random_results};
285
286   require Storable;
287   %$base_collection = (
288     %$base_collection,
289     refrozen => Storable::dclone( $base_collection ),
290     rerefrozen => Storable::dclone( Storable::dclone( $base_collection ) ),
291     pref_row_implicit => $cds_with_impl_artist->next,
292     schema => $schema,
293     storage => $storage,
294     sql_maker => $storage->sql_maker,
295     dbh => $storage->_dbh,
296     fresh_pager => $rs->page(5)->pager,
297     pager => $pager,
298   );
299 }
300
301   # FIXME - ideally this kind of collector ought to be global, but attempts
302   # with an invasive debugger-based tracer did not quite work out... yet
303   # Manually scan the innards of everything we have in the base collection
304   # we assembled so far (skip the DT madness below) *recursively*
305   #
306   # Only do this when we do have the bits to look inside CVs properly,
307   # without it we are liable to pick up object defaults that are locked
308   # in method closures
309   if (DBICTest::Util::LeakTracer::CV_TRACING) {
310     visit_refs(
311       refs => [ $base_collection ],
312       action => sub {
313         populate_weakregistry ($weak_registry, $_[0]);
314         1;  # true means "keep descending"
315       },
316     );
317
318     # do a heavy-duty fire-and-compare loop on all resultsets
319     # this is expensive - not running on install
320     my $typecounts = {};
321     if (
322       ! DBICTest::RunMode->is_plain
323         and
324       ! $ENV{DBICTEST_IN_PERSISTENT_ENV}
325     ) {
326
327       # FIXME - ideally we should be able to just populate an alternative
328       # registry, subtract everything from the main one, and arrive at
329       # an "empty" resulting hash
330       # However due to gross inefficiencies in the ::ResultSet code we
331       # end up recalculating a new set of aliasmaps which could have very
332       # well been cached if it wasn't for... anyhow
333       # What we do here for the time being is similar to the lazy approach
334       # of Devel::LeakTrace - we just make sure we do not end up with more
335       # reftypes than when we started. At least we are not blanket-counting
336       # SVs like D::LT does, but going by reftype... sigh...
337
338       for (values %$weak_registry) {
339         if ( my $r = reftype($_->{weakref}) ) {
340           $typecounts->{$r}--;
341         }
342       }
343
344       # For now we can only reuse the same registry, see FIXME above/below
345       #for my $interim_wr ({}, {}) {
346       for my $interim_wr ( ($weak_registry) x 4 ) {
347
348         visit_refs(
349           refs => [ $fire_resultsets->(), @rsets ],
350           action => sub {
351             populate_weakregistry ($interim_wr, $_[0]);
352             1;  # true means "keep descending"
353           },
354         );
355
356         # FIXME - this is what *should* be here
357         #
358         ## anything we have seen so far is cool
359         #delete @{$interim_wr}{keys %$weak_registry};
360         #
361         ## moment of truth - the rest ought to be gone
362         #assert_empty_weakregistry($interim_wr);
363       }
364
365       for (values %$weak_registry) {
366         if ( my $r = reftype($_->{weakref}) ) {
367           $typecounts->{$r}++;
368         }
369       }
370     }
371
372     for (keys %$typecounts) {
373       fail ("Amount of $_ refs changed by $typecounts->{$_} during resultset mass-execution")
374         if ( abs ($typecounts->{$_}) > 1 ); # there is a pad caught somewhere, the +1/-1 can be ignored
375     }
376   }
377
378   if ($has_dt) {
379     my $rs = $base_collection->{icdt_rs} = $schema->resultset('Event');
380
381     my $now = DateTime->now;
382     for (1..5) {
383       $base_collection->{"icdt_row_$_"} = $rs->create({
384         created_on => DateTime->new(year => 2011, month => 1, day => $_, time_zone => "-0${_}00" ),
385         starts_at => $now->clone->add(days => $_),
386       });
387     }
388
389     # re-search
390     my @dummy = $rs->all;
391   }
392
393   # dbh's are created in XS space, so pull them separately
394   for ( grep { defined } map { @{$_->{ChildHandles}} } values %{ {DBI->installed_drivers()} } ) {
395     $base_collection->{"DBI handle $_"} = $_;
396   }
397
398   populate_weakregistry ($weak_registry, $base_collection->{$_}, "basic $_")
399     for keys %$base_collection;
400 }
401
402 # check that "phantom-chaining" works - we never lose track of the original $schema
403 # and have access to the entire tree without leaking anything
404 {
405   my $phantom;
406   for (
407     sub { DBICTest->init_schema( sqlite_use_file => 0 ) },
408     sub { shift->source('Artist') },
409     sub { shift->resultset },
410     sub { shift->result_source },
411     sub { shift->schema },
412     sub { shift->resultset('Artist') },
413     sub { shift->find_or_create({ name => 'detachable' }) },
414     sub { shift->result_source },
415     sub { shift->schema },
416     sub { shift->clone },
417     sub { shift->resultset('CD') },
418     sub { shift->next },
419     sub { shift->artist },
420     sub { shift->search_related('cds') },
421     sub { shift->next },
422     sub { shift->search_related('artist') },
423     sub { shift->result_source },
424     sub { shift->resultset },
425     sub { shift->create({ name => 'detached' }) },
426     sub { shift->update({ name => 'reattached' }) },
427     sub { shift->discard_changes },
428     sub { shift->delete },
429     sub { shift->insert },
430   ) {
431     $phantom = populate_weakregistry ( $weak_registry, scalar $_->($phantom) );
432   }
433
434   ok( $phantom->in_storage, 'Properly deleted/reinserted' );
435   is( $phantom->name, 'reattached', 'Still correct name' );
436 }
437
438 # Naturally we have some exceptions
439 my $cleared;
440 for my $addr (keys %$weak_registry) {
441   my $names = join "\n", keys %{$weak_registry->{$addr}{slot_names}};
442
443   if ($names =~ /^Test::Builder/m) {
444     # T::B 2.0 has result objects and other fancyness
445     delete $weak_registry->{$addr};
446   }
447   # remove this when IO::Dir is gone from SQLT
448   elsif ($INC{"IO/Dir.pm"} and $names =~ /^Class::Struct::Tie_ISA/m) {
449     delete $weak_registry->{$addr};
450   }
451   elsif ($names =~ /^Hash::Merge/m) {
452     # only clear one object of a specific behavior - more would indicate trouble
453     delete $weak_registry->{$addr}
454       unless $cleared->{hash_merge_singleton}{$weak_registry->{$addr}{weakref}{behavior}}++;
455   }
456   elsif ($names =~ /^B::Hooks::EndOfScope::PP::_TieHintHashFieldHash/m) {
457     # there is one tied lexical which stays alive until GC time
458     # https://metacpan.org/source/ETHER/B-Hooks-EndOfScope-0.15/lib/B/Hooks/EndOfScope/PP/FieldHash.pm#L24
459     # simply ignore it here, instead of teaching the leaktracer to examine ties
460     # the latter is possible yet terrible: https://github.com/dbsrgits/dbix-class/blob/v0.082820/t/lib/DBICTest/Util/LeakTracer.pm#L113-L117
461     delete $weak_registry->{$addr}
462       unless $cleared->{bheos_pptiehinthashfieldhash}++;
463   }
464   elsif (
465     $names =~ /^Data::Dumper/m
466       and
467     $weak_registry->{$addr}{stacktrace} =~ /\bDBIx::Class::SQLMaker::Util::lax_serialize\b/
468   ) {
469     # only clear one object of a specific behavior - more would indicate trouble
470     delete $weak_registry->{$addr}
471       unless $cleared->{dd_lax_serializer}++;
472   }
473   elsif ($names =~ /^DateTime::TimeZone::UTC/m) {
474     # DT is going through a refactor it seems - let it leak zones for now
475     delete $weak_registry->{$addr};
476   }
477   elsif (
478 #    # if we can look at closed over pieces - we will register it as a global
479 #    !DBICTest::Util::LeakTracer::CV_TRACING
480 #      and
481     $names =~ /^SQL::Translator::Generator::DDL::SQLite/m
482   ) {
483     # SQLT::Producer::SQLite keeps global generators around for quoted
484     # and non-quoted DDL, allow one for each quoting style
485     delete $weak_registry->{$addr}
486       unless $cleared->{sqlt_ddl_sqlite}->{@{$weak_registry->{$addr}{weakref}->quote_chars}}++;
487   }
488 }
489
490 # FIXME !!!
491 # There is an actual strong circular reference taking place here, but because
492 # half of it is in XS, so it is a bit harder to track down (it stumps D::FR)
493 # (our tracker does not yet do it, but it'd be nice)
494 # The problem is:
495 #
496 # $cond_object --> result_source --> schema --> storage --> $dbh --> {CachedKids}
497 #          ^                                                           /
498 #           \-------- bound value on prepared/cached STH  <-----------/
499 #
500 {
501   my @circreffed;
502
503   for my $r (map
504     { $_->{weakref} }
505     grep
506       { $_->{slot_names}{'basic leaky_resultset_cond'} }
507       values %$weak_registry
508   ) {
509     local $TODO = 'Needs Data::Entangled or somesuch - see RT#82942';
510     ok(! defined $r, 'Self-referential RS conditions no longer leak!')
511       or push @circreffed, $r;
512   }
513
514   if (@circreffed) {
515     is (scalar @circreffed, 1, 'One resultset expected to leak');
516
517     # this is useless on its own, it is to showcase the circref-diag
518     # and eventually test it when it is operational
519     local $TODO = 'Needs Data::Entangled or somesuch - see RT#82942';
520     while (@circreffed) {
521       weaken (my $r = shift @circreffed);
522
523       populate_weakregistry( (my $mini_registry = {}), $r );
524       assert_empty_weakregistry( $mini_registry );
525
526       $r->result_source(undef);
527     }
528   }
529 }
530
531 assert_empty_weakregistry ($weak_registry);
532
533 # we got so far without a failure - this is a good thing
534 # now let's try to rerun this script under a "persistent" environment
535 # this is ugly and dirty but we do not yet have a Test::Embedded or
536 # similar
537
538 my $persistence_tests;
539 SKIP: {
540   skip 'Test already in a persistent loop', 1
541     if $ENV{DBICTEST_IN_PERSISTENT_ENV};
542
543   skip 'Main test failed - skipping persistent env tests', 1
544     unless $TB->is_passing;
545
546   skip "Test::Builder\@@{[ Test::Builder->VERSION ]} known to break persistence tests", 1
547     if modver_gt_or_eq_and_lt( 'Test::More', '1.200', '1.301001_099' );
548
549   local $ENV{DBICTEST_IN_PERSISTENT_ENV} = 1;
550   local $ENV{DBICTEST_ANFANG_DEFANG} = 1;
551
552   require File::Spec;
553
554   $persistence_tests = {
555     PPerl => {
556       cmd => [qw/pperl --prefork=1/, __FILE__],
557     },
558     'CGI::SpeedyCGI' => {
559       cmd => [qw/speedy -- -t5/, __FILE__],
560     },
561   };
562
563   # scgi is smart and will auto-reap after -t amount of seconds
564   # pperl needs an actual killer :(
565   $persistence_tests->{PPerl}{termcmd} = [
566     $persistence_tests->{PPerl}{cmd}[0],
567     '--kill',
568     @{$persistence_tests->{PPerl}{cmd}}[ 1 .. $#{$persistence_tests->{PPerl}{cmd}} ],
569   ];
570
571   # set up -I
572   require Config;
573   $ENV{PERL5LIB} = join ($Config::Config{path_sep}, @INC);
574
575   # adjust PATH for -T
576   if (length $ENV{PATH}) {
577     ( $ENV{PATH} ) = join ( $Config::Config{path_sep},
578       map { length($_) ? File::Spec->rel2abs($_) : () }
579         split /\Q$Config::Config{path_sep}/, $ENV{PATH}
580     ) =~ /\A(.+)\z/;
581   }
582
583   for my $type (keys %$persistence_tests) { SKIP: {
584     unless (eval "require $type") {
585       # Don't terminate what we didn't start
586       delete $persistence_tests->{$type}{termcmd};
587       skip "$type module not found", 1;
588     }
589
590     my @cmd = @{$persistence_tests->{$type}{cmd}};
591
592     # since PPerl is racy and sucks - just prime the "server"
593     {
594       local $ENV{DBICTEST_PERSISTENT_ENV_BAIL_EARLY} = 1;
595       system(@cmd);
596       sleep 1;
597
598       # see if the thing actually runs, if not - might as well bail now
599       skip "Something is wrong with $type ($!)", 1
600         if system(@cmd);
601     }
602
603     require IPC::Open2;
604
605     for (1,2,3) {
606       note ("Starting run in persistent env ($type pass $_)");
607       IPC::Open2::open2(my $out, undef, @cmd);
608       my @out_lines;
609       while (my $ln = <$out>) {
610         next if $ln =~ /^\s*$/;
611         push @out_lines, "   $ln";
612         last if $ln =~ /^\d+\.\.\d+$/;  # this is persistence, we need to terminate reading on our end
613       }
614       print $_ for @out_lines;
615       close $out;
616       wait;
617       ok (!$?, "Run in persistent env ($type pass $_): exit $?");
618       ok (scalar @out_lines, "Run in persistent env ($type pass $_): got output");
619     }
620
621     ok (! system (@{$persistence_tests->{$type}{termcmd}}), "killed $type server instance")
622       if $persistence_tests->{$type}{termcmd};
623   }}
624 }
625
626 done_testing;
627
628 # just an extra precaution in case we blew away from the SKIP - since there are no
629 # PID files to go by (man does pperl really suck :(
630 END {
631   if ($persistence_tests->{PPerl}{termcmd}) {
632     local $?; # otherwise test will inherit $? of the system()
633     require IPC::Open3;
634     open my $null, ">", File::Spec->devnull;
635     waitpid(
636       IPC::Open3::open3(undef, $null, $null, @{$persistence_tests->{PPerl}{termcmd}}),
637       0,
638     );
639   }
640 }