blib/lib/Langertha/Knarr/Tracing.pm

filter: Statementstmt 93.8% 257 / 274 Branchbran 77.7% 115 / 148 Conditioncond 56.7% 42 / 74 MC/DCmcdc 27.2% 12 / 44 Subroutinesub 100% 46 / 46 Podpod 75.0% 3 / 4 totaltotal 80.5% 475 / 590 CC 107 SCAR 26.3
CC
107
Cov
83%
_input_buckets
85.8
end_trace
25.2
_tool_calls_full
12.3
CRAP 13.9
« blib/lib/Langertha/Knarr/Handler/Passthrough.pm ↑ Summary blib/lib/Langertha/Knarr/Router.pm »
1 package Langertha::Knarr::Tracing;
2 18 our $VERSION = '1.102';
3 # ABSTRACT: Automatic Langfuse tracing per proxy request
4 18 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 18 ▶use Time::HiRes qw( gettimeofday );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 18 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 18 ▶use Scalar::Util qw( blessed looks_like_number );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 18 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 18 ▶use Langertha::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 18 ▶use MIME::Base64 qw( encode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 18 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 18 ▶use Langertha::Knarr::Image;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 18 ▶use HTTP::Request ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 18 ▶use Net::Async::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 18 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17  
18 18 has config => (
19 is => 'ro',
20 required => 1,
21 );
22  
23  
24 18 has _enabled => (
25 is => 'lazy',
26 builder => '_build__enabled',
27 );
28  
29 62 ▶sub _build__enabled {
Subroutine _build__enabled: called CC=5 SCAR=16.4
30 62 my ($self) = @_;
31 62 my $lf = $self->config->langfuse;
32 62 ▶ my $pub = $lf->{public_key} // _strip_quotes($ENV{LANGFUSE_PUBLIC_KEY});
Condition66%2/3
$lf->{"public_key"} // _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
l!l&&r!l&&!r
5507
MC/DC50%1/2
$lf->{"public_key"} // _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
$lf->{"public_key"} _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
Truth table66%2/3
A // B
A= $lf->{"public_key"}B= _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
ABresult
1X1
011
000
33 62 ▶ my $sec = $lf->{secret_key} // _strip_quotes($ENV{LANGFUSE_SECRET_KEY});
Condition66%2/3
$lf->{"secret_key"} // _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
l!l&&r!l&&!r
5507
MC/DC50%1/2
$lf->{"secret_key"} // _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
$lf->{"secret_key"} _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
Truth table66%2/3
A // B
A= $lf->{"secret_key"}B= _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
ABresult
1X1
011
000
34 62 ▶ return ($pub && $sec) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$pub && $sec ? : 55 7 62
Condition66%2/3
$pub and $sec
!ll&&!rl&&r
7055
MC/DC50%1/2
$pub and $sec
$pub $sec
Truth table66%2/3
A and B
A= $pubB= $sec
ABresult
0X0
100
111
35 }
36  
37 18 has _public_key => (
38 is => 'lazy',
39 builder => '_build__public_key',
40 );
41  
42 45 ▶sub _build__public_key {
Subroutine _build__public_key: called CC=2 SCAR=8.1
43 45 my ($self) = @_;
44 45 ▶ return $self->config->langfuse->{public_key} // _strip_quotes($ENV{LANGFUSE_PUBLIC_KEY});
Condition33%1/3
$self->config->langfuse->{"public_key"} // _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
l!l&&r!l&&!r
4500
MC/DC0%0/2
$self->config->langfuse->{"public_key"} // _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
$self->config->langfuse->{"public_key"} _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
Truth table33%1/3
A // B
A= $self->config->langfuse->{"public_key"}B= _strip_quotes($ENV{"LANGFUSE_PUBLIC_KEY"})
ABresult
1X1
011
000
45 }
46  
47 18 has _secret_key => (
48 is => 'lazy',
49 builder => '_build__secret_key',
50 );
51  
52 45 ▶sub _build__secret_key {
Subroutine _build__secret_key: called CC=2 SCAR=8.1
53 45 my ($self) = @_;
54 45 ▶ return $self->config->langfuse->{secret_key} // _strip_quotes($ENV{LANGFUSE_SECRET_KEY});
Condition33%1/3
$self->config->langfuse->{"secret_key"} // _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
l!l&&r!l&&!r
4500
MC/DC0%0/2
$self->config->langfuse->{"secret_key"} // _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
$self->config->langfuse->{"secret_key"} _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
Truth table33%1/3
A // B
A= $self->config->langfuse->{"secret_key"}B= _strip_quotes($ENV{"LANGFUSE_SECRET_KEY"})
ABresult
1X1
011
000
55 }
56  
57 18 has _url => (
58 is => 'lazy',
59 builder => '_build__url',
60 );
61  
62 18 has trace_name => (
63 is => 'lazy',
64 builder => '_build_trace_name',
65 );
66  
67  
68 50 ▶sub _build_trace_name {
Subroutine _build_trace_name: called CC=4 SCAR=14.2
69 50 my ($self) = @_;
70 return $self->config->langfuse->{trace_name}
71 // _strip_quotes($ENV{LANGFUSE_TRACE_NAME})
72 // _strip_quotes($ENV{KNARR_TRACE_NAME})
73 50 ▶ // 'knarr-proxy';
Condition75%6/8
(($self->config->langfuse->{"trace_name"} // _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})) // _strip_quotes($ENV{"KNARR_TRACE_NAME"})) // "knarr-proxy"
l!l
1337
($self->config->langfuse->{"trace_name"} // _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})) // _strip_quotes($ENV{"KNARR_TRACE_NAME"})
l!l&&r!l&&!r
13037
$self->config->langfuse->{"trace_name"} // _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})
l!l&&r!l&&!r
13037
MC/DC33%1/3
(($self->config->langfuse->{"trace_name"} // _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})) // _strip_quotes($ENV{"KNARR_TRACE_NAME"})) // "knarr-proxy"
$self->config->langfuse->{"trace_name"} _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"}) _strip_quotes($ENV{"KNARR_TRACE_NAME"})
Truth table50%2/4
A // B // C
A= $self->config->langfuse->{"trace_name"}B= _strip_quotes($ENV{"LANGFUSE_TRACE_NAME"})C= _strip_quotes($ENV{"KNARR_TRACE_NAME"})
ABCresult
1XX1
01X1
0011
0000
74 }
75  
76 18 has transport => (
77 is => 'lazy',
78 builder => '_build_transport',
79 );
80  
81  
82 55 ▶sub _build_transport {
Subroutine _build_transport: called CC=1 SCAR=0.0
83 55 my ($self) = @_;
84 55 return $self->config->langfuse_transport;
85 }
86  
87 62 ▶sub BUILD {
Subroutine BUILD: called CC=2 SCAR=6.9
Pod undocumented
88 62 my ($self) = @_;
89 62 ▶ return unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 7 55 62
90 55 $self->transport;
91 54 $self->config->langfuse_timeout;
92 }
93  
94 45 ▶sub _build__url {
Subroutine _build__url: called CC=4 SCAR=17.9
95 45 my ($self) = @_;
96 45 ▶ return $self->config->langfuse->{url} // _strip_quotes($ENV{LANGFUSE_URL}) // _strip_quotes($ENV{LANGFUSE_BASE_URL}) // 'https://cloud.langfuse.com';
Condition37%3/8
(($self->config->langfuse->{"url"} // _strip_quotes($ENV{"LANGFUSE_URL"})) // _strip_quotes($ENV{"LANGFUSE_BASE_URL"})) // "https://cloud.langfuse.com"
l!l
450
($self->config->langfuse->{"url"} // _strip_quotes($ENV{"LANGFUSE_URL"})) // _strip_quotes($ENV{"LANGFUSE_BASE_URL"})
l!l&&r!l&&!r
4500
$self->config->langfuse->{"url"} // _strip_quotes($ENV{"LANGFUSE_URL"})
l!l&&r!l&&!r
4500
MC/DC0%0/3
(($self->config->langfuse->{"url"} // _strip_quotes($ENV{"LANGFUSE_URL"})) // _strip_quotes($ENV{"LANGFUSE_BASE_URL"})) // "https://cloud.langfuse.com"
$self->config->langfuse->{"url"} _strip_quotes($ENV{"LANGFUSE_URL"}) _strip_quotes($ENV{"LANGFUSE_BASE_URL"})
Truth table25%1/4
A // B // C
A= $self->config->langfuse->{"url"}B= _strip_quotes($ENV{"LANGFUSE_URL"})C= _strip_quotes($ENV{"LANGFUSE_BASE_URL"})
ABCresult
1XX1
01X1
0011
0000
97 }
98  
99 has _batch => (
100 is => 'rw',
101 62 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
102 18 );
103  
104 18 has _json => (
105 is => 'lazy',
106 builder => '_build__json',
107 );
108  
109 # Strip surrounding quotes from env values (Docker --env-file includes them literally)
110 88 ▶sub _strip_quotes {
Subroutine _strip_quotes: called CC=2 SCAR=9.2
111 88 my $v = shift;
112 88 ▶ return $v unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 88 0 88
113 0 $v =~ s/^["']|["']$//g;
114 0 return $v;
115 }
116  
117 45 ▶sub _build__json {
Subroutine _build__json: called CC=1 SCAR=0.0
118 45 return JSON::MaybeXS->new(utf8 => 1, convert_blessed => 1);
119 }
120  
121 # Encodes structured values into OTLP string attributes. Character output:
122 # the attribute ends up inside the payload _json encodes to UTF-8 bytes.
123 18 has _attr_json => (
124 is => 'lazy',
125 builder => '_build__attr_json',
126 );
127  
128 12 ▶sub _build__attr_json {
Subroutine _build__attr_json: called CC=1 SCAR=0.0
129 12 return JSON::MaybeXS->new( utf8 => 0, canonical => 1, convert_blessed => 1, allow_nonref => 1 );
130 }
131  
132 # A random OTel id of $bytes bytes as lowercase hex (OTLP/JSON sends ids as
133 # hex, not base64). All zeros is the invalid id, so it is never returned.
134 51 ▶sub _hex_id {
Subroutine _hex_id: called CC=2 SCAR=7.0
135 51 my ($bytes) = @_;
136 51 my $id;
137 51 ▶ do { $id = join '', map { sprintf '%02x', int rand 256 } 1 .. $bytes } until $id =~ /[^0]/;
Branch: 1 branch
BranchTrueFalseTotal
$id =~ /[^0]/ or do { do { $id = join("", map({sprintf "%02x", int rand 256;} 1 .. $bytes)) } } 51 0 51
138 51 return $id;
139 }
140  
141 # A gettimeofday pair as OTLP's Unix nanoseconds, a decimal string.
142 50 ▶sub _unix_nano {
Subroutine _unix_nano: called CC=1 SCAR=0.0
143 50 my ($s, $us) = @_;
144 50 return sprintf '%d%06d000', $s, $us;
145 }
146  
147 306 ▶sub _uuid {
Subroutine _uuid: called CC=1 SCAR=0.0
148 306 my @hex = map { sprintf("%04x", int(rand(65536))) } 1..8;
149 306 return join('-',
150 $hex[0].$hex[1],
151 $hex[2],
152 '4'.substr($hex[3], 1),
153 sprintf("%x", 8 + int(rand(4))).substr($hex[4], 1),
154 $hex[5].$hex[6].$hex[7],
155 );
156 }
157  
158 188 ▶sub _timestamp {
Subroutine _timestamp: called CC=2 SCAR=7.1
159 188 ▶ my ($s, $us) = @_ ? @_ : gettimeofday;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 188 0 188
160 188 my @t = gmtime($s);
161 188 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
162 $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0], int($us/1000));
163 }
164  
165 # The instant $start_hires + $delta_seconds, as a gettimeofday pair that
166 # either transport formats. Turns the deltas an engine measured
167 # (ttft_seconds / total_seconds on Langertha::Response) into absolute
168 # Langfuse timestamps anchored to the moment start_trace ran — not to "now",
169 # which has already moved past the end of the call.
170 8 ▶sub _after {
Subroutine _after: called CC=4 SCAR=15.0
171 8 my ($start_hires, $delta_seconds) = @_;
172 8 ▶ return undef unless ref $start_hires eq 'ARRAY' && defined $delta_seconds;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $start_hires eq "ARRAY" and defined $delta_seconds 0 8 8
Condition33%1/3
ref $start_hires eq "ARRAY" and defined $delta_seconds
!ll&&!rl&&r
008
MC/DC0%0/2
ref $start_hires eq "ARRAY" and defined $delta_seconds
ref $start_hires eq "ARRAY" defined $delta_seconds
Truth table33%1/3
A and B
A= ref $start_hires eq "ARRAY"B= defined $delta_seconds
ABresult
0X0
100
111
173 # Clamp: a negative delta (clock skew, or a provider-reported duration we
174 # did not produce) would otherwise report a trip into the past.
175 8 ▶ $delta_seconds = 0 if $delta_seconds < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $delta_seconds < 0 0 8 8
176 8 my ($s, $us) = @$start_hires;
177 8 my $sum = $us + $delta_seconds * 1_000_000;
178 8 return [ $s + int( $sum / 1_000_000 ), int($sum) % 1_000_000 ];
179 }
180  
181 # Flatten a Langertha::RateLimit (or an equivalent hashref) into plain
182 # scalars for the trace metadata. Only the quota fields — the object's raw
183 # header hash is deliberately left out so response headers never leak into
184 # Langfuse, and so the payload stays JSON-encodable without convert_blessed.
185 18 my @RATE_LIMIT_FIELDS = qw(
186 requests_limit requests_remaining requests_reset
187 tokens_limit tokens_remaining tokens_reset
188 );
189  
190 64 ▶sub _rate_limit_hash {
Subroutine _rate_limit_hash: called CC=10 SCAR=23.2
191 64 my ($rl) = @_;
192 64 ▶ return undef unless defined $rl;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rl 62 2 64
193 2 my %out;
194 2 ▶ if ( blessed $rl ) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($rl)) { } 1 1 2
elsif (ref $rl eq 'HASH') { } 1 0 1
195 1 for my $f (@RATE_LIMIT_FIELDS) {
196 6 ▶ next unless $rl->can($f);
Branch: 1 branch
BranchTrueFalseTotal
unless $rl->can($f) 0 6 6
197 6 my $v = $rl->$f;
198 6 ▶ $out{$f} = $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 2 4 6
199 }
200 }
201 elsif ( ref $rl eq 'HASH' ) {
202 1 for my $f (@RATE_LIMIT_FIELDS) {
203 6 ▶ $out{$f} = $rl->{$f} if defined $rl->{$f};
Branch: 1 branch
BranchTrueFalseTotal
if defined $rl->{$f} 1 5 6
204 }
205 }
206 2 ▶ return %out ? \%out : undef;
Branch: 1 branch
BranchTrueFalseTotal
%out ? : 2 0 2
207 }
208  
209 # Langfuse's usage details are exclusive buckets, each priced on its own:
210 # input is the uncached input, prompt-cache reads and writes have their own
211 # keys (the names Langfuse's own normalizer and model prices use), and total
212 # is the sum of all of them (k65).
213 18 my @CACHE_BUCKETS = qw( input_cached_tokens input_cache_creation );
214  
215 # Token counts in the keys Langfuse stores: { input, output, total } plus
216 # the cache buckets that are not zero. Langertha::Usage's canonical
217 # input_tokens / output_tokens / total_tokens are keys Langfuse's ingestion
218 # silently drops, leaving the generation at 0 / 0 / 0 (k57). Takes a
219 # Langertha::Usage, a hashref already in Langfuse's keys (the shape
220 # end_trace's SYNOPSIS documents), or a provider's own usage hash (OpenAI,
221 # Anthropic, Ollama), which Langertha::Usage reads. Anything else, an empty
222 # hash, or one that counts nothing, is no usage at all -- never a zeroed one.
223 69 ▶sub _usage_hash {
Subroutine _usage_hash: called CC=6 SCAR=18.2
224 69 my ($u) = @_;
225 69 ▶ return undef unless defined $u;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $u 17 52 69
226 52 ▶ if ( ref $u eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $u eq "HASH") 37 15 52
227 return _langfuse_counts( $u, $u->{total} )
228 37 ▶ if grep { defined $u->{$_} } qw( input output total );
Branch: 1 branch
BranchTrueFalseTotal
if grep {defined $u->{$_};} "input", "output", "total" 5 32 37
229 32 $u = Langertha::Usage->from_hash($u);
230 }
231 47 ▶ return undef unless blessed($u) && $u->can('input_tokens');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($u) and $u->can("input_tokens") 0 47 47
Condition33%1/3
builtin::blessed($u) and $u->can("input_tokens")
!ll&&!rl&&r
0047
MC/DC0%0/2
builtin::blessed($u) and $u->can("input_tokens")
builtin::blessed($u) $u->can("input_tokens")
Truth table33%1/3
A and B
A= builtin::blessed($u)B= $u->can("input_tokens")
ABresult
0X0
100
111
232 47 return _langfuse_counts( { _input_buckets($u), output => $u->output_tokens } );
233 }
234  
235 # The input of a Langertha::Usage split into Langfuse's buckets. A core
236 # that knows the cache counts says how they relate to input_tokens; older
237 # ones (0.503) keep only the provider's hash, read here for the two wires
238 # that carry cache counts: OpenAI counts cached_tokens (and
239 # cache_write_tokens) inside prompt_tokens, Anthropic counts
240 # cache_read_input_tokens and cache_creation_input_tokens beside
241 # input_tokens.
242 47 ▶sub _input_buckets {
Subroutine _input_buckets: called CC=10 SCAR=44.5
243 47 my ($u) = @_;
244 return (
245 47 ▶ input => $u->uncached_input_tokens,
Branch: 1 branch
BranchTrueFalseTotal
if $u->can("uncached_input_tokens") 47 0 47
246 input_cached_tokens => $u->cached_tokens,
247 input_cache_creation => $u->cache_write_tokens,
248 ) if $u->can('uncached_input_tokens');
249 0 my $input = $u->input_tokens;
250 0 ▶ my $raw = $u->can('raw') ? $u->raw : undef;
Branch: 1 branch
BranchTrueFalseTotal
$u->can('raw') ? : 0 0 0
251 0 ▶ return ( input => $input ) unless ref $raw eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw eq "HASH" 0 0 0
252 0 ▶ my $ptd = ref $raw->{prompt_tokens_details} eq 'HASH' ? $raw->{prompt_tokens_details} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $raw->{'prompt_tokens_details'} eq 'HASH' ? : 0 0 0
253 0 ▶ my $inside = $ptd && grep { defined $ptd->{$_} } qw( cached_tokens cache_write_tokens );
Condition0%0/3
$ptd && grep({defined $ptd->{$_};} 'cached_tokens', 'cache_write_tokens')
!ll&&!rl&&r
000
MC/DC0%0/2
$ptd && grep({defined $ptd->{$_};} 'cached_tokens', 'cache_write_tokens')
$ptd grep({defined $ptd->{$_};} 'cached_tokens', 'cache_write_tokens')
Truth table0%0/3
A && B
A= $ptdB= grep({defined $ptd->{$_};} 'cached_tokens', 'cache_write_tokens')
ABresult
0X0
100
111
254 # Copied out first: map aliases its list, which would add the missing
255 # keys to the provider's hash.
256 my @counts = $inside
257 ? ( $ptd->{cached_tokens}, $ptd->{cache_write_tokens} )
258 0 ▶ : ( $raw->{cache_read_input_tokens}, $raw->{cache_creation_input_tokens} );
Branch: 1 branch
BranchTrueFalseTotal
$inside ? : 0 0 0
259 0 ▶ my ( $read, $write ) = map { looks_like_number($_) ? int($_) : 0 } @counts;
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($_) ? : 0 0 0
260 0 ▶ if ($inside) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inside) 0 0 0
261 0 $input -= $read + $write;
262 0 ▶ $input = 0 if $input < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $input < 0 0 0 0
263 }
264 0 return ( input => $input, input_cached_tokens => $read, input_cache_creation => $write );
265 }
266  
267 # Langfuse validates the counts as integers: a count that arrived as a
268 # string would be encoded as a JSON string and the whole event rejected.
269 # A missing total is the sum of the buckets; a usage that counts nothing
270 # is none.
271 52 ▶sub _langfuse_counts {
Subroutine _langfuse_counts: called CC=7 SCAR=19.5
272 52 my ( $counts, $total ) = @_;
273 52 ▶ my %out = map { $_ => looks_like_number( $counts->{$_} ) ? int( $counts->{$_} ) : 0 }
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($counts->{$_}) ? : 142 66 208
274 qw( input output ), @CACHE_BUCKETS;
275 52 my $sum = 0;
276 52 $sum += $_ for values %out;
277 52 delete $out{$_} for grep { !$out{$_} } @CACHE_BUCKETS;
278 52 ▶ $out{total} = looks_like_number($total) ? int($total) : $sum;
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($total) ? : 2 50 52
279 52 ▶ return ( $sum || $out{total} ) ? \%out : undef;
Branch: 1 branch
BranchTrueFalseTotal
$sum || $out{'total'} ? : 45 7 52
Condition66%2/3
$sum or $out{"total"}
l!l&&r!l&&!r
4507
MC/DC50%1/2
$sum or $out{"total"}
$sum $out{"total"}
Truth table66%2/3
A or B
A= $sumB= $out{"total"}
ABresult
1X1
011
000
280 }
281  
282 # Langfuse v2's usage has no cache buckets: its input is the whole input.
283 34 ▶sub _legacy_usage {
Subroutine _legacy_usage: called CC=3 SCAR=11.0
284 34 my ($usage) = @_;
285 34 my $input = 0;
286 34 ▶ $input += $usage->{$_} // 0 for 'input', @CACHE_BUCKETS;
Condition100%2/2
$usage->{$_} // 0
l!l
6240
MC/DC100%1/1
$usage->{$_} // 0
$usage->{$_}
Truth table100%2/2
A
A= $usage->{$_}
Aresult
11
00
287 34 return { input => $input, output => $usage->{output}, total => $usage->{total}, unit => 'TOKENS' };
288 }
289  
290 # Flatten the response's tool calls into plain hashes for the trace metadata.
291 # The trace is the detailed view, so it records the full
292 # { id, name, arguments, synthetic } shape -- the whole point of putting tool
293 # calls in a trace is seeing which tool ran with which arguments. Langertha
294 # 0.503's ToolCall carries a TO_JSON (so it would survive flush's
295 # convert_blessed encode either way), but flattening here keeps the metadata a
296 # plain structure like usage and rate_limit.
297 64 ▶sub _tool_calls_full {
Subroutine _tool_calls_full: called CC=10 SCAR=25.1
298 64 my ($tcs) = @_;
299 64 ▶ return undef unless ref $tcs eq 'ARRAY' && @$tcs;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tcs eq "ARRAY" and @$tcs 62 2 64
Condition66%2/3
ref $tcs eq "ARRAY" and @$tcs
!ll&&!rl&&r
6202
MC/DC50%1/2
ref $tcs eq "ARRAY" and @$tcs
ref $tcs eq "ARRAY" @$tcs
Truth table66%2/3
A and B
A= ref $tcs eq "ARRAY"B= @$tcs
ABresult
0X0
100
111
300 2 my @out;
301 2 for my $tc (@$tcs) {
302 3 ▶ if ( blessed($tc) && $tc->can('to_hash') ) { push @out, $tc->to_hash }
Branch: 3 branches
BranchTrueFalseTotal
if (builtin::blessed($tc) and $tc->can('to_hash')) { } 2 1 3
elsif (builtin::blessed($tc) and $tc->can('TO_JSON')) { } 0 1 1
elsif (ref $tc eq 'HASH') { } 1 0 1
Condition66%2/3
builtin::blessed($tc) and $tc->can("to_hash")
!ll&&!rl&&r
102
MC/DC50%1/2
builtin::blessed($tc) and $tc->can("to_hash")
builtin::blessed($tc) $tc->can("to_hash")
Truth table66%2/3
A and B
A= builtin::blessed($tc)B= $tc->can("to_hash")
ABresult
0X0
100
111
303 0 ▶ elsif ( blessed($tc) && $tc->can('TO_JSON') ) { push @out, $tc->TO_JSON }
Condition33%1/3
builtin::blessed($tc) and $tc->can("TO_JSON")
!ll&&!rl&&r
100
MC/DC0%0/2
builtin::blessed($tc) and $tc->can("TO_JSON")
builtin::blessed($tc) $tc->can("TO_JSON")
Truth table33%1/3
A and B
A= builtin::blessed($tc)B= $tc->can("TO_JSON")
ABresult
0X0
100
111
304 1 elsif ( ref $tc eq 'HASH' ) { push @out, $tc }
305 }
306 2 ▶ return @out ? \@out : undef;
Branch: 1 branch
BranchTrueFalseTotal
@out ? : 2 0 2
307 }
308  
309  
310 73 ▶sub start_trace {
Subroutine start_trace: called CC=5 SCAR=16.1
Pod documented
311 73 my ($self, %opts) = @_;
312 73 ▶ return undef unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 4 69 73
313  
314 69 ▶ my @hires = $opts{start_hires} ? @{ $opts{start_hires} } : gettimeofday;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'start_hires'} ? : 2 67 69
315 69 my $now = _timestamp(@hires);
316 # Image objects (k33) carry no TO_JSON and would fail the batch encode.
317 69 my $input = Langertha::Knarr::Image::plain_messages( $opts{messages} );
318  
319 # OTel spans are exported once, finished: nothing is sent yet, end_trace
320 # builds both spans from what is kept here.
321 return {
322 trace_id => _hex_id(16),
323 root_id => _hex_id(8),
324 gen_id => _hex_id(8),
325 start_time => $now,
326 start_hires => \@hires,
327 otel => {
328 name => $self->trace_name,
329 model => $opts{model},
330 input => $input,
331 metadata => {
332 format => $opts{format},
333 engine => $opts{engine},
334 model => $opts{model},
335 params => $opts{params},
336 # Left out when undef, like every other attribute.
337 passthrough_fallback => $opts{passthrough_fallback},
338 },
339 },
340 69 ▶ } if $self->transport eq 'otel';
Branch: 1 branch
BranchTrueFalseTotal
if $self->transport eq "otel" 17 52 69
341  
342 52 my $trace_id = _uuid();
343 52 my $gen_id = _uuid();
344  
345 52 ▶ push @{$self->_batch}, {
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'passthrough_fallback'} ? : 1 51 52
346 id => _uuid(),
347 type => 'trace-create',
348 timestamp => $now,
349 body => {
350 id => $trace_id,
351 name => $self->trace_name,
352 input => $input,
353 metadata => {
354 format => $opts{format},
355 engine => $opts{engine},
356 model => $opts{model},
357 params => $opts{params},
358 defined $opts{passthrough_fallback}
359 52 ? ( passthrough_fallback => $opts{passthrough_fallback} ) : (),
360 },
361 tags => ['knarr'],
362 },
363 };
364  
365 52 push @{$self->_batch}, {
366 id => _uuid(),
367 type => 'generation-create',
368 timestamp => $now,
369 body => {
370 id => $gen_id,
371 traceId => $trace_id,
372 name => 'proxy-request',
373 model => $opts{model},
374 52 input => $input,
375 startTime => $now,
376 },
377 };
378  
379 return {
380 52 trace_id => $trace_id,
381 gen_id => $gen_id,
382 start_time => $now,
383 start_hires => \@hires,
384 };
385 }
386  
387  
388 66 ▶sub end_trace {
Subroutine end_trace: called CC=25 SCAR=32.3
Pod documented
389 66 my ($self, $trace_info, %opts) = @_;
390 66 ▶ return unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 0 66 66
391 66 ▶ return unless $trace_info;
Branch: 1 branch
BranchTrueFalseTotal
unless $trace_info 0 66 66
392  
393 66 my @now = gettimeofday;
394 66 my $now = _timestamp(@now);
395 66 my $otel = $self->transport eq 'otel';
396  
397 66 ▶ if ( $opts{error} && $otel ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($opts{'error'} and $otel) { } 1 65 66
elsif ($opts{'error'}) { } 1 64 65
Condition100%3/3
$opts{"error"} and $otel
!ll&&!rl&&r
6411
MC/DC100%2/2
$opts{"error"} and $otel
$opts{"error"} $otel
Truth table100%3/3
A and B
A= $opts{"error"}B= $otel
ABresult
0X0
100
111
398 1 push @{$self->_batch}, {
399 info => $trace_info,
400 now => \@now,
401 end => \@now,
402 output => $opts{output},
403 1 error => "$opts{error}",
404 };
405 } elsif ($opts{error}) {
406 1 push @{$self->_batch}, {
407 id => _uuid(),
408 type => 'generation-update',
409 timestamp => $now,
410 body => {
411 id => $trace_info->{gen_id},
412 endTime => $now,
413 level => 'ERROR',
414 statusMessage => $opts{error},
415 },
416 1 };
417 } else {
418 64 ▶ my $timing = ( ref $opts{timing} eq 'HASH' ) ? $opts{timing} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $opts{'timing'} eq 'HASH' ? : 6 58 64
419  
420 # Engine-measured deltas win over the proxy's wall clock: they are
421 # anchored to the same instant as start_time and exclude our own
422 # dispatch/formatting overhead. Without them endTime stays "now".
423 64 my $end_at = \@now;
424 64 my $completion_at = undef;
425 64 ▶ if ( $timing ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($timing) 6 58 64
426 6 my $hires = $trace_info->{start_hires};
427 $end_at = _after( $hires, $timing->{total_seconds} ) // $end_at
428 6 ▶ if defined $timing->{total_seconds};
Branch: 1 branch
BranchTrueFalseTotal
if defined $timing->{"total_seconds"} 3 3 6
Condition33%1/3
_after($hires, $timing->{"total_seconds"}) // $end_at
l!l&&r!l&&!r
300
MC/DC0%0/2
_after($hires, $timing->{"total_seconds"}) // $end_at
_after($hires, $timing->{"total_seconds"}) $end_at
Truth table33%1/3
A // B
A= _after($hires, $timing->{"total_seconds"})B= $end_at
ABresult
1X1
011
000
429 $completion_at = _after( $hires, $timing->{ttft_seconds} )
430 6 ▶ if defined $timing->{ttft_seconds};
Branch: 1 branch
BranchTrueFalseTotal
if defined $timing->{"ttft_seconds"} 5 1 6
431 }
432  
433 64 my $usage = _usage_hash( $opts{usage} );
434  
435 64 my %metadata;
436 64 ▶ $metadata{timing} = $timing if $timing;
Branch: 1 branch
BranchTrueFalseTotal
if $timing 6 58 64
437 64 ▶ $metadata{response_id} = $opts{response_id} if defined $opts{response_id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"response_id"} 2 62 64
438 64 ▶ $metadata{configured_model} = $opts{configured_model} if defined $opts{configured_model};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"configured_model"} 3 61 64
439 $metadata{thinking} = $opts{thinking}
440 64 ▶ if defined $opts{thinking} && length $opts{thinking};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"thinking"} and length $opts{"thinking"} 2 62 64
Condition66%2/3
defined $opts{"thinking"} and length $opts{"thinking"}
!ll&&!rl&&r
6202
MC/DC50%1/2
defined $opts{"thinking"} and length $opts{"thinking"}
defined $opts{"thinking"} length $opts{"thinking"}
Truth table66%2/3
A and B
A= defined $opts{"thinking"}B= length $opts{"thinking"}
ABresult
0X0
100
111
441 64 ▶ if ( my $rl = _rate_limit_hash( $opts{rate_limit} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rl = _rate_limit_hash($opts{"rate_limit"})) 2 62 64
442 2 $metadata{rate_limit} = $rl;
443 }
444 64 ▶ if ( my $tcs = _tool_calls_full( $opts{tool_calls} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tcs = _tool_calls_full($opts{"tool_calls"})) 2 62 64
445 2 $metadata{tool_calls} = $tcs;
446 }
447  
448 64 ▶ if ($otel) {
Branch: 1 branch
BranchTrueFalseTotal
if ($otel) { } 16 48 64
449 16 push @{$self->_batch}, {
450 info => $trace_info,
451 now => \@now,
452 end => $end_at,
453 completion_start => $completion_at,
454 output => $opts{output},
455 model => $opts{model},
456 16 usage => $usage,
457 metadata => \%metadata,
458 };
459 } else {
460 48 ▶ push @{$self->_batch}, {
Branch: 4 branches
BranchTrueFalseTotal
defined $completion_at ? : 2 46 48
$opts{'model'} ? : 24 24 48
$usage ? : 34 14 48
%metadata ? : 4 44 48
461 id => _uuid(),
462 type => 'generation-update',
463 timestamp => $now,
464 body => {
465 id => $trace_info->{gen_id},
466 output => $opts{output},
467 endTime => _timestamp(@$end_at),
468 defined $completion_at ? (completionStartTime => _timestamp(@$completion_at)) : (),
469 48 $opts{model} ? (model => $opts{model}) : (),
470 # Langfuse v2 reads usage and drops usageDetails; v3 reads both,
471 # usageDetails overriding usage.
472 $usage ? (usage => _legacy_usage($usage),
473 usageDetails => $usage) : (),
474 %metadata ? (metadata => \%metadata) : (),
475 },
476 };
477 }
478 }
479  
480 49 ▶ push @{$self->_batch}, {
Condition66%2/3
$opts{"output"} // $opts{"error"}
l!l&&r!l&&!r
4810
MC/DC0%0/2
$opts{"output"} // $opts{"error"}
$opts{"output"} $opts{"error"}
Truth table66%2/3
A // B
A= $opts{"output"}B= $opts{"error"}
ABresult
1X1
011
000
481 id => _uuid(),
482 type => 'trace-create',
483 timestamp => $now,
484 body => {
485 id => $trace_info->{trace_id},
486 output => $opts{output} // $opts{error},
487 },
488 66 ▶ } unless $otel;
Branch: 1 branch
BranchTrueFalseTotal
unless $otel 49 17 66
489  
490 66 $self->flush;
491 }
492  
493  
494 has _loop => (
495 is => 'lazy',
496 2 ▶ builder => sub { IO::Async::Loop->new },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine _build__loop: called CC=1 SCAR=0.0
497 18 );
498  
499 has _http => (
500 is => 'lazy',
501 25 ▶ builder => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
Subroutine _build__http: called CC=2 SCAR=6.9
502 25 my ($self) = @_;
503 # Net::Async::HTTP times out at once on 0, so 0 (none) sets no timeout.
504 25 my $timeout = $self->config->langfuse_timeout;
505 25 ▶ my $h = Net::Async::HTTP->new( user_agent => 'Langertha-Knarr',
Branch: 2 branches
BranchTrueFalseTotal
$timeout ? : 25 0 25
$timeout ? : 16 1 17
506 $timeout ? ( timeout => $timeout ) : () );
507 25 $self->_loop->add($h);
508 25 return $h;
509 },
510 18 );
511  
512 63 ▶sub flush {
Subroutine flush: called CC=7 SCAR=19.5
Pod documented
513 63 my ($self) = @_;
514 63 ▶ return unless $self->_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_enabled 0 63 63
515 63 my $batch = $self->_batch;
516 63 ▶ return unless @$batch;
Branch: 1 branch
BranchTrueFalseTotal
unless @$batch 0 63 63
517 63 $self->_batch([]);
518  
519 63 my $auth = encode_base64($self->_public_key . ':' . $self->_secret_key, '');
520 63 my $otel = $self->transport eq 'otel';
521  
522 # Tracing is observability, not the product. flush runs inside end_trace on
523 # the response path — and for streams after the last chunk was written — so
524 # an exception here turns an already-answered request into a 500, or leaves
525 # a client waiting for an end marker that never comes. The batch was
526 # detached from _batch above and is unrecoverable either way, so a failed
527 # encode is logged at error level (as loud as any request fault in
528 # Langertha::Knarr) and dropped, exactly like the ingestion failures below.
529 63 my $body;
530 63 my $encode_error = do {
531 63 local $@;
532 63 eval {
533 63 ▶ $body = $self->_json->encode(
Branch: 1 branch
BranchTrueFalseTotal
$otel ? : 17 46 63
534 $otel ? $self->_otlp_request($batch) : { batch => $batch } );
535 };
536 63 $@;
537 };
538 63 ▶ if ($encode_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($encode_error) 2 61 63
539 2 $log->errorf("Langfuse batch encode failed, dropping %d event(s): %s",
540 scalar @$batch, $encode_error);
541 2 return;
542 }
543  
544 61 ▶ my $req = HTTP::Request->new(
Branch: 2 branches
BranchTrueFalseTotal
$otel ? : 16 45 61
$otel ? : 16 45 61
545 POST => $self->_url . ( $otel ? '/api/public/otel/v1/traces' : '/api/public/ingestion' ),
546 [
547 'Content-Type' => 'application/json',
548 'Authorization' => 'Basic ' . $auth,
549 # Selects Langfuse v4's real-time OTel ingestion (else up to 10 min late).
550 $otel ? ( 'x-langfuse-ingestion-version' => '4' ) : (),
551 ],
552 $body,
553 );
554  
555 61 my $f = $self->_http->do_request( request => $req );
556 56 ▶ $f->on_done(sub {
Subroutine __ANON__: called CC=2 SCAR=8.1
557 56 my ($resp) = @_;
558 56 ▶ return if $resp->is_success;
Branch: 1 branch
BranchTrueFalseTotal
if $resp->is_success 56 0 56
559 0 $log->warnf("Langfuse ingestion failed: %s", $resp->status_line);
560 61 });
561 2 ▶ $f->on_fail(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
562 2 my ($err) = @_;
563 2 $log->warnf("Langfuse flush error: %s", $err);
564 61 });
565 61 $f->retain;
566 61 return;
567 }
568  
569 # OTLP/JSON ExportTraceServiceRequest for the traces end_trace finished.
570 # Enums (span kind, status code) are integers, ids lowercase hex and times
571 # decimal strings, as the OTLP/JSON encoding prescribes.
572 17 ▶sub _otlp_request {
Subroutine _otlp_request: called CC=1 SCAR=0.0
573 17 my ($self, $batch) = @_;
574 return {
575 resourceSpans => [ {
576 resource => { attributes => [ $self->_otel_attributes( 'service.name' => 'langertha-knarr' ) ] },
577 scopeSpans => [ {
578 scope => { name => __PACKAGE__, version => $VERSION },
579 17 spans => [ map { $self->_otel_spans($_) } @$batch ],
580 } ],
581 } ],
582 };
583 }
584  
585 18 my %SPAN_KIND = ( server => 2, client => 3 );
586 18 my $STATUS_ERROR = 2;
587  
588 # The root span (the Langfuse trace) and its generation child for one
589 # request, from the record end_trace pushed.
590 17 ▶sub _otel_spans {
Subroutine _otel_spans: called CC=8 SCAR=20.8
591 17 my ($self, $rec) = @_;
592 17 my $info = $rec->{info};
593 17 my $o = $info->{otel};
594 17 my $error = $rec->{error};
595 17 my $start = _unix_nano( @{ $info->{start_hires} } );
596  
597 # Langfuse v4 reads trace attributes off every span that carries them.
598 my @trace_attrs = (
599 17 $self->_otel_attributes( 'langfuse.trace.name' => $o->{name} ),
600 { key => 'langfuse.trace.tags',
601 value => { arrayValue => { values => [ { stringValue => 'knarr' } ] } } },
602 );
603 17 my $meta = $o->{metadata};
604 17 ▶ my $gen_meta = $rec->{metadata} // {};
Condition100%2/2
$rec->{"metadata"} // {}
l!l
161
MC/DC100%1/1
$rec->{"metadata"} // {}
$rec->{"metadata"}
Truth table100%2/2
A
A= $rec->{"metadata"}
Aresult
11
00
605  
606 # A failed request marks both the trace's span and the generation.
607 17 ▶ my @error_attrs = $error ? $self->_otel_attributes(
Branch: 1 branch
BranchTrueFalseTotal
$error ? : 1 16 17
608 'langfuse.observation.level' => 'ERROR',
609 'langfuse.observation.status_message' => $error,
610 ) : ();
611 17 ▶ my @error_status = $error ? ( status => { code => $STATUS_ERROR, message => $error } ) : ();
Branch: 1 branch
BranchTrueFalseTotal
$error ? : 1 16 17
612  
613 my $root = {
614 traceId => $info->{trace_id},
615 spanId => $info->{root_id},
616 name => $o->{name},
617 kind => $SPAN_KIND{server},
618 startTimeUnixNano => $start,
619 17 ▶ endTimeUnixNano => _unix_nano( @{ $rec->{now} } ),
Condition66%2/3
$rec->{"output"} // $error
l!l&&r!l&&!r
1610
MC/DC0%0/2
$rec->{"output"} // $error
$rec->{"output"} $error
Truth table66%2/3
A // B
A= $rec->{"output"}B= $error
ABresult
1X1
011
000
620 attributes => [
621 @trace_attrs,
622 $self->_otel_attributes(
623 'langfuse.observation.type' => 'span',
624 'langfuse.observation.input' => $o->{input},
625 'langfuse.observation.output' => $rec->{output} // $error,
626 17 map { ( 'langfuse.trace.metadata.'.$_ => $meta->{$_} ) } sort keys %$meta,
627 ),
628 @error_attrs,
629 ],
630 @error_status,
631 };
632  
633 my $gen = {
634 traceId => $info->{trace_id},
635 spanId => $info->{gen_id},
636 parentSpanId => $info->{root_id},
637 name => 'proxy-request',
638 kind => $SPAN_KIND{client},
639 startTimeUnixNano => $start,
640 16 ▶ endTimeUnixNano => _unix_nano( @{ $rec->{end} } ),
Branch: 2 branches
BranchTrueFalseTotal
$error ? : 1 15 16
$rec->{'completion_start'} ? : 3 12 15
Condition66%2/3
$rec->{'model'} || $o->{'model'}
l!l&&r!l&&!r
5110
MC/DC0%0/2
$rec->{'model'} || $o->{'model'}
$rec->{'model'} $o->{'model'}
Truth table66%2/3
A || B
A= $rec->{'model'}B= $o->{'model'}
ABresult
1X1
011
000
641 attributes => [
642 @trace_attrs,
643 $self->_otel_attributes(
644 'langfuse.observation.type' => 'generation',
645 'langfuse.observation.model.name' => $rec->{model} || $o->{model},
646 'langfuse.observation.input' => $o->{input},
647 $error ? () : (
648 'langfuse.observation.output' => $rec->{output},
649 'langfuse.observation.completion_start_time' =>
650 3 $rec->{completion_start} ? _timestamp( @{ $rec->{completion_start} } ) : undef,
651 'langfuse.observation.usage_details' => $rec->{usage},
652 16 map { ( 'langfuse.observation.metadata.'.$_ => $gen_meta->{$_} ) } sort keys %$gen_meta,
653 ),
654 ),
655 @error_attrs,
656 ],
657 @error_status,
658 };
659  
660 16 return ( $root, $gen );
661 }
662  
663 # OTLP KeyValue list from key/value pairs. An undef value is left out; a
664 # reference is JSON-encoded into a string, which is how Langfuse takes
665 # structured input, output, usage and metadata; anything else is a string.
666 68 ▶sub _otel_attributes {
Subroutine _otel_attributes: called CC=4 SCAR=13.9
667 68 my ($self, @pairs) = @_;
668 68 my @attrs;
669 68 ▶ while ( my ( $key, $value ) = splice @pairs, 0, 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@pairs, 0, 2)) 274 67 341
670 274 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 75 199 274
671 199 ▶ $value = $self->_attr_json->encode($value) if ref $value;
Branch: 1 branch
BranchTrueFalseTotal
if ref $value 34 165 199
672 198 push @attrs, { key => $key, value => { stringValue => "$value" } };
673 }
674 67 return @attrs;
675 }
676  
677  
678 18 1;
679  
680 __END__
681  
682 =pod
683  
684 =encoding UTF-8
685  
686 =head1 NAME
687  
688 Langertha::Knarr::Tracing - Automatic Langfuse tracing per proxy request
689  
690 =head1 VERSION
691  
692 version 1.102
693  
694 =head1 SYNOPSIS
695  
696 use Langertha::Knarr::Tracing;
697  
698 my $tracing = Langertha::Knarr::Tracing->new(config => $config);
699  
700 my $trace_id = $tracing->start_trace(
701 model => 'gpt-5.6-terra',
702 engine => 'Langertha::Engine::OpenAI',
703 messages => \@messages,
704 params => \%params,
705 format => 'openai',
706 );
707  
708 # ... handle request ...
709  
710 $tracing->end_trace($trace_id,
711 output => $response_text,
712 model => 'gpt-5.6-terra',
713 usage => { input => 100, output => 50, total => 150 },
714 );
715  
716 =head1 DESCRIPTION
717  
718 Records every proxy request as a Langfuse trace with a nested generation. When
719 tracing is not configured (no public and secret key), all methods are no-ops.
720  
721 Two transports carry the trace to Langfuse, selected by L</transport>:
722 C<ingestion> (the default) posts events to Langfuse's
723 C</api/public/ingestion> API, C<otel> exports OpenTelemetry spans (see
724 L</OpenTelemetry transport>). Both record the same content through the
725 same calls, in one fire-and-forget POST per request that gives up after
726 L<Langertha::Knarr::Config/langfuse_timeout> seconds (default 15).
727  
728 Langfuse credentials are read from the config file's C<langfuse:> section or
729 from the C<LANGFUSE_PUBLIC_KEY>, C<LANGFUSE_SECRET_KEY>, and C<LANGFUSE_URL>
730 environment variables. The module strips surrounding quotes from environment
731 variable values, which Docker C<--env-file> sometimes adds literally.
732  
733 =head2 Timing sources
734  
735 Knarr has two request paths and they do not measure latency the same way.
736 The generation's C<startTime> always marks the moment L</start_trace> ran;
737 what differs is where C<endTime> and C<completionStartTime> come from.
738  
739 =over
740  
741 =item * B<Routed, non-streaming> — a L<Langertha> engine produced a
742 L<Langertha::Response>, so L<Langertha::Knarr::Handler::Tracing> hands the
743 engine-measured C<timing> hash to L</end_trace>. C<endTime> becomes
744 C<startTime + total_seconds> and C<completionStartTime> becomes
745 C<startTime + ttft_seconds>, both anchored to the high-resolution
746 timestamp L</start_trace> recorded. This is the only path with a real
747 time-to-first-token, and the durations exclude the proxy's own
748 formatting overhead.
749  
750 =item * B<Routed, streaming> — the decorator accumulates deltas and never
751 sees a response object, so it measures time-to-first-token itself in the
752 proxy: L<Langertha::Knarr::Handler::Tracing> starts its clock before
753 opening the upstream stream and stops at the first non-C<undef> delta,
754 then passes that C<ttft_seconds> to L</end_trace> as C<timing>.
755 C<completionStartTime> is therefore emitted, but — unlike the
756 non-streaming path, where the engine measures — this figure is the
757 proxy's own view and includes its dispatch overhead. C<endTime> stays the
758 wall-clock moment the stream was exhausted; a stream that yields no delta
759 (empty or failed) produces no C<timing> and no C<completionStartTime>.
760  
761 =item * B<Raw passthrough> — bytes are piped 1:1 and never parsed, so no
762 L<Langertha::Response> exists at all. C<endTime> is again the proxy's own
763 wall clock at L</end_trace>, which includes network time to the upstream
764 provider.
765  
766 =back
767  
768 Callers that pass no C<timing> therefore keep exactly the previous
769 behaviour: proxy-measured C<endTime>, no C<completionStartTime>.
770  
771 =head2 OpenTelemetry transport
772  
773 With L</transport> C<otel>, each request goes out as one OTLP/HTTP request,
774 JSON encoded, to C</api/public/otel/v1/traces> under L</config>'s Langfuse
775 URL, with the same Basic authentication and the
776 C<x-langfuse-ingestion-version: 4> header (Langfuse's real-time ingestion
777 path). A span must not be exported twice, so L</start_trace> only records
778 the start and L</end_trace> builds and sends the finished trace, two spans
779 under one random trace id:
780  
781 =over
782  
783 =item * a root span named after L</trace_name> (kind C<SERVER>) with
784 C<langfuse.trace.name>, C<langfuse.trace.tags> (C<knarr>),
785 C<langfuse.trace.metadata.*> (C<format>, C<engine>, C<model>, C<params>,
786 C<passthrough_fallback>),
787 and the request messages and the output (or the error) as
788 C<langfuse.observation.input> / C<langfuse.observation.output>, which
789 Langfuse shows as the trace's input and output;
790  
791 =item * its child C<proxy-request> (kind C<CLIENT>), a
792 C<langfuse.observation.type> C<generation> with
793 C<langfuse.observation.model.name>, input and output,
794 C<langfuse.observation.usage_details> (the same buckets the ingestion
795 path sends as C<usageDetails>, cache reads and writes apart from the
796 uncached input, see L</end_trace>),
797 C<langfuse.observation.completion_start_time> and
798 C<langfuse.observation.metadata.*> (C<timing>, C<response_id>,
799 C<configured_model>, C<thinking>, C<rate_limit>, C<tool_calls>). A
800 C<start_hires> given to L</start_trace> is the start of both spans.
801  
802 =back
803  
804 An error sets the status of both spans to C<ERROR> with the message, plus
805 C<langfuse.observation.level> C<ERROR> and
806 C<langfuse.observation.status_message>, so the trace itself shows as
807 failed, not only its generation.
808  
809 Span start and end are the instants the ingestion path reports (see
810 L</Timing sources>), in Unix nanoseconds. Structured values (messages,
811 params, usage, metadata hashes) are JSON-encoded into string attributes;
812 plain strings go as they are, as Langfuse's own SDKs send them.
813  
814 =head2 config
815  
816 The L<Langertha::Knarr::Config> object. Required. Provides Langfuse
817 credentials and C<trace_name>.
818  
819 =head2 trace_name
820  
821 The Langfuse trace name applied to all traces. Resolved in priority order from:
822 C<langfuse.trace_name> in config, C<LANGFUSE_TRACE_NAME> env var,
823 C<KNARR_TRACE_NAME> env var, or the default C<knarr-proxy>.
824  
825 =head2 transport
826  
827 C<ingestion> (default) or C<otel>, from
828 L<Langertha::Knarr::Config/langfuse_transport> (C<langfuse.transport>, else
829 C<KNARR_LANGFUSE_TRANSPORT>). An enabled tracer reads it, and
830 L<Langertha::Knarr::Config/langfuse_timeout>, when it is built, so an
831 invalid value croaks at startup, not on the first request.
832  
833 =head2 start_trace
834  
835 my $trace_info = $tracing->start_trace(
836 model => $model_name,
837 engine => $engine_class,
838 messages => \@messages,
839 params => \%params,
840 format => 'openai',
841 );
842  
843 Creates a new Langfuse trace and generation. Returns a C<$trace_info> hashref
844 that must be passed to L</end_trace>. Returns C<undef> when tracing is
845 disabled.
846  
847 The returned hashref carries C<start_hires>, the C<gettimeofday> pair behind
848 C<start_time>. L</end_trace> anchors engine-measured durations to it; see
849 L</Timing sources>.
850  
851 Two optional arguments:
852  
853 =over
854  
855 =item * C<start_hires> -- a C<gettimeofday> pair the trace starts at instead
856 of now, for a trace opened after the request went out. The raw passthrough
857 of a model that may still fall back to its engine opens its trace only once
858 the upstream's status rules that out (see L<Langertha::Knarr/raw_passthrough>).
859  
860 =item * C<passthrough_fallback> -- the upstream status that sent a raw
861 passthrough request to its engine instead (C<401>), recorded in the trace's
862 metadata. L<Langertha::Knarr::Handler::Tracing> passes it from the request.
863  
864 =back
865  
866 =head2 end_trace
867  
868 $tracing->end_trace($trace_info,
869 output => $response_text,
870 model => $model,
871 usage => { input => 100, output => 50, total => 150 },
872 timing => { ttft_seconds => 0.25, total_seconds => 1.5 },
873 response_id => 'chatcmpl-123',
874 );
875  
876 # On error:
877 $tracing->end_trace($trace_info, error => "Something went wrong");
878  
879 Closes the generation and trace started by L</start_trace>, then flushes the
880 batch to Langfuse. Pass C<error> to record a failed generation at level ERROR.
881 Does nothing when C<$trace_info> is C<undef> (tracing was disabled at start).
882  
883 Optional metadata carried off a L<Langertha::Knarr::Response>, all skipped
884 when absent:
885  
886 =over
887  
888 =item * C<timing> — HashRef with C<ttft_seconds> / C<total_seconds>. Drives
889 the generation's C<endTime> and C<completionStartTime> (the Langfuse field
890 for time-to-first-token) and is recorded verbatim in the metadata, so
891 provider-native stage durations survive too. See L</Timing sources>.
892  
893 =item * C<response_id> — the provider's own response id, for correlating a
894 Langfuse generation with the provider's logs.
895  
896 =item * C<configured_model> — the model name Knarr answers the client under
897 when it differs from the C<model> the backend reported (a routed model's
898 configured name). The generation's C<model> is the reported one; this keeps
899 the configured one next to it.
900  
901 =item * C<thinking> — reasoning text the engine split off C<content>. It is
902 model output that C<output> no longer contains, so the trace is the only
903 place it survives.
904  
905 =item * C<rate_limit> — a L<Langertha::RateLimit> (or equivalent hashref).
906 Flattened to its quota scalars; the raw header hash is not recorded.
907  
908 =item * C<usage> — a L<Langertha::Usage> (the shape every routed response
909 carries), a hashref in Langfuse's own keys (C<input> / C<output> / C<total>),
910 or a provider's usage hash (OpenAI C<prompt_tokens>, Anthropic
911 C<input_tokens>, Ollama C<prompt_eval_count>, ...), read through
912 L<Langertha::Usage/from_hash>. Whatever the input, the generation gets the
913 counts in the only keys Langfuse stores: C<usageDetails> for v3, which
914 lets it override C<usage>, and C<usage> as C<< { input, output, total,
915 unit => 'TOKENS' } >> for Langfuse v2, which drops the key it does not
916 know.
917  
918 C<usageDetails> holds Langfuse's exclusive buckets, each priced on its own
919 and C<total> their sum: C<input> is the uncached input, prompt-cache reads
920 go to C<input_cached_tokens> and cache writes to C<input_cache_creation>
921 (each only when not zero), and C<output>. Every token lands in exactly one
922 bucket, whichever way the provider counts: Anthropic reports
923 C<cache_read_input_tokens> / C<cache_creation_input_tokens> beside
924 C<input_tokens>, OpenAI's C<prompt_tokens_details.cached_tokens> is part
925 of C<prompt_tokens> and is taken out of C<input>. v2's C<usage> has no
926 cache buckets, so its C<input> is the whole input, cache included. A
927 hashref in Langfuse's keys may carry the two cache buckets itself; its
928 missing C<total> is the sum of its buckets; a provider's C<total> is
929 always the sum. Without usage, with an empty hash, or with one that
930 counts no tokens (an error body, a hash without any count key), neither
931 key is sent, so Langfuse never records a zeroed usage. The raw
932 passthrough passes the provider's usage hash it read off a copy of the upstream's answer (see
933 L<Langertha::Knarr/tracing>).
934  
935 =item * C<tool_calls> — the response's L<Langertha::ToolCall> list. The trace
936 is the detailed view, so it records the B<full> tool calls — C<id>, C<name>,
937 the complete C<arguments> and C<synthetic> — flattened to plain hashes. The
938 JSONL request log keeps only a trimmed form (see
939 L<Langertha::Knarr::RequestLog/end_request>).
940  
941 =back
942  
943 =head2 flush
944  
945 $tracing->flush;
946  
947 Sends all pending trace events to Langfuse in one POST and clears the
948 internal buffer: an ingestion batch to C</api/public/ingestion>, or, with
949 L</transport> C<otel>, an OTLP C<ExportTraceServiceRequest> to
950 C</api/public/otel/v1/traces>. Called automatically by L</end_trace>. Does
951 nothing when tracing is disabled or the batch is empty.
952  
953 Never throws: a batch that cannot be JSON-encoded is logged at error level and
954 dropped, the same way an ingestion HTTP failure is. L</end_trace> runs on the
955 request's response path, so a tracing problem must not take the client's
956 response down with it.
957  
958 The POST is sent without waiting for it and gives up after
959 L<Langertha::Knarr::Config/langfuse_timeout> seconds (C<langfuse.timeout>
960 or C<KNARR_LANGFUSE_TIMEOUT>, default 15, C<0> for none): a Langfuse that
961 accepts the connection and never answers is logged as a C<Langfuse flush
962 error> warning, and never holds a request.
963  
964 =head1 SEE ALSO
965  
966 =over
967  
968 =item * L<Langertha::Knarr> — Tracing is wired in automatically for all routes
969  
970 =item * L<Langertha::Knarr::Config> — Provides Langfuse credentials
971  
972 =back
973  
974 =head1 SUPPORT
975  
976 =head2 Issues
977  
978 Please report bugs and feature requests on GitHub at
979 L<https://github.com/Getty/langertha-knarr/issues>.
980  
981 =head2 IRC
982  
983 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
984  
985 =head1 CONTRIBUTING
986  
987 Contributions are welcome! Please fork the repository and submit a pull request.
988  
989 =head1 AUTHOR
990  
991 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
992  
993 =head1 COPYRIGHT AND LICENSE
994  
995 This software is copyright (c) 2026 by Torsten Raudssus.
996  
997 This is free software; you can redistribute it and/or modify it under
998 the same terms as the Perl 5 programming language system itself.
999  
1000 =cut
« blib/lib/Langertha/Knarr/Handler/Passthrough.pm ↑ Summary blib/lib/Langertha/Knarr/Router.pm »