-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplete_cache_visualizer.py
More file actions
executable file
·2086 lines (1785 loc) · 79 KB
/
complete_cache_visualizer.py
File metadata and controls
executable file
·2086 lines (1785 loc) · 79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Complete Cache Visualizer
Analyzes cache behavior using COMPLETE conversation (streaming + non-streaming).
Creates visualizations and detailed statistics with TTL analysis.
Version: 21.0 (2024-10-31)
IMPORTANT: Now normalizes cache_control markers for accurate cache simulation
NEW: Chunk prefill count analysis (formerly churn rate)
"""
import sqlite3
import json
import hashlib
import tiktoken
import time
import os
from datetime import datetime, timedelta
from typing import List, Dict, Tuple, Optional
from dataclasses import dataclass
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
@dataclass
class CacheChunk:
"""Cache chunk"""
token_count: int
chunk_hash: str
sequence_number: int
created_at: datetime
last_accessed: datetime
def is_expired(self, ts: datetime, ttl_seconds: int = 300) -> bool:
return (ts - self.last_accessed).total_seconds() > ttl_seconds
def refresh(self, ts: datetime):
self.last_accessed = ts
@staticmethod
def create_from_tokens(token_ids: List[int], seq_num: int, ts: datetime):
token_str = " ".join(map(str, token_ids))
chunk_hash = hashlib.md5(token_str.encode()).hexdigest()[:16]
return CacheChunk(
token_count=len(token_ids),
chunk_hash=chunk_hash,
sequence_number=seq_num,
created_at=ts,
last_accessed=ts
)
@dataclass
class MessageSegment:
"""A single message/block in the request"""
type: str # 'system', 'user_text', 'assistant_text', 'tool_use', 'tool_result'
tokens: int
preview: str # First 300 chars
start_token: int # Starting token position in request
end_token: int # Ending token position in request
is_cache_hit: bool = False # Whether this segment was a cache hit
@dataclass
class RequestAnalysis:
"""Analysis for one request"""
index: int
request_id: str
request_type: str
message_count: int
timestamp: datetime
total_tokens: int
cache_read_tokens: int
cache_creation_tokens: int
cache_hit_rate: float
output_tokens: int
api_cache_read: Optional[int]
api_cache_creation: Optional[int]
api_input_tokens: Optional[int]
model: Optional[str]
# Message breakdown
user_text_messages: int = 0
tool_use_messages: int = 0
tool_result_messages: int = 0
assistant_messages: int = 0
# Message sequence
message_segments: List['MessageSegment'] = None
class CompleteCacheSimulator:
"""Cache simulator that processes ALL requests"""
def __init__(self, block_size: int = 64, ttl: int = 300):
self.block_size = block_size
self.ttl = ttl
self.tokenizer = tiktoken.encoding_for_model("gpt-4")
self.cache: Dict[str, Dict[int, CacheChunk]] = {}
self.analyses: List[RequestAnalysis] = []
self.cached_requests: List[CachedRequest] = [] # For TTL analysis
def normalize_body(self, body):
"""Remove cache_control and signature markers recursively for cache key calculation"""
import copy
normalized = copy.deepcopy(body)
def remove_markers(obj):
"""Recursively remove cache_control and signature from nested structures"""
if isinstance(obj, dict):
obj.pop('cache_control', None)
obj.pop('signature', None)
for value in obj.values():
remove_markers(value)
elif isinstance(obj, list):
for item in obj:
remove_markers(item)
remove_markers(normalized)
return normalized
def extract_all_tokens(self, body):
"""Extract all tokens from request (normalized - cache_control removed)"""
# Normalize body to remove cache_control markers
normalized_body = self.normalize_body(body)
all_tokens = []
if 'tools' in normalized_body and normalized_body['tools']:
all_tokens.extend(self.tokenizer.encode(json.dumps(normalized_body['tools'], separators=(',', ':'))))
if 'system' in normalized_body:
all_tokens.extend(self.tokenizer.encode(json.dumps(normalized_body['system'], separators=(',', ':'))))
if 'messages' in normalized_body and normalized_body['messages']:
all_tokens.extend(self.tokenizer.encode(json.dumps(normalized_body['messages'], separators=(',', ':'))))
return all_tokens
def chunk_tokens(self, tokens: List[int], ts: datetime) -> List[CacheChunk]:
"""Create chunks"""
chunks = []
for i in range(0, len(tokens), self.block_size):
chunk_tokens = tokens[i:i + self.block_size]
chunk = CacheChunk.create_from_tokens(chunk_tokens, i // self.block_size, ts)
chunks.append(chunk)
return chunks
def find_prefix_match(self, chunks: List[CacheChunk], ts: datetime) -> Tuple[int, int]:
"""Find longest prefix match"""
matched_tokens = 0
matched_chunks = 0
for chunk in chunks:
if chunk.chunk_hash in self.cache:
cached_chunks = self.cache[chunk.chunk_hash]
if chunk.sequence_number in cached_chunks:
cached_chunk = cached_chunks[chunk.sequence_number]
if not cached_chunk.is_expired(ts, self.ttl):
cached_chunk.refresh(ts)
matched_tokens += chunk.token_count
matched_chunks += 1
else:
break
else:
break
else:
break
return matched_tokens, matched_chunks
def update_cache(self, chunks: List[CacheChunk], start_from: int):
"""Update cache with new chunks"""
for chunk in chunks[start_from:]:
if chunk.chunk_hash not in self.cache:
self.cache[chunk.chunk_hash] = {}
self.cache[chunk.chunk_hash][chunk.sequence_number] = chunk
def cleanup_expired(self, ts: datetime):
"""Remove expired chunks"""
for h in list(self.cache.keys()):
for s in list(self.cache[h].keys()):
if self.cache[h][s].is_expired(ts, self.ttl):
del self.cache[h][s]
if not self.cache[h]:
del self.cache[h]
def analyze(self, index: int, req_id: str, ts: datetime, body_str: str,
response_str: Optional[str], req_type: str, msg_count: int):
"""Analyze one request"""
body = json.loads(body_str)
# Extract model
model = body.get('model', 'unknown')
# Extract API metrics and output tokens
api_cache_read = None
api_cache_creation = None
api_input_tokens = None
output_tokens = 0
if response_str:
try:
resp = json.loads(response_str)
usage = resp.get('body', {}).get('usage') if 'body' in resp else resp.get('usage', {})
if usage:
api_cache_read = usage.get('cache_read_input_tokens')
api_cache_creation = usage.get('cache_creation_input_tokens')
api_input_tokens = usage.get('input_tokens')
output_tokens = usage.get('output_tokens', 0)
except:
pass
# Run simulation
all_tokens = self.extract_all_tokens(body)
self.cleanup_expired(ts)
chunks = self.chunk_tokens(all_tokens, ts)
cache_read_tokens, matched_chunks = self.find_prefix_match(chunks, ts)
cache_creation_tokens = len(all_tokens) - cache_read_tokens
self.update_cache(chunks, matched_chunks)
cache_hit_rate = cache_read_tokens / len(all_tokens) if all_tokens else 0.0
# Analyze message breakdown
user_text, tool_use, tool_result, assistant = analyze_message_breakdown(body)
# Extract message segments for detailed visualization
message_segments = extract_message_segments(body, self.tokenizer)
# Mark which segments are cache hits
for segment in message_segments:
# A segment is a cache hit if it's fully within the cache read range
if segment.end_token <= cache_read_tokens:
segment.is_cache_hit = True
# Store for TTL analysis
self.cached_requests.append(CachedRequest(
timestamp=ts,
chunks=chunks,
total_tokens=len(all_tokens)
))
analysis = RequestAnalysis(
index=index,
request_id=req_id[:12],
request_type=req_type,
message_count=msg_count,
timestamp=ts,
total_tokens=len(all_tokens),
cache_read_tokens=cache_read_tokens,
cache_creation_tokens=cache_creation_tokens,
cache_hit_rate=cache_hit_rate,
output_tokens=output_tokens,
api_cache_read=api_cache_read,
api_cache_creation=api_cache_creation,
api_input_tokens=api_input_tokens,
model=model,
user_text_messages=user_text,
tool_use_messages=tool_use,
tool_result_messages=tool_result,
assistant_messages=assistant,
message_segments=message_segments
)
self.analyses.append(analysis)
return analysis
def classify_request(body_str: str) -> str:
"""Classify request type based on stream flag."""
body = json.loads(body_str)
stream = body.get('stream')
if stream is True:
return 'streaming'
elif stream is False or stream is None:
return 'non_streaming'
return 'unknown'
def format_preview_text(text: str, max_line_length: int = 100) -> str:
"""Format preview text preserving original newlines but wrapping long lines"""
lines = text.split('\n')
formatted_lines = []
for line in lines:
if len(line) <= max_line_length:
formatted_lines.append(line)
else:
# Wrap long lines
for i in range(0, len(line), max_line_length):
formatted_lines.append(line[i:i+max_line_length])
return '<br>'.join(formatted_lines)
def analyze_message_breakdown(body: dict) -> tuple:
"""Analyze message types in request body
Returns: (user_text_messages, tool_use_messages, tool_result_messages, assistant_messages)
"""
user_text = 0
tool_use = 0
tool_result = 0
assistant = 0
messages = body.get('messages', [])
for msg in messages:
role = msg.get('role', '')
content = msg.get('content', '')
if role == 'user':
# Check if it's a tool result or regular text
if isinstance(content, list):
for block in content:
if isinstance(block, dict):
if block.get('type') == 'tool_result':
tool_result += 1
elif block.get('type') == 'text':
user_text += 1
elif isinstance(content, str):
user_text += 1
elif role == 'assistant':
# Check if it contains tool use
if isinstance(content, list):
has_tool_use = any(isinstance(b, dict) and b.get('type') == 'tool_use' for b in content)
if has_tool_use:
tool_use += 1
else:
assistant += 1
else:
assistant += 1
return (user_text, tool_use, tool_result, assistant)
def normalize_for_cache(body: dict) -> dict:
"""Remove cache_control and signature markers recursively"""
import copy
normalized = copy.deepcopy(body)
def remove_markers(obj):
if isinstance(obj, dict):
obj.pop('cache_control', None)
obj.pop('signature', None)
for value in obj.values():
remove_markers(value)
elif isinstance(obj, list):
for item in obj:
remove_markers(item)
remove_markers(normalized)
return normalized
def extract_message_segments(body: dict, tokenizer) -> List[MessageSegment]:
"""Extract detailed message sequence from request body with token positions
Note: Token positions follow the cache hierarchy: tools → system → messages
Note: Normalizes out cache_control for consistent hashing
"""
# Normalize body to remove cache_control
body = normalize_for_cache(body)
segments = []
current_position = 0
# Tools (come first in cache hierarchy)
if 'tools' in body and body['tools']:
tools_content = json.dumps(body['tools'], separators=(',', ':'))
tokens = tokenizer.encode(tools_content)
num_tokens = len(tokens)
segments.append(MessageSegment(
type='tools',
tokens=num_tokens,
preview=f"{len(body['tools'])} tools defined",
start_token=current_position,
end_token=current_position + num_tokens
))
current_position += num_tokens
# System prompt (comes second in cache hierarchy)
if 'system' in body and body['system']:
system_content = json.dumps(body['system'], separators=(',', ':'))
tokens = tokenizer.encode(system_content)
num_tokens = len(tokens)
# Get preview
if isinstance(body['system'], list):
preview_text = ' '.join([block.get('text', '')[:5000] for block in body['system'] if isinstance(block, dict)])[:5000]
else:
preview_text = str(body['system'])[:5000]
segments.append(MessageSegment(
type='system',
tokens=num_tokens,
preview=preview_text,
start_token=current_position,
end_token=current_position + num_tokens
))
current_position += num_tokens
# Messages in sequence
messages = body.get('messages', [])
for msg in messages:
role = msg.get('role', '')
content = msg.get('content', '')
# Tokenize this message
msg_json = json.dumps(msg, separators=(',', ':'))
tokens = tokenizer.encode(msg_json)
if role == 'user':
# Check if it contains tool results or text
if isinstance(content, list):
for block in content:
if isinstance(block, dict):
block_type = block.get('type', 'unknown')
block_json = json.dumps(block, separators=(',', ':'))
block_tokens = tokenizer.encode(block_json)
if block_type == 'tool_result':
preview = str(block.get('content', ''))[:5000]
num_tokens = len(block_tokens)
segments.append(MessageSegment(
type='tool_result',
tokens=num_tokens,
preview=preview,
start_token=current_position,
end_token=current_position + num_tokens
))
current_position += num_tokens
elif block_type == 'text':
preview = block.get('text', '')[:5000]
num_tokens = len(block_tokens)
segments.append(MessageSegment(
type='user_text',
tokens=num_tokens,
preview=preview,
start_token=current_position,
end_token=current_position + num_tokens
))
current_position += num_tokens
elif isinstance(content, str):
preview = content[:5000]
num_tokens = len(tokens)
segments.append(MessageSegment(
type='user_text',
tokens=num_tokens,
preview=preview,
start_token=current_position,
end_token=current_position + num_tokens
))
current_position += num_tokens
elif role == 'assistant':
# Check if it contains tool use or text
if isinstance(content, list):
for block in content:
if isinstance(block, dict):
block_type = block.get('type', 'unknown')
block_json = json.dumps(block, separators=(',', ':'))
block_tokens = tokenizer.encode(block_json)
if block_type == 'tool_use':
tool_name = block.get('name', 'unknown')
preview = f"Tool: {tool_name}, Input: {str(block.get('input', {}))[:4900]}"
num_tokens = len(block_tokens)
segments.append(MessageSegment(
type='tool_use',
tokens=num_tokens,
preview=preview,
start_token=current_position,
end_token=current_position + num_tokens
))
current_position += num_tokens
elif block_type == 'text':
preview = block.get('text', '')[:5000]
num_tokens = len(block_tokens)
segments.append(MessageSegment(
type='assistant_text',
tokens=num_tokens,
preview=preview,
start_token=current_position,
end_token=current_position + num_tokens
))
current_position += num_tokens
elif isinstance(content, str):
preview = content[:5000]
num_tokens = len(tokens)
segments.append(MessageSegment(
type='assistant_text',
tokens=num_tokens,
preview=preview,
start_token=current_position,
end_token=current_position + num_tokens
))
current_position += num_tokens
return segments
def calculate_time_stats(analyses: List[RequestAnalysis]) -> Dict:
"""Calculate time between turns statistics"""
if len(analyses) < 2:
return None
gaps = []
for i in range(1, len(analyses)):
gap = (analyses[i].timestamp - analyses[i-1].timestamp).total_seconds()
gaps.append(gap)
gaps_sorted = sorted(gaps)
n = len(gaps_sorted)
return {
'mean': np.mean(gaps),
'p25': gaps_sorted[int(n * 0.25)],
'p50': gaps_sorted[int(n * 0.50)],
'p75': gaps_sorted[int(n * 0.75)],
'p90': gaps_sorted[int(n * 0.90)],
}
def calculate_model_stats(analyses: List[RequestAnalysis]) -> Dict[str, Dict]:
"""Calculate usage statistics by model"""
model_stats = {}
for a in analyses:
model = a.model or 'unknown'
if model not in model_stats:
model_stats[model] = {
'requests': 0,
'input_tokens': 0,
'output_tokens': 0
}
model_stats[model]['requests'] += 1
model_stats[model]['input_tokens'] += a.total_tokens
model_stats[model]['output_tokens'] += a.output_tokens
return model_stats
def calculate_context_stats(analyses: List[RequestAnalysis]) -> Dict:
"""Calculate context length statistics"""
if not analyses:
return None
context_lengths = [a.total_tokens for a in analyses]
context_sorted = sorted(context_lengths)
n = len(context_sorted)
# Calculate incremental changes (message additions)
incremental_changes = []
for i in range(1, len(analyses)):
change = analyses[i].total_tokens - analyses[i-1].total_tokens
if change > 0: # Only count additions
incremental_changes.append(change)
inc_sorted = sorted(incremental_changes) if incremental_changes else []
n_inc = len(inc_sorted)
return {
'mean': np.mean(context_lengths),
'p25': context_sorted[int(n * 0.25)],
'p50': context_sorted[int(n * 0.50)],
'p75': context_sorted[int(n * 0.75)],
'p90': context_sorted[int(n * 0.90)],
'max': context_sorted[-1],
'incremental': {
'mean': np.mean(incremental_changes) if incremental_changes else 0,
'p25': inc_sorted[int(n_inc * 0.25)] if inc_sorted else 0,
'p50': inc_sorted[int(n_inc * 0.50)] if inc_sorted else 0,
'p75': inc_sorted[int(n_inc * 0.75)] if inc_sorted else 0,
'p90': inc_sorted[int(n_inc * 0.90)] if inc_sorted else 0,
'max': inc_sorted[-1] if inc_sorted else 0,
}
}
@dataclass
class CachedRequest:
"""Pre-tokenized request for TTL analysis"""
timestamp: datetime
chunks: List[CacheChunk]
total_tokens: int
def analyze_ttl_impact_fast(cached_requests: List[CachedRequest], block_size: int, interpolation_interval: int = 15, skip_long_ttls: bool = False, show_progress: bool = True) -> Tuple[Dict[int, float], Dict[int, int], Dict[int, List[Tuple[datetime, int]]], Dict[int, List[Tuple[datetime, float]]], Dict[int, float], Dict[int, float]]:
"""Fast TTL analysis using pre-tokenized requests with interpolated time points
Returns:
- hit_rates: Dict mapping TTL to cache hit rate
- max_working_set: Dict mapping TTL to maximum working set size in tokens
- working_set_timeseries: Dict mapping TTL to list of (timestamp, tokens_in_cache) - only for graphed TTLs
- cache_hit_rate_timeseries: Dict mapping TTL to list of (timestamp, hit_rate%) - only for graphed TTLs
- churn_rates: Dict mapping TTL to average churn rate
- churn_efficiency: Dict mapping TTL to churn efficiency %
"""
# All TTLs for statistics
if skip_long_ttls:
all_ttl_values = [60, 120, 180, 240, 300, 600, 900, 1800, 3600, 7200, 14400, 28800, 86400]
else:
all_ttl_values = [60, 120, 180, 240, 300, 600, 900, 1800, 3600, 7200, 14400, 28800, 86400, 259200]
# Only generate detailed timeseries for graphed TTLs (optimization)
graphed_ttls = [60, 300, 900, 3600, 86400]
results = {}
max_working_set = {}
working_set_timeseries = {}
cache_hit_rate_timeseries = {}
churn_rates = {}
churn_efficiency = {}
if not cached_requests:
return results, max_working_set, working_set_timeseries, cache_hit_rate_timeseries, churn_rates, churn_efficiency
# Get time range for interpolation
start_time = cached_requests[0].timestamp
end_time = cached_requests[-1].timestamp + timedelta(minutes=interpolation_interval) # Buffer for decay
total_ttls = len(all_ttl_values)
for ttl_idx, ttl in enumerate(all_ttl_values):
# Progress indicator
if show_progress:
ttl_labels = {60: '1m', 120: '2m', 180: '3m', 240: '4m', 300: '5m',
600: '10m', 900: '15m', 1800: '30m', 3600: '1h',
7200: '2h', 14400: '4h', 28800: '8h', 86400: '24h', 259200: '72h'}
print(f"\r Analyzing TTL impact... {ttl_idx+1}/{total_ttls} ({ttl_labels.get(ttl, str(ttl)+'s')})", end='', flush=True)
use_interpolation = ttl in graphed_ttls
cache: Dict[str, Dict[int, CacheChunk]] = {}
total_cache_read = 0
total_tokens = 0
max_cache_tokens = 0
# Track chunk lifecycle for churn analysis
chunk_lifecycle = {} # (hash, seq) -> creation_count
# Generate time points
if use_interpolation:
# Interpolated time points using specified interval
time_points = []
current_time = start_time
while current_time <= end_time:
time_points.append(current_time)
current_time += timedelta(minutes=interpolation_interval)
# Add actual request timestamps
for req in cached_requests:
if req.timestamp not in time_points:
time_points.append(req.timestamp)
time_points.sort()
else:
# Just use request timestamps (faster)
time_points = [req.timestamp for req in cached_requests]
# Process requests and calculate working set at each time point
req_index = 0
timeseries = [] if use_interpolation else None
hit_rate_timeseries = [] if use_interpolation else None
cumulative_cache_read = 0
cumulative_total_tokens = 0
for time_point in time_points:
# Process all requests up to this time point
while req_index < len(cached_requests) and cached_requests[req_index].timestamp <= time_point:
req = cached_requests[req_index]
total_tokens += req.total_tokens
# Find prefix match
matched_tokens = 0
matched_chunks = 0
for chunk in req.chunks:
if chunk.chunk_hash in cache:
cached_chunks = cache[chunk.chunk_hash]
if chunk.sequence_number in cached_chunks:
cached_chunk = cached_chunks[chunk.sequence_number]
time_diff = (req.timestamp - cached_chunk.last_accessed).total_seconds()
if time_diff <= ttl:
matched_tokens += chunk.token_count
matched_chunks += 1
# Refresh
cached_chunks[chunk.sequence_number] = CacheChunk(
token_count=chunk.token_count,
chunk_hash=chunk.chunk_hash,
sequence_number=chunk.sequence_number,
created_at=cached_chunk.created_at,
last_accessed=req.timestamp
)
else:
break
else:
break
else:
break
total_cache_read += matched_tokens
cumulative_cache_read += matched_tokens
cumulative_total_tokens += req.total_tokens
# Update cache with new chunks
for chunk in req.chunks[matched_chunks:]:
# Track chunk creation for churn analysis
chunk_key = (chunk.chunk_hash, chunk.sequence_number)
if chunk_key not in chunk_lifecycle:
chunk_lifecycle[chunk_key] = 1
else:
chunk_lifecycle[chunk_key] += 1
if chunk.chunk_hash not in cache:
cache[chunk.chunk_hash] = {}
cache[chunk.chunk_hash][chunk.sequence_number] = CacheChunk(
token_count=chunk.token_count,
chunk_hash=chunk.chunk_hash,
sequence_number=chunk.sequence_number,
created_at=req.timestamp,
last_accessed=req.timestamp
)
req_index += 1
# Calculate working set size at this time point
current_cache_tokens = 0
for chunk_hash_dict in cache.values():
for chunk in chunk_hash_dict.values():
time_since_access = (time_point - chunk.last_accessed).total_seconds()
if time_since_access <= ttl:
current_cache_tokens += chunk.token_count
# Calculate rolling cache hit rate
rolling_hit_rate = (cumulative_cache_read / cumulative_total_tokens * 100) if cumulative_total_tokens > 0 else 0.0
if use_interpolation:
timeseries.append((time_point, current_cache_tokens))
hit_rate_timeseries.append((time_point, rolling_hit_rate))
max_cache_tokens = max(max_cache_tokens, current_cache_tokens)
hit_rate = total_cache_read / total_tokens if total_tokens > 0 else 0.0
results[ttl] = hit_rate
max_working_set[ttl] = max_cache_tokens
if use_interpolation:
working_set_timeseries[ttl] = timeseries
cache_hit_rate_timeseries[ttl] = hit_rate_timeseries
# Calculate churn metrics
if chunk_lifecycle:
creation_counts = list(chunk_lifecycle.values())
avg_churn = sum(creation_counts) / len(creation_counts)
stable_chunks = sum(1 for count in creation_counts if count == 1)
efficiency = (stable_chunks / len(creation_counts)) * 100
else:
avg_churn = 0.0
efficiency = 0.0
churn_rates[ttl] = avg_churn
churn_efficiency[ttl] = efficiency
# Final progress message
if show_progress:
print(f"\r Analyzing TTL impact... {total_ttls}/{total_ttls} (complete) ", flush=True)
return results, max_working_set, working_set_timeseries, cache_hit_rate_timeseries, churn_rates, churn_efficiency
def create_cache_visualization(analyses: List[RequestAnalysis]) -> go.Figure:
"""Create stacked bar chart of cache usage"""
# Subsample if too many requests for visualization
if len(analyses) > 5000:
step = len(analyses) // 5000
sampled = analyses[::step]
note = f" (showing every {step}th request)"
else:
sampled = analyses
note = ""
fig = go.Figure()
x_labels = [f"R{a.index}" for a in sampled]
# Cache read (grey)
cache_read = [a.cache_read_tokens for a in sampled]
fig.add_trace(go.Bar(
x=x_labels, y=cache_read,
name='Cache Read',
marker=dict(color='lightgrey'),
opacity=0.8
))
# Cache creation (red)
cache_creation = [a.cache_creation_tokens for a in sampled]
fig.add_trace(go.Bar(
x=x_labels, y=cache_creation,
name='Cache Creation',
marker=dict(color='lightcoral'),
opacity=0.8
))
# Output (blue)
output = [a.output_tokens for a in sampled]
fig.add_trace(go.Bar(
x=x_labels, y=output,
name='Output',
marker=dict(color='darkblue'),
opacity=0.9
))
num_requests = len(sampled)
width = max(1200, num_requests * 40)
title = f'Cache Usage - {len(analyses):,} requests{note}' if len(analyses) != num_requests else None
fig.update_layout(
title=title,
xaxis_title='Request Number',
yaxis_title='Tokens',
barmode='stack',
height=700,
width=width,
showlegend=True,
plot_bgcolor='white',
xaxis=dict(showticklabels=False)
)
return fig
def create_cache_visualization_skinny(analyses: List[RequestAnalysis]) -> go.Figure:
"""Create compressed/skinny stacked bar chart with no gaps - fits screen width"""
fig = go.Figure()
x_labels = [f"R{a.index}" for a in analyses]
# Cache read (grey)
cache_read = [a.cache_read_tokens for a in analyses]
fig.add_trace(go.Bar(
x=x_labels, y=cache_read,
name='Cache Read',
marker=dict(color='lightgrey'),
opacity=0.8
))
# Cache creation (red)
cache_creation = [a.cache_creation_tokens for a in analyses]
fig.add_trace(go.Bar(
x=x_labels, y=cache_creation,
name='Cache Creation',
marker=dict(color='lightcoral'),
opacity=0.8
))
# Output (blue)
output = [a.output_tokens for a in analyses]
fig.add_trace(go.Bar(
x=x_labels, y=output,
name='Output',
marker=dict(color='darkblue'),
opacity=0.9
))
fig.update_layout(
title=f'Cache Usage (Skinny) - {len(analyses):,} requests',
xaxis_title='Request Number',
yaxis_title='Tokens',
barmode='stack',
height=700,
width=1920, # Fixed width for screen
showlegend=True,
plot_bgcolor='white',
xaxis=dict(showticklabels=False),
bargap=0, # NO GAP between bars
bargroupgap=0 # NO GAP between groups
)
return fig
def create_detailed_cache_visualization(analyses: List[RequestAnalysis]) -> go.Figure:
"""Create detailed stacked bar chart showing actual message sequence with cache hit coloring"""
# Subsample if too many requests
if len(analyses) > 5000:
step = len(analyses) // 5000
sampled = analyses[::step]
note = f" (showing every {step}th request)"
else:
sampled = analyses
note = ""
# Color mapping for different message types (when cache hit)
cache_hit_colors = {
'tools': '#B8B8B8', # Medium-light grey
'system': '#D0D0D0', # Light grey
'user_text': '#E8E8E8', # Very light grey
'assistant_text': '#808080', # Medium grey
'tool_use': '#606060', # Dark grey
'tool_result': '#A8A8A8' # Medium-light grey
}
# Color for cache misses (same as cache creation in simple graph)
cache_miss_color = 'lightcoral'
fig = go.Figure()
# For each request, we need to create trace data for each segment
max_segments = max(len(a.message_segments) if a.message_segments else 0 for a in sampled)
# Create traces for each segment position
for seg_idx in range(max_segments):
# Collect data for this segment position across all requests
y_values = []
hover_texts = []
colors_list = []
for analysis in sampled:
if analysis.message_segments and seg_idx < len(analysis.message_segments):
segment = analysis.message_segments[seg_idx]
y_values.append(segment.tokens)
# Determine color based on cache hit status
if segment.is_cache_hit:
color = cache_hit_colors.get(segment.type, '#999999')
status = "CACHE HIT"
else:
color = cache_miss_color
status = "CACHE MISS"
# Format preview preserving original line breaks and wrapping long lines
preview_text = segment.preview[:5000] # ~1000 words
formatted_preview = format_preview_text(preview_text, max_line_length=100)
hover_text = f"<b>{status}</b><br>Type: {segment.type}<br>Tokens: {segment.tokens:,}<br><br><b>Preview:</b><br>{formatted_preview}"
hover_texts.append(hover_text)
colors_list.append(color)
else:
y_values.append(0)
hover_texts.append("")
colors_list.append('#FFFFFF')
fig.add_trace(go.Bar(
x=[f"R{a.index}" for a in sampled],
y=y_values,
name=f'Segment {seg_idx}',
marker=dict(color=colors_list, line=dict(width=0)),
hovertext=hover_texts,
hoverinfo='text',
showlegend=False
))
# Add output tokens (same color as simple graph)
output = [a.output_tokens for a in sampled]
fig.add_trace(go.Bar(
x=[f"R{a.index}" for a in sampled],
y=output,
name='Output',
marker=dict(color='darkblue'),
opacity=0.9
))
# Add legend-only entries to explain colors
for msg_type, color in cache_hit_colors.items():
fig.add_trace(go.Bar(
x=['LEGEND_ONLY'],
y=[1],
marker=dict(color=color),
name=f'{msg_type} (cached)',
showlegend=True,
visible='legendonly'
))
fig.add_trace(go.Bar(
x=['LEGEND_ONLY'],
y=[1],
marker=dict(color=cache_miss_color),
name='Cache Miss',
showlegend=True,
visible='legendonly'
))
num_requests = len(sampled)
width = max(1200, num_requests * 40)
title = f'Detailed Message Sequence - {len(analyses):,} requests{note}' if len(analyses) != num_requests else f'Detailed Message Sequence - {len(analyses):,} requests'
fig.update_layout(
title=title,
xaxis_title='Request Number',
yaxis_title='Tokens',
barmode='stack',
height=700,
width=width,
showlegend=True,
plot_bgcolor='white',
xaxis=dict(showticklabels=False)
)
return fig
def create_detailed_cache_visualization_skinny(analyses: List[RequestAnalysis]) -> go.Figure:
"""Create detailed skinny stacked bar chart showing actual message sequence with cache hit coloring - no gaps"""
# Color mapping for different message types (when cache hit)
cache_hit_colors = {
'tools': '#B8B8B8', # Medium-light grey
'system': '#D0D0D0', # Light grey
'user_text': '#E8E8E8', # Very light grey
'assistant_text': '#808080', # Medium grey
'tool_use': '#606060', # Dark grey
'tool_result': '#A8A8A8' # Medium-light grey
}