blib/lib/Langertha/Skeid.pm

filter: Statementstmt 97.1% 1310 / 1348 Branchbran 80.9% 625 / 772 Conditioncond 63.6% 578 / 908 MC/DCmcdc 36.3% 179 / 493 Subroutinesub 98.8% 171 / 173 Podpod 95.5% 43 / 45 totaltotal 77.7% 2906 / 3739 CC 794 SCAR 35.4
CC
794
Cov
83%
call_function
268.5
_usage_lost
61.2
_load_manifest
56.8
CRAP 34.5
« blib/lib/Langertha/Skeid/Protocol/Anthropic.pm ↑ Summary blib/lib/Langertha/Skeid/UsageStore/JsonLog.pm »
1 package Langertha::Skeid;
2 67 our $VERSION = '0.003';
3 # ABSTRACT: Dynamic routing control-plane for multi-node LLM serving with normalized metrics and cost accounting
4 67 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 67 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 67 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 67 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 67 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 67 ▶use Digest::SHA qw(sha1_hex sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 67 ▶use Scalar::Util qw(blessed looks_like_number refaddr reftype weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 67 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 67 ▶use YAML::PP;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 67 ▶use Langertha ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 67 ▶use Langertha::Skeid::UsageStore;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 67 ▶use Langertha::Skeid::Protocol;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 67 ▶use Langertha::Skeid::Protocol::Anthropic;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 67 ▶use Langertha::Skeid::Protocol::Ollama;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 67 ▶use Langertha::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 67 ▶use Langertha::Cost;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 67 ▶use Langertha::Pricing;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 67 ▶use Langertha::UsageRecord;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23  
24  
25 has nodes => (
26 is => 'rw',
27 499 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
28 # Routing caches derived node lists, so every path that can change the inventory has to
29 # invalidate them. The methods below bump the generation explicitly; this trigger catches
30 # the remaining one -- somebody assigning the whole list through the public accessor.
31 1344 ▶ trigger => sub { $_[0]->_bump_inventory },
Subroutine __ANON__: called CC=1 SCAR=0.0
32 67 );
33  
34  
35 has model_pricing => (
36 is => 'rw',
37 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
38 67 );
39  
40  
41 has model_aliases => (
42 is => 'rw',
43 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
44 67 );
45  
46  
47 has policies => (
48 is => 'rw',
49 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
50 67 );
51  
52  
53 has default_policy => (
54 is => 'rw',
55 499 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
56 67 );
57  
58  
59 # Key id -> resolved policy. Identical resolutions share one object, and a key that takes the
60 # default is not listed at all, so ten thousand identical customers cost nothing here.
61 has key_policies => (
62 is => 'rw',
63 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
64 67 );
65  
66  
67 # Readable name -> customer key id, from the config `names:` section. A config-authoring
68 # convenience only: it lets `keys:` entries be written by name and localises key rotation to
69 # one line, and is resolved to key ids once at config load. It never reaches the request path
70 # -- a request still carries a derived key id, and policy_for_key still costs one hash lookup.
71 has key_names => (
72 is => 'rw',
73 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
74 67 );
75  
76  
77 # /.well-known/langertha.json (skeid #29, ADR 0015). Off until the config enables it.
78 has manifest_enabled => (
79 is => 'rw',
80 499 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
81 67 );
82  
83 # Whether this Langertha has Langertha::Manifest (core newer than 0.503). Enabled without it,
84 # the route answers 404 rather than failing the config.
85 has manifest_available => (
86 is => 'rw',
87 499 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
88 67 );
89  
90 # Key id -> the canonical JSON of that key's manifest, built at config load. This is the
91 # manifest cache, and it is keyed by the key id the caller's key derives to: a customer can
92 # only ever be served the entry built from its own keys: line, never another key's catalog.
93 has key_manifests => (
94 is => 'rw',
95 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
96 67 );
97  
98  
99 # Whether x-skeid-key-id / x-api-key-id from the client may name the customer. Off by default:
100 # once a policy hangs off the key id, believing that header lets any client pick its own
101 # permissions in one line. Turn it on only when something in front of Skeid authenticates the
102 # caller and sets the header itself.
103 67 has trust_key_id_header => (
104 is => 'rw',
105 builder => '_build_trust_key_id_header',
106 );
107  
108 499 ▶sub _build_trust_key_id_header {
Subroutine _build_trust_key_id_header: called CC=3 SCAR=14.2
109 499 ▶ return (defined($ENV{SKEID_TRUST_KEY_ID_HEADER}) && $ENV{SKEID_TRUST_KEY_ID_HEADER} =~ /^(1|true|yes|on)$/i)
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_TRUST_KEY_ID_HEADER'} && $ENV{'SKEID_TRUST_KEY_ID_HEADER'} =~ /^(1|true|yes|on)$/i ? : 0 499 499
Condition33%1/3
defined $ENV{"SKEID_TRUST_KEY_ID_HEADER"} and $ENV{"SKEID_TRUST_KEY_ID_HEADER"} =~ /^(1|true|yes|on)$/i
!ll&&!rl&&r
49900
MC/DC0%0/2
defined $ENV{"SKEID_TRUST_KEY_ID_HEADER"} and $ENV{"SKEID_TRUST_KEY_ID_HEADER"} =~ /^(1|true|yes|on)$/i
defined $ENV{"SKEID_TRUST_KEY_ID_HEADER"} $ENV{"SKEID_TRUST_KEY_ID_HEADER"} =~ /^(1|true|yes|on)$/i
Truth table33%1/3
A and B
A= defined $ENV{"SKEID_TRUST_KEY_ID_HEADER"}B= $ENV{"SKEID_TRUST_KEY_ID_HEADER"} =~ /^(1|true|yes|on)$/i
ABresult
0X0
100
111
110 ? 1 : 0;
111 }
112  
113  
114 67 has route_wait_timeout_ms => (
115 is => 'rw',
116 builder => '_build_route_wait_timeout_ms',
117 );
118  
119 485 ▶sub _build_route_wait_timeout_ms {
Subroutine _build_route_wait_timeout_ms: called CC=3 SCAR=12.0
120 return (defined($ENV{SKEID_ROUTE_WAIT_TIMEOUT_MS}) && length($ENV{SKEID_ROUTE_WAIT_TIMEOUT_MS}))
121 ? 0 + $ENV{SKEID_ROUTE_WAIT_TIMEOUT_MS}
122 485 ▶ : 2000;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_ROUTE_WAIT_TIMEOUT_MS'} && length $ENV{'SKEID_ROUTE_WAIT_TIMEOUT_MS'} ? : 0 485 485
Condition66%2/3
defined $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"} and length $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"}
!ll&&!rl&&r
48410
MC/DC0%0/2
defined $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"} and length $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"}
defined $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"} length $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"}
Truth table66%2/3
A and B
A= defined $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"}B= length $ENV{"SKEID_ROUTE_WAIT_TIMEOUT_MS"}
ABresult
0X0
100
111
123 }
124  
125  
126 67 has route_wait_poll_ms => (
127 is => 'rw',
128 builder => '_build_route_wait_poll_ms',
129 );
130  
131 365 ▶sub _build_route_wait_poll_ms {
Subroutine _build_route_wait_poll_ms: called CC=3 SCAR=14.2
132 return (defined($ENV{SKEID_ROUTE_WAIT_POLL_MS}) && length($ENV{SKEID_ROUTE_WAIT_POLL_MS}))
133 ? 0 + $ENV{SKEID_ROUTE_WAIT_POLL_MS}
134 365 ▶ : 25;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_ROUTE_WAIT_POLL_MS'} && length $ENV{'SKEID_ROUTE_WAIT_POLL_MS'} ? : 0 365 365
Condition33%1/3
defined $ENV{"SKEID_ROUTE_WAIT_POLL_MS"} and length $ENV{"SKEID_ROUTE_WAIT_POLL_MS"}
!ll&&!rl&&r
36500
MC/DC0%0/2
defined $ENV{"SKEID_ROUTE_WAIT_POLL_MS"} and length $ENV{"SKEID_ROUTE_WAIT_POLL_MS"}
defined $ENV{"SKEID_ROUTE_WAIT_POLL_MS"} length $ENV{"SKEID_ROUTE_WAIT_POLL_MS"}
Truth table33%1/3
A and B
A= defined $ENV{"SKEID_ROUTE_WAIT_POLL_MS"}B= length $ENV{"SKEID_ROUTE_WAIT_POLL_MS"}
ABresult
0X0
100
111
135 }
136  
137  
138 has usage_db_path => (
139 is => 'rw',
140 predicate => 'has_usage_db_path',
141 clearer => 'clear_usage_db_path',
142 499 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
143 return (defined($ENV{SKEID_USAGE_DB}) && length($ENV{SKEID_USAGE_DB}))
144 ? $ENV{SKEID_USAGE_DB}
145 499 ▶ : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_USAGE_DB'} && length $ENV{'SKEID_USAGE_DB'} ? : 0 499 499
Condition33%1/3
defined $ENV{"SKEID_USAGE_DB"} and length $ENV{"SKEID_USAGE_DB"}
!ll&&!rl&&r
49900
MC/DC0%0/2
defined $ENV{"SKEID_USAGE_DB"} and length $ENV{"SKEID_USAGE_DB"}
defined $ENV{"SKEID_USAGE_DB"} length $ENV{"SKEID_USAGE_DB"}
Truth table33%1/3
A and B
A= defined $ENV{"SKEID_USAGE_DB"}B= length $ENV{"SKEID_USAGE_DB"}
ABresult
0X0
100
111
146 },
147 67 );
148  
149  
150 has usage_store => (
151 is => 'rw',
152 476 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
153 67 );
154  
155  
156 67 has store_usage_event => (
157 is => 'ro',
158 predicate => 'has_store_usage_event',
159 );
160  
161  
162 67 has query_usage_report => (
163 is => 'ro',
164 predicate => 'has_query_usage_report',
165 );
166  
167  
168 67 has on_usage_lost => (
169 is => 'rw',
170 predicate => 'has_on_usage_lost',
171 );
172  
173  
174 67 has admin_api_key => (
175 is => 'rw',
176 builder => '_build_admin_api_key',
177 );
178  
179 994 ▶sub _build_admin_api_key { $_[0]->_env_admin_api_key }
Subroutine _build_admin_api_key: called CC=1 SCAR=0.0
180  
181 1201 ▶sub _env_admin_api_key {
Subroutine _env_admin_api_key: called CC=3 SCAR=11.0
182 return (defined($ENV{SKEID_ADMIN_API_KEY}) && length($ENV{SKEID_ADMIN_API_KEY}))
183 ? $ENV{SKEID_ADMIN_API_KEY}
184 1201 ▶ : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_ADMIN_API_KEY'} && length $ENV{'SKEID_ADMIN_API_KEY'} ? : 6 1195 1201
Condition100%3/3
defined $ENV{"SKEID_ADMIN_API_KEY"} and length $ENV{"SKEID_ADMIN_API_KEY"}
!ll&&!rl&&r
1173226
MC/DC100%2/2
defined $ENV{"SKEID_ADMIN_API_KEY"} and length $ENV{"SKEID_ADMIN_API_KEY"}
defined $ENV{"SKEID_ADMIN_API_KEY"} length $ENV{"SKEID_ADMIN_API_KEY"}
Truth table100%3/3
A and B
A= defined $ENV{"SKEID_ADMIN_API_KEY"}B= length $ENV{"SKEID_ADMIN_API_KEY"}
ABresult
0X0
100
111
185 }
186  
187 # The admin API key given explicitly -- to new(), to build_app, or by `skeid serve
188 # --admin-api-key` (skeid k64). It outranks the config, so a reload re-resolves the key under
189 # it instead of overwriting it; empty means none was given.
190 has _explicit_admin_api_key => (
191 is => 'rw',
192 init_arg => undef,
193 499 ▶ default => sub { '' },
Subroutine __ANON__: called CC=1 SCAR=0.0
194 67 );
195  
196 # The admin API key the config (or SKEID_ADMIN_API_KEY under it) resolved to when it was last
197 # applied. Kept apart from the explicit key so that clearing that one falls back to it at once.
198 67 has _config_admin_api_key => (
199 is => 'rw',
200 init_arg => undef,
201 builder => '_build_admin_api_key',
202 );
203  
204  
205 67 has key_broker => (is => 'ro', predicate => 'has_key_broker');
206  
207  
208 67 has config_file => (
209 is => 'ro',
210 predicate => 'has_config_file',
211 );
212  
213  
214 67 has config_loader => (
215 is => 'ro',
216 predicate => 'has_config_loader',
217 );
218  
219 has _config_mtime => (
220 is => 'rw',
221 499 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
222 67 );
223  
224 # A file version that failed before it could update _config_mtime, and when that same version
225 # may be tried again. A different mtime bypasses this window, so a correction is prompt; the
226 # retry keeps a transient read error from freezing an otherwise unchanged file forever.
227 has _config_file_failed_mtime => (
228 is => 'rw',
229 499 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
230 67 );
231  
232 has _config_file_retry_at => (
233 is => 'rw',
234 499 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
235 67 );
236  
237 # Set while config_file is missing after a good load, so the loss is warned once.
238 has _config_file_missing => (
239 is => 'rw',
240 499 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
241 67 );
242  
243  
244 has config_reload_interval => (
245 is => 'rw',
246 470 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
247 return (defined($ENV{SKEID_CONFIG_RELOAD_INTERVAL}) && length($ENV{SKEID_CONFIG_RELOAD_INTERVAL}))
248 ? 0 + $ENV{SKEID_CONFIG_RELOAD_INTERVAL}
249 470 ▶ : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_CONFIG_RELOAD_INTERVAL'} && length $ENV{'SKEID_CONFIG_RELOAD_INTERVAL'} ? : 0 470 470
Condition33%1/3
defined $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"} and length $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"}
!ll&&!rl&&r
47000
MC/DC0%0/2
defined $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"} and length $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"}
defined $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"} length $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"}
Truth table33%1/3
A and B
A= defined $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"}B= length $ENV{"SKEID_CONFIG_RELOAD_INTERVAL"}
ABresult
0X0
100
111
250 },
251 67 );
252  
253 # When the loader may run next (see config_reload_interval).
254 has _config_next_check_at => (
255 is => 'rw',
256 499 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
257 67 );
258  
259 # What the last applied config was: the loader's version when it gives one, else a digest of
260 # the loaded structure. A reload that reads the same fingerprint changes nothing (skeid #38).
261 has _config_fingerprint => (
262 is => 'rw',
263 499 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
264 67 );
265  
266  
267 499 ▶has last_reload_error => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
268 499 ▶has last_reload_error_at => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
269 499 ▶has reload_failures => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
270  
271 # The fingerprint of the config that last failed to apply. Reading the same one again is not
272 # retried: the answer would be the same error (skeid #39).
273 has _failed_fingerprint => (
274 is => 'rw',
275 499 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
276 67 );
277  
278 # The routing attributes as they were before any config was applied (see BUILD).
279 has _routing_baseline => (
280 is => 'rw',
281 init_arg => undef,
282 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
283 67 );
284  
285 # The sections the last applied config declared (see _apply_config). A section that was declared
286 # and is gone from the next config goes back to its default; one never declared is left alone.
287 has _config_declared => (
288 is => 'rw',
289 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
290 67 );
291  
292 # Digest of the nodes section the node list was last built from. An unchanged section keeps
293 # the node list -- and with it the inventory generation, the running probes and any health an
294 # admin set -- even when another section of the config changed.
295 has _nodes_fingerprint => (
296 is => 'rw',
297 499 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
298 67 );
299  
300 has _rr_cursor => (
301 is => 'rw',
302 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
303 67 );
304  
305 has _inventory_generation => (
306 is => 'rw',
307 499 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
308 67 );
309  
310 has _route_cache => (
311 is => 'rw',
312 499 ▶ default => sub { { generation => -1, entries => {}, order => [] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
313 67 );
314  
315 # The probe key (see _probe_inventory_key) as of one inventory generation.
316 has _probe_key_cache => (
317 is => 'rw',
318 499 ▶ default => sub { { generation => -1, key => undef } },
Subroutine __ANON__: called CC=1 SCAR=0.0
319 67 );
320  
321 has _inflight => (
322 is => 'rw',
323 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
324 67 );
325  
326 # node_id => normalized capacity reading (see set_capacity_reading). Written by probes off the
327 # request path, read by admission.
328 has _capacity => (
329 is => 'rw',
330 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
331 67 );
332  
333  
334 has capacity_max_age_ms => (
335 is => 'rw',
336 489 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
337 return (defined($ENV{SKEID_CAPACITY_MAX_AGE_MS}) && length($ENV{SKEID_CAPACITY_MAX_AGE_MS}))
338 ? 0 + $ENV{SKEID_CAPACITY_MAX_AGE_MS}
339 489 ▶ : 5000;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_CAPACITY_MAX_AGE_MS'} && length $ENV{'SKEID_CAPACITY_MAX_AGE_MS'} ? : 0 489 489
Condition33%1/3
defined $ENV{"SKEID_CAPACITY_MAX_AGE_MS"} and length $ENV{"SKEID_CAPACITY_MAX_AGE_MS"}
!ll&&!rl&&r
48900
MC/DC0%0/2
defined $ENV{"SKEID_CAPACITY_MAX_AGE_MS"} and length $ENV{"SKEID_CAPACITY_MAX_AGE_MS"}
defined $ENV{"SKEID_CAPACITY_MAX_AGE_MS"} length $ENV{"SKEID_CAPACITY_MAX_AGE_MS"}
Truth table33%1/3
A and B
A= defined $ENV{"SKEID_CAPACITY_MAX_AGE_MS"}B= length $ENV{"SKEID_CAPACITY_MAX_AGE_MS"}
ABresult
0X0
100
111
340 },
341 67 );
342  
343  
344 has worker_count => (
345 is => 'rw',
346 490 ▶ default => sub { 1 },
Subroutine __ANON__: called CC=1 SCAR=0.0
347 14 ▶ trigger => sub { $_[0]->_bump_inventory },
Subroutine __ANON__: called CC=1 SCAR=0.0
348 67 );
349  
350  
351 67 has frontend_count => (
352 is => 'rw',
353 builder => '_build_frontend_count',
354 );
355  
356 492 ▶sub _build_frontend_count {
Subroutine _build_frontend_count: called CC=3 SCAR=12.0
357 return (defined($ENV{SKEID_FRONTEND_COUNT}) && length($ENV{SKEID_FRONTEND_COUNT}))
358 ? 0 + $ENV{SKEID_FRONTEND_COUNT}
359 492 ▶ : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'SKEID_FRONTEND_COUNT'} && length $ENV{'SKEID_FRONTEND_COUNT'} ? : 0 492 492
Condition66%2/3
defined $ENV{"SKEID_FRONTEND_COUNT"} and length $ENV{"SKEID_FRONTEND_COUNT"}
!ll&&!rl&&r
49110
MC/DC0%0/2
defined $ENV{"SKEID_FRONTEND_COUNT"} and length $ENV{"SKEID_FRONTEND_COUNT"}
defined $ENV{"SKEID_FRONTEND_COUNT"} length $ENV{"SKEID_FRONTEND_COUNT"}
Truth table66%2/3
A and B
A= defined $ENV{"SKEID_FRONTEND_COUNT"}B= length $ENV{"SKEID_FRONTEND_COUNT"}
ABresult
0X0
100
111
360 }
361  
362  
363 499 ▶has registry_enabled => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
364 499 ▶has registry_secret => (is => 'rw', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
365 499 ▶has registry_read_key => (is => 'rw', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
366 499 ▶has registry_ttl_s => (is => 'rw', default => sub { 10 });
Subroutine __ANON__: called CC=1 SCAR=0.0
367 499 ▶has registry_instance_id => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
368 499 ▶has registry_error_window_s => (is => 'rw', default => sub { 60 });
Subroutine __ANON__: called CC=1 SCAR=0.0
369  
370 # node_id => { last_at => epoch, buckets => { epoch_second => count } }. Failed requests, for
371 # the registry snapshot's errors_in_window and last_failure_at. Reported, never consulted by
372 # admission: health is operator state (ADR 0009, ADR 0017).
373 has _failures => (
374 is => 'rw',
375 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
376 67 );
377  
378 has _stats => (
379 is => 'rw',
380 499 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
381 67 );
382  
383 has _usage_store_obj => (
384 is => 'rw',
385 499 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
386 67 );
387  
388 67 my %FALLBACK_ENGINE_IDS = map { $_ => 1 } qw(
389 aki
390 akiopenai
391 anthropic
392 anthropicbase
393 cerebras
394 deepseek
395 gemini
396 groq
397 huggingface
398 lmstudio
399 lmstudioanthropic
400 lmstudioopenai
401 llamacpp
402 minimax
403 mistral
404 nousresearch
405 ollama
406 ollamaopenai
407 openai
408 openaibase
409 openrouter
410 perplexity
411 remote
412 replicate
413 sglang
414 vllm
415 whisper
416 );
417  
418 # How a routing key of the config sets its attribute. A key removed from the config sets it back
419 # to its value before any config was applied (_routing_baseline, skeid k65).
420 my %ROUTING_SETTINGS = (
421 6 ▶ wait_timeout_ms => [ route_wait_timeout_ms => sub { 0 + $_[0] } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
422 6 ▶ wait_poll_ms => [ route_wait_poll_ms => sub { my $poll = 0 + $_[0]; $poll < 1 ? 1 : $poll } ],
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$poll < 1 ? : 0 6 6
423 1 ▶ trust_key_id_header => [ trust_key_id_header => sub { $_[0] =~ /^(1|true|yes|on)$/i ? 1 : 0 } ],
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /^(1|true|yes|on)$/i ? : 1 0 1
424 # How many Skeid hosts share the nodes. Only the config knows it -- there is nothing to
425 # detect -- and forgetting it over-admits every node by that factor (ADR 0012). Floor at one,
426 # so a stray 0 falls back to today's single-frontend behaviour instead of dividing max_conns
427 # to nothing.
428 5 ▶ frontend_count => [ frontend_count => sub { my $n = int(0 + $_[0]); $n < 1 ? 1 : $n } ],
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$n < 1 ? : 1 4 5
429 );
430  
431 499 ▶sub BUILD {
Subroutine BUILD: called CC=9 SCAR=22.5
Pod undocumented
432 499 my ($self, $args) = @_;
433 # A key handed to new() is explicit: the config applied next must not replace it.
434 $self->_explicit_admin_api_key("$args->{admin_api_key}")
435 499 ▶ if defined($args->{admin_api_key}) && length($args->{admin_api_key});
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"admin_api_key"} and length $args->{"admin_api_key"} 4 495 499
Condition66%2/3
defined $args->{"admin_api_key"} and length $args->{"admin_api_key"}
!ll&&!rl&&r
49504
MC/DC50%1/2
defined $args->{"admin_api_key"} and length $args->{"admin_api_key"}
defined $args->{"admin_api_key"} length $args->{"admin_api_key"}
Truth table66%2/3
A and B
A= defined $args->{"admin_api_key"}B= length $args->{"admin_api_key"}
ABresult
0X0
100
111
436 # What the routing attributes are without a config -- passed to new(), else from the
437 # environment, else built in: a routing key removed from the config goes back to this.
438 499 $self->_routing_baseline({ map { my $attr = $_->[0]; ($attr => $self->$attr) } values %ROUTING_SETTINGS });
439 499 ▶ if ($self->has_config_loader || $self->has_config_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_config_loader or $self->has_config_file) 205 294 499
Condition100%3/3
$self->has_config_loader or $self->has_config_file
l!l&&r!l&&!r
1969294
MC/DC100%2/2
$self->has_config_loader or $self->has_config_file
$self->has_config_loader $self->has_config_file
Truth table100%3/3
A or B
A= $self->has_config_loaderB= $self->has_config_file
ABresult
1X1
011
000
440 205 $self->reload_config;
441 }
442 471 ▶ if (ref($self->usage_store) eq 'HASH' && keys %{$self->usage_store}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->usage_store eq 'HASH' and keys %{$self->usage_store;}) { } 26 445 471
Condition66%2/3
ref $self->usage_store eq "HASH" and keys %{$self->usage_store;}
!ll&&!rl&&r
044526
MC/DC50%1/2
ref $self->usage_store eq "HASH" and keys %{$self->usage_store;}
ref $self->usage_store eq "HASH" keys %{$self->usage_store;}
Truth table66%2/3
A and B
A= ref $self->usage_store eq "HASH"B= keys %{$self->usage_store;}
ABresult
0X0
100
111
443 26 $self->_configure_usage_store($self->usage_store);
444 } else {
445 445 my $path = $self->usage_db_path;
446 445 ▶ if (defined $path && length $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $path and length $path) 0 445 445
Condition33%1/3
defined $path and length $path
!ll&&!rl&&r
44500
MC/DC0%0/2
defined $path and length $path
defined $path length $path
Truth table33%1/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
447 0 $self->_set_usage_db_path($path);
448 }
449 }
450 }
451  
452  
453 1105 ▶sub add_node {
Subroutine add_node: called CC=20 SCAR=31.0
Pod documented
454 1105 my ($self, %node) = @_;
455 1105 ▶ my $id = $node{id} // croak 'node id required';
Condition33%1/3
$node{"id"} // croak("node id required")
l!l&&r!l&&!r
110500
MC/DC0%0/2
$node{"id"} // croak("node id required")
$node{"id"} croak("node id required")
Truth table33%1/3
A // B
A= $node{"id"}B= croak("node id required")
ABresult
1X1
011
000
456 1105 ▶ my $url = $node{url} // croak 'node url required';
Condition33%1/3
$node{"url"} // croak("node url required")
l!l&&r!l&&!r
110500
MC/DC0%0/2
$node{"url"} // croak("node url required")
$node{"url"} croak("node url required")
Truth table33%1/3
A // B
A= $node{"url"}B= croak("node url required")
ABresult
1X1
011
000
457  
458 # A registry probe with no secret would forget on every poll and look like a silent
459 # downstream; say so where the operator wrote it (ADR 0017).
460 1105 ▶ if (ref($node{capacity}) eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node{"capacity"} eq "HASH" and lc(($node{"capacity"}{"probe"} // $node{"capacity"}{"type"}) // "") eq "registry") 12 1093 1105
Condition75%6/8
ref $node{"capacity"} eq "HASH" and lc(($node{"capacity"}{"probe"} // $node{"capacity"}{"type"}) // "") eq "registry"
!ll&&!rl&&r
10751812
($node{"capacity"}{"probe"} // $node{"capacity"}{"type"}) // ""
l!l
300
$node{"capacity"}{"probe"} // $node{"capacity"}{"type"}
l!l&&r!l&&!r
2910
MC/DC33%1/3
ref $node{"capacity"} eq "HASH" and lc(($node{"capacity"}{"probe"} // $node{"capacity"}{"type"}) // "") eq "registry"
ref $node{"capacity"} eq "HASH" $node{"capacity"}{"probe"} $node{"capacity"}{"type"}
Truth table75%3/4
A and B // C
A= ref $node{"capacity"} eq "HASH"B= $node{"capacity"}{"probe"}C= $node{"capacity"}{"type"}
ABCresult
0XX0
1000
11X1
1011
461 && lc($node{capacity}{probe} // $node{capacity}{type} // '') eq 'registry') {
462 12 require Langertha::Skeid::CapacityProbe::Registry;
463 12 Langertha::Skeid::CapacityProbe::Registry->validate_config($node{capacity}, $id);
464 }
465  
466 1100 $self->remove_node($id);
467 1100 ▶ push @{$self->nodes}, {
Branch: 9 branches
BranchTrueFalseTotal
defined $node{'engine'} && length $node{'engine'} ? : 788 312 1100
defined $node{'weight'} ? : 12 1087 1099
defined $node{'max_conns'} ? : 921 178 1099
exists $node{'healthy'} ? : 804 295 1099
$node{'healthy'} ? : 804 0 804
ref $node{'metadata'} eq 'HASH' ? : 1 1098 1099
defined $node{'api_key_env'} && length $node{'api_key_env'} ? : 86 1013 1099
defined $node{'api_key_ref'} && length $node{'api_key_ref'} ? : 103 996 1099
ref $node{'capacity'} eq 'HASH' ? : 25 1074 1099
Condition72%8/11
$node{"model"} // ""
l!l
106733
defined $node{"engine"} and length $node{"engine"}
!ll&&!rl&&r
3120788
defined $node{"api_key_env"} and length $node{"api_key_env"}
!ll&&!rl&&r
1013086
defined $node{"api_key_ref"} and length $node{"api_key_ref"}
!ll&&!rl&&r
9960103
MC/DC100%1/1
$node{"model"} // ""
$node{"model"}
MC/DC50%1/2
defined $node{"engine"} and length $node{"engine"}
defined $node{"engine"} length $node{"engine"}
MC/DC50%1/2
defined $node{"api_key_env"} and length $node{"api_key_env"}
defined $node{"api_key_env"} length $node{"api_key_env"}
MC/DC50%1/2
defined $node{"api_key_ref"} and length $node{"api_key_ref"}
defined $node{"api_key_ref"} length $node{"api_key_ref"}
Truth table100%2/2
A
A= $node{"model"}
Aresult
11
00
Truth table66%2/3
A and B
A= defined $node{"engine"}B= length $node{"engine"}
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= defined $node{"api_key_env"}B= length $node{"api_key_env"}
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= defined $node{"api_key_ref"}B= length $node{"api_key_ref"}
ABresult
0X0
100
111
468 id => $id,
469 url => $url,
470 model => ($node{model} // ''),
471 engine => $self->normalize_engine_id((defined($node{engine}) && length($node{engine})) ? $node{engine} : 'OpenAIBase'),
472 weight => (defined $node{weight} ? 0 + $node{weight} : 1),
473 max_conns => (defined $node{max_conns} ? 0 + $node{max_conns} : 0),
474 healthy => (exists $node{healthy} ? ($node{healthy} ? 1 : 0) : 1),
475 tags => $self->normalize_tags($node{tags}),
476 metadata => (ref($node{metadata}) eq 'HASH' ? $node{metadata} : {}),
477 (defined($node{api_key_env}) && length($node{api_key_env})
478 ? (api_key_env => "$node{api_key_env}")
479 : ()),
480 (defined($node{api_key_ref}) && length($node{api_key_ref})
481 ? (api_key_ref => "$node{api_key_ref}")
482 : ()),
483 # How this node's capacity is found (ADR 0009). Absent means inflight, which is every
484 # deployment that existed before probes did.
485 1100 (ref($node{capacity}) eq 'HASH' ? (capacity => { %{$node{capacity}} }) : ()),
486 };
487 1099 $self->_bump_inventory;
488 1099 return 1;
489 }
490  
491  
492 1117 ▶sub remove_node {
Subroutine remove_node: called CC=6 SCAR=18.2
Pod documented
493 1117 my ($self, $id) = @_;
494 1117 ▶ return 0 unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 0 1117 1117
Condition33%1/3
defined $id and length $id
!ll&&!rl&&r
001117
MC/DC0%0/2
defined $id and length $id
defined $id length $id
Truth table33%1/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
495 1117 ▶ my @keep = grep { ($_->{id} // '') ne $id } @{$self->nodes};
Condition50%1/2
$_->{"id"} // ""
l!l
17780
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
496 1117 my $removed = @{$self->nodes} - @keep;
497 1117 $self->nodes(\@keep);
498 # Or a node re-added under the same id inherits a reading -- or an error history -- about a
499 # different machine.
500 1117 ▶ if ($removed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($removed) 18 1099 1117
501 18 $self->forget_capacity($id);
502 18 delete $self->_failures->{$id};
503 }
504 1117 ▶ return $removed ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$removed ? : 18 1099 1117
505 }
506  
507 # What the running capacity probes were built from: the worker count (it sets the poll interval,
508 # ADR 0010) and, per node with a capacity block, its id, URL and that block. The inventory
509 # generation is the wrong key for them -- it also moves on a health flip, which has to drop the
510 # route cache but changes nothing a probe polls, and restarting the probes forgets every reading
511 # (skeid #40). The URL is in because a Prometheus probe may derive its endpoint from it, and a
512 # reading about the machine a node id used to point at is not one about the new one.
513 # Recomputed only when the generation has moved, so the per-request check stays an integer
514 # compare.
515 1189 ▶sub _probe_inventory_key {
Subroutine _probe_inventory_key: called CC=7 SCAR=20.2
516 1189 my ($self) = @_;
517 1189 my $generation = $self->_inventory_generation;
518 1189 my $cache = $self->_probe_key_cache;
519 1189 ▶ return $cache->{key} if ($cache->{generation} // -1) == $generation;
Branch: 1 branch
BranchTrueFalseTotal
if ($cache->{"generation"} // -1) == $generation 690 499 1189
Condition50%1/2
$cache->{"generation"} // -1
l!l
11890
MC/DC0%0/1
$cache->{"generation"} // -1
$cache->{"generation"}
Truth table50%1/2
A
A= $cache->{"generation"}
Aresult
11
00
520  
521 my $key = _config_digest([
522 0 + ($self->worker_count // 1),
523 40 map { [ $_->{id}, $_->{url}, $_->{capacity} ] }
524 20 ▶ sort { ($a->{id} // '') cmp ($b->{id} // '') }
Condition50%2/4
$Langertha::Skeid::a->{"id"} // ""
l!l
200
$Langertha::Skeid::b->{"id"} // ""
l!l
200
MC/DC0%0/1
$Langertha::Skeid::a->{"id"} // ""
$Langertha::Skeid::a->{"id"}
MC/DC0%0/1
$Langertha::Skeid::b->{"id"} // ""
$Langertha::Skeid::b->{"id"}
Truth table50%1/2
A
A= $Langertha::Skeid::a->{"id"}
Aresult
11
00
Truth table50%1/2
A
A= $Langertha::Skeid::b->{"id"}
Aresult
11
00
525 993 grep { ref($_->{capacity}) eq 'HASH' }
526 499 ▶ @{$self->nodes || []},
Condition50%2/4
$self->worker_count // 1
l!l
4990
$self->nodes || []
l!l
4990
MC/DC0%0/1
$self->worker_count // 1
$self->worker_count
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $self->worker_count
Aresult
11
00
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
527 ]);
528 499 $self->_probe_key_cache({ generation => $generation, key => $key });
529 499 return $key;
530 }
531  
532 2478 ▶sub _bump_inventory {
Subroutine _bump_inventory: called CC=2 SCAR=7.0
533 2478 my ($self) = @_;
534 # Defensive //0: the nodes trigger can fire during construction, before this attribute's own
535 # default has been assigned.
536 2478 ▶ $self->_inventory_generation(($self->_inventory_generation // 0) + 1);
Condition50%1/2
$self->_inventory_generation // 0
l!l
24780
MC/DC0%0/1
$self->_inventory_generation // 0
$self->_inventory_generation
Truth table50%1/2
A
A= $self->_inventory_generation
Aresult
11
00
537 # A cursor names weighted ranges in exactly one inventory generation. Keeping it after a
538 # health, node or worker-share change both retains client-created keys and resumes fairness at
539 # a position that described a different set, so inventory invalidation clears all cursors.
540 2478 $self->_rr_cursor({});
541 2478 return;
542 }
543  
544  
545 12278 ▶sub normalize_tags {
Subroutine normalize_tags: called CC=7 SCAR=19.5
Pod documented
546 12278 my ($self, $value) = @_;
547 12278 ▶ return [] unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 6216 6062 12278
548  
549 6062 ▶ my @raw = ref($value) eq 'ARRAY' ? @$value : split(/[,\s]+/, "$value");
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'ARRAY' ? : 6060 2 6062
550 6062 my (@tags, %seen);
551 6062 for my $tag (@raw) {
552 965 ▶ next unless defined $tag;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tag 0 965 965
553 965 my $clean = lc "$tag";
554 965 $clean =~ s/\A\s+//;
555 965 $clean =~ s/\s+\z//;
556 965 ▶ next unless length $clean;
Branch: 1 branch
BranchTrueFalseTotal
unless length $clean 0 965 965
557 965 ▶ next if $seen{$clean}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$clean}++ 1 964 965
558 964 push @tags, $clean;
559 }
560 6062 return \@tags;
561 }
562  
563  
564 343 ▶sub list_nodes {
Subroutine list_nodes: called CC=1 SCAR=0.0
Pod documented
565 343 my ($self) = @_;
566 343 return [ map { +{%$_} } @{$self->nodes} ];
567 }
568  
569  
570 12 ▶sub list_models {
Subroutine list_models: called CC=12 SCAR=25.0
Pod documented
571 12 my ($self, %args) = @_;
572 12 my $policy = $self->policy_for_key($args{api_key_id});
573 12 ▶ my $deny = $policy ? $policy->{deny_tags} : [];
Branch: 1 branch
BranchTrueFalseTotal
$policy ? : 5 7 12
574 12 my %entry;
575  
576 12 ▶ for my $n (@{$self->nodes || []}) {
Condition50%1/2
$self->nodes || []
l!l
120
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
577 37 my $model = $n->{model};
578 37 ▶ next unless defined $model && length $model;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and length $model 10 27 37
Condition66%2/3
defined $model and length $model
!ll&&!rl&&r
01027
MC/DC50%1/2
defined $model and length $model
defined $model length $model
Truth table66%2/3
A and B
A= defined $modelB= length $model
ABresult
0X0
100
111
579 27 ▶ next if $self->_node_has_any_tag($n, $deny);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_node_has_any_tag($n, $deny) 3 24 27
580 24 ▶ $entry{$model} //= { model => $model, engine => ($n->{engine} // '') };
Condition75%3/4
$entry{$model} //= {"model", $model, "engine", $n->{"engine"} // ""}
l!l
222
$n->{"engine"} // ""
l!l
220
MC/DC100%1/1
$entry{$model} //= {"model", $model, "engine", $n->{"engine"} // ""}
$entry{$model}
MC/DC0%0/1
$n->{"engine"} // ""
$n->{"engine"}
Truth table100%2/2
A
A= $entry{$model}
Aresult
11
00
Truth table50%1/2
A
A= $n->{"engine"}
Aresult
11
00
581 }
582 12 ▶ for my $name (keys %{$self->model_aliases || {}}) {
Condition50%1/2
$self->model_aliases || {}
l!l
120
MC/DC0%0/1
$self->model_aliases || {}
$self->model_aliases
Truth table50%1/2
A
A= $self->model_aliases
Aresult
11
00
583 18 ▶ $entry{$name} //= { model => $name, engine => '' };
Condition100%2/2
$entry{$name} //= {"model", $name, "engine", ""}
l!l
612
MC/DC100%1/1
$entry{$name} //= {"model", $name, "engine", ""}
$entry{$name}
Truth table100%2/2
A
A= $entry{$name}
Aresult
11
00
584 }
585  
586 return [
587 26 map { $entry{$_} }
588 12 grep { $self->route_plan(model => $_, api_key_id => $args{api_key_id})->{permitted} }
589 sort keys %entry
590 ];
591 }
592  
593  
594 22 ▶sub set_node_health {
Subroutine set_node_health: called CC=10 SCAR=23.2
Pod documented
595 22 my ($self, $id, $healthy) = @_;
596 22 ▶ return 0 unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 0 22 22
Condition33%1/3
defined $id and length $id
!ll&&!rl&&r
0022
MC/DC0%0/2
defined $id and length $id
defined $id length $id
Truth table33%1/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
597 22 my ($found, $changed) = (0, 0);
598 22 ▶ my $next = $healthy ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$healthy ? : 8 14 22
599 22 for my $n (@{$self->nodes}) {
600 26 ▶ next unless ($n->{id} // '') eq $id;
Branch: 1 branch
BranchTrueFalseTotal
unless ($n->{"id"} // "") eq $id 4 22 26
Condition50%1/2
$n->{"id"} // ""
l!l
260
MC/DC0%0/1
$n->{"id"} // ""
$n->{"id"}
Truth table50%1/2
A
A= $n->{"id"}
Aresult
11
00
601 22 ▶ if (($n->{healthy} ? 1 : 0) != $next) {
Branch: 2 branches
BranchTrueFalseTotal
if (($n->{"healthy"} ? 1 : 0) != $next) 21 1 22
$n->{'healthy'} ? : 15 7 22
602 21 $n->{healthy} = $next;
603 21 $changed = 1;
604 }
605 22 $found = 1;
606 22 last;
607 }
608 # Health is part of eligibility, so flipping it has to drop the derived lists -- otherwise a
609 # node taken out of rotation keeps receiving traffic until something else changes. It is not
610 # part of the probe key, so the capacity probes and their readings stay (skeid #40). Repeating
611 # the current value changes no inventory and must not reset its round-robin cursors.
612 22 ▶ $self->_bump_inventory if $changed;
Branch: 1 branch
BranchTrueFalseTotal
if $changed 21 1 22
613 22 return $found;
614 }
615  
616 # The prompt-cache rates a pricing rule may carry (skeid #28, ADR 0013). Optional: a rule
617 # without them prices every input token at input_per_million, exactly as before.
618 67 my @CACHE_RATE_KEYS = qw(cached_input_per_million cache_write_per_million);
619 67 my $cache_rates_unsupported_warned;
620  
621 # True when the installed Langertha prices prompt-cache reads and writes (Langertha::Cost has
622 # the cache amounts, core ADR 0031). The released 0.503 does not; there the cache rates are
623 # dropped at config load, so a rule prices exactly as a rule without them.
624 57 ▶sub _core_prices_cache { Langertha::Cost->can('cache_read_usd') ? 1 : 0 }
Subroutine _core_prices_cache: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
'Langertha::Cost'->can('cache_read_usd') ? : 57 0 57
625  
626  
627 137 ▶sub set_model_pricing {
Subroutine set_model_pricing: called CC=14 SCAR=26.6
Pod documented
628 137 my ($self, $model, $pricing) = @_;
629 137 ▶ croak 'model required' unless defined $model && length $model;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and length $model 0 137 137
Condition33%1/3
defined $model and length $model
!ll&&!rl&&r
00137
MC/DC0%0/2
defined $model and length $model
defined $model length $model
Truth table33%1/3
A and B
A= defined $modelB= length $model
ABresult
0X0
100
111
630 137 ▶ croak 'pricing hash required' unless ref($pricing) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pricing eq "HASH" 0 137 137
631 my %rule = (
632 input_per_million => 0 + ($pricing->{input_per_million} // 0),
633 137 ▶ output_per_million => 0 + ($pricing->{output_per_million} // 0),
Condition75%3/4
$pricing->{"input_per_million"} // 0
l!l
1370
$pricing->{"output_per_million"} // 0
l!l
1334
MC/DC0%0/1
$pricing->{"input_per_million"} // 0
$pricing->{"input_per_million"}
MC/DC100%1/1
$pricing->{"output_per_million"} // 0
$pricing->{"output_per_million"}
Truth table50%1/2
A
A= $pricing->{"input_per_million"}
Aresult
11
00
Truth table100%2/2
A
A= $pricing->{"output_per_million"}
Aresult
11
00
634 );
635 137 my @rates = grep { defined $pricing->{$_} } @CACHE_RATE_KEYS;
636 137 for my $key (@rates) {
637 123 my $rate = $pricing->{$key};
638 123 ▶ croak "pricing for '$model': $key must be a number >= 0"
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $rate and &looks_like_number($rate) and $rate >= 0 7 116 123
Condition100%6/6
not ref $rate and &looks_like_number($rate) and $rate >= 0
!ll&&!rl&&r
43116
not ref $rate and &looks_like_number($rate)
!ll&&!rl&&r
22119
MC/DC100%3/3
not ref $rate and &looks_like_number($rate) and $rate >= 0
not ref $rate &looks_like_number($rate) $rate >= 0
Truth table100%4/4
not(A) and B and C
A= not ref $rateB= &looks_like_number($rate)C= $rate >= 0
ABCresult
0XX0
10X0
1100
1111
639 unless !ref($rate) && looks_like_number($rate) && $rate >= 0;
640 }
641 130 ▶ if (@rates && !_core_prices_cache()) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rates and not _core_prices_cache()) 2 128 130
Condition100%3/3
@rates and not _core_prices_cache()
!ll&&!rl&&r
71572
MC/DC100%2/2
@rates and not _core_prices_cache()
@rates not _core_prices_cache()
Truth table100%3/3
A and not(B)
A= @ratesB= not _core_prices_cache()
ABresult
0X0
100
111
642 2 ▶ warn "skeid: pricing sets cached_input_per_million / cache_write_per_million, but this "
Branch: 1 branch
BranchTrueFalseTotal
unless $cache_rates_unsupported_warned++ 1 1 2
643 . "Langertha cannot price prompt-cache tokens; they are ignored and cached tokens bill "
644 . "at input_per_million\n"
645 unless $cache_rates_unsupported_warned++;
646 2 @rates = ();
647 }
648 130 $rule{$_} = 0 + $pricing->{$_} for @rates;
649 130 $self->model_pricing->{$model} = \%rule;
650 130 return $self->model_pricing->{$model};
651 }
652  
653  
654 341 ▶sub pricing_for_model {
Subroutine pricing_for_model: called CC=3 SCAR=11.0
Pod documented
655 341 my ($self, $model) = @_;
656 return $self->model_pricing->{$model}
657 341 ▶ || $self->model_pricing->{'*'}
Condition100%5/5
$self->model_pricing->{$model} || $self->model_pricing->{'*'} || {'input_per_million', 0, 'output_per_million', 0}
l!l
120221
$self->model_pricing->{$model} or $self->model_pricing->{"*"}
l!l&&r!l&&!r
14106221
MC/DC100%2/2
$self->model_pricing->{$model} || $self->model_pricing->{'*'} || {'input_per_million', 0, 'output_per_million', 0}
$self->model_pricing->{$model} $self->model_pricing->{"*"}
Truth table100%3/3
A or B
A= $self->model_pricing->{$model}B= $self->model_pricing->{"*"}
ABresult
1X1
011
000
658 || { input_per_million => 0, output_per_million => 0 };
659 }
660  
661 # The config state a reload replaces. A reload is all or nothing (skeid #29 review): a
662 # config that fails anywhere -- a bad policy, alias or manifest grant -- must not leave the
663 # sections before it applied and the ones after it not, which served every customer a 403
664 # from an emptied manifest map while routing already ran on the new policies.
665 67 my @CONFIG_STATE = qw(
666 model_aliases policies default_policy key_policies key_names nodes
667 route_wait_timeout_ms route_wait_poll_ms trust_key_id_header frontend_count
668 admin_api_key _config_admin_api_key
669 manifest_enabled manifest_available key_manifests
670 registry_enabled registry_secret registry_read_key registry_ttl_s registry_instance_id registry_error_window_s
671 );
672  
673  
674 350 ▶sub reload_config {
Subroutine reload_config: called CC=15 SCAR=27.1
Pod documented
675 350 my ($self) = @_;
676 350 my ($cfg, $fingerprint);
677 350 ▶ unless (eval { ($cfg, $fingerprint) = $self->_read_config; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { () = $self->_read_config; 1 } }) 6 344 350
678 6 ▶ my $err = $@ || 'config loader failed';
Condition50%1/2
$@ || 'config loader failed'
l!l
60
MC/DC0%0/1
$@ || 'config loader failed'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
679 6 $self->_record_reload_failure($err, undef);
680 6 die $err;
681 }
682  
683 # Same config as last applied: nothing to do. Rebuilding would replace the node list, which
684 # bumps the inventory generation, restarts every capacity probe and forgets health an admin
685 # set -- for a config that did not change (skeid #38).
686 344 my $last = $self->_config_fingerprint;
687 344 ▶ if (defined($last) && $last eq $fingerprint) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $last and $last eq $fingerprint) 77 267 344
Condition100%3/3
defined $last and $last eq $fingerprint
!ll&&!rl&&r
2046377
MC/DC100%2/2
defined $last and $last eq $fingerprint
defined $last $last eq $fingerprint
Truth table100%3/3
A and B
A= defined $lastB= $last eq $fingerprint
ABresult
0X0
100
111
688 77 $self->_clear_reload_failure;
689 77 return $cfg;
690 }
691  
692 # The config that just failed, read again: it would fail the same way, so it is not applied
693 # again -- but it still counts as a failure, which is what the retry back-off grows on.
694 267 my $failed = $self->_failed_fingerprint;
695 267 ▶ if (defined($failed) && $failed eq $fingerprint && defined $self->last_reload_error) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $failed and $failed eq $fingerprint and defined $self->last_reload_error) 15 252 267
Condition83%5/6
defined $failed and $failed eq $fingerprint and defined $self->last_reload_error
!ll&&!rl&&r
252015
defined $failed and $failed eq $fingerprint
!ll&&!rl&&r
250215
MC/DC66%2/3
defined $failed and $failed eq $fingerprint and defined $self->last_reload_error
defined $failed $failed eq $fingerprint defined $self->last_reload_error
Truth table75%3/4
A and B and C
A= defined $failedB= $failed eq $fingerprintC= defined $self->last_reload_error
ABCresult
0XX0
10X0
1100
1111
696 15 my $err = $self->last_reload_error;
697 15 $self->_record_reload_failure($err, $fingerprint);
698 15 die $err;
699 }
700  
701 252 my %before = map { $_ => $self->$_ } @CONFIG_STATE;
702 252 ▶ my %pricing = %{$self->model_pricing || {}};
Condition50%1/2
$self->model_pricing || {}
l!l
2520
MC/DC0%0/1
$self->model_pricing || {}
$self->model_pricing
Truth table50%1/2
A
A= $self->model_pricing
Aresult
11
00
703 252 my ($generation, $route_cache, $probe_key_cache, $rr_cursor)
704 = ($self->_inventory_generation, $self->_route_cache, $self->_probe_key_cache, $self->_rr_cursor);
705  
706 252 my ($nodes_print, $declared, $notices);
707 252 ▶ if (eval { ($nodes_print, $declared, $notices) = $self->_apply_config($cfg); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { () = $self->_apply_config($cfg); 1 } }) 219 33 252
708 219 $self->_forget_departed_nodes;
709 219 $self->_config_fingerprint($fingerprint);
710 219 $self->_nodes_fingerprint($nodes_print);
711 219 $self->_config_declared($declared);
712 219 $self->_clear_reload_failure;
713 219 warn 'skeid: ' . $_ . "\n" for @$notices;
714 219 return $cfg;
715 }
716  
717 33 ▶ my $err = $@ || 'config reload failed';
Condition50%1/2
$@ || 'config reload failed'
l!l
330
MC/DC0%0/1
$@ || 'config reload failed'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
718 33 $self->_record_reload_failure($err, $fingerprint);
719 33 for my $attr (@CONFIG_STATE) {
720 693 ▶ next if $attr eq 'nodes';
Branch: 1 branch
BranchTrueFalseTotal
if $attr eq "nodes" 33 660 693
721 660 $self->$attr($before{$attr});
722 }
723 33 $self->model_pricing(\%pricing);
724 # Setting nodes bumps the inventory generation. The old list comes back unchanged (the failed
725 # load only built a new array), so its generation, derived caches and fairness cursors come back
726 # with it: an inventory that did not change must not look changed, and a cache left keyed on a
727 # generation number that is about to be reused would answer for a different list.
728 33 ▶ if ($self->nodes != $before{nodes}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->nodes != $before{"nodes"}) 21 12 33
729 21 $self->nodes($before{nodes});
730 21 $self->_inventory_generation($generation);
731 21 $self->_route_cache($route_cache);
732 21 $self->_probe_key_cache($probe_key_cache);
733 21 $self->_rr_cursor($rr_cursor);
734 }
735 33 die $err;
736 }
737  
738 # A reload that drops a node drops what was known about it too, as remove_node does: its
739 # capacity reading and its failure history. Otherwise a node re-added later under the same id
740 # inherits a reading -- or errors -- about whatever machine the id used to point at. Run only
741 # after a reload succeeded, so a failed one that restores the old list loses nothing.
742 219 ▶sub _forget_departed_nodes {
Subroutine _forget_departed_nodes: called CC=4 SCAR=13.9
743 219 my ($self) = @_;
744 219 ▶ my %present = map { (($_->{id} // '') => 1) } @{$self->nodes};
Condition50%1/2
$_->{"id"} // ""
l!l
7450
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
745 219 for my $store ($self->_capacity, $self->_failures) {
746 438 delete $store->{$_} for grep { !$present{$_} } keys %$store;
747 }
748 219 return;
749 }
750  
751 54 ▶sub _record_reload_failure {
Subroutine _record_reload_failure: called CC=2 SCAR=7.0
752 54 my ($self, $err, $fingerprint) = @_;
753 54 $self->last_reload_error("$err");
754 54 $self->last_reload_error_at(time);
755 54 ▶ $self->reload_failures(($self->reload_failures // 0) + 1);
Condition50%1/2
$self->reload_failures // 0
l!l
540
MC/DC0%0/1
$self->reload_failures // 0
$self->reload_failures
Truth table50%1/2
A
A= $self->reload_failures
Aresult
11
00
756 54 $self->_failed_fingerprint($fingerprint);
757 54 return;
758 }
759  
760 296 ▶sub _clear_reload_failure {
Subroutine _clear_reload_failure: called CC=1 SCAR=0.0
761 296 my ($self) = @_;
762 296 $self->last_reload_error(undef);
763 296 $self->last_reload_error_at(undef);
764 296 $self->reload_failures(0);
765 296 $self->_failed_fingerprint(undef);
766 296 $self->_config_file_failed_mtime(undef);
767 296 $self->_config_file_retry_at(undef);
768 296 return;
769 }
770  
771  
772 47 ▶sub reload_status {
Subroutine reload_status: called CC=4 SCAR=14.5
Pod documented
773 47 my ($self) = @_;
774 47 my $err = $self->last_reload_error;
775 47 ▶ return { ok => 1 } unless defined $err;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err 39 8 47
776 8 (my $message = $err) =~ s/\s+\z//;
777 return {
778 8 ▶ ok => 0,
Condition40%2/5
$self->last_reload_error_at // time
l!l&&r!l&&!r
800
$self->reload_failures // 0
l!l
80
MC/DC0%0/2
$self->last_reload_error_at // time
$self->last_reload_error_at time
MC/DC0%0/1
$self->reload_failures // 0
$self->reload_failures
Truth table33%1/3
A // B
A= $self->last_reload_error_atB= time
ABresult
1X1
011
000
Truth table50%1/2
A
A= $self->reload_failures
Aresult
11
00
779 error => $message,
780 failed_at => strftime('%Y-%m-%dT%H:%M:%SZ', gmtime($self->last_reload_error_at // time)),
781 failures => 0 + ($self->reload_failures // 0),
782 };
783 }
784  
785 # Reads the config source: the loader's answer or the parsed file, plus its fingerprint. A
786 # loader may return ($config, $version); a defined version is the fingerprint, otherwise it is
787 # a digest of the structure (see _config_digest).
788 350 ▶sub _read_config {
Subroutine _read_config: called CC=10 SCAR=23.5
789 350 my ($self) = @_;
790 350 my $cfg = {};
791 350 my $version;
792  
793 350 ▶ if ($self->has_config_loader) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->has_config_loader) { } 330 20 350
elsif ($self->has_config_file) { } 20 0 20
794 # Counted from the start of the run, so the throttle also holds for a loader that dies.
795 330 ▶ $self->_config_next_check_at($self->_now + (0 + ($self->config_reload_interval // 0)));
Condition50%1/2
$self->config_reload_interval // 0
l!l
3300
MC/DC0%0/1
$self->config_reload_interval // 0
$self->config_reload_interval
Truth table50%1/2
A
A= $self->config_reload_interval
Aresult
11
00
796 330 my ($loaded, $loader_version) = $self->config_loader->($self);
797 327 ▶ $cfg = $loaded if ref($loaded) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $loaded eq "HASH" 327 0 327
798 327 $version = $loader_version;
799 } elsif ($self->has_config_file) {
800 20 my $file = $self->config_file;
801 # A named config that is not there is an operator error, not an empty config: starting
802 # with no nodes would answer every request 503 with nothing saying why (skeid k68). A file
803 # that vanishes after a good load never gets here -- maybe_reload_config keeps the config.
804 20 ▶ croak 'config file not found: ' . $file unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 1 19 20
805 # Record the version observed before parsing. The file may be atomically replaced after
806 # load_file has read its bytes; recording a later stat would mark that unread replacement
807 # as applied and prevent the next dispatch from loading it.
808 19 my $read_mtime = (stat($file))[9];
809 19 my $ypp = YAML::PP->new;
810 19 my $loaded = $ypp->load_file($file);
811 17 ▶ $cfg = $loaded if ref($loaded) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $loaded eq "HASH" 17 0 17
812 17 ▶ $self->_config_mtime($read_mtime) if defined $read_mtime;
Branch: 1 branch
BranchTrueFalseTotal
if defined $read_mtime 17 0 17
813 }
814  
815 344 ▶ my $fingerprint = defined($version) && !ref($version)
Branch: 1 branch
BranchTrueFalseTotal
defined $version && !ref($version) ? : 3 341 344
Condition66%2/3
defined $version and not ref $version
!ll&&!rl&&r
34103
MC/DC50%1/2
defined $version and not ref $version
defined $version not ref $version
Truth table66%2/3
A and not(B)
A= defined $versionB= not ref $version
ABresult
0X0
100
111
816 ? "version:$version"
817 : 'digest:' . _config_digest($cfg);
818 344 return ($cfg, $fingerprint);
819 }
820  
821 # A canonical digest of a loaded config structure: hash keys sorted, so two loads of the same
822 # data digest alike whatever order the loader built them in. A code ref or an object other
823 # than a boolean digests by identity -- the same callback digests alike, a fresh closure per
824 # load counts as a change, which reloads rather than missing one.
825 1066 ▶sub _config_digest {
Subroutine _config_digest: called CC=1 SCAR=0.2
826 1066 my ($data) = @_;
827 1066 my $out = '';
828 1066 my $walk;
829 15366 ▶ $walk = sub {
Subroutine __ANON__: called CC=12 SCAR=27.8
830 15366 my ($node) = @_;
831 15366 ▶ if (!defined $node) {
Branch: 5 branches
BranchTrueFalseTotal
if (not defined $node) { } 0 15366 15366
elsif (not ref $node) { } 10920 4446 15366
elsif (builtin::blessed($node) and builtin::reftype($node) eq 'SCALAR') { } 0 4446 4446
elsif (not builtin::blessed($node) and builtin::reftype($node) eq 'HASH') { } 2959 1487 4446
elsif (not builtin::blessed($node) and builtin::reftype($node) eq 'ARRAY') { } 1417 70 1487
832 0 $out .= 'u;';
833 } elsif (!ref $node) {
834 10920 $out .= 's' . length($node) . ':' . $node . ';';
835 ▶ } elsif (blessed($node) && reftype($node) eq 'SCALAR') {
Condition33%1/3
builtin::blessed($node) and builtin::reftype($node) eq "SCALAR"
!ll&&!rl&&r
444600
MC/DC0%0/2
builtin::blessed($node) and builtin::reftype($node) eq "SCALAR"
builtin::blessed($node) builtin::reftype($node) eq "SCALAR"
Truth table33%1/3
A and B
A= builtin::blessed($node)B= builtin::reftype($node) eq "SCALAR"
ABresult
0X0
100
111
836 # JSON / YAML booleans: their value is what counts, not which object carries it.
837 0 ▶ $out .= 'b' . (${$node} ? 1 : 0) . ';';
Branch: 1 branch
BranchTrueFalseTotal
${$node;} ? : 0 0 0
838 ▶ } elsif (!blessed($node) && reftype($node) eq 'HASH') {
Condition66%2/3
not builtin::blessed($node) and builtin::reftype($node) eq "HASH"
!ll&&!rl&&r
014872959
MC/DC50%1/2
not builtin::blessed($node) and builtin::reftype($node) eq "HASH"
not builtin::blessed($node) builtin::reftype($node) eq "HASH"
Truth table66%2/3
not(A) and B
A= not builtin::blessed($node)B= builtin::reftype($node) eq "HASH"
ABresult
0X0
100
111
839 2959 $out .= 'h{';
840 2959 for my $key (sort keys %$node) {
841 11546 $out .= 's' . length($key) . ':' . $key . ';';
842 11546 $walk->($node->{$key});
843 }
844 2959 $out .= '}';
845 ▶ } elsif (!blessed($node) && reftype($node) eq 'ARRAY') {
Condition66%2/3
not builtin::blessed($node) and builtin::reftype($node) eq "ARRAY"
!ll&&!rl&&r
0701417
MC/DC50%1/2
not builtin::blessed($node) and builtin::reftype($node) eq "ARRAY"
not builtin::blessed($node) builtin::reftype($node) eq "ARRAY"
Truth table66%2/3
not(A) and B
A= not builtin::blessed($node)B= builtin::reftype($node) eq "ARRAY"
ABresult
0X0
100
111
846 1417 $out .= 'a[';
847 1417 $walk->($_) for @$node;
848 1417 $out .= ']';
849 } else {
850 70 $out .= 'r' . reftype($node) . ':' . refaddr($node) . ';';
851 }
852 1066 };
853 1066 $walk->($data);
854 1066 undef $walk;
855 1066 return sha256_hex($out);
856 }
857  
858 # Applies a config to $self, section by section; reload_config undoes it on a croak. The usage
859 # store goes last and swaps only once the new store is prepared, so nothing after it can fail.
860 #
861 # A section the config declares replaces what is loaded: the file is the declared state. A
862 # section the previously applied config declared and this one does not goes back to what a
863 # restart with this config would give (skeid k65) -- except the usage store, see below. A
864 # section no applied config ever declared is left to whoever set it: nodes pushed through the
865 # admin API, prices set through pricing.set.
866 #
867 # Returns the fingerprint of the nodes section the node list now stands for (undef when the
868 # config declares none), the sections this config declares, and notices to log once it applied.
869 252 ▶sub _apply_config {
Subroutine _apply_config: called CC=30 SCAR=34.6
870 252 my ($self, $cfg) = @_;
871 252 my $before = $self->_config_declared;
872 252 my (%declared, @notices);
873  
874 252 ▶ if (exists $cfg->{pricing}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'pricing'}) { } 115 137 252
elsif ($before->{'pricing'}) { } 1 136 137
875 115 $declared{pricing} = 1;
876 # Replaced wholesale, not merged: a model removed from the section loses its price.
877 115 $self->model_pricing({});
878 115 ▶ my $pricing = ref($cfg->{pricing}) eq 'HASH' ? $cfg->{pricing} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'pricing'} eq 'HASH' ? : 115 0 115
879 115 for my $model (keys %$pricing) {
880 116 my $p = $pricing->{$model};
881 116 ▶ next unless ref($p) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $p eq "HASH" 0 116 116
882 116 $self->set_model_pricing($model, $p);
883 }
884 } elsif ($before->{pricing}) {
885 1 $self->model_pricing({});
886 }
887  
888 251 ▶ if (grep { exists $cfg->{$_} } qw( policies default_policy names keys )) {
Branch: 2 branches
BranchTrueFalseTotal
if (grep {exists $cfg->{$_};} 'policies', 'default_policy', 'names', 'keys') { } 50 201 251
elsif ($before->{'policies'}) { } 1 200 201
889 50 $declared{policies} = 1;
890 50 $self->_load_policies($cfg);
891 } elsif ($before->{policies}) {
892 1 $self->_load_policies({});
893 }
894  
895 240 ▶ if (exists $cfg->{aliases}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'aliases'}) { } 31 209 240
elsif ($before->{'aliases'}) { } 4 205 209
896 31 $declared{aliases} = 1;
897 # Replaced wholesale, like nodes: the file is the declared state.
898 31 $self->model_aliases({});
899 31 ▶ my $aliases = ref($cfg->{aliases}) eq 'HASH' ? $cfg->{aliases} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'aliases'} eq 'HASH' ? : 31 0 31
900 31 for my $name (keys %$aliases) {
901 26 $self->set_model_alias($name, $aliases->{$name});
902 }
903 } elsif ($before->{aliases}) {
904 4 $self->model_aliases({});
905 }
906  
907 240 my $nodes_print = $self->_nodes_fingerprint;
908 240 ▶ if (exists $cfg->{nodes}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $cfg->{'nodes'}) { } 226 14 240
elsif ($before->{'nodes'}) { } 1 13 14
909 226 $declared{nodes} = 1;
910 226 ▶ my $nodes = ref($cfg->{nodes}) eq 'ARRAY' ? $cfg->{nodes} : [];
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'nodes'} eq 'ARRAY' ? : 226 0 226
911 # An unchanged nodes section keeps the node list as it is (skeid #38).
912 226 my $print = _config_digest($nodes);
913 226 ▶ if (!defined($nodes_print) || $print ne $nodes_print) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $nodes_print or $print ne $nodes_print) 204 22 226
Condition100%3/3
not defined $nodes_print or $print ne $nodes_print
l!l&&r!l&&!r
1861822
MC/DC100%2/2
not defined $nodes_print or $print ne $nodes_print
not defined $nodes_print $print ne $nodes_print
Truth table100%3/3
not(A) or B
A= not defined $nodes_printB= $print ne $nodes_print
ABresult
1X1
011
000
914 204 $self->nodes([]);
915 204 for my $n (@$nodes) {
916 759 ▶ next unless ref($n) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $n eq "HASH" 0 759 759
917 759 ▶ next unless defined $n->{id} && defined $n->{url};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n->{"id"} and defined $n->{"url"} 0 759 759
Condition33%1/3
defined $n->{"id"} and defined $n->{"url"}
!ll&&!rl&&r
00759
MC/DC0%0/2
defined $n->{"id"} and defined $n->{"url"}
defined $n->{"id"} defined $n->{"url"}
Truth table33%1/3
A and B
A= defined $n->{"id"}B= defined $n->{"url"}
ABresult
0X0
100
111
918 759 $self->add_node(%$n);
919 }
920 200 $nodes_print = $print;
921 }
922 } elsif ($before->{nodes}) {
923 1 $self->nodes([]);
924 1 $nodes_print = undef;
925 }
926  
927 236 ▶ my $routing = ref($cfg->{routing}) eq 'HASH' ? $cfg->{routing} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'routing'} eq 'HASH' ? : 13 223 236
928 236 for my $key (sort keys %ROUTING_SETTINGS) {
929 944 my ($attr, $convert) = @{ $ROUTING_SETTINGS{$key} };
930 944 ▶ if (defined $routing->{$key}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $routing->{$key}) { } 18 926 944
elsif ($$before{'routing.' . $key}) { } 3 923 926
931 18 $declared{'routing.' . $key} = 1;
932 18 $self->$attr($convert->($routing->{$key}));
933 } elsif ($before->{'routing.' . $key}) {
934 3 $self->$attr($self->_routing_baseline->{$attr});
935 }
936 }
937  
938 236 $self->_config_admin_api_key($self->_admin_api_key_from_config($cfg));
939 236 $self->_apply_admin_api_key;
940  
941 236 $self->_load_registry($cfg);
942  
943 # Last: a key's manifest is checked against its routing policy and the aliases.
944 228 $self->_load_manifest($cfg);
945  
946 # A changed usage store is swapped here, the new one prepared before the old one goes. A
947 # removed one is not: the removal names no destination, so honouring it would stop recording
948 # usage events -- billing data (ADR 0004) -- on a reload, silently. The running store stays
949 # until a restart, and the reload says so once (skeid k65).
950 219 my $usage_cfg = $cfg->{usage_store};
951 219 ▶ if (ref($usage_cfg) eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $usage_cfg eq 'HASH') { } 4 215 219
elsif (exists $cfg->{'usage_db_path'}) { } 0 215 215
elsif ($before->{'usage_store'}) { } 1 214 215
952 4 $declared{usage_store} = 1;
953 4 $self->_configure_usage_store($usage_cfg);
954 } elsif (exists $cfg->{usage_db_path}) {
955 0 $declared{usage_store} = 1;
956 $self->_configure_usage_store({
957 backend => 'sqlite',
958 sqlite_path => $cfg->{usage_db_path},
959 0 });
960 } elsif ($before->{usage_store}) {
961 1 ▶ my $backend = (ref($self->usage_store) eq 'HASH' && $self->usage_store->{backend}) || 'no';
Condition40%2/5
ref $self->usage_store eq 'HASH' && $self->usage_store->{'backend'} || 'no'
l!l
10
ref $self->usage_store eq "HASH" and $self->usage_store->{"backend"}
!ll&&!rl&&r
001
MC/DC0%0/2
ref $self->usage_store eq 'HASH' && $self->usage_store->{'backend'} || 'no'
ref $self->usage_store eq "HASH" $self->usage_store->{"backend"}
Truth table33%1/3
A and B
A= ref $self->usage_store eq "HASH"B= $self->usage_store->{"backend"}
ABresult
111
0X0
100
962 1 push @notices, 'usage_store was removed from the config; the running ' . $backend
963 . ' store stays in force until restart (usage events are billing data, ADR 0004)';
964 }
965  
966 219 return ($nodes_print, \%declared, \@notices);
967 }
968  
969 # The admin API key a config names (skeid k64). It may be named directly or handed over by
970 # environment variable, the same way usage_store takes password_env -- a deployment should not
971 # have to write the key into a file that gets mounted into a container. The first spelling
972 # present decides, even when it is empty: a config may switch the admin API off. A config that
973 # names none leaves the key to SKEID_ADMIN_API_KEY.
974 236 ▶sub _admin_api_key_from_config {
Subroutine _admin_api_key_from_config: called CC=10 SCAR=25.1
975 236 my ($self, $cfg) = @_;
976 236 ▶ my $admin = ref($cfg->{admin}) eq 'HASH' ? $cfg->{admin} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg->{'admin'} eq 'HASH' ? : 27 209 236
977 return exists($cfg->{admin_api_key}) ? ($cfg->{admin_api_key} // '') . ''
978 : defined($cfg->{admin_api_key_env}) ? $ENV{$cfg->{admin_api_key_env}} // ''
979 : exists($admin->{api_key}) ? ($admin->{api_key} // '') . ''
980 236 ▶ : defined($admin->{api_key_env}) ? $ENV{$admin->{api_key_env}} // ''
Branch: 4 branches
BranchTrueFalseTotal
exists $cfg->{'admin_api_key'} ? : 2 234 236
defined $cfg->{'admin_api_key_env'} ? : 0 234 234
exists $admin->{'api_key'} ? : 26 208 234
defined $admin->{'api_key_env'} ? : 1 207 208
Condition37%3/8
$cfg->{"admin_api_key"} // ""
l!l
20
$ENV{$cfg->{"admin_api_key_env"}} // ""
l!l
00
$admin->{"api_key"} // ""
l!l
260
$ENV{$admin->{"api_key_env"}} // ""
l!l
10
MC/DC0%0/1
$cfg->{"admin_api_key"} // ""
$cfg->{"admin_api_key"}
MC/DC0%0/1
$ENV{$cfg->{"admin_api_key_env"}} // ""
$ENV{$cfg->{"admin_api_key_env"}}
MC/DC0%0/1
$admin->{"api_key"} // ""
$admin->{"api_key"}
MC/DC0%0/1
$ENV{$admin->{"api_key_env"}} // ""
$ENV{$admin->{"api_key_env"}}
Truth table50%1/2
A
A= $cfg->{"admin_api_key"}
Aresult
11
00
Truth table0%0/2
A
A= $ENV{$cfg->{"admin_api_key_env"}}
Aresult
11
00
Truth table50%1/2
A
A= $admin->{"api_key"}
Aresult
11
00
Truth table50%1/2
A
A= $ENV{$admin->{"api_key_env"}}
Aresult
11
00
981 : $self->_env_admin_api_key;
982 }
983  
984 # The admin API key in force: the explicit one, else the config's.
985 241 ▶sub _apply_admin_api_key {
Subroutine _apply_admin_api_key: called CC=2 SCAR=6.9
986 241 my ($self) = @_;
987 241 my $explicit = $self->_explicit_admin_api_key;
988 241 ▶ $self->admin_api_key(length($explicit) ? $explicit : $self->_config_admin_api_key);
Branch: 1 branch
BranchTrueFalseTotal
length $explicit ? : 10 231 241
989 241 return $self->admin_api_key;
990 }
991  
992  
993 5 ▶sub set_admin_api_key {
Subroutine set_admin_api_key: called CC=2 SCAR=7.1
Pod documented
994 5 my ($self, $key) = @_;
995 5 ▶ $self->_explicit_admin_api_key(defined($key) ? "$key" : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $key ? : 5 0 5
996 5 return $self->_apply_admin_api_key;
997 }
998  
999  
1000 # Longest wait between two retries of a failing config_loader, in seconds.
1001 67 my $RELOAD_BACKOFF_MAX = 60;
1002  
1003 3978 ▶sub maybe_reload_config {
Subroutine maybe_reload_config: called CC=15 SCAR=27.2
Pod documented
1004 3978 my ($self) = @_;
1005  
1006 3978 ▶ if ($self->has_config_loader && !$self->has_config_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_config_loader and not $self->has_config_file) 1623 2355 3978
Condition66%2/3
$self->has_config_loader and not $self->has_config_file
!ll&&!rl&&r
235501623
MC/DC50%1/2
$self->has_config_loader and not $self->has_config_file
$self->has_config_loader not $self->has_config_file
Truth table66%2/3
A and not(B)
A= $self->has_config_loaderB= not $self->has_config_file
ABresult
0X0
100
111
1007 # Loader-based configs are dynamic, but not re-read more often than
1008 # config_reload_interval, and a load that reads what was already applied is a no-op.
1009 1623 my $now = $self->_now;
1010 1623 my $next = $self->_config_next_check_at;
1011 1623 ▶ return 0 if defined($next) && $now < $next;
Branch: 1 branch
BranchTrueFalseTotal
if defined $next and $now < $next 1495 128 1623
Condition66%2/3
defined $next and $now < $next
!ll&&!rl&&r
01281495
MC/DC50%1/2
defined $next and $now < $next
defined $next $now < $next
Truth table66%2/3
A and B
A= defined $nextB= $now < $next
ABresult
0X0
100
111
1012 128 return $self->_reload_on_request;
1013 }
1014  
1015 2355 ▶ return 0 unless $self->has_config_file;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_config_file 2298 57 2355
1016 57 my $file = $self->config_file;
1017 57 ▶ unless (-f $file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $file) 6 51 57
1018 # Gone after a good load (a botched deploy, a volume that went away): the config in force
1019 # stays, as it would for a file that fails to parse -- but said once, not silently.
1020 6 ▶ warn 'skeid: config file ' . $file . " is gone, keeping the previous config\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_config_file_missing 2 4 6
1021 unless $self->_config_file_missing;
1022 6 $self->_config_file_missing(1);
1023 6 return 0;
1024 }
1025 51 $self->_config_file_missing(0);
1026  
1027 51 ▶ my $mtime = (stat($file))[9] || 0;
Condition50%1/2
(stat $file)[9] || 0
l!l
510
MC/DC0%0/1
(stat $file)[9] || 0
(stat $file)[9]
Truth table50%1/2
A
A= (stat $file)[9]
Aresult
11
00
1028 51 my $last = $self->_config_mtime;
1029 51 ▶ if (!defined($last) || $mtime > $last) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $last or $mtime > $last) 50 1 51
Condition66%2/3
not defined $last or $mtime > $last
l!l&&r!l&&!r
0501
MC/DC50%1/2
not defined $last or $mtime > $last
not defined $last $mtime > $last
Truth table66%2/3
not(A) or B
A= not defined $lastB= $mtime > $last
ABresult
1X1
011
000
1030 50 my $failed = $self->_config_file_failed_mtime;
1031 50 my $retry = $self->_config_file_retry_at;
1032 50 ▶ return 0 if defined($failed) && $mtime == $failed
Branch: 1 branch
BranchTrueFalseTotal
if defined $failed and $mtime == $failed and defined $retry and $self->_now < $retry 39 11 50
Condition88%8/9
defined $failed and $mtime == $failed and defined $retry and $self->_now < $retry
!ll&&!rl&&r
10139
defined $failed and $mtime == $failed and defined $retry
!ll&&!rl&&r
10040
defined $failed and $mtime == $failed
!ll&&!rl&&r
9140
MC/DC75%3/4
defined $failed and $mtime == $failed and defined $retry and $self->_now < $retry
defined $failed $mtime == $failed defined $retry $self->_now < $retry
Truth table80%4/5
A and B and C and D
A= defined $failedB= $mtime == $failedC= defined $retryD= $self->_now < $retry
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1033 && defined($retry) && $self->_now < $retry;
1034 11 return $self->_reload_on_request($mtime);
1035 }
1036 1 return 0;
1037 }
1038  
1039 # One retry schedule for loader and file failures. A file's next version bypasses this delay in
1040 # maybe_reload_config; the delay applies only while the observed mtime is unchanged.
1041 23 ▶sub _reload_retry_delay {
Subroutine _reload_retry_delay: called CC=5 SCAR=16.2
1042 23 my ($self) = @_;
1043 23 ▶ my $failures = $self->reload_failures // 0;
Condition50%1/2
$self->reload_failures // 0
l!l
230
MC/DC0%0/1
$self->reload_failures // 0
$self->reload_failures
Truth table50%1/2
A
A= $self->reload_failures
Aresult
11
00
1044 23 ▶ my $base = 0 + ($self->config_reload_interval // 0);
Condition50%1/2
$self->config_reload_interval // 0
l!l
230
MC/DC0%0/1
$self->config_reload_interval // 0
$self->config_reload_interval
Truth table50%1/2
A
A= $self->config_reload_interval
Aresult
11
00
1045 23 ▶ $base = 1 if $base < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $base < 1 6 17 23
1046 23 my $delay = $base * 2 ** ($failures - 1);
1047 23 ▶ $delay = $RELOAD_BACKOFF_MAX if $delay > $RELOAD_BACKOFF_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if $delay > $RELOAD_BACKOFF_MAX 9 14 23
1048 23 return $delay;
1049 }
1050  
1051 # A reload triggered by a request (skeid #39). Its failure is not the request's: the previous
1052 # config is still fully in force, so the request is served under it. Failing it with a 500
1053 # would take every request down until the config is fixed -- with a loader, every one.
1054 139 ▶sub _reload_on_request {
Subroutine _reload_on_request: called CC=13 SCAR=26.7
1055 139 my ($self, $file_mtime) = @_;
1056 139 ▶ my $before = $self->_config_fingerprint // '';
Condition50%1/2
$self->_config_fingerprint // ""
l!l
1390
MC/DC0%0/1
$self->_config_fingerprint // ""
$self->_config_fingerprint
Truth table50%1/2
A
A= $self->_config_fingerprint
Aresult
11
00
1057 139 my $error_before = $self->last_reload_error;
1058 139 ▶ if (eval { $self->reload_config; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { $self->reload_config; 1 } }) 116 23 139
1059 116 ▶ return (($self->_config_fingerprint // '') ne $before) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
($self->_config_fingerprint // '') ne $before ? : 39 77 116
Condition50%1/2
$self->_config_fingerprint // ""
l!l
1160
MC/DC0%0/1
$self->_config_fingerprint // ""
$self->_config_fingerprint
Truth table50%1/2
A
A= $self->_config_fingerprint
Aresult
11
00
1060 }
1061  
1062 23 ▶ my $err = $@ || 'config reload failed';
Condition50%1/2
$@ || 'config reload failed'
l!l
230
MC/DC0%0/1
$@ || 'config reload failed'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
1063 23 ▶ my $failures = $self->reload_failures // 0;
Condition50%1/2
$self->reload_failures // 0
l!l
230
MC/DC0%0/1
$self->reload_failures // 0
$self->reload_failures
Truth table50%1/2
A
A= $self->reload_failures
Aresult
11
00
1064 23 ▶ if ($self->has_config_loader && $failures > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->has_config_loader and $failures > 0) { } 21 2 23
elsif (defined $file_mtime and $failures > 0) { } 2 0 2
Condition66%2/3
$self->has_config_loader and $failures > 0
!ll&&!rl&&r
2021
MC/DC50%1/2
$self->has_config_loader and $failures > 0
$self->has_config_loader $failures > 0
Truth table66%2/3
A and B
A= $self->has_config_loaderB= $failures > 0
ABresult
0X0
100
111
1065 21 $self->_config_next_check_at($self->_now + $self->_reload_retry_delay);
1066 ▶ } elsif (defined($file_mtime) && $failures > 0) {
Condition33%1/3
defined $file_mtime and $failures > 0
!ll&&!rl&&r
002
MC/DC0%0/2
defined $file_mtime and $failures > 0
defined $file_mtime $failures > 0
Truth table33%1/3
A and B
A= defined $file_mtimeB= $failures > 0
ABresult
0X0
100
111
1067 2 $self->_config_file_failed_mtime($file_mtime);
1068 2 $self->_config_file_retry_at($self->_now + $self->_reload_retry_delay);
1069 }
1070 # Logged when the reason is new; the same failure again, retry after retry, is not.
1071 23 ▶ if (!defined($error_before) || $error_before ne $err) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $error_before or $error_before ne $err) 8 15 23
Condition66%2/3
not defined $error_before or $error_before ne $err
l!l&&r!l&&!r
8015
MC/DC50%1/2
not defined $error_before or $error_before ne $err
not defined $error_before $error_before ne $err
Truth table66%2/3
not(A) or B
A= not defined $error_beforeB= $error_before ne $err
ABresult
1X1
011
000
1072 8 (my $msg = $err) =~ s/\s+\z//;
1073 8 warn "skeid: config reload failed, keeping the previous config: $msg\n";
1074 }
1075 23 return 0;
1076 }
1077  
1078 1615 ▶sub _now { Time::HiRes::time() }
Subroutine _now: called CC=1 SCAR=0.0
1079  
1080 # The client-facing faces Skeid serves, as manifest endpoints. Each face's spec -- dialect,
1081 # path under public_url, and the capability flags its translator actually carries upstream --
1082 # lives with that face's translator (ADR 0001: format-specific facts stay in the translator).
1083 my %MANIFEST_FACES = (
1084 17 ▶ openai => sub { Langertha::Skeid::Protocol->openai_manifest_endpoint },
Subroutine __ANON__: called CC=1 SCAR=0.0
1085 17 ▶ anthropic => sub { Langertha::Skeid::Protocol::Anthropic->manifest_endpoint },
Subroutine __ANON__: called CC=1 SCAR=0.0
1086 17 ▶ ollama => sub { Langertha::Skeid::Protocol::Ollama->manifest_endpoint },
Subroutine __ANON__: called CC=1 SCAR=0.0
1087 67 );
1088 67 my @MANIFEST_FACE_ORDER = qw(openai anthropic ollama);
1089 67 my $manifest_unavailable_warned;
1090  
1091 118 ▶sub _is_true {
Subroutine _is_true: called CC=3 SCAR=11.1
1092 118 my ($value) = @_;
1093 118 ▶ return (defined($value) && "$value" =~ /^(1|true|yes|on)$/i) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $value && "$value" =~ /^(1|true|yes|on)$/i ? : 110 8 118
Condition66%2/3
defined $value and "$value" =~ /^(1|true|yes|on)$/i
!ll&&!rl&&r
08110
MC/DC50%1/2
defined $value and "$value" =~ /^(1|true|yes|on)$/i
defined $value "$value" =~ /^(1|true|yes|on)$/i
Truth table66%2/3
A and B
A= defined $valueB= "$value" =~ /^(1|true|yes|on)$/i
ABresult
0X0
100
111
1094 }
1095  
1096 67 my %REGISTRY_KEYS = map { $_ => 1 } qw(enabled secret_env read_key_env ttl_s instance_id error_window_s);
1097  
1098 # The registry section (ADR 0017). Absent means off, so removing the block disables publishing
1099 # on the next reload. Enabled without a usable secret (set, at least MIN_SECRET_BYTES) or
1100 # without any credential to read it (admin key or read key) is a load error: the route never
1101 # answers unsigned, is unreadable without one of the two, and a config that asked for it should
1102 # not load as if it had not.
1103 236 ▶sub _load_registry {
Subroutine _load_registry: called CC=29 SCAR=35.5
1104 236 my ($self, $cfg) = @_;
1105 236 my $section = $cfg->{registry};
1106 236 my ($enabled, $secret, $read_key, $ttl, $instance, $window) = (0, '', '', 10, undef, 60);
1107  
1108 236 ▶ if (defined $section) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section) 16 220 236
1109 16 ▶ croak 'registry must be a hashref' unless ref($section) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 0 16 16
1110 16 for my $key (sort keys %$section) {
1111 croak "registry: unknown key '$key' (known: " . join(' ', sort keys %REGISTRY_KEYS)
1112 . '; the secret is named by secret_env, never written into the config)'
1113 38 ▶ unless $REGISTRY_KEYS{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $REGISTRY_KEYS{$key} 2 36 38
1114 }
1115 14 $enabled = _is_true($section->{enabled});
1116  
1117 14 ▶ if (defined $section->{ttl_s}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"ttl_s"}) 2 12 14
1118 croak 'registry.ttl_s must be a positive number of seconds'
1119 2 ▶ unless looks_like_number($section->{ttl_s}) && $section->{ttl_s} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($section->{"ttl_s"}) and $section->{"ttl_s"} > 0 1 1 2
Condition66%2/3
&looks_like_number($section->{"ttl_s"}) and $section->{"ttl_s"} > 0
!ll&&!rl&&r
011
MC/DC50%1/2
&looks_like_number($section->{"ttl_s"}) and $section->{"ttl_s"} > 0
&looks_like_number($section->{"ttl_s"}) $section->{"ttl_s"} > 0
Truth table66%2/3
A and B
A= &looks_like_number($section->{"ttl_s"})B= $section->{"ttl_s"} > 0
ABresult
0X0
100
111
1120 1 $ttl = 0 + $section->{ttl_s};
1121 }
1122 13 ▶ if (defined $section->{error_window_s}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"error_window_s"}) 0 13 13
1123 croak 'registry.error_window_s must be a positive number of seconds'
1124 0 ▶ unless looks_like_number($section->{error_window_s}) && $section->{error_window_s} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($section->{"error_window_s"}) and $section->{"error_window_s"} > 0 0 0 0
Condition0%0/3
&looks_like_number($section->{"error_window_s"}) and $section->{"error_window_s"} > 0
!ll&&!rl&&r
000
MC/DC0%0/2
&looks_like_number($section->{"error_window_s"}) and $section->{"error_window_s"} > 0
&looks_like_number($section->{"error_window_s"}) $section->{"error_window_s"} > 0
Truth table0%0/3
A and B
A= &looks_like_number($section->{"error_window_s"})B= $section->{"error_window_s"} > 0
ABresult
0X0
100
111
1125 0 $window = 0 + $section->{error_window_s};
1126 }
1127 13 ▶ if (defined $section->{instance_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"instance_id"}) 1 12 13
1128 croak 'registry.instance_id must be a non-empty string'
1129 1 ▶ if ref($section->{instance_id}) || !length($section->{instance_id});
Branch: 1 branch
BranchTrueFalseTotal
if ref $section->{"instance_id"} or not length $section->{"instance_id"} 0 1 1
Condition33%1/3
ref $section->{"instance_id"} or not length $section->{"instance_id"}
l!l&&r!l&&!r
001
MC/DC0%0/2
ref $section->{"instance_id"} or not length $section->{"instance_id"}
ref $section->{"instance_id"} not length $section->{"instance_id"}
Truth table33%1/3
A or not(B)
A= ref $section->{"instance_id"}B= not length $section->{"instance_id"}
ABresult
1X1
011
000
1130 1 $instance = "$section->{instance_id}";
1131 }
1132  
1133 13 ▶ if ($enabled) {
Branch: 1 branch
BranchTrueFalseTotal
if ($enabled) 12 1 13
1134 12 my $env = $section->{secret_env};
1135 12 ▶ croak 'registry.secret_env is required when the registry is enabled: snapshots are '
Branch: 1 branch
BranchTrueFalseTotal
unless defined $env and not ref $env and length $env 1 11 12
Condition66%4/6
defined $env and not ref $env and length $env
!ll&&!rl&&r
1011
defined $env and not ref $env
!ll&&!rl&&r
1011
MC/DC33%1/3
defined $env and not ref $env and length $env
defined $env not ref $env length $env
Truth table50%2/4
A and not(B) and C
A= defined $envB= not ref $envC= length $env
ABCresult
0XX0
10X0
1100
1111
1136 . 'signed, never published unsigned'
1137 unless defined($env) && !ref($env) && length($env);
1138 11 ▶ $secret = $ENV{$env} // '';
Condition100%2/2
$ENV{$env} // ""
l!l
101
MC/DC100%1/1
$ENV{$env} // ""
$ENV{$env}
Truth table100%2/2
A
A= $ENV{$env}
Aresult
11
00
1139 11 ▶ croak "registry.secret_env names '$env', which is not set: snapshots are signed, never "
Branch: 1 branch
BranchTrueFalseTotal
unless length $secret 1 10 11
1140 . 'published unsigned'
1141 unless length $secret;
1142 10 require Langertha::Skeid::Registry;
1143 10 my $min = Langertha::Skeid::Registry->MIN_SECRET_BYTES;
1144 10 ▶ croak "registry.secret_env names '$env', which holds fewer than $min bytes: use a random "
Branch: 1 branch
BranchTrueFalseTotal
if length $secret < $min 1 9 10
1145 . "secret of at least $min bytes (e.g. openssl rand -hex 32)"
1146 if length($secret) < $min;
1147 # The read key opens the snapshot route and nothing else (skeid #49), so a fronting tier
1148 # need not hold the admin key. Named but empty is a mistake, not "no read key".
1149 9 ▶ if (defined $section->{read_key_env}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"read_key_env"}) 4 5 9
1150 4 my $read_env = $section->{read_key_env};
1151 4 ▶ croak 'registry.read_key_env must name an environment variable'
Branch: 1 branch
BranchTrueFalseTotal
if ref $read_env or not length $read_env 0 4 4
Condition33%1/3
ref $read_env or not length $read_env
l!l&&r!l&&!r
004
MC/DC0%0/2
ref $read_env or not length $read_env
ref $read_env not length $read_env
Truth table33%1/3
A or not(B)
A= ref $read_envB= not length $read_env
ABresult
1X1
011
000
1152 if ref($read_env) || !length($read_env);
1153 4 ▶ $read_key = $ENV{$read_env} // '';
Condition100%2/2
$ENV{$read_env} // ""
l!l
31
MC/DC100%1/1
$ENV{$read_env} // ""
$ENV{$read_env}
Truth table100%2/2
A
A= $ENV{$read_env}
Aresult
11
00
1154 4 ▶ croak "registry.read_key_env names '$read_env', which is not set"
Branch: 1 branch
BranchTrueFalseTotal
unless length $read_key 1 3 4
1155 unless length $read_key;
1156 }
1157 # The fronting tier reads the snapshot with the read key or this Skeid's admin key.
1158 # Without either nobody can, and a registry nobody can read is a config mistake, not a
1159 # choice -- say so at load instead of answering 404 forever.
1160 8 ▶ croak 'registry.enabled needs a credential to read the snapshot: registry.read_key_env '
Branch: 1 branch
BranchTrueFalseTotal
unless length $read_key or length($self->admin_api_key // "") 1 7 8
Condition80%4/5
length $read_key or length($self->admin_api_key // "")
l!l&&r!l&&!r
341
$self->admin_api_key // ""
l!l
50
MC/DC0%0/2
length $read_key or length($self->admin_api_key // "")
length $read_key $self->admin_api_key
Truth table66%2/3
A or B
A= length $read_keyB= $self->admin_api_key
ABresult
1X1
011
000
1161 . 'or an admin API key (admin.api_key or admin.api_key_env)'
1162 unless length($read_key) || length($self->admin_api_key // '');
1163 }
1164 }
1165  
1166 228 $self->registry_enabled($enabled);
1167 228 $self->registry_secret($secret);
1168 228 $self->registry_read_key($read_key);
1169 228 $self->registry_ttl_s($ttl);
1170 228 $self->registry_instance_id($instance);
1171 228 $self->registry_error_window_s($window);
1172 228 return 1;
1173 }
1174  
1175 # Resolves the manifest section and every key's manifest: grant once, at config load (ADR
1176 # 0015). Nothing is published that a keys: entry does not list, and what is listed has to be
1177 # something that key's routing policy lets it reach -- a contradiction is a load error, not a
1178 # manifest that promises a model the request path then refuses with 403. Everything is built
1179 # into lexicals and set together at the end; reload_config restores the old state on a croak.
1180 228 ▶sub _load_manifest {
Subroutine _load_manifest: called CC=48 SCAR=40.4
1181 228 my ($self, $cfg) = @_;
1182 228 my ($enabled, $available, %manifests) = (0, 0);
1183 219 ▶ my $commit = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1184 219 $self->manifest_enabled($enabled);
1185 219 $self->manifest_available($available);
1186 219 $self->key_manifests({%manifests});
1187 219 return 1;
1188 228 };
1189  
1190 228 my %grants;
1191 228 ▶ if (ref($cfg->{keys}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"keys"} eq "HASH") 32 196 228
1192 32 for my $label (sort keys %{$cfg->{keys}}) {
1193 60 my $entry = $cfg->{keys}{$label};
1194 60 ▶ next unless ref($entry) eq 'HASH' && exists $entry->{manifest};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" and exists $entry->{"manifest"} 19 41 60
Condition100%3/3
ref $entry eq "HASH" and exists $entry->{"manifest"}
!ll&&!rl&&r
14541
MC/DC100%2/2
ref $entry eq "HASH" and exists $entry->{"manifest"}
ref $entry eq "HASH" exists $entry->{"manifest"}
Truth table100%3/3
A and B
A= ref $entry eq "HASH"B= exists $entry->{"manifest"}
ABresult
0X0
100
111
1195 41 my $grant = $entry->{manifest};
1196 croak "key '$label': manifest must be a hashref with a models list"
1197 41 ▶ unless ref($grant) eq 'HASH' && ref($grant->{models}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $grant eq "HASH" and ref $grant->{"models"} eq "ARRAY" 0 41 41
Condition33%1/3
ref $grant eq "HASH" and ref $grant->{"models"} eq "ARRAY"
!ll&&!rl&&r
0041
MC/DC0%0/2
ref $grant eq "HASH" and ref $grant->{"models"} eq "ARRAY"
ref $grant eq "HASH" ref $grant->{"models"} eq "ARRAY"
Truth table33%1/3
A and B
A= ref $grant eq "HASH"B= ref $grant->{"models"} eq "ARRAY"
ABresult
0X0
100
111
1198 41 my (%seen, @models);
1199 41 for my $model (@{$grant->{models}}) {
1200 80 ▶ croak "key '$label': manifest models must be non-empty model names"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $model and not ref $model and length $model 0 80 80
Condition33%2/6
defined $model and not ref $model and length $model
!ll&&!rl&&r
0080
defined $model and not ref $model
!ll&&!rl&&r
0080
MC/DC0%0/3
defined $model and not ref $model and length $model
defined $model not ref $model length $model
Truth table25%1/4
A and not(B) and C
A= defined $modelB= not ref $modelC= length $model
ABCresult
0XX0
10X0
1100
1111
1201 unless defined($model) && !ref($model) && length($model);
1202 80 ▶ push @models, "$model" unless $seen{$model}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$model}++ 80 0 80
1203 }
1204 41 ▶ my $id = $self->key_names->{$label} // $label;
Condition66%2/3
$self->key_names->{$label} // $label
l!l&&r!l&&!r
3920
MC/DC0%0/2
$self->key_names->{$label} // $label
$self->key_names->{$label} $label
Truth table66%2/3
A // B
A= $self->key_names->{$label}B= $label
ABresult
1X1
011
000
1205 41 $grants{$id} = { label => $label, models => \@models };
1206 }
1207 }
1208  
1209 228 my $section = $cfg->{manifest};
1210 228 ▶ return $commit->() unless defined $section;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $section 208 20 228
1211 20 ▶ croak 'manifest must be a hashref' unless ref($section) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 0 20 20
1212 20 ▶ return $commit->() unless _is_true($section->{enabled});
Branch: 1 branch
BranchTrueFalseTotal
unless _is_true($section->{"enabled"}) 1 19 20
1213  
1214 19 my $public_url = $section->{public_url};
1215 19 ▶ croak 'manifest.public_url is required when the manifest is enabled: the URL clients reach '
Branch: 1 branch
BranchTrueFalseTotal
unless defined $public_url and not ref $public_url and length $public_url 1 18 19
Condition66%4/6
defined $public_url and not ref $public_url and length $public_url
!ll&&!rl&&r
1018
defined $public_url and not ref $public_url
!ll&&!rl&&r
1018
MC/DC33%1/3
defined $public_url and not ref $public_url and length $public_url
defined $public_url not ref $public_url length $public_url
Truth table50%2/4
A and not(B) and C
A= defined $public_urlB= not ref $public_urlC= length $public_url
ABCresult
0XX0
10X0
1100
1111
1216 . 'Skeid at, never a node URL'
1217 unless defined($public_url) && !ref($public_url) && length($public_url);
1218 18 $public_url =~ s{/+\z}{};
1219 18 my ($issuer) = $public_url =~ m{\A([A-Za-z][A-Za-z0-9+.-]*://[^/?#]+)};
1220 18 ▶ croak "manifest.public_url must be an absolute http(s) URL, got '$public_url'" unless $issuer;
Branch: 1 branch
BranchTrueFalseTotal
unless $issuer 0 18 18
1221  
1222 18 ▶ my $provider_id = $section->{provider_id} // 'skeid';
Condition100%2/2
$section->{"provider_id"} // "skeid"
l!l
171
MC/DC100%1/1
$section->{"provider_id"} // "skeid"
$section->{"provider_id"}
Truth table100%2/2
A
A= $section->{"provider_id"}
Aresult
11
00
1223  
1224 18 my @faces = @MANIFEST_FACE_ORDER;
1225 18 ▶ if (defined $section->{faces}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $section->{"faces"}) 2 16 18
1226 2 ▶ croak 'manifest.faces must be a list' unless ref($section->{faces}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section->{"faces"} eq "ARRAY" 0 2 2
1227 2 my %want;
1228 2 for my $face (@{$section->{faces}}) {
1229 croak "manifest.faces: unknown face '" . ($face // '') . "' (known: @MANIFEST_FACE_ORDER)"
1230 2 ▶ unless defined($face) && !ref($face) && $MANIFEST_FACES{$face};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $face and not ref $face and $MANIFEST_FACES{$face} 1 1 2
Condition50%4/8
defined $face and not ref $face and $MANIFEST_FACES{$face}
!ll&&!rl&&r
011
defined $face and not ref $face
!ll&&!rl&&r
002
$face // ""
l!l
10
MC/DC33%1/3
defined $face and not ref $face and $MANIFEST_FACES{$face}
defined $face not ref $face $MANIFEST_FACES{$face}
MC/DC0%0/1
$face // ""
$face
Truth table50%2/4
A and not(B) and C
A= defined $faceB= not ref $faceC= $MANIFEST_FACES{$face}
ABCresult
0XX0
10X0
1100
1111
Truth table50%1/2
A
A= $face
Aresult
11
00
1231 1 $want{$face} = 1;
1232 }
1233 1 @faces = grep { $want{$_} } @MANIFEST_FACE_ORDER;
1234 1 ▶ croak 'manifest.faces must name at least one face' unless @faces;
Branch: 1 branch
BranchTrueFalseTotal
unless @faces 0 1 1
1235 }
1236 17 my %spec = map { $_ => $MANIFEST_FACES{$_}->() } @MANIFEST_FACE_ORDER;
1237  
1238 17 ▶ my $declared = $section->{capabilities} // {};
Condition100%2/2
$section->{"capabilities"} // {}
l!l
512
MC/DC100%1/1
$section->{"capabilities"} // {}
$section->{"capabilities"}
Truth table100%2/2
A
A= $section->{"capabilities"}
Aresult
11
00
1239 croak 'manifest.capabilities must map model names to capability hashes'
1240 17 ▶ unless ref($declared) eq 'HASH' && !grep { ref($_) ne 'HASH' } values %$declared;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $declared eq "HASH" and not grep({ref $_ ne "HASH";} values %$declared) 0 17 17
Condition33%1/3
ref $declared eq "HASH" and not grep({ref $_ ne "HASH";} values %$declared)
!ll&&!rl&&r
0017
MC/DC0%0/2
ref $declared eq "HASH" and not grep({ref $_ ne "HASH";} values %$declared)
ref $declared eq "HASH" not grep({ref $_ ne "HASH";} values %$declared)
Truth table33%1/3
A and not(B)
A= ref $declared eq "HASH"B= not grep({ref $_ ne "HASH";} values %$declared)
ABresult
0X0
100
111
1241  
1242 17 $enabled = 1;
1243  
1244 # Core's manifest (Langertha::Manifest, ADR 0029) is newer than the released Langertha this
1245 # dist requires. Without it the route answers 404; the config is still loaded.
1246 17 ▶ unless (eval { require Langertha::Manifest::Builder; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { require Langertha::Manifest::Builder; 1 } }) 0 17 17
1247 0 ▶ warn "skeid: manifest is enabled, but this Langertha has no Langertha::Manifest; "
Branch: 1 branch
BranchTrueFalseTotal
unless $manifest_unavailable_warned++ 0 0 0
1248 . "/.well-known/langertha.json answers 404\n"
1249 unless $manifest_unavailable_warned++;
1250 0 return $commit->();
1251 }
1252  
1253 # A claim no face of Skeid carries could never be published; saying so beats dropping it.
1254 17 my %allowed = map { $_ => 1 } Langertha::Manifest::Builder->model_capabilities;
1255 17 my %carried = map { $_ => 1 } map { @{$spec{$_}{capabilities}} } @MANIFEST_FACE_ORDER;
1256 17 for my $model (sort keys %$declared) {
1257 5 for my $flag (sort keys %{$declared->{$model}}) {
1258 croak "manifest.capabilities.$model: '$flag' is not a model capability a manifest may "
1259 . 'claim (see Langertha::Manifest::Builder->model_capabilities)'
1260 16 ▶ unless $allowed{$flag};
Branch: 1 branch
BranchTrueFalseTotal
unless $allowed{$flag} 1 15 16
1261 croak "manifest.capabilities.$model: '$flag' is not carried by any face Skeid serves"
1262 15 ▶ unless $carried{$flag};
Branch: 1 branch
BranchTrueFalseTotal
unless $carried{$flag} 1 14 15
1263 }
1264 }
1265  
1266 15 for my $id (sort keys %grants) {
1267 27 my $grant = $grants{$id};
1268 27 for my $model (@{$grant->{models}}) {
1269 52 ▶ croak "key '$grant->{label}': manifest lists model '$model', which its routing policy "
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_manifest_model_reachable($model, $id) 4 48 52
1270 . 'does not let it reach'
1271 unless $self->_manifest_model_reachable($model, $id);
1272 }
1273 23 my $json = eval {
1274 23 my $builder = Langertha::Manifest::Builder->new(
1275 provider_id => $provider_id,
1276 issuer => $issuer,
1277 );
1278 23 $builder->add_auth(id => 'api', type => 'api_key');
1279 23 for my $face (@faces) {
1280 63 my $face_spec = $spec{$face};
1281 63 my %face_carries = map { $_ => 1 } @{$face_spec->{capabilities}};
1282 $builder->add_endpoint(
1283 id => $face,
1284 dialect => $face_spec->{dialect},
1285 base_url => $public_url . $face_spec->{path},
1286 63 auth_ref => 'api',
1287 );
1288 62 for my $model (@{$grant->{models}}) {
1289 # Declared claims over the chat + streaming default, then cut to what this face's
1290 # translator carries: a claim holds "at that endpoint" (core ADR 0029) or not at all.
1291 124 my %caps = (chat => 1, streaming => 1);
1292 124 ▶ my $claims = $declared->{$model} || {};
Condition100%2/2
$declared->{$model} || {}
l!l
18106
MC/DC100%1/1
$declared->{$model} || {}
$declared->{$model}
Truth table100%2/2
A
A= $declared->{$model}
Aresult
11
00
1293 124 for my $flag (keys %$claims) {
1294 84 ▶ if (_is_true($claims->{$flag})) { $caps{$flag} = 1 } else { delete $caps{$flag} }
Branch: 1 branch
BranchTrueFalseTotal
if (_is_true($claims->{$flag})) { } 78 6 84
1295 }
1296 124 delete $caps{$_} for grep { !$face_carries{$_} } keys %caps;
1297 124 $builder->add_model(id => $model, endpoint_ref => $face, capabilities => \%caps);
1298 }
1299 }
1300 22 $builder->manifest->to_json;
1301 };
1302 23 ▶ unless (defined $json) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $json) 1 22 23
1303 1 (my $err = $@) =~ s/\s+at \S+ line \d+\.?\s*\z//s;
1304 1 croak "key '$grant->{label}': manifest does not validate: $err";
1305 }
1306 22 $manifests{$id} = $json;
1307 }
1308  
1309 10 $available = 1;
1310 10 return $commit->();
1311 }
1312  
1313 # Whether the key could be routed to the model at all: its policy grants the name, and some
1314 # node a permitted tier selects -- deny_tags applied, health ignored (a manifest is a claim,
1315 # not a probe) -- serves it. A raw node model behind a denied tag is as unreachable as an alias
1316 # the policy leaves out (ADR 0008), so it is not published either.
1317 52 ▶sub _manifest_model_reachable {
Subroutine _manifest_model_reachable: called CC=7 SCAR=19.7
1318 52 my ($self, $model, $api_key_id) = @_;
1319 52 my $plan = $self->route_plan(model => $model, api_key_id => $api_key_id);
1320 52 ▶ return 0 unless $plan->{permitted};
Branch: 1 branch
BranchTrueFalseTotal
unless $plan->{"permitted"} 2 50 52
1321 50 for my $tier (@{$plan->{tiers}}) {
1322 50 for my $node (@{$self->select_nodes(tags => $tier->{tags}, deny_tags => $tier->{deny_tags})}) {
1323 62 my $served = $node->{model};
1324 62 ▶ return 1 if !defined($served) || !length($served) || $served eq $tier->{model};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $served && length $served or $served eq $tier->{"model"} 48 14 62
Condition50%3/6
not defined $served && length $served or $served eq $tier->{"model"}
l!l&&r!l&&!r
04814
defined $served && length $served
!ll&&!rl&&r
0062
MC/DC33%1/3
not defined $served && length $served or $served eq $tier->{"model"}
defined $served length $served $served eq $tier->{"model"}
Truth table50%2/4
not(A && B) or C
A= defined $servedB= length $servedC= $served eq $tier->{"model"}
ABCresult
0XX1
10X1
1111
1100
1325 }
1326 }
1327 2 return 0;
1328 }
1329  
1330  
1331 17 ▶sub manifest_for_key {
Subroutine manifest_for_key: called CC=4 SCAR=14.6
Pod documented
1332 17 my ($self, $api_key_id) = @_;
1333 17 ▶ return undef unless $self->manifest_enabled && $self->manifest_available;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->manifest_enabled and $self->manifest_available 0 17 17
Condition33%1/3
$self->manifest_enabled and $self->manifest_available
!ll&&!rl&&r
0017
MC/DC0%0/2
$self->manifest_enabled and $self->manifest_available
$self->manifest_enabled $self->manifest_available
Truth table33%1/3
A and B
A= $self->manifest_enabledB= $self->manifest_available
ABresult
0X0
100
111
1334 17 my $id = $self->_configured_key_id($self->key_manifests, $api_key_id);
1335 17 ▶ return defined($id) ? $self->key_manifests->{$id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $id ? : 14 3 17
1336 }
1337  
1338  
1339 4 ▶sub configure_usage_store {
Subroutine configure_usage_store: called CC=1 SCAR=0.0
Pod documented
1340 4 my ($self, $cfg) = @_;
1341 4 return $self->_configure_usage_store($cfg);
1342 }
1343  
1344  
1345 34 ▶sub _configure_usage_store {
Subroutine _configure_usage_store: called CC=41 SCAR=39.0
1346 34 my ($self, $cfg) = @_;
1347 34 ▶ my $normalized = Langertha::Skeid::UsageStore->normalize_config(
Branch: 1 branch
BranchTrueFalseTotal
$self->has_usage_db_path ? : 34 0 34
1348 $cfg,
1349 default_sqlite_path => ($self->has_usage_db_path ? $self->usage_db_path : undef),
1350 );
1351  
1352 34 ▶ my $old = $self->usage_store || {};
Condition50%1/2
$self->usage_store || {}
l!l
340
MC/DC0%0/1
$self->usage_store || {}
$self->usage_store
Truth table50%1/2
A
A= $self->usage_store
Aresult
11
00
1353 my $same = ref($old) eq 'HASH'
1354 && (($old->{backend} // '') eq ($normalized->{backend} // ''))
1355 && (($old->{dsn} // '') eq ($normalized->{dsn} // ''))
1356 && (($old->{path} // '') eq ($normalized->{path} // ''))
1357 && (($old->{mode} // '') eq ($normalized->{mode} // ''))
1358 && (($old->{user} // '') eq ($normalized->{user} // ''))
1359 && (($old->{password} // '') eq ($normalized->{password} // ''))
1360 && (($old->{schema_file} // '') eq ($normalized->{schema_file} // ''))
1361 && ((($old->{auto_migrate} // 1) ? 1 : 0) == (($normalized->{auto_migrate} // 1) ? 1 : 0))
1362 34 ▶ && (($old->{flush_interval_ms} // 0) == ($normalized->{flush_interval_ms} // 0));
Branch: 2 branches
BranchTrueFalseTotal
$old->{'auto_migrate'} // 1 ? : 11 0 11
$normalized->{'auto_migrate'} // 1 ? : 11 0 11
Condition87%55/63
ref $old eq 'HASH' && ($old->{'backend'} // '') eq ($normalized->{'backend'} // '') && ($old->{'dsn'} // '') eq ($normalized->{'dsn'} // '') && ($old->{'path'} // '') eq ($normalized->{'path'} // '') && ($old->{'mode'} // '') eq ($normalized->{'mode'} // '') && ($old->{'user'} // '') eq ($normalized->{'user'} // '') && ($old->{'password'} // '') eq ($normalized->{'password'} // '') && ($old->{'schema_file'} // '') eq ($normalized->{'schema_file'} // '') && ($old->{'auto_migrate'} // 1 ? 1 : 0) == ($normalized->{'auto_migrate'} // 1 ? 1 : 0) && ($old->{'flush_interval_ms'} // 0) == ($normalized->{'flush_interval_ms'} // 0)
!ll&&!rl&&r
2329
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "") and ($old->{"mode"} // "") eq ($normalized->{"mode"} // "") and ($old->{"user"} // "") eq ($normalized->{"user"} // "") and ($old->{"password"} // "") eq ($normalized->{"password"} // "") and ($old->{"schema_file"} // "") eq ($normalized->{"schema_file"} // "") and ($old->{"auto_migrate"} // 1 ? 1 : 0) == ($normalized->{"auto_migrate"} // 1 ? 1 : 0)
!ll&&!rl&&r
23011
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "") and ($old->{"mode"} // "") eq ($normalized->{"mode"} // "") and ($old->{"user"} // "") eq ($normalized->{"user"} // "") and ($old->{"password"} // "") eq ($normalized->{"password"} // "") and ($old->{"schema_file"} // "") eq ($normalized->{"schema_file"} // "")
!ll&&!rl&&r
23011
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "") and ($old->{"mode"} // "") eq ($normalized->{"mode"} // "") and ($old->{"user"} // "") eq ($normalized->{"user"} // "") and ($old->{"password"} // "") eq ($normalized->{"password"} // "")
!ll&&!rl&&r
23011
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "") and ($old->{"mode"} // "") eq ($normalized->{"mode"} // "") and ($old->{"user"} // "") eq ($normalized->{"user"} // "")
!ll&&!rl&&r
23011
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "") and ($old->{"mode"} // "") eq ($normalized->{"mode"} // "")
!ll&&!rl&&r
18511
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "") and ($old->{"path"} // "") eq ($normalized->{"path"} // "")
!ll&&!rl&&r
16216
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "") and ($old->{"dsn"} // "") eq ($normalized->{"dsn"} // "")
!ll&&!rl&&r
61018
ref $old eq "HASH" and ($old->{"backend"} // "") eq ($normalized->{"backend"} // "")
!ll&&!rl&&r
0628
$old->{"backend"} // ""
l!l
286
$normalized->{"backend"} // ""
l!l
340
$old->{"dsn"} // ""
l!l
523
$normalized->{"dsn"} // ""
l!l
1414
$old->{"path"} // ""
l!l
180
$normalized->{"path"} // ""
l!l
180
$old->{"mode"} // ""
l!l
79
$normalized->{"mode"} // ""
l!l
124
$old->{"user"} // ""
l!l
47
$normalized->{"user"} // ""
l!l
47
$old->{"password"} // ""
l!l
47
$normalized->{"password"} // ""
l!l
47
$old->{"schema_file"} // ""
l!l
47
$normalized->{"schema_file"} // ""
l!l
47
$old->{"auto_migrate"} // 1
l!l
47
$normalized->{"auto_migrate"} // 1
l!l
47
$old->{"flush_interval_ms"} // 0
l!l
47
$normalized->{"flush_interval_ms"} // 0
l!l
47
MC/DC0%0/10
ref $old eq 'HASH' && ($old->{'backend'} // '') eq ($normalized->{'backend'} // '') && ($old->{'dsn'} // '') eq ($normalized->{'dsn'} // '') && ($old->{'path'} // '') eq ($normalized->{'path'} // '') && ($old->{'mode'} // '') eq ($normalized->{'mode'} // '') && ($old->{'user'} // '') eq ($normalized->{'user'} // '') && ($old->{'password'} // '') eq ($normalized->{'password'} // '') && ($old->{'schema_file'} // '') eq ($normalized->{'schema_file'} // '') && ($old->{'auto_migrate'} // 1 ? 1 : 0) == ($normalized->{'auto_migrate'} // 1 ? 1 : 0) && ($old->{'flush_interval_ms'} // 0) == ($normalized->{'flush_interval_ms'} // 0)
ref $old eq "HASH" $old->{"backend"} $old->{"dsn"} $old->{"path"} $old->{"mode"} $old->{"user"} $old->{"password"} $old->{"schema_file"} $old->{"auto_migrate"} $old->{"flush_interval_ms"}
MC/DC0%0/1
$normalized->{"backend"} // ""
$normalized->{"backend"}
MC/DC100%1/1
$normalized->{"dsn"} // ""
$normalized->{"dsn"}
MC/DC0%0/1
$normalized->{"path"} // ""
$normalized->{"path"}
MC/DC100%1/1
$normalized->{"mode"} // ""
$normalized->{"mode"}
MC/DC100%1/1
$normalized->{"user"} // ""
$normalized->{"user"}
MC/DC100%1/1
$normalized->{"password"} // ""
$normalized->{"password"}
MC/DC100%1/1
$normalized->{"schema_file"} // ""
$normalized->{"schema_file"}
MC/DC100%1/1
$normalized->{"auto_migrate"} // 1
$normalized->{"auto_migrate"}
MC/DC100%1/1
$normalized->{"flush_interval_ms"} // 0
$normalized->{"flush_interval_ms"}
Truth table18%2/11
A and B and C and D and E and F and G and H and I && J
A= ref $old eq "HASH"B= $old->{"backend"}C= $old->{"dsn"}D= $old->{"path"}E= $old->{"mode"}F= $old->{"user"}G= $old->{"password"}H= $old->{"schema_file"}I= $old->{"auto_migrate"}J= $old->{"flush_interval_ms"}
ABCDEFGHIJresult
0XXXXXXXXX0
10XXXXXXXX0
110XXXXXXX0
1110XXXXXX0
11110XXXXX0
111110XXXX0
1111110XXX0
11111110XX0
111111110X0
11111111100
11111111111
Truth table50%1/2
A
A= $normalized->{"backend"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"dsn"}
Aresult
11
00
Truth table50%1/2
A
A= $normalized->{"path"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"mode"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"user"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"password"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"schema_file"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"auto_migrate"}
Aresult
11
00
Truth table100%2/2
A
A= $normalized->{"flush_interval_ms"}
Aresult
11
00
1363  
1364 # Rebuild when the config changed, and also when there simply is no store object yet:
1365 # BUILD hands us the caller's raw config as $old, which can compare equal to its own
1366 # normalized form and would otherwise leave the store unbuilt.
1367 34 ▶ my $changed = $same ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$same ? : 9 25 34
1368 34 ▶ if ($changed || !$self->_usage_store_obj) {
Branch: 1 branch
BranchTrueFalseTotal
if ($changed or not $self->_usage_store_obj) 31 3 34
Condition100%3/3
$changed or not $self->_usage_store_obj
l!l&&r!l&&!r
2563
MC/DC100%2/2
$changed or not $self->_usage_store_obj
$changed not $self->_usage_store_obj
Truth table100%3/3
A or not(B)
A= $changedB= not $self->_usage_store_obj
ABresult
1X1
011
000
1369 # Prepare the new store before letting go of the old one: a store that fails to come up
1370 # fails the reload with the old store still connected (reload_config is all or nothing).
1371 31 my $store = Langertha::Skeid::UsageStore->for_config($normalized);
1372 31 ▶ $store->prepare if $store;
Branch: 1 branch
BranchTrueFalseTotal
if $store 31 0 31
1373 31 ▶ if ($store && $store->can('on_lost')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($store and $store->can("on_lost")) 17 14 31
Condition66%2/3
$store and $store->can("on_lost")
!ll&&!rl&&r
01417
MC/DC50%1/2
$store and $store->can("on_lost")
$store $store->can("on_lost")
Truth table66%2/3
A and B
A= $storeB= $store->can("on_lost")
ABresult
0X0
100
111
1374 17 weaken(my $weak = $self);
1375 17 ▶ $store->on_lost(sub { $weak->_usage_lost(@_) if $weak });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $weak 1 0 1
1376 }
1377 # The old store flushes what it still holds on the way out: those events were recorded
1378 # while it was the configured destination.
1379 31 $self->_disconnect_usage_store;
1380 31 $self->usage_store($normalized);
1381 31 $self->_usage_store_obj($store);
1382 }
1383  
1384 34 ▶ if ($normalized->{backend} eq 'sqlite') {
Branch: 2 branches
BranchTrueFalseTotal
if ($normalized->{'backend'} eq 'sqlite') { } 19 15 34
elsif ($normalized->{'backend'} ne 'jsonlog') { } 0 15 15
1385 19 $self->usage_db_path($normalized->{path});
1386 } elsif ($normalized->{backend} ne 'jsonlog') {
1387 0 ▶ $self->clear_usage_db_path if $self->has_usage_db_path;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_usage_db_path 0 0 0
1388 }
1389  
1390 34 return $self->usage_store;
1391 }
1392 0 ▶sub _set_usage_db_path {
Subroutine _set_usage_db_path: not called CC=1 SCAR=6.9
1393 0 my ($self, $path) = @_;
1394 0 return $self->_configure_usage_store({
1395 backend => 'sqlite',
1396 sqlite_path => $path,
1397 });
1398 }
1399  
1400  
1401 13274 ▶sub _num {
Subroutine _num: called CC=2 SCAR=6.9
1402 13274 my ($v) = @_;
1403 13274 ▶ return 0 unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 7278 5996 13274
1404 5996 return 0 + $v;
1405 }
1406  
1407 38 ▶sub _iso8601_now {
Subroutine _iso8601_now: called CC=1 SCAR=0.0
1408 38 return strftime('%Y-%m-%dT%H:%M:%SZ', gmtime());
1409 }
1410  
1411 1100 ▶sub _discover_engine_ids {
Subroutine _discover_engine_ids: called CC=7 SCAR=21.8
1412 1100 my %ids = %FALLBACK_ENGINE_IDS;
1413 1100 ▶ if (Langertha->can('available_engine_ids')) {
Branch: 1 branch
BranchTrueFalseTotal
if ("Langertha"->can("available_engine_ids")) 1100 0 1100
1414 1100 my $found = eval { Langertha->available_engine_ids };
1415 1100 ▶ if (!$@ && ref($found) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $@ and ref $found eq "ARRAY") 1100 0 1100
Condition33%1/3
not $@ and ref $found eq "ARRAY"
!ll&&!rl&&r
001100
MC/DC0%0/2
not $@ and ref $found eq "ARRAY"
not $@ ref $found eq "ARRAY"
Truth table33%1/3
not(A) and B
A= not $@B= ref $found eq "ARRAY"
ABresult
0X0
100
111
1416 1100 for my $id (@$found) {
1417 41800 ▶ next unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 0 41800 41800
Condition33%1/3
defined $id and length $id
!ll&&!rl&&r
0041800
MC/DC0%0/2
defined $id and length $id
defined $id length $id
Truth table33%1/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
1418 41800 $ids{lc $id} = 1;
1419 }
1420 }
1421 }
1422  
1423 1100 return \%ids;
1424 }
1425  
1426  
1427 0 ▶sub supported_engine_ids {
Subroutine supported_engine_ids: not called CC=1 SCAR=6.9
Pod documented
1428 0 my ($self) = @_;
1429 0 my $ids = _discover_engine_ids();
1430 0 return [ sort keys %$ids ];
1431 }
1432  
1433  
1434 8415 ▶sub normalize_engine_id {
Subroutine normalize_engine_id: called CC=4 SCAR=13.9
Pod documented
1435 8415 my ($self, $value) = @_;
1436 8415 ▶ return '' unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 8415 8415
1437  
1438 8415 my $raw = "$value";
1439 8415 $raw =~ s/^\s+//;
1440 8415 $raw =~ s/\s+$//;
1441 8415 ▶ return '' unless length $raw;
Branch: 1 branch
BranchTrueFalseTotal
unless length $raw 7315 1100 8415
1442  
1443 1100 my $id = lc($raw);
1444 1100 $id =~ s/\Alangertha::engine:://;
1445 1100 $id =~ s/\Alangerthax::engine:://;
1446  
1447 1100 my $ids = _discover_engine_ids();
1448 1100 ▶ return $id if $ids->{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $ids->{$id} 1099 1 1100
1449  
1450 1 my $known = join(', ', sort keys %$ids);
1451 1 croak "unknown engine '$raw' (expected one of: $known)";
1452 }
1453  
1454  
1455 504 ▶sub record_usage {
Subroutine record_usage: called CC=40 SCAR=37.5
Pod documented
1456 504 my ($self, %args) = @_;
1457  
1458 # Disabled fast path: with no sink at all, the event has nowhere to go, so
1459 # skip building it. record_usage runs once per forwarded request, and a
1460 # deployment that meters nothing should not pay for a normalized event it is
1461 # only going to throw away in _store_usage_event. (karr #15)
1462 504 ▶ return { ok => 0, enabled => 0, error => 'usage_store not configured' }
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_has_usage_sink 27 477 504
1463 unless $self->_has_usage_sink;
1464  
1465 477 ▶ my $metrics = ref($args{metrics}) eq 'HASH' ? $args{metrics} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $args{'metrics'} eq 'HASH' ? : 472 5 477
1466 477 ▶ my $usage = ref($metrics->{usage}) eq 'HASH' ? $metrics->{usage} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $metrics->{'usage'} eq 'HASH' ? : 471 6 477
1467 my $tool_calls = ref($metrics->{tool_names}) eq 'ARRAY'
1468 308 ? scalar(@{$metrics->{tool_names}})
1469 477 ▶ : _num($metrics->{tool_calls});
Branch: 1 branch
BranchTrueFalseTotal
ref $metrics->{'tool_names'} eq 'ARRAY' ? : 308 169 477
1470 477 ▶ my $input_tokens = _num($usage->{input}) || _num($usage->{prompt_tokens}) || _num($metrics->{input_tokens});
Condition100%6/6
_num($usage->{'input'}) || _num($usage->{'prompt_tokens'}) || _num($metrics->{'input_tokens'})
l!l&&r!l&&!r
32308137
_num($usage->{"input"}) or _num($usage->{"prompt_tokens"})
l!l&&r!l&&!r
284445
MC/DC100%3/3
_num($usage->{'input'}) || _num($usage->{'prompt_tokens'}) || _num($metrics->{'input_tokens'})
_num($usage->{"input"}) _num($usage->{"prompt_tokens"}) _num($metrics->{'input_tokens'})
Truth table100%4/4
A or B || C
A= _num($usage->{"input"})B= _num($usage->{"prompt_tokens"})C= _num($metrics->{'input_tokens'})
ABCresult
1XX1
01X1
0011
0000
1471 477 ▶ my $output_tokens = _num($usage->{output}) || _num($usage->{completion_tokens}) || _num($metrics->{output_tokens});
Condition100%6/6
_num($usage->{'output'}) || _num($usage->{'completion_tokens'}) || _num($metrics->{'output_tokens'})
l!l&&r!l&&!r
31298148
_num($usage->{"output"}) or _num($usage->{"completion_tokens"})
l!l&&r!l&&!r
274446
MC/DC100%3/3
_num($usage->{'output'}) || _num($usage->{'completion_tokens'}) || _num($metrics->{'output_tokens'})
_num($usage->{"output"}) _num($usage->{"completion_tokens"}) _num($metrics->{'output_tokens'})
Truth table100%4/4
A or B || C
A= _num($usage->{"output"})B= _num($usage->{"completion_tokens"})C= _num($metrics->{'output_tokens'})
ABCresult
1XX1
01X1
0011
0000
1472 477 ▶ my $total_tokens = _num($usage->{total}) || _num($metrics->{total_tokens}) || ($input_tokens + $output_tokens);
Condition100%6/6
_num($usage->{'total'}) || _num($metrics->{'total_tokens'}) || $input_tokens + $output_tokens
l!l&&r!l&&!r
3364137
_num($usage->{"total"}) or _num($metrics->{"total_tokens"})
l!l&&r!l&&!r
28308141
MC/DC100%3/3
_num($usage->{'total'}) || _num($metrics->{'total_tokens'}) || $input_tokens + $output_tokens
_num($usage->{"total"}) _num($metrics->{"total_tokens"}) $input_tokens + $output_tokens
Truth table100%4/4
A or B || C
A= _num($usage->{"total"})B= _num($metrics->{"total_tokens"})C= $input_tokens + $output_tokens
ABCresult
1XX1
01X1
0011
0000
1473 # Prompt-cache read count (k27). Read the same way as the token counts above: the normalized
1474 # name first, then the OpenAI wire spelling (nested under prompt_tokens_details on a real
1475 # OpenAI usage payload), then a flat cached_tokens some compatible servers use, then the
1476 # flattened metrics fallback. Pricing it is metrics.normalize's job (skeid #28): the cost
1477 # fields below arrive already priced.
1478 my $cached_tokens = _num($usage->{cached})
1479 || _num($usage->{cached_tokens})
1480 || _num(ref($usage->{prompt_tokens_details}) eq 'HASH' ? $usage->{prompt_tokens_details}{cached_tokens} : undef)
1481 477 ▶ || _num($metrics->{cached_tokens});
Branch: 1 branch
BranchTrueFalseTotal
ref $usage->{'prompt_tokens_details'} eq 'HASH' ? : 4 371 375
Condition77%7/9
_num($usage->{'cached'}) || _num($usage->{'cached_tokens'}) || _num(ref $usage->{'prompt_tokens_details'} eq 'HASH' ? $usage->{'prompt_tokens_details'}{'cached_tokens'} : undef) || _num($metrics->{'cached_tokens'})
l!l&&r!l&&!r
1060371
_num($usage->{"cached"}) or _num($usage->{"cached_tokens"}) or _num(ref $usage->{"prompt_tokens_details"} eq "HASH" ? $usage->{"prompt_tokens_details"}{"cached_tokens"} : undef)
l!l&&r!l&&!r
1024371
_num($usage->{"cached"}) or _num($usage->{"cached_tokens"})
l!l&&r!l&&!r
1020375
MC/DC50%2/4
_num($usage->{'cached'}) || _num($usage->{'cached_tokens'}) || _num(ref $usage->{'prompt_tokens_details'} eq 'HASH' ? $usage->{'prompt_tokens_details'}{'cached_tokens'} : undef) || _num($metrics->{'cached_tokens'})
_num($usage->{"cached"}) _num($usage->{"cached_tokens"}) _num(ref $usage->{"prompt_tokens_details"} eq "HASH" ? $usage->{"prompt_tokens_details"}{"cached_tokens"} : undef) _num($metrics->{'cached_tokens'})
Truth table60%3/5
A or B or C || D
A= _num($usage->{"cached"})B= _num($usage->{"cached_tokens"})C= _num(ref $usage->{"prompt_tokens_details"} eq "HASH" ? $usage->{"prompt_tokens_details"}{"cached_tokens"} : undef)D= _num($metrics->{'cached_tokens'})
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1482 # Prompt-cache write count (skeid #41), the count cost_cache_write_usd was priced from: the
1483 # normalized name, then the flat metrics value metrics.normalize or the proxy put there.
1484 my $cache_write_tokens = _num($usage->{cache_write})
1485 || _num($usage->{cache_write_tokens})
1486 477 ▶ || _num($metrics->{cache_write_tokens});
Condition50%3/6
_num($usage->{'cache_write'}) || _num($usage->{'cache_write_tokens'}) || _num($metrics->{'cache_write_tokens'})
l!l&&r!l&&!r
096381
_num($usage->{"cache_write"}) or _num($usage->{"cache_write_tokens"})
l!l&&r!l&&!r
00477
MC/DC33%1/3
_num($usage->{'cache_write'}) || _num($usage->{'cache_write_tokens'}) || _num($metrics->{'cache_write_tokens'})
_num($usage->{"cache_write"}) _num($usage->{"cache_write_tokens"}) _num($metrics->{'cache_write_tokens'})
Truth table50%2/4
A or B || C
A= _num($usage->{"cache_write"})B= _num($usage->{"cache_write_tokens"})C= _num($metrics->{'cache_write_tokens'})
ABCresult
1XX1
01X1
0011
0000
1487 477 ▶ my $cost_input = _num($metrics->{cost_input_usd}) || _num($metrics->{input_cost_usd});
Condition66%2/3
_num($metrics->{'cost_input_usd'}) || _num($metrics->{'input_cost_usd'})
l!l&&r!l&&!r
0111366
MC/DC50%1/2
_num($metrics->{'cost_input_usd'}) || _num($metrics->{'input_cost_usd'})
_num($metrics->{'cost_input_usd'}) _num($metrics->{'input_cost_usd'})
Truth table66%2/3
A || B
A= _num($metrics->{'cost_input_usd'})B= _num($metrics->{'input_cost_usd'})
ABresult
1X1
011
000
1488 477 ▶ my $cost_output = _num($metrics->{cost_output_usd}) || _num($metrics->{output_cost_usd});
Condition66%2/3
_num($metrics->{'cost_output_usd'}) || _num($metrics->{'output_cost_usd'})
l!l&&r!l&&!r
0111366
MC/DC50%1/2
_num($metrics->{'cost_output_usd'}) || _num($metrics->{'output_cost_usd'})
_num($metrics->{'cost_output_usd'}) _num($metrics->{'output_cost_usd'})
Truth table66%2/3
A || B
A= _num($metrics->{'cost_output_usd'})B= _num($metrics->{'output_cost_usd'})
ABresult
1X1
011
000
1489 477 ▶ my $cost_total = _num($metrics->{cost_total_usd}) || _num($metrics->{total_cost_usd});
Condition100%3/3
_num($metrics->{'cost_total_usd'}) || _num($metrics->{'total_cost_usd'})
l!l&&r!l&&!r
1111365
MC/DC100%2/2
_num($metrics->{'cost_total_usd'}) || _num($metrics->{'total_cost_usd'})
_num($metrics->{'cost_total_usd'}) _num($metrics->{'total_cost_usd'})
Truth table100%3/3
A || B
A= _num($metrics->{'cost_total_usd'})B= _num($metrics->{'total_cost_usd'})
ABresult
1X1
011
000
1490 # Prompt-cache amounts (skeid #28), already part of cost_total. 0 when the rule had no cache
1491 # rate or the installed Langertha cannot price them -- the cached tokens are then in cost_input.
1492 477 ▶ my $cost_cache_read = _num($metrics->{cost_cache_read_usd}) || _num($metrics->{cache_read_cost_usd});
Condition66%2/3
_num($metrics->{'cost_cache_read_usd'}) || _num($metrics->{'cache_read_cost_usd'})
l!l&&r!l&&!r
055422
MC/DC50%1/2
_num($metrics->{'cost_cache_read_usd'}) || _num($metrics->{'cache_read_cost_usd'})
_num($metrics->{'cost_cache_read_usd'}) _num($metrics->{'cache_read_cost_usd'})
Truth table66%2/3
A || B
A= _num($metrics->{'cost_cache_read_usd'})B= _num($metrics->{'cache_read_cost_usd'})
ABresult
1X1
011
000
1493 477 ▶ my $cost_cache_write = _num($metrics->{cost_cache_write_usd}) || _num($metrics->{cache_write_cost_usd});
Condition66%2/3
_num($metrics->{'cost_cache_write_usd'}) || _num($metrics->{'cache_write_cost_usd'})
l!l&&r!l&&!r
054423
MC/DC50%1/2
_num($metrics->{'cost_cache_write_usd'}) || _num($metrics->{'cache_write_cost_usd'})
_num($metrics->{'cost_cache_write_usd'}) _num($metrics->{'cache_write_cost_usd'})
Truth table66%2/3
A || B
A= _num($metrics->{'cost_cache_write_usd'})B= _num($metrics->{'cache_write_cost_usd'})
ABresult
1X1
011
000
1494  
1495 my %event = (
1496 created_at => ($args{created_at} // _iso8601_now()),
1497 request_id => ($args{request_id} // ''),
1498 api_format => ($args{api_format} // ''),
1499 endpoint => ($args{endpoint} // ''),
1500 api_key_id => ($args{api_key_id} // ''),
1501 provider => ($args{provider} // ''),
1502 engine => ($args{engine} // ''),
1503 model => ($args{model} // ''),
1504 requested_model => ($args{requested_model} // $args{model} // ''),
1505 node_id => ($args{node_id} // ''),
1506 route_url => ($args{route_url} // ''),
1507 status_code => (_num($args{status_code}) || 0),
1508 ok => ($args{ok} ? 1 : 0),
1509 duration_ms => (_num($args{duration_ms}) || 0),
1510 input_tokens => $input_tokens,
1511 output_tokens => $output_tokens,
1512 total_tokens => $total_tokens,
1513 cached_tokens => $cached_tokens,
1514 cache_write_tokens => $cache_write_tokens,
1515 tool_calls => _num($tool_calls),
1516 cost_input_usd => $cost_input,
1517 cost_output_usd => $cost_output,
1518 cost_total_usd => $cost_total,
1519 cost_cache_read_usd => $cost_cache_read,
1520 cost_cache_write_usd => $cost_cache_write,
1521 error_type => ($args{error_type} // ''),
1522 477 ▶ error_message => ($args{error_message} // ''),
Branch: 1 branch
BranchTrueFalseTotal
$args{'ok'} ? : 339 138 477
Condition88%30/34
$args{"created_at"} // _iso8601_now()
l!l&&r!l&&!r
439380
$args{"request_id"} // ""
l!l
44235
$args{"api_format"} // ""
l!l
45027
$args{"endpoint"} // ""
l!l
44136
$args{"api_key_id"} // ""
l!l
46314
$args{"provider"} // ""
l!l
44037
$args{"engine"} // ""
l!l
44037
$args{"model"} // ""
l!l
4770
($args{"requested_model"} // $args{"model"}) // ""
l!l
4770
$args{"requested_model"} // $args{"model"}
l!l&&r!l&&!r
440370
$args{"node_id"} // ""
l!l
44136
$args{"route_url"} // ""
l!l
43938
_num($args{'status_code'}) || 0
l!l
46611
_num($args{'duration_ms'}) || 0
l!l
44334
$args{"error_type"} // ""
l!l
43938
$args{"error_message"} // ""
l!l
43938
MC/DC0%0/2
$args{"created_at"} // _iso8601_now()
$args{"created_at"} _iso8601_now()
MC/DC100%1/1
$args{"request_id"} // ""
$args{"request_id"}
MC/DC100%1/1
$args{"api_format"} // ""
$args{"api_format"}
MC/DC100%1/1
$args{"endpoint"} // ""
$args{"endpoint"}
MC/DC100%1/1
$args{"api_key_id"} // ""
$args{"api_key_id"}
MC/DC100%1/1
$args{"provider"} // ""
$args{"provider"}
MC/DC100%1/1
$args{"engine"} // ""
$args{"engine"}
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
MC/DC0%0/2
($args{"requested_model"} // $args{"model"}) // ""
$args{"requested_model"} $args{"model"}
MC/DC100%1/1
$args{"node_id"} // ""
$args{"node_id"}
MC/DC100%1/1
$args{"route_url"} // ""
$args{"route_url"}
MC/DC100%1/1
_num($args{'status_code'}) || 0
_num($args{'status_code'})
MC/DC100%1/1
_num($args{'duration_ms'}) || 0
_num($args{'duration_ms'})
MC/DC100%1/1
$args{"error_type"} // ""
$args{"error_type"}
MC/DC100%1/1
$args{"error_message"} // ""
$args{"error_message"}
Truth table66%2/3
A // B
A= $args{"created_at"}B= _iso8601_now()
ABresult
1X1
011
000
Truth table100%2/2
A
A= $args{"request_id"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"api_format"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"endpoint"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"api_key_id"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"provider"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
Truth table66%2/3
A // B
A= $args{"requested_model"}B= $args{"model"}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $args{"node_id"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"route_url"}
Aresult
11
00
Truth table100%2/2
A
A= _num($args{'status_code'})
Aresult
11
00
Truth table100%2/2
A
A= _num($args{'duration_ms'})
Aresult
11
00
Truth table100%2/2
A
A= $args{"error_type"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"error_message"}
Aresult
11
00
1523 );
1524 # UTF-8 bytes of the content a streamed request relayed (skeid #36). Optional and additive: a
1525 # non-streamed event has no such key, which a store records as "not measured". An observation
1526 # beside the token counts -- never used to estimate or replace them.
1527 477 ▶ $event{content_bytes} = _num($args{content_bytes}) if defined $args{content_bytes};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"content_bytes"} 191 286 477
1528  
1529 477 return $self->_store_usage_event(\%event);
1530 }
1531  
1532 473 ▶sub _store_usage_event {
Subroutine _store_usage_event: called CC=3 SCAR=11.0
1533 473 my ($self, $event) = @_;
1534 473 ▶ return $self->store_usage_event->($self, $event) if $self->has_store_usage_event;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_store_usage_event 438 35 473
1535 35 my $store = $self->_usage_store_obj;
1536 35 ▶ return { ok => 0, enabled => 0, error => 'usage_store not configured' } unless $store;
Branch: 1 branch
BranchTrueFalseTotal
unless $store 0 35 35
1537 35 return $store->store($event);
1538 }
1539  
1540 # A queued event the store could not write (skeid k78): through on_usage_lost when the
1541 # embedding application -- the proxy -- set it, else a warning. Never the DSN, never a key.
1542 1 ▶sub _usage_lost {
Subroutine _usage_lost: called CC=9 SCAR=41.1
1543 1 my ($self, $event, $err) = @_;
1544 1 ▶ return $self->on_usage_lost->($self, $event, $err) if $self->has_on_usage_lost;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_on_usage_lost 1 0 1
1545 0 my $cfg = $self->usage_store;
1546 warn 'skeid: usage event lost: request_id=' . ($event->{request_id} // '')
1547 . ' store=' . ((ref($cfg) eq 'HASH' && $cfg->{backend}) || 'custom')
1548 . ' api_key_id=' . ($event->{api_key_id} // '')
1549 . ' model=' . ($event->{model} // '')
1550 0 ▶ . ' status=' . ($event->{status_code} // 0)
Condition0%0/15
$event->{"request_id"} // ""
l!l
00
ref $cfg eq 'HASH' && $cfg->{'backend'} || 'custom'
l!l
00
ref $cfg eq "HASH" and $cfg->{"backend"}
!ll&&!rl&&r
000
$event->{"api_key_id"} // ""
l!l
00
$event->{"model"} // ""
l!l
00
$event->{"status_code"} // 0
l!l
00
$err // "unknown error"
l!l
00
MC/DC0%0/1
$event->{"request_id"} // ""
$event->{"request_id"}
MC/DC0%0/2
ref $cfg eq 'HASH' && $cfg->{'backend'} || 'custom'
ref $cfg eq "HASH" $cfg->{"backend"}
MC/DC0%0/1
$event->{"api_key_id"} // ""
$event->{"api_key_id"}
MC/DC0%0/1
$event->{"model"} // ""
$event->{"model"}
MC/DC0%0/1
$event->{"status_code"} // 0
$event->{"status_code"}
MC/DC0%0/1
$err // "unknown error"
$err
Truth table0%0/2
A
A= $event->{"request_id"}
Aresult
11
00
Truth table0%0/3
A and B
A= ref $cfg eq "HASH"B= $cfg->{"backend"}
ABresult
111
0X0
100
Truth table0%0/2
A
A= $event->{"api_key_id"}
Aresult
11
00
Truth table0%0/2
A
A= $event->{"model"}
Aresult
11
00
Truth table0%0/2
A
A= $event->{"status_code"}
Aresult
11
00
Truth table0%0/2
A
A= $err
Aresult
11
00
1551 . ': ' . ($err // 'unknown error') . "\n";
1552 0 return;
1553 }
1554  
1555  
1556 2 ▶sub flush_usage {
Subroutine flush_usage: called CC=3 SCAR=12.0
Pod documented
1557 2 my ($self) = @_;
1558 2 my $store = $self->_usage_store_obj;
1559 2 ▶ return { ok => 1, written => 0 } unless $store && $store->can('flush');
Branch: 1 branch
BranchTrueFalseTotal
unless $store and $store->can("flush") 0 2 2
Condition33%1/3
$store and $store->can("flush")
!ll&&!rl&&r
002
MC/DC0%0/2
$store and $store->can("flush")
$store $store->can("flush")
Truth table33%1/3
A and B
A= $storeB= $store->can("flush")
ABresult
0X0
100
111
1560 2 return $store->flush;
1561 }
1562  
1563 # True when a usage event has somewhere to go: a store_usage_event callback, a
1564 # configured usage store object, or a subclass that overrides _store_usage_event
1565 # (documented in README, exercised by t/14) -- the last is why this cannot be a
1566 # plain attribute check. record_usage consults this before building an event.
1567 504 ▶sub _has_usage_sink {
Subroutine _has_usage_sink: called CC=5 SCAR=16.1
1568 504 my ($self) = @_;
1569 504 ▶ return 1 if $self->has_store_usage_event;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_store_usage_event 438 66 504
1570 66 ▶ return 1 if $self->_usage_store_obj;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_usage_store_obj 35 31 66
1571 31 my $impl = $self->can('_store_usage_event');
1572 31 ▶ return 1 if $impl && $impl != \&_store_usage_event;
Branch: 1 branch
BranchTrueFalseTotal
if $impl and $impl != \&Langertha::Skeid::_store_usage_event 4 27 31
Condition66%2/3
$impl and $impl != \&Langertha::Skeid::_store_usage_event
!ll&&!rl&&r
0274
MC/DC50%1/2
$impl and $impl != \&Langertha::Skeid::_store_usage_event
$impl $impl != \&Langertha::Skeid::_store_usage_event
Truth table66%2/3
A and B
A= $implB= $impl != \&Langertha::Skeid::_store_usage_event
ABresult
0X0
100
111
1573 27 return 0;
1574 }
1575  
1576  
1577 15 ▶sub usage_report {
Subroutine usage_report: called CC=9 SCAR=22.2
Pod documented
1578 15 my ($self, %args) = @_;
1579  
1580 15 my $limit = _num($args{limit});
1581 15 ▶ $limit = 20 if $limit < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $limit < 1 11 4 15
1582 15 ▶ $limit = 500 if $limit > 500;
Branch: 1 branch
BranchTrueFalseTotal
if $limit > 500 0 15 15
1583  
1584 15 my %filters;
1585 15 ▶ $filters{since} = $args{since} if defined $args{since} && length $args{since};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"since"} and length $args{"since"} 1 14 15
Condition66%2/3
defined $args{"since"} and length $args{"since"}
!ll&&!rl&&r
1401
MC/DC50%1/2
defined $args{"since"} and length $args{"since"}
defined $args{"since"} length $args{"since"}
Truth table66%2/3
A and B
A= defined $args{"since"}B= length $args{"since"}
ABresult
0X0
100
111
1586 15 ▶ $filters{api_key_id} = $args{api_key_id} if defined $args{api_key_id} && length $args{api_key_id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"api_key_id"} and length $args{"api_key_id"} 1 14 15
Condition66%2/3
defined $args{"api_key_id"} and length $args{"api_key_id"}
!ll&&!rl&&r
1401
MC/DC50%1/2
defined $args{"api_key_id"} and length $args{"api_key_id"}
defined $args{"api_key_id"} length $args{"api_key_id"}
Truth table66%2/3
A and B
A= defined $args{"api_key_id"}B= length $args{"api_key_id"}
ABresult
0X0
100
111
1587 15 ▶ $filters{model} = $args{model} if defined $args{model} && length $args{model};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"model"} and length $args{"model"} 2 13 15
Condition66%2/3
defined $args{"model"} and length $args{"model"}
!ll&&!rl&&r
1302
MC/DC50%1/2
defined $args{"model"} and length $args{"model"}
defined $args{"model"} length $args{"model"}
Truth table66%2/3
A and B
A= defined $args{"model"}B= length $args{"model"}
ABresult
0X0
100
111
1588 15 $filters{limit} = $limit;
1589  
1590 15 return $self->_query_usage_report(\%filters);
1591 }
1592  
1593 13 ▶sub _query_usage_report {
Subroutine _query_usage_report: called CC=3 SCAR=11.0
1594 13 my ($self, $filters) = @_;
1595 13 ▶ return $self->query_usage_report->($self, $filters) if $self->has_query_usage_report;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_query_usage_report 1 12 13
1596 12 my $store = $self->_usage_store_obj;
1597 12 ▶ return { ok => 0, enabled => 0, error => 'usage_store not configured' } unless $store;
Branch: 1 branch
BranchTrueFalseTotal
unless $store 1 11 12
1598 11 return $store->report($filters);
1599 }
1600 333 ▶sub _usage_object {
Subroutine _usage_object: called CC=4 SCAR=14.6
1601 333 my ($self, %args) = @_;
1602 333 ▶ return Langertha::Usage->from_hash($args{usage}) if ref($args{usage}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $args{"usage"} eq "HASH" 3 330 333
1603 330 ▶ return $args{usage} if ref($args{usage}) && $args{usage}->isa('Langertha::Usage');
Branch: 1 branch
BranchTrueFalseTotal
if ref $args{"usage"} and $args{"usage"}->isa("Langertha::Usage") 0 330 330
Condition33%1/3
ref $args{"usage"} and $args{"usage"}->isa("Langertha::Usage")
!ll&&!rl&&r
33000
MC/DC0%0/2
ref $args{"usage"} and $args{"usage"}->isa("Langertha::Usage")
ref $args{"usage"} $args{"usage"}->isa("Langertha::Usage")
Truth table33%1/3
A and B
A= ref $args{"usage"}B= $args{"usage"}->isa("Langertha::Usage")
ABresult
0X0
100
111
1604 330 return Langertha::Usage->from_response($args{response});
1605 }
1606  
1607  
1608 1 ▶sub estimate_cost {
Subroutine estimate_cost: called CC=3 SCAR=11.6
Pod documented
1609 1 my ($self, %args) = @_;
1610 1 ▶ my $model = $args{model} // '';
Condition50%1/2
$args{"model"} // ""
l!l
10
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
1611 1 my $usage = $self->_usage_object(%args);
1612 1 ▶ my $rule = $args{pricing} || $self->pricing_for_model($model);
Condition33%1/3
$args{'pricing'} || $self->pricing_for_model($model)
l!l&&r!l&&!r
010
MC/DC0%0/2
$args{'pricing'} || $self->pricing_for_model($model)
$args{'pricing'} $self->pricing_for_model($model)
Truth table33%1/3
A || B
A= $args{'pricing'}B= $self->pricing_for_model($model)
ABresult
1X1
011
000
1613 1 my $pricing = Langertha::Pricing->new( default_rule => $rule );
1614 1 return $pricing->cost_for( $usage, undef )->to_hash;
1615 }
1616  
1617  
1618 332 ▶sub normalize_metrics {
Subroutine normalize_metrics: called CC=14 SCAR=28.4
Pod documented
1619 332 my ($self, %args) = @_;
1620 332 ▶ my $model = $args{model} // '';
Condition50%1/2
$args{"model"} // ""
l!l
3320
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
1621 332 my $usage = $self->_usage_object(%args);
1622 332 ▶ my $rule = $args{pricing} || $self->pricing_for_model($model);
Condition33%1/3
$args{'pricing'} || $self->pricing_for_model($model)
l!l&&r!l&&!r
03320
MC/DC0%0/2
$args{'pricing'} || $self->pricing_for_model($model)
$args{'pricing'} $self->pricing_for_model($model)
Truth table33%1/3
A || B
A= $args{'pricing'}B= $self->pricing_for_model($model)
ABresult
1X1
011
000
1623 332 my $pricing = Langertha::Pricing->new( default_rule => $rule );
1624 332 my $cost = $pricing->cost_for( $usage, undef );
1625  
1626 332 my @names;
1627 332 ▶ for my $tc ( @{ $args{tool_calls} || [] } ) {
Condition50%1/2
$args{'tool_calls'} || []
l!l
3320
MC/DC0%0/1
$args{'tool_calls'} || []
$args{'tool_calls'}
Truth table50%1/2
A
A= $args{'tool_calls'}
Aresult
11
00
1628 5 ▶ next unless ref($tc) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tc eq "HASH" 0 5 5
1629 5 ▶ my $n = $tc->{name} // ( ref( $tc->{function} ) eq 'HASH' ? $tc->{function}{name} : undef );
Branch: 1 branch
BranchTrueFalseTotal
ref $tc->{'function'} eq 'HASH' ? : 2 0 2
Condition66%2/3
$tc->{"name"} // (ref $tc->{"function"} eq "HASH" ? $tc->{"function"}{"name"} : undef)
l!l&&r!l&&!r
320
MC/DC0%0/2
$tc->{"name"} // (ref $tc->{"function"} eq "HASH" ? $tc->{"function"}{"name"} : undef)
$tc->{"name"} (ref $tc->{"function"} eq "HASH" ? $tc->{"function"}{"name"} : undef)
Truth table66%2/3
A // B
A= $tc->{"name"}B= (ref $tc->{"function"} eq "HASH" ? $tc->{"function"}{"name"} : undef)
ABresult
1X1
011
000
1630 5 ▶ push @names, $n if defined $n && length $n;
Branch: 1 branch
BranchTrueFalseTotal
if defined $n and length $n 5 0 5
Condition33%1/3
defined $n and length $n
!ll&&!rl&&r
005
MC/DC0%0/2
defined $n and length $n
defined $n length $n
Truth table33%1/3
A and B
A= defined $nB= length $n
ABresult
0X0
100
111
1631 }
1632  
1633 my $record = Langertha::UsageRecord->new(
1634 usage => $usage,
1635 cost => $cost,
1636 provider => $args{provider},
1637 engine => $args{engine},
1638 model => $model,
1639 route => $args{route},
1640 duration_ms => $args{duration_ms},
1641 started_at => $args{started_at},
1642 finished_at => $args{finished_at},
1643 tool_calls => scalar(@names),
1644 tool_names => \@names,
1645 pricing_version => $args{pricing_version},
1646 332 );
1647 332 my $normalized = $record->to_hash;
1648 # The cache read count as the Usage read it, from whichever wire spelling the upstream used
1649 # (skeid #28) -- so the event's cached_tokens is the count its cache cost was priced from.
1650 # Langertha 0.503's Usage has no such count; there the caller reads it off the raw payload.
1651 332 ▶ if ($usage->can('cached_tokens') && defined(my $cached = $usage->cached_tokens)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($usage->can("cached_tokens") and defined(my $cached = $usage->cached_tokens)) 101 231 332
Condition66%2/3
$usage->can("cached_tokens") and defined(my $cached = $usage->cached_tokens)
!ll&&!rl&&r
0231101
MC/DC50%1/2
$usage->can("cached_tokens") and defined(my $cached = $usage->cached_tokens)
$usage->can("cached_tokens") defined(my $cached = $usage->cached_tokens)
Truth table66%2/3
A and B
A= $usage->can("cached_tokens")B= defined(my $cached = $usage->cached_tokens)
ABresult
0X0
100
111
1652 101 $normalized->{cached_tokens} = $cached;
1653 }
1654 # Likewise the cache write count, the one cost_cache_write_usd was priced from (skeid #41).
1655 332 ▶ if ($usage->can('cache_write_tokens') && defined(my $written = $usage->cache_write_tokens)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($usage->can("cache_write_tokens") and defined(my $written = $usage->cache_write_tokens)) 96 236 332
Condition66%2/3
$usage->can("cache_write_tokens") and defined(my $written = $usage->cache_write_tokens)
!ll&&!rl&&r
023696
MC/DC50%1/2
$usage->can("cache_write_tokens") and defined(my $written = $usage->cache_write_tokens)
$usage->can("cache_write_tokens") defined(my $written = $usage->cache_write_tokens)
Truth table66%2/3
A and B
A= $usage->can("cache_write_tokens")B= defined(my $written = $usage->cache_write_tokens)
ABresult
0X0
100
111
1656 96 $normalized->{cache_write_tokens} = $written;
1657 }
1658 332 return $normalized;
1659 }
1660  
1661 3208 ▶sub _route_key {
Subroutine _route_key: called CC=6 SCAR=17.9
1662 3208 my ($self, %args) = @_;
1663 3208 ▶ my $model = $args{model} // '';
Condition50%1/2
$args{"model"} // ""
l!l
32080
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
1664 3208 ▶ my $engine = $self->normalize_engine_id($args{engine} // '');
Condition100%2/2
$args{"engine"} // ""
l!l
18911317
MC/DC100%1/1
$args{"engine"} // ""
$args{"engine"}
Truth table100%2/2
A
A= $args{"engine"}
Aresult
11
00
1665 3208 my $tags = join(',', @{$self->normalize_tags($args{tags})});
1666 3208 my $deny = join(',', @{$self->normalize_tags($args{deny_tags})});
1667 # Tags belong in the key: two selections over the same model address different node sets, and
1668 # a shared round-robin cursor across different-sized sets picks the wrong node. Denied tags
1669 # too -- a key that may not use cloud addresses a smaller set than one that may.
1670 3208 ▶ return join('|', $model, $engine, $tags, ($deny ? "-$deny" : ())) if length($tags) || length($deny);
Branch: 2 branches
BranchTrueFalseTotal
if length $tags or length $deny 503 2705 3208
$deny ? : 294 209 503
Condition100%3/3
length $tags or length $deny
l!l&&r!l&&!r
2182852705
MC/DC100%2/2
length $tags or length $deny
length $tags length $deny
Truth table100%3/3
A or B
A= length $tagsB= length $deny
ABresult
1X1
011
000
1671 2705 return join('|', $model, $engine);
1672 }
1673  
1674 2265 ▶sub _node_can_take {
Subroutine _node_can_take: called CC=8 SCAR=21.7
1675 2265 my ($self, $node) = @_;
1676 2265 ▶ return 0 unless ref($node) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node eq "HASH" 0 2265 2265
1677 2265 ▶ return 0 unless ($node->{healthy} // 0);
Branch: 1 branch
BranchTrueFalseTotal
unless $node->{"healthy"} // 0 0 2265 2265
Condition50%1/2
$node->{"healthy"} // 0
l!l
22650
MC/DC0%0/1
$node->{"healthy"} // 0
$node->{"healthy"}
Truth table50%1/2
A
A= $node->{"healthy"}
Aresult
11
00
1678 2265 ▶ my $id = $node->{id} // '';
Condition50%1/2
$node->{"id"} // ""
l!l
22650
MC/DC0%0/1
$node->{"id"} // ""
$node->{"id"}
Truth table50%1/2
A
A= $node->{"id"}
Aresult
11
00
1679 2265 ▶ return 0 unless length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless length $id 0 2265 2265
1680  
1681 # Both have to agree, and they are not symmetric: max_conns is this process's own guardrail
1682 # and always applies, while a probe may only narrow what it allows. A probe that could widen
1683 # it would turn a stale or broken reading into an overload -- and for a rented node,
1684 # max_conns is a spend limit, not a capacity estimate (ADR 0009).
1685 2265 ▶ return 0 unless $self->_inflight_allows($node);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_inflight_allows($node) 258 2007 2265
1686 2007 ▶ return 0 unless $self->_capacity_allows($id);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_capacity_allows($id) 83 1924 2007
1687 1924 return 1;
1688 }
1689  
1690 2265 ▶sub _inflight_allows {
Subroutine _inflight_allows: called CC=5 SCAR=16.1
1691 2265 my ($self, $node) = @_;
1692 2265 my $max = $self->worker_max_conns($node);
1693 2265 ▶ return 1 if $max <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $max <= 0 469 1796 2265
1694 1796 ▶ return (0 + ($self->_inflight->{$node->{id} // ''} // 0)) < $max ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
0 + ($self->_inflight->{$node->{'id'} // ''} // 0) < $max ? : 1538 258 1796
Condition75%3/4
$self->_inflight->{$node->{"id"} // ""} // 0
l!l
7821014
$node->{"id"} // ""
l!l
17960
MC/DC100%1/1
$self->_inflight->{$node->{"id"} // ""} // 0
$self->_inflight->{$node->{"id"} // ""}
MC/DC0%0/1
$node->{"id"} // ""
$node->{"id"}
Truth table100%2/2
A
A= $self->_inflight->{$node->{"id"} // ""}
Aresult
11
00
Truth table50%1/2
A
A= $node->{"id"}
Aresult
11
00
1695 }
1696  
1697  
1698 2346 ▶sub worker_max_conns {
Subroutine worker_max_conns: called CC=6 SCAR=17.9
Pod documented
1699 2346 my ($self, $node) = @_;
1700 2346 ▶ my $max = 0 + ((ref($node) eq 'HASH' ? $node->{max_conns} : $node) // 0);
Branch: 1 branch
BranchTrueFalseTotal
ref $node eq 'HASH' ? : 2346 0 2346
Condition100%2/2
(ref $node eq "HASH" ? $node->{"max_conns"} : $node) // 0
l!l
23451
MC/DC100%1/1
(ref $node eq "HASH" ? $node->{"max_conns"} : $node) // 0
(ref $node eq "HASH" ? $node->{"max_conns"} : $node)
Truth table100%2/2
A
A= (ref $node eq "HASH" ? $node->{"max_conns"} : $node)
Aresult
11
00
1701 2346 ▶ return 0 if $max <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $max <= 0 471 1875 2346
1702  
1703 1875 my $divisor = $self->_admission_divisor;
1704 1875 ▶ return $max if $divisor <= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $divisor <= 1 1839 36 1875
1705  
1706 36 my $share = int($max / $divisor);
1707 36 ▶ return $share > 0 ? $share : 1;
Branch: 1 branch
BranchTrueFalseTotal
$share > 0 ? : 34 2 36
1708 }
1709  
1710 # How many processes across the whole deployment share one node's max_conns: the prefork workers
1711 # of this process (worker_count) times the separate Skeid frontends in front of the node
1712 # (frontend_count). max_conns is partitioned across frontends first and then across workers, but
1713 # integer division composes -- floor(floor(max/F)/N) == floor(max/(F*N)) -- so the product is
1714 # the only number admission needs (ADR 0012).
1715 1875 ▶sub _admission_divisor {
Subroutine _admission_divisor: called CC=5 SCAR=17.2
1716 1875 my ($self) = @_;
1717 1875 ▶ my $workers = 0 + ($self->worker_count // 1);
Condition50%1/2
$self->worker_count // 1
l!l
18750
MC/DC0%0/1
$self->worker_count // 1
$self->worker_count
Truth table50%1/2
A
A= $self->worker_count
Aresult
11
00
1718 1875 ▶ my $frontends = 0 + ($self->frontend_count // 1);
Condition50%1/2
$self->frontend_count // 1
l!l
18750
MC/DC0%0/1
$self->frontend_count // 1
$self->frontend_count
Truth table50%1/2
A
A= $self->frontend_count
Aresult
11
00
1719 1875 ▶ $workers = 1 if $workers < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $workers < 1 0 1875 1875
1720 1875 ▶ $frontends = 1 if $frontends < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $frontends < 1 0 1875 1875
1721 1875 return $workers * $frontends;
1722 }
1723  
1724  
1725 6 ▶sub worker_share_warnings {
Subroutine worker_share_warnings: called CC=14 SCAR=26.8
Pod documented
1726 6 my ($self) = @_;
1727 6 ▶ my $workers = 0 + ($self->worker_count // 1);
Condition50%1/2
$self->worker_count // 1
l!l
60
MC/DC0%0/1
$self->worker_count // 1
$self->worker_count
Truth table50%1/2
A
A= $self->worker_count
Aresult
11
00
1728 6 ▶ my $frontends = 0 + ($self->frontend_count // 1);
Condition50%1/2
$self->frontend_count // 1
l!l
60
MC/DC0%0/1
$self->frontend_count // 1
$self->frontend_count
Truth table50%1/2
A
A= $self->frontend_count
Aresult
11
00
1729 6 ▶ $workers = 1 if $workers < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $workers < 1 0 6 6
1730 6 ▶ $frontends = 1 if $frontends < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $frontends < 1 0 6 6
1731 6 my $divisor = $workers * $frontends;
1732 6 ▶ return [] if $divisor <= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $divisor <= 1 1 5 6
1733  
1734 # Name the axes that are actually in play, and the matching fix: the operator can only shed
1735 # what they configured. With both dividing, "worker" alone would misname where the surplus
1736 # comes from.
1737 5 my ($split, $fix);
1738 5 ▶ if ($frontends > 1 && $workers > 1) {
Branch: 2 branches
BranchTrueFalseTotal
if ($frontends > 1 and $workers > 1) { } 1 4 5
elsif ($frontends > 1) { } 2 2 4
Condition100%3/3
$frontends > 1 and $workers > 1
!ll&&!rl&&r
221
MC/DC100%2/2
$frontends > 1 and $workers > 1
$frontends > 1 $workers > 1
Truth table100%3/3
A and B
A= $frontends > 1B= $workers > 1
ABresult
0X0
100
111
1739 1 $split = sprintf('%d frontends x %d workers = %d processes', $frontends, $workers, $divisor);
1740 1 $fix = 'fewer frontends or workers, or raise max_conns';
1741 } elsif ($frontends > 1) {
1742 2 $split = sprintf('%d frontends', $frontends);
1743 2 $fix = 'fewer frontends or raise max_conns';
1744 } else {
1745 2 $split = sprintf('%d workers', $workers);
1746 2 $fix = 'fewer workers or raise max_conns';
1747 }
1748  
1749 5 my @warnings;
1750 5 for my $node (@{$self->nodes}) {
1751 5 ▶ my $max = 0 + ($node->{max_conns} // 0);
Condition50%1/2
$node->{"max_conns"} // 0
l!l
50
MC/DC0%0/1
$node->{"max_conns"} // 0
$node->{"max_conns"}
Truth table50%1/2
A
A= $node->{"max_conns"}
Aresult
11
00
1752 5 ▶ next if $max <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $max <= 0 0 5 5
1753 5 ▶ next if $max >= $divisor;
Branch: 1 branch
BranchTrueFalseTotal
if $max >= $divisor 2 3 5
1754 push @warnings, sprintf(
1755 "node '%s': max_conns %d cannot be split across %s; each process will admit 1, "
1756 . "so the node may see up to %d concurrent requests. Use %s.",
1757 3 ▶ ($node->{id} // '?'), $max, $split, $divisor, $fix,
Condition50%1/2
$node->{"id"} // "?"
l!l
30
MC/DC0%0/1
$node->{"id"} // "?"
$node->{"id"}
Truth table50%1/2
A
A= $node->{"id"}
Aresult
11
00
1758 );
1759 }
1760 5 return \@warnings;
1761 }
1762  
1763 # What a probe says about a node, if anything current. Unknown is a valid answer and means
1764 # "inflight decides" -- which is the entire behaviour of a deployment that configures no probes.
1765 2009 ▶sub _capacity_allows {
Subroutine _capacity_allows: called CC=8 SCAR=21.3
1766 2009 my ($self, $node_id) = @_;
1767 2009 ▶ my $reading = $self->capacity_reading($node_id) or return 1;
Branch: 1 branch
BranchTrueFalseTotal
my $reading = $self->capacity_reading($node_id) or return 1 129 1880 2009
1768  
1769 # A provider that told us to come back later is not busy in the inflight sense: no request of
1770 # ours is outstanding, and admitting one would just buy another 429.
1771 129 ▶ return 0 if $reading->{retry_after} && time < $reading->{retry_after};
Branch: 1 branch
BranchTrueFalseTotal
if $reading->{"retry_after"} and time < $reading->{"retry_after"} 39 90 129
Condition66%2/3
$reading->{"retry_after"} and time < $reading->{"retry_after"}
!ll&&!rl&&r
90039
MC/DC50%1/2
$reading->{"retry_after"} and time < $reading->{"retry_after"}
$reading->{"retry_after"} time < $reading->{"retry_after"}
Truth table66%2/3
A and B
A= $reading->{"retry_after"}B= time < $reading->{"retry_after"}
ABresult
0X0
100
111
1772  
1773 90 ▶ my $limit = 0 + ($reading->{limit} // 0);
Condition50%1/2
$reading->{"limit"} // 0
l!l
900
MC/DC0%0/1
$reading->{"limit"} // 0
$reading->{"limit"}
Truth table50%1/2
A
A= $reading->{"limit"}
Aresult
11
00
1774 90 ▶ return 1 if $limit <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $limit <= 0 0 90 90
1775 90 ▶ return (0 + ($reading->{used} // 0)) < $limit ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
0 + ($reading->{'used'} // 0) < $limit ? : 45 45 90
Condition50%1/2
$reading->{"used"} // 0
l!l
900
MC/DC0%0/1
$reading->{"used"} // 0
$reading->{"used"}
Truth table50%1/2
A
A= $reading->{"used"}
Aresult
11
00
1776 }
1777  
1778 1323 ▶sub _node_has_tags {
Subroutine _node_has_tags: called CC=6 SCAR=18.0
1779 1323 my ($self, $node, $tags) = @_;
1780 1323 ▶ return 1 unless $tags && @$tags;
Branch: 1 branch
BranchTrueFalseTotal
unless $tags and @$tags 1231 92 1323
Condition66%2/3
$tags and @$tags
!ll&&!rl&&r
0123192
MC/DC50%1/2
$tags and @$tags
$tags @$tags
Truth table66%2/3
A and B
A= $tagsB= @$tags
ABresult
0X0
100
111
1781 92 ▶ my %have = map { $_ => 1 } @{$node->{tags} || []};
Condition50%1/2
$node->{'tags'} || []
l!l
920
MC/DC0%0/1
$node->{'tags'} || []
$node->{'tags'}
Truth table50%1/2
A
A= $node->{'tags'}
Aresult
11
00
1782 92 for my $tag (@$tags) {
1783 94 ▶ return 0 unless $have{$tag};
Branch: 1 branch
BranchTrueFalseTotal
unless $have{$tag} 46 48 94
1784 }
1785 46 return 1;
1786 }
1787  
1788 # The deny side is ANY, not ALL: one forbidden tag on a node is enough to rule it out. A policy
1789 # that denies "cloud" must exclude a node tagged [cloud, groq] without having to name groq too.
1790 1304 ▶sub _node_has_any_tag {
Subroutine _node_has_any_tag: called CC=6 SCAR=18.0
1791 1304 my ($self, $node, $tags) = @_;
1792 1304 ▶ return 0 unless $tags && @$tags;
Branch: 1 branch
BranchTrueFalseTotal
unless $tags and @$tags 1255 49 1304
Condition66%2/3
$tags and @$tags
!ll&&!rl&&r
0125549
MC/DC50%1/2
$tags and @$tags
$tags @$tags
Truth table66%2/3
A and B
A= $tagsB= @$tags
ABresult
0X0
100
111
1793 49 ▶ my %have = map { $_ => 1 } @{$node->{tags} || []};
Condition50%1/2
$node->{'tags'} || []
l!l
490
MC/DC0%0/1
$node->{'tags'} || []
$node->{'tags'}
Truth table50%1/2
A
A= $node->{'tags'}
Aresult
11
00
1794 49 for my $tag (@$tags) {
1795 49 ▶ return 1 if $have{$tag};
Branch: 1 branch
BranchTrueFalseTotal
if $have{$tag} 9 40 49
1796 }
1797 40 return 0;
1798 }
1799  
1800 # The selection cache includes negative requested models, and requested models are client input.
1801 # Keep a small fixed working set rather than turning every spelling ever seen into process-lifetime
1802 # state. FIFO makes eviction deterministic; an evicted route's cursor is removed with it, so that
1803 # route restarts weighted fairness if it is requested again.
1804 67 my $ROUTE_CACHE_MAX_ENTRIES = 256;
1805  
1806 # Everything derived from the inventory -- which nodes are eligible, their round-robin order
1807 # and their weights -- is computed once per selection and reused until the inventory changes.
1808 # Only admission stays per request, because inflight is the one part that moves between two
1809 # requests to the same selection.
1810 2141 ▶sub _route_entry {
Subroutine _route_entry: called CC=28 SCAR=36.1
1811 2141 my ($self, %args) = @_;
1812 2141 my $cache = $self->_route_cache;
1813 2141 ▶ if (($cache->{generation} // -1) != $self->_inventory_generation) {
Branch: 1 branch
BranchTrueFalseTotal
if (($cache->{"generation"} // -1) != $self->_inventory_generation) 338 1803 2141
Condition50%1/2
$cache->{"generation"} // -1
l!l
21410
MC/DC0%0/1
$cache->{"generation"} // -1
$cache->{"generation"}
Truth table50%1/2
A
A= $cache->{"generation"}
Aresult
11
00
1814 338 $cache = { generation => $self->_inventory_generation, entries => {}, order => [] };
1815 338 $self->_route_cache($cache);
1816 }
1817  
1818 2141 my $key = $self->_route_key(%args);
1819 2141 my $entry = $cache->{entries}{$key};
1820 2141 ▶ return $entry if $entry;
Branch: 1 branch
BranchTrueFalseTotal
if $entry 955 1186 2141
1821  
1822 1186 my $model = $args{model};
1823 1186 ▶ my $engine = $self->normalize_engine_id($args{engine} // '');
Condition100%2/2
$args{"engine"} // ""
l!l
345841
MC/DC100%1/1
$args{"engine"} // ""
$args{"engine"}
Truth table100%2/2
A
A= $args{"engine"}
Aresult
11
00
1824 1186 my $tags = $self->normalize_tags($args{tags});
1825 1186 my $deny = $self->normalize_tags($args{deny_tags});
1826  
1827 my @nodes = grep {
1828 (!defined($model) || !length($model) || !defined($_->{model}) || !length($_->{model}) || $_->{model} eq $model)
1829 && (!defined($engine) || !length($engine) || !defined($_->{engine}) || !length($_->{engine}) || $_->{engine} eq $engine)
1830 2447 ▶ && (($_->{healthy} // 0) ? 1 : 0)
Branch: 1 branch
BranchTrueFalseTotal
$_->{'healthy'} // 0 ? : 1211 6 1217
Condition60%23/38
(!(defined $model && length $model && defined $_->{'model'} && length $_->{'model'}) || $_->{'model'} eq $model) && (!(defined $engine && length $engine && defined $_->{'engine'} && length $_->{'engine'}) || $_->{'engine'} eq $engine) && ($_->{'healthy'} // 0 ? 1 : 0) && $self->_node_has_tags($_, $tags) && !$self->_node_has_any_tag($_, $deny)
!ll&&!rl&&r
125541188
!(defined $model && length $model && defined $_->{"model"} && length $_->{"model"}) || $_->{"model"} eq $model and !(defined $engine && length $engine && defined $_->{"engine"} && length $_->{"engine"}) || $_->{"engine"} eq $engine and $_->{"healthy"} // 0 ? 1 : 0 and $self->_node_has_tags($_, $tags)
!ll&&!rl&&r
1236191192
!(defined $model && length $model && defined $_->{"model"} && length $_->{"model"}) || $_->{"model"} eq $model and !(defined $engine && length $engine && defined $_->{"engine"} && length $_->{"engine"}) || $_->{"engine"} eq $engine and $_->{"healthy"} // 0 ? 1 : 0
!ll&&!rl&&r
123061211
!(defined $model && length $model && defined $_->{"model"} && length $_->{"model"}) || $_->{"model"} eq $model and !(defined $engine && length $engine && defined $_->{"engine"} && length $_->{"engine"}) || $_->{"engine"} eq $engine
!ll&&!rl&&r
123001217
not defined $model && length $model && defined $_->{"model"} && length $_->{"model"} or $_->{"model"} eq $model
l!l&&r!l&&!r
8084091230
defined $model && length $model && defined $_->{'model'} && length $_->{'model'}
!ll&&!rl&&r
08081639
defined $model and length $model and defined $_->{"model"}
!ll&&!rl&&r
002447
defined $model and length $model
!ll&&!rl&&r
002447
not defined $engine && length $engine && defined $_->{"engine"} && length $_->{"engine"} or $_->{"engine"} eq $engine
l!l&&r!l&&!r
121700
defined $engine && length $engine && defined $_->{'engine'} && length $_->{'engine'}
!ll&&!rl&&r
121700
defined $engine and length $engine and defined $_->{"engine"}
!ll&&!rl&&r
121700
defined $engine and length $engine
!ll&&!rl&&r
012170
$_->{"healthy"} // 0
l!l
12170
MC/DC30%4/13
(!(defined $model && length $model && defined $_->{'model'} && length $_->{'model'}) || $_->{'model'} eq $model) && (!(defined $engine && length $engine && defined $_->{'engine'} && length $_->{'engine'}) || $_->{'engine'} eq $engine) && ($_->{'healthy'} // 0 ? 1 : 0) && $self->_node_has_tags($_, $tags) && !$self->_node_has_any_tag($_, $deny)
defined $model length $model defined $_->{"model"} length $_->{'model'} $_->{"model"} eq $model defined $engine length $engine defined $_->{"engine"} length $_->{'engine'} $_->{"engine"} eq $engine $_->{"healthy"} $self->_node_has_tags($_, $tags) !$self->_node_has_any_tag($_, $deny)
Truth table6%7/106
not(A and B and C && D) or E and not(F and G and H && I) or J and K and L && not(M)
A= defined $modelB= length $modelC= defined $_->{"model"}D= length $_->{'model'}E= $_->{"model"} eq $modelF= defined $engineG= length $engineH= defined $_->{"engine"}I= length $_->{'engine'}J= $_->{"engine"} eq $engineK= $_->{"healthy"}L= $self->_node_has_tags($_, $tags)M= !$self->_node_has_any_tag($_, $deny)
ABCDEFGHIJKLMresult
11110XXXXXXXX0
0XXXX11110XXX0
10XXX11110XXX0
110XX11110XXX0
1110X11110XXX0
1111111110XXX0
0XXXX0XXXX0XX0
0XXXX10XXX0XX0
0XXXX110XX0XX0
0XXXX1110X0XX0
0XXXX111110XX0
10XXX0XXXX0XX0
10XXX10XXX0XX0
10XXX110XX0XX0
10XXX1110X0XX0
10XXX111110XX0
110XX0XXXX0XX0
110XX10XXX0XX0
110XX110XX0XX0
110XX1110X0XX0
110XX111110XX0
1110X0XXXX0XX0
1110X10XXX0XX0
1110X110XX0XX0
1110X1110X0XX0
1110X111110XX0
111110XXXX0XX0
1111110XXX0XX0
11111110XX0XX0
111111110X0XX0
11111111110XX0
0XXXX0XXXX10X0
0XXXX10XXX10X0
0XXXX110XX10X0
0XXXX1110X10X0
0XXXX1111110X0
10XXX0XXXX10X0
10XXX10XXX10X0
10XXX110XX10X0
10XXX1110X10X0
10XXX1111110X0
110XX0XXXX10X0
110XX10XXX10X0
110XX110XX10X0
110XX1110X10X0
110XX1111110X0
1110X0XXXX10X0
1110X10XXX10X0
1110X110XX10X0
1110X1110X10X0
1110X1111110X0
111110XXXX10X0
1111110XXX10X0
11111110XX10X0
111111110X10X0
111111111110X0
0XXXX0XXXX1100
0XXXX10XXX1100
0XXXX110XX1100
0XXXX1110X1100
0XXXX111111100
10XXX0XXXX1100
10XXX10XXX1100
10XXX110XX1100
10XXX1110X1100
10XXX111111100
110XX0XXXX1100
110XX10XXX1100
110XX110XX1100
110XX1110X1100
110XX111111100
1110X0XXXX1100
1110X10XXX1100
1110X110XX1100
1110X1110X1100
1110X111111100
111110XXXX1100
1111110XXX1100
11111110XX1100
111111110X1100
11111111111100
0XXXX0XXXX1111
0XXXX10XXX1111
0XXXX110XX1111
0XXXX1110X1111
0XXXX111111111
10XXX0XXXX1111
10XXX10XXX1111
10XXX110XX1111
10XXX1110X1111
10XXX111111111
110XX0XXXX1111
110XX10XXX1111
110XX110XX1111
110XX1110X1111
110XX111111111
1110X0XXXX1111
1110X10XXX1111
1110X110XX1111
1110X1110X1111
1110X111111111
111110XXXX1111
1111110XXX1111
11111110XX1111
111111110X1111
11111111111111
1831 && $self->_node_has_tags($_, $tags)
1832 && !$self->_node_has_any_tag($_, $deny)
1833 1186 ▶ } @{$self->nodes || []};
Condition50%1/2
$self->nodes || []
l!l
11860
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
1834  
1835 1186 ▶ @nodes = sort { ($a->{id} // '') cmp ($b->{id} // '') } @nodes;
Condition50%2/4
$Langertha::Skeid::a->{"id"} // ""
l!l
4200
$Langertha::Skeid::b->{"id"} // ""
l!l
4200
MC/DC0%0/1
$Langertha::Skeid::a->{"id"} // ""
$Langertha::Skeid::a->{"id"}
MC/DC0%0/1
$Langertha::Skeid::b->{"id"} // ""
$Langertha::Skeid::b->{"id"}
Truth table50%1/2
A
A= $Langertha::Skeid::a->{"id"}
Aresult
11
00
Truth table50%1/2
A
A= $Langertha::Skeid::b->{"id"}
Aresult
11
00
1836 my @weights = map {
1837 1186 ▶ my $w = 0 + ($_->{weight} // 1);
Condition100%2/2
$_->{"weight"} // 1
l!l
11871
MC/DC100%1/1
$_->{"weight"} // 1
$_->{"weight"}
Truth table100%2/2
A
A= $_->{"weight"}
Aresult
11
00
1838 1188 ▶ $w = 1 if $w < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $w < 1 0 1188 1188
1839 1188 int($w);
1840 } @nodes;
1841 1186 my $total_weight = 0;
1842 1186 $total_weight += $_ for @weights;
1843  
1844 1186 my $new_entry = {
1845 nodes => \@nodes,
1846 weights => \@weights,
1847 total_weight => $total_weight,
1848 };
1849  
1850 1186 ▶ my $order = $cache->{order} ||= [];
Condition50%1/2
$cache->{"order"} ||= []
l!l
11860
MC/DC0%0/1
$cache->{"order"} ||= []
$cache->{"order"}
Truth table50%1/2
A
A= $cache->{"order"}
Aresult
11
00
1851 1186 ▶ while (@$order >= $ROUTE_CACHE_MAX_ENTRIES) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$order >= $ROUTE_CACHE_MAX_ENTRIES) 290 1186 1476
1852 290 my $evicted = shift @$order;
1853 290 ▶ next unless exists $cache->{entries}{$evicted};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cache->{"entries"}{$evicted} 0 290 290
1854 290 delete $cache->{entries}{$evicted};
1855 # The cursor tracks ranges stored by this entry. Keeping it would defeat the bound and would
1856 # resume at stale fairness state if this route key later re-enters the working set.
1857 290 delete $self->_rr_cursor->{$evicted};
1858 }
1859 1186 $cache->{entries}{$key} = $new_entry;
1860 1186 push @$order, $key;
1861 1186 return $new_entry;
1862 }
1863  
1864 # Returns the live node hashrefs, not copies. Callers read them and must not mutate them --
1865 # pick_node builds its own hash for the node it returns.
1866 1076 ▶sub _eligible_nodes {
Subroutine _eligible_nodes: called CC=1 SCAR=0.0
1867 1076 my ($self, %args) = @_;
1868 1076 return $self->_route_entry(%args)->{nodes};
1869 }
1870  
1871  
1872 39 ▶sub set_model_alias {
Subroutine set_model_alias: called CC=14 SCAR=27.2
Pod documented
1873 39 my ($self, $name, $spec) = @_;
1874 39 ▶ croak 'alias name required' unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 39 39
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
0039
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
1875  
1876 my $tiers = ref($spec) eq 'ARRAY' ? $spec
1877 : ref($spec) eq 'HASH' ? $spec->{tiers}
1878 39 ▶ : croak "alias '$name': must be a hashref with tiers, or an arrayref of tiers";
Branch: 2 branches
BranchTrueFalseTotal
ref $spec eq 'ARRAY' ? : 1 38 39
ref $spec eq 'HASH' ? : 37 1 38
1879 38 ▶ croak "alias '$name': tiers must be an arrayref" unless ref($tiers) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tiers eq "ARRAY" 0 38 38
1880 38 ▶ croak "alias '$name': needs at least one tier" unless @$tiers;
Branch: 1 branch
BranchTrueFalseTotal
unless @$tiers 1 37 38
1881  
1882 37 my @normalized;
1883 37 for my $tier (@$tiers) {
1884 43 ▶ croak "alias '$name': each tier must be a hashref" unless ref($tier) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tier eq "HASH" 0 43 43
1885 push @normalized, {
1886 tags => $self->normalize_tags($tier->{tags}),
1887 model => ((defined($tier->{model}) && length($tier->{model})) ? "$tier->{model}" : $name),
1888 engine => $self->normalize_engine_id($tier->{engine} // ''),
1889 43 ▶ wait_ms => (defined($tier->{wait_ms}) && $tier->{wait_ms} > 0 ? 0 + $tier->{wait_ms} : 0),
Branch: 2 branches
BranchTrueFalseTotal
defined $tier->{'model'} && length $tier->{'model'} ? : 41 2 43
defined $tier->{'wait_ms'} && $tier->{'wait_ms'} > 0 ? : 4 39 43
Condition75%6/8
defined $tier->{"model"} and length $tier->{"model"}
!ll&&!rl&&r
2041
$tier->{"engine"} // ""
l!l
043
defined $tier->{"wait_ms"} and $tier->{"wait_ms"} > 0
!ll&&!rl&&r
3544
MC/DC50%1/2
defined $tier->{"model"} and length $tier->{"model"}
defined $tier->{"model"} length $tier->{"model"}
MC/DC0%0/1
$tier->{"engine"} // ""
$tier->{"engine"}
MC/DC100%2/2
defined $tier->{"wait_ms"} and $tier->{"wait_ms"} > 0
defined $tier->{"wait_ms"} $tier->{"wait_ms"} > 0
Truth table66%2/3
A and B
A= defined $tier->{"model"}B= length $tier->{"model"}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $tier->{"engine"}
Aresult
11
00
Truth table100%3/3
A and B
A= defined $tier->{"wait_ms"}B= $tier->{"wait_ms"} > 0
ABresult
0X0
100
111
1890 };
1891 }
1892  
1893 37 $self->model_aliases->{$name} = { tiers => \@normalized };
1894 37 return 1;
1895 }
1896  
1897  
1898 3 ▶sub set_policy {
Subroutine set_policy: called CC=3 SCAR=12.0
Pod documented
1899 3 my ($self, $name, $spec) = @_;
1900 3 ▶ croak 'policy name required' unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 3 3
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
003
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
1901 3 $self->policies->{$name} = $self->resolve_policy($spec, $name);
1902 3 return 1;
1903 }
1904  
1905  
1906 83 ▶sub resolve_policy {
Subroutine resolve_policy: called CC=9 SCAR=22.3
Pod documented
1907 83 my ($self, $spec, $name) = @_;
1908 83 ▶ $spec = {} unless ref($spec) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 0 83 83
1909  
1910 83 ▶ my $allow = $spec->{models} // $spec->{aliases};
Condition66%2/3
$spec->{"models"} // $spec->{"aliases"}
l!l&&r!l&&!r
23060
MC/DC50%1/2
$spec->{"models"} // $spec->{"aliases"}
$spec->{"models"} $spec->{"aliases"}
Truth table66%2/3
A // B
A= $spec->{"models"}B= $spec->{"aliases"}
ABresult
1X1
011
000
1911 83 my $allow_models;
1912 83 ▶ if (defined $allow) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $allow) 23 60 83
1913 23 ▶ my @list = ref($allow) eq 'ARRAY' ? @$allow : split(/[,\s]+/, "$allow");
Branch: 1 branch
BranchTrueFalseTotal
ref $allow eq 'ARRAY' ? : 22 1 23
1914 23 ▶ @list = grep { defined && length } @list;
Condition33%1/3
defined $_ && length $_
!ll&&!rl&&r
0045
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
1915 # An explicit '*' is the same as saying nothing, and saying it out loud reads better in a
1916 # config than an absent key.
1917 23 ▶ $allow_models = (grep { $_ eq '*' } @list) ? undef : { map { $_ => 1 } @list };
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ eq '*';} @list) ? : 1 22 23
1918 }
1919  
1920 return {
1921 name => ($name // $spec->{name} // ''),
1922 allow_models => $allow_models,
1923 83 ▶ deny_tags => $self->normalize_tags($spec->{deny_tags}),
Condition80%4/5
($name // $spec->{"name"}) // ""
l!l
785
$name // $spec->{"name"}
l!l&&r!l&&!r
7805
MC/DC50%1/2
($name // $spec->{"name"}) // ""
$name $spec->{"name"}
Truth table66%2/3
A // B
A= $nameB= $spec->{"name"}
ABresult
1X1
011
000
1924 };
1925 }
1926  
1927 # Key ids before ADR 0016 were the first 12 hex digits of the same digest, so a short id is
1928 # the prefix of the full id of the same key.
1929 67 my $LEGACY_KEY_ID_HEX = 12;
1930 67 my %legacy_key_id_warned;
1931  
1932 # Resolves the whole policy section once, at config load. Nothing here happens per request:
1933 # a request costs one hash lookup, and identical resolutions share a single object, so a
1934 # thousand keys on three profiles are three policy objects and a thousand pointers.
1935 51 ▶sub _load_policies {
Subroutine _load_policies: called CC=30 SCAR=34.2
1936 51 my ($self, $cfg) = @_;
1937  
1938 51 my %policies;
1939 51 ▶ if (ref($cfg->{policies}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"policies"} eq "HASH") 46 5 51
1940 46 for my $name (keys %{$cfg->{policies}}) {
1941 75 $policies{$name} = $self->resolve_policy($cfg->{policies}{$name}, $name);
1942 }
1943 }
1944  
1945 51 my %interned = map { $self->_policy_fingerprint($_) => $_ } values %policies;
1946 46 ▶ my $intern = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1947 46 my ($policy) = @_;
1948 46 my $print = $self->_policy_fingerprint($policy);
1949 46 ▶ return $interned{$print} ||= $policy;
Condition66%2/3
$interned{$print} ||= $policy
l!l&&r!l&&!r
4420
MC/DC0%0/2
$interned{$print} ||= $policy
$interned{$print} $policy
Truth table66%2/3
A ||= B
A= $interned{$print}B= $policy
ABresult
1X1
011
000
1950 51 };
1951  
1952 51 my $default;
1953 51 ▶ if (defined $cfg->{default_policy} && length $cfg->{default_policy}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cfg->{"default_policy"} and length $cfg->{"default_policy"}) 36 15 51
Condition66%2/3
defined $cfg->{"default_policy"} and length $cfg->{"default_policy"}
!ll&&!rl&&r
15036
MC/DC50%1/2
defined $cfg->{"default_policy"} and length $cfg->{"default_policy"}
defined $cfg->{"default_policy"} length $cfg->{"default_policy"}
Truth table66%2/3
A and B
A= defined $cfg->{"default_policy"}B= length $cfg->{"default_policy"}
ABresult
0X0
100
111
1954 36 $default = $policies{$cfg->{default_policy}};
1955 36 ▶ croak "default_policy '$cfg->{default_policy}' is not defined in policies" unless $default;
Branch: 1 branch
BranchTrueFalseTotal
unless $default 5 31 36
1956 }
1957  
1958 # names: is a readable-name -> key-id registry that lives in the config, resolved to key ids
1959 # here and never consulted on the request path (karr #17, ADR 0008). A value must be an id
1960 # from `skeid keyid`, never a customer key -- the config still holds no keys. With it, a
1961 # keys: entry may be written by name, and rotating a customer's key is a one-line edit here
1962 # rather than a rewrite of every policy line that named them by id.
1963 46 my %key_names;
1964 46 ▶ if (ref($cfg->{names}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"names"} eq "HASH") 27 19 46
1965 27 for my $name (keys %{$cfg->{names}}) {
1966 48 my $id = $cfg->{names}{$name};
1967 48 ▶ croak "name '$name' must map to a key id string, not a structure" if ref $id;
Branch: 1 branch
BranchTrueFalseTotal
if ref $id 1 47 48
1968 47 ▶ croak "name '$name' maps to an empty key id" unless defined($id) && length($id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 1 46 47
Condition66%2/3
defined $id and length $id
!ll&&!rl&&r
0146
MC/DC50%1/2
defined $id and length $id
defined $id length $id
Truth table66%2/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
1969 46 $key_names{$name} = $id;
1970 }
1971 }
1972  
1973 # Resolve a keys: entry's label through the names registry, if it is a known name; otherwise
1974 # it is taken to be a key id already. Two labels resolving to the same id is a config error,
1975 # not a silent last-wins -- it usually means a name and its own id were both listed.
1976 44 my %seen_id;
1977 67 ▶ my $resolve_key_id = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1978 67 my ($label) = @_;
1979 67 ▶ my $id = exists $key_names{$label} ? $key_names{$label} : $label;
Branch: 1 branch
BranchTrueFalseTotal
exists $key_names{$label} ? : 46 21 67
1980 croak "keys entry '$label' resolves to key id '$id', which another entry already claims"
1981 67 ▶ if $seen_id{$id}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen_id{$id}++ 1 66 67
1982 66 return $id;
1983 44 };
1984  
1985 44 my %key_policies;
1986 44 ▶ if (ref($cfg->{keys}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg->{"keys"} eq "HASH") 36 8 44
1987 36 for my $label (keys %{$cfg->{keys}}) {
1988 67 my $key = $resolve_key_id->($label);
1989 66 my $entry = $cfg->{keys}{$label};
1990  
1991 66 ▶ if (!ref($entry)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $entry) 20 46 66
1992 20 my $policy = $policies{$entry};
1993 20 ▶ croak "key '$label' references undefined policy '$entry'" unless $policy;
Branch: 1 branch
BranchTrueFalseTotal
unless $policy 1 19 20
1994 19 $key_policies{$key} = $policy;
1995 19 next;
1996 }
1997  
1998 46 ▶ croak "key '$label' must be a policy name or a hashref" unless ref($entry) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 0 46 46
1999  
2000 46 my $base = {};
2001 46 ▶ if (defined $entry->{policy} && length $entry->{policy}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $entry->{'policy'} and length $entry->{'policy'}) { } 25 21 46
elsif ($default) { } 21 0 21
Condition66%2/3
defined $entry->{"policy"} and length $entry->{"policy"}
!ll&&!rl&&r
21025
MC/DC50%1/2
defined $entry->{"policy"} and length $entry->{"policy"}
defined $entry->{"policy"} length $entry->{"policy"}
Truth table66%2/3
A and B
A= defined $entry->{"policy"}B= length $entry->{"policy"}
ABresult
0X0
100
111
2002 25 my $named = $policies{$entry->{policy}};
2003 25 ▶ croak "key '$label' references undefined policy '$entry->{policy}'" unless $named;
Branch: 1 branch
BranchTrueFalseTotal
unless $named 0 25 25
2004 25 $base = $named;
2005 } elsif ($default) {
2006 21 $base = $default;
2007 }
2008  
2009 # Overrides are sparse: an absent field keeps the profile's value, so "same as standard
2010 # but allowed to use cloud" is one line rather than a restated profile.
2011 46 ▶ my $overrides = ref($entry->{overrides}) eq 'HASH' ? $entry->{overrides} : $entry;
Branch: 1 branch
BranchTrueFalseTotal
ref $entry->{'overrides'} eq 'HASH' ? : 0 46 46
2012 my $merged = {
2013 name => ($base->{name} // ''),
2014 allow_models => (exists($overrides->{models}) || exists($overrides->{aliases})
2015 ? $self->resolve_policy($overrides)->{allow_models}
2016 : $base->{allow_models}),
2017 deny_tags => (exists($overrides->{deny_tags})
2018 ? $self->normalize_tags($overrides->{deny_tags})
2019 46 ▶ : ($base->{deny_tags} // [])),
Branch: 2 branches
BranchTrueFalseTotal
exists $overrides->{'models'} || exists $overrides->{'aliases'} ? : 2 44 46
exists $overrides->{'deny_tags'} ? : 2 44 46
Condition57%4/7
$base->{"name"} // ""
l!l
460
exists $overrides->{"models"} or exists $overrides->{"aliases"}
l!l&&r!l&&!r
2044
$base->{"deny_tags"} // []
l!l
440
MC/DC0%0/1
$base->{"name"} // ""
$base->{"name"}
MC/DC50%1/2
exists $overrides->{"models"} or exists $overrides->{"aliases"}
exists $overrides->{"models"} exists $overrides->{"aliases"}
MC/DC0%0/1
$base->{"deny_tags"} // []
$base->{"deny_tags"}
Truth table50%1/2
A
A= $base->{"name"}
Aresult
11
00
Truth table66%2/3
A or B
A= exists $overrides->{"models"}B= exists $overrides->{"aliases"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $base->{"deny_tags"}
Aresult
11
00
2020 };
2021 46 $key_policies{$key} = $intern->($merged);
2022 }
2023 }
2024  
2025 # Short key ids from before ADR 0016 still name their customer: a request's full id falls
2026 # back to its short prefix (see _configured_key_id). Where one key would match two entries --
2027 # a short id and a full id it is the prefix of -- which one governs is not for Skeid to guess.
2028 42 my %legacy = map { $_ => 1 } grep { _is_legacy_key_id($_) } keys %seen_id;
2029 42 for my $id (sort keys %seen_id) {
2030 64 ▶ next unless $id =~ /\Ak_[0-9a-f]{40}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\Ak_[0-9a-f]{40}\z/ 14 50 64
2031 50 my $short = substr($id, 0, 2 + $LEGACY_KEY_ID_HEX);
2032 croak "key id '$short' is the short form of '$id', and both have a keys entry: one key "
2033 . 'would match both; keep only the full id'
2034 50 ▶ if $legacy{$short};
Branch: 1 branch
BranchTrueFalseTotal
if $legacy{$short} 2 48 50
2035 }
2036 40 _warn_legacy_key_id($_) for sort(keys %legacy), grep { _is_legacy_key_id($_) } values %key_names;
2037  
2038 40 $self->policies(\%policies);
2039 40 $self->default_policy($default);
2040 40 $self->key_policies(\%key_policies);
2041 40 $self->key_names(\%key_names);
2042 40 return 1;
2043 }
2044  
2045 108 ▶sub _is_legacy_key_id {
Subroutine _is_legacy_key_id: called CC=3 SCAR=11.1
2046 108 my ($id) = @_;
2047 108 ▶ return defined($id) && $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/ ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $id && $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/ ? : 9 99 108
Condition66%2/3
defined $id and $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/
!ll&&!rl&&r
0999
MC/DC50%1/2
defined $id and $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/
defined $id $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/
Truth table66%2/3
A and B
A= defined $idB= $id =~ /\Ak_[0-9a-f]{$LEGACY_KEY_ID_HEX}\z/
ABresult
0X0
100
111
2048 }
2049  
2050 7 ▶sub _warn_legacy_key_id {
Subroutine _warn_legacy_key_id: called CC=2 SCAR=6.9
2051 7 my ($id) = @_;
2052 7 ▶ return if $legacy_key_id_warned{$id}++;
Branch: 1 branch
BranchTrueFalseTotal
if $legacy_key_id_warned{$id}++ 2 5 7
2053 5 warn "skeid: key id '$id' is a short key id from before ADR 0016; it still matches the key "
2054 . "whose full id starts with it, but is deprecated: replace it with the full id "
2055 . "`skeid keyid` prints\n";
2056 5 return;
2057 }
2058  
2059 # The id a customer's entry in a config table is filed under: the request's own id, or -- for
2060 # a config still written with short ids -- that id's short prefix. Exact wins, so a full id
2061 # entry is always what a full id finds.
2062 653 ▶sub _configured_key_id {
Subroutine _configured_key_id: called CC=6 SCAR=17.9
2063 653 my ($self, $table, $api_key_id) = @_;
2064 653 ▶ return undef unless defined($api_key_id) && length($api_key_id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_key_id and length $api_key_id 4 649 653
Condition66%2/3
defined $api_key_id and length $api_key_id
!ll&&!rl&&r
40649
MC/DC50%1/2
defined $api_key_id and length $api_key_id
defined $api_key_id length $api_key_id
Truth table66%2/3
A and B
A= defined $api_key_idB= length $api_key_id
ABresult
0X0
100
111
2065 649 ▶ return $api_key_id if exists $table->{$api_key_id};
Branch: 1 branch
BranchTrueFalseTotal
if exists $table->{$api_key_id} 106 543 649
2066 543 ▶ return undef unless $api_key_id =~ /\Ak_[0-9a-f]{40}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $api_key_id =~ /\Ak_[0-9a-f]{40}\z/ 306 237 543
2067 237 my $short = substr($api_key_id, 0, 2 + $LEGACY_KEY_ID_HEX);
2068 237 ▶ return exists $table->{$short} ? $short : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $table->{$short} ? : 5 232 237
2069 }
2070  
2071 121 ▶sub _policy_fingerprint {
Subroutine _policy_fingerprint: called CC=2 SCAR=6.9
2072 121 my ($self, $policy) = @_;
2073 121 ▶ my $models = defined($policy->{allow_models}) ? join(',', sort keys %{$policy->{allow_models}}) : '*';
Branch: 1 branch
BranchTrueFalseTotal
defined $policy->{'allow_models'} ? : 21 100 121
2074 121 return join("\0", $models, join(',', @{$policy->{deny_tags}}));
2075 }
2076  
2077  
2078 747 ▶sub key_id_for_key {
Subroutine key_id_for_key: called CC=3 SCAR=11.0
Pod documented
2079 747 my ($self, $api_key) = @_;
2080 747 ▶ return 'anonymous' unless defined($api_key) && length($api_key);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_key and length $api_key 401 346 747
Condition66%2/3
defined $api_key and length $api_key
!ll&&!rl&&r
0401346
MC/DC50%1/2
defined $api_key and length $api_key
defined $api_key length $api_key
Truth table66%2/3
A and B
A= defined $api_keyB= length $api_key
ABresult
0X0
100
111
2081 346 return 'k_' . sha1_hex($api_key);
2082 }
2083  
2084  
2085 636 ▶sub policy_for_key {
Subroutine policy_for_key: called CC=3 SCAR=11.0
Pod documented
2086 636 my ($self, $api_key_id) = @_;
2087 636 my $id = $self->_configured_key_id($self->key_policies, $api_key_id);
2088 636 ▶ return $self->key_policies->{$id} if defined($id) && $self->key_policies->{$id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $id and $self->key_policies->{$id} 97 539 636
Condition66%2/3
defined $id and $self->key_policies->{$id}
!ll&&!rl&&r
539097
MC/DC50%1/2
defined $id and $self->key_policies->{$id}
defined $id $self->key_policies->{$id}
Truth table66%2/3
A and B
A= defined $idB= $self->key_policies->{$id}
ABresult
0X0
100
111
2089 539 return $self->default_policy;
2090 }
2091  
2092  
2093 2 ▶sub key_id_for_name {
Subroutine key_id_for_name: called CC=3 SCAR=12.5
Pod documented
2094 2 my ($self, $name) = @_;
2095 2 ▶ return undef unless defined($name) && length($name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 2 2
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
002
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
2096 2 return $self->key_names->{$name};
2097 }
2098  
2099  
2100 602 ▶sub route_plan {
Subroutine route_plan: called CC=13 SCAR=25.8
Pod documented
2101 602 my ($self, %args) = @_;
2102 602 ▶ my $model = $args{model} // '';
Condition50%1/2
$args{"model"} // ""
l!l
6020
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
2103 602 my $policy = $self->policy_for_key($args{api_key_id});
2104 602 ▶ my $deny = $policy ? $policy->{deny_tags} : [];
Branch: 1 branch
BranchTrueFalseTotal
$policy ? : 157 445 602
2105  
2106 602 ▶ if ($policy && $policy->{allow_models} && !$policy->{allow_models}{$model}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($policy and $policy->{"allow_models"} and not $policy->{"allow_models"}{$model}) 16 586 602
Condition100%6/6
$policy and $policy->{"allow_models"} and not $policy->{"allow_models"}{$model}
!ll&&!rl&&r
5117516
$policy and $policy->{"allow_models"}
!ll&&!rl&&r
4456691
MC/DC100%3/3
$policy and $policy->{"allow_models"} and not $policy->{"allow_models"}{$model}
$policy $policy->{"allow_models"} not $policy->{"allow_models"}{$model}
Truth table100%4/4
A and B and not(C)
A= $policyB= $policy->{"allow_models"}C= not $policy->{"allow_models"}{$model}
ABCresult
0XX0
10X0
1100
1111
2107 16 return { tiers => [], permitted => 0, reason => 'model_not_permitted' };
2108 }
2109  
2110 586 my $alias = $self->model_aliases->{$model};
2111 my @tiers = $alias
2112 64 ▶ ? (map { +{ %$_, deny_tags => $deny } } @{$alias->{tiers}})
Condition50%2/4
$args{"engine"} // ""
l!l
0533
$self->route_wait_timeout_ms // 0
l!l
5330
MC/DC0%0/1
$args{"engine"} // ""
$args{"engine"}
MC/DC0%0/1
$self->route_wait_timeout_ms // 0
$self->route_wait_timeout_ms
Truth table50%1/2
A
A= $args{"engine"}
Aresult
11
00
Truth table50%1/2
A
A= $self->route_wait_timeout_ms
Aresult
11
00
2113 : ({
2114 tags => [],
2115 model => $model,
2116 586 ▶ engine => $self->normalize_engine_id($args{engine} // ''),
Branch: 1 branch
BranchTrueFalseTotal
$alias ? : 53 533 586
2117 wait_ms => 0 + ($self->route_wait_timeout_ms // 0),
2118 deny_tags => $deny,
2119 });
2120  
2121 586 my $before = scalar @tiers;
2122 586 ▶ if (@$deny) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$deny) 91 495 586
2123 91 my %denied = map { $_ => 1 } @$deny;
2124 @tiers = grep {
2125 91 my $tier = $_;
2126 95 ▶ !grep { $denied{$_} } @{$tier->{tags} || []};
Condition50%1/2
$tier->{'tags'} || []
l!l
950
MC/DC0%0/1
$tier->{'tags'} || []
$tier->{'tags'}
Truth table50%1/2
A
A= $tier->{'tags'}
Aresult
11
00
2127 } @tiers;
2128 }
2129  
2130 586 ▶ return { tiers => [], permitted => 0, reason => 'all_tiers_denied' }
Branch: 1 branch
BranchTrueFalseTotal
if $before and not @tiers 4 582 586
Condition66%2/3
$before and not @tiers
!ll&&!rl&&r
05824
MC/DC50%1/2
$before and not @tiers
$before not @tiers
Truth table66%2/3
A and not(B)
A= $beforeB= not @tiers
ABresult
0X0
100
111
2131 if $before && !@tiers;
2132  
2133 582 return { tiers => \@tiers, permitted => 1, reason => '' };
2134 }
2135  
2136  
2137 54 ▶sub select_nodes {
Subroutine select_nodes: called CC=3 SCAR=11.0
Pod documented
2138 54 my ($self, %args) = @_;
2139 54 my $tags = $self->normalize_tags($args{tags});
2140 54 my $deny = $self->normalize_tags($args{deny_tags});
2141 return [
2142 83 map { +{%$_} }
2143 112 ▶ grep { $self->_node_has_tags($_, $tags) && !$self->_node_has_any_tag($_, $deny) }
Condition100%3/3
$self->_node_has_tags($_, $tags) && !$self->_node_has_any_tag($_, $deny)
!ll&&!rl&&r
27283
MC/DC100%2/2
$self->_node_has_tags($_, $tags) && !$self->_node_has_any_tag($_, $deny)
$self->_node_has_tags($_, $tags) !$self->_node_has_any_tag($_, $deny)
Truth table100%3/3
A && not(B)
A= $self->_node_has_tags($_, $tags)B= !$self->_node_has_any_tag($_, $deny)
ABresult
0X0
100
111
2144 54 ▶ @{$self->nodes || []}
Condition50%1/2
$self->nodes || []
l!l
540
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
2145 ];
2146 }
2147  
2148  
2149 1065 ▶sub pick_node {
Subroutine pick_node: called CC=10 SCAR=23.0
Pod documented
2150 1065 my ($self, %args) = @_;
2151 1065 my $entry = $self->_route_entry(%args);
2152 1065 my @nodes = @{$entry->{nodes}};
2153 1065 ▶ return unless @nodes;
Branch: 1 branch
BranchTrueFalseTotal
unless @nodes 4 1061 1065
2154  
2155 1061 my @weights = @{$entry->{weights}};
2156 1061 my $total_weight = $entry->{total_weight};
2157 1061 ▶ return unless $total_weight > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $total_weight > 0 0 1061 1061
2158  
2159 1061 my $key = $self->_route_key(%args);
2160 1061 ▶ my $cursor = 0 + ($self->_rr_cursor->{$key} // 0);
Condition100%2/2
$self->_rr_cursor->{$key} // 0
l!l
244817
MC/DC100%1/1
$self->_rr_cursor->{$key} // 0
$self->_rr_cursor->{$key}
Truth table100%2/2
A
A= $self->_rr_cursor->{$key}
Aresult
11
00
2161 1061 $cursor %= $total_weight;
2162  
2163 # Locate the weighted range containing the cursor without expanding weights into slots. From
2164 # that owner onward, the old slot walk considered nodes in inventory order and, if none admitted
2165 # before the end, wrapped to target zero. Admission is one per-node observation for this
2166 # synchronous selection pass; resampling it once per weight slot describes no new capacity.
2167 # Check each node once and skip the rest of every saturated weight range.
2168 1061 my ($owner, $range_end) = (0, 0);
2169 1061 for my $idx (0 .. $#nodes) {
2170 1077 $range_end += $weights[$idx];
2171 1077 ▶ if ($cursor < $range_end) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cursor < $range_end) 1061 16 1077
2172 1061 $owner = $idx;
2173 1061 last;
2174 }
2175 }
2176  
2177 1061 for my $offset (0 .. $#nodes) {
2178 1071 my $idx = ($owner + $offset) % @nodes;
2179 1071 my $candidate = $nodes[$idx];
2180 1071 ▶ next unless $self->_node_can_take($candidate);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_node_can_take($candidate) 164 907 1071
2181  
2182 # Before a wrap, the historical cursor advances one weighted slot even when a later node was
2183 # selected because the owning range was saturated. After a wrap, the first target examined is
2184 # slot zero, so its successor is slot one. Keeping both cases preserves partial-saturation
2185 # ordering while avoiding one admission check per skipped slot.
2186 907 ▶ $self->_rr_cursor->{$key} = $idx < $owner
Branch: 1 branch
BranchTrueFalseTotal
$idx < $owner ? : 6 901 907
2187 ? (1 % $total_weight)
2188 : (($cursor + 1) % $total_weight);
2189 907 my $id = $candidate->{id};
2190 907 ▶ my $inflight = 0 + ($self->_inflight->{$id} // 0);
Condition100%2/2
$self->_inflight->{$id} // 0
l!l
150757
MC/DC100%1/1
$self->_inflight->{$id} // 0
$self->_inflight->{$id}
Truth table100%2/2
A
A= $self->_inflight->{$id}
Aresult
11
00
2191 return {
2192 907 %$candidate,
2193 inflight => $inflight,
2194 route_key => $key,
2195 };
2196 }
2197  
2198 154 return;
2199 }
2200  
2201  
2202 1076 ▶sub route_state {
Subroutine route_state: called CC=5 SCAR=16.1
Pod documented
2203 1076 my ($self, %args) = @_;
2204 1076 ▶ my $engine = $self->normalize_engine_id($args{engine} // '');
Condition100%2/2
$args{"engine"} // ""
l!l
647429
MC/DC100%1/1
$args{"engine"} // ""
$args{"engine"}
Truth table100%2/2
A
A= $args{"engine"}
Aresult
11
00
2205 1076 my $eligible = $self->_eligible_nodes(%args);
2206 1076 my $available = [ grep { $self->_node_can_take($_) } @$eligible ];
2207  
2208 return {
2209 model => ($args{model} // ''),
2210 engine => $engine,
2211 tags => $self->normalize_tags($args{tags}),
2212 1076 ▶ deny_tags => $self->normalize_tags($args{deny_tags}),
Branch: 2 branches
BranchTrueFalseTotal
@$eligible ? : 653 423 1076
@$available ? : 488 588 1076
Condition50%1/2
$args{"model"} // ""
l!l
10760
MC/DC0%0/1
$args{"model"} // ""
$args{"model"}
Truth table50%1/2
A
A= $args{"model"}
Aresult
11
00
2213 eligible_count => scalar(@$eligible),
2214 available_count => scalar(@$available),
2215 has_eligible => @$eligible ? 1 : 0,
2216 has_available => @$available ? 1 : 0,
2217 };
2218 }
2219  
2220  
2221 90 ▶sub set_capacity_reading {
Subroutine set_capacity_reading: called CC=26 SCAR=33.2
Pod documented
2222 90 my ($self, $node_id, %reading) = @_;
2223 90 ▶ croak 'node_id required' unless defined $node_id && length $node_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 90 90
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
0090
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
2224  
2225 90 my $now = time;
2226 my $entry = {
2227 source => ((defined($reading{source}) && length($reading{source})) ? "$reading{source}" : 'custom'),
2228 used => (defined $reading{used} ? 0 + $reading{used} : undef),
2229 limit => (defined $reading{limit} ? 0 + $reading{limit} : undef),
2230 at => (defined $reading{at} ? 0 + $reading{at} : $now),
2231 # Which of a provider's several quotas this reading is about, when it had more than one.
2232 # For reports only -- admission just sees used and limit.
2233 (defined $reading{quota} ? (quota => "$reading{quota}") : ()),
2234 (defined $reading{expires_at} ? (expires_at => 0 + $reading{expires_at}) : ()),
2235 # How often this source reports; it sets how long this reading holds a looser one off.
2236 ((defined($reading{interval_ms}) && $reading{interval_ms} > 0)
2237 90 ▶ ? (interval_ms => 0 + $reading{interval_ms}) : ()),
Branch: 7 branches
BranchTrueFalseTotal
defined $reading{'source'} && length $reading{'source'} ? : 86 4 90
defined $reading{'used'} ? : 78 12 90
defined $reading{'limit'} ? : 78 12 90
defined $reading{'at'} ? : 22 68 90
defined $reading{'quota'} ? : 13 77 90
defined $reading{'expires_at'} ? : 20 70 90
defined $reading{'interval_ms'} && $reading{'interval_ms'} > 0 ? : 31 59 90
Condition66%4/6
defined $reading{"source"} and length $reading{"source"}
!ll&&!rl&&r
4086
defined $reading{"interval_ms"} and $reading{"interval_ms"} > 0
!ll&&!rl&&r
59031
MC/DC50%1/2
defined $reading{"source"} and length $reading{"source"}
defined $reading{"source"} length $reading{"source"}
MC/DC50%1/2
defined $reading{"interval_ms"} and $reading{"interval_ms"} > 0
defined $reading{"interval_ms"} $reading{"interval_ms"} > 0
Truth table66%2/3
A and B
A= defined $reading{"source"}B= length $reading{"source"}
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= defined $reading{"interval_ms"}B= $reading{"interval_ms"} > 0
ABresult
0X0
100
111
2238 };
2239  
2240 90 ▶ if (defined $reading{retry_after_ms} && $reading{retry_after_ms} > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $reading{'retry_after_ms'} and $reading{'retry_after_ms'} > 0) { } 12 78 90
elsif (defined $reading{'retry_after'}) { } 0 78 78
Condition66%2/3
defined $reading{"retry_after_ms"} and $reading{"retry_after_ms"} > 0
!ll&&!rl&&r
78012
MC/DC50%1/2
defined $reading{"retry_after_ms"} and $reading{"retry_after_ms"} > 0
defined $reading{"retry_after_ms"} $reading{"retry_after_ms"} > 0
Truth table66%2/3
A and B
A= defined $reading{"retry_after_ms"}B= $reading{"retry_after_ms"} > 0
ABresult
0X0
100
111
2241 12 $entry->{retry_after} = $now + ($reading{retry_after_ms} / 1000);
2242 } elsif (defined $reading{retry_after}) {
2243 0 $entry->{retry_after} = 0 + $reading{retry_after};
2244 }
2245  
2246 # Two sources disagreeing about one node: the tighter one decides while it is current.
2247 # Taking the latest instead would let whichever probe polls last lift what the other just
2248 # said. But "tighter" alone lets a reading nobody refreshes -- a passive rate-limit reading
2249 # from the last response before traffic stopped -- block a probe that says the node is empty,
2250 # for as long as capacity_max_age_ms allows (forever with 0). So only a pending backoff, or a
2251 # reading younger than the longer of the two sources' poll intervals, holds the incoming one
2252 # off: within that window neither source has had a full poll since, and the tighter one is
2253 # the safer view of the same moment. Two passive readings (no interval) never hold.
2254 90 my $current = $self->capacity_reading($node_id);
2255 90 ▶ if ($current && $current->{source} ne $entry->{source}
Branch: 1 branch
BranchTrueFalseTotal
if ($current and $current->{"source"} ne $entry->{"source"} and _reading_tightness($current) > _reading_tightness($entry)) 9 81 90
Condition100%6/6
$current and $current->{"source"} ne $entry->{"source"} and _reading_tightness($current) > _reading_tightness($entry)
!ll&&!rl&&r
7749
$current and $current->{"source"} ne $entry->{"source"}
!ll&&!rl&&r
522513
MC/DC100%3/3
$current and $current->{"source"} ne $entry->{"source"} and _reading_tightness($current) > _reading_tightness($entry)
$current $current->{"source"} ne $entry->{"source"} _reading_tightness($current) > _reading_tightness($entry)
Truth table100%4/4
A and B and C
A= $currentB= $current->{"source"} ne $entry->{"source"}C= _reading_tightness($current) > _reading_tightness($entry)
ABCresult
0XX0
10X0
1100
1111
2256 && _reading_tightness($current) > _reading_tightness($entry)) {
2257 9 ▶ my $backoff_pending = ($current->{retry_after} && time < $current->{retry_after}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$current->{'retry_after'} && time < $current->{'retry_after'} ? : 2 7 9
Condition66%2/3
$current->{"retry_after"} and time < $current->{"retry_after"}
!ll&&!rl&&r
702
MC/DC50%1/2
$current->{"retry_after"} and time < $current->{"retry_after"}
$current->{"retry_after"} time < $current->{"retry_after"}
Truth table66%2/3
A and B
A= $current->{"retry_after"}B= time < $current->{"retry_after"}
ABresult
0X0
100
111
2258 9 ▶ my ($cur_ms, $new_ms) = (($current->{interval_ms} // 0), ($entry->{interval_ms} // 0));
Condition100%4/4
$current->{"interval_ms"} // 0
l!l
45
$entry->{"interval_ms"} // 0
l!l
63
MC/DC100%1/1
$current->{"interval_ms"} // 0
$current->{"interval_ms"}
MC/DC100%1/1
$entry->{"interval_ms"} // 0
$entry->{"interval_ms"}
Truth table100%2/2
A
A= $current->{"interval_ms"}
Aresult
11
00
Truth table100%2/2
A
A= $entry->{"interval_ms"}
Aresult
11
00
2259 9 ▶ my $hold_s = ($cur_ms > $new_ms ? $cur_ms : $new_ms) / 1000;
Branch: 1 branch
BranchTrueFalseTotal
$cur_ms > $new_ms ? : 4 5 9
2260 9 ▶ my $age = Time::HiRes::time() - ($current->{at} // 0);
Condition50%1/2
$current->{"at"} // 0
l!l
90
MC/DC0%0/1
$current->{"at"} // 0
$current->{"at"}
Truth table50%1/2
A
A= $current->{"at"}
Aresult
11
00
2261 9 ▶ return $current if $backoff_pending || $age < $hold_s;
Branch: 1 branch
BranchTrueFalseTotal
if $backoff_pending or $age < $hold_s 6 3 9
Condition100%3/3
$backoff_pending or $age < $hold_s
l!l&&r!l&&!r
243
MC/DC100%2/2
$backoff_pending or $age < $hold_s
$backoff_pending $age < $hold_s
Truth table100%3/3
A or B
A= $backoff_pendingB= $age < $hold_s
ABresult
1X1
011
000
2262 }
2263  
2264 84 $self->_capacity->{$node_id} = $entry;
2265 84 return $entry;
2266 }
2267  
2268 # How much a reading holds admission back: a pending backoff above everything, then the used
2269 # fraction, then nothing for a reading without a limit.
2270 26 ▶sub _reading_tightness {
Subroutine _reading_tightness: called CC=6 SCAR=18.8
2271 26 my ($reading) = @_;
2272 26 ▶ return 9**9**9 if $reading->{retry_after} && time < $reading->{retry_after};
Branch: 1 branch
BranchTrueFalseTotal
if $reading->{"retry_after"} and time < $reading->{"retry_after"} 4 22 26
Condition66%2/3
$reading->{"retry_after"} and time < $reading->{"retry_after"}
!ll&&!rl&&r
2204
MC/DC50%1/2
$reading->{"retry_after"} and time < $reading->{"retry_after"}
$reading->{"retry_after"} time < $reading->{"retry_after"}
Truth table66%2/3
A and B
A= $reading->{"retry_after"}B= time < $reading->{"retry_after"}
ABresult
0X0
100
111
2273 22 ▶ my $limit = 0 + ($reading->{limit} // 0);
Condition50%1/2
$reading->{"limit"} // 0
l!l
220
MC/DC0%0/1
$reading->{"limit"} // 0
$reading->{"limit"}
Truth table50%1/2
A
A= $reading->{"limit"}
Aresult
11
00
2274 22 ▶ return 0 if $limit <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $limit <= 0 0 22 22
2275 22 ▶ return (0 + ($reading->{used} // 0)) / $limit;
Condition50%1/2
$reading->{"used"} // 0
l!l
220
MC/DC0%0/1
$reading->{"used"} // 0
$reading->{"used"}
Truth table50%1/2
A
A= $reading->{"used"}
Aresult
11
00
2276 }
2277  
2278  
2279 2367 ▶sub capacity_reading {
Subroutine capacity_reading: called CC=14 SCAR=26.7
Pod documented
2280 2367 my ($self, $node_id) = @_;
2281 2367 ▶ return unless defined($node_id) && length($node_id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 2367 2367
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
002367
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
2282 2367 ▶ my $entry = $self->_capacity->{$node_id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $entry = $self->_capacity->{$node_id} or return 223 2144 2367
2283  
2284 223 ▶ my $backoff_pending = ($entry->{retry_after} && time < $entry->{retry_after}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$entry->{'retry_after'} && time < $entry->{'retry_after'} ? : 59 164 223
Condition66%2/3
$entry->{"retry_after"} and time < $entry->{"retry_after"}
!ll&&!rl&&r
164059
MC/DC50%1/2
$entry->{"retry_after"} and time < $entry->{"retry_after"}
$entry->{"retry_after"} time < $entry->{"retry_after"}
Truth table66%2/3
A and B
A= $entry->{"retry_after"}B= time < $entry->{"retry_after"}
ABresult
0X0
100
111
2285 223 ▶ my $max_age = 0 + ($self->capacity_max_age_ms // 0);
Condition50%1/2
$self->capacity_max_age_ms // 0
l!l
2230
MC/DC0%0/1
$self->capacity_max_age_ms // 0
$self->capacity_max_age_ms
Truth table50%1/2
A
A= $self->capacity_max_age_ms
Aresult
11
00
2286 223 ▶ if (!$backoff_pending && $max_age > 0 && (time - ($entry->{at} // 0)) > ($max_age / 1000)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $backoff_pending and $max_age > 0 and time - ($entry->{"at"} // 0) > $max_age / 1000) 1 222 223
Condition87%7/8
not $backoff_pending and $max_age > 0 and time - ($entry->{"at"} // 0) > $max_age / 1000
!ll&&!rl&&r
711511
not $backoff_pending and $max_age > 0
!ll&&!rl&&r
5912152
$entry->{"at"} // 0
l!l
1520
MC/DC100%3/3
not $backoff_pending and $max_age > 0 and time - ($entry->{"at"} // 0) > $max_age / 1000
not $backoff_pending $max_age > 0 time - ($entry->{"at"} // 0) > $max_age / 1000
MC/DC0%0/1
$entry->{"at"} // 0
$entry->{"at"}
Truth table100%4/4
not(A) and B and C
A= not $backoff_pendingB= $max_age > 0C= time - ($entry->{"at"} // 0) > $max_age / 1000
ABCresult
0XX0
10X0
1100
1111
Truth table50%1/2
A
A= $entry->{"at"}
Aresult
11
00
2287 1 delete $self->_capacity->{$node_id};
2288 1 return;
2289 }
2290 # A reading that said how long it may be believed is not believed longer (ADR 0017).
2291 222 ▶ if (!$backoff_pending && defined($entry->{expires_at}) && Time::HiRes::time() > $entry->{expires_at}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $backoff_pending and defined $entry->{"expires_at"} and &Time::HiRes::time() > $entry->{"expires_at"}) 1 221 222
Condition100%6/6
not $backoff_pending and defined $entry->{"expires_at"} and &Time::HiRes::time() > $entry->{"expires_at"}
!ll&&!rl&&r
169521
not $backoff_pending and defined $entry->{"expires_at"}
!ll&&!rl&&r
5911053
MC/DC100%3/3
not $backoff_pending and defined $entry->{"expires_at"} and &Time::HiRes::time() > $entry->{"expires_at"}
not $backoff_pending defined $entry->{"expires_at"} &Time::HiRes::time() > $entry->{"expires_at"}
Truth table100%4/4
not(A) and B and C
A= not $backoff_pendingB= defined $entry->{"expires_at"}C= &Time::HiRes::time() > $entry->{"expires_at"}
ABCresult
0XX0
10X0
1100
1111
2292 1 delete $self->_capacity->{$node_id};
2293 1 return;
2294 }
2295 221 return $entry;
2296 }
2297  
2298  
2299 66 ▶sub forget_capacity {
Subroutine forget_capacity: called CC=7 SCAR=21.1
Pod documented
2300 66 my ($self, $node_id, %args) = @_;
2301 66 ▶ if (defined($node_id) && length($node_id)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $node_id and length $node_id) 66 0 66
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
0066
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
2302 66 ▶ if (defined $args{source}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"source"}) 25 41 66
2303 25 my $entry = $self->_capacity->{$node_id};
2304 25 ▶ return 0 unless $entry && ($entry->{source} // '') eq $args{source};
Branch: 1 branch
BranchTrueFalseTotal
unless $entry and ($entry->{"source"} // "") eq $args{"source"} 17 8 25
Condition80%4/5
$entry and ($entry->{"source"} // "") eq $args{"source"}
!ll&&!rl&&r
1168
$entry->{"source"} // ""
l!l
140
MC/DC50%1/2
$entry and ($entry->{"source"} // "") eq $args{"source"}
$entry $entry->{"source"}
Truth table66%2/3
A and B
A= $entryB= $entry->{"source"}
ABresult
0X0
100
111
2305 }
2306 49 delete $self->_capacity->{$node_id};
2307 49 return 1;
2308 }
2309 0 %{$self->_capacity} = ();
2310 0 return 1;
2311 }
2312  
2313 # Rate-limit headers, in the spellings the big providers actually use. Ordered: the first one
2314 # present wins, so a provider sending several does not get read twice.
2315 # Providers meter more than one thing at once, and for an LLM API the token budget is usually
2316 # what runs out first -- a node with requests to spare and no tokens left answers 429 all the
2317 # same. Each quota is read separately and the tightest one decides.
2318 #
2319 # Within a quota the order is "most specific first": the first name present wins, so a provider
2320 # sending both a specific and a generic spelling is not counted twice.
2321 67 my @RATELIMIT_QUOTAS = (
2322 {
2323 name => 'requests',
2324 remaining => [qw(
2325 x-ratelimit-remaining-requests
2326 anthropic-ratelimit-requests-remaining
2327 x-ratelimit-remaining
2328 ratelimit-remaining
2329 )],
2330 limit => [qw(
2331 x-ratelimit-limit-requests
2332 anthropic-ratelimit-requests-limit
2333 x-ratelimit-limit
2334 ratelimit-limit
2335 )],
2336 },
2337 {
2338 name => 'tokens',
2339 remaining => [qw(
2340 x-ratelimit-remaining-tokens
2341 anthropic-ratelimit-tokens-remaining
2342 anthropic-ratelimit-input-tokens-remaining
2343 )],
2344 limit => [qw(
2345 x-ratelimit-limit-tokens
2346 anthropic-ratelimit-tokens-limit
2347 anthropic-ratelimit-input-tokens-limit
2348 )],
2349 },
2350 );
2351  
2352  
2353 47 ▶sub capacity_header_names {
Subroutine capacity_header_names: called CC=1 SCAR=0.0
Pod documented
2354 47 return ((map { @{$_->{remaining}}, @{$_->{limit}} } @RATELIMIT_QUOTAS), 'retry-after');
2355 }
2356  
2357  
2358 27 ▶sub observe_response_headers {
Subroutine observe_response_headers: called CC=22 SCAR=31.9
Pod documented
2359 27 my ($self, $node_id, $headers, %args) = @_;
2360 27 ▶ return unless defined($node_id) && length($node_id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 27 27
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
0027
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
2361 27 ▶ return unless ref($headers) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $headers eq "HASH" 0 27 27
2362  
2363 # Case-insensitive: header casing is not something a provider promises.
2364 27 my %h = map { lc($_) => $headers->{$_} } keys %$headers;
2365 27 my %reading = (source => 'ratelimit');
2366 27 my $useful = 0;
2367  
2368 # The tightest quota wins, compared as a fraction because requests and tokens are not the
2369 # same unit. Reporting the roomier one would admit a request the provider is about to refuse.
2370 27 my $tightest = -1;
2371 27 for my $quota (@RATELIMIT_QUOTAS) {
2372 54 my ($remaining) = grep { defined } map { $h{$_} } @{$quota->{remaining}};
2373 54 ▶ next unless defined($remaining) && $remaining =~ /^\s*(\d+)/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $remaining and $remaining =~ /^\s*(\d+)/ 38 16 54
Condition66%2/3
defined $remaining and $remaining =~ /^\s*(\d+)/
!ll&&!rl&&r
38016
MC/DC50%1/2
defined $remaining and $remaining =~ /^\s*(\d+)/
defined $remaining $remaining =~ /^\s*(\d+)/
Truth table66%2/3
A and B
A= defined $remainingB= $remaining =~ /^\s*(\d+)/
ABresult
0X0
100
111
2374 16 my $left = 0 + $1;
2375  
2376 16 my ($limit) = grep { defined } map { $h{$_} } @{$quota->{limit}};
2377 # The probe contract counts what is used, not what is left; a limit we were not told is
2378 # reconstructed as "one more than we have", which is enough to stop admitting at zero.
2379 16 ▶ my $total = (defined($limit) && $limit =~ /^\s*(\d+)/) ? 0 + $1 : $left + 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $limit && $limit =~ /^\s*(\d+)/ ? : 13 3 16
Condition66%2/3
defined $limit and $limit =~ /^\s*(\d+)/
!ll&&!rl&&r
3013
MC/DC50%1/2
defined $limit and $limit =~ /^\s*(\d+)/
defined $limit $limit =~ /^\s*(\d+)/
Truth table66%2/3
A and B
A= defined $limitB= $limit =~ /^\s*(\d+)/
ABresult
0X0
100
111
2380 16 ▶ next unless $total > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $total > 0 0 16 16
2381  
2382 16 my $used = $total - $left;
2383 16 ▶ $used = $total if $used > $total;
Branch: 1 branch
BranchTrueFalseTotal
if $used > $total 0 16 16
2384 16 ▶ $used = 0 if $used < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $used < 0 0 16 16
2385  
2386 16 my $fraction = $used / $total;
2387 16 ▶ next unless $fraction > $tightest;
Branch: 1 branch
BranchTrueFalseTotal
unless $fraction > $tightest 1 15 16
2388 15 $tightest = $fraction;
2389 15 $reading{limit} = $total;
2390 15 $reading{used} = $used;
2391 15 $reading{quota} = $quota->{name};
2392 15 $useful = 1;
2393 }
2394  
2395 27 my $retry = $h{'retry-after'};
2396 27 ▶ my $status = 0 + ($args{status} // 0);
Condition100%2/2
$args{"status"} // 0
l!l
1413
MC/DC100%1/1
$args{"status"} // 0
$args{"status"}
Truth table100%2/2
A
A= $args{"status"}
Aresult
11
00
2397 27 ▶ if ($status == 429 || defined $retry) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status == 429 or defined $retry) 11 16 27
Condition66%2/3
$status == 429 or defined $retry
l!l&&r!l&&!r
11016
MC/DC50%1/2
$status == 429 or defined $retry
$status == 429 defined $retry
Truth table66%2/3
A or B
A= $status == 429B= defined $retry
ABresult
1X1
011
000
2398 11 my $secs;
2399 11 ▶ if (defined($retry) && $retry =~ /^\s*([\d.]+)\s*$/) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $retry and $retry =~ /^\s*([\d.]+)\s*$/) { } 8 3 11
elsif ($status == 429) { } 3 0 3
Condition66%2/3
defined $retry and $retry =~ /^\s*([\d.]+)\s*$/
!ll&&!rl&&r
308
MC/DC50%1/2
defined $retry and $retry =~ /^\s*([\d.]+)\s*$/
defined $retry $retry =~ /^\s*([\d.]+)\s*$/
Truth table66%2/3
A and B
A= defined $retryB= $retry =~ /^\s*([\d.]+)\s*$/
ABresult
0X0
100
111
2400 8 $secs = 0 + $1;
2401 } elsif ($status == 429) {
2402 # A 429 with no Retry-After still means "not now". One second is short enough not to
2403 # strand capacity and long enough to stop hammering.
2404 3 $secs = 1;
2405 }
2406 11 ▶ if (defined $secs && $secs > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $secs and $secs > 0) 11 0 11
Condition33%1/3
defined $secs and $secs > 0
!ll&&!rl&&r
0011
MC/DC0%0/2
defined $secs and $secs > 0
defined $secs $secs > 0
Truth table33%1/3
A and B
A= defined $secsB= $secs > 0
ABresult
0X0
100
111
2407 11 $reading{retry_after_ms} = $secs * 1000;
2408 11 $useful = 1;
2409 }
2410 }
2411  
2412 27 ▶ return unless $useful;
Branch: 1 branch
BranchTrueFalseTotal
unless $useful 3 24 27
2413 24 return $self->set_capacity_reading($node_id, %reading);
2414 }
2415  
2416  
2417 525 ▶sub start_request {
Subroutine start_request: called CC=8 SCAR=21.4
Pod documented
2418 525 my ($self, $node_id) = @_;
2419 525 ▶ croak 'node_id required' unless defined $node_id && length $node_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 525 525
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
00525
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
2420 525 ▶ my $node = (grep { ($_->{id} // '') eq $node_id } @{$self->nodes})[0];
Condition50%1/2
$_->{"id"} // ""
l!l
15980
MC/DC0%0/1
$_->{"id"} // ""
$_->{"id"}
Truth table50%1/2
A
A= $_->{"id"}
Aresult
11
00
2421 525 ▶ return 0 unless $node && $self->_node_can_take($node);
Branch: 1 branch
BranchTrueFalseTotal
unless $node and $self->_node_can_take($node) 6 519 525
Condition66%2/3
$node and $self->_node_can_take($node)
!ll&&!rl&&r
06519
MC/DC50%1/2
$node and $self->_node_can_take($node)
$node $self->_node_can_take($node)
Truth table66%2/3
A and B
A= $nodeB= $self->_node_can_take($node)
ABresult
0X0
100
111
2422  
2423 519 ▶ $self->_inflight->{$node_id} = 1 + ($self->_inflight->{$node_id} // 0);
Condition100%2/2
$self->_inflight->{$node_id} // 0
l!l
175344
MC/DC100%1/1
$self->_inflight->{$node_id} // 0
$self->_inflight->{$node_id}
Truth table100%2/2
A
A= $self->_inflight->{$node_id}
Aresult
11
00
2424 519 ▶ $self->_stats->{$node_id}{started} = 1 + ($self->_stats->{$node_id}{started} // 0);
Condition100%2/2
$self->_stats->{$node_id}{"started"} // 0
l!l
175344
MC/DC100%1/1
$self->_stats->{$node_id}{"started"} // 0
$self->_stats->{$node_id}{"started"}
Truth table100%2/2
A
A= $self->_stats->{$node_id}{"started"}
Aresult
11
00
2425 519 return 1;
2426 }
2427  
2428  
2429 511 ▶sub finish_request {
Subroutine finish_request: called CC=12 SCAR=25.3
Pod documented
2430 511 my ($self, $node_id, %args) = @_;
2431 511 ▶ croak 'node_id required' unless defined $node_id && length $node_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node_id and length $node_id 0 511 511
Condition33%1/3
defined $node_id and length $node_id
!ll&&!rl&&r
00511
MC/DC0%0/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table33%1/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
2432 511 ▶ my $cur = 0 + ($self->_inflight->{$node_id} // 0);
Condition50%1/2
$self->_inflight->{$node_id} // 0
l!l
5110
MC/DC0%0/1
$self->_inflight->{$node_id} // 0
$self->_inflight->{$node_id}
Truth table50%1/2
A
A= $self->_inflight->{$node_id}
Aresult
11
00
2433 511 $cur--;
2434 511 ▶ $cur = 0 if $cur < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cur < 0 0 511 511
2435 511 $self->_inflight->{$node_id} = $cur;
2436  
2437 511 ▶ if ($args{aborted}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'aborted'}) { } 9 502 511
elsif ($args{'ok'}) { } 375 127 502
2438 # The client left. The node did nothing wrong: not an error, not a failure in the window.
2439 9 ▶ $self->_stats->{$node_id}{aborted} = 1 + ($self->_stats->{$node_id}{aborted} // 0);
Condition50%1/2
$self->_stats->{$node_id}{"aborted"} // 0
l!l
09
MC/DC0%0/1
$self->_stats->{$node_id}{"aborted"} // 0
$self->_stats->{$node_id}{"aborted"}
Truth table50%1/2
A
A= $self->_stats->{$node_id}{"aborted"}
Aresult
11
00
2440 } elsif ($args{ok}) {
2441 375 ▶ $self->_stats->{$node_id}{ok} = 1 + ($self->_stats->{$node_id}{ok} // 0);
Condition100%2/2
$self->_stats->{$node_id}{"ok"} // 0
l!l
129246
MC/DC100%1/1
$self->_stats->{$node_id}{"ok"} // 0
$self->_stats->{$node_id}{"ok"}
Truth table100%2/2
A
A= $self->_stats->{$node_id}{"ok"}
Aresult
11
00
2442 } else {
2443 127 ▶ $self->_stats->{$node_id}{error} = 1 + ($self->_stats->{$node_id}{error} // 0);
Condition100%2/2
$self->_stats->{$node_id}{"error"} // 0
l!l
4087
MC/DC100%1/1
$self->_stats->{$node_id}{"error"} // 0
$self->_stats->{$node_id}{"error"}
Truth table100%2/2
A
A= $self->_stats->{$node_id}{"error"}
Aresult
11
00
2444 127 $self->_record_failure($node_id);
2445 }
2446  
2447 511 ▶ if (defined $args{duration_ms}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"duration_ms"}) 467 44 511
2448 $self->_stats->{$node_id}{duration_ms_total}
2449 467 ▶ = (0 + ($self->_stats->{$node_id}{duration_ms_total} // 0)) + (0 + $args{duration_ms});
Condition100%2/2
$self->_stats->{$node_id}{"duration_ms_total"} // 0
l!l
146321
MC/DC100%1/1
$self->_stats->{$node_id}{"duration_ms_total"} // 0
$self->_stats->{$node_id}{"duration_ms_total"}
Truth table100%2/2
A
A= $self->_stats->{$node_id}{"duration_ms_total"}
Aresult
11
00
2450 }
2451  
2452 511 return 1;
2453 }
2454  
2455 # One bucket per second, pruned to the window on every write, so a node that fails a lot costs
2456 # at most error_window_s buckets.
2457 127 ▶sub _record_failure {
Subroutine _record_failure: called CC=5 SCAR=16.2
2458 127 my ($self, $node_id) = @_;
2459 127 my $now = Time::HiRes::time();
2460 127 ▶ my $f = $self->_failures->{$node_id} //= { buckets => {} };
Condition100%2/2
$self->_failures->{$node_id} //= {"buckets", {}}
l!l
4087
MC/DC100%1/1
$self->_failures->{$node_id} //= {"buckets", {}}
$self->_failures->{$node_id}
Truth table100%2/2
A
A= $self->_failures->{$node_id}
Aresult
11
00
2461 127 $f->{last_at} = $now;
2462 127 $f->{buckets}{int $now}++;
2463 127 ▶ my $oldest = int($now - (0 + ($self->registry_error_window_s || 60)));
Condition50%1/2
$self->registry_error_window_s || 60
l!l
1270
MC/DC0%0/1
$self->registry_error_window_s || 60
$self->registry_error_window_s
Truth table50%1/2
A
A= $self->registry_error_window_s
Aresult
11
00
2464 127 for my $second (keys %{$f->{buckets}}) {
2465 135 ▶ delete $f->{buckets}{$second} if $second < $oldest;
Branch: 1 branch
BranchTrueFalseTotal
if $second < $oldest 0 135 135
2466 }
2467 127 return;
2468 }
2469  
2470 64 ▶sub _errors_in_window {
Subroutine _errors_in_window: called CC=5 SCAR=16.2
2471 64 my ($self, $node_id) = @_;
2472 64 ▶ my $f = $self->_failures->{$node_id} or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $f = $self->_failures->{$node_id} or return 0 1 63 64
2473 1 ▶ my $oldest = int(Time::HiRes::time() - (0 + ($self->registry_error_window_s || 60)));
Condition50%1/2
$self->registry_error_window_s || 60
l!l
10
MC/DC0%0/1
$self->registry_error_window_s || 60
$self->registry_error_window_s
Truth table50%1/2
A
A= $self->registry_error_window_s
Aresult
11
00
2474 1 my $count = 0;
2475 1 for my $second (keys %{$f->{buckets}}) {
2476 1 ▶ $count += $f->{buckets}{$second} if $second >= $oldest;
Branch: 1 branch
BranchTrueFalseTotal
if $second >= $oldest 1 0 1
2477 }
2478 1 return $count;
2479 }
2480  
2481  
2482 25 ▶sub registry_snapshot {
Subroutine registry_snapshot: called CC=19 SCAR=34.8
Pod documented
2483 25 my ($self) = @_;
2484 25 my $instance = $self->registry_instance_id;
2485 25 ▶ unless (defined($instance) && length($instance)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $instance and length $instance) 24 1 25
Condition66%2/3
defined $instance and length $instance
!ll&&!rl&&r
2401
MC/DC50%1/2
defined $instance and length $instance
defined $instance length $instance
Truth table66%2/3
A and B
A= defined $instanceB= length $instance
ABresult
0X0
100
111
2486 24 require Sys::Hostname;
2487 24 $instance = Sys::Hostname::hostname();
2488 }
2489  
2490 25 my @nodes;
2491 25 ▶ for my $node (sort { ($a->{id} // '') cmp ($b->{id} // '') } @{$self->nodes || []}) {
Condition50%3/6
$Langertha::Skeid::a->{"id"} // ""
l!l
620
$Langertha::Skeid::b->{"id"} // ""
l!l
620
$self->nodes || []
l!l
250
MC/DC0%0/1
$Langertha::Skeid::a->{"id"} // ""
$Langertha::Skeid::a->{"id"}
MC/DC0%0/1
$Langertha::Skeid::b->{"id"} // ""
$Langertha::Skeid::b->{"id"}
MC/DC0%0/1
$self->nodes || []
$self->nodes
Truth table50%1/2
A
A= $Langertha::Skeid::a->{"id"}
Aresult
11
00
Truth table50%1/2
A
A= $Langertha::Skeid::b->{"id"}
Aresult
11
00
Truth table50%1/2
A
A= $self->nodes
Aresult
11
00
2492 64 ▶ my $id = $node->{id} // next;
Condition50%1/2
$node->{"id"} // (next)
l!l
640
MC/DC0%0/1
$node->{"id"} // (next)
$node->{"id"}
Truth table50%1/2
A
A= $node->{"id"}
Aresult
11
00
2493 64 my $reading = $self->capacity_reading($id);
2494 64 my $failure = $self->_failures->{$id};
2495 push @nodes, {
2496 id => "$id",
2497 64 ▶ tags => [ @{$node->{tags} || []} ],
Branch: 6 branches
BranchTrueFalseTotal
$node->{'healthy'} ? : 64 0 64
$failure && defined $failure->{'last_at'} ? : 1 63 64
$reading ? : 0 64 64
defined $reading->{'used'} ? : 0 0 0
defined $reading->{'limit'} ? : 0 0 0
$reading->{'retry_after'} ? : 0 0 0
Condition71%5/7
$node->{'tags'} || []
l!l
640
$self->_inflight->{$id} // 0
l!l
4915
$failure and defined $failure->{"last_at"}
!ll&&!rl&&r
6301
MC/DC0%0/1
$node->{'tags'} || []
$node->{'tags'}
MC/DC100%1/1
$self->_inflight->{$id} // 0
$self->_inflight->{$id}
MC/DC50%1/2
$failure and defined $failure->{"last_at"}
$failure defined $failure->{"last_at"}
Truth table50%1/2
A
A= $node->{'tags'}
Aresult
11
00
Truth table100%2/2
A
A= $self->_inflight->{$id}
Aresult
11
00
Truth table66%2/3
A and B
A= $failureB= defined $failure->{"last_at"}
ABresult
0X0
100
111
2498 healthy => ($node->{healthy} ? 1 : 0),
2499 inflight => 0 + ($self->_inflight->{$id} // 0),
2500 max_conns => 0 + $self->worker_max_conns($node),
2501 errors_in_window => 0 + $self->_errors_in_window($id),
2502 last_failure_at => ($failure && defined $failure->{last_at} ? 0 + $failure->{last_at} : undef),
2503 ($reading ? (capacity => {
2504 used => (defined $reading->{used} ? 0 + $reading->{used} : undef),
2505 limit => (defined $reading->{limit} ? 0 + $reading->{limit} : undef),
2506 source => "$reading->{source}",
2507 64 ($reading->{retry_after} ? (retry_after => 0 + $reading->{retry_after}) : ()),
2508 }) : ()),
2509 };
2510 }
2511  
2512 return {
2513 25 ▶ version => 1,
Condition50%2/4
$self->registry_ttl_s || 10
l!l
250
$self->worker_count // 1
l!l
250
MC/DC0%0/1
$self->registry_ttl_s || 10
$self->registry_ttl_s
MC/DC0%0/1
$self->worker_count // 1
$self->worker_count
Truth table50%1/2
A
A= $self->registry_ttl_s
Aresult
11
00
Truth table50%1/2
A
A= $self->worker_count
Aresult
11
00
2514 instance => "$instance",
2515 generated_at => Time::HiRes::time(),
2516 ttl => 0 + ($self->registry_ttl_s || 10),
2517 workers => 0 + ($self->worker_count // 1),
2518 nodes => \@nodes,
2519 };
2520 }
2521  
2522  
2523 142 ▶sub node_metrics {
Subroutine node_metrics: called CC=12 SCAR=24.9
Pod documented
2524 142 my ($self, $node_id) = @_;
2525 142 ▶ if (defined $node_id && length $node_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $node_id and length $node_id) 139 3 142
Condition66%2/3
defined $node_id and length $node_id
!ll&&!rl&&r
30139
MC/DC50%1/2
defined $node_id and length $node_id
defined $node_id length $node_id
Truth table66%2/3
A and B
A= defined $node_idB= length $node_id
ABresult
0X0
100
111
2526 139 ▶ my $s = $self->_stats->{$node_id} || {};
Condition100%2/2
$self->_stats->{$node_id} || {}
l!l
1336
MC/DC100%1/1
$self->_stats->{$node_id} || {}
$self->_stats->{$node_id}
Truth table100%2/2
A
A= $self->_stats->{$node_id}
Aresult
11
00
2527 139 my $reading = $self->capacity_reading($node_id);
2528 return {
2529 node_id => $node_id,
2530 inflight => 0 + ($self->_inflight->{$node_id} // 0),
2531 started => 0 + ($s->{started} // 0),
2532 ok => 0 + ($s->{ok} // 0),
2533 error => 0 + ($s->{error} // 0),
2534 aborted => 0 + ($s->{aborted} // 0),
2535 139 ▶ duration_ms_total => 0 + ($s->{duration_ms_total} // 0),
Branch: 1 branch
BranchTrueFalseTotal
$reading ? : 12 127 139
Condition100%12/12
$self->_inflight->{$node_id} // 0
l!l
1336
$s->{"started"} // 0
l!l
1336
$s->{"ok"} // 0
l!l
4495
$s->{"error"} // 0
l!l
7564
$s->{"aborted"} // 0
l!l
13126
$s->{"duration_ms_total"} // 0
l!l
12217
MC/DC100%1/1
$self->_inflight->{$node_id} // 0
$self->_inflight->{$node_id}
MC/DC100%1/1
$s->{"started"} // 0
$s->{"started"}
MC/DC100%1/1
$s->{"ok"} // 0
$s->{"ok"}
MC/DC100%1/1
$s->{"error"} // 0
$s->{"error"}
MC/DC100%1/1
$s->{"aborted"} // 0
$s->{"aborted"}
MC/DC100%1/1
$s->{"duration_ms_total"} // 0
$s->{"duration_ms_total"}
Truth table100%2/2
A
A= $self->_inflight->{$node_id}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"started"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"ok"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"error"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"aborted"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"duration_ms_total"}
Aresult
11
00
2536 # Present only when a probe has something current to say. A report must not present a
2537 # measured node and an inferred one as equally known (ADR 0009).
2538 ($reading ? (capacity => { %$reading }) : ()),
2539 };
2540 }
2541  
2542 3 my @rows;
2543 3 for my $n (@{$self->nodes}) {
2544 6 push @rows, $self->node_metrics($n->{id});
2545 }
2546 3 return \@rows;
2547 }
2548  
2549  
2550 3846 ▶sub call_function {
Subroutine call_function: called CC=58 SCAR=55.9
Pod documented
2551 3846 my ($self, $name, $args) = @_;
2552 3846 ▶ $args ||= {};
Condition50%1/2
$args ||= {}
l!l
38460
MC/DC0%0/1
$args ||= {}
$args
Truth table50%1/2
A
A= $args
Aresult
11
00
2553 3846 ▶ croak 'function name required' unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 3846 3846
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
003846
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
2554 3846 ▶ croak 'function args must be hashref' unless ref($args) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "HASH" 0 3846 3846
2555  
2556 # Dynamic config refresh on each task/function dispatch. Never dies: a failed reload keeps
2557 # the previous config and is reported by reload_status (skeid #39).
2558 3846 $self->maybe_reload_config;
2559  
2560 3846 ▶ if ($name eq 'metrics.estimate_cost') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "metrics.estimate_cost") 0 3846 3846
2561 0 return $self->estimate_cost(%$args);
2562 }
2563 3846 ▶ if ($name eq 'metrics.normalize') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "metrics.normalize") 331 3515 3846
2564 331 return $self->normalize_metrics(%$args);
2565 }
2566 3515 ▶ if ($name eq 'pricing.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "pricing.set") 13 3502 3515
2567 13 ▶ my $model = $args->{model} // croak 'pricing.set: model required';
Condition33%1/3
$args->{"model"} // croak("pricing.set: model required")
l!l&&r!l&&!r
1300
MC/DC0%0/2
$args->{"model"} // croak("pricing.set: model required")
$args->{"model"} croak("pricing.set: model required")
Truth table33%1/3
A // B
A= $args->{"model"}B= croak("pricing.set: model required")
ABresult
1X1
011
000
2568 13 ▶ my $pricing = $args->{pricing} // croak 'pricing.set: pricing required';
Condition33%1/3
$args->{"pricing"} // croak("pricing.set: pricing required")
l!l&&r!l&&!r
1300
MC/DC0%0/2
$args->{"pricing"} // croak("pricing.set: pricing required")
$args->{"pricing"} croak("pricing.set: pricing required")
Truth table33%1/3
A // B
A= $args->{"pricing"}B= croak("pricing.set: pricing required")
ABresult
1X1
011
000
2569 13 return $self->set_model_pricing($model, $pricing);
2570 }
2571 3502 ▶ if ($name eq 'nodes.add') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.add") 2 3500 3502
2572 2 ▶ return { ok => $self->add_node(%$args) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->add_node(%$args) ? : 1 0 1
2573 }
2574 3500 ▶ if ($name eq 'nodes.remove') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.remove") 0 3500 3500
2575 0 ▶ return { ok => $self->remove_node($args->{id}) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->remove_node($args->{'id'}) ? : 0 0 0
2576 }
2577 3500 ▶ if ($name eq 'nodes.list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.list") 248 3252 3500
2578 248 return { nodes => $self->list_nodes };
2579 }
2580 3252 ▶ if ($name eq 'nodes.select') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.select") 0 3252 3252
2581 0 return { nodes => $self->select_nodes(tags => $args->{tags}, deny_tags => $args->{deny_tags}) };
2582 }
2583 3252 ▶ if ($name eq 'alias.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "alias.set") 0 3252 3252
2584 0 ▶ my $alias = $args->{name} // croak 'alias.set: name required';
Condition0%0/3
$args->{"name"} // croak("alias.set: name required")
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{"name"} // croak("alias.set: name required")
$args->{"name"} croak("alias.set: name required")
Truth table0%0/3
A // B
A= $args->{"name"}B= croak("alias.set: name required")
ABresult
1X1
011
000
2585 0 ▶ return { ok => $self->set_model_alias($alias, $args->{alias} // $args) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->set_model_alias($alias, $args->{'alias'} // $args) ? : 0 0 0
Condition0%0/3
$args->{"alias"} // $args
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{"alias"} // $args
$args->{"alias"} $args
Truth table0%0/3
A // B
A= $args->{"alias"}B= $args
ABresult
1X1
011
000
2586 }
2587 3252 ▶ if ($name eq 'route.plan') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "route.plan") 508 2744 3252
2588 return $self->route_plan(
2589 model => ($args->{model} // ''),
2590 engine => $args->{engine},
2591 api_key_id => $args->{api_key_id},
2592 508 ▶ );
Condition50%1/2
$args->{"model"} // ""
l!l
5080
MC/DC0%0/1
$args->{"model"} // ""
$args->{"model"}
Truth table50%1/2
A
A= $args->{"model"}
Aresult
11
00
2593 }
2594 2744 ▶ if ($name eq 'policy.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "policy.set") 0 2744 2744
2595 0 ▶ my $policy = $args->{name} // croak 'policy.set: name required';
Condition0%0/3
$args->{"name"} // croak("policy.set: name required")
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{"name"} // croak("policy.set: name required")
$args->{"name"} croak("policy.set: name required")
Truth table0%0/3
A // B
A= $args->{"name"}B= croak("policy.set: name required")
ABresult
1X1
011
000
2596 0 ▶ return { ok => $self->set_policy($policy, $args->{policy} // $args) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->set_policy($policy, $args->{'policy'} // $args) ? : 0 0 0
Condition0%0/3
$args->{"policy"} // $args
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{"policy"} // $args
$args->{"policy"} $args
Truth table0%0/3
A // B
A= $args->{"policy"}B= $args
ABresult
1X1
011
000
2597 }
2598 2744 ▶ if ($name eq 'policy.for_key') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "policy.for_key") 0 2744 2744
2599 0 return { policy => $self->policy_for_key($args->{api_key_id}) };
2600 }
2601 2744 ▶ if ($name eq 'nodes.set_health') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.set_health") 14 2730 2744
2602 14 ▶ return { ok => $self->set_node_health($args->{id}, $args->{healthy}) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->set_node_health($args->{'id'}, $args->{'healthy'}) ? : 14 0 14
2603 }
2604 2730 ▶ if ($name eq 'nodes.metrics') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "nodes.metrics") 1 2729 2730
2605 1 return { metrics => $self->node_metrics($args->{id}) };
2606 }
2607 2729 ▶ if ($name eq 'engines.list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "engines.list") 0 2729 2729
2608 0 return { engines => $self->supported_engine_ids };
2609 }
2610 2729 ▶ if ($name eq 'route.next') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "route.next") 622 2107 2729
2611 my $node = $self->pick_node(
2612 model => ($args->{model} // ''),
2613 engine => $self->normalize_engine_id($args->{engine} // ''),
2614 tags => $args->{tags},
2615 deny_tags => $args->{deny_tags},
2616 622 ▶ );
Condition50%2/4
$args->{"model"} // ""
l!l
6220
$args->{"engine"} // ""
l!l
0622
MC/DC0%0/1
$args->{"model"} // ""
$args->{"model"}
MC/DC0%0/1
$args->{"engine"} // ""
$args->{"engine"}
Truth table50%1/2
A
A= $args->{"model"}
Aresult
11
00
Truth table50%1/2
A
A= $args->{"engine"}
Aresult
11
00
2617 622 return { node => $node };
2618 }
2619 2107 ▶ if ($name eq 'route.state') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "route.state") 647 1460 2107
2620 647 ▶ my $engine = $self->normalize_engine_id($args->{engine} // '');
Condition50%1/2
$args->{"engine"} // ""
l!l
0647
MC/DC0%0/1
$args->{"engine"} // ""
$args->{"engine"}
Truth table50%1/2
A
A= $args->{"engine"}
Aresult
11
00
2621 return $self->route_state(
2622 model => ($args->{model} // ''),
2623 engine => $engine,
2624 tags => $args->{tags},
2625 deny_tags => $args->{deny_tags},
2626 647 ▶ );
Condition50%1/2
$args->{"model"} // ""
l!l
6470
MC/DC0%0/1
$args->{"model"} // ""
$args->{"model"}
Truth table50%1/2
A
A= $args->{"model"}
Aresult
11
00
2627 }
2628 1460 ▶ if ($name eq 'capacity.set') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.set") 0 1460 1460
2629 0 ▶ my $id = $args->{id} // croak 'capacity.set: id required';
Condition0%0/3
$args->{"id"} // croak("capacity.set: id required")
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{"id"} // croak("capacity.set: id required")
$args->{"id"} croak("capacity.set: id required")
Truth table0%0/3
A // B
A= $args->{"id"}B= croak("capacity.set: id required")
ABresult
1X1
011
000
2630 0 return { capacity => $self->set_capacity_reading($id, %$args) };
2631 }
2632 1460 ▶ if ($name eq 'capacity.get') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.get") 0 1460 1460
2633 0 ▶ my $id = $args->{id} // croak 'capacity.get: id required';
Condition0%0/3
$args->{"id"} // croak("capacity.get: id required")
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{"id"} // croak("capacity.get: id required")
$args->{"id"} croak("capacity.get: id required")
Truth table0%0/3
A // B
A= $args->{"id"}B= croak("capacity.get: id required")
ABresult
1X1
011
000
2634 0 return { capacity => $self->capacity_reading($id) };
2635 }
2636 1460 ▶ if ($name eq 'capacity.observe') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.observe") 5 1455 1460
2637 5 ▶ my $id = $args->{id} // croak 'capacity.observe: id required';
Condition33%1/3
$args->{"id"} // croak("capacity.observe: id required")
l!l&&r!l&&!r
500
MC/DC0%0/2
$args->{"id"} // croak("capacity.observe: id required")
$args->{"id"} croak("capacity.observe: id required")
Truth table33%1/3
A // B
A= $args->{"id"}B= croak("capacity.observe: id required")
ABresult
1X1
011
000
2638 return { capacity => $self->observe_response_headers(
2639 5 ▶ $id, ($args->{headers} || {}), status => $args->{status}) };
Condition50%1/2
$args->{'headers'} || {}
l!l
50
MC/DC0%0/1
$args->{'headers'} || {}
$args->{'headers'}
Truth table50%1/2
A
A= $args->{'headers'}
Aresult
11
00
2640 }
2641 1455 ▶ if ($name eq 'capacity.forget') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "capacity.forget") 0 1455 1455
2642 0 ▶ return { ok => $self->forget_capacity($args->{id}) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->forget_capacity($args->{'id'}) ? : 0 0 0
2643 }
2644 1455 ▶ if ($name eq 'request.start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "request.start") 468 987 1455
2645 468 ▶ my $id = $args->{id} // croak 'request.start: id required';
Condition33%1/3
$args->{"id"} // croak("request.start: id required")
l!l&&r!l&&!r
46800
MC/DC0%0/2
$args->{"id"} // croak("request.start: id required")
$args->{"id"} croak("request.start: id required")
Truth table33%1/3
A // B
A= $args->{"id"}B= croak("request.start: id required")
ABresult
1X1
011
000
2646 468 ▶ return { ok => $self->start_request($id) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->start_request($id) ? : 468 0 468
2647 }
2648 987 ▶ if ($name eq 'request.finish') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "request.finish") 467 520 987
2649 467 ▶ my $id = $args->{id} // croak 'request.finish: id required';
Condition33%1/3
$args->{"id"} // croak("request.finish: id required")
l!l&&r!l&&!r
46700
MC/DC0%0/2
$args->{"id"} // croak("request.finish: id required")
$args->{"id"} croak("request.finish: id required")
Truth table33%1/3
A // B
A= $args->{"id"}B= croak("request.finish: id required")
ABresult
1X1
011
000
2650 467 ▶ return { ok => $self->finish_request($id, %$args) ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$self->finish_request($id, %$args) ? : 467 0 467
2651 }
2652 520 ▶ if ($name eq 'config.reload') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "config.reload") 1 519 520
2653 1 return { config => $self->reload_config };
2654 }
2655 519 ▶ if ($name eq 'config.status') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "config.status") 1 518 519
2656 1 return $self->reload_status;
2657 }
2658 518 ▶ if ($name eq 'usage.record') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "usage.record") 503 15 518
2659 503 return $self->record_usage(%$args);
2660 }
2661 15 ▶ if ($name eq 'usage.report') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "usage.report") 14 1 15
2662 14 return $self->usage_report(%$args);
2663 }
2664 1 ▶ if ($name eq 'usage.configure') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "usage.configure") 1 0 1
2665 1 ▶ my $store = $args->{usage_store} // $args;
Condition33%1/3
$args->{"usage_store"} // $args
l!l&&r!l&&!r
100
MC/DC0%0/2
$args->{"usage_store"} // $args
$args->{"usage_store"} $args
Truth table33%1/3
A // B
A= $args->{"usage_store"}B= $args
ABresult
1X1
011
000
2666 1 return { usage_store => $self->configure_usage_store($store) };
2667 }
2668  
2669 0 croak "unknown function: $name";
2670 }
2671  
2672 343 ▶sub DEMOLISH {
Subroutine DEMOLISH: called CC=1 SCAR=0.0
Pod undocumented
2673 343 my ($self) = @_;
2674 343 $self->_disconnect_usage_store;
2675 }
2676  
2677 374 ▶sub _disconnect_usage_store {
Subroutine _disconnect_usage_store: called CC=2 SCAR=6.9
2678 374 my ($self) = @_;
2679 374 ▶ my $store = $self->_usage_store_obj or return;
Branch: 1 branch
BranchTrueFalseTotal
my $store = $self->_usage_store_obj or return 31 343 374
2680 31 $store->disconnect;
2681 31 $self->_usage_store_obj(undef);
2682 31 return;
2683 }
2684  
2685  
2686 67 1;
2687  
2688 __END__
2689  
2690 =pod
2691  
2692 =encoding UTF-8
2693  
2694 =head1 NAME
2695  
2696 Langertha::Skeid - Dynamic routing control-plane for multi-node LLM serving with normalized metrics and cost accounting
2697  
2698 =head1 VERSION
2699  
2700 version 0.003
2701  
2702 =head1 SYNOPSIS
2703  
2704 use Langertha::Skeid;
2705  
2706 my $skeid = Langertha::Skeid->new(
2707 config_file => '/etc/skeid/config.yaml',
2708 );
2709  
2710 my $cost = $skeid->call_function('metrics.estimate_cost', {
2711 model => 'gpt-4o-mini',
2712 usage => { prompt_tokens => 1000, completion_tokens => 200 },
2713 });
2714  
2715 =head1 DESCRIPTION
2716  
2717 Langertha::Skeid is a routing control-plane for provider-style LLM operations.
2718 It keeps a live node table, routes by model/health/capacity, and records
2719 normalized token/cost usage.
2720  
2721 Skeid is commonly used as one API edge in front of many upstream APIs
2722 (cloud + local). With C<pricing> and C<usage.record/report>, you can build
2723 tenant billing from one consistent ledger.
2724  
2725 =head2 Multi-API Billing Flow
2726  
2727 1. Define multiple nodes in config (for example OpenAI-compatible cloud APIs
2728 and local vLLM/SGLang).
2729 2. Set model pricing via C<pricing> or C<pricing.set>.
2730 3. Let tenant identity follow from the API key the caller presents. C<skeid keyid>
2731 prints the id a given key resolves to. A deployment that authenticates callers
2732 in front of Skeid can instead pass C<x-skeid-key-id> and set
2733 C<routing.trust_key_id_header>.
2734 4. Read totals by key/model/time with C<usage.report>.
2735  
2736 =head2 Engine IDs
2737  
2738 C<nodes[].engine> uses lowercased engine class names from L<Langertha>.
2739 Examples: C<OpenAI =E<gt> openai>, C<OpenAIBase =E<gt> openaibase>,
2740 C<vLLM =E<gt> vllm>. Legacy aliases like C<openai-compatible> are intentionally
2741 rejected. A node without C<engine> is C<openaibase>. See L</normalize_engine_id>.
2742  
2743 =head2 Pluggable Usage Storage
2744  
2745 The usage storage layer is pluggable. Built-in backends are C<jsonlog>
2746 (recommended, no DBI required), C<sqlite>, and C<postgresql>. You can also
2747 replace the storage layer entirely via constructor callbacks or subclass
2748 override.
2749  
2750 B<jsonlog backend> (recommended — no DBI dependency):
2751  
2752 # Directory mode: one JSON file per event (no collision risk)
2753 my $skeid = Langertha::Skeid->new(
2754 usage_store => { backend => 'jsonlog', path => '/var/log/skeid/events/' },
2755 );
2756  
2757 # File mode: JSON-lines appended to a single file
2758 my $skeid = Langertha::Skeid->new(
2759 usage_store => { backend => 'jsonlog', path => '/var/log/skeid/usage.jsonl', mode => 'file' },
2760 );
2761  
2762 Directory mode is auto-detected when the path is an existing directory or ends
2763 with C</>. It writes one C<.json> file per event, which avoids file-level
2764 locking and concurrent-write collisions entirely.
2765  
2766 B<Constructor callbacks> (custom backend, no subclassing):
2767  
2768 my $skeid = Langertha::Skeid->new(
2769 store_usage_event => sub {
2770 my ($self, $event) = @_;
2771 # $event is a hashref with all normalized usage columns
2772 publish_to_nats($event);
2773 return { ok => 1 };
2774 },
2775 query_usage_report => sub {
2776 my ($self, $filters) = @_;
2777 # $filters has: since, api_key_id, model, limit
2778 return { ok => 1, enabled => 1, totals => { ... } };
2779 },
2780 );
2781  
2782 B<Subclass override>:
2783  
2784 package MyApp::Skeid;
2785 use Moo;
2786 extends 'Langertha::Skeid';
2787  
2788 sub _store_usage_event {
2789 my ($self, $event) = @_;
2790 ...
2791 return { ok => 1 };
2792 }
2793  
2794 sub _query_usage_report {
2795 my ($self, $filters) = @_;
2796 ...
2797 }
2798  
2799 B<Optional fields.> A streamed request's event also carries C<content_bytes>: the
2800 UTF-8 byte count of the content Skeid relayed (OpenAI face) or translated (Anthropic
2801 and Ollama faces). It is set on every stream, including one whose upstream reported
2802 token counts, and is absent from non-streamed events -- a sink must not assume it is
2803 there. It is an observation, not a billing quantity: Skeid never derives token counts
2804 or cost from it. The DBI stores keep it in a nullable C<content_bytes> column (C<NULL>
2805 for a non-streamed or pre-existing row); C<jsonlog> writes it as part of the event.
2806  
2807 When a callback or override is provided, the configured store is bypassed entirely
2808 and no database connection is created. DBI, DBD::SQLite and DBD::Pg are C<recommends>
2809 dependencies — they are not required for C<jsonlog> or when usage is handled externally.
2810 With no sink at all, L</record_usage> builds no event and answers
2811 C<< { ok => 0, enabled => 0, error => 'usage_store not configured' } >>. A sink that fails answers
2812 C<< { ok => 0, error => ... } >> (or dies); the proxy logs that at C<error> level as a lost usage
2813 event, naming the request id and the store backend.
2814  
2815 =head2 Per-Key Routing Policy
2816  
2817 Which nodes a customer key may be served from, and which models it may ask for:
2818  
2819 policies:
2820 standard: { deny_tags: [cloud] } # our own hardware only
2821 burstable: {} # cloud is fine when local is full
2822 default_policy: standard
2823 names:
2824 alice: k_5f0e1a2b3c4de5f60718293a4b5c6d7e8f901a2b # id from `skeid keyid <key>` -- never the key
2825 bigcorp: k_9c8b7a6f5e4de5f60718293a4b5c6d7e8f901a2b
2826 keys:
2827 alice: burstable # a keys: entry may be written by name ...
2828 bigcorp:
2829 policy: standard
2830 models: [house-model] # sparse override of one field
2831 k_1122334455aae5f60718293a4b5c6d7e8f901a2b: burstable # ... or still by the raw key id
2832  
2833 Resolved once at config load: a request costs one hash lookup, keys on the same profile share
2834 one policy object, and a key that takes the default is not listed at all. C<deny_tags> filters
2835 node selection, not just the plan, so a denied node cannot be reached by asking for its own
2836 model name instead of an alias. A refusal is C<403>, never a capacity error.
2837  
2838 The optional C<names:> section maps a readable name to a customer key id (karr #17). It makes
2839 C<keys:> entries legible and confines key rotation to a single line -- change the id a name
2840 points at, and every policy line that named the customer follows. Its values are ids from
2841 C<skeid keyid>, never customer keys, so the config still holds no secret; it is read only at
2842 config load and never on the request path.
2843  
2844 Identity comes from the API key the caller presented — see L</key_id_for_key>. See also ADR
2845 0008 in the distribution repository.
2846  
2847 =head2 Admin API Key
2848  
2849 C<admin.api_key> (or C<admin_api_key>) controls access to proxy admin routes; C<admin.api_key_env>
2850 (or C<admin_api_key_env>) names an environment variable to read it from instead, so the key need
2851 not be written into a mounted file. If empty, admin routes are effectively disabled by returning
2852 C<404>. If set, the proxy expects C<Authorization: Bearer ...>. An explicit key
2853 (C<skeid serve --admin-api-key>, L</set_admin_api_key>) outranks the config, and
2854 C<SKEID_ADMIN_API_KEY> stands in when the config names none; a reload re-applies that order.
2855 See L</admin>.
2856  
2857 =head2 Provider Manifest
2858  
2859 C<GET /.well-known/langertha.json> serves a provider manifest (core's
2860 L<Langertha::Manifest>, schema v1) to a customer key -- listing only the models that key's own
2861 C<keys:> entry names. Nothing is published automatically: the route answers C<404> until the
2862 config turns it on, and a key without a C<manifest:> entry gets C<403>, never the catalog.
2863  
2864 manifest:
2865 enabled: true
2866 public_url: https://llm.example.com # where clients reach Skeid -- never a node URL
2867 provider_id: example-llm # default: skeid
2868 faces: [openai, anthropic, ollama] # default: all three
2869 capabilities: # optional claims per model; default chat + streaming
2870 house-model: { tools_native: true, tool_choice_auto: true }
2871 names: # ids from `skeid keyid <key>` -- never the key
2872 alice: k_5f0e1a2b3c4de5f60718293a4b5c6d7e8f901a2b
2873 bob: k_9c8b7a6f5e4de5f60718293a4b5c6d7e8f901a2b
2874 keys:
2875 alice:
2876 policy: burstable
2877 manifest: { models: [house-model, qwen3-32b] }
2878 bob:
2879 manifest: { models: [house-model] }
2880  
2881 One endpoint per face, all under C<public_url> and all with one C<api_key> auth entry (the
2882 C<Authorization: Bearer> / C<x-api-key> scheme every face already takes): C<openai>
2883 (C<openai-chat>, C<public_url/v1>), C<anthropic> (C<anthropic-compat> at C<public_url> --
2884 Skeid translates C</v1/messages> to the OpenAI upstream call and does not carry
2885 C<output_config.format>, so structured output takes the synthetic-tool path) and C<ollama>
2886 (C<public_url>). Every listed model appears on every published face. Its capabilities default
2887 to C<chat> and C<streaming>, take the claims declared for it (only flags from
2888 L<Langertha::Manifest::Builder/model_capabilities>), and are then cut per face to what that
2889 face's translator carries upstream -- a claim holds at that endpoint or is not made there. The
2890 lists are L<Langertha::Skeid::Protocol/openai_manifest_endpoint>,
2891 L<Langertha::Skeid::Protocol::Anthropic/manifest_endpoint> and
2892 L<Langertha::Skeid::Protocol::Ollama/manifest_endpoint>.
2893  
2894 Resolved at config load, like the routing policy: each key's manifest is built and validated
2895 once and stored under the key id, so a request costs one hash lookup and one key's manifest
2896 cannot be served for another. The load croaks on a model the key's routing policy does not
2897 let it reach (not granted, or served only by nodes it is denied), on an unknown capability,
2898 one no face carries, an unknown face, and an enabled manifest without C<public_url>. A config
2899 that fails to load keeps the previous one in force, manifests included. The route never
2900 reloads the config itself; the request paths that already do pick up a change.
2901 Without a key the route answers C<401>. Needs a Langertha with L<Langertha::Manifest>; on an
2902 older one the route answers C<404>. See ADR 0015 in the distribution repository.
2903  
2904 =head1 CONFIGURATION
2905  
2906 The config is a YAML file (C<config_file>) or the hashref a C<config_loader> returns; both go
2907 through the same loader. The top-level keys below are every one Skeid reads -- anything else in
2908 the file is ignored. A reload is all or nothing: a config that fails anywhere leaves the previous
2909 one in force, and is reported by L</reload_status>.
2910  
2911 A reload makes the running config equal to the file (skeid k65), as a restart with that file
2912 would:
2913  
2914 =over 4
2915  
2916 =item * C<nodes>, C<pricing>, C<aliases>, the policy keys (C<policies>, C<default_policy>,
2917 C<names>, C<keys>) and C<usage_store>: present, the section replaces what is loaded -- C<pricing>
2918 too, so a model removed from it loses its price. Removed from the file, the section goes back
2919 to empty with the next reload: no nodes, no prices, no aliases, no policies.
2920  
2921 =item * C<routing>: each key present sets its value; a key removed from the file goes back to
2922 the value it had before any config was applied -- passed to C<new>, else from
2923 L</ENVIRONMENT>, else built in.
2924  
2925 =item * The admin key: absent falls back to C<SKEID_ADMIN_API_KEY>, else off -- see L</admin>.
2926  
2927 =item * C<registry> and C<manifest>: absent means off.
2928  
2929 =back
2930  
2931 Two exceptions. A section no applied config has declared belongs to whoever set it: nodes added
2932 through the admin API or L</add_node>, prices from L</set_model_pricing>, values passed to
2933 C<new> -- a config without that section leaves them alone. And the usage store is not removed by
2934 a reload: a C<usage_store> taken out of the file keeps the running store in force until restart,
2935 with one warning (C<usage_store was removed from the config ...>), because a reload that stopped
2936 recording usage events would lose billing data silently (ADR 0004). A I<changed> C<usage_store>
2937 is swapped at once, the new store prepared before the old one is let go.
2938  
2939 Three settings look like config but are not read from it: L</capacity_max_age_ms> and
2940 L</config_reload_interval> (constructor or environment only) and L</worker_count> (constructor,
2941 set by C<skeid serve --workers>).
2942  
2943 =head2 nodes
2944  
2945 nodes:
2946 - id: gpu-1 # required, unique
2947 url: http://gpu-1:8000/v1 # required; /v1 is added when the URL does not end in it
2948 model: qwen3-32b # default '': matches any requested model
2949 engine: vllm # default openaibase; see "Engine IDs"
2950 weight: 3 # default 1; round-robin weight, integer, below 1 counts as 1
2951 max_conns: 8 # default 0 = unlimited; admission limit, see worker_max_conns
2952 healthy: true # default true; operator state, never derived from errors
2953 tags: [local, gb10] # default none; "local, gb10" works too, see normalize_tags
2954 metadata: { rack: b2 } # default {}; kept on the node, never read by routing
2955 api_key_ref: secret/skeid/remote/groq # upstream key, resolved through the key broker
2956 api_key_env: GROQ_API_KEY # upstream key from this variable when the ref resolves none
2957 capacity: { probe: prometheus } # default none: inflight admission, see below
2958  
2959 An entry without C<id> or C<url> is skipped; one with an unknown C<engine> fails the load. When
2960 a node has a key of its own it replaces the client's C<Authorization> upstream (see
2961 L<Langertha::Skeid::Proxy>); otherwise the client's headers go through. Key references and
2962 variable names are the only key material a config holds (ADR 0003).
2963  
2964 The section replaces the whole inventory when it changed -- nodes added through the admin API are
2965 lost then -- and keeps the node list as it is when it did not: its inventory generation, its
2966 running probes and any health set through the admin API. Removing the section empties the
2967 inventory.
2968  
2969 C<capacity> selects how admission learns a node's real occupancy (ADR 0009). C<probe> (or
2970 C<type>) is C<inflight> (the default, also C<none>), C<ratelimit>, C<prometheus>, C<registry> or
2971 C<custom>; C<interval_ms> (default 2000) sets the poll rate. Rate-limit headers are read off every
2972 upstream response whatever the block says, so C<ratelimit> starts nothing. The keys per probe
2973 are documented in L<Langertha::Skeid::CapacityProbe/for_node>,
2974 L<Langertha::Skeid::CapacityProbe::Prometheus> and L<Langertha::Skeid::CapacityProbe::Registry>.
2975  
2976 =head2 pricing
2977  
2978 pricing:
2979 gpt-4o-mini:
2980 input_per_million: 0.15 # default 0
2981 output_per_million: 0.60 # default 0
2982 cached_input_per_million: 0.075 # optional; prompt-cache reads
2983 cache_write_per_million: 0.1875 # optional; prompt-cache writes
2984 '*': # fallback for every model not listed
2985 input_per_million: 0
2986 output_per_million: 0
2987  
2988 Keyed by the B<served> model -- the name the node is asked for, not an alias. The section is the
2989 whole price list: a reload replaces it, it is not merged. A cache rate must be
2990 a number C<E<gt>= 0>, or the load fails; on a Langertha that cannot price cache tokens the cache
2991 rates are dropped with one warning and cached tokens bill at C<input_per_million>. See
2992 L</set_model_pricing>.
2993  
2994 =head2 aliases
2995  
2996 aliases:
2997 house-model:
2998 tiers:
2999 - { tags: [local], model: qwen3-32b, wait_ms: 200 }
3000 - { tags: [cloud], model: llama-3.3-70b-versatile }
3001  
3002 A client-facing model name as an ordered plan of tiers (ADR 0008). Per tier: C<tags>, C<model>
3003 (default: the alias name), C<engine> and C<wait_ms> (default 0). C<tiers> may be given as a bare
3004 list. See L</set_model_alias>.
3005  
3006 =head2 policies, default_policy, names, keys
3007  
3008 Who may reach what; see L</Per-Key Routing Policy>. A policy is C<models> (or C<aliases>: the
3009 requested names the key may use; absent or C<'*'> means all) and C<deny_tags> (nodes the key must
3010 never reach). C<default_policy> names the policy of every unlisted key; unset, an unlisted key is
3011 unrestricted. C<names> maps a readable name to a key id from C<skeid keyid>.
3012  
3013 A C<keys> entry is keyed by a key id or a C<names> name and is either a policy name or a hash:
3014  
3015 keys:
3016 alice: burstable
3017 bigcorp:
3018 policy: standard # default: default_policy
3019 models: [house-model] # sparse overrides: an absent field keeps the policy's value
3020 deny_tags: [cloud]
3021 manifest: { models: [house-model] } # see "Provider Manifest"
3022  
3023 The override fields may instead sit under an C<overrides> hash. The load fails on a
3024 C<default_policy> or a C<keys> entry naming an undefined policy, on a C<names> value that is not
3025 a non-empty string, and on two entries that resolve to one key id -- including a short
3026 (pre-ADR 0016) id beside the full id it is the prefix of. Short ids still match, with a one-time
3027 warning.
3028  
3029 =head2 routing
3030  
3031 routing:
3032 wait_timeout_ms: 2000 # default 2000: the wait of a model that has no alias
3033 wait_poll_ms: 25 # default 25, at least 1: how often a waiting request retries
3034 trust_key_id_header: false # default false; see key_id_for_key
3035 frontend_count: 1 # default 1, at least 1; see frontend_count
3036  
3037 The defaults come from L</ENVIRONMENT> when set there.
3038  
3039 =head2 admin
3040  
3041 admin:
3042 api_key_env: SKEID_ADMIN_API_KEY # or api_key: "..."
3043  
3044 The key for the C</skeid/*> admin API. It comes from the first of these that has one
3045 (skeid k64):
3046  
3047 =over 4
3048  
3049 =item 1. An explicit key: C<skeid serve --admin-api-key>, C<< build_app(admin_api_key => ...) >>,
3050 an C<admin_api_key> passed to C<new>, or L</set_admin_api_key>.
3051  
3052 =item 2. The config: the first of C<admin_api_key>, C<admin_api_key_env>, C<admin.api_key> and
3053 C<admin.api_key_env> that is present decides -- set empty, or naming an unset variable, it turns
3054 the admin API off.
3055  
3056 =item 3. C<SKEID_ADMIN_API_KEY>, when the config names none of the four.
3057  
3058 =back
3059  
3060 With none of them the admin API is off (C<404>). Every applied config re-resolves the key in
3061 this order, so a reload never replaces an explicit key, and removing the key from the config
3062 falls back to the variable. A variable is read when the config is applied, so a changed value
3063 takes effect with the next changed config.
3064  
3065 =head2 registry
3066  
3067 Publishes this Skeid's capacity to a fronting Skeid: C<enabled>, C<secret_env>, C<read_key_env>,
3068 C<ttl_s> (default 10), C<instance_id> (default the hostname) and C<error_window_s> (default 60).
3069 Documented under L</registry_enabled>.
3070  
3071 =head2 manifest
3072  
3073 The provider manifest: C<enabled>, C<public_url>, C<provider_id> (default C<skeid>), C<faces>
3074 (default all three) and C<capabilities>. Documented under L</Provider Manifest>.
3075  
3076 =head2 usage_store
3077  
3078 usage_store:
3079 backend: jsonlog # jsonlog | sqlite | postgresql; inferred when absent
3080 path: /var/log/skeid/events/ # jsonlog: log_path or path; mode dir|file (inferred), fsync
3081 # sqlite: sqlite_path (or path, db_path), schema_file, auto_migrate (default on)
3082 # postgresql: dsn, or host (127.0.0.1) / port (5432) / dbname or database (skeid);
3083 # user, password or password_env, schema_file, auto_migrate (default on)
3084 # sqlite and postgresql: flush_interval_ms (default 0) -- above 0, queue events and
3085 # write them in one transaction per interval (write-behind)
3086  
3087 Where usage events go; see L<Langertha::Skeid::UsageStore/normalize_config> for the inference and
3088 the defaults. C<usage_db_path>, a top-level key, is the older spelling of a sqlite store and is
3089 read only when C<usage_store> is absent. A changed store is swapped on reload; a removed one stays
3090 in force until restart, with a warning -- see L</CONFIGURATION>.
3091  
3092 C<flush_interval_ms> moves a database write off the request path: the request is answered at
3093 once and the queued events are written together once per interval. Queued events are held in
3094 memory until then; a process that is killed rather than stopped loses them. See
3095 L<Langertha::Skeid::UsageStore::DBI/flush_interval_ms> and ADR 0005.
3096  
3097 =head1 ENVIRONMENT
3098  
3099 Defaults for the attributes of the same meaning; a value in the config wins. Besides these, the
3100 config names variables of its own -- C<api_key_env> on a node, C<admin.api_key_env>, a usage
3101 store's C<password_env>, the registry's C<secret_env> and C<read_key_env> -- so that no secret has
3102 to be written into it. L<Langertha::Skeid::Proxy/build_app> reads the C<OPENBAO_*> variables,
3103 C<SKEID_UPSTREAM_POOL> and C<SKEID_UPSTREAM_TIMEOUT>.
3104  
3105 =head2 SKEID_ROUTE_WAIT_TIMEOUT_MS
3106  
3107 Default of L</route_wait_timeout_ms> (2000).
3108  
3109 =head2 SKEID_ROUTE_WAIT_POLL_MS
3110  
3111 Default of L</route_wait_poll_ms> (25).
3112  
3113 =head2 SKEID_TRUST_KEY_ID_HEADER
3114  
3115 Default of L</trust_key_id_header>: C<1>, C<true>, C<yes> or C<on> turn it on.
3116  
3117 =head2 SKEID_FRONTEND_COUNT
3118  
3119 Default of L</frontend_count> (1).
3120  
3121 =head2 SKEID_ADMIN_API_KEY
3122  
3123 The admin API key when neither an explicit key nor the config names one; see L</admin>.
3124  
3125 =head2 SKEID_USAGE_DB
3126  
3127 Default of L</usage_db_path>: a SQLite usage store at this path when no C<usage_store> is given,
3128 and the path of a C<sqlite> store that names none.
3129  
3130 =head2 SKEID_CAPACITY_MAX_AGE_MS
3131  
3132 Default of L</capacity_max_age_ms> (5000).
3133  
3134 =head2 SKEID_CONFIG_RELOAD_INTERVAL
3135  
3136 Default of L</config_reload_interval> (1 second).
3137  
3138 =head1 ATTRIBUTES
3139  
3140 Every attribute can be passed to C<new>. Those a config sets are overwritten by the next changed
3141 config that sets them (see L</CONFIGURATION>) -- except L</admin_api_key>, which C<new> takes as
3142 an explicit key that outranks the config.
3143  
3144 =head2 nodes
3145  
3146 The node inventory: an arrayref of node hashrefs, in the shape of the config's C<nodes> entries
3147 after L</add_node> normalized them (default empty). Change it through L</add_node>,
3148 L</remove_node> and L</set_node_health>, or assign a whole new list: routing caches what it
3149 derives from the inventory, and only those paths invalidate the cache. Editing a node hash in
3150 place does not.
3151  
3152 =head2 model_pricing
3153  
3154 Served model name to pricing rule, C<'*'> as the fallback (default empty). Written by
3155 L</set_model_pricing>; read through L</pricing_for_model>.
3156  
3157 =head2 model_aliases
3158  
3159 Alias name to C<< { tiers => [...] } >>, normalized (default empty). Written by
3160 L</set_model_alias>.
3161  
3162 =head2 policies
3163  
3164 Policy name to resolved policy (see L</resolve_policy>), from the config's C<policies> or
3165 L</set_policy> (default empty).
3166  
3167 =head2 default_policy
3168  
3169 The resolved policy an unlisted key routes under -- the policy object, not its name -- or undef,
3170 which leaves unlisted keys unrestricted (default undef).
3171  
3172 =head2 key_policies
3173  
3174 Customer key id to resolved policy, built at config load (default empty). Keys that take the
3175 default policy are not in it; see L</policy_for_key>.
3176  
3177 =head2 key_names
3178  
3179 Readable name to customer key id, from the config's C<names> section (default empty). See
3180 L</key_id_for_name>.
3181  
3182 =head2 manifest_enabled
3183  
3184 Whether the config enables the provider manifest (default 0).
3185  
3186 =head2 manifest_available
3187  
3188 Whether the installed Langertha has L<Langertha::Manifest>; with it missing an enabled manifest
3189 answers C<404> instead of failing the config (default 0).
3190  
3191 =head2 key_manifests
3192  
3193 Customer key id to the canonical JSON of that key's manifest, built at config load (default
3194 empty). Read through L</manifest_for_key>.
3195  
3196 =head2 trust_key_id_header
3197  
3198 Whether a client's C<x-skeid-key-id> (or C<x-api-key-id>) header names the customer key id
3199 instead of the key it presented (default off, or C<SKEID_TRUST_KEY_ID_HEADER>; config
3200 C<routing.trust_key_id_header>). Turn it on only behind a gateway that authenticates the caller
3201 and sets that header itself: the key id selects both the routing policy and the bill.
3202  
3203 =head2 route_wait_timeout_ms
3204  
3205 How long, in milliseconds, a request for a model without an alias waits for a free node before
3206 it is answered C<429> (default 2000, or C<SKEID_ROUTE_WAIT_TIMEOUT_MS>; config
3207 C<routing.wait_timeout_ms>). An alias tier waits its own C<wait_ms> instead.
3208  
3209 =head2 route_wait_poll_ms
3210  
3211 How often, in milliseconds, a waiting request tries again (default 25, or
3212 C<SKEID_ROUTE_WAIT_POLL_MS>; config C<routing.wait_poll_ms>, at least 1). The wait is a
3213 L<Mojo::IOLoop> timer, never a sleep.
3214  
3215 =head2 usage_db_path
3216  
3217 A SQLite usage database path (default C<SKEID_USAGE_DB>, else unset). At construction it
3218 configures a SQLite store when C<usage_store> is not given; it is also the path of a C<sqlite>
3219 store config that names none. Kept in step with the store: set to a SQLite store's path, cleared
3220 for PostgreSQL. C<has_usage_db_path> and C<clear_usage_db_path> are its predicate and clearer.
3221  
3222 =head2 usage_store
3223  
3224 The usage store config (default empty: no store). Passed to C<new> it is a raw C<usage_store>
3225 config; afterwards it holds the normalized form (see
3226 L<Langertha::Skeid::UsageStore/normalize_config>). Change it through
3227 L</configure_usage_store>.
3228  
3229 =head2 store_usage_event
3230  
3231 store_usage_event => sub { my ($skeid, $event) = @_; ...; return { ok => 1 } },
3232  
3233 Optional code ref that receives every usage event instead of the configured store
3234 (C<has_store_usage_event> is its predicate). See L</Pluggable Usage Storage>.
3235  
3236 =head2 query_usage_report
3237  
3238 query_usage_report => sub { my ($skeid, $filters) = @_; ...; return { ok => 1, ... } },
3239  
3240 Optional code ref that answers L</usage_report> instead of the configured store
3241 (C<has_query_usage_report> is its predicate). It gets C<since>, C<api_key_id>, C<model> and
3242 C<limit>.
3243  
3244 =head2 on_usage_lost
3245  
3246 $skeid->on_usage_lost(sub { my ($skeid, $event, $error) = @_; ... });
3247  
3248 Optional code ref (C<has_on_usage_lost> is its predicate), called for every usage event a
3249 write-behind store (C<usage_store.flush_interval_ms>) queued and then could not write. The
3250 request was answered before the write was tried, so this is the only place that failure can be
3251 said. L<Langertha::Skeid::Proxy/build_app> sets it to the proxy's C<usage event lost> log line;
3252 without it Skeid C<warn>s. A failure of a synchronous write is the caller's to report, from the
3253 answer of L</record_usage>, and never comes here.
3254  
3255 =head2 admin_api_key
3256  
3257 The bearer token of the C</skeid/*> admin API in force; empty disables it, which the proxy
3258 answers with C<404>. Passed to C<new> it is an explicit key (see L</set_admin_api_key>) that
3259 wins over the config; otherwise it is resolved from the config and C<SKEID_ADMIN_API_KEY>
3260 whenever a config is applied -- see L</admin> for the order. Read it here; set it through
3261 L</set_admin_api_key>, since a value written through this accessor lasts only until the next
3262 changed config.
3263  
3264 =head2 key_broker
3265  
3266 Optional L<Langertha::Skeid::KeyBroker> that resolves a node's C<api_key_ref> per request
3267 (C<has_key_broker> is its predicate). L<Langertha::Skeid::Proxy/build_app> passes a
3268 L<Langertha::Skeid::KeyBroker::OpenBao> when the C<OPENBAO_*> variables are set.
3269  
3270 =head2 config_file
3271  
3272 Path of a YAML config (see L</CONFIGURATION>; C<has_config_file> is its predicate). Read at
3273 construction and again whenever its mtime moves. Give either this or L</config_loader>, not
3274 both. A path that is not an existing file dies at construction (C<config file not found: ...>);
3275 a file that disappears later keeps the config in force (see L</maybe_reload_config>).
3276  
3277 =head2 config_loader
3278  
3279 A code ref that returns the config as a hashref, instead of a C<config_file>. It is called with
3280 the Skeid object, at construction and then from C<call_function> at most once per
3281 L</config_reload_interval>.
3282  
3283 It may return C<($config, $version)>. A defined version is the change detector: the same
3284 version as last applied means nothing changed and the config is not applied again. Without a
3285 version Skeid digests the returned structure (hash keys sorted) instead. Either way an
3286 unchanged config is a no-op, and a changed one whose C<nodes> section is unchanged keeps the
3287 node list -- its inventory generation, its running capacity probes and any health set through
3288 the admin API. A code ref inside the config (a custom probe's C<code>) digests by identity, so
3289 a loader that builds a fresh closure every call should return a version.
3290  
3291 A config file follows the same rules, minus the throttle for a new file version: an mtime change
3292 whose content is unchanged applies nothing. A version that fails to parse is retried with the
3293 same bounded back-off as a failing loader, while a different mtime is read immediately. An
3294 explicit C<config.reload> does too, so a value taken from the environment (C<admin.api_key_env>,
3295 a usage store's C<password_env>) is read again only when the config itself changes.
3296  
3297 =head2 config_reload_interval
3298  
3299 The least time, in seconds, between two runs of a C<config_loader> (default 1; fractions
3300 allowed; 0 runs it on every dispatch, as before skeid #38).
3301  
3302 A loader-based config is re-read from C<call_function>, which every request passes through
3303 several times. Without a throttle every request would rerun the loader. A config file normally
3304 pays only one C<stat> per dispatch; only retries of one failed file version are throttled.
3305  
3306 =head2 last_reload_error
3307  
3308 Why the last config reload failed, or undef when the last one succeeded. A failed reload keeps
3309 the previous config in force; see L</maybe_reload_config>. C<last_reload_error_at> is when (epoch
3310 seconds), C<reload_failures> how many reloads in a row have failed.
3311  
3312 =head2 capacity_max_age_ms
3313  
3314 How long a capacity reading is trusted, in milliseconds (default 5000, 0 disables expiry).
3315  
3316 A stale reading is worse than none: it describes a node as it was, and admission acts on it as
3317 if it were now. Past this age a reading is ignored and C<inflight> decides again, which is the
3318 same behaviour as having configured no probe at all (ADR 0009).
3319  
3320 =head2 worker_count
3321  
3322 How many worker processes share this configuration (default 1).
3323  
3324 C<inflight> and C<max_conns> are per-process, so N workers would each admit up to C<max_conns>
3325 to a node that can only serve one number — C<max_conns: 8> across 4 workers would permit 32,
3326 silently. Setting this makes each worker take its share instead (ADR 0010). Anything on a timer
3327 is spread the same way, so the process group's aggregate poll rate stays what was configured.
3328  
3329 =head2 frontend_count
3330  
3331 How many separate Skeid frontends stand in front of one node (default 1).
3332  
3333 C<worker_count> partitions C<max_conns> across the prefork workers of one process; this
3334 partitions it across the distinct Skeid hosts sharing a node — a number only the operator
3335 knows, because two frontends are two processes on two machines with nothing between them to
3336 count each other's C<inflight> (there is no probe and no shared state; that absence is the
3337 whole reason this has to be declared rather than detected). With F frontends each admits its
3338 share C<max_conns/F>, so the group as a whole never admits more than the node was configured
3339 for (ADR 0009, ADR 0012).
3340  
3341 It composes with C<worker_count>: the two divisors multiply, so one worker's share is
3342 C<max_conns/(F*N)> — partitioned across frontends first, then across workers, which integer
3343 division makes the same thing either way. Unlike the worker divisor it does not scale anything
3344 on a timer: separate frontends each run their own probes and hold their own vault token, the
3345 same reason vault renewal is not scaled per worker (ADR 0010).
3346  
3347 Explicit and opt-in: the default 1 is today's behaviour, unchanged. An operator who runs two
3348 frontends and forgets to say so over-admits the node by a factor of two, silently — which is
3349 exactly the failure this field exists to prevent.
3350  
3351 =head2 registry_enabled
3352  
3353 Whether this Skeid publishes its registry snapshot on C<GET /skeid/registry/snapshot> (default
3354 off; ADR 0017). Set by the config's C<registry> block:
3355  
3356 registry:
3357 enabled: true
3358 secret_env: SKEID_REGISTRY_SECRET # required when enabled; the HMAC key
3359 ttl_s: 10 # how long a snapshot may be believed
3360 instance_id: skeid-b # default: the hostname
3361 error_window_s: 60 # how far back errors_in_window counts
3362 read_key_env: SKEID_REGISTRY_READ_KEY # optional; a bearer for the snapshot route only
3363  
3364 The fronting tier reads the snapshot with L<Langertha::Skeid::CapacityProbe::Registry>. The
3365 secret is taken from the environment only and kept in memory (ADR 0003); an enabled registry
3366 whose variable is empty or shorter than 32 bytes does not load, because a snapshot is never
3367 published unsigned or weakly signed. Neither does one without a credential to read it: an admin
3368 API key or a registry read key.
3369  
3370 C<read_key_env> names the variable holding the B<registry read key> (skeid #49). The snapshot
3371 route accepts it as a bearer token besides the admin API key; it opens no other route, so a
3372 fronting tier holding it cannot add nodes or flip health. A named variable that is empty does
3373 not load. C<registry_secret>, C<registry_read_key>, C<registry_ttl_s>, C<registry_instance_id>
3374 and C<registry_error_window_s> hold the other fields.
3375  
3376 =head1 METHODS
3377  
3378 =head2 add_node
3379  
3380 $skeid->add_node(id => 'gpu-1', url => 'http://gpu-1:8000/v1', model => 'qwen3-32b',
3381 tags => ['local'], max_conns => 8);
3382  
3383 Adds a node, replacing any node with the same id. Takes the fields of a config C<nodes> entry
3384 and fills in their defaults (see L</nodes>). Returns 1. Croaks without C<id> or C<url>, on an
3385 unknown C<engine>, and on a C<registry> capacity block that
3386 L<Langertha::Skeid::CapacityProbe::Registry/validate_config> rejects. The C<nodes.add> function
3387 and C<POST /skeid/nodes> call it.
3388  
3389 =head2 remove_node
3390  
3391 my $removed = $skeid->remove_node('gpu-1');
3392  
3393 Removes a node, and with it its capacity reading and failure history, so a node later added
3394 under the same id starts clean. Returns 1 when a node was removed, else 0.
3395  
3396 =head2 normalize_tags
3397  
3398 my $tags = Langertha::Skeid->normalize_tags(['Local', 'gb10']);
3399 my $tags = Langertha::Skeid->normalize_tags('local, gb10');
3400  
3401 Tags are lowercased, trimmed, de-duplicated and kept in the order first seen. A plain string is
3402 accepted and split on commas or whitespace, because a hand-written config says
3403 C<tags: local, gb10> at least as often as it says a YAML list.
3404  
3405 =head2 list_nodes
3406  
3407 my $nodes = $skeid->list_nodes;
3408  
3409 The inventory as an arrayref of shallow copies of the node hashes.
3410  
3411 =head2 list_models
3412  
3413 my $models = $skeid->list_models(api_key_id => $key_id);
3414 # [ { model => 'house-model', engine => '' }, { model => 'qwen3-32b', engine => 'vllm' } ]
3415  
3416 The names a client can put in C<model>, sorted by name, each once: the distinct C<model> of the
3417 nodes plus the alias names. A node without a C<model> lists nothing -- it matches any name, so
3418 none reaches it in particular. A name that is both a node model and an alias is one entry.
3419 C<engine> is the first node's engine for a node model, empty for an alias.
3420  
3421 The list is narrowed by the policy of C<api_key_id> (none means the default policy), so a key is
3422 never shown a name L</route_plan> would refuse it: a name its C<models> do not grant is left out,
3423 an alias with every tier denied is left out, and a node model that only nodes carrying a denied
3424 tag serve is left out. This backs C</v1/models> and C</api/tags>.
3425  
3426 =head2 set_node_health
3427  
3428 $skeid->set_node_health('gpu-1', 0); # take it out of rotation
3429  
3430 Sets the operator health flag. An unhealthy node is not eligible for routing. Health is operator
3431 state: no error, timeout or C<429> ever sets it. Returns 1 when the node exists, else 0. Setting
3432 the value it already has changes nothing, round-robin position included.
3433  
3434 =head2 set_model_pricing
3435  
3436 $skeid->set_model_pricing('gpt-4o-mini', {
3437 input_per_million => 0.15,
3438 output_per_million => 0.60,
3439 cached_input_per_million => 0.075, # optional
3440 cache_write_per_million => 0.1875, # optional
3441 });
3442  
3443 Sets the pricing rule for one served model (C<'*'> is the fallback) and returns it as stored.
3444 Absent input and output rates are 0. Croaks without a model or a pricing hash, and on a cache
3445 rate that is not a number C<E<gt>= 0>. On a Langertha that cannot price prompt-cache tokens the
3446 cache rates are dropped, with one warning per process.
3447  
3448 =head2 pricing_for_model
3449  
3450 my $rule = $skeid->pricing_for_model('gpt-4o-mini');
3451  
3452 The rule for a model, else the C<'*'> rule, else a rule that prices everything at 0.
3453  
3454 =head2 reload_config
3455  
3456 my $config = $skeid->reload_config;
3457  
3458 Reads the config source and applies it, returning the config hashref. A config whose fingerprint
3459 matches the one last applied changes nothing. Dies when the source cannot be read or the config
3460 does not apply; the previous config then stays in force and L</reload_status> reports the
3461 failure. The C<config.reload> function calls it; the request path uses
3462 L</maybe_reload_config>, which never dies.
3463  
3464 =head2 reload_status
3465  
3466 my $status = $skeid->reload_status;
3467 # { ok => 0, error => '...', failed_at => '2026-09-25T16:08:30Z', failures => 3 }
3468  
3469 Whether the last config reload succeeded, and if not, why, when, and how many times in a row.
3470 Served by the admin route C<GET /skeid/config>; the public C</health> carries only C<ok>,
3471 C<failed_at> and C<failures>, never the message, which can name customers and models.
3472  
3473 =head2 set_admin_api_key
3474  
3475 $skeid->set_admin_api_key($key); # explicit: wins over the config, on every reload
3476 $skeid->set_admin_api_key(''); # back to the config's key, or SKEID_ADMIN_API_KEY
3477  
3478 Sets the explicit admin API key -- what C<skeid serve --admin-api-key> and
3479 C<< build_app(admin_api_key => ...) >> set, and what an C<admin_api_key> passed to C<new> is. It
3480 outranks the config: a reload re-applies the order of L</admin> under it instead of replacing it.
3481 An empty or undefined key clears it, and the key the config resolved to takes over at once.
3482 Returns the admin API key now in force.
3483  
3484 =head2 maybe_reload_config
3485  
3486 my $applied = $skeid->maybe_reload_config;
3487  
3488 Reloads the config if its source may have changed: the file's mtime moved, or a
3489 C<config_loader> is due (L</config_reload_interval>). Returns true when a changed config was
3490 applied. C<call_function> runs it on every dispatch, so it never dies: a reload that fails is
3491 logged, recorded in L</reload_status>, and the request goes on under the config that was in
3492 force before (the reload is all or nothing). A failing source is then retried with a back-off --
3493 the interval doubling per failure, from at least a second up to a minute. A loader that keeps
3494 returning the same broken config is not applied again; a changed config-file mtime bypasses the
3495 failed version's retry window. A config file that has disappeared is not a reload at all: the
3496 config in force stays, and the loss is warned once until the file is back. Only construction
3497 and an explicit C<config.reload> still die on a bad or missing config.
3498  
3499 =head2 manifest_for_key
3500  
3501 my $json = $skeid->manifest_for_key($api_key_id); # UTF-8 JSON bytes, or undef
3502  
3503 The provider manifest published to a customer key id, as canonical JSON, or undef when the
3504 key has no C<manifest:> grant, the manifest is disabled, or this Langertha has no
3505 L<Langertha::Manifest>. Built at config load; see L</Provider Manifest>.
3506  
3507 =head2 configure_usage_store
3508  
3509 $skeid->configure_usage_store({ backend => 'jsonlog', path => '/var/log/skeid/events/' });
3510  
3511 Normalizes a C<usage_store> config and, when it differs from the current one, prepares the new
3512 store before disconnecting the old. Returns the normalized config. Croaks on a config
3513 L<Langertha::Skeid::UsageStore/normalize_config> rejects and on a store that fails to prepare,
3514 leaving the old store in place. The C<usage.configure> function calls it.
3515  
3516 =head2 supported_engine_ids
3517  
3518 my $ids = $skeid->supported_engine_ids; # [ 'aki', 'akiopenai', 'anthropic', ... ]
3519  
3520 The engine ids a node may name, sorted: a built-in list, plus whatever
3521 C<< Langertha->available_engine_ids >> reports when the installed Langertha has it.
3522  
3523 =head2 normalize_engine_id
3524  
3525 my $id = $skeid->normalize_engine_id('Langertha::Engine::vLLM'); # 'vllm'
3526  
3527 Lowercases an engine name and strips a C<Langertha::Engine::> or C<LangerthaX::Engine::>
3528 prefix. Returns the empty string for an empty value and croaks on an id that is not in
3529 L</supported_engine_ids>.
3530  
3531 =head2 record_usage
3532  
3533 my $res = $skeid->record_usage(
3534 api_key_id => $key_id, model => 'qwen3-32b', requested_model => 'house-model',
3535 node_id => 'gpu-1', status_code => 200, ok => 1, duration_ms => 840,
3536 metrics => $normalized, # from normalize_metrics
3537 );
3538  
3539 Builds one usage event and hands it to the sink: the L</store_usage_event> callback, a subclass's
3540 C<_store_usage_event>, or the configured store. Returns the sink's answer, or
3541 C<< { ok => 0, enabled => 0, error => 'usage_store not configured' } >> without building an
3542 event when there is no sink.
3543  
3544 The event carries C<created_at>, C<request_id>, C<api_format>, C<endpoint>, C<api_key_id>,
3545 C<provider>, C<engine>, C<model> (served), C<requested_model> (default C<model>), C<node_id>,
3546 C<route_url>, C<status_code>, C<ok>, C<duration_ms>, C<error_type>, C<error_message>, and from
3547 C<metrics> the token counts (C<input_tokens>, C<output_tokens>, C<total_tokens>,
3548 C<cached_tokens>, C<cache_write_tokens>), C<tool_calls> and the costs (C<cost_input_usd>,
3549 C<cost_output_usd>, C<cost_total_usd>, C<cost_cache_read_usd>, C<cost_cache_write_usd>). Costs
3550 arrive already priced; nothing is priced here. C<content_bytes> is set only when given. The
3551 C<usage.record> function calls it.
3552  
3553 =head2 flush_usage
3554  
3555 my $res = $skeid->flush_usage;
3556  
3557 Writes the usage events a write-behind store still holds (see
3558 L<Langertha::Skeid::UsageStore::DBI/flush>) and returns its answer, or C<< { ok => 1, written
3559 => 0 } >> when the store holds nothing back. F<bin/skeid> calls it when the server stops, and an
3560 application embedding the proxy should call it before it exits: queued events live in memory
3561 only. Replacing the store on a reload and destroying this object flush as well.
3562  
3563 =head2 usage_report
3564  
3565 my $report = $skeid->usage_report(since => '2026-09-01T00:00:00Z', api_key_id => $id,
3566 model => 'qwen3-32b', limit => 50);
3567  
3568 Asks the L</query_usage_report> callback, a subclass's C<_query_usage_report> or the configured
3569 store for a report (its shape: L<Langertha::Skeid::UsageStore>). Empty filters are dropped;
3570 C<limit> defaults to 20 and is capped at 500. Without a store it returns
3571 C<< { ok => 0, enabled => 0, error => 'usage_store not configured' } >>. The C<usage.report>
3572 function, C<GET /skeid/usage> and C<skeid usage> call it.
3573  
3574 =head2 estimate_cost
3575  
3576 my $cost = $skeid->estimate_cost(model => 'gpt-4o-mini',
3577 usage => { prompt_tokens => 1000, completion_tokens => 200 });
3578  
3579 Prices a usage with the model's rule (L</pricing_for_model>) or an explicit C<pricing> rule, and
3580 returns the hash form of the L<Langertha::Cost>. The usage is a hash, a L<Langertha::Usage>, or
3581 read from a C<response>. The C<metrics.estimate_cost> function calls it.
3582  
3583 =head2 normalize_metrics
3584  
3585 my $metrics = $skeid->normalize_metrics(model => 'gpt-4o-mini', response => $upstream_body,
3586 tool_calls => \@calls, duration_ms => 840, engine => 'openaibase', route => '/v1/chat/completions');
3587  
3588 What a usage event is built from: the usage (as for L</estimate_cost>) priced into a
3589 L<Langertha::UsageRecord>, returned as its hash, with C<tool_calls> counted by name. Adds
3590 C<cached_tokens> and C<cache_write_tokens> when the installed L<Langertha::Usage> reads them.
3591 Optional C<provider>, C<started_at>, C<finished_at> and C<pricing_version> are carried into the
3592 record. The C<metrics.normalize> function calls it; the proxy runs it on every upstream answer,
3593 streamed or not.
3594  
3595 =head2 worker_max_conns
3596  
3597 my $share = $skeid->worker_max_conns($node);
3598  
3599 This process's share of a node's C<max_conns> (ADR 0010, ADR 0012). With one worker and one
3600 frontend that is the configured value; otherwise it is the configured value divided by the
3601 number of processes sharing the node — C<frontend_count> separate Skeid hosts times the
3602 C<worker_count> prefork workers of this one — so the group as a whole never admits more than was
3603 asked for.
3604  
3605 Never less than 1 when a limit is set: a process that may admit nothing is a process that does
3606 nothing. That means a C<max_conns> below that combined process count cannot be honoured, and
3607 L</worker_share_warnings> is what says so out loud.
3608  
3609 =head2 worker_share_warnings
3610  
3611 warn $_ for @{ $skeid->worker_share_warnings };
3612  
3613 The nodes whose C<max_conns> cannot be divided among the processes sharing them without
3614 exceeding it — C<frontend_count> frontends times C<worker_count> workers. Returned rather than
3615 warned so the caller decides where they go; C<bin/skeid> prints them at startup.
3616  
3617 Silence here would be the bad kind: the operator wrote a number, and the process group is about
3618 to ignore it.
3619  
3620 =head2 set_model_alias
3621  
3622 $skeid->set_model_alias('our-fast-model', {
3623 tiers => [
3624 { tags => ['local'], model => 'qwen3-32b', wait_ms => 200 },
3625 { tags => ['cloud'], model => 'llama-3.3-70b-versatile' },
3626 ],
3627 });
3628  
3629 Defines a client-facing model name as an ordered list of tiers. A bare arrayref of tiers is
3630 accepted as shorthand for C<< { tiers => [...] } >>.
3631  
3632 Per tier: C<tags> selects nodes, C<model> is the model actually asked of them (defaulting to
3633 the alias name itself, for the case where nodes carry that name), C<engine> optionally
3634 constrains the engine, and C<wait_ms> is how long to wait for capacity in this tier before
3635 falling through to the next.
3636  
3637 C<wait_ms> defaults to B<0>. Writing tiers means "try here, then there"; waiting is the
3638 exception you opt into, and a tier that waits by default would send traffic to a paid cloud
3639 only after a delay nobody asked for -- or, worse, make a cheap tier look slow.
3640  
3641 =head2 set_policy
3642  
3643 $skeid->set_policy('standard-local-only', { deny_tags => ['cloud'] });
3644  
3645 Defines a named policy profile. Profiles are the "standard setups" most customers take
3646 unchanged; a customer needing something precise gets the profile plus overrides, or a profile
3647 of their own.
3648  
3649 =head2 resolve_policy
3650  
3651 my $policy = $skeid->resolve_policy({ models => ['house-model'], deny_tags => ['cloud'] });
3652  
3653 Turns a policy spec into the immutable form routing uses: C<models> (or C<aliases>) becomes a
3654 lookup hash of the requested model names the key may ask for, absent meaning all of them, and
3655 C<deny_tags> becomes a normalized tag list.
3656  
3657 =head2 key_id_for_key
3658  
3659 my $id = Langertha::Skeid->key_id_for_key('sk-alice-secret'); # k_5f0e...
3660  
3661 The customer key id derived from the presented API key. This is the name a C<keys:> entry has
3662 to use, and C<skeid keyid> prints it, because the config must be able to name a customer
3663 without holding that customer's key.
3664  
3665 It is the full SHA-1 hex digest of the key (160 bits), not a secret: it identifies, it does not
3666 authenticate. What authenticates is that the caller presented the key it was derived from.
3667  
3668 Before ADR 0016 the id was the first 12 hex digits of the same digest (C<k_5f0e1a2b3c4d>), so
3669 an old id is the prefix of the new one. A config may still name a customer by its short id:
3670 it matches the key whose full id starts with it, with a one-time deprecation warning at
3671 config load, and a config that lists both a short id and a full id it is the prefix of fails
3672 to load. Usage events keep the id they were recorded under -- events from before the change
3673 carry the short id, later ones the full id; nothing is migrated.
3674  
3675 =head2 policy_for_key
3676  
3677 my $policy = $skeid->policy_for_key($key_id); # k_5f0e...
3678  
3679 The policy a customer key routes under. Unlisted keys take the default policy, which is what
3680 makes a deployment with ten thousand identically-configured customers a config with zero key
3681 entries. Returns undef when no policies are configured at all.
3682  
3683 =head2 key_id_for_name
3684  
3685 my $id = $skeid->key_id_for_name('alice'); # k_5f0e1a2b3c4de5f60718293a4b5c6d7e8f901a2b, or undef
3686  
3687 The customer key id a readable name maps to under the config C<names:> section, or undef when
3688 the name is not registered. The registry is a config-authoring convenience -- it lets a
3689 C<keys:> entry be written by name and confines key rotation to one line -- and is resolved to
3690 ids at config load, so it never appears on the request path.
3691  
3692 =head2 route_plan
3693  
3694 my $plan = $skeid->route_plan(model => 'our-fast-model', api_key_id => $key_id);
3695 # { tiers => [...], permitted => 1, reason => '' }
3696  
3697 The ordered tiers to try for a requested model, under the policy of the key that asked. A model
3698 with no alias yields a single implicit tier that selects on the name itself and inherits the
3699 global C<route_wait_timeout_ms>, which is what makes an aliasless config behave exactly as it
3700 did before aliases existed.
3701  
3702 C<permitted> is false when the policy does not grant this model, or when every tier of it was
3703 denied. Both mean the same thing to a caller — this key may not reach this model — and neither
3704 is a capacity problem, so they must not be reported as one.
3705  
3706 Tiers carry the policy's C<deny_tags> down into node selection. Dropping a denied tier is only
3707 the reporting half; without the node-level filter, a key denied C<cloud> could still reach a
3708 cloud node by asking for its raw model name instead of the alias.
3709  
3710 =head2 select_nodes
3711  
3712 my $local = $skeid->select_nodes(tags => ['local']);
3713  
3714 Nodes carrying every listed tag, as copies. No tags selects everything. Selection is by tag,
3715 never by node id, so a config can talk about C<local> or C<cloud> without naming machines.
3716 C<deny_tags> drops every node carrying any of those tags. Health is not considered. The
3717 C<nodes.select> function calls it.
3718  
3719 =head2 pick_node
3720  
3721 my $node = $skeid->pick_node(model => 'qwen3-32b', tags => ['local'], deny_tags => ['cloud']);
3722  
3723 The next node for a selection by weighted round-robin (over the eligible nodes, ordered by id),
3724 skipping every node admission would refuse right now. Returns a copy of the node with
3725 C<inflight> and C<route_key> added, or nothing. Picking does not admit: the caller still has to
3726 L</start_request>, which can refuse when another request took the slot in between. The
3727 C<route.next> function calls it.
3728  
3729 =head2 route_state
3730  
3731 my $state = $skeid->route_state(model => 'qwen3-32b', tags => ['local']);
3732 # { model, engine, tags, deny_tags, eligible_count, available_count,
3733 # has_eligible, has_available }
3734  
3735 How many nodes a selection matches (eligible) and how many of those admission would take now
3736 (available). No eligible node is a C<503>; eligible but none available is worth waiting for. The
3737 C<route.state> function calls it.
3738  
3739 =head2 set_capacity_reading
3740  
3741 $skeid->set_capacity_reading('gpu-1', used => 6, limit => 8, source => 'prometheus');
3742 $skeid->set_capacity_reading('groq-1', retry_after_ms => 2000, source => 'ratelimit');
3743  
3744 Records what a probe found. One shape for every probe, so admission never learns where a
3745 number came from (ADR 0009):
3746  
3747 =over 4
3748  
3749 =item * C<used> / C<limit> — occupancy. C<limit> 0 or absent means the probe measured
3750 something it cannot turn into a ceiling, so it does not constrain admission.
3751  
3752 =item * C<retry_after_ms> — do not send anything here until it elapses. What a C<429> means.
3753  
3754 =item * C<source> — which probe, for reports. Never consulted by admission. C<quota> -- which of
3755 a provider's quotas (C<requests>, C<tokens>) the reading is about -- likewise.
3756  
3757 =item * C<at> — when the reading was taken (default now), and C<expires_at> — an absolute
3758 moment after which it is dropped even inside L</capacity_max_age_ms>. The registry probe uses
3759 both: a snapshot is as old as its C<generated_at>, and never outlives its own C<ttl>.
3760  
3761 =item * C<interval_ms> — how often this source reports, for a probe on a timer. Stored with the
3762 reading; it sets how long a tighter reading can hold a looser one from another source off
3763 (below). A passive observation (a response's rate-limit headers) passes none.
3764  
3765 =back
3766  
3767 A reading only ever narrows what C<max_conns> already allows, and expires after
3768 L</capacity_max_age_ms>. Probing is a background activity: calling this from a request handler
3769 is a bug unless the reading was a by-product of a response already in hand.
3770  
3771 B<The tighter reading wins across sources, while it is current> (ADR 0017). A source always
3772 replaces its own last reading. A reading from a different source is held off by the current one
3773 only when the current one is tighter (a pending backoff is tightest, then C<used/limit>, then a
3774 reading without a limit) B<and> either
3775  
3776 =over 4
3777  
3778 =item * it carries a pending backoff, or
3779  
3780 =item * it is younger than the longer of the two sources' C<interval_ms> -- neither has had a
3781 full poll since the tighter reading was taken.
3782  
3783 =back
3784  
3785 Otherwise the incoming reading replaces it. So a registry snapshot saying "empty" cannot lift a
3786 C<429> backoff a response just recorded; a fresh, tight probe reading is not lifted by a roomy
3787 response or by a faster, looser probe before its own next poll; and a passive reading that is
3788 never refreshed (C<remaining: 0> with no reset, from the last response before traffic stopped)
3789 cannot keep a fresh probe out for longer than one of that probe's polls. Returns the reading in
3790 force afterwards.
3791  
3792 =head2 capacity_reading
3793  
3794 my $reading = $skeid->capacity_reading('gpu-1'); # or nothing
3795  
3796 The node's current capacity reading, or nothing when no probe has reported or the last report
3797 has aged out. A backoff outlives the age limit: a provider that said "not for another 30
3798 seconds" told us something that is still true.
3799  
3800 =head2 forget_capacity
3801  
3802 $skeid->forget_capacity('gpu-1'); # or all of them with no argument
3803 $skeid->forget_capacity('gpu-1', source => 'registry'); # only if that source holds it
3804  
3805 Drops probe readings, so C<inflight> decides again. What a node removal calls, and what a probe
3806 calls when it can no longer reach its source — reporting nothing beats reporting last hour.
3807  
3808 With C<source>, the reading is dropped only when that source wrote it. A probe forgetting what
3809 I<it> said must not wipe a backoff another source recorded (ADR 0017).
3810  
3811 =head2 capacity_header_names
3812  
3813 The response headers worth looking at, so a caller on the request path can pull those few by
3814 name instead of walking every header of every response.
3815  
3816 =head2 observe_response_headers
3817  
3818 $skeid->observe_response_headers('groq-1', \%headers, status => 429);
3819  
3820 The zero-cost probe: commercial providers do not publish queue depth, but they do put their
3821 rate-limit state on every response Skeid already receives. Reading it costs no extra request
3822 (ADR 0009).
3823  
3824 Providers meter requests and tokens separately, and for an LLM API the token budget is usually
3825 what runs out first. Both are read, and the one closest to exhausted decides — compared as a
3826 fraction, since the two are not the same unit.
3827  
3828 C<Retry-After> on a C<429> becomes a backoff. It deliberately does B<not> touch C<healthy>:
3829 rate-limited is busy, not broken, and nothing would ever flip that back.
3830  
3831 Returns the reading it recorded, or nothing when the response said nothing useful.
3832  
3833 =head2 start_request
3834  
3835 $skeid->start_request('gpu-1') or ...; # refused
3836  
3837 Admits one request to a node and counts it in C<inflight>. Returns 1 when admitted, 0 when the
3838 node is unknown, unhealthy or full. B<Every> 1 must be paired with a L</finish_request> on every
3839 path -- errors, timeouts, client aborts -- or the node loses that slot until restart. The
3840 C<request.start> function calls it.
3841  
3842 =head2 finish_request
3843  
3844 $skeid->finish_request('gpu-1', ok => 1, duration_ms => 840);
3845 $skeid->finish_request('gpu-1', aborted => 1); # the client hung up
3846  
3847 Releases the slot L</start_request> took and counts the outcome for L</node_metrics>. There are
3848 three outcomes: C<ok>, failed (neither C<ok> nor C<aborted>), and C<aborted> -- the client went
3849 away, which says nothing about the node. A failed request counts toward the registry snapshot's
3850 C<errors_in_window> and C<last_failure_at>; an aborted one is counted apart and toward neither.
3851 C<aborted> wins over C<ok>. Never touches C<healthy>. Returns 1. The C<request.finish> function calls it.
3852  
3853 =head2 registry_snapshot
3854  
3855 my $snapshot = $skeid->registry_snapshot;
3856  
3857 What this Skeid publishes to a fronting tier (ADR 0017): schema C<version> 1, C<instance>,
3858 C<generated_at>, C<ttl>, C<workers>, and per node C<id>, C<tags>, C<healthy>, C<inflight>,
3859 C<max_conns> (this process's share), C<errors_in_window>, C<last_failure_at> and, when a
3860 current reading exists, C<capacity> (C<used>, C<limit>, C<source>, C<retry_after>).
3861  
3862 Built from a whitelist, so it cannot carry what it must not: no node URL, no key reference, no
3863 metadata, no customer key id, no policy, no usage. L<Langertha::Skeid::Registry> signs it.
3864  
3865 =head2 node_metrics
3866  
3867 my $one = $skeid->node_metrics('gpu-1');
3868 my $all = $skeid->node_metrics;
3869  
3870 Volatile per-process counters for operations, never billed: C<node_id>, C<inflight>,
3871 C<started>, C<ok>, C<error>, C<aborted>, C<duration_ms_total>, and C<capacity> while a current reading
3872 exists. With no id, an arrayref with one entry per node. Served by C<GET /skeid/metrics/nodes>.
3873  
3874 =head2 call_function
3875  
3876 my $result = $skeid->call_function('route.plan', { model => 'house-model', api_key_id => $id });
3877  
3878 The command surface the proxy drives Skeid through. Every call first runs
3879 L</maybe_reload_config>. Croaks on an unknown name, on args that are not a hashref, and where a
3880 function names a required argument.
3881  
3882 function args returns
3883 metrics.estimate_cost as estimate_cost estimate_cost
3884 metrics.normalize as normalize_metrics normalize_metrics
3885 pricing.set model, pricing the stored rule
3886 nodes.add a node { ok }
3887 nodes.remove id { ok }
3888 nodes.list { nodes }
3889 nodes.select tags, deny_tags { nodes } (select_nodes)
3890 nodes.set_health id, healthy { ok }
3891 nodes.metrics id (optional) { metrics }
3892 alias.set name, alias (or the tiers inline) { ok }
3893 policy.set name, policy (or the spec inline) { ok }
3894 policy.for_key api_key_id { policy }
3895 route.plan model, engine, api_key_id route_plan
3896 route.next model, engine, tags, deny_tags { node } (pick_node)
3897 route.state model, engine, tags, deny_tags route_state
3898 capacity.set id, and the reading { capacity }
3899 capacity.get id { capacity }
3900 capacity.observe id, headers, status { capacity }
3901 capacity.forget id (optional) { ok }
3902 request.start id { ok }
3903 request.finish id, ok|aborted, duration_ms { ok }
3904 config.reload { config } (dies on failure)
3905 config.status reload_status
3906 usage.record as record_usage record_usage
3907 usage.report since, api_key_id, model, limit usage_report
3908 usage.configure usage_store (or the config inline) { usage_store }
3909 engines.list { engines }
3910  
3911 Add a function here rather than reaching into the object from the app.
3912  
3913 =head1 SEE ALSO
3914  
3915 =over 4
3916  
3917 =item * L<Langertha::Skeid::Proxy> -- the HTTP application on top of this control plane, and its routes
3918  
3919 =item * L<skeid> -- C<serve>, C<usage> and C<keyid>
3920  
3921 =item * L<Langertha::Skeid::CapacityProbe> -- node capacity probes
3922  
3923 =item * L<Langertha::Skeid::UsageStore> -- where usage events go
3924  
3925 =item * L<Langertha::Skeid::KeyBroker> -- resolving a node's C<api_key_ref>
3926  
3927 =item * L<Langertha::Skeid::Registry> -- the signed Skeid-to-Skeid snapshot
3928  
3929 =item * L<Langertha> -- engines, usage, pricing
3930  
3931 =back
3932  
3933 =head1 SUPPORT
3934  
3935 =head2 Issues
3936  
3937 Please report bugs and feature requests on GitHub at
3938 L<https://github.com/Getty/langertha-skeid/issues>.
3939  
3940 =head2 IRC
3941  
3942 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
3943  
3944 =head1 CONTRIBUTING
3945  
3946 Contributions are welcome! Please fork the repository and submit a pull request.
3947  
3948 =head1 AUTHOR
3949  
3950 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
3951  
3952 =head1 COPYRIGHT AND LICENSE
3953  
3954 This software is copyright (c) 2026 by Torsten Raudssus.
3955  
3956 This is free software; you can redistribute it and/or modify it under
3957 the same terms as the Perl 5 programming language system itself.
3958  
3959 =cut
« blib/lib/Langertha/Skeid/Protocol/Anthropic.pm ↑ Summary blib/lib/Langertha/Skeid/UsageStore/JsonLog.pm »