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
@@ -0,0 +1,124 @@
1
+ # CtxCache Prompt Cache Break Taxonomy and Cause Registry (BUILD_HANDBOOK §5.2)
2
+ # Version: 1.0.0
3
+ # Last Updated: 2026-10-19
4
+
5
+ breaks:
6
+ - id: 1
7
+ code: below_minimum
8
+ detected_when: "Prefix is shorter than the model's cache minimum threshold"
9
+ user_caused: false
10
+ level: system
11
+ fix_ctxcache_offers: "None needed; caching is automatically skipped for sub-threshold calls"
12
+ description: "Providers impose a minimum token threshold before caching activates (e.g. 1024 or 2048 tokens). Sub-minimum requests cannot be cached."
13
+
14
+ - id: 2
15
+ code: short_session
16
+ detected_when: "Session ended before any prompt cache reuse occurred"
17
+ user_caused: false
18
+ level: system
19
+ fix_ctxcache_offers: "The planner skips expensive write premiums when it predicts a single-shot session"
20
+ description: "Single-turn requests that write to cache without subsequent reuse waste cache write fees."
21
+
22
+ - id: 3
23
+ code: ttl_expired
24
+ detected_when: "Prefix is identical, but elapsed time between consecutive calls exceeded provider TTL"
25
+ user_caused: false
26
+ level: system
27
+ fix_ctxcache_offers: "1-hour TTL on stable breakpoints or application expect_pause() hints"
28
+ description: "Provider cache entries evict after idle periods (e.g. 5 minutes on Anthropic/Gemini). Long pauses between turns cause cold evictions."
29
+
30
+ - id: 4
31
+ code: provider_miss
32
+ detected_when: "Identical prefix sent within TTL window, but provider reported 0 read tokens"
33
+ user_caused: false
34
+ level: system
35
+ fix_ctxcache_offers: "Recorded as provider failure; never attributed as an application error"
36
+ description: "Backend provider cache node evictions or routing across uncoordinated cluster replicas."
37
+
38
+ - id: 5
39
+ code: params_changed
40
+ detected_when: "Model name, tool_choice, thinking effort, response format, or parallel_tool_calls changed"
41
+ user_caused: true
42
+ level: system
43
+ fix_ctxcache_offers: "Maintain stable parameters per session; switch models via dedicated subagents"
44
+ description: "Provider prompt caches are partitioned by exact model and decoding configuration. Changing temperature or model mid-session resets cache."
45
+
46
+ - id: 6
47
+ code: tools_changed
48
+ detected_when: "Tool definitions, schemas, or tool count differ from the session baseline"
49
+ user_caused: true
50
+ level: tools
51
+ fix_ctxcache_offers: "Declare full tool suite at session start; use tool_addition where supported"
52
+ description: "Adding, removing, or editing tool JSON schemas alters prefix bytes preceding the system and dialogue turns."
53
+
54
+ - id: 7
55
+ code: tools_reordered
56
+ detected_when: "The exact same set of tools is provided, but in a different permutation"
57
+ user_caused: true
58
+ level: tools
59
+ fix_ctxcache_offers: "CtxCache safe mode automatically restores tools into their first-seen order"
60
+ description: "Dict iteration non-determinism or dynamic list assembly scrambles tool order, busting byte-exact prefix caches."
61
+
62
+ - id: 8
63
+ code: volatile_in_prefix
64
+ detected_when: "Differing bytes match a volatile pattern (timestamp, ISO date, UUID, counter, git hash)"
65
+ user_caused: true
66
+ level: system
67
+ fix_ctxcache_offers: "CtxCache volatile() marker, or CtxCache optimize mode automatically relocates volatile elements to the user turn tail"
68
+ description: "Prepending timestamps or session IDs at byte 0 invalidates the entire subsequent system prompt and conversation history."
69
+
70
+ - id: 9
71
+ code: system_changed
72
+ detected_when: "System prompt instructions changed mid-session"
73
+ user_caused: true
74
+ level: system
75
+ fix_ctxcache_offers: "Append runtime updates as user notes, or move mutable instructions to conversation tail"
76
+ description: "Modifying instructions inside the system prompt resets the entire prompt cache from the point of change."
77
+
78
+ - id: 10
79
+ code: session_mutated
80
+ detected_when: "A SESSION segment changed mid-conversation (e.g. dynamic memory fact injection)"
81
+ user_caused: true
82
+ level: session
83
+ fix_ctxcache_offers: "Queue facts for user turn tail; promote to SESSION on subsequent sessions"
84
+ description: "Injecting memory facts into early session blocks alters the prefix for all subsequent turns."
85
+
86
+ - id: 11
87
+ code: image_toggled
88
+ detected_when: "An image was added, modified, or removed earlier in prompt history"
89
+ user_caused: true
90
+ level: messages
91
+ fix_ctxcache_offers: "Place multimodal media only in the specific turn that requires visual analysis"
92
+ description: "Multimodal tokens alter early prefix alignment and token offsets."
93
+
94
+ - id: 12
95
+ code: history_rewritten
96
+ detected_when: "An earlier dialogue message differs (trimming, naive sliding window, content edit)"
97
+ user_caused: true
98
+ level: messages
99
+ fix_ctxcache_offers: "Maintain append-only message history, or execute CtxCache planned compaction"
100
+ description: "Sliding window trimming drops message 0, changing prefix byte 0 and causing 100% cache invalidation."
101
+
102
+ - id: 13
103
+ code: no_breakpoints
104
+ detected_when: "Provider requires explicit breakpoint markers (e.g. Anthropic) and none were set"
105
+ user_caused: true
106
+ level: system
107
+ fix_ctxcache_offers: "CtxCache safe mode automatically plans and injects optimal cache breakpoints"
108
+ description: "Without cache_control breakpoints, explicit caching providers treat requests as un-cached."
109
+
110
+ - id: 14
111
+ code: metadata_dropped
112
+ detected_when: "Application set cache metadata, but framework dropped it before API dispatch"
113
+ user_caused: false
114
+ level: system
115
+ fix_ctxcache_offers: "Flagged with agent framework version for upstream bug reporting"
116
+ description: "Certain framework middleware strips vendor-specific fields during serialization."
117
+
118
+ - id: 15
119
+ code: cold_subagent
120
+ detected_when: "A spawned subagent session begins with a completely cold prefix"
121
+ user_caused: false
122
+ level: system
123
+ fix_ctxcache_offers: "Share a common stable system/tool prefix with the parent agent"
124
+ description: "Ephemeral subagent tasks incur cold start writes unless designed to share prefix geometry."
@@ -0,0 +1,199 @@
1
+ # Provider caching parameters, pricing, and invalidation rules.
2
+ # Each entry is sourced and dated. Never hard-code these values in code.
3
+ # Date: 2026-10-19
4
+
5
+ [providers.gemini]
6
+ name = "Google Gemini"
7
+ source_url = "https://ai.google.dev/gemini-api/docs/caching"
8
+ source_date = "2026-10-19"
9
+ caching_mode = "implicit_and_explicit"
10
+ default_ttl_seconds = 3600
11
+ min_prefix_tokens = 2048
12
+ read_multiplier = 0.10
13
+ write_multiplier = 1.00
14
+ usage_cached_tokens_field = "cachedContentTokenCount"
15
+ usage_total_input_field = "promptTokenCount"
16
+ usage_output_field = "candidatesTokenCount"
17
+
18
+ [providers.gemini.models."gemini-2.5-flash"]
19
+ input_price_per_million = 0.15
20
+ output_price_per_million = 0.60
21
+ min_prefix_tokens = 2048
22
+ read_multiplier = 0.10
23
+ write_multiplier = 1.00
24
+
25
+ [providers.gemini.models."gemini-2.0-flash"]
26
+ input_price_per_million = 0.10
27
+ output_price_per_million = 0.40
28
+ min_prefix_tokens = 2048
29
+ read_multiplier = 0.10
30
+ write_multiplier = 1.00
31
+
32
+ [providers.gemini.models."gemini-1.5-flash"]
33
+ input_price_per_million = 0.075
34
+ output_price_per_million = 0.30
35
+ min_prefix_tokens = 2048
36
+ read_multiplier = 0.10
37
+ write_multiplier = 1.00
38
+
39
+ [providers.anthropic]
40
+ name = "Anthropic"
41
+ source_url = "https://platform.claude.com/docs/en/build-with-claude/prompt-caching"
42
+ source_date = "2026-10-19"
43
+ caching_mode = "explicit_breakpoints"
44
+ default_ttl_seconds = 300
45
+ long_ttl_seconds = 3600
46
+ min_prefix_tokens = 1024
47
+ max_breakpoints = 4
48
+ lookback_blocks = 20
49
+ read_multiplier = 0.10
50
+ write_multiplier_5m = 1.25
51
+ write_multiplier_1h = 2.00
52
+ usage_cache_read_field = "cache_read_input_tokens"
53
+ usage_cache_creation_field = "cache_creation_input_tokens"
54
+ usage_total_input_field = "input_tokens"
55
+ usage_output_field = "output_tokens"
56
+ levels = ["tools", "system", "messages"]
57
+
58
+ [providers.anthropic.models."claude-3-5-sonnet-20241022"]
59
+ input_price_per_million = 3.00
60
+ output_price_per_million = 15.00
61
+ min_prefix_tokens = 1024
62
+ read_multiplier = 0.10
63
+ write_multiplier = 1.25
64
+
65
+ [providers.anthropic.models."claude-3-5-haiku-20241022"]
66
+ input_price_per_million = 0.80
67
+ output_price_per_million = 4.00
68
+ min_prefix_tokens = 512
69
+ read_multiplier = 0.10
70
+ write_multiplier = 1.25
71
+
72
+ [providers.openai]
73
+ name = "OpenAI"
74
+ source_url = "https://developers.openai.com/api/docs/guides/prompt-caching"
75
+ source_date = "2026-10-19"
76
+ caching_mode = "automatic_prefix"
77
+ default_ttl_seconds = 1800
78
+ min_prefix_tokens = 1024
79
+ max_breakpoints = 4
80
+ read_multiplier = 0.10
81
+ write_multiplier = 1.25
82
+ usage_cache_read_field = "input_tokens_details.cached_tokens"
83
+ usage_cache_write_field = "cache_write_tokens"
84
+ usage_total_input_field = "prompt_tokens"
85
+ usage_output_field = "completion_tokens"
86
+
87
+ [providers.openai.models."gpt-4o"]
88
+ input_price_per_million = 2.50
89
+ output_price_per_million = 10.00
90
+ min_prefix_tokens = 1024
91
+ read_multiplier = 0.10
92
+ write_multiplier = 1.25
93
+
94
+ [providers.openai.models."gpt-4o-mini"]
95
+ input_price_per_million = 0.15
96
+ output_price_per_million = 0.60
97
+ min_prefix_tokens = 1024
98
+ read_multiplier = 0.10
99
+ write_multiplier = 1.25
100
+
101
+ # Amazon Bedrock, US East (N. Virginia). Prices are the on-demand rows in the
102
+ # AWS price list, converted from USD per 1K tokens to USD per 1M tokens.
103
+ # Nova cache read is 0.25x input. Nova cache write is $0. gpt-oss has input
104
+ # and output prices and no cache-read row, so its multipliers stay at 1.
105
+ # Cache minimums for Nova are from the Bedrock prompt-caching guide.
106
+ [providers.bedrock]
107
+ name = "Amazon Bedrock"
108
+ source_url = "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonBedrock/20261111013037/us-east-1/index.json"
109
+ source_date = "2026-11-11"
110
+ caching_mode = "explicit_checkpoints"
111
+ default_ttl_seconds = 300
112
+ min_prefix_tokens = 1024
113
+ read_multiplier = 0.25
114
+ write_multiplier = 0.00
115
+
116
+ [providers.bedrock.models."amazon.nova-micro-v1:0"]
117
+ input_price_per_million = 0.035
118
+ output_price_per_million = 0.140
119
+ min_prefix_tokens = 1024
120
+ read_multiplier = 0.25
121
+ write_multiplier = 0.00
122
+
123
+ [providers.bedrock.models."amazon.nova-lite-v1:0"]
124
+ input_price_per_million = 0.060
125
+ output_price_per_million = 0.240
126
+ min_prefix_tokens = 1024
127
+ read_multiplier = 0.25
128
+ write_multiplier = 0.00
129
+
130
+ [providers.bedrock.models."openai.gpt-oss-120b-1:0"]
131
+ input_price_per_million = 0.15
132
+ output_price_per_million = 0.60
133
+ min_prefix_tokens = 1024
134
+ read_multiplier = 1.00
135
+ write_multiplier = 1.00
136
+
137
+ # Regional on-demand, US East, standard tier. Per 1K in the price list:
138
+ # input 0.0033, output 0.0165, cache read 0.00033, cache write 30m 0.004125.
139
+ # Read is 0.10x input. Write is 1.25x input. The global profile is cheaper
140
+ # and is a separate model id below.
141
+ [providers.bedrock.models."us.moonshotai.kimi-k3"]
142
+ input_price_per_million = 3.30
143
+ output_price_per_million = 16.50
144
+ min_prefix_tokens = 1024
145
+ read_multiplier = 0.10
146
+ write_multiplier = 1.25
147
+
148
+ [providers.bedrock.models."moonshotai.kimi-k3"]
149
+ input_price_per_million = 3.30
150
+ output_price_per_million = 16.50
151
+ min_prefix_tokens = 1024
152
+ read_multiplier = 0.10
153
+ write_multiplier = 1.25
154
+
155
+ # Global standard: input 0.003, output 0.015, cache read 0.0003, write 0.00375 per 1K.
156
+ [providers.bedrock.models."global.moonshotai.kimi-k3"]
157
+ input_price_per_million = 3.00
158
+ output_price_per_million = 15.00
159
+ min_prefix_tokens = 1024
160
+ read_multiplier = 0.10
161
+ write_multiplier = 1.25
162
+
163
+ # Grok regional standard. Input 0.0022, output 0.0066, cache read 0.00055 per 1K.
164
+ # The price list has no cache-write row, so a write is priced as standard input.
165
+ [providers.bedrock.models."us.xai.grok-4.7"]
166
+ input_price_per_million = 2.20
167
+ output_price_per_million = 6.60
168
+ min_prefix_tokens = 1024
169
+ read_multiplier = 0.25
170
+ write_multiplier = 1.00
171
+
172
+ [providers.bedrock.models."xai.grok-4.7"]
173
+ input_price_per_million = 2.20
174
+ output_price_per_million = 6.60
175
+ min_prefix_tokens = 1024
176
+ read_multiplier = 0.25
177
+ write_multiplier = 1.00
178
+
179
+ [providers.bedrock.models."us.xai.grok-4.6"]
180
+ input_price_per_million = 2.20
181
+ output_price_per_million = 6.60
182
+ min_prefix_tokens = 1024
183
+ read_multiplier = 0.25
184
+ write_multiplier = 1.00
185
+
186
+ [providers.bedrock.models."xai.grok-4.6"]
187
+ input_price_per_million = 2.20
188
+ output_price_per_million = 6.60
189
+ min_prefix_tokens = 1024
190
+ read_multiplier = 0.25
191
+ write_multiplier = 1.00
192
+
193
+ # Nova Pro: input 0.0008, output 0.0032, cache read 0.0002, cache write 0 per 1K.
194
+ [providers.bedrock.models."amazon.nova-pro-v1:0"]
195
+ input_price_per_million = 0.80
196
+ output_price_per_million = 3.20
197
+ min_prefix_tokens = 1024
198
+ read_multiplier = 0.25
199
+ write_multiplier = 0.00
ctxcache/exceptions.py ADDED
@@ -0,0 +1,23 @@
1
+ """Exception types for CtxCache."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class CtxCacheError(Exception):
7
+ """Base exception for all CtxCache errors."""
8
+
9
+
10
+ class CtxCachePrefixBreak(CtxCacheError):
11
+ """Raised before sending when strict=True and a user-caused prefix break is detected."""
12
+
13
+ def __init__(
14
+ self,
15
+ message: str,
16
+ cause: str,
17
+ level: str,
18
+ message_index: int | None = None,
19
+ ):
20
+ super().__init__(message)
21
+ self.cause = cause
22
+ self.level = level
23
+ self.message_index = message_index
@@ -0,0 +1,68 @@
1
+ """Deterministic per-message fingerprints and rolling segment hashes (BUILD_HANDBOOK §5.1, INV-03)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from decimal import Decimal
8
+ from typing import Any
9
+
10
+
11
+ class _DecimalEncoder(json.JSONEncoder):
12
+ def default(self, o: Any) -> Any:
13
+ if isinstance(o, Decimal):
14
+ return str(o)
15
+ return super().default(o)
16
+
17
+
18
+ def canonical_serialize(obj: Any) -> str:
19
+ """Serialize object to JSON deterministically in application key order without float round-tripping."""
20
+ # separators=(',', ':') removes whitespace
21
+ # ensure_ascii=False ensures exact UTF-8 byte representation
22
+ return json.dumps(obj, cls=_DecimalEncoder, separators=(",", ":"), ensure_ascii=False)
23
+
24
+
25
+ # Cache structure: key -> (full_hash, serialized_str)
26
+ # Max capacity 4096 entries
27
+ _LRU_CAPACITY = 4096
28
+ _fingerprint_cache: dict[tuple[str, int, str, str], str] = {}
29
+
30
+
31
+ def fingerprint_message(msg: Any) -> str:
32
+ """Compute deterministic SHA-256 fingerprint for a message, system block, or tool.
33
+
34
+ LRU-cached by (role, length, first 64 bytes, last 64 bytes) for sub-millisecond lookups.
35
+ """
36
+ serialized = canonical_serialize(msg)
37
+ encoded = serialized.encode("utf-8")
38
+ length = len(encoded)
39
+
40
+ role = "none"
41
+ if isinstance(msg, dict):
42
+ role = str(msg.get("role", "none"))
43
+
44
+ prefix = encoded[:64].decode("utf-8", errors="replace")
45
+ suffix = encoded[-64:].decode("utf-8", errors="replace") if length > 64 else prefix
46
+ cache_key = (role, length, prefix, suffix)
47
+
48
+ if cache_key in _fingerprint_cache:
49
+ return _fingerprint_cache[cache_key]
50
+
51
+ digest = hashlib.sha256(encoded).hexdigest()
52
+
53
+ # Simple LRU eviction if over capacity
54
+ if len(_fingerprint_cache) >= _LRU_CAPACITY:
55
+ # Pop oldest item
56
+ first_key = next(iter(_fingerprint_cache))
57
+ del _fingerprint_cache[first_key]
58
+
59
+ _fingerprint_cache[cache_key] = digest
60
+ return digest
61
+
62
+
63
+ def rolling_segment_hash(fingerprints: list[str]) -> str:
64
+ """Compute rolling SHA-256 over fingerprints in order so divergence is O(number of messages)."""
65
+ h = hashlib.sha256()
66
+ for fp in fingerprints:
67
+ h.update(fp.encode("utf-8"))
68
+ return h.hexdigest()
ctxcache/guard.py ADDED
@@ -0,0 +1,253 @@
1
+ """Prefix guard and break taxonomy (BUILD_HANDBOOK §5.2, INV-10)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ from ctxcache.exceptions import CtxCachePrefixBreak
10
+ from ctxcache.fingerprint import fingerprint_message
11
+
12
+ # Taxonomy of cause codes and user attribution (BUILD_HANDBOOK §5.2, INV-10)
13
+ # INV-10: below_minimum, short_session, ttl_expired, and provider_miss are NEVER user-caused.
14
+ CAUSE_ATTRIBUTION: dict[str, bool] = {
15
+ "below_minimum": False,
16
+ "short_session": False,
17
+ "ttl_expired": False,
18
+ "provider_miss": False,
19
+ "params_changed": True,
20
+ "tools_changed": True,
21
+ "tools_reordered": True,
22
+ "volatile_in_prefix": True,
23
+ "system_changed": True,
24
+ "session_mutated": True,
25
+ "image_toggled": True,
26
+ "history_rewritten": True,
27
+ "no_breakpoints": True,
28
+ "metadata_dropped": False, # Framework caused
29
+ "cold_subagent": False, # Design trade-off
30
+ }
31
+
32
+ VOLATILE_PATTERN = re.compile(
33
+ r"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}|git commit|session-|branch)",
34
+ re.IGNORECASE,
35
+ )
36
+
37
+
38
+ def is_user_caused(cause: str) -> bool:
39
+ """Return whether a prefix break cause is attributable to user/application code (INV-10)."""
40
+ return CAUSE_ATTRIBUTION.get(cause, False)
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class BreakEvent:
45
+ cause: str
46
+ user_caused: bool
47
+ level: str # "tools", "system", "messages"
48
+ message_index: int | None
49
+ tokens_rewritten: int
50
+ details: str
51
+
52
+
53
+ def classify_break_cause(
54
+ prev_params: dict[str, Any],
55
+ curr_params: dict[str, Any],
56
+ prev_tools: list[dict[str, Any]],
57
+ curr_tools: list[dict[str, Any]],
58
+ prev_system: str,
59
+ curr_system: str,
60
+ prev_messages: list[dict[str, Any]],
61
+ curr_messages: list[dict[str, Any]],
62
+ total_tokens: int,
63
+ min_prefix_tokens: int,
64
+ time_gap_seconds: float,
65
+ ttl_seconds: float,
66
+ provider_read_tokens: int | None = None,
67
+ ) -> BreakEvent | None:
68
+ """Classifies divergence between calls strictly in precedence order (BUILD_HANDBOOK §5.2)."""
69
+ # 1. below_minimum
70
+ if total_tokens < min_prefix_tokens:
71
+ return BreakEvent(
72
+ cause="below_minimum",
73
+ user_caused=False,
74
+ level="system",
75
+ message_index=None,
76
+ tokens_rewritten=0,
77
+ details=f"Context tokens ({total_tokens}) below provider minimum ({min_prefix_tokens})",
78
+ )
79
+
80
+ # 3. ttl_expired
81
+ if time_gap_seconds > ttl_seconds:
82
+ return BreakEvent(
83
+ cause="ttl_expired",
84
+ user_caused=False,
85
+ level="system",
86
+ message_index=None,
87
+ tokens_rewritten=total_tokens,
88
+ details=f"Call gap ({time_gap_seconds:.1f}s) exceeded provider TTL ({ttl_seconds:.1f}s)",
89
+ )
90
+
91
+ # 4. provider_miss
92
+ # Only when the caller supplies the provider's read count. A missing count
93
+ # means the call has not been answered yet, which is not a miss.
94
+ if (
95
+ provider_read_tokens is not None
96
+ and prev_params == curr_params
97
+ and prev_tools == curr_tools
98
+ and prev_system == curr_system
99
+ and prev_messages == curr_messages[: len(prev_messages)]
100
+ and provider_read_tokens == 0
101
+ and len(prev_messages) > 0
102
+ ):
103
+ return BreakEvent(
104
+ cause="provider_miss",
105
+ user_caused=False,
106
+ level="system",
107
+ message_index=None,
108
+ tokens_rewritten=total_tokens,
109
+ details="Identical prefix within TTL had 0 cached tokens reported by provider",
110
+ )
111
+
112
+ # 5. params_changed
113
+ for k in ("model", "tool_choice", "temperature", "parallel_tool_calls"):
114
+ if prev_params.get(k) != curr_params.get(k):
115
+ return BreakEvent(
116
+ cause="params_changed",
117
+ user_caused=True,
118
+ level="system",
119
+ message_index=None,
120
+ tokens_rewritten=total_tokens,
121
+ details=f"Parameter '{k}' changed from '{prev_params.get(k)}' to '{curr_params.get(k)}'",
122
+ )
123
+
124
+ # 6 & 7. tools_changed / tools_reordered
125
+ prev_names = [str(t.get("name", "")) for t in prev_tools]
126
+ curr_names = [str(t.get("name", "")) for t in curr_tools]
127
+ if sorted(prev_names) == sorted(curr_names) and prev_names != curr_names:
128
+ return BreakEvent(
129
+ cause="tools_reordered",
130
+ user_caused=True,
131
+ level="tools",
132
+ message_index=None,
133
+ tokens_rewritten=total_tokens,
134
+ details=f"Tools order changed: {prev_names} -> {curr_names}",
135
+ )
136
+ if prev_tools != curr_tools:
137
+ return BreakEvent(
138
+ cause="tools_changed",
139
+ user_caused=True,
140
+ level="tools",
141
+ message_index=None,
142
+ tokens_rewritten=total_tokens,
143
+ details="Tool definitions or count differed from previous call",
144
+ )
145
+
146
+ # 8. volatile_in_prefix
147
+ if prev_system != curr_system:
148
+ if VOLATILE_PATTERN.search(curr_system):
149
+ return BreakEvent(
150
+ cause="volatile_in_prefix",
151
+ user_caused=True,
152
+ level="system",
153
+ message_index=0,
154
+ tokens_rewritten=total_tokens,
155
+ details="Detected volatile timestamp, date, or git hash in system prompt",
156
+ )
157
+ # 9. system_changed
158
+ return BreakEvent(
159
+ cause="system_changed",
160
+ user_caused=True,
161
+ level="system",
162
+ message_index=0,
163
+ tokens_rewritten=total_tokens,
164
+ details="System prompt differed from previous call",
165
+ )
166
+
167
+ # 12. history_rewritten
168
+ # Compare common prefix of messages
169
+ for idx, (p_msg, c_msg) in enumerate(zip(prev_messages, curr_messages, strict=False)):
170
+ if fingerprint_message(p_msg) != fingerprint_message(c_msg):
171
+ return BreakEvent(
172
+ cause="history_rewritten",
173
+ user_caused=True,
174
+ level="messages",
175
+ message_index=idx,
176
+ tokens_rewritten=total_tokens,
177
+ details=f"Historical message at index {idx} was modified",
178
+ )
179
+
180
+ return None
181
+
182
+
183
+ class PrefixGuard:
184
+ """Tracks session history and verifies prefix stability across consecutive calls."""
185
+
186
+ def __init__(
187
+ self, strict: bool = False, min_prefix_tokens: int = 2048, ttl_seconds: float = 3600.0
188
+ ):
189
+ self.strict = strict
190
+ self.min_prefix_tokens = min_prefix_tokens
191
+ self.ttl_seconds = ttl_seconds
192
+ self.prev_params: dict[str, Any] = {}
193
+ self.prev_tools: list[dict[str, Any]] = []
194
+ self.prev_system: str = ""
195
+ self.prev_messages: list[dict[str, Any]] = []
196
+ self.last_ts: float | None = None
197
+
198
+ def evaluate_call(
199
+ self,
200
+ curr_params: dict[str, Any],
201
+ curr_tools: list[dict[str, Any]],
202
+ curr_system: str,
203
+ curr_messages: list[dict[str, Any]],
204
+ total_tokens: int,
205
+ ts: float,
206
+ provider_read_tokens: int | None = None,
207
+ ) -> BreakEvent | None:
208
+ """Evaluate upcoming call against previous call state."""
209
+ time_gap = (ts - self.last_ts) if self.last_ts is not None else 0.0
210
+
211
+ event = None
212
+ if self.prev_messages or self.prev_system or self.prev_tools:
213
+ event = classify_break_cause(
214
+ prev_params=self.prev_params,
215
+ curr_params=curr_params,
216
+ prev_tools=self.prev_tools,
217
+ curr_tools=curr_tools,
218
+ prev_system=self.prev_system,
219
+ curr_system=curr_system,
220
+ prev_messages=self.prev_messages,
221
+ curr_messages=curr_messages,
222
+ total_tokens=total_tokens,
223
+ min_prefix_tokens=self.min_prefix_tokens,
224
+ time_gap_seconds=time_gap,
225
+ ttl_seconds=self.ttl_seconds,
226
+ provider_read_tokens=provider_read_tokens,
227
+ )
228
+ elif total_tokens < self.min_prefix_tokens:
229
+ event = BreakEvent(
230
+ cause="below_minimum",
231
+ user_caused=False,
232
+ level="system",
233
+ message_index=None,
234
+ tokens_rewritten=0,
235
+ details=f"Context tokens ({total_tokens}) below provider minimum ({self.min_prefix_tokens})",
236
+ )
237
+
238
+ if event is not None and self.strict and event.user_caused:
239
+ raise CtxCachePrefixBreak(
240
+ f"Prefix break detected: {event.cause} ({event.details})",
241
+ cause=event.cause,
242
+ level=event.level,
243
+ message_index=event.message_index,
244
+ )
245
+
246
+ # Update previous call state
247
+ self.prev_params = dict(curr_params)
248
+ self.prev_tools = list(curr_tools)
249
+ self.prev_system = curr_system
250
+ self.prev_messages = list(curr_messages)
251
+ self.last_ts = ts
252
+
253
+ return event
@@ -0,0 +1,17 @@
1
+ """CtxCache framework integrations (Pydantic AI, OpenAI Agents SDK, LangGraph)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ctxcache.integrations.langchain import CtxCacheMiddleware as LangChainMiddleware
6
+ from ctxcache.integrations.langgraph import CtxCacheMiddleware
7
+ from ctxcache.integrations.openai_agents import set_default_openai_client, wrap_agents_client
8
+ from ctxcache.integrations.pydantic_ai import CtxCachePydanticAIModel, wrap_pydantic_ai_client
9
+
10
+ __all__ = [
11
+ "CtxCacheMiddleware",
12
+ "LangChainMiddleware",
13
+ "wrap_pydantic_ai_client",
14
+ "CtxCachePydanticAIModel",
15
+ "set_default_openai_client",
16
+ "wrap_agents_client",
17
+ ]
@@ -0,0 +1,7 @@
1
+ """LangChain integration alias for CtxCache prompt caching (BUILD_HANDBOOK §4.2, §6.1)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ctxcache.integrations.langgraph import CtxCacheMiddleware
6
+
7
+ __all__ = ["CtxCacheMiddleware"]