-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathbase.py
More file actions
855 lines (747 loc) · 33 KB
/
base.py
File metadata and controls
855 lines (747 loc) · 33 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
import base64
import binascii
import logging
import random
from abc import abstractmethod
from typing import Any, Dict, Generic, List, Optional, Sequence, Tuple, Union, cast
import orjson
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.base import (
WRITES_IDX_MAP,
BaseCheckpointSaver,
Checkpoint,
CheckpointMetadata,
PendingWrite,
)
from langgraph.checkpoint.serde.base import SerializerProtocol
from langgraph.checkpoint.serde.types import ChannelProtocol
from redisvl.query import FilterQuery
from redisvl.query.filter import Tag
from langgraph.checkpoint.redis.util import (
safely_decode,
to_storage_safe_id,
to_storage_safe_str,
)
from .jsonplus_redis import JsonPlusRedisSerializer
from .types import IndexType, RedisClientType
logger = logging.getLogger(__name__)
REDIS_KEY_SEPARATOR = ":"
CHECKPOINT_PREFIX = "checkpoint"
CHECKPOINT_WRITE_PREFIX = "checkpoint_write"
class BaseRedisSaver(BaseCheckpointSaver[str], Generic[RedisClientType, IndexType]):
"""Base Redis implementation for checkpoint saving.
Uses Redis JSON for storing checkpoints and related data, with RediSearch for querying.
"""
_redis: RedisClientType
_owns_its_client: bool = False
_key_registry: Optional[Any] = None
checkpoints_index: IndexType
checkpoint_writes_index: IndexType
def __init__(
self,
redis_url: Optional[str] = None,
*,
redis_client: Optional[RedisClientType] = None,
connection_args: Optional[Dict[str, Any]] = None,
ttl: Optional[Dict[str, Any]] = None,
checkpoint_prefix: str = CHECKPOINT_PREFIX,
checkpoint_write_prefix: str = CHECKPOINT_WRITE_PREFIX,
) -> None:
"""Initialize Redis-backed checkpoint saver.
Args:
redis_url: Redis connection URL
redis_client: Redis client instance to use (alternative to redis_url)
connection_args: Additional arguments for Redis connection
ttl: Optional TTL configuration dict with optional keys:
- default_ttl: TTL in minutes for all checkpoint keys
- refresh_on_read: Whether to refresh TTL on reads
checkpoint_prefix: Prefix for checkpoint keys (default: "checkpoint")
checkpoint_write_prefix: Prefix for checkpoint write keys (default: "checkpoint_write")
"""
super().__init__(serde=JsonPlusRedisSerializer())
if redis_url is None and redis_client is None:
raise ValueError("Either redis_url or redis_client must be provided")
# Store TTL configuration
self.ttl_config = ttl
# Store custom prefixes
self._checkpoint_prefix = checkpoint_prefix
self._checkpoint_write_prefix = checkpoint_write_prefix
self.configure_client(
redis_url=redis_url,
redis_client=redis_client,
connection_args=connection_args or {},
)
# Initialize indexes
self.checkpoints_index: IndexType
self.checkpoint_writes_index: IndexType
self.create_indexes()
@property
def checkpoints_schema(self) -> Dict[str, Any]:
"""Schema for the checkpoints index."""
return {
"index": {
"name": self._checkpoint_prefix,
"prefix": self._checkpoint_prefix + REDIS_KEY_SEPARATOR,
"storage_type": "json",
},
"fields": [
{"name": "thread_id", "type": "tag"},
{"name": "run_id", "type": "tag"},
{"name": "checkpoint_ns", "type": "tag"},
{"name": "checkpoint_id", "type": "tag"},
{"name": "parent_checkpoint_id", "type": "tag"},
{"name": "checkpoint_ts", "type": "numeric"},
{"name": "source", "type": "tag"},
{"name": "step", "type": "numeric"},
{"name": "has_writes", "type": "tag"},
],
}
@property
def writes_schema(self) -> Dict[str, Any]:
"""Schema for the checkpoint writes index."""
return {
"index": {
"name": self._checkpoint_write_prefix,
"prefix": self._checkpoint_write_prefix + REDIS_KEY_SEPARATOR,
"storage_type": "json",
},
"fields": [
{"name": "thread_id", "type": "tag"},
{"name": "checkpoint_ns", "type": "tag"},
{"name": "checkpoint_id", "type": "tag"},
{"name": "task_id", "type": "tag"},
{"name": "idx", "type": "numeric"},
{"name": "channel", "type": "tag"},
{"name": "type", "type": "tag"},
],
}
@abstractmethod
def create_indexes(self) -> None:
"""Create appropriate SearchIndex instances."""
pass
@abstractmethod
def configure_client(
self,
redis_url: Optional[str] = None,
redis_client: Optional[RedisClientType] = None,
connection_args: Optional[Dict[str, Any]] = None,
) -> None:
"""Configure the Redis client."""
pass
def set_client_info(self) -> None:
"""Set client info for Redis monitoring."""
from redis.exceptions import ResponseError
from langgraph.checkpoint.redis.version import __full_lib_name__
try:
# Try to use client_setinfo command if available
self._redis.client_setinfo("LIB-NAME", __full_lib_name__)
except (ResponseError, AttributeError):
# Fall back to a simple echo if client_setinfo is not available
try:
self._redis.echo(__full_lib_name__)
except Exception:
# Silently fail if even echo doesn't work
pass
async def aset_client_info(self) -> None:
"""Set client info for Redis monitoring asynchronously."""
from redis.exceptions import ResponseError
from langgraph.checkpoint.redis.version import __full_lib_name__
try:
# Try to use client_setinfo command if available
await self._redis.client_setinfo("LIB-NAME", __full_lib_name__)
except (ResponseError, AttributeError):
# Fall back to a simple echo if client_setinfo is not available
try:
# Call with await to ensure it's an async call
echo_result = self._redis.echo(__full_lib_name__)
if hasattr(echo_result, "__await__"):
await echo_result
except Exception:
# Silently fail if even echo doesn't work
pass
def setup(self) -> None:
"""Initialize the indices in Redis."""
# Create indexes in Redis
self.checkpoints_index.create(overwrite=False)
self.checkpoint_writes_index.create(overwrite=False)
def _load_checkpoint(
self,
checkpoint: Union[Dict[str, Any], str],
channel_values: Dict[str, Any],
pending_sends: List[Any],
) -> Checkpoint:
if not checkpoint:
return {}
# OPTIMIZED: Handle both dict and string inputs efficiently
loaded = (
checkpoint
if isinstance(checkpoint, dict)
else cast(dict, orjson.loads(checkpoint))
)
return {
**loaded,
"pending_sends": [
self.serde.loads_typed((safely_decode(c), b))
for c, b in pending_sends or []
],
"channel_values": channel_values,
}
def _apply_ttl_to_keys(
self,
main_key: str,
related_keys: Optional[list[str]] = None,
ttl_minutes: Optional[float] = None,
) -> Any:
"""Apply Redis native TTL to keys.
Args:
main_key: The primary Redis key
related_keys: Additional Redis keys that should expire at the same time
ttl_minutes: Time-to-live in minutes, overrides default_ttl if provided
Use -1 to remove TTL (make keys persistent)
Returns:
Result of the Redis operation
"""
if ttl_minutes is None:
# Check if there's a default TTL in config
if self.ttl_config and "default_ttl" in self.ttl_config:
ttl_minutes = self.ttl_config.get("default_ttl")
if ttl_minutes is not None:
# Special case: -1 means remove TTL (make persistent)
if ttl_minutes == -1:
# Apply PERSIST individually per key so that a single failure
# does not prevent TTL removal on the remaining keys.
all_keys = [main_key] + (related_keys or [])
for key in all_keys:
try:
self._redis.persist(key)
except Exception:
logger.warning("Failed to remove TTL from key: %s", key)
return True
# Regular TTL setting
ttl_seconds = int(ttl_minutes * 60)
# Apply TTL individually per key so that a single EXPIRE failure
# (e.g. MOVED on Redis Enterprise proxy) does not prevent TTL
# from being set on the remaining keys.
all_keys = [main_key] + (related_keys or [])
for key in all_keys:
try:
self._redis.expire(key, ttl_seconds)
except Exception:
logger.warning("Failed to apply TTL to key: %s", key)
return True
def _dump_checkpoint(self, checkpoint: Checkpoint) -> dict[str, Any]:
"""Convert checkpoint to Redis format."""
type_, data = self.serde.dumps_typed(checkpoint)
# Decode the serialized data - handle both JSON and msgpack
if type_ == "json":
checkpoint_data = cast(dict, orjson.loads(data))
else:
checkpoint_data = cast(dict, self.serde.loads_typed((type_, data)))
if type_ == "msgpack":
# Msgpack fallback can rehydrate LangChain messages as live Python
# objects. Normalize the checkpoint back through the JSON serializer
# so RedisJSON only sees JSON-safe constructor dictionaries.
checkpoint_data = cast(
dict, self._msgpack_to_redis_json(checkpoint_data)
)
# Ensure channel_versions are always strings to fix issue #40
if "channel_versions" in checkpoint_data:
checkpoint_data["channel_versions"] = {
k: str(v) for k, v in checkpoint_data["channel_versions"].items()
}
return {"type": type_, **checkpoint_data, "pending_sends": []}
def _msgpack_to_redis_json(self, value: Any) -> dict[str, Any]:
"""Convert a msgpack-deserialized checkpoint into Redis JSON-safe data."""
binary_safe = self._replace_binary_markers(value)
serializer = cast(JsonPlusRedisSerializer, self.serde)
processed = serializer._preprocess_interrupts(binary_safe)
json_bytes = orjson.dumps(
processed,
default=serializer._default_handler,
option=orjson.OPT_NON_STR_KEYS,
)
return cast(dict, orjson.loads(json_bytes))
def _replace_binary_markers(self, value: Any) -> Any:
"""Recursively replace binary values with JSON-safe markers."""
if isinstance(value, bytes):
return {"__bytes__": self._encode_blob(value)}
if isinstance(value, dict):
return {k: self._replace_binary_markers(v) for k, v in value.items()}
if isinstance(value, list):
return [self._replace_binary_markers(item) for item in value]
if isinstance(value, tuple):
return tuple(self._replace_binary_markers(item) for item in value)
return value
def _deserialize_channel_values(
self, channel_values: dict[str, Any]
) -> dict[str, Any]:
"""Deserialize channel values that were stored inline.
When channel values are stored inline in the checkpoint, they're in their
serialized form. This method deserializes them back to their original types.
This specifically handles LangChain message objects that may be stored in their
serialized format: {'lc': 1, 'type': 'constructor', 'id': [...], 'kwargs': {...}}
and ensures they are properly reconstructed as message objects.
"""
if not channel_values:
return {}
try:
# Apply recursive deserialization to handle nested structures and LangChain objects
return self._recursive_deserialize(channel_values)
except Exception as e:
logger.warning(
f"Error deserializing channel values, attempting recovery: {e}"
)
# Attempt to recover by processing each channel individually
recovered = {}
for key, value in channel_values.items():
try:
recovered[key] = self._recursive_deserialize(value)
except Exception as inner_e:
logger.error(
f"Failed to deserialize channel '{key}': {inner_e}. "
f"Value will be returned as-is."
)
recovered[key] = value
return recovered
def _recursive_deserialize(self, obj: Any) -> Any:
"""Recursively deserialize LangChain objects and nested structures.
This method specifically handles the deserialization of LangChain message objects
that may be stored in their serialized format to prevent MESSAGE_COERCION_FAILURE.
Args:
obj: The object to deserialize, which may be a dict, list, or primitive.
Returns:
The deserialized object, with LangChain objects properly reconstructed.
"""
if isinstance(obj, dict):
# Check if this is a bytes marker from msgpack storage
if "__bytes__" in obj and len(obj) == 1:
# Decode base64-encoded bytes
return self._decode_blob(obj["__bytes__"])
# Check if this is a Send object marker (issue #94)
if (
obj.get("__send__") is True
and "node" in obj
and "arg" in obj
and len(obj) == 3
):
try:
from langgraph.types import Send
return Send(
node=obj["node"],
arg=self._recursive_deserialize(obj["arg"]),
)
except (ImportError, TypeError, ValueError) as e:
logger.debug(
"Failed to deserialize Send object: %s", e, exc_info=True
)
# Check if this is a LangChain serialized object
if obj.get("lc") in (1, 2) and obj.get("type") == "constructor":
try:
# Use the serde's reviver to reconstruct the object
if hasattr(self.serde, "_revive_if_needed"):
return self.serde._revive_if_needed(obj)
elif hasattr(self.serde, "_reviver"):
return self.serde._reviver(obj)
else:
# Log warning if serde doesn't have reviver
logger.warning(
"Serializer does not have a reviver method. "
"LangChain object may not be properly deserialized. "
f"Object ID: {obj.get('id')}"
)
return obj
except Exception as e:
# Provide detailed error message for debugging
obj_id = obj.get("id", "unknown")
obj_type = (
obj.get("id", ["unknown"])[-1]
if isinstance(obj.get("id"), list)
else "unknown"
)
logger.error(
f"Failed to deserialize LangChain object of type '{obj_type}'. "
f"This may cause MESSAGE_COERCION_FAILURE. Error: {e}. "
f"Object structure: lc={obj.get('lc')}, type={obj.get('type')}, "
f"id={obj_id}"
)
# Return the object as-is to prevent complete failure
return obj
# Recursively process nested dicts
return {k: self._recursive_deserialize(v) for k, v in obj.items()}
elif isinstance(obj, list):
# Recursively process lists
return [self._recursive_deserialize(item) for item in obj]
else:
# Return primitives as-is
return obj
def _dump_writes(
self,
thread_id: str,
checkpoint_ns: str,
checkpoint_id: str,
task_id: str,
writes: Sequence[tuple[str, Any]],
) -> list[dict[str, Any]]:
"""Convert write operations for Redis storage."""
return [
{
"thread_id": to_storage_safe_id(thread_id),
"checkpoint_ns": to_storage_safe_str(checkpoint_ns),
"checkpoint_id": to_storage_safe_id(checkpoint_id),
"task_id": task_id,
"idx": WRITES_IDX_MAP.get(channel, idx),
"channel": channel,
"type": t,
"blob": self._encode_blob(b), # Encode bytes to base64 string for Redis
}
for idx, (channel, value) in enumerate(writes)
for t, b in [self.serde.dumps_typed(value)]
]
def _load_metadata(self, metadata: dict[str, Any]) -> CheckpointMetadata:
"""Load metadata from Redis-compatible dictionary.
Args:
metadata: Dictionary representation from Redis.
Returns:
Original metadata dictionary.
"""
# Roundtrip through serializer to ensure proper type handling
type_str, data_bytes = self.serde.dumps_typed(metadata)
return self.serde.loads_typed((type_str, data_bytes))
def _dump_metadata(self, metadata: CheckpointMetadata) -> str:
"""Convert metadata to a Redis-compatible dictionary.
Args:
metadata: Metadata to convert.
Returns:
Dictionary representation of metadata for Redis storage.
"""
type_str, serialized_bytes = self.serde.dumps_typed(metadata)
# NOTE: we're using JSON serializer (not msgpack), so we need to remove null characters before writing
return serialized_bytes.decode().replace("\\u0000", "")
def get_next_version( # type: ignore[override]
self, current: Optional[str], channel: ChannelProtocol[Any, Any, Any]
) -> str:
"""Generate next version number."""
if current is None:
current_v = 0
elif isinstance(current, int):
current_v = current
else:
current_v = int(current.split(".")[0])
next_v = current_v + 1
next_h = random.random()
return f"{next_v:032}.{next_h:016}"
def _encode_blob(self, blob: Any) -> str:
"""Encode blob data for Redis storage."""
if isinstance(blob, bytes):
return base64.b64encode(blob).decode()
return blob
def _decode_blob(self, blob: str) -> bytes:
"""Decode blob data from Redis storage."""
try:
return base64.b64decode(blob)
except (binascii.Error, TypeError):
# Handle both malformed base64 data and incorrect input types
return blob.encode() if isinstance(blob, str) else blob
def _load_writes_from_redis(self, write_key: str) -> List[Tuple[str, str, Any]]:
"""Load writes from Redis JSON storage by key."""
if not write_key:
return []
# Get the full JSON document
# Cast needed: redis-py types json().get() as List[JsonType] but returns dict
result = cast(Optional[Dict[str, Any]], self._redis.json().get(write_key))
if not result:
return []
writes = []
for write in result["writes"]:
writes.append(
(
write["task_id"],
write["channel"],
self.serde.loads_typed(
(write["type"], self._decode_blob(write["blob"]))
),
)
)
return writes
def put_writes(
self,
config: RunnableConfig,
writes: Sequence[tuple[str, Any]],
task_id: str,
task_path: str = "",
) -> None:
"""Store intermediate writes linked to a checkpoint.
Args:
config: Configuration of the related checkpoint.
writes: List of writes to store, each as (channel, value) pair.
task_id: Identifier for the task creating the writes.
task_path: Optional path info for the task.
"""
thread_id = config["configurable"]["thread_id"]
checkpoint_ns = config["configurable"].get("checkpoint_ns", "")
checkpoint_id = config["configurable"]["checkpoint_id"]
# Transform writes into appropriate format
writes_objects = []
for idx, (channel, value) in enumerate(writes):
type_, blob = self.serde.dumps_typed(value)
write_obj = {
"thread_id": to_storage_safe_id(thread_id),
"checkpoint_ns": to_storage_safe_str(checkpoint_ns),
"checkpoint_id": to_storage_safe_id(checkpoint_id),
"task_id": task_id,
"task_path": task_path,
"idx": WRITES_IDX_MAP.get(channel, idx),
"channel": channel,
"type": type_,
"blob": self._encode_blob(
blob
), # Encode bytes to base64 string for Redis
}
writes_objects.append(write_obj)
# For each write, check existence and then perform appropriate operation
with self._redis.json().pipeline(transaction=False) as pipeline:
# Keep track of keys we're creating
created_keys = []
for write_obj in writes_objects:
idx_value = write_obj["idx"]
assert isinstance(idx_value, int)
key = self._make_redis_checkpoint_writes_key(
thread_id,
checkpoint_ns,
checkpoint_id,
task_id,
idx_value,
)
# First check if key exists
key_exists = self._redis.exists(key) == 1
if all(w[0] in WRITES_IDX_MAP for w in writes):
# UPSERT case - only update specific fields
if key_exists:
# Update only channel, type, and blob fields
pipeline.json().set(key, "$.channel", write_obj["channel"])
pipeline.json().set(key, "$.type", write_obj["type"])
pipeline.json().set(key, "$.blob", write_obj["blob"])
else:
# For new records, set the complete object
pipeline.json().set(key, "$", write_obj)
created_keys.append(key)
else:
# INSERT case - only insert if doesn't exist
if not key_exists:
pipeline.json().set(key, "$", write_obj)
created_keys.append(key)
pipeline.execute()
# Apply TTL to newly created keys
if created_keys and self.ttl_config and "default_ttl" in self.ttl_config:
self._apply_ttl_to_keys(
created_keys[0], created_keys[1:] if len(created_keys) > 1 else None
)
# Update checkpoint to indicate it has writes
if writes_objects:
checkpoint_key = self._make_redis_checkpoint_key(
to_storage_safe_id(thread_id),
to_storage_safe_str(checkpoint_ns),
to_storage_safe_id(checkpoint_id),
)
# Check if the checkpoint exists before updating
if self._redis.exists(checkpoint_key):
# JSON.SET can add new fields at non-root paths for existing documents
# Use JSONPath $ to update at root level
self._redis.json().set(checkpoint_key, "$.has_writes", True)
def _load_pending_writes(
self, thread_id: str, checkpoint_ns: str, checkpoint_id: str
) -> List[PendingWrite]:
if checkpoint_id is None:
return [] # Early return if no checkpoint_id
# Most checkpoints don't have writes, return empty list quickly
# Quick check: see if write registry exists and has any keys
write_registry_key = self._key_registry.make_write_keys_zset_key(
thread_id, checkpoint_ns, checkpoint_id
)
registry_exists = self._redis.exists(write_registry_key)
if not registry_exists:
# No writes registry means no writes
return []
# Use search index instead of keys() to avoid CrossSlot errors
# Note: All tag fields use sentinel values for consistency
writes_query = FilterQuery(
filter_expression=(Tag("thread_id") == to_storage_safe_id(thread_id))
& (Tag("checkpoint_ns") == to_storage_safe_str(checkpoint_ns))
& (Tag("checkpoint_id") == to_storage_safe_id(checkpoint_id)),
return_fields=["task_id", "idx", "channel", "type", "$.blob"],
num_results=1000, # Adjust as needed
)
writes_results = self.checkpoint_writes_index.search(writes_query)
# Sort results by idx to maintain order
sorted_writes = sorted(writes_results.docs, key=lambda x: getattr(x, "idx", 0))
# Build the writes dictionary
writes_dict: Dict[Tuple[str, str], Dict[str, Any]] = {}
for doc in sorted_writes:
task_id = str(getattr(doc, "task_id", ""))
idx = str(getattr(doc, "idx", 0))
blob_data = getattr(doc, "$.blob", "")
# Ensure blob is bytes for deserialization
if isinstance(blob_data, str):
blob_data = blob_data.encode("utf-8")
writes_dict[(task_id, idx)] = {
"task_id": task_id,
"idx": idx,
"channel": str(getattr(doc, "channel", "")),
"type": str(getattr(doc, "type", "")),
"blob": blob_data,
}
pending_writes = BaseRedisSaver._load_writes(self.serde, writes_dict)
return pending_writes
def _load_pending_writes_with_registry_check(
self,
thread_id: str,
checkpoint_ns: str,
checkpoint_id: str,
checkpoint_has_writes: bool,
registry_has_writes: bool,
) -> List[PendingWrite]:
"""Load pending writes with pre-computed registry check to avoid duplicate Redis calls."""
if checkpoint_id is None:
return [] # Early return if no checkpoint_id
# Pre-computed registry check instead of making another Redis call
if not registry_has_writes:
# No writes in registry means no writes to load
return []
# Also check checkpoint-level has_writes flag for additional optimization
if not checkpoint_has_writes:
return []
# Fallback to original FT.SEARCH logic since registry indicates writes exist
# Use search index instead of keys() to avoid CrossSlot errors
# Note: All tag fields use sentinel values for consistency
writes_query = FilterQuery(
filter_expression=(Tag("thread_id") == to_storage_safe_id(thread_id))
& (Tag("checkpoint_ns") == to_storage_safe_str(checkpoint_ns))
& (Tag("checkpoint_id") == to_storage_safe_id(checkpoint_id)),
return_fields=["task_id", "idx", "channel", "type", "$.blob"],
num_results=1000, # Adjust as needed
)
writes_results = self.checkpoint_writes_index.search(writes_query)
# Sort results by idx to maintain order
sorted_writes = sorted(writes_results.docs, key=lambda x: getattr(x, "idx", 0))
# Build the writes dictionary
writes_dict: Dict[Tuple[str, str], Dict[str, Any]] = {}
for doc in sorted_writes:
task_id = str(getattr(doc, "task_id", ""))
idx = str(getattr(doc, "idx", 0))
blob_data = getattr(doc, "$.blob", "")
# Ensure blob is bytes for deserialization
if isinstance(blob_data, str):
blob_data = blob_data.encode("utf-8")
writes_dict[(task_id, idx)] = {
"task_id": task_id,
"idx": idx,
"channel": str(getattr(doc, "channel", "")),
"type": str(getattr(doc, "type", "")),
"blob": blob_data,
}
pending_writes = BaseRedisSaver._load_writes(self.serde, writes_dict)
return pending_writes
@staticmethod
def _load_writes(
serde: SerializerProtocol, task_id_to_data: dict[tuple[str, str], dict]
) -> list[PendingWrite]:
"""Deserialize pending writes."""
writes = [
(
task_id,
data["channel"],
serde.loads_typed(
(data["type"], BaseRedisSaver._decode_blob_static(data["blob"]))
),
)
for (task_id, _), data in task_id_to_data.items()
]
return writes
@staticmethod
def _decode_blob_static(blob: bytes | str) -> bytes:
"""Decode blob data from Redis storage (static method)."""
try:
# If it's already bytes, try to decode as base64
if isinstance(blob, bytes):
return base64.b64decode(blob)
# If it's a string, encode to bytes first then decode
return base64.b64decode(blob.encode("utf-8"))
except (binascii.Error, TypeError, ValueError):
# Handle both malformed base64 data and incorrect input types
return blob.encode("utf-8") if isinstance(blob, str) else blob
@staticmethod
def _parse_redis_checkpoint_writes_key(redis_key: str) -> dict:
# Ensure redis_key is a string
redis_key = safely_decode(redis_key)
parts = redis_key.split(REDIS_KEY_SEPARATOR)
# Ensure we have at least 6 parts
if len(parts) < 6:
raise ValueError(
f"Expected at least 6 parts in Redis key, got {len(parts)}"
)
# Extract the first 6 parts regardless of total length
namespace, thread_id, checkpoint_ns, checkpoint_id, task_id, idx = parts[:6]
if namespace != CHECKPOINT_WRITE_PREFIX:
raise ValueError("Expected checkpoint key to start with 'checkpoint'")
return {
"thread_id": to_storage_safe_str(thread_id),
"checkpoint_ns": to_storage_safe_str(checkpoint_ns),
"checkpoint_id": to_storage_safe_str(checkpoint_id),
"task_id": task_id,
"idx": idx,
}
def _make_redis_checkpoint_key(
self, thread_id: str, checkpoint_ns: str, checkpoint_id: str
) -> str:
return REDIS_KEY_SEPARATOR.join(
[
self._checkpoint_prefix,
str(to_storage_safe_id(thread_id)),
to_storage_safe_str(checkpoint_ns),
str(to_storage_safe_id(checkpoint_id)),
]
)
def _make_redis_checkpoint_latest_key(
self, thread_id: str, checkpoint_ns: str
) -> str:
"""Build the latest-checkpoint pointer key."""
storage_safe_thread_id = str(to_storage_safe_id(thread_id))
storage_safe_checkpoint_ns = to_storage_safe_str(checkpoint_ns)
return REDIS_KEY_SEPARATOR.join(
[
f"{self._checkpoint_prefix}_latest",
storage_safe_thread_id,
storage_safe_checkpoint_ns,
]
)
def _make_redis_checkpoint_writes_key(
self,
thread_id: str,
checkpoint_ns: str,
checkpoint_id: str,
task_id: str,
idx: Optional[int],
) -> str:
storage_safe_thread_id = str(to_storage_safe_id(thread_id))
storage_safe_checkpoint_ns = to_storage_safe_str(checkpoint_ns)
storage_safe_checkpoint_id = str(to_storage_safe_id(checkpoint_id))
if idx is None:
return REDIS_KEY_SEPARATOR.join(
[
self._checkpoint_write_prefix,
storage_safe_thread_id,
storage_safe_checkpoint_ns,
storage_safe_checkpoint_id,
task_id,
]
)
return REDIS_KEY_SEPARATOR.join(
[
self._checkpoint_write_prefix,
storage_safe_thread_id,
storage_safe_checkpoint_ns,
storage_safe_checkpoint_id,
task_id,
str(idx),
]
)