ctxcache 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. ctxcache/__init__.py +109 -0
  2. ctxcache/adapters/__init__.py +15 -0
  3. ctxcache/adapters/anthropic.py +34 -0
  4. ctxcache/adapters/base.py +25 -0
  5. ctxcache/adapters/bedrock.py +46 -0
  6. ctxcache/adapters/gemini.py +34 -0
  7. ctxcache/adapters/openai.py +42 -0
  8. ctxcache/bedrock_converse.py +67 -0
  9. ctxcache/bench/__init__.py +1 -0
  10. ctxcache/bench/runner.py +96 -0
  11. ctxcache/cli.py +326 -0
  12. ctxcache/compaction.py +102 -0
  13. ctxcache/cost.py +171 -0
  14. ctxcache/data/breaks.yaml +124 -0
  15. ctxcache/data/providers.toml +199 -0
  16. ctxcache/exceptions.py +23 -0
  17. ctxcache/fingerprint.py +68 -0
  18. ctxcache/guard.py +253 -0
  19. ctxcache/integrations/__init__.py +17 -0
  20. ctxcache/integrations/langchain.py +7 -0
  21. ctxcache/integrations/langgraph.py +144 -0
  22. ctxcache/integrations/openai_agents.py +42 -0
  23. ctxcache/integrations/pydantic_ai.py +44 -0
  24. ctxcache/layout.py +255 -0
  25. ctxcache/ledger.py +179 -0
  26. ctxcache/memory/__init__.py +25 -0
  27. ctxcache/memory/checks.py +53 -0
  28. ctxcache/memory/recall.py +50 -0
  29. ctxcache/memory/store.py +315 -0
  30. ctxcache/offload.py +134 -0
  31. ctxcache/openai_chat.py +61 -0
  32. ctxcache/otel.py +60 -0
  33. ctxcache/planner.py +167 -0
  34. ctxcache/policies/__init__.py +36 -0
  35. ctxcache/policies/route.py +179 -0
  36. ctxcache/replay.py +193 -0
  37. ctxcache/scenarios.py +250 -0
  38. ctxcache/segments.py +162 -0
  39. ctxcache/sim/__init__.py +13 -0
  40. ctxcache/sim/cache_sim.py +152 -0
  41. ctxcache/sim/tokens.py +56 -0
  42. ctxcache/testing.py +250 -0
  43. ctxcache/tools.py +49 -0
  44. ctxcache/trace.py +109 -0
  45. ctxcache/wrapper.py +609 -0
  46. ctxcache-0.3.0.dist-info/METADATA +218 -0
  47. ctxcache-0.3.0.dist-info/RECORD +50 -0
  48. ctxcache-0.3.0.dist-info/WHEEL +4 -0
  49. ctxcache-0.3.0.dist-info/entry_points.txt +2 -0
  50. ctxcache-0.3.0.dist-info/licenses/LICENSE +176 -0
