blib/lib/Langertha/Skeid/UsageStore/DBI.pm

filter: Statementstmt 91.3% 508 / 556 Branchbran 71.4% 180 / 252 Conditioncond 47.3% 71 / 150 MC/DCmcdc 15.6% 13 / 83 Subroutinesub 97.3% 73 / 75 Podpod 100% 9 / 9 totaltotal 75.9% 854 / 1125 CC 200 SCAR 26.8
CC
200
Cov
79%
_report
58.0
dbh
30.9
__ANON__
30.0
CRAP 14.6
« lib/Langertha/Skeid/Rate.pm ↑ Summary lib/Langertha/Skeid/Protocol/Ollama/Stream.pm »
1 package Langertha::Skeid::UsageStore::DBI;
2 18 our $VERSION = '0.005';
3 # ABSTRACT: SQLite and PostgreSQL usage store
4 18 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 18 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 18 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 18 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 18 ▶use File::Basename qw(dirname);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 18 ▶use File::Path qw(make_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 18 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 18 ▶use File::ShareDir qw(dist_dir);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 18 ▶use Fcntl qw(LOCK_EX LOCK_NB);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 18 ▶use IO::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 18 ▶use JSON::MaybeXS qw(encode_json decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 18 ▶use List::Util qw(min);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 18 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 18 ▶use Mojo::Util qw(steady_time);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 18 ▶use Scalar::Util qw(weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 18 ▶use Sys::Hostname ();
Subroutine BEGIN: called CC=1 SCAR=0.0
20 18 ▶use Langertha::Skeid::UsageStore;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22  
23 18 has backend => (is => 'ro', required => 1);
24 18 has dsn => (is => 'ro', required => 1);
25 25 ▶has user => (is => 'ro', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
26 25 ▶has password => (is => 'ro', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
27 3 ▶has path => (is => 'ro', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
28 25 ▶has schema_file => (is => 'ro', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
29 25 ▶has auto_migrate => (is => 'ro', default => sub { 1 });
Subroutine __ANON__: called CC=1 SCAR=0.0
30 16 ▶has flush_interval_ms => (is => 'ro', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
31 18 has on_lost => (is => 'rw');
32 13 ▶has spool_dir => (is => 'ro', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
33  
34 18 has _dbh => (is => 'rw');
35 64 ▶has _queue => (is => 'ro', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
36 18 has _flush_timer => (is => 'rw');
37 # Reconnect backoff (k110): no connect before _reconnect_at (steady clock); _backoff_s is the
38 # wait the last failure set, _connect_error the masked error it failed with.
39 64 ▶has _reconnect_at => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
40 64 ▶has _backoff_s => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
41 64 ▶has _connect_error => (is => 'rw', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
42 # Prepared while the database was down (spool_dir): the schema is applied on the first connect.
43 64 ▶has _schema_pending => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
44 64 ▶has _spool_pending => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
45 64 ▶has _spool_announced => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
46 18 has _replay_timer => (is => 'rw');
47  
48 # The values ADR 0027 names; tests lower them.
49 18 our $BACKOFF_START_S = 1;
50 18 our $BACKOFF_MAX_S = 60;
51 18 our $REPLAY_BATCH = 500;
52  
53  
54 59 ▶sub prepare {
Subroutine prepare: called CC=9 SCAR=22.4
Pod documented
55 59 my ($self) = @_;
56 59 ▶ if (length $self->spool_dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->spool_dir) 12 47 59
57 12 ▶ $self->_spool_pending(1) if $self->_spool_files('any');
Branch: 1 branch
BranchTrueFalseTotal
if $self->_spool_files("any") 1 11 12
58 12 my $dbh = eval { $self->dbh };
59 12 ▶ unless ($dbh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dbh) 1 11 12
60 1 my $err = $@;
61 1 ▶ return unless defined($err) && length($err); # no DBI: as without a spool
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err and length $err 0 1 1
Condition33%1/3
defined $err and length $err
!ll&&!rl&&r
001
MC/DC0%0/2
defined $err and length $err
defined $err length $err
Truth table33%1/3
A and B
A= defined $errB= length $err
ABresult
0X0
100
111
62 1 ▶ if ($self->auto_migrate) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->auto_migrate) 1 0 1
63 1 $self->_schema_path; # a missing file still croaks here
64 1 $self->_schema_pending(1);
65 }
66 1 warn 'skeid: usage database unreachable at start, usage events go to the spool in '
67 . $self->spool_dir . ': ' . $self->_error_text($err) . "\n";
68 1 $self->_spool_announced(1);
69 1 return 1;
70 }
71 }
72 58 ▶ my $dbh = $self->dbh or return;
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = $self->dbh or return 57 0 57
73 57 ▶ $self->_apply_schema($dbh) if $self->auto_migrate;
Branch: 1 branch
BranchTrueFalseTotal
if $self->auto_migrate 57 0 57
74 57 $self->_schedule_replay;
75 57 return 1;
76 }
77  
78 59 ▶sub _schema_path {
Subroutine _schema_path: called CC=3 SCAR=11.3
79 59 my ($self) = @_;
80 59 my $schema_file = $self->schema_file;
81 59 ▶ $schema_file = $self->shipped_schema_file unless length $schema_file;
Branch: 1 branch
BranchTrueFalseTotal
unless length $schema_file 59 0 59
82 59 ▶ croak "usage schema file not found: $schema_file" unless -f $schema_file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $schema_file 0 59 59
83 59 return $schema_file;
84 }
85  
86 58 ▶sub _apply_schema {
Subroutine _apply_schema: called CC=5 SCAR=16.1
87 58 my ($self, $dbh) = @_;
88 58 my $sql = Langertha::Skeid::UsageStore::read_text_file($self->_schema_path);
89 348 my @stmts = grep { /\S/ } map {
90 58 my $s = $_;
91 348 $s =~ s/^\s+//;
92 348 $s =~ s/\s+$//;
93 348 $s;
94 } split /;\s*(?:\n|$)/, $sql;
95 # Tables first, then any column an older table is missing, then the rest. The index
96 # statements reference columns, so on an upgraded table they only work after the ALTER --
97 # running the file top to bottom fails on exactly the deployments this exists for.
98 58 my (@tables, @rest);
99 58 for my $stmt (@stmts) {
100 348 ▶ if ($stmt =~ /\A\s*CREATE\s+TABLE\b/i) { push @tables, $stmt }
Branch: 1 branch
BranchTrueFalseTotal
if ($stmt =~ /\A\s*CREATE\s+TABLE\b/i) { } 58 290 348
101 290 else { push @rest, $stmt }
102 }
103 58 $dbh->do($_) for @tables;
104 58 $self->_add_missing_columns($dbh);
105 58 $dbh->do($_) for @rest;
106 58 return 1;
107 }
108  
109 # The shipped schema is CREATE TABLE IF NOT EXISTS, so it does nothing to a table that already
110 # exists -- a deployment that upgrades Skeid keeps its old columns and every insert naming a
111 # new one fails. Usage failures are reported rather than thrown, so that would show up as
112 # silently missing billing data. Adding the column is the whole migration story; nothing here
113 # ever drops or rewrites one.
114 18 my @ADDED_COLUMNS = (
115 ['requested_model', 'TEXT'],
116 # Prompt-cache read count (k27). Nullable on purpose: an old row that predates it reads NULL
117 # ("was not measured"), which is not the same as a measured zero. BIGINT is INTEGER affinity
118 # in SQLite and a 64-bit integer in PostgreSQL, so one type serves both ALTER statements.
119 ['cached_tokens', 'BIGINT'],
120 # UTF-8 bytes a streamed request relayed (skeid #36). Nullable: only streamed events carry it.
121 ['content_bytes', 'BIGINT'],
122 # Prompt-cache read / write cost (skeid #28), already part of cost_total_usd. Nullable: an old
123 # row reads NULL ("was not priced apart"). DOUBLE PRECISION is REAL affinity in SQLite.
124 ['cost_cache_read_usd', 'DOUBLE PRECISION'],
125 ['cost_cache_write_usd', 'DOUBLE PRECISION'],
126 # Prompt-cache write count (skeid #41), beside cached_tokens. Nullable: an old row reads NULL.
127 ['cache_write_tokens', 'BIGINT'],
128 # Seconds of audio an audio route's node reported (skeid k91, ADR 0021). Nullable: an event
129 # whose node did not say reads NULL ("not measured"), not a measured zero.
130 ['audio_seconds', 'DOUBLE PRECISION'],
131 # Documents a rerank request carried (skeid k92). Nullable: only a rerank event has a count.
132 ['documents', 'BIGINT'],
133 # Pages a documents request converted (skeid k94, ADR 0028), read off the answer's
134 # json_content. Nullable: only a documents event whose answer carried a page count has one.
135 ['pages', 'BIGINT'],
136 # The usage contract (skeid k121): how the answer ended, the time to its first token (streams
137 # only) and the caller's correlation id. Nullable: an old row, or an event without one, reads
138 # NULL.
139 ['finish_reason', 'TEXT'],
140 ['ttft_ms', 'BIGINT'],
141 ['correlation_id', 'TEXT'],
142 # The catch-all target a bent request was routed under (skeid k129, ADR 0033). Nullable: only
143 # a bent request has one, and an old row reads NULL.
144 ['routed_model', 'TEXT'],
145 );
146  
147 58 ▶sub _add_missing_columns {
Subroutine _add_missing_columns: called CC=5 SCAR=16.1
148 58 my ($self, $dbh) = @_;
149  
150 58 ▶ my $existing = eval {
Branch: 1 branch
BranchTrueFalseTotal
my $existing = eval { do { my $sth = $dbh->prepare("SELECT * FROM usage_events WHERE 1=0"); $sth->execute; my(%cols) = map({lc $_, 1;} @{$sth->{"NAME_lc"} or [];}); $sth->finish; \%cols } } or return 58 0 58
151 58 my $sth = $dbh->prepare('SELECT * FROM usage_events WHERE 1=0');
152 58 $sth->execute;
153 58 ▶ my %cols = map { lc($_) => 1 } @{ $sth->{NAME_lc} || [] };
Condition50%1/2
$sth->{'NAME_lc'} || []
l!l
580
MC/DC0%0/1
$sth->{'NAME_lc'} || []
$sth->{'NAME_lc'}
Truth table50%1/2
A
A= $sth->{'NAME_lc'}
Aresult
11
00
154 58 $sth->finish;
155 58 \%cols;
156 } or return;
157  
158 58 for my $column (@ADDED_COLUMNS) {
159 754 my ($name, $type) = @$column;
160 754 ▶ next if $existing->{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $existing->{$name} 654 100 754
161 100 eval { $dbh->do("ALTER TABLE usage_events ADD COLUMN $name $type") };
162 }
163 58 return 1;
164 }
165  
166  
167 304 ▶sub dbh {
Subroutine dbh: called CC=20 SCAR=34.3
Pod documented
168 304 my ($self) = @_;
169 304 my $cached = $self->_dbh;
170 304 ▶ return $cached if $cached;
Branch: 1 branch
BranchTrueFalseTotal
if $cached 153 151 304
171 151 ▶ return unless length($self->backend) && length($self->dsn);
Branch: 1 branch
BranchTrueFalseTotal
unless length $self->backend and length $self->dsn 0 151 151
Condition33%1/3
length $self->backend and length $self->dsn
!ll&&!rl&&r
00151
MC/DC0%0/2
length $self->backend and length $self->dsn
length $self->backend length $self->dsn
Truth table33%1/3
A and B
A= length $self->backendB= length $self->dsn
ABresult
0X0
100
111
172  
173 151 ▶ eval { require DBI } or return;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require DBI } } or return 151 0 151
174  
175 151 ▶ if ($self->backend eq 'sqlite' && length $self->path) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->backend eq "sqlite" and length $self->path) 151 0 151
Condition33%1/3
$self->backend eq "sqlite" and length $self->path
!ll&&!rl&&r
00151
MC/DC0%0/2
$self->backend eq "sqlite" and length $self->path
$self->backend eq "sqlite" length $self->path
Truth table33%1/3
A and B
A= $self->backend eq "sqlite"B= length $self->path
ABresult
0X0
100
111
176 151 my $dir = dirname($self->path);
177 151 ▶ if (defined $dir && length $dir && $dir ne '.' && !-d $dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dir and length $dir and $dir ne "." and not -d $dir) 0 151 151
Condition33%3/9
defined $dir and length $dir and $dir ne "." and not -d $dir
!ll&&!rl&&r
01510
defined $dir and length $dir and $dir ne "."
!ll&&!rl&&r
00151
defined $dir and length $dir
!ll&&!rl&&r
00151
MC/DC0%0/4
defined $dir and length $dir and $dir ne "." and not -d $dir
defined $dir length $dir $dir ne "." not -d $dir
Truth table20%1/5
A and B and C and not(D)
A= defined $dirB= length $dirC= $dir ne "."D= not -d $dir
ABCDresult
0XXX0
10XX0
110X0
11100
11111
178 0 make_path($dir);
179 }
180 }
181  
182 151 my %connect_attr = (
183 RaiseError => 1,
184 PrintError => 0,
185 AutoCommit => 1,
186 );
187 151 ▶ $connect_attr{sqlite_unicode} = 1 if $self->backend eq 'sqlite';
Branch: 1 branch
BranchTrueFalseTotal
if $self->backend eq "sqlite" 151 0 151
188  
189 151 my $wait = $self->_reconnect_at - _now();
190 151 ▶ if ($wait > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wait > 0) 43 108 151
191 43 die sprintf("usage database unreachable (next connect attempt in %.1fs): %s\n",
192 $wait, $self->_connect_error);
193 }
194  
195 108 my $dbh = eval {
196 108 ▶ my $h = DBI->connect($self->dsn, $self->user, $self->password, \%connect_attr)
Branch: 1 branch
BranchTrueFalseTotal
my $h = "DBI"->connect($self->dsn, $self->user, $self->password, \%connect_attr) or die +("DBI"->errstr // "failed to connect usage database") . "\n" 69 0 69
Condition0%0/2
"DBI"->errstr // "failed to connect usage database"
l!l
00
MC/DC0%0/1
"DBI"->errstr // "failed to connect usage database"
"DBI"->errstr
Truth table0%0/2
A
A= "DBI"->errstr
Aresult
11
00
197 or die((DBI->errstr // 'failed to connect usage database') . "\n");
198 # Prepared while the database was down (spool_dir): the schema waited for this connect.
199 69 ▶ if ($self->_schema_pending) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_schema_pending) 1 68 69
200 1 ▶ unless (eval { $self->_apply_schema($h); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $self->_apply_schema($h); 1 } }) 0 1 1
201 0 my $err = $@;
202 0 eval { $h->disconnect };
203 0 die $err;
204 }
205 1 $self->_schema_pending(0);
206 }
207 69 $h;
208 };
209 108 ▶ unless ($dbh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dbh) 39 69 108
210 39 ▶ my $err = $@ || 'failed to connect usage database';
Condition50%1/2
$@ || 'failed to connect usage database'
l!l
390
MC/DC0%0/1
$@ || 'failed to connect usage database'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
211 # Back off (k110): one blocking connect per deadline while the database is away, never one
212 # per event or per flush tick.
213 39 ▶ my $backoff = $self->_backoff_s
Branch: 1 branch
BranchTrueFalseTotal
$self->_backoff_s ? : 26 13 39
214 ? min($self->_backoff_s * 2, $BACKOFF_MAX_S)
215 : $BACKOFF_START_S;
216 39 $self->_backoff_s($backoff);
217 39 $self->_reconnect_at(_now() + $backoff);
218 39 $self->_connect_error($self->_error_text($err));
219 39 die $err;
220 }
221 69 $self->_backoff_s(0);
222 69 $self->_reconnect_at(0);
223 69 $self->_connect_error('');
224 69 $self->_spool_announced(0);
225 69 $self->_dbh($dbh);
226 69 return $dbh;
227 }
228  
229 # The steady clock the backoff is measured on; a test moves it.
230 55 ▶sub _now { steady_time() }
Subroutine _now: called CC=1 SCAR=0.0
231  
232  
233 37 ▶sub disconnect {
Subroutine disconnect: called CC=2 SCAR=7.6
Pod documented
234 37 my ($self) = @_;
235 37 ▶ if (defined(my $timer = $self->_replay_timer)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $timer = $self->_replay_timer)) 0 37 37
236 0 Mojo::IOLoop->remove($timer);
237 0 $self->_replay_timer(undef);
238 }
239 37 $self->flush;
240 37 $self->_drop_handle;
241 37 return;
242 }
243  
244 # Forget the handle without flushing: what _with_handle does to a handle a failed statement left
245 # dead, in the middle of a flush as well -- where a flush of its own would be a re-entry.
246 50 ▶sub _drop_handle {
Subroutine _drop_handle: called CC=2 SCAR=7.0
247 50 my ($self) = @_;
248 50 ▶ my $dbh = $self->_dbh or return;
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = $self->_dbh or return 50 0 50
249 50 eval { $dbh->disconnect };
250 50 $self->_dbh(undef);
251 50 return;
252 }
253  
254  
255 61 ▶sub shipped_schema_file {
Subroutine shipped_schema_file: called CC=10 SCAR=25.3
Pod documented
256 61 my ($self) = @_;
257 61 ▶ my $name = ($self->backend eq 'postgresql') ? 'usage_events.postgresql.sql' : 'usage_events.sqlite.sql';
Branch: 1 branch
BranchTrueFalseTotal
$self->backend eq 'postgresql' ? : 1 60 61
258 61 my @candidates;
259  
260 # Installed/runtime lookup via dist sharedir.
261 61 my $share_dir = eval { dist_dir('Langertha-Skeid') };
262 61 ▶ if (!$@ && defined($share_dir) && length($share_dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $@ and defined $share_dir and length $share_dir) 61 0 61
Condition33%2/6
not $@ and defined $share_dir and length $share_dir
!ll&&!rl&&r
0061
not $@ and defined $share_dir
!ll&&!rl&&r
0061
MC/DC0%0/3
not $@ and defined $share_dir and length $share_dir
not $@ defined $share_dir length $share_dir
Truth table25%1/4
not(A) and B and C
A= not $@B= defined $share_dirC= length $share_dir
ABCresult
0XX0
10X0
1100
1111
263 61 push @candidates, File::Spec->catfile($share_dir, 'sql', $name);
264 }
265  
266 # Dev + dzil test fallback: walk up from this file looking for the repo's share/.
267 61 my $dir = dirname(dirname(dirname(dirname(__FILE__))));
268 61 for (1 .. 6) {
269 366 push @candidates, File::Spec->catfile($dir, 'share', 'sql', $name);
270 366 push @candidates, File::Spec->catfile($dir, 'sql', $name);
271 366 my $parent = dirname($dir);
272 366 ▶ last if !defined($parent) || $parent eq $dir;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $parent or $parent eq $dir 0 366 366
Condition33%1/3
not defined $parent or $parent eq $dir
l!l&&r!l&&!r
00366
MC/DC0%0/2
not defined $parent or $parent eq $dir
not defined $parent $parent eq $dir
Truth table33%1/3
not(A) or B
A= not defined $parentB= $parent eq $dir
ABresult
1X1
011
000
273 366 $dir = $parent;
274 }
275  
276 61 for my $path (@candidates) {
277 61 ▶ return $path if -f $path;
Branch: 1 branch
BranchTrueFalseTotal
if -f $path 61 0 61
278 }
279  
280 0 return $candidates[0];
281 }
282  
283  
284 165 ▶sub store {
Subroutine store: called CC=7 SCAR=19.5
Pod documented
285 165 my ($self, $event) = @_;
286 165 ▶ if ($self->_writes_behind) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_writes_behind) 33 132 165
287 33 push @{ $self->_queue }, { %$event };
288 33 $self->_arm_flush;
289 33 return { ok => 1, queued => 1 };
290 }
291 # Whatever was queued while the loop ran goes first, so the table keeps the order the events
292 # arrived in.
293 132 ▶ $self->flush if @{ $self->_queue };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->_queue;} 1 131 132
294 76 ▶ my $res = $self->_with_handle(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
295 76 my ($dbh) = @_;
296 76 return { ok => 1, $self->_insert($dbh, $event) };
297 132 });
298 132 ▶ if ($res->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"ok"}) 63 69 132
299 63 $self->_schedule_replay;
300 63 return $res;
301 }
302 # A live handle refused the event: spooling it would only replay the refusal.
303 69 ▶ return $res if $self->_dbh || !length($self->spool_dir);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_dbh or not length $self->spool_dir 30 39 69
Condition100%3/3
$self->_dbh or not length $self->spool_dir
l!l&&r!l&&!r
32739
MC/DC100%2/2
$self->_dbh or not length $self->spool_dir
$self->_dbh not length $self->spool_dir
Truth table100%3/3
A or not(B)
A= $self->_dbhB= not length $self->spool_dir
ABresult
1X1
011
000
304 39 my $spool_err = $self->_spool_events([$event]);
305 39 ▶ unless ($spool_err) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($spool_err) 39 0 39
306 39 $self->_announce_spool($res->{error});
307 39 return { ok => 1, spooled => 1 };
308 }
309 0 return $self->_failure("$res->{error}; spool write failed: $spool_err");
310 }
311  
312 # Queue only while a loop runs to fire the flush timer. Outside one -- a script calling
313 # usage.record, the prefork manager before it forks -- there is no request path to keep free and
314 # a queue that nothing would ever write.
315 165 ▶sub _writes_behind {
Subroutine _writes_behind: called CC=3 SCAR=11.0
316 165 my ($self) = @_;
317 165 ▶ return 0 unless $self->flush_interval_ms > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->flush_interval_ms > 0 76 89 165
318 89 ▶ return Mojo::IOLoop->is_running ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
'Mojo::IOLoop'->is_running ? : 33 56 89
319 }
320  
321 33 ▶sub _arm_flush {
Subroutine _arm_flush: called CC=2 SCAR=6.9
322 33 my ($self) = @_;
323 33 ▶ return if defined $self->_flush_timer;
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->_flush_timer 9 24 33
324 24 weaken(my $weak = $self);
325 2 ▶ $self->_flush_timer(Mojo::IOLoop->timer($self->flush_interval_ms / 1000 => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
326 2 ▶ return unless $weak;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak 0 2 2
327 2 $weak->_flush_timer(undef);
328 2 $weak->flush;
329 24 }));
330 24 return;
331 }
332  
333  
334 87 ▶sub flush {
Subroutine flush: called CC=10 SCAR=23.2
Pod documented
335 87 my ($self) = @_;
336 87 ▶ if (defined(my $timer = $self->_flush_timer)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $timer = $self->_flush_timer)) 22 65 87
337 22 Mojo::IOLoop->remove($timer);
338 22 $self->_flush_timer(undef);
339 }
340 87 my @events = splice @{ $self->_queue };
341 87 ▶ return { ok => 1, written => 0 } unless @events;
Branch: 1 branch
BranchTrueFalseTotal
unless @events 63 24 87
342  
343 14 ▶ my $batch = $self->_with_handle(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
344 14 my ($dbh) = @_;
345 14 $dbh->begin_work;
346 14 my $done = eval {
347 14 $self->_insert($dbh, $_) for @events;
348 9 $dbh->commit;
349 9 1;
350 };
351 14 ▶ unless ($done) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($done) 5 9 14
352 5 my $err = $@;
353 5 eval { $dbh->rollback };
354 5 die $err;
355 }
356 9 return { ok => 1, written => scalar @events };
357 24 });
358 24 ▶ if ($batch->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($batch->{"ok"}) 9 15 24
359 9 $self->_schedule_replay;
360 9 return $batch;
361 }
362  
363 # No handle left: the reconnect failed (or the backoff runs), and one attempt per event would
364 # only repeat it.
365 15 ▶ return _flush_answer(0, $self->_spool_or_lose(\@events, $batch->{error}))
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_dbh 12 3 15
366 unless $self->_dbh;
367  
368 3 my ($written, $spooled, $lost, $error) = (0, 0, 0);
369 3 ▶ while (@events) {
Branch: 1 branch
BranchTrueFalseTotal
if (@events) 5 3 8
370 5 my $event = shift @events;
371 5 ▶ my $one = $self->_with_handle(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
372 5 my ($dbh) = @_;
373 5 $self->_insert($dbh, $event);
374 2 return { ok => 1 };
375 5 });
376 5 ▶ if ($one->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($one->{"ok"}) 2 3 5
377 2 $written++;
378 2 next;
379 }
380 3 ▶ if ($self->_dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_dbh) 3 0 3
381 # Refused on a live handle: this event alone is lost, and never spooled.
382 3 $lost++;
383 3 $error = $one->{error};
384 3 $self->_report_lost($event, $error);
385 3 next;
386 }
387 # The handle died under the single writes and did not come back: this event and the rest
388 # go with it.
389 0 my ($s, $l, $e) = $self->_spool_or_lose([$event, @events], $one->{error});
390 0 $spooled += $s;
391 0 $lost += $l;
392 0 ▶ $error = $e if $l;
Branch: 1 branch
BranchTrueFalseTotal
if $l 0 0 0
393 0 last;
394 }
395 3 ▶ $self->_schedule_replay if $written;
Branch: 1 branch
BranchTrueFalseTotal
if $written 1 2 3
396 3 return _flush_answer($written, $spooled, $lost, $error);
397 }
398  
399 15 ▶sub _flush_answer {
Subroutine _flush_answer: called CC=4 SCAR=13.9
400 15 my ($written, $spooled, $lost, $error) = @_;
401 return {
402 15 ▶ ok => ($lost ? 0 : 1),
Branch: 3 branches
BranchTrueFalseTotal
$lost ? : 9 6 15
$spooled ? : 6 9 15
$lost ? : 9 6 15
403 written => $written,
404 ($spooled ? (spooled => $spooled) : ()),
405 ($lost ? (lost => $lost, error => $error) : ()),
406 };
407 }
408  
409 # Events that could not be written for want of a connection: to the spool when there is one,
410 # else -- or when the spool write fails -- reported lost. Answers ($spooled, $lost, $error).
411 12 ▶sub _spool_or_lose {
Subroutine _spool_or_lose: called CC=4 SCAR=14.0
412 12 my ($self, $events, $err) = @_;
413 12 ▶ if (length $self->spool_dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->spool_dir) 6 6 12
414 6 my $spool_err = $self->_spool_events($events);
415 6 ▶ unless ($spool_err) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($spool_err) 6 0 6
416 6 $self->_announce_spool($err);
417 6 return (scalar(@$events), 0, undef);
418 }
419 0 $err = $self->_error_text($err) . "; spool write failed: $spool_err";
420 }
421 6 my $failure = $self->_failure($err);
422 6 $self->_report_lost($_, $failure->{error}) for @$events;
423 6 return (0, scalar(@$events), $failure->{error});
424 }
425  
426 # Fail loud once per outage: spooled events are not lost, but the database is away.
427 45 ▶sub _announce_spool {
Subroutine _announce_spool: called CC=2 SCAR=6.9
428 45 my ($self, $err) = @_;
429 45 ▶ return if $self->_spool_announced;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_spool_announced 38 7 45
430 7 $self->_spool_announced(1);
431 7 warn 'skeid: usage database unreachable, usage events go to the spool in '
432 . $self->spool_dir . ' until it is back: ' . $self->_error_text($err) . "\n";
433 7 return;
434 }
435  
436 11 ▶sub _report_lost {
Subroutine _report_lost: called CC=4 SCAR=17.9
437 11 my ($self, $event, $err) = @_;
438 11 my $cb = $self->on_lost;
439 11 ▶ return if $cb && eval { $cb->($event, $err); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if $cb and eval { do { &$cb($event, $err); 1 } } 11 0 11
Condition33%1/3
$cb and eval { do { &$cb($event, $err); 1 } }
!ll&&!rl&&r
0011
MC/DC0%0/2
$cb and eval { do { &$cb($event, $err); 1 } }
$cb eval { do { &$cb($event, $err); 1 } }
Truth table33%1/3
A and B
A= $cbB= eval { do { &$cb($event, $err); 1 } }
ABresult
0X0
100
111
440 # A timer callback that dies takes the reactor's error path; a lost event must still be said.
441 0 ▶ warn 'skeid: usage event lost: request_id=' . ($event->{request_id} // '')
Condition0%0/2
$event->{"request_id"} // ""
l!l
00
MC/DC0%0/1
$event->{"request_id"} // ""
$event->{"request_id"}
Truth table0%0/2
A
A= $event->{"request_id"}
Aresult
11
00
442 . ' store=' . $self->backend . ': ' . $err . "\n";
443 0 return;
444 }
445  
446 # Runs $work with the store's handle and returns its answer, or { ok => 0, error } when it dies.
447 # On a failure that left the handle dead the handle is dropped, connected once more and $work
448 # retried once on the new one (skeid k71). Never more than that, never a wait.
449 207 ▶sub _with_handle {
Subroutine _with_handle: called CC=8 SCAR=21.0
450 207 my ($self, $work) = @_;
451  
452 207 my $dbh = eval { $self->dbh };
453 207 ▶ return $self->_failure($@ || 'failed to connect usage database') unless $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh 69 138 207
Condition50%1/2
$@ || 'failed to connect usage database'
l!l
690
MC/DC0%0/1
$@ || 'failed to connect usage database'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
454  
455 138 my $res = eval { $work->($dbh) };
456 138 ▶ return $res if $res;
Branch: 1 branch
BranchTrueFalseTotal
if $res 116 22 138
457 22 my $err = $@;
458 22 ▶ return $self->_failure($err) if $self->_handle_alive($dbh);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_handle_alive($dbh) 9 13 22
459  
460 13 $self->_drop_handle;
461 13 my $fresh = eval { $self->dbh };
462 13 ▶ return $self->_failure('usage database connection lost, reconnect failed: '
Branch: 1 branch
BranchTrueFalseTotal
unless $fresh 11 2 13
Condition50%1/2
$@ || 'no database handle'
l!l
110
MC/DC0%0/1
$@ || 'no database handle'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
463 .($@ || 'no database handle')) unless $fresh;
464  
465 2 $res = eval { $work->($fresh) };
466 2 ▶ return $res || $self->_failure($@);
Condition33%1/3
$res || $self->_failure($@)
l!l&&r!l&&!r
200
MC/DC0%0/2
$res || $self->_failure($@)
$res $self->_failure($@)
Truth table33%1/3
A || B
A= $resB= $self->_failure($@)
ABresult
1X1
011
000
467 }
468  
469 # Asked only after a statement failed, so the round-trip a ping costs on PostgreSQL is never
470 # paid by a healthy write. DBD::Pg keeps Active set on a connection the server dropped; ping
471 # is what notices.
472 22 ▶sub _handle_alive {
Subroutine _handle_alive: called CC=3 SCAR=11.0
473 22 my ($self, $dbh) = @_;
474 22 ▶ return 0 unless $dbh->{Active};
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh->{"Active"} 13 9 22
475 9 ▶ return eval { $dbh->ping } ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $dbh->ping } } ? : 9 0 9
476 }
477  
478 95 ▶sub _failure {
Subroutine _failure: called CC=1 SCAR=0.0
479 95 my ($self, $err) = @_;
480 95 return { ok => 0, error => $self->_error_text($err) };
481 }
482  
483 # A DBI error names the DSN it failed on, and a DSN may carry the password. Nothing that
484 # leaves this store may (ADR 0003).
485 143 ▶sub _error_text {
Subroutine _error_text: called CC=3 SCAR=11.8
486 143 my ($self, $err) = @_;
487 143 ▶ $err = 'unknown database error' unless defined($err) && length($err);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err and length $err 0 143 143
Condition33%1/3
defined $err and length $err
!ll&&!rl&&r
00143
MC/DC0%0/2
defined $err and length $err
defined $err length $err
Truth table33%1/3
A and B
A= defined $errB= length $err
ABresult
0X0
100
111
488 143 $err =~ s/\b(password|pwd)=[^;'"\s)]*/$1=***/gi;
489 143 $err =~ s/\s+$//;
490 143 return $err;
491 }
492  
493 # The columns of one event, in the order _insert binds them. The spool writes exactly these keys
494 # of an event and nothing else (k110), so a new column is added here once and reaches both.
495 18 my @EVENT_COLUMNS = qw(
496 created_at request_id api_format endpoint api_key_id provider engine model node_id route_url
497 status_code ok duration_ms input_tokens output_tokens total_tokens cached_tokens tool_calls
498 cost_input_usd cost_output_usd cost_total_usd error_type error_message requested_model
499 content_bytes cost_cache_read_usd cost_cache_write_usd cache_write_tokens audio_seconds
500 documents pages finish_reason ttft_ms correlation_id routed_model
501 );
502 # Nullable, written as NULL when the event has no such key -- "not measured", not a zero:
503 # cached_tokens an event that carried no cache count
504 # content_bytes only a streamed request carries it
505 # cost_cache_read_usd,
506 # cost_cache_write_usd an event from a caller that does not price the cache apart
507 # cache_write_tokens an event that carried no cache write count
508 # audio_seconds only an audio route's event, and only when its node reported it
509 # documents only a rerank or documents event
510 # pages only a documents event whose answer said how many pages it was
511 # finish_reason an event whose answer had none (embeddings, audio, ...) and no error
512 # ttft_ms only a streamed event that relayed a token
513 # correlation_id an event whose caller sent none, or the config names no header
514 # routed_model only an event of a request the catch-all bent (ADR 0033)
515 # requested_model falls back to model, then ''.
516 18 my $INSERT_SQL = 'INSERT INTO usage_events (' . join(', ', @EVENT_COLUMNS) . ') VALUES ('
517 . join(', ', ('?') x @EVENT_COLUMNS) . ')';
518  
519 148 ▶sub _insert {
Subroutine _insert: called CC=6 SCAR=19.3
520 148 my ($self, $dbh, $event) = @_;
521 148 my $sth = $dbh->prepare_cached($INSERT_SQL);
522 $sth->execute(map {
523 131 $_ eq 'requested_model'
524 ? ($event->{requested_model} // $event->{model} // '')
525 4585 ▶ : $event->{$_}
Branch: 1 branch
BranchTrueFalseTotal
$_ eq 'requested_model' ? : 131 4454 4585
Condition60%3/5
($event->{"requested_model"} // $event->{"model"}) // ""
l!l
1310
$event->{"requested_model"} // $event->{"model"}
l!l&&r!l&&!r
52790
MC/DC0%0/2
($event->{"requested_model"} // $event->{"model"}) // ""
$event->{"requested_model"} $event->{"model"}
Truth table66%2/3
A // B
A= $event->{"requested_model"}B= $event->{"model"}
ABresult
1X1
011
000
526 } @EVENT_COLUMNS);
527  
528 127 ▶ return ($self->backend eq 'sqlite' && $dbh->can('sqlite_last_insert_rowid'))
Branch: 1 branch
BranchTrueFalseTotal
$self->backend eq 'sqlite' && $dbh->can('sqlite_last_insert_rowid') ? : 127 0 127
Condition33%1/3
$self->backend eq "sqlite" and $dbh->can("sqlite_last_insert_rowid")
!ll&&!rl&&r
00127
MC/DC0%0/2
$self->backend eq "sqlite" and $dbh->can("sqlite_last_insert_rowid")
$self->backend eq "sqlite" $dbh->can("sqlite_last_insert_rowid")
Truth table33%1/3
A and B
A= $self->backend eq "sqlite"B= $dbh->can("sqlite_last_insert_rowid")
ABresult
0X0
100
111
529 ? ( id => Langertha::Skeid::UsageStore::num($dbh->sqlite_last_insert_rowid) )
530 : ();
531 }
532  
533 # Replay's insert (k110): skipped when the event is already in the table. The key is
534 # request_id with created_at -- the spool holds the event as it was built, so a copy that made it
535 # in carries both, while a client that sends the same x-request-id twice does not lose its
536 # second, real event. Without a request_id there is no key: the event is written. Answers 1 for
537 # a row written, 0 for one skipped.
538 53 ▶sub _insert_once {
Subroutine _insert_once: called CC=4 SCAR=13.9
539 53 my ($self, $dbh, $event) = @_;
540 53 my $request_id = $event->{request_id};
541 53 ▶ if (defined($request_id) && length($request_id)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $request_id and length $request_id) 52 1 53
Condition66%2/3
defined $request_id and length $request_id
!ll&&!rl&&r
0152
MC/DC50%1/2
defined $request_id and length $request_id
defined $request_id length $request_id
Truth table66%2/3
A and B
A= defined $request_idB= length $request_id
ABresult
0X0
100
111
542 my $found = $dbh->selectrow_arrayref(
543 'SELECT 1 FROM usage_events WHERE request_id = ? AND created_at = ?',
544 52 undef, $request_id, $event->{created_at});
545 52 ▶ return 0 if $found;
Branch: 1 branch
BranchTrueFalseTotal
if $found 4 48 52
546 }
547 49 $self->_insert($dbh, $event);
548 49 return 1;
549 }
550  
551 # --- The spool (k110, ADR 0027) ----------------------------------------------------------------
552 #
553 # Writers append to usage-spool-<host>-<pid>.jsonl, one per process. A replay first claims a
554 # writer's file by renaming it to <name>.replay-<host>-<pid>-<n> under the file's lock; a writer
555 # that was waiting for that lock sees the path no longer names its file and opens a new one. A
556 # claimed file is then worked under its own lock, which only replays ever take -- so a writer
557 # waits at most for a rename, never for a database. Temporary files start with a dot and match
558 # neither pattern.
559  
560 18 my $SPOOL_FILE = qr/\Ausage-spool-[A-Za-z0-9._-]+\.jsonl\z/;
561 18 my $CLAIMED_FILE = qr/\Ausage-spool-[A-Za-z0-9._-]+\.jsonl\.replay-[A-Za-z0-9._-]+\z/;
562 18 my $CLAIM_SEQ = 0;
563 18 my $HOST;
564  
565 58 ▶sub _host {
Subroutine _host: called CC=4 SCAR=14.5
566 58 ▶ return $HOST //= do {
Condition66%2/3
$HOST //= do { my $host = eval { do { Sys::Hostname::hostname() } } // ""; $host =~ s/[^A-Za-z0-9.-]+/_/g; length $host ? $host : "localhost" }
l!l&&r!l&&!r
5710
MC/DC0%0/2
$HOST //= do { my $host = eval { do { Sys::Hostname::hostname() } } // ""; $host =~ s/[^A-Za-z0-9.-]+/_/g; length $host ? $host : "localhost" }
$HOST do { my $host = eval { do { Sys::Hostname::hostname() } } // ""; $host =~ s/[^A-Za-z0-9.-]+/_/g; length $host ? $host : "localhost" }
Truth table66%2/3
A //= B
A= $HOSTB= do { my $host = eval { do { Sys::Hostname::hostname() } } // ""; $host =~ s/[^A-Za-z0-9.-]+/_/g; length $host ? $host : "localhost" }
ABresult
1X1
011
000
567 1 ▶ my $host = eval { Sys::Hostname::hostname() } // '';
Condition50%1/2
eval { do { Sys::Hostname::hostname() } } // ""
l!l
10
MC/DC0%0/1
eval { do { Sys::Hostname::hostname() } } // ""
eval { do { Sys::Hostname::hostname() } }
Truth table50%1/2
A
A= eval { do { Sys::Hostname::hostname() } }
Aresult
11
00
568 1 $host =~ s/[^A-Za-z0-9.-]+/_/g;
569 1 ▶ length($host) ? $host : 'localhost';
Branch: 1 branch
BranchTrueFalseTotal
length $host ? : 1 0 1
570 };
571 }
572  
573 59 ▶sub _spool_files {
Subroutine _spool_files: called CC=5 SCAR=16.1
574 59 my ($self, $kind) = @_;
575 59 ▶ opendir(my $dh, $self->spool_dir) or return;
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $self->spool_dir or return 49 10 59
576 my @names = sort grep {
577 49 ▶ $kind eq 'writer' ? $_ =~ $SPOOL_FILE
Branch: 2 branches
BranchTrueFalseTotal
$kind eq 'writer' ? : 47 90 137
$kind eq 'claimed' ? : 47 43 90
Condition100%3/3
$_ =~ /$SPOOL_FILE/ or $_ =~ /$CLAIMED_FILE/
l!l&&r!l&&!r
2338
MC/DC100%2/2
$_ =~ /$SPOOL_FILE/ or $_ =~ /$CLAIMED_FILE/
$_ =~ /$SPOOL_FILE/ $_ =~ /$CLAIMED_FILE/
Truth table100%3/3
A or B
A= $_ =~ /$SPOOL_FILE/B= $_ =~ /$CLAIMED_FILE/
ABresult
1X1
011
000
578 : $kind eq 'claimed' ? $_ =~ $CLAIMED_FILE
579 : ($_ =~ $SPOOL_FILE || $_ =~ $CLAIMED_FILE)
580 } readdir $dh;
581 49 closedir $dh;
582 49 return @names;
583 }
584  
585 # True when the open $fh is still the file at $path: a replay may have renamed or removed it
586 # between the open and the lock.
587 75 ▶sub _same_file {
Subroutine _same_file: called CC=4 SCAR=15.6
588 75 my ($fh, $path) = @_;
589 75 ▶ my @open = stat $fh or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my(@open) = stat $fh or return 0 75 0 75
590 75 ▶ my @named = stat $path or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my(@named) = stat $path or return 0 75 0 75
591 75 ▶ return $open[0] == $named[0] && $open[1] == $named[1];
Condition33%1/3
$open[0] == $named[0] && $open[1] == $named[1]
!ll&&!rl&&r
0075
MC/DC0%0/2
$open[0] == $named[0] && $open[1] == $named[1]
$open[0] == $named[0] $open[1] == $named[1]
Truth table33%1/3
A && B
A= $open[0] == $named[0]B= $open[1] == $named[1]
ABresult
0X0
100
111
592 }
593  
594 # Appends $events to this process's spool file. Answers undef, or the error -- never dies.
595 45 ▶sub _spool_events {
Subroutine _spool_events: called CC=3 SCAR=11.6
596 45 my ($self, $events) = @_;
597 45 my $ok = eval { $self->_append_spool($events); 1 };
598 45 ▶ return $@ || 'unknown spool error' unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 45 45
Condition0%0/2
$@ || 'unknown spool error'
l!l
00
MC/DC0%0/1
$@ || 'unknown spool error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
599 45 $self->_spool_pending(1);
600 45 return undef;
601 }
602  
603 45 ▶sub _append_spool {
Subroutine _append_spool: called CC=12 SCAR=26.6
604 45 my ($self, $events) = @_;
605 45 my $dir = $self->spool_dir;
606 45 ▶ unless (-d $dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $dir) 7 38 45
607 7 make_path($dir, { error => \my $mkerr });
608 7 ▶ die "Cannot create spool directory $dir\n" unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 0 7 7
609 }
610 # Only the columns: whatever else an event hash carries never reaches the disk.
611 my $lines = join '', map {
612 45 my $event = $_;
613 47 ▶ encode_json({ map { exists $event->{$_} ? ($_ => $event->{$_}) : () } @EVENT_COLUMNS }) . "\n";
Branch: 1 branch
BranchTrueFalseTotal
exists $event->{$_} ? : 752 893 1645
614 } @$events;
615 45 my $path = File::Spec->catfile($dir, 'usage-spool-' . _host() . "-$$.jsonl");
616  
617 45 for (1 .. 5) {
618 45 ▶ open my $fh, '>>', $path or die "Cannot append $path: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">>", $path or die "Cannot append ${path}: $!\n" 45 0 45
619 45 binmode $fh;
620 45 ▶ flock($fh, LOCK_EX) or die "Cannot lock $path: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
flock $fh, 2 or die "Cannot lock ${path}: $!\n" 45 0 45
621 45 ▶ unless (_same_file($fh, $path)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_same_file($fh, $path)) 0 45 45
622 0 close $fh; # claimed by a replay meanwhile: append to a new file
623 0 next;
624 }
625 45 ▶ print {$fh} $lines or die "Cannot append $path: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $lines or die "Cannot append ${path}: $!\n" 45 0 45
626 45 ▶ $fh->flush or die "Cannot flush $path: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
$fh->flush or die "Cannot flush ${path}: $!\n" 45 0 45
627 45 ▶ $fh->sync or die "Cannot sync $path: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
$fh->sync or die "Cannot sync ${path}: $!\n" 45 0 45
628 45 ▶ close $fh or die "Cannot close $path: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die "Cannot close ${path}: $!\n" 45 0 45
629 45 return 1;
630 }
631 0 die "Cannot append $path: claimed by a replay on every attempt\n";
632 }
633  
634  
635 15 ▶sub replay_spool {
Subroutine replay_spool: called CC=10 SCAR=23.3
Pod documented
636 15 my ($self) = @_;
637 15 my %res = (ok => 1, replayed => 0, consumed => 0, remaining => 0);
638 15 ▶ return \%res unless length $self->spool_dir;
Branch: 1 branch
BranchTrueFalseTotal
unless length $self->spool_dir 0 15 15
639 15 my $dir = $self->spool_dir;
640  
641 # Claim: rename every writer file this process can lock right now.
642 15 for my $name ($self->_spool_files('writer')) {
643 13 my $path = File::Spec->catfile($dir, $name);
644 13 ▶ open my $fh, '<', $path or next;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $path or next 13 0 13
645 13 ▶ flock($fh, LOCK_EX | LOCK_NB) or next;
Branch: 1 branch
BranchTrueFalseTotal
flock $fh, 6 or next 13 0 13
646 13 ▶ rename($path, "$path.replay-" . _host() . "-$$-" . ++$CLAIM_SEQ) if _same_file($fh, $path);
Branch: 1 branch
BranchTrueFalseTotal
if _same_file($fh, $path) 13 0 13
647 13 close $fh;
648 }
649  
650 15 my $budget = $REPLAY_BATCH;
651 15 for my $name ($self->_spool_files('claimed')) {
652 17 ▶ last if $budget <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $budget <= 0 0 17 17
653 17 my $one = $self->_replay_file(File::Spec->catfile($dir, $name), $budget);
654 17 $res{replayed} += $one->{replayed};
655 17 $res{consumed} += $one->{consumed};
656 17 $budget -= $one->{consumed};
657 17 ▶ next if $one->{ok};
Branch: 1 branch
BranchTrueFalseTotal
if $one->{"ok"} 16 1 17
658 1 @res{qw(ok error)} = (0, $one->{error});
659 1 last;
660 }
661  
662 15 ▶ $res{remaining} = $self->_spool_files('any') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->_spool_files('any') ? : 3 12 15
663 15 $self->_spool_pending($res{remaining});
664 15 return \%res;
665 }
666  
667 17 ▶sub _replay_file {
Subroutine _replay_file: called CC=15 SCAR=28.8
668 17 my ($self, $path, $budget) = @_;
669 17 my %none = (ok => 1, replayed => 0, consumed => 0);
670 17 ▶ open my $fh, '<', $path or return \%none; # finished by another process
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $path or return \%none 17 0 17
671 17 ▶ flock($fh, LOCK_EX | LOCK_NB) or return \%none; # being replayed by another process
Branch: 1 branch
BranchTrueFalseTotal
flock $fh, 6 or return \%none 17 0 17
672 17 ▶ return \%none unless _same_file($fh, $path);
Branch: 1 branch
BranchTrueFalseTotal
unless _same_file($fh, $path) 0 17 17
673 17 binmode $fh;
674 17 my @lines = <$fh>;
675 17 my @take = splice @lines, 0, $budget;
676  
677 17 my @events;
678 17 for my $i (0 .. $#take) {
679 55 ▶ next unless $take[$i] =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $take[$i] =~ /\S/ 0 55 55
680 55 my $event = eval { decode_json($take[$i]) };
681 55 ▶ if (ref($event) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $event eq "HASH") 54 1 55
682 54 push @events, $event;
683 54 next;
684 }
685 # A torn last line (the process died mid-write, the disk filled up): nothing to replay.
686 1 warn "skeid: unreadable line dropped from usage spool $path\n";
687 }
688  
689 17 my $written = $self->_replay_events(\@events);
690 return { ok => 0, replayed => 0, consumed => 0, error => $written->{error} }
691 17 ▶ unless $written->{ok};
Branch: 1 branch
BranchTrueFalseTotal
unless $written->{"ok"} 1 16 17
692  
693 # Committed: only now do the lines leave the spool. Should this fail, they stay and the next
694 # replay skips them as already present.
695 16 ▶ if (@lines) {
Branch: 1 branch
BranchTrueFalseTotal
if (@lines) { } 2 14 16
696 2 my ($vol, $dir) = File::Spec->splitpath($path);
697 2 my $tmp = File::Spec->catpath($vol, $dir, ".tmp-$$-" . ++$CLAIM_SEQ);
698 2 ▶ if (open my $out, '>', $tmp) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $out, ">", $tmp) 2 0 2
699 2 binmode $out;
700 2 ▶ if ((print {$out} @lines) && $out->flush && $out->sync && close($out)) {
Branch: 1 branch
BranchTrueFalseTotal
if (print {$out;} @lines and $out->flush and $out->sync and close $out) { } 2 0 2
Condition33%3/9
print {$out;} @lines and $out->flush and $out->sync and close $out
!ll&&!rl&&r
002
print {$out;} @lines and $out->flush and $out->sync
!ll&&!rl&&r
002
print {$out;} @lines and $out->flush
!ll&&!rl&&r
002
MC/DC0%0/4
print {$out;} @lines and $out->flush and $out->sync and close $out
print {$out;} @lines $out->flush $out->sync close $out
Truth table20%1/5
A and B and C and D
A= print {$out;} @linesB= $out->flushC= $out->syncD= close $out
ABCDresult
0XXX0
10XX0
110X0
11100
11111
701 2 ▶ rename($tmp, $path) or unlink $tmp;
Branch: 1 branch
BranchTrueFalseTotal
rename $tmp, $path or unlink $tmp 2 0 2
702 } else {
703 0 unlink $tmp;
704 }
705 }
706 } else {
707 14 unlink $path;
708 }
709 16 close $fh;
710 16 return { ok => 1, replayed => $written->{written}, consumed => scalar(@take) };
711 }
712  
713 # One transaction for the batch. A refusal on a live handle falls back to one event at a time,
714 # so a single event the database will never take is reported lost and does not hold up the
715 # rest; a database that went away again stops the replay with the spool untouched.
716 17 ▶sub _replay_events {
Subroutine _replay_events: called CC=7 SCAR=27.5
717 17 my ($self, $events) = @_;
718 17 ▶ return { ok => 1, written => 0 } unless @$events;
Branch: 1 branch
BranchTrueFalseTotal
unless @$events 0 17 17
719  
720 16 ▶ my $batch = $self->_with_handle(sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
721 16 my ($dbh) = @_;
722 16 $dbh->begin_work;
723 16 my $written = eval {
724 16 my $n = 0;
725 16 $n += $self->_insert_once($dbh, $_) for @$events;
726 16 $dbh->commit;
727 16 $n;
728 };
729 16 ▶ unless (defined $written) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $written) 0 16 16
730 0 my $err = $@;
731 0 eval { $dbh->rollback };
732 0 die $err;
733 }
734 16 return { ok => 1, written => $written };
735 17 });
736 17 ▶ return $batch if $batch->{ok} || !$self->_dbh;
Branch: 1 branch
BranchTrueFalseTotal
if $batch->{"ok"} or not $self->_dbh 17 0 17
Condition66%2/3
$batch->{"ok"} or not $self->_dbh
l!l&&r!l&&!r
1610
MC/DC0%0/2
$batch->{"ok"} or not $self->_dbh
$batch->{"ok"} not $self->_dbh
Truth table66%2/3
A or not(B)
A= $batch->{"ok"}B= not $self->_dbh
ABresult
1X1
011
000
737  
738 0 my $written = 0;
739 0 for my $event (@$events) {
740 0 ▶ my $one = $self->_with_handle(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
741 0 my ($dbh) = @_;
742 0 return { ok => 1, written => $self->_insert_once($dbh, $event) };
743 0 });
744 0 ▶ if ($one->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($one->{"ok"}) 0 0 0
745 0 $written += $one->{written};
746 0 next;
747 }
748 0 ▶ return $one unless $self->_dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_dbh 0 0 0
749 0 $self->_report_lost($event, $one->{error});
750 }
751 0 return { ok => 1, written => $written };
752 }
753  
754 # After a write that succeeded: replay one batch of the spool. Inside the loop on the next tick,
755 # batch after batch while there is progress; outside it -- prepare at start, a script -- one
756 # batch at once, the rest with the next write.
757 130 ▶sub _schedule_replay {
Subroutine _schedule_replay: called CC=5 SCAR=25.7
758 130 my ($self) = @_;
759 130 ▶ return unless $self->_spool_pending && length $self->spool_dir;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_spool_pending and length $self->spool_dir 124 6 130
Condition66%2/3
$self->_spool_pending and length $self->spool_dir
!ll&&!rl&&r
12406
MC/DC50%1/2
$self->_spool_pending and length $self->spool_dir
$self->_spool_pending length $self->spool_dir
Truth table66%2/3
A and B
A= $self->_spool_pendingB= length $self->spool_dir
ABresult
0X0
100
111
760 6 ▶ unless (Mojo::IOLoop->is_running) {
Branch: 1 branch
BranchTrueFalseTotal
unless ("Mojo::IOLoop"->is_running) 6 0 6
761 6 $self->replay_spool;
762 6 return;
763 }
764 0 ▶ return if defined $self->_replay_timer;
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->_replay_timer 0 0 0
765 0 weaken(my $weak = $self);
766 0 ▶ $self->_replay_timer(Mojo::IOLoop->timer(0 => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
767 0 ▶ return unless $weak;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak 0 0 0
768 0 $weak->_replay_timer(undef);
769 0 my $res = $weak->replay_spool;
770 0 ▶ $weak->_schedule_replay if $res->{ok} && $res->{consumed} && $res->{remaining};
Branch: 1 branch
BranchTrueFalseTotal
if $res->{"ok"} and $res->{"consumed"} and $res->{"remaining"} 0 0 0
Condition0%0/6
$res->{"ok"} and $res->{"consumed"} and $res->{"remaining"}
!ll&&!rl&&r
000
$res->{"ok"} and $res->{"consumed"}
!ll&&!rl&&r
000
MC/DC0%0/3
$res->{"ok"} and $res->{"consumed"} and $res->{"remaining"}
$res->{"ok"} $res->{"consumed"} $res->{"remaining"}
Truth table0%0/4
A and B and C
A= $res->{"ok"}B= $res->{"consumed"}C= $res->{"remaining"}
ABCresult
0XX0
10X0
1100
1111
771 0 }));
772 0 return;
773 }
774  
775  
776  
777 6 ▶sub purge {
Subroutine purge: called CC=6 SCAR=17.9
Pod documented
778 6 my ($self, $request) = @_;
779 6 $self->flush;
780 6 ▶ if (length($self->spool_dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->spool_dir) 2 4 6
781 2 my @waiting = grep { -s File::Spec->catfile($self->spool_dir, $_) } $self->_spool_files('any');
782 2 ▶ return { ok => 0, error => 'the usage spool holds ' . scalar(@waiting) . ' file(s) of events '
Branch: 1 branch
BranchTrueFalseTotal
if @waiting 1 1 2
783 . 'not yet in the database; purge again once they are replayed' } if @waiting;
784 }
785  
786 5 my (@where, @bind);
787 5 ▶ if (my $ids = $request->{api_key_ids}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ids = $request->{"api_key_ids"}) 4 1 5
788 4 push @where, 'api_key_id IN (' . join(', ', ('?') x @$ids) . ')';
789 4 push @bind, @$ids;
790 }
791 5 ▶ if (defined $request->{before}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $request->{"before"}) 1 4 5
792 1 push @where, 'created_at < ?';
793 1 push @bind, $request->{before};
794 }
795 5 ▶ return { ok => 0, error => 'a purge needs api_key_ids, before, or both' } unless @where;
Branch: 1 branch
BranchTrueFalseTotal
unless @where 0 5 5
796 5 my $where = join ' AND ', @where;
797  
798 5 ▶ return $self->_with_handle(sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
799 5 my ($dbh) = @_;
800 5 my ($matched) = $dbh->selectrow_array("SELECT COUNT(*) FROM usage_events WHERE $where", undef, @bind);
801 5 my $deleted = 0;
802 5 ▶ unless ($request->{dry_run}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($request->{"dry_run"}) 4 1 5
803 4 $deleted = $dbh->do("DELETE FROM usage_events WHERE $where", undef, @bind);
804 4 ▶ $deleted = 0 if !defined($deleted) || $deleted eq '0E0';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $deleted or $deleted eq "0E0" 2 2 4
Condition66%2/3
not defined $deleted or $deleted eq "0E0"
l!l&&r!l&&!r
022
MC/DC50%1/2
not defined $deleted or $deleted eq "0E0"
not defined $deleted $deleted eq "0E0"
Truth table66%2/3
not(A) or B
A= not defined $deletedB= $deleted eq "0E0"
ABresult
1X1
011
000
805 }
806 5 ▶ return { ok => 1, matched => 0 + ($matched // 0), deleted => 0 + $deleted };
Condition50%1/2
$matched // 0
l!l
50
MC/DC0%0/1
$matched // 0
$matched
Truth table50%1/2
A
A= $matched
Aresult
11
00
807 5 });
808 }
809  
810 24 ▶sub report {
Subroutine report: called CC=3 SCAR=11.0
Pod documented
811 24 my ($self, $filters) = @_;
812 24 ▶ $filters ||= {};
Condition50%1/2
$filters ||= {}
l!l
240
MC/DC0%0/1
$filters ||= {}
$filters
Truth table50%1/2
A
A= $filters
Aresult
11
00
813 24 $self->flush;
814  
815 24 ▶ my $report = $self->_with_handle(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
816 24 my ($dbh) = @_;
817 24 return $self->_report($dbh, $filters);
818 24 });
819 24 ▶ return $report->{ok} ? $report : { %$report, enabled => 0 };
Branch: 1 branch
BranchTrueFalseTotal
$report->{'ok'} ? : 23 1 24
820 }
821  
822 24 ▶sub _report {
Subroutine _report: called CC=29 SCAR=40.6
823 24 my ($self, $dbh, $filters) = @_;
824 24 my $num = \&Langertha::Skeid::UsageStore::num;
825  
826 24 ▶ my $limit = $filters->{limit} // 20;
Condition100%2/2
$filters->{"limit"} // 20
l!l
213
MC/DC100%1/1
$filters->{"limit"} // 20
$filters->{"limit"}
Truth table100%2/2
A
A= $filters->{"limit"}
Aresult
11
00
827  
828 24 my @where;
829 my @bind;
830 24 ▶ if (defined $filters->{since} && length $filters->{since}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filters->{"since"} and length $filters->{"since"}) 0 24 24
Condition33%1/3
defined $filters->{"since"} and length $filters->{"since"}
!ll&&!rl&&r
2400
MC/DC0%0/2
defined $filters->{"since"} and length $filters->{"since"}
defined $filters->{"since"} length $filters->{"since"}
Truth table33%1/3
A and B
A= defined $filters->{"since"}B= length $filters->{"since"}
ABresult
0X0
100
111
831 0 push @where, 'created_at >= ?';
832 0 push @bind, $filters->{since};
833 }
834 24 ▶ if (defined $filters->{api_key_id} && length $filters->{api_key_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filters->{"api_key_id"} and length $filters->{"api_key_id"}) 3 21 24
Condition66%2/3
defined $filters->{"api_key_id"} and length $filters->{"api_key_id"}
!ll&&!rl&&r
2103
MC/DC50%1/2
defined $filters->{"api_key_id"} and length $filters->{"api_key_id"}
defined $filters->{"api_key_id"} length $filters->{"api_key_id"}
Truth table66%2/3
A and B
A= defined $filters->{"api_key_id"}B= length $filters->{"api_key_id"}
ABresult
0X0
100
111
835 3 push @where, 'api_key_id = ?';
836 3 push @bind, $filters->{api_key_id};
837 }
838 24 ▶ if (defined $filters->{model} && length $filters->{model}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filters->{"model"} and length $filters->{"model"}) 0 24 24
Condition33%1/3
defined $filters->{"model"} and length $filters->{"model"}
!ll&&!rl&&r
2400
MC/DC0%0/2
defined $filters->{"model"} and length $filters->{"model"}
defined $filters->{"model"} length $filters->{"model"}
Truth table33%1/3
A and B
A= defined $filters->{"model"}B= length $filters->{"model"}
ABresult
0X0
100
111
839 0 push @where, 'model = ?';
840 0 push @bind, $filters->{model};
841 }
842  
843 24 ▶ my $where_sql = @where ? ('WHERE ' . join(' AND ', @where)) : '';
Branch: 1 branch
BranchTrueFalseTotal
@where ? : 3 21 24
844  
845 24 ▶ my $totals = $dbh->selectrow_hashref(
Condition50%1/2
$dbh->selectrow_hashref("SELECT\n COUNT(*) AS requests,\n COALESCE(SUM(input_tokens), 0) AS input_tokens,\n COALESCE(SUM(output_tokens), 0) AS output_tokens,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cached_tokens), 0) AS cached_tokens,\n COALESCE(SUM(cache_write_tokens), 0) AS cache_write_tokens,\n COALESCE(SUM(tool_calls), 0) AS tool_calls,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events $where_sql", undef, @bind) || {}
l!l
230
MC/DC0%0/1
$dbh->selectrow_hashref("SELECT\n COUNT(*) AS requests,\n COALESCE(SUM(input_tokens), 0) AS input_tokens,\n COALESCE(SUM(output_tokens), 0) AS output_tokens,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cached_tokens), 0) AS cached_tokens,\n COALESCE(SUM(cache_write_tokens), 0) AS cache_write_tokens,\n COALESCE(SUM(tool_calls), 0) AS tool_calls,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events $where_sql", undef, @bind) || {}
$dbh->selectrow_hashref("SELECT\n COUNT(*) AS requests,\n COALESCE(SUM(input_tokens), 0) AS input_tokens,\n COALESCE(SUM(output_tokens), 0) AS output_tokens,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cached_tokens), 0) AS cached_tokens,\n COALESCE(SUM(cache_write_tokens), 0) AS cache_write_tokens,\n COALESCE(SUM(tool_calls), 0) AS tool_calls,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events $where_sql", undef, @bind)
Truth table50%1/2
A
A= $dbh->selectrow_hashref("SELECT\n COUNT(*) AS requests,\n COALESCE(SUM(input_tokens), 0) AS input_tokens,\n COALESCE(SUM(output_tokens), 0) AS output_tokens,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(cached_tokens), 0) AS cached_tokens,\n COALESCE(SUM(cache_write_tokens), 0) AS cache_write_tokens,\n COALESCE(SUM(tool_calls), 0) AS tool_calls,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events $where_sql", undef, @bind)
Aresult
11
00
846 "SELECT
847 COUNT(*) AS requests,
848 COALESCE(SUM(input_tokens), 0) AS input_tokens,
849 COALESCE(SUM(output_tokens), 0) AS output_tokens,
850 COALESCE(SUM(total_tokens), 0) AS total_tokens,
851 COALESCE(SUM(cached_tokens), 0) AS cached_tokens,
852 COALESCE(SUM(cache_write_tokens), 0) AS cache_write_tokens,
853 COALESCE(SUM(tool_calls), 0) AS tool_calls,
854 COALESCE(SUM(audio_seconds), 0) AS audio_seconds,
855 COALESCE(SUM(documents), 0) AS documents,
856 COALESCE(SUM(pages), 0) AS pages,
857 COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd
858 FROM usage_events $where_sql",
859 undef,
860 @bind,
861 ) || {};
862  
863 23 ▶ my $by_key = $dbh->selectall_arrayref(
Condition50%1/2
$dbh->selectall_arrayref("SELECT\n COALESCE(api_key_id, '') AS api_key_id,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY api_key_id\n ORDER BY total_cost_usd DESC, requests DESC, api_key_id ASC", {'Slice', {}}, @bind) || []
l!l
230
MC/DC0%0/1
$dbh->selectall_arrayref("SELECT\n COALESCE(api_key_id, '') AS api_key_id,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY api_key_id\n ORDER BY total_cost_usd DESC, requests DESC, api_key_id ASC", {'Slice', {}}, @bind) || []
$dbh->selectall_arrayref("SELECT\n COALESCE(api_key_id, '') AS api_key_id,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY api_key_id\n ORDER BY total_cost_usd DESC, requests DESC, api_key_id ASC", {'Slice', {}}, @bind)
Truth table50%1/2
A
A= $dbh->selectall_arrayref("SELECT\n COALESCE(api_key_id, '') AS api_key_id,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY api_key_id\n ORDER BY total_cost_usd DESC, requests DESC, api_key_id ASC", {'Slice', {}}, @bind)
Aresult
11
00
864 "SELECT
865 COALESCE(api_key_id, '') AS api_key_id,
866 COUNT(*) AS requests,
867 COALESCE(SUM(total_tokens), 0) AS total_tokens,
868 COALESCE(SUM(audio_seconds), 0) AS audio_seconds,
869 COALESCE(SUM(documents), 0) AS documents,
870 COALESCE(SUM(pages), 0) AS pages,
871 COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd
872 FROM usage_events
873 $where_sql
874 GROUP BY api_key_id
875 ORDER BY total_cost_usd DESC, requests DESC, api_key_id ASC",
876 { Slice => {} },
877 @bind,
878 ) || [];
879  
880 23 ▶ my $by_model = $dbh->selectall_arrayref(
Condition50%1/2
$dbh->selectall_arrayref("SELECT\n COALESCE(model, '') AS model,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY model\n ORDER BY total_cost_usd DESC, requests DESC, model ASC", {'Slice', {}}, @bind) || []
l!l
230
MC/DC0%0/1
$dbh->selectall_arrayref("SELECT\n COALESCE(model, '') AS model,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY model\n ORDER BY total_cost_usd DESC, requests DESC, model ASC", {'Slice', {}}, @bind) || []
$dbh->selectall_arrayref("SELECT\n COALESCE(model, '') AS model,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY model\n ORDER BY total_cost_usd DESC, requests DESC, model ASC", {'Slice', {}}, @bind)
Truth table50%1/2
A
A= $dbh->selectall_arrayref("SELECT\n COALESCE(model, '') AS model,\n COUNT(*) AS requests,\n COALESCE(SUM(total_tokens), 0) AS total_tokens,\n COALESCE(SUM(audio_seconds), 0) AS audio_seconds,\n COALESCE(SUM(documents), 0) AS documents,\n COALESCE(SUM(pages), 0) AS pages,\n COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd\n FROM usage_events\n $where_sql\n GROUP BY model\n ORDER BY total_cost_usd DESC, requests DESC, model ASC", {'Slice', {}}, @bind)
Aresult
11
00
881 "SELECT
882 COALESCE(model, '') AS model,
883 COUNT(*) AS requests,
884 COALESCE(SUM(total_tokens), 0) AS total_tokens,
885 COALESCE(SUM(audio_seconds), 0) AS audio_seconds,
886 COALESCE(SUM(documents), 0) AS documents,
887 COALESCE(SUM(pages), 0) AS pages,
888 COALESCE(SUM(cost_total_usd), 0) AS total_cost_usd
889 FROM usage_events
890 $where_sql
891 GROUP BY model
892 ORDER BY total_cost_usd DESC, requests DESC, model ASC",
893 { Slice => {} },
894 @bind,
895 ) || [];
896  
897 23 ▶ my $recent = $dbh->selectall_arrayref(
Condition50%1/2
$dbh->selectall_arrayref("SELECT\n id, created_at, api_format, endpoint, api_key_id, model, requested_model, routed_model, node_id, status_code, ok,\n input_tokens, output_tokens, total_tokens, cached_tokens, cache_write_tokens, tool_calls, cost_total_usd\n FROM usage_events\n $where_sql\n ORDER BY id DESC\n LIMIT ?", {'Slice', {}}, @bind, $limit) || []
l!l
230
MC/DC0%0/1
$dbh->selectall_arrayref("SELECT\n id, created_at, api_format, endpoint, api_key_id, model, requested_model, routed_model, node_id, status_code, ok,\n input_tokens, output_tokens, total_tokens, cached_tokens, cache_write_tokens, tool_calls, cost_total_usd\n FROM usage_events\n $where_sql\n ORDER BY id DESC\n LIMIT ?", {'Slice', {}}, @bind, $limit) || []
$dbh->selectall_arrayref("SELECT\n id, created_at, api_format, endpoint, api_key_id, model, requested_model, routed_model, node_id, status_code, ok,\n input_tokens, output_tokens, total_tokens, cached_tokens, cache_write_tokens, tool_calls, cost_total_usd\n FROM usage_events\n $where_sql\n ORDER BY id DESC\n LIMIT ?", {'Slice', {}}, @bind, $limit)
Truth table50%1/2
A
A= $dbh->selectall_arrayref("SELECT\n id, created_at, api_format, endpoint, api_key_id, model, requested_model, routed_model, node_id, status_code, ok,\n input_tokens, output_tokens, total_tokens, cached_tokens, cache_write_tokens, tool_calls, cost_total_usd\n FROM usage_events\n $where_sql\n ORDER BY id DESC\n LIMIT ?", {'Slice', {}}, @bind, $limit)
Aresult
11
00
898 "SELECT
899 id, created_at, api_format, endpoint, api_key_id, model, requested_model, routed_model, node_id, status_code, ok,
900 input_tokens, output_tokens, total_tokens, cached_tokens, cache_write_tokens, tool_calls, cost_total_usd
901 FROM usage_events
902 $where_sql
903 ORDER BY id DESC
904 LIMIT ?",
905 { Slice => {} },
906 @bind,
907 $limit,
908 ) || [];
909  
910 return {
911 ok => 1,
912 enabled => 1,
913 backend => $self->backend,
914 db_path => ($self->backend eq 'sqlite' ? ($self->path // '') : ''),
915 since => ($filters->{since} // ''),
916 totals => {
917 requests => $num->($totals->{requests}),
918 input_tokens => $num->($totals->{input_tokens}),
919 output_tokens => $num->($totals->{output_tokens}),
920 total_tokens => $num->($totals->{total_tokens}),
921 cached_tokens => $num->($totals->{cached_tokens}),
922 cache_write_tokens => $num->($totals->{cache_write_tokens}),
923 tool_calls => $num->($totals->{tool_calls}),
924 audio_seconds => $num->($totals->{audio_seconds}),
925 documents => $num->($totals->{documents}),
926 pages => $num->($totals->{pages}),
927 total_cost_usd => $num->($totals->{total_cost_usd}),
928 },
929 by_key => [ map {
930 +{
931 api_key_id => ($_->{api_key_id} // ''),
932 requests => $num->($_->{requests}),
933 total_tokens => $num->($_->{total_tokens}),
934 audio_seconds => $num->($_->{audio_seconds}),
935 documents => $num->($_->{documents}),
936 pages => $num->($_->{pages}),
937 54 ▶ total_cost_usd => $num->($_->{total_cost_usd}),
Condition50%1/2
$_->{"api_key_id"} // ""
l!l
540
MC/DC0%0/1
$_->{"api_key_id"} // ""
$_->{"api_key_id"}
Truth table50%1/2
A
A= $_->{"api_key_id"}
Aresult
11
00
938 }
939 } @$by_key ],
940 by_model => [ map {
941 +{
942 model => ($_->{model} // ''),
943 requests => $num->($_->{requests}),
944 total_tokens => $num->($_->{total_tokens}),
945 audio_seconds => $num->($_->{audio_seconds}),
946 documents => $num->($_->{documents}),
947 pages => $num->($_->{pages}),
948 50 ▶ total_cost_usd => $num->($_->{total_cost_usd}),
Condition50%1/2
$_->{"model"} // ""
l!l
500
MC/DC0%0/1
$_->{"model"} // ""
$_->{"model"}
Truth table50%1/2
A
A= $_->{"model"}
Aresult
11
00
949 }
950 } @$by_model ],
951 recent => [ map {
952 23 ▶ +{
Branch: 1 branch
BranchTrueFalseTotal
$self->backend eq 'sqlite' ? : 23 0 23
Condition50%2/4
$self->path // ""
l!l
230
$filters->{"since"} // ""
l!l
023
MC/DC0%0/1
$self->path // ""
$self->path
MC/DC0%0/1
$filters->{"since"} // ""
$filters->{"since"}
Truth table50%1/2
A
A= $self->path
Aresult
11
00
Truth table50%1/2
A
A= $filters->{"since"}
Aresult
11
00
953 id => $num->($_->{id}),
954 created_at => ($_->{created_at} // ''),
955 api_format => ($_->{api_format} // ''),
956 endpoint => ($_->{endpoint} // ''),
957 api_key_id => ($_->{api_key_id} // ''),
958 model => ($_->{model} // ''),
959 requested_model => ($_->{requested_model} // $_->{model} // ''),
960 # Only a request the catch-all bent (ADR 0033); absent otherwise.
961 (defined($_->{routed_model}) && length($_->{routed_model}) ? (routed_model => $_->{routed_model}) : ()),
962 node_id => ($_->{node_id} // ''),
963 status_code => $num->($_->{status_code}),
964 ok => ($_->{ok} ? 1 : 0),
965 input_tokens => $num->($_->{input_tokens}),
966 output_tokens => $num->($_->{output_tokens}),
967 total_tokens => $num->($_->{total_tokens}),
968 cached_tokens => $num->($_->{cached_tokens}),
969 cache_write_tokens => $num->($_->{cache_write_tokens}),
970 tool_calls => $num->($_->{tool_calls}),
971 67 ▶ cost_total_usd => $num->($_->{cost_total_usd}),
Branch: 2 branches
BranchTrueFalseTotal
defined $_->{'routed_model'} && length $_->{'routed_model'} ? : 0 67 67
$_->{'ok'} ? : 65 2 67
Condition70%14/20
$_->{"created_at"} // ""
l!l
670
$_->{"api_format"} // ""
l!l
625
$_->{"endpoint"} // ""
l!l
625
$_->{"api_key_id"} // ""
l!l
661
$_->{"model"} // ""
l!l
670
($_->{"requested_model"} // $_->{"model"}) // ""
l!l
670
$_->{"requested_model"} // $_->{"model"}
l!l&&r!l&&!r
6250
defined $_->{"routed_model"} and length $_->{"routed_model"}
!ll&&!rl&&r
6700
$_->{"node_id"} // ""
l!l
625
MC/DC0%0/1
$_->{"created_at"} // ""
$_->{"created_at"}
MC/DC100%1/1
$_->{"api_format"} // ""
$_->{"api_format"}
MC/DC100%1/1
$_->{"endpoint"} // ""
$_->{"endpoint"}
MC/DC100%1/1
$_->{"api_key_id"} // ""
$_->{"api_key_id"}
MC/DC0%0/1
$_->{"model"} // ""
$_->{"model"}
MC/DC0%0/2
($_->{"requested_model"} // $_->{"model"}) // ""
$_->{"requested_model"} $_->{"model"}
MC/DC0%0/2
defined $_->{"routed_model"} and length $_->{"routed_model"}
defined $_->{"routed_model"} length $_->{"routed_model"}
MC/DC100%1/1
$_->{"node_id"} // ""
$_->{"node_id"}
Truth table50%1/2
A
A= $_->{"created_at"}
Aresult
11
00
Truth table100%2/2
A
A= $_->{"api_format"}
Aresult
11
00
Truth table100%2/2
A
A= $_->{"endpoint"}
Aresult
11
00
Truth table100%2/2
A
A= $_->{"api_key_id"}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"model"}
Aresult
11
00
Truth table66%2/3
A // B
A= $_->{"requested_model"}B= $_->{"model"}
ABresult
1X1
011
000
Truth table33%1/3
A and B
A= defined $_->{"routed_model"}B= length $_->{"routed_model"}
ABresult
0X0
100
111
Truth table100%2/2
A
A= $_->{"node_id"}
Aresult
11
00
972 }
973 } @$recent ],
974 };
975 }
976  
977  
978 18 1;
979  
980 __END__
« lib/Langertha/Skeid/Rate.pm ↑ Summary lib/Langertha/Skeid/Protocol/Ollama/Stream.pm »