Coverage for app / agents / checkpoint.py: 92%

51 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""How graph state is written to a checkpoint — and why that cannot fail. 

2 

3A paused run (``ask_user``, an approval gate, a scope question) resumes from 

4the checkpoint LangGraph wrote at every superstep, so every value in 

5``GraphState`` is serialised: messages, node results, the evaluator's 

6verdict, skill state. Two ways that could break, both closed here: 

7 

8* **Types revived from a checkpoint.** langgraph-checkpoint revives a class 

9 only when it is allowed. Today an unregistered class revives with a 

10 warning; under ``LANGGRAPH_STRICT_MSGPACK`` — the stated future default — 

11 it would come back as a plain dict, and a resumed run would read an 

12 ``EvaluatorVerdict`` that is not one. ``state_types()`` registers every 

13 pydantic model and enum the agent modules define, from ``STATE_MODULES``; 

14 ``tests/agents/test_checkpoint.py`` fails when a module that defines one 

15 is missing from it. 

16* **A value msgpack cannot encode** — an integer beyond 64 bits from a 

17 ``parse`` transform, an object no encoder knows. That raised at the 

18 checkpoint write and failed the run. ``CheckpointSerializer`` retries with 

19 the value made encodable, and as a last resort writes it as JSON 

20 (``safe_json``), which ``loads_typed`` reads back. A degraded value in one 

21 channel beats a failed run. 

22""" 

23 

24from __future__ import annotations 

25 

26import importlib 

27from enum import Enum 

28from functools import lru_cache 

29from typing import Any 

30 

31from langchain_core.messages import BaseMessage 

32from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer 

33from pydantic import BaseModel 

34 

35from app.util import safe_json 

36from app.util.logger import get_logger 

37 

38logger = get_logger(__name__) 

39 

40#: Modules whose pydantic models and enums may sit in graph state (node 

41#: results, verdicts, plans, clarification payloads). 

42STATE_MODULES: tuple[str, ...] = ( 

43 "app.agents.analyzer", 

44 "app.agents.base", 

45 "app.agents.conditions", 

46 "app.agents.enums", 

47 "app.agents.graph", 

48 "app.agents.interfaces", 

49 "app.agents.loop", 

50 "app.agents.operations", 

51 "app.agents.planner.enums", 

52 "app.agents.planner.models", 

53 "app.agents.researcher", 

54 "app.agents.reviewer", 

55 "app.agents.router", 

56 "app.agents.source_ledger", 

57 "app.agents.validator", 

58 "app.memory.kinds", 

59 "app.memory.render", 

60 "app.tools.clarify", 

61 # The documents attached to the conversation (``GraphState.attachments``). 

62 "app.util.attachment_wire", 

63 "app.util.attachments", 

64) 

65 

66_INT64_MIN = -(2**63) 

67_UINT64_MAX = 2**64 - 1 

68 

69 

70def defined_types(module_name: str) -> list[type]: 

71 """The pydantic models and enums ``module_name`` itself defines.""" 

72 module = importlib.import_module(module_name) 

73 found: list[type] = [] 

74 for value in vars(module).values(): 

75 if ( 

76 isinstance(value, type) 

77 and value.__module__ == module_name 

78 and issubclass(value, (BaseModel, Enum)) 

79 and value not in (BaseModel, Enum) 

80 ): 

81 found.append(value) 

82 return found 

83 

84 

85@lru_cache(maxsize=1) 

86def state_types() -> tuple[type, ...]: 

87 """Every type registered to revive from a checkpoint.""" 

88 return tuple( 

89 dict.fromkeys(t for name in STATE_MODULES for t in defined_types(name)) 

90 ) 

91 

92 

93def _encodable(value: Any) -> Any: 

94 """``value`` with what msgpack refuses replaced: out-of-range integers 

95 become strings, models become their fields. Messages are left whole.""" 

96 if isinstance(value, bool) or value is None: 

97 return value 

98 if isinstance(value, int): 

99 return value if _INT64_MIN <= value <= _UINT64_MAX else str(value) 

100 if isinstance(value, dict): 

101 return {k: _encodable(v) for k, v in value.items()} 

102 if isinstance(value, (list, tuple)): 

103 return [_encodable(v) for v in value] 

104 if isinstance(value, BaseMessage): 

105 return value 

106 if isinstance(value, BaseModel): 

107 return _encodable(value.model_dump()) 

108 return value 

109 

110 

111class CheckpointSerializer(JsonPlusSerializer): 

112 """``JsonPlusSerializer`` with svc-ai's state types allowed, and a write 

113 that cannot fail. See the module docstring.""" 

114 

115 def __init__(self) -> None: 

116 super().__init__(allowed_msgpack_modules=state_types()) 

117 

118 def dumps_typed(self, obj: Any) -> tuple[str, bytes]: 

119 try: 

120 return super().dumps_typed(obj) 

121 except Exception as exc: # noqa: BLE001 — degrade the value, not the run 

122 logger.warning( 

123 "[checkpoint] %s did not encode (%s) — writing an encodable copy", 

124 type(obj).__name__, 

125 exc, 

126 ) 

127 try: 

128 return super().dumps_typed(_encodable(obj)) 

129 except Exception: # noqa: BLE001 

130 logger.warning( 

131 "[checkpoint] %s still did not encode — writing it as JSON", 

132 type(obj).__name__, 

133 ) 

134 return "json", safe_json.dumps(obj).encode()