ctxcache/planner.py ADDED
@@ -0,0 +1,167 @@
1
+ """Prompt cache planner: breakpoints, TTL, and cache key planning (BUILD_HANDBOOK §5.3, §5.4, INV-11)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from dataclasses import dataclass, field
7
+
8
+ from ctxcache.segments import Segment, StabilityClass
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Breakpoint:
13
+ segment_kind: str
14
+ segment_index: int
15
+ ttl_seconds: int = 300
16
+
17
+
18
+ @dataclass
19
+ class CachePlan:
20
+ should_cache: bool
21
+ breakpoints: list[Breakpoint] = field(default_factory=list)
22
+ prompt_cache_key: str | None = None
23
+
24
+
25
+ class TTLOptimizer:
26
+ """Predicts inter-call gaps and chooses between 5-minute and 1-hour TTL (BUILD_HANDBOOK §5.4).
27
+
28
+ Break-even rule (§5.4):
29
+ For a stable prefix of P tokens with k expected gaps longer than 5 minutes before session ends:
30
+ - 5-minute TTL rewrites P at each long gap -> ~1.25 * k * P extra cost.
31
+ - 1-hour TTL writes once at 2.0 * P instead of 1.25 * P -> 0.75 * P extra cost.
32
+ - Use 1 hour if k >= 1 and the session is expected to continue past the gap.
33
+ """
34
+
35
+ def __init__(self, alpha: float = 0.3):
36
+ self.alpha = alpha
37
+ self._last_call_time: dict[str, float] = {}
38
+ self._gap_ewma: dict[str, float] = {}
39
+ self._session_decisions: dict[str, bool] = {}
40
+
41
+ def record_call(self, session_id: str, timestamp: float | None = None) -> None:
42
+ """Record a call timestamp and update exponential moving average of inter-call gaps."""
43
+ ts = timestamp if timestamp is not None else time.time()
44
+ if session_id in self._last_call_time:
45
+ gap = ts - self._last_call_time[session_id]
46
+ if session_id in self._gap_ewma:
47
+ self._gap_ewma[session_id] = (
48
+ self.alpha * gap + (1.0 - self.alpha) * self._gap_ewma[session_id]
49
+ )
50
+ else:
51
+ self._gap_ewma[session_id] = gap
52
+ self._last_call_time[session_id] = ts
53
+
54
+ def should_use_long_ttl(
55
+ self,
56
+ session_id: str | None = None,
57
+ expected_calls: int = 2,
58
+ expected_pause: bool = False,
59
+ ) -> bool:
60
+ """Evaluate if 1-hour TTL on stable prefix saves money over 5-minute TTL (§5.4)."""
61
+ if expected_calls <= 1:
62
+ return False
63
+
64
+ # If decision already established for this session, preserve it (§5.4 once per session rule)
65
+ if session_id and session_id in self._session_decisions:
66
+ return self._session_decisions[session_id]
67
+
68
+ decision = False
69
+ if expected_pause:
70
+ decision = True
71
+ elif session_id and session_id in self._gap_ewma:
72
+ # If EWMA inter-call gap exceeds 300 seconds (5 mins), gap k >= 1 is anticipated
73
+ if self._gap_ewma[session_id] > 300.0:
74
+ decision = True
75
+
76
+ if session_id:
77
+ self._session_decisions[session_id] = decision
78
+ return decision
79
+
80
+ def clear(self) -> None:
81
+ """Clear optimizer state."""
82
+ self._last_call_time.clear()
83
+ self._gap_ewma.clear()
84
+ self._session_decisions.clear()
85
+
86
+
87
+ _global_ttl_optimizer = TTLOptimizer()
88
+
89
+
90
+ def get_ttl_optimizer() -> TTLOptimizer:
91
+ return _global_ttl_optimizer
92
+
93
+
94
+ def plan_breakpoints(
95
+ provider: str,
96
+ segments: list[Segment],
97
+ expected_calls: int = 2,
98
+ use_long_ttl_on_stable: bool | None = None,
99
+ session_id: str | None = None,
100
+ expected_pause: bool = False,
101
+ ) -> CachePlan:
102
+ """Decide whether and where to place cache breakpoints and metadata (INV-11).
103
+
104
+ Rules:
105
+ 1. If expected_calls <= 1, do not add cache metadata (skips write premium on one-shots).
106
+ 2. Respect provider limits: max 4 breakpoints for Anthropic and OpenAI.
107
+ 3. Place 1-hour TTL on stable prefix only, before 5-minute entries (INV-11).
108
+ """
109
+ if expected_calls <= 1:
110
+ return CachePlan(should_cache=False, breakpoints=[])
111
+
112
+ # Determine whether 1-hour TTL on stable prefix is economically advantageous (§5.4)
113
+ if use_long_ttl_on_stable is not None:
114
+ long_ttl_active = use_long_ttl_on_stable
115
+ else:
116
+ long_ttl_active = get_ttl_optimizer().should_use_long_ttl(
117
+ session_id=session_id,
118
+ expected_calls=expected_calls,
119
+ expected_pause=expected_pause,
120
+ )
121
+
122
+ breakpoints: list[Breakpoint] = []
123
+ stable_segments = [
124
+ s for s in segments if s.stability in (StabilityClass.STATIC, StabilityClass.SESSION)
125
+ ]
126
+ append_segments = [s for s in segments if s.stability == StabilityClass.APPEND]
127
+
128
+ # Breakpoint 1: Stable boundary (STATIC / SESSION)
129
+ if stable_segments:
130
+ last_stable = stable_segments[-1]
131
+ ttl = 3600 if long_ttl_active else 300
132
+ breakpoints.append(
133
+ Breakpoint(
134
+ segment_kind=last_stable.kind,
135
+ segment_index=last_stable.index,
136
+ ttl_seconds=ttl,
137
+ )
138
+ )
139
+
140
+ # Breakpoints on rolling conversation tail
141
+ # Provider limit is max 4 breakpoints (Anthropic, OpenAI)
142
+ remaining_slots = 4 - len(breakpoints)
143
+ if append_segments and remaining_slots > 0:
144
+ # Choose most recent append messages (closer to turn tail)
145
+ selected_appends = append_segments[-remaining_slots:]
146
+ for seg in selected_appends:
147
+ breakpoints.append(
148
+ Breakpoint(
149
+ segment_kind=seg.kind,
150
+ segment_index=seg.index,
151
+ ttl_seconds=300, # Conversation tail always gets 5-minute TTL
152
+ )
153
+ )
154
+
155
+ # Enforce INV-11: 1-hour TTL entries must precede 5-minute entries
156
+ breakpoints.sort(key=lambda b: 0 if b.ttl_seconds == 3600 else 1)
157
+
158
+ # Ensure hard limit of 4 breakpoints
159
+ final_breakpoints = breakpoints[:4]
160
+
161
+ cache_key = f"ctxcache:{session_id}" if session_id else None
162
+
163
+ return CachePlan(
164
+ should_cache=True,
165
+ breakpoints=final_breakpoints,
166
+ prompt_cache_key=cache_key,
167
+ )
@@ -0,0 +1,36 @@
1
+ """Policy implementations for CtxCache context optimization (BUILD_HANDBOOK §5).
2
+
3
+ Re-exports relocation, offloading, compaction, and routing policies.
4
+ """
5
+
6
+ from ctxcache.compaction import (
7
+ CompactionPlan,
8
+ compute_compaction_payback,
9
+ )
10
+ from ctxcache.layout import optimize_layout
11
+ from ctxcache.offload import (
12
+ BlobStore,
13
+ get_blob_store,
14
+ is_read_tool_registered,
15
+ offload_large_tool_outputs,
16
+ )
17
+ from ctxcache.policies.route import (
18
+ RouteDecision,
19
+ RouteVerdict,
20
+ calculate_break_even_n,
21
+ evaluate_route,
22
+ )
23
+
24
+ __all__ = [
25
+ "optimize_layout",
26
+ "BlobStore",
27
+ "get_blob_store",
28
+ "is_read_tool_registered",
29
+ "offload_large_tool_outputs",
30
+ "CompactionPlan",
31
+ "compute_compaction_payback",
32
+ "RouteVerdict",
33
+ "RouteDecision",
34
+ "calculate_break_even_n",
35
+ "evaluate_route",
36
+ ]
@@ -0,0 +1,179 @@
1
+ """Switch-or-stay model router evaluating cost and context retention (BUILD_HANDBOOK §5.8).
2
+
3
+ Evaluates whether to stay on current model, switch models, or delegate sub-tasks
4
+ using closed-form break-even economics and exact Decimal arithmetic (INV-13).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from decimal import Decimal
11
+ from typing import Literal
12
+
13
+ from ctxcache.cost import get_model_pricing
14
+
15
+ RouteVerdict = Literal["stay", "switch", "delegate"]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class RouteDecision:
20
+ """Outcome of switch-or-stay evaluation."""
21
+
22
+ verdict: RouteVerdict
23
+ current_model: str
24
+ target_model: str
25
+ expected_calls: int
26
+ stay_cost: Decimal
27
+ switch_cost: Decimal
28
+ delegate_cost: Decimal | None
29
+ break_even_n: Decimal | None
30
+ price_ratio_q: Decimal
31
+ reason: str
32
+
33
+
34
+ def calculate_break_even_n(
35
+ price_a: Decimal,
36
+ price_b: Decimal,
37
+ read_multiplier: Decimal,
38
+ write_multiplier: Decimal,
39
+ ) -> Decimal | None:
40
+ """Calculate the closed-form threshold calls n* where switching to B pays back.
41
+
42
+ Formula (BUILD_HANDBOOK §5.8):
43
+ q = p_B / p_A
44
+ If q >= 1: switching never saves money (returns None).
45
+ If q < 1: n* = (q * w) / (r * (1 - q))
46
+ """
47
+ if price_a <= Decimal("0"):
48
+ return None
49
+
50
+ q = price_b / price_a
51
+ if q >= Decimal("1"):
52
+ return None
53
+
54
+ denominator = read_multiplier * (Decimal("1") - q)
55
+ if denominator <= Decimal("0"):
56
+ return None
57
+
58
+ numerator = q * write_multiplier
59
+ return numerator / denominator
60
+
61
+
62
+ def evaluate_route(
63
+ current_provider: str,
64
+ current_model: str,
65
+ target_provider: str,
66
+ target_model: str,
67
+ prefix_tokens: int,
68
+ expected_calls: int,
69
+ expected_new_input_tokens: int = 100,
70
+ expected_output_tokens: int = 500,
71
+ subtask_prefix_tokens: int | None = None,
72
+ subtask_expected_calls: int = 1,
73
+ ) -> RouteDecision:
74
+ """Evaluate whether to stay, switch, or delegate using exact Decimal pricing (INV-13).
75
+
76
+ Rules (BUILD_HANDBOOK §5.8):
77
+ 1. Switching to model B writes cold prefix at B's write price on call 1.
78
+ 2. Later calls on B read from cache at B's read price.
79
+ 3. If target is more expensive (q >= 1), switching never saves money -> verdict is 'stay'.
80
+ 4. If subtask_prefix_tokens is provided and delegate cost < min(stay, switch),
81
+ verdict is 'delegate'.
82
+ 5. If switch_cost < stay_cost, verdict is 'switch'.
83
+ 6. Otherwise, verdict is 'stay'.
84
+ """
85
+ p_curr = get_model_pricing(current_provider, current_model)
86
+ p_targ = get_model_pricing(target_provider, target_model)
87
+
88
+ p_in_a = p_curr.input_price_per_token
89
+ p_out_a = p_curr.output_price_per_token
90
+ r_a = p_curr.read_multiplier
91
+
92
+ p_in_b = p_targ.input_price_per_token
93
+ p_out_b = p_targ.output_price_per_token
94
+ r_b = p_targ.read_multiplier
95
+ w_b = p_targ.write_multiplier
96
+
97
+ p_tokens = Decimal(str(prefix_tokens))
98
+ n_calls = Decimal(str(expected_calls))
99
+ t_new = Decimal(str(expected_new_input_tokens))
100
+ out_tokens = Decimal(str(expected_output_tokens))
101
+
102
+ # Closed-form price ratio q
103
+ q = (p_in_b / p_in_a) if p_in_a > Decimal("0") else Decimal("1")
104
+ break_even_n = calculate_break_even_n(p_in_a, p_in_b, r_b, w_b)
105
+
106
+ # 1. Stay cost: reads warm prefix on current model for all n calls
107
+ cost_per_call_stay = p_in_a * (r_a * p_tokens + t_new) + p_out_a * out_tokens
108
+ stay_cost = n_calls * cost_per_call_stay
109
+
110
+ # 2. Switch cost:
111
+ # Call 1 on B: cold write of prefix at write multiplier w_b
112
+ call_1_switch = p_in_b * (w_b * p_tokens + t_new) + p_out_b * out_tokens
113
+ # Remaining n - 1 calls on B: read from B's warm cache
114
+ if expected_calls > 1:
115
+ calls_rest_switch = (n_calls - Decimal("1")) * (
116
+ p_in_b * (r_b * p_tokens + t_new) + p_out_b * out_tokens
117
+ )
118
+ else:
119
+ calls_rest_switch = Decimal("0")
120
+ switch_cost = call_1_switch + calls_rest_switch
121
+
122
+ # 3. Delegate cost (if subtask context is specified)
123
+ delegate_cost: Decimal | None = None
124
+ if subtask_prefix_tokens is not None and subtask_expected_calls > 0:
125
+ p_sub = Decimal(str(subtask_prefix_tokens))
126
+ m_calls = Decimal(str(subtask_expected_calls))
127
+ # Subtask runs as a fresh session on B with only p_sub tokens:
128
+ # First call writes p_sub on B, remaining m - 1 read on B
129
+ sub_call_1 = p_in_b * (w_b * p_sub + t_new) + p_out_b * out_tokens
130
+ sub_calls_rest = (
131
+ (m_calls - Decimal("1")) * (p_in_b * (r_b * p_sub + t_new) + p_out_b * out_tokens)
132
+ if subtask_expected_calls > 1
133
+ else Decimal("0")
134
+ )
135
+ total_subtask_cost = sub_call_1 + sub_calls_rest
136
+ # Main session stays on A for remaining calls
137
+ remaining_main_calls = max(Decimal("1"), n_calls - m_calls)
138
+ main_stay_cost = remaining_main_calls * cost_per_call_stay
139
+ delegate_cost = total_subtask_cost + main_stay_cost
140
+
141
+ # Decision logic
142
+ if q >= Decimal("1"):
143
+ verdict: RouteVerdict = "stay"
144
+ reason = f"Target model {target_model} is not cheaper (price ratio q={q:.2f} >= 1.0); stay on {current_model}."
145
+ elif delegate_cost is not None and delegate_cost < stay_cost and delegate_cost < switch_cost:
146
+ verdict = "delegate"
147
+ savings = min(stay_cost, switch_cost) - delegate_cost
148
+ reason = (
149
+ f"Delegate subtask to {target_model} with smaller context ({subtask_prefix_tokens} tokens): "
150
+ f"saves ${savings:.6f} vs full prefix cold rewrite."
151
+ )
152
+ elif switch_cost < stay_cost:
153
+ verdict = "switch"
154
+ savings = stay_cost - switch_cost
155
+ b_even_str = f"{break_even_n:.1f}" if break_even_n is not None else "N/A"
156
+ reason = (
157
+ f"Switch to {target_model}: n={expected_calls} exceeds break-even n*={b_even_str}; "
158
+ f"saves ${savings:.6f} over {expected_calls} calls."
159
+ )
160
+ else:
161
+ verdict = "stay"
162
+ b_even_str = f"{break_even_n:.1f}" if break_even_n is not None else "N/A"
163
+ reason = (
164
+ f"Stay on {current_model}: n={expected_calls} below break-even n*={b_even_str}; "
165
+ f"cold write penalty on {target_model} would cost more than cache reads on {current_model}."
166
+ )
167
+
168
+ return RouteDecision(
169
+ verdict=verdict,
170
+ current_model=current_model,
171
+ target_model=target_model,
172
+ expected_calls=expected_calls,
173
+ stay_cost=stay_cost,
174
+ switch_cost=switch_cost,
175
+ delegate_cost=delegate_cost,
176
+ break_even_n=break_even_n,
177
+ price_ratio_q=q,
178
+ reason=reason,
179
+ )
ctxcache/replay.py ADDED
@@ -0,0 +1,193 @@
1
+ """Replay CLI and trace evaluation engine (BUILD_HANDBOOK §5.9, §6.2, M4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass
7
+ from decimal import Decimal
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from ctxcache.cost import compute_call_cost
12
+ from ctxcache.guard import PrefixGuard
13
+ from ctxcache.layout import LayoutMemory, optimize_layout
14
+ from ctxcache.sim.cache_sim import CacheSimulator
15
+ from ctxcache.sim.tokens import count_text_tokens
16
+
17
+
18
+ @dataclass
19
+ class ReplayModeSummary:
20
+ mode: str
21
+ total_input: int
22
+ read_tokens: int
23
+ write_tokens: int
24
+ uncached_tokens: int
25
+ read_pct: float
26
+ written_pct: float
27
+ uncached_pct: float
28
+ cost_usd: Decimal
29
+ no_cache_cost_usd: Decimal
30
+ cost_ratio: Decimal
31
+ user_caused_breaks: int
32
+
33
+
34
+ def replay_trace_events(
35
+ calls: list[dict[str, Any]],
36
+ mode: str = "safe",
37
+ provider: str = "gemini",
38
+ model: str = "gemini-2.5-flash",
39
+ ) -> ReplayModeSummary:
40
+ """Replay a sequence of recorded call events through the simulator under a specific policy mode."""
41
+ sim = CacheSimulator(provider=provider, model=model)
42
+ guard = PrefixGuard(strict=False)
43
+
44
+ tot_read = 0
45
+ tot_write = 0
46
+ tot_uncached = 0
47
+ tot_input = 0
48
+ total_cost = Decimal("0")
49
+ total_no_cache_cost = Decimal("0")
50
+ user_caused_breaks = 0
51
+
52
+ first_seen_tools: list[str] = []
53
+ layout_memory = LayoutMemory()
54
+
55
+ for call_idx, call in enumerate(calls, start=1):
56
+ req = call.get("request", {})
57
+ kwargs = req.get("kwargs", {}) if isinstance(req, dict) else {}
58
+ ts = float(call.get("ts", call_idx * 10.0))
59
+
60
+ system = str(kwargs.get("system", ""))
61
+ messages = list(kwargs.get("messages", []))
62
+ tools = kwargs.get("tools")
63
+ if isinstance(tools, list):
64
+ tools = list(tools)
65
+ else:
66
+ tools = None
67
+
68
+ # Mode transformations
69
+ if mode == "safe":
70
+ # Restore first seen tool ordering
71
+ if tools:
72
+ curr_names = [
73
+ str(t.get("name")) for t in tools if isinstance(t, dict) and t.get("name")
74
+ ]
75
+ if not first_seen_tools and curr_names:
76
+ first_seen_tools = list(curr_names)
77
+ elif first_seen_tools and curr_names != first_seen_tools:
78
+ tool_map = {t.get("name"): t for t in tools if isinstance(t, dict)}
79
+ reordered = [tool_map[n] for n in first_seen_tools if n in tool_map]
80
+ for t in tools:
81
+ if t not in reordered:
82
+ reordered.append(t)
83
+ tools = reordered
84
+ elif mode == "optimize":
85
+ # Relocate volatile timestamps and offload large results
86
+ system, messages, _ = optimize_layout(
87
+ system=system,
88
+ messages=messages,
89
+ tools=tools,
90
+ memory=layout_memory,
91
+ )
92
+
93
+ # PrefixGuard evaluation. Count the system and tools, not only the latest message.
94
+ token_total = count_text_tokens(system, model=model)
95
+ token_total += sum(
96
+ count_text_tokens(str(m.get("content", "")), model=model) for m in messages
97
+ )
98
+ if tools:
99
+ token_total += count_text_tokens(str(tools), model=model)
100
+ ev = guard.evaluate_call(
101
+ curr_params={"model": model},
102
+ curr_tools=tools or [],
103
+ curr_system=system,
104
+ curr_messages=messages,
105
+ total_tokens=token_total,
106
+ ts=ts,
107
+ )
108
+ if ev is not None and ev.user_caused:
109
+ user_caused_breaks += 1
110
+
111
+ # Simulate cache
112
+ sim_res = sim.simulate_call(
113
+ call_index=call_idx,
114
+ messages=messages,
115
+ tools=tools,
116
+ system=system if system else None,
117
+ ts=ts,
118
+ )
119
+
120
+ tot_read += sim_res.predicted_read
121
+ tot_write += sim_res.predicted_write
122
+ tot_uncached += sim_res.predicted_uncached
123
+ tot_input += sim_res.total_input
124
+
125
+ # Compute cost
126
+ cost_info = compute_call_cost(
127
+ provider=provider,
128
+ model=model,
129
+ read_tokens=sim_res.predicted_read,
130
+ write_tokens=sim_res.predicted_write,
131
+ uncached_tokens=sim_res.predicted_uncached,
132
+ output_tokens=50,
133
+ )
134
+ total_cost += cost_info.actual_cost
135
+ total_no_cache_cost += cost_info.uncached_baseline
136
+
137
+ read_pct = (tot_read / tot_input * 100.0) if tot_input > 0 else 0.0
138
+ written_pct = (tot_write / tot_input * 100.0) if tot_input > 0 else 0.0
139
+ uncached_pct = (tot_uncached / tot_input * 100.0) if tot_input > 0 else 0.0
140
+ cost_ratio = (total_cost / total_no_cache_cost) if total_no_cache_cost > 0 else Decimal("1.0")
141
+
142
+ return ReplayModeSummary(
143
+ mode=mode,
144
+ total_input=tot_input,
145
+ read_tokens=tot_read,
146
+ write_tokens=tot_write,
147
+ uncached_tokens=tot_uncached,
148
+ read_pct=read_pct,
149
+ written_pct=written_pct,
150
+ uncached_pct=uncached_pct,
151
+ cost_usd=total_cost,
152
+ no_cache_cost_usd=total_no_cache_cost,
153
+ cost_ratio=cost_ratio,
154
+ user_caused_breaks=user_caused_breaks,
155
+ )
156
+
157
+
158
+ def replay_trace_file(
159
+ trace_path: str | Path,
160
+ modes: list[str] | None = None,
161
+ provider: str = "gemini",
162
+ model: str = "gemini-2.5-flash",
163
+ ) -> list[ReplayModeSummary]:
164
+ """Load trace file and replay across specified modes."""
165
+ path = Path(trace_path)
166
+ if not path.exists():
167
+ raise FileNotFoundError(f"Trace file not found: {trace_path}")
168
+
169
+ calls: list[dict[str, Any]] = []
170
+ with open(path, encoding="utf-8") as f:
171
+ for line in f:
172
+ if line.strip():
173
+ calls.append(json.loads(line))
174
+
175
+ if modes is None:
176
+ modes = ["observe", "safe", "optimize"]
177
+
178
+ return [replay_trace_events(calls=calls, mode=m, provider=provider, model=model) for m in modes]
179
+
180
+
181
+ def format_replay_table(summaries: list[ReplayModeSummary]) -> str:
182
+ """Format replay summaries into canonical CLI table output."""
183
+ header = f"{'mode':<10}{'read':<9}{'written':<11}{'uncached':<11}{'input cost':<13}{'user-caused breaks'}"
184
+ lines = [header]
185
+ for s in summaries:
186
+ read_s = f"{s.read_pct:.0f}%"
187
+ writ_s = f"{s.written_pct:.0f}%"
188
+ unc_s = f"{s.uncached_pct:.0f}%"
189
+ cost_s = f"{float(s.cost_ratio):.2f}\u00d7"
190
+ lines.append(
191
+ f"{s.mode:<10}{read_s:<9}{writ_s:<11}{unc_s:<11}{cost_s:<13}{s.user_caused_breaks}"
192
+ )
193
+ return "\n".join(lines)