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

filter: Statementstmt 89.4% 76 / 85 Branchbran 71.0% 27 / 38 Conditioncond 45.4% 10 / 22 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 94.4% 17 / 18 Podpod 0.0% 0 / 3 totaltotal 73.0% 130 / 178 CC 28 SCAR 19.1
CC
28
Cov
78%
__ANON__
14.0
_model_opts
8.5
_close_trace
7.0
CRAP 6.8
« blib/lib/Langertha/Knarr/CLI/Cmd/Init.pm ↑ Summary blib/lib/Langertha/Knarr/Reasoning.pm »
1 package Langertha::Knarr::Handler::Tracing;
2 # ABSTRACT: Decorator handler that records every request as a Langfuse trace
3 7 our $VERSION = '1.103';
4 7 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 7 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 7 ▶use Time::HiRes qw( gettimeofday tv_interval );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 7 ▶use Langertha::Knarr::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 7 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 7 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 7 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 12 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
39 7 );
40  
41 11 ▶sub _open_trace {
Subroutine _open_trace: called CC=4 SCAR=15.8
42 11 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 11 ▶ ? ( passthrough_fallback => $request->extra->{passthrough_fallback} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
defined $request->extra->{'passthrough_fallback'} ? : 0 11 11
Condition50%2/4
$request->model // ""
l!l
110
$self->engine_label // ref $self->wrapped
l!l
011
MC/DC0%0/1
$request->model // ""
$request->model
MC/DC0%0/1
$self->engine_label // ref $self->wrapped
$self->engine_label
Truth table50%1/2
A
A= $request->model
Aresult
11
00
Truth table50%1/2
A
A= $self->engine_label
Aresult
11
00
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 10 ▶sub _model_opts {
Subroutine _model_opts: called CC=6 SCAR=21.4
63 10 my ($self, $label, $reported, $fallback) = @_;
64 10 ▶ my $model = $reported // $label // $fallback;
Condition66%4/6
($reported // $label) // $fallback
l!l&&r!l&&!r
730
$reported // $label
l!l&&r!l&&!r
073
MC/DC0%0/3
($reported // $label) // $fallback
$reported $label $fallback
Truth table50%2/4
A // B // C
A= $reportedB= $labelC= $fallback
ABCresult
1XX1
01X1
0011
0000
65 return (
66 10 ▶ model => $model,
Branch: 1 branch
BranchTrueFalseTotal
defined $reported && defined $label && $label ne $reported ? : 0 10 10
Condition33%2/6
defined $reported and defined $label and $label ne $reported
!ll&&!rl&&r
1000
defined $reported and defined $label
!ll&&!rl&&r
1000
MC/DC0%0/3
defined $reported and defined $label and $label ne $reported
defined $reported defined $label $label ne $reported
Truth table25%1/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 7 ▶sub _close_trace {
Subroutine _close_trace: called CC=7 SCAR=19.5
73 7 my ($self, $trace, $r) = @_;
74 7 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 7 ▶ $self->tracing->end_trace(
Branch: 6 branches
BranchTrueFalseTotal
$resp->usage ? : 1 6 7
$resp->timing ? : 1 6 7
defined $resp->id ? : 1 6 7
defined $resp->thinking ? : 1 6 7
$resp->rate_limit ? : 1 6 7
$resp->has_tool_calls ? : 1 6 7
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 8 ▶async sub handle_chat_f {
Subroutine handle_chat_f: called CC=2 SCAR=7.0
Pod undocumented
93 8 my ($self, $session, $request) = @_;
94 8 my $trace = $self->_open_trace($request);
95 8 my $result = eval { $self->wrapped->handle_chat_f( $session, $request ) };
96 8 ▶ if ( my $err = $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 0 8 8
97 0 $self->tracing->end_trace( $trace, error => "$err" );
98 0 die $err;
99 }
100 7 ▶ my $f = $result->then( sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
101 7 my ($r) = @_;
102 7 $self->_close_trace( $trace, $r );
103 7 return Future->done($r);
104 1 ▶ })->else( sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
105 1 my ($err) = @_;
106 1 $self->tracing->end_trace( $trace, error => "$err" );
107 # The whole failure: a timeout's category rides along (k36).
108 1 return Future->fail(@_);
109 8 });
110 8 return await $f;
111 7 }
112  
113 3 ▶async sub handle_stream_f {
Subroutine handle_stream_f: called CC=2 SCAR=7.6
Pod undocumented
114 3 my ($self, $session, $request) = @_;
115 3 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 3 my $stream_start = [ gettimeofday ];
123  
124 3 my $upstream_stream;
125 3 my $err = do {
126 3 local $@;
127 3 eval { $upstream_stream = $self->wrapped->handle_stream_f( $session, $request )->get; };
128 3 $@;
129 };
130 3 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 3 3
131 0 $self->tracing->end_trace( $trace, error => "$err" );
132 0 die $err;
133 }
134  
135 3 my $accumulated = '';
136 3 my $ttft;
137 3 my $closed = 0;
138  
139 return Langertha::Knarr::Stream->new(
140 upstream => $upstream_stream,
141 9 ▶ source => sub {
Subroutine __ANON__: called CC=1 SCAR=0.7
142 9 ▶ $upstream_stream->next_chunk_f->then( sub {
Subroutine __ANON__: called CC=11 SCAR=26.4
143 9 my ($delta) = @_;
144 9 ▶ if ( defined $delta ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $delta) 6 3 9
145 6 ▶ $ttft = tv_interval($stream_start) unless defined $ttft;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ttft 2 4 6
146 6 $accumulated .= $delta;
147 6 return Future->done($delta);
148 }
149 3 ▶ unless ( $closed ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($closed) 3 0 3
150 3 $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 3 ▶ $self->tracing->end_trace(
Branch: 5 branches
BranchTrueFalseTotal
$upstream_stream->can('model') ? : 3 0 3
$upstream_stream->can('upstream_model') ? : 3 0 3
defined $ttft ? : 2 1 3
$upstream_stream->can('has_tool_calls') && $upstream_stream->has_tool_calls ? : 0 3 3
$upstream_stream->can('usage') && $upstream_stream->usage ? : 0 3 3
Condition33%2/6
$upstream_stream->can("has_tool_calls") and $upstream_stream->has_tool_calls
!ll&&!rl&&r
030
$upstream_stream->can("usage") and $upstream_stream->usage
!ll&&!rl&&r
030
MC/DC0%0/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/DC0%0/2
$upstream_stream->can("usage") and $upstream_stream->usage
$upstream_stream->can("usage") $upstream_stream->usage
Truth table33%1/3
A and B
A= $upstream_stream->can("has_tool_calls")B= $upstream_stream->has_tool_calls
ABresult
0X0
100
111
Truth table33%1/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 3 return Future->done(undef);
171 0 ▶ })->else( sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
172 0 my ($e) = @_;
173 0 ▶ unless ( $closed ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($closed) 0 0 0
174 0 $closed = 1;
175 0 $self->tracing->end_trace( $trace, error => "$e" );
176 }
177 0 return Future->fail(@_);
178 9 });
179 },
180 3 );
181 7 }
182  
183 1 ▶sub list_models { $_[0]->wrapped->list_models }
Subroutine list_models: called CC=1 SCAR=0.0
Pod undocumented
184  
185 7 __PACKAGE__->meta->make_immutable;
186 7 1;
187  
188 __END__
« blib/lib/Langertha/Knarr/CLI/Cmd/Init.pm ↑ Summary blib/lib/Langertha/Knarr/Reasoning.pm »