blib/lib/Hailo/Storage.pm

filter: Statementstmt 100% 112 / 112 Branchbran 100% 16 / 16 Conditioncond 88.2% 15 / 17 MC/DCmcdc 77.7% 7 / 9 Subroutinesub 100% 19 / 19 Podpod 0.0% 0 / 6 totaltotal 94.4% 169 / 179 CC 16 SCAR 9.3
CC
16
Cov
99%
totals
5.0
_engage_initialized_check_and_set_tokenizer
4.0
initialized
3.0
CRAP 2.5
« blib/lib/Hailo/Storage/SQLite.pm ↑ Summary blib/lib/Hailo/Role/Tokenizer.pm »
1 package Hailo::Storage;
2 29 our $AUTHORITY = 'cpan:AVAR';
3 29 $Hailo::Storage::VERSION = '0.73';
4 29 ▶use v5.28.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 29 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 29 ▶use MooseX::StrictConstructor;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 29 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 29 ▶use Hailo::Storage::Schema;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 29 has dbd => (
11 isa => 'Str',
12 is => 'ro',
13 lazy_build => 1,
14 documentation => "The DBD::* driver we're using",
15 );
16  
17 29 has dbd_options => (
18 isa => 'HashRef',
19 is => 'ro',
20 lazy_build => 1,
21 documentation => 'Options passed as the last argument to DBI->connect()',
22 );
23  
24 sub _build_dbd_options {
25 254 ▶ my ($self) = @_;
Subroutine _build_dbd_options: called CC=1 SCAR=0.0
26 return {
27 254 RaiseError => 1
28 };
29 }
30  
31 29 has dbh => (
32 isa => 'DBI::db',
33 is => 'ro',
34 lazy_build => 1,
35 documentation => 'Our DBD object',
36 );
37  
38 sub _build_dbh {
39 249 ▶ my ($self) = @_;
Subroutine _build_dbh: called CC=1 SCAR=0.0
40 249 my $dbd_options = $self->dbi_options;
41  
42 249 return DBI->connect($self->dbi_options);
43 };
44  
45 29 has dbi_options => (
46 isa => 'ArrayRef',
47 is => 'ro',
48 auto_deref => 1,
49 lazy_build => 1,
50 documentation => 'Options passed to DBI->connect()',
51 );
52  
53 sub _build_dbi_options {
54 249 ▶ my ($self) = @_;
Subroutine _build_dbi_options: called CC=2 SCAR=6.9
55 249 my $dbd = $self->dbd;
56 249 my $dbd_options = $self->dbd_options;
57 249 ▶ my $db = $self->brain // '';
Condition100%2/2
$self->brain // ""
l!l
23811
MC/DC100%1/1
$self->brain // ""
$self->brain
Truth table100%2/2
A
A= $self->brain
Aresult
11
00
58  
59 249 my @options = (
60 "dbi:$dbd:dbname=$db",
61 '',
62 '',
63 $dbd_options,
64 );
65  
66 249 return \@options;
67 }
68  
69 29 has _engaged => (
70 isa => 'Bool',
71 is => 'rw',
72 default => 0,
73 documentation => 'Have we done setup work to get this database going?',
74 );
75  
76 29 has sth => (
77 isa => 'HashRef',
78 is => 'ro',
79 lazy_build => 1,
80 documentation => 'A HashRef of prepared DBI statement handles',
81 );
82  
83 sub _build_sth {
84 50 ▶ my ($self) = @_;
Subroutine _build_sth: called CC=1 SCAR=0.0
85 50 return Hailo::Storage::Schema->sth($self->dbd, $self->dbh, $self->order);
86 }
87  
88 29 has _boundary_token_id => (
89 isa => 'Int',
90 is => 'rw',
91 );
92  
93 # bootstrap the database
94 sub _engage {
95 251 ▶ my ($self) = @_;
Subroutine _engage: called CC=2 SCAR=6.9
96  
97 251 ▶ if ($self->initialized) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->initialized) { } 209 42 251
98 # Check the order we've been given and retrieve it from the
99 # database if there's nothing odd going on.
100 209 $self->_engage_initialized_check_and_set_order;
101  
102 # Likewise for the Tokenizer
103 10 $self->_engage_initialized_check_and_set_tokenizer;
104  
105 8 $self->sth->{token_id}->execute(0, '');
106 8 my $id = $self->sth->{token_id}->fetchrow_array;
107 8 $self->_boundary_token_id($id);
108 }
109 else {
110 42 Hailo::Storage::Schema->deploy($self->dbd, $self->dbh, $self->order);
111  
112 # Set metadata in the database for use by subsequent
113 # invocations
114 {
115 # Don't change order again
116 42 my $order = $self->order;
117 42 $self->sth->{set_info}->execute('markov_order', $order);
118  
119 # Warn if the tokenizer changes
120 42 my $tokenizer = $self->tokenizer_class;
121 42 $self->sth->{set_info}->execute('tokenizer_class', $tokenizer);
122 }
123  
124 42 $self->sth->{add_token}->execute(0, '');
125 42 $self->sth->{last_token_rowid}->execute();
126 42 my $id = $self->sth->{last_token_rowid}->fetchrow_array();
127 42 $self->_boundary_token_id($id);
128 }
129  
130 50 $self->_engaged(1);
131  
132 50 return;
133 }
134  
135 sub _engage_initialized_check_and_set_order {
136 209 ▶ my ($self) = @_;
Subroutine _engage_initialized_check_and_set_order: called CC=3 SCAR=11.0
137  
138 209 my $sth = $self->dbh->prepare(qq[SELECT text FROM info WHERE attribute = ?;]);
139 209 $sth->execute('markov_order');
140 209 my $db_order = $sth->fetchrow_array();
141  
142 209 my $my_order = $self->order;
143 209 ▶ if ($my_order != $db_order) {
Branch: 1 branch
BranchTrueFalseTotal
if ($my_order != $db_order) 200 9 209
144 200 ▶ if ($self->hailo->{has_custom_order}->()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->hailo->{"has_custom_order"}->()) 199 1 200
145 199 die <<"DIE";
146 You've manually supplied an order of `$my_order' to Hailo but you're
147 loading a brain that has the order `$db_order'.
148  
149 Hailo will automatically load the order from existing brains, however
150 you've constructed Hailo and manually specified an order not
151 equivalent to the existing order of the database.
152  
153 Either supply the correct order or omit the order attribute
154 altogether. We could continue but I'd rather die since you're probably
155 expecting something I can't deliver.
156 DIE
157 }
158  
159 1 $self->order($db_order);
160 1 $self->hailo->{set_order}->($db_order);
161 }
162  
163 10 return;
164 }
165  
166 sub _engage_initialized_check_and_set_tokenizer {
167 10 ▶ my ($self) = @_;
Subroutine _engage_initialized_check_and_set_tokenizer: called CC=4 SCAR=13.9
168  
169 10 my $sth = $self->dbh->prepare(qq[SELECT text FROM info WHERE attribute = ?;]);
170 10 $sth->execute('tokenizer_class');
171 10 my $db_tokenizer_class = $sth->fetchrow_array;
172 10 my $my_tokenizer_class = $self->tokenizer_class;
173  
174 # defined() because we can't count on old brains having this
175 10 ▶ if (defined $db_tokenizer_class
Branch: 1 branch
BranchTrueFalseTotal
if (defined $db_tokenizer_class and $my_tokenizer_class ne $db_tokenizer_class) 3 7 10
Condition100%3/3
defined $db_tokenizer_class and $my_tokenizer_class ne $db_tokenizer_class
!ll&&!rl&&r
163
MC/DC100%2/2
defined $db_tokenizer_class and $my_tokenizer_class ne $db_tokenizer_class
defined $db_tokenizer_class $my_tokenizer_class ne $db_tokenizer_class
Truth table100%3/3
A and B
A= defined $db_tokenizer_classB= $my_tokenizer_class ne $db_tokenizer_class
ABresult
0X0
100
111
176 and $my_tokenizer_class ne $db_tokenizer_class) {
177 3 ▶ if ($self->hailo->{has_custom_tokenizer_class}->()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->hailo->{"has_custom_tokenizer_class"}->()) 2 1 3
178 2 die <<"DIE";
179 You've manually supplied a tokenizer class `$my_tokenizer_class' to
180 Hailo, but you're loading a brain that has the tokenizer class
181 `$db_tokenizer_class'.
182  
183 Hailo will automatically load the tokenizer class from existing
184 brains, however you've constructed Hailo and manually specified an
185 tokenizer class not equivalent to the existing tokenizer class of the
186 database.
187  
188 Either supply the correct tokenizer class or omit the order attribute
189 altogether. We could continue but I'd rather die since you're probably
190 expecting something I can't deliver.
191 DIE
192 }
193  
194 1 $self->tokenizer_class($db_tokenizer_class);
195 1 $self->hailo->{set_tokenizer_class}->($db_tokenizer_class);
196 }
197  
198 8 return;
199 }
200  
201 sub start_training {
202 23 ▶ my ($self) = @_;
Subroutine start_training: called CC=2 SCAR=6.9
Pod undocumented
203 23 ▶ $self->_engage() unless $self->_engaged;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_engaged 19 4 23
204 23 $self->start_learning();
205 23 return;
206 }
207  
208 sub stop_training {
209 19 ▶ my ($self) = @_;
Subroutine stop_training: called CC=1 SCAR=0.0
Pod undocumented
210 19 $self->stop_learning();
211 19 return;
212 }
213  
214 sub start_learning {
215 1658 ▶ my ($self) = @_;
Subroutine start_learning: called CC=2 SCAR=6.9
Pod undocumented
216 1658 ▶ $self->_engage() unless $self->_engaged;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_engaged 18 1640 1658
217  
218 # start a transaction
219 1658 $self->dbh->begin_work;
220 1658 return;
221 }
222  
223 sub stop_learning {
224 1653 ▶ my ($self) = @_;
Subroutine stop_learning: called CC=1 SCAR=0.0
Pod undocumented
225 # finish a transaction
226 1653 $self->dbh->commit;
227 1653 return;
228 }
229  
230 # See if SELECT count(*) FROM info; fails. If not we assume that we
231 # have an up and running database.
232 sub initialized {
233 214 ▶ my ($self) = @_;
Subroutine initialized: called CC=3 SCAR=11.1
Pod undocumented
234 214 my $dbh = $self->dbh;
235  
236 214 my ($err, $warn, $res);
237 214 eval {
238 # SQLite will warn 'no such table info'
239 214 ▶ local $SIG{__WARN__} = sub { $err = $_[0] };
Subroutine __ANON__: called CC=1 SCAR=0.0
240  
241 # If it doesn't warn trust that it dies here
242 214 local ($@, $!);
243 214 $res = $dbh->do("SELECT count(*) FROM info;");
244 };
245  
246 214 ▶ return (not $err and not $warn and defined $res);
Condition66%4/6
!($err || $warn) && defined $res
!ll&&!rl&&r
50209
$err || $warn
l!l&&r!l&&!r
50209
MC/DC33%1/3
!($err || $warn) && defined $res
$err $warn defined $res
Truth table50%2/4
not(A || B) && C
A= $errB= $warnC= defined $res
ABCresult
1XX0
01X0
0000
0011
247 }
248  
249 # return some statistics
250 sub totals {
251 34 ▶ my ($self) = @_;
Subroutine totals: called CC=5 SCAR=16.1
Pod undocumented
252 34 ▶ $self->_engage() unless $self->_engaged;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_engaged 3 31 34
253  
254 34 $self->sth->{token_total}->execute();
255 34 my $token = $self->sth->{token_total}->fetchrow_array - 1;
256 34 $self->sth->{expr_total}->execute();
257 34 ▶ my $expr = $self->sth->{expr_total}->fetchrow_array // 0;
Condition100%2/2
$self->sth->{"expr_total"}->fetchrow_array // 0
l!l
313
MC/DC100%1/1
$self->sth->{"expr_total"}->fetchrow_array // 0
$self->sth->{"expr_total"}->fetchrow_array
Truth table100%2/2
A
A= $self->sth->{"expr_total"}->fetchrow_array
Aresult
11
00
258 34 $self->sth->{prev_total}->execute();
259 34 ▶ my $prev = $self->sth->{prev_total}->fetchrow_array // 0;
Condition100%2/2
$self->sth->{"prev_total"}->fetchrow_array // 0
l!l
313
MC/DC100%1/1
$self->sth->{"prev_total"}->fetchrow_array // 0
$self->sth->{"prev_total"}->fetchrow_array
Truth table100%2/2
A
A= $self->sth->{"prev_total"}->fetchrow_array
Aresult
11
00
260 34 $self->sth->{next_total}->execute();
261 34 ▶ my $next = $self->sth->{next_total}->fetchrow_array // 0;
Condition100%2/2
$self->sth->{"next_total"}->fetchrow_array // 0
l!l
313
MC/DC100%1/1
$self->sth->{"next_total"}->fetchrow_array // 0
$self->sth->{"next_total"}->fetchrow_array
Truth table100%2/2
A
A= $self->sth->{"next_total"}->fetchrow_array
Aresult
11
00
262  
263 34 return $token, $expr, $prev, $next;
264 }
265  
266 29 __PACKAGE__->meta->make_immutable;
267  
268 =encoding utf8
269  
270 =head1 NAME
271  
272 Hailo::Storage - A base class for L<Hailo> L<storage|Hailo::Role::Storage> backends
273  
274 =head1 METHODS
275  
276 The following two methods must to be implemented by subclasses:
277  
278 =head2 C<_build_dbd>
279  
280 Should return the name of the database driver (e.g. 'SQLite') which will be
281 passed to L<DBI|DBI>.
282  
283 =head2 C<_build_dbd_options>
284  
285 Subclasses can override this method to add options of their own. E.g:
286  
287 override _build_dbd_options => sub {
288 return {
289 %{ super() },
290 sqlite_unicode => 1,
291 };
292 };
293  
294 =head1 Comparison of backends
295  
296 This benchmark shows how the backends compare when training on the
297 small testsuite dataset as reported by the F<utils/hailo-benchmark>
298 utility (found in the distribution):
299  
300 Rate DBD::Pg DBD::mysql DBD::SQLite/file DBD::SQLite/memory
301 DBD::Pg 2.22/s -- -33% -49% -56%
302 DBD::mysql 3.33/s 50% -- -23% -33%
303 DBD::SQLite/file 4.35/s 96% 30% -- -13%
304 DBD::SQLite/memory 5.00/s 125% 50% 15% --
305  
306 Under real-world workloads SQLite is much faster than these results
307 indicate since the time it takes to train/reply is relative to the
308 existing database size. Here's how long it took to train on a 214,710
309 line IRC log on a Linode 1080 with Hailo 0.18:
310  
311 =over
312  
313 =item * SQLite
314  
315 real 8m38.285s
316 user 8m30.831s
317 sys 0m1.175s
318  
319 =item * MySQL
320  
321 real 48m30.334s
322 user 8m25.414s
323 sys 4m38.175s
324  
325 =item * PostgreSQL
326  
327 real 216m38.906s
328 user 11m13.474s
329 sys 4m35.509s
330  
331 =back
332  
333 In the case of PostgreSQL it's actually much faster to first train
334 with SQLite, dump that database and then import it with L<psql(1)>,
335 see L<failo's README|http://github.com/hinrik/failo> for how to do
336 that.
337  
338 However, replying with an existing database (using
339 F<utils/hailo-benchmark-replies>) yields different results. SQLite can
340 reply really quickly without being warmed up (which is the typical
341 usecase for chatbots) but once PostgreSQL and MySQL are warmed up they
342 start replying faster:
343  
344 Here's a comparison of doing 10 replies:
345  
346 Rate PostgreSQL MySQL SQLite-file SQLite-file-28MB SQLite-memory
347 PostgreSQL 71.4/s -- -14% -14% -29% -50%
348 MySQL 83.3/s 17% -- 0% -17% -42%
349 SQLite-file 83.3/s 17% 0% -- -17% -42%
350 SQLite-file-28MB 100.0/s 40% 20% 20% -- -30%
351 SQLite-memory 143/s 100% 71% 71% 43% --
352  
353 In this test MySQL uses around 28MB of memory (using Debian's
354 F<my-small.cnf>) and PostgreSQL around 34MB. Plain SQLite uses 2MB of
355 cache but it's also tested with 28MB of cache as well as with the
356 entire database in memory.
357  
358 But doing 10,000 replies is very different:
359  
360 Rate SQLite-file PostgreSQL SQLite-file-28MB MySQL SQLite-memory
361 SQLite-file 85.1/s -- -7% -18% -27% -38%
362 PostgreSQL 91.4/s 7% -- -12% -21% -33%
363 SQLite-file-28MB 103/s 21% 13% -- -11% -25%
364 MySQL 116/s 37% 27% 13% -- -15%
365 SQLite-memory 137/s 61% 50% 33% 18% --
366  
367 Once MySQL gets more memory (using Debian's F<my-large.cnf>) and a
368 chance to warm it starts yielding better results (I couldn't find out
369 how to make PostgreSQL take as much memory as it wanted):
370  
371 Rate MySQL SQLite-memory
372 MySQL 121/s -- -12%
373 SQLite-memory 138/s 14% --
374  
375 =head1 AUTHOR
376  
377 E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason <avar@cpan.org>
378  
379 Hinrik E<Ouml>rn SigurE<eth>sson, hinrik.sig@gmail.com
380  
381 =head1 LICENSE AND COPYRIGHT
382  
383 Copyright 2010 E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason and
384 Hinrik E<Ouml>rn SigurE<eth>sson
385  
386 This program is free software, you can redistribute it and/or modify
387 it under the same terms as Perl itself.
388  
389 =cut
« blib/lib/Hailo/Storage/SQLite.pm ↑ Summary blib/lib/Hailo/Role/Tokenizer.pm »