blib/lib/Langertha/Knarr/Handler/Tracing.pm

filter: Statementstmt 97.6% 83 / 85 Branchbran 86.8% 33 / 38 Conditioncond 82.6% 19 / 23 MC/DCmcdc 69.2% 9 / 13 Subroutinesub 100% 18 / 18 Podpod 0.0% 0 / 3 totaltotal 90.0% 162 / 180 CC 28 SCAR 17.2
CC
28
Cov
92%
__ANON__
11.5
_close_trace
7.0
_model_opts
6.0
CRAP 5.6
« blib/lib/Langertha/Knarr/Handler/ACPClient.pm ↑ Summary blib/lib/Langertha/Knarr/Protocol/Ollama.pm »
1 package Langertha::Knarr::Handler::Tracing;
2 # ABSTRACT: Decorator handler that records every request as a Langfuse trace
3 15 our $VERSION = '1.102';
4 15 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 15 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 15 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 15 ▶use Time::HiRes qw( gettimeofday tv_interval );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 15 ▶use Langertha::Knarr::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 15 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 15 with 'Langertha::Knarr::Handler';
12  
13  
14 # Wraps an inner Knarr::Handler with Langfuse tracing. Each chat or stream
15 # request opens a trace+generation via $tracing->start_trace, then closes
16 # it with the assistant text via end_trace once the wrapped handler is done.
17 # The attribute is named "wrapped" rather than "inner" because Moose
18 # imports an inner() keyword used for augmented methods.
19  
20 15 has wrapped => (
21 is => 'ro',
22 required => 1,
23 );
24  
25 # Anything implementing start_trace($opts) → $info / end_trace($info, %opts).
26 # In production this is a Langertha::Knarr::Tracing instance; tests can
27 # pass a mock that records calls.
28 15 has tracing => (
29 is => 'ro',
30 required => 1,
31 );
32  
33 # Optional: a label injected into the trace metadata's "engine" field when
34 # the wrapped handler doesn't have a more specific name.
35 has engine_label => (
36 is => 'ro',
37 isa => 'Maybe[Str]',
38 38 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
39 15 );
40  
41 121 ▶sub _open_trace {
Subroutine _open_trace: called CC=4 SCAR=14.3
42 121 my ($self, $request) = @_;
43 return $self->tracing->start_trace(
44 model => ( $request->model // '' ),
45 engine => ( $self->engine_label // ref( $self->wrapped ) ),
46 messages => $request->messages,
47 params => {
48 temperature => $request->temperature,
49 max_tokens => $request->max_tokens,
50 tools => $request->tools,
51 },
52 format => $request->protocol,
53 # A raw passthrough the upstream refused (k66): this is its one trace.
54 ( defined $request->extra->{passthrough_fallback}
55 121 ▶ ? ( passthrough_fallback => $request->extra->{passthrough_fallback} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
defined $request->extra->{'passthrough_fallback'} ? : 9 112 121
Condition60%3/5
$request->model // ""
l!l
1174
$self->engine_label // ref $self->wrapped
l!l&&r!l&&!r
01210
MC/DC100%1/1
$request->model // ""
$request->model
MC/DC0%0/2
$self->engine_label // ref $self->wrapped
$self->engine_label ref $self->wrapped
Truth table100%2/2
A
A= $request->model
Aresult
11
00
Truth table33%1/3
A // B
A= $self->engine_labelB= ref $self->wrapped
ABresult
1X1
011
000
56 );
57 }
58  
59 # The generation's model is the one the backend reported answering with; the
60 # name the handler labeled the answer with (the configured model a Router
61 # relabels it to, k70) goes into the metadata when it differs.
62 66 ▶sub _model_opts {
Subroutine _model_opts: called CC=6 SCAR=17.9
63 66 my ($self, $label, $reported, $fallback) = @_;
64 66 ▶ my $model = $reported // $label // $fallback;
Condition100%6/6
($reported // $label) // $fallback
l!l&&r!l&&!r
5592
$reported // $label
l!l&&r!l&&!r
223311
MC/DC100%3/3
($reported // $label) // $fallback
$reported $label $fallback
Truth table100%4/4
A // B // C
A= $reportedB= $labelC= $fallback
ABCresult
1XX1
01X1
0011
0000
65 return (
66 66 ▶ model => $model,
Branch: 1 branch
BranchTrueFalseTotal
defined $reported && defined $label && $label ne $reported ? : 13 53 66
Condition100%6/6
defined $reported and defined $label and $label ne $reported
!ll&&!rl&&r
47613
defined $reported and defined $label
!ll&&!rl&&r
44319
MC/DC100%3/3
defined $reported and defined $label and $label ne $reported
defined $reported defined $label $label ne $reported
Truth table100%4/4
A and B and C
A= defined $reportedB= defined $labelC= $label ne $reported
ABCresult
0XX0
10X0
1100
1111
67 ( defined $reported && defined $label && $label ne $reported
68 ? ( configured_model => $label ) : () ),
69 );
70 }
71  
72 28 ▶sub _close_trace {
Subroutine _close_trace: called CC=7 SCAR=19.5
73 28 my ($self, $trace, $r) = @_;
74 28 my $resp = Langertha::Knarr::Response->coerce($r);
75 # timing is the engine's own measurement (ttft/total); passing it lets
76 # Tracing anchor endTime/completionStartTime to the real call window
77 # instead of the proxy's wall clock. Streaming and passthrough have no
78 # response object and keep the wall-clock fallback.
79 28 ▶ $self->tracing->end_trace(
Branch: 6 branches
BranchTrueFalseTotal
$resp->usage ? : 12 16 28
$resp->timing ? : 9 19 28
defined $resp->id ? : 9 19 28
defined $resp->thinking ? : 1 27 28
$resp->rate_limit ? : 1 27 28
$resp->has_tool_calls ? : 1 27 28
80 $trace,
81 output => $resp->content,
82 $self->_model_opts( $resp->model, $resp->upstream_model ),
83 ( $resp->usage ? ( usage => $resp->usage ) : () ),
84 ( $resp->timing ? ( timing => $resp->timing ) : () ),
85 ( defined $resp->id ? ( response_id => $resp->id ) : () ),
86 ( defined $resp->thinking ? ( thinking => $resp->thinking ) : () ),
87 ( $resp->rate_limit ? ( rate_limit => $resp->rate_limit ) : () ),
88 ( $resp->has_tool_calls ? ( tool_calls => $resp->tool_calls ) : () ),
89 );
90 }
91  
92 50 ▶async sub handle_chat_f {
Subroutine handle_chat_f: called CC=2 SCAR=7.0
Pod undocumented
93 50 my ($self, $session, $request) = @_;
94 50 my $trace = $self->_open_trace($request);
95 50 my $result = eval { $self->wrapped->handle_chat_f( $session, $request ) };
96 50 ▶ if ( my $err = $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 0 50 50
97 0 $self->tracing->end_trace( $trace, error => "$err" );
98 0 die $err;
99 }
100 28 ▶ my $f = $result->then( sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
101 28 my ($r) = @_;
102 28 $self->_close_trace( $trace, $r );
103 28 return Future->done($r);
104 22 ▶ })->else( sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
105 22 my ($err) = @_;
106 22 $self->tracing->end_trace( $trace, error => "$err" );
107 # The whole failure: a timeout's category rides along (k36).
108 22 return Future->fail(@_);
109 50 });
110 50 return await $f;
111 15 }
112  
113 71 ▶async sub handle_stream_f {
Subroutine handle_stream_f: called CC=2 SCAR=7.0
Pod undocumented
114 71 my ($self, $session, $request) = @_;
115 71 my $trace = $self->_open_trace($request);
116  
117 # TTFT for the routed streaming path is measured here, in the proxy: the
118 # decorator only ever sees deltas and never a Langertha::Response, so unlike
119 # the non-streaming path there is no engine-measured timing to hand off. The
120 # clock starts before the upstream stream is opened, so this ttft includes
121 # the proxy's own dispatch overhead.
122 71 my $stream_start = [ gettimeofday ];
123  
124 71 my $upstream_stream;
125 71 my $err = do {
126 71 local $@;
127 71 eval { $upstream_stream = $self->wrapped->handle_stream_f( $session, $request )->get; };
128 71 $@;
129 };
130 71 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 8 63 71
131 8 $self->tracing->end_trace( $trace, error => "$err" );
132 8 die $err;
133 }
134  
135 63 my $accumulated = '';
136 63 my $ttft;
137 63 my $closed = 0;
138  
139 return Langertha::Knarr::Stream->new(
140 upstream => $upstream_stream,
141 130 ▶ source => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
142 105 ▶ $upstream_stream->next_chunk_f->then( sub {
Subroutine __ANON__: called CC=11 SCAR=24.4
143 105 my ($delta) = @_;
144 105 ▶ if ( defined $delta ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $delta) 67 38 105
145 67 ▶ $ttft = tv_interval($stream_start) unless defined $ttft;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ttft 49 18 67
146 67 $accumulated .= $delta;
147 67 return Future->done($delta);
148 }
149 38 ▶ unless ( $closed ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($closed) 38 0 38
150 38 $closed = 1;
151 # Only claim a ttft when a delta actually arrived; an empty stream
152 # leaves $ttft undef and end_trace keeps its wall-clock fallback.
153 38 ▶ $self->tracing->end_trace(
Branch: 5 branches
BranchTrueFalseTotal
$upstream_stream->can('model') ? : 38 0 38
$upstream_stream->can('upstream_model') ? : 38 0 38
defined $ttft ? : 37 1 38
$upstream_stream->can('has_tool_calls') && $upstream_stream->has_tool_calls ? : 1 37 38
$upstream_stream->can('usage') && $upstream_stream->usage ? : 12 26 38
Condition66%4/6
$upstream_stream->can("has_tool_calls") and $upstream_stream->has_tool_calls
!ll&&!rl&&r
0371
$upstream_stream->can("usage") and $upstream_stream->usage
!ll&&!rl&&r
02612
MC/DC50%1/2
$upstream_stream->can("has_tool_calls") and $upstream_stream->has_tool_calls
$upstream_stream->can("has_tool_calls") $upstream_stream->has_tool_calls
MC/DC50%1/2
$upstream_stream->can("usage") and $upstream_stream->usage
$upstream_stream->can("usage") $upstream_stream->usage
Truth table66%2/3
A and B
A= $upstream_stream->can("has_tool_calls")B= $upstream_stream->has_tool_calls
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= $upstream_stream->can("usage")B= $upstream_stream->usage
ABresult
0X0
100
111
154 $trace,
155 output => $accumulated,
156 $self->_model_opts(
157 ( $upstream_stream->can('model') ? $upstream_stream->model : undef ),
158 ( $upstream_stream->can('upstream_model') ? $upstream_stream->upstream_model : undef ),
159 $request->model,
160 ),
161 ( defined $ttft ? ( timing => { ttft_seconds => $ttft } ) : () ),
162 # The complete tool calls, known once the stream is exhausted (k19).
163 ( $upstream_stream->can('has_tool_calls') && $upstream_stream->has_tool_calls
164 ? ( tool_calls => $upstream_stream->tool_calls ) : () ),
165 # So is the token usage the backend reported on its chunks.
166 ( $upstream_stream->can('usage') && $upstream_stream->usage
167 ? ( usage => $upstream_stream->usage ) : () ),
168 );
169 }
170 38 return Future->done(undef);
171 25 ▶ })->else( sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
172 25 my ($e) = @_;
173 25 ▶ unless ( $closed ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($closed) 25 0 25
174 25 $closed = 1;
175 25 $self->tracing->end_trace( $trace, error => "$e" );
176 }
177 25 return Future->fail(@_);
178 130 });
179 },
180 63 );
181 15 }
182  
183 1 ▶sub list_models { $_[0]->wrapped->list_models }
Subroutine list_models: called CC=1 SCAR=0.0
Pod undocumented
184  
185 15 __PACKAGE__->meta->make_immutable;
186 15 1;
187  
188 __END__
189  
190 =pod
191  
192 =encoding UTF-8
193  
194 =head1 NAME
195  
196 Langertha::Knarr::Handler::Tracing - Decorator handler that records every request as a Langfuse trace
197  
198 =head1 VERSION
199  
200 version 1.102
201  
202 =head1 SYNOPSIS
203  
204 use Langertha::Knarr::Tracing;
205 use Langertha::Knarr::Handler::Tracing;
206  
207 my $tracing = Langertha::Knarr::Tracing->new(config => $config);
208 $handler = Langertha::Knarr::Handler::Tracing->new(
209 wrapped => $handler,
210 tracing => $tracing,
211 );
212  
213 =head1 DESCRIPTION
214  
215 Decorator handler that opens a Langfuse trace + generation around every
216 chat or stream request and closes it with the assistant text once the
217 inner handler resolves (or fails). Streaming requests accumulate every
218 delta into a single output before closing the trace, so the Langfuse
219 view shows the full assembled response, with the token usage the backend
220 reported on its stream (L<Langertha::Knarr::Stream/usage>).
221  
222 The generation's C<model> is the model the backend reported answering with
223 (L<Langertha::Knarr::Response/upstream_model>,
224 L<Langertha::Knarr::Stream/upstream_model>), which can be more concrete than
225 the one asked for. When a handler labeled the answer with another name --
226 L<Langertha::Knarr::Handler::Router> answers under the configured model --
227 that name is recorded as C<configured_model> in the generation's metadata.
228 Without a reported model the generation gets the label, and a stream without
229 either the model the client asked for.
230  
231 C<knarr start> mounts this automatically when
232 the config supplies Langfuse credentials.
233  
234 A raw passthrough request that L<Langertha::Knarr> answers through the
235 handler chain after the upstream refused the client's key (see
236 L<Langertha::Knarr/raw_passthrough>) is traced here only, once, with the
237 refusing status as C<passthrough_fallback> in the trace's metadata.
238  
239 =head2 wrapped
240  
241 Required. The inner L<Langertha::Knarr::Handler> being decorated. The
242 attribute is named C<wrapped> rather than C<inner> because Moose
243 imports an C<inner()> keyword used for augmented methods.
244  
245 =head2 tracing
246  
247 Required. A L<Langertha::Knarr::Tracing> instance (or any object
248 implementing C<start_trace> / C<end_trace>).
249  
250 =head2 engine_label
251  
252 Optional. A string injected into the trace metadata's C<engine> field.
253 Defaults to C<< ref($self->wrapped) >>.
254  
255 =head1 SUPPORT
256  
257 =head2 Issues
258  
259 Please report bugs and feature requests on GitHub at
260 L<https://github.com/Getty/langertha-knarr/issues>.
261  
262 =head2 IRC
263  
264 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
265  
266 =head1 CONTRIBUTING
267  
268 Contributions are welcome! Please fork the repository and submit a pull request.
269  
270 =head1 AUTHOR
271  
272 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
273  
274 =head1 COPYRIGHT AND LICENSE
275  
276 This software is copyright (c) 2026 by Torsten Raudssus.
277  
278 This is free software; you can redistribute it and/or modify it under
279 the same terms as the Perl 5 programming language system itself.
280  
281 =cut
« blib/lib/Langertha/Knarr/Handler/ACPClient.pm ↑ Summary blib/lib/Langertha/Knarr/Protocol/Ollama.pm »