Coverage for core / src / sensorkit / core / state.py: 98%

101 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2from __future__ import annotations 

3 

4import asyncio 

5import contextlib 

6import copy 

7import inspect 

8import threading 

9from collections.abc import AsyncIterator, Iterable 

10from typing import ClassVar, Protocol, Self, get_type_hints 

11 

12from pydantic import BaseModel 

13 

14from sensorkit.backend.base import KVError 

15from sensorkit.backend.event import Event 

16from sensorkit.core.entity import EntityBase, EntityClient 

17from sensorkit.core.impl.entity import EntityImpl 

18 

19 

20class StateUpdate[S](Protocol): 

21 """Publish state events within an update scope.""" 

22 

23 async def __call__( 

24 self, 

25 *events: Event, 

26 publish_state: bool = True, 

27 return_snapshot: bool = False, 

28 ) -> S | None: 

29 """Apply events and optionally publish or copy the updated state.""" 

30 

31 

32class EventSourcedState(BaseModel): 

33 """State model that can recover values of Event-typed fields from an event stream.""" 

34 

35 _event_fields: ClassVar[dict[type[Event], str]] = {} 

36 _event_fields_lock: ClassVar[threading.Lock] = threading.Lock() 

37 

38 def model_post_init(self, __context): 

39 """Introspect fields at init time to identify Event-typed fields.""" 

40 super().model_post_init(__context) 

41 self._set_event_fields() 

42 self._update_lock = asyncio.Lock() 

43 

44 @classmethod 

45 def _set_event_fields(cls): 

46 if cls._event_fields: 

47 return 

48 

49 with cls._event_fields_lock: 

50 # Double-check pattern to avoid redundant work if another thread already initialized 

51 if cls._event_fields: 

52 return 

53 

54 # Store at class level. 

55 cls._event_fields = cls._introspect_event_fields() 

56 

57 @classmethod 

58 def _introspect_event_fields(cls): 

59 type_hints = get_type_hints(cls) 

60 event_fields = {} 

61 

62 for field, field_type in type_hints.items(): 

63 # Check if field type is a subclass of Event 

64 if inspect.isclass(field_type) and issubclass(field_type, Event): 

65 if field_type in event_fields: 

66 raise RuntimeError( 

67 f"Duplicate event type {field_type.model_tag()}" 

68 f" found at {cls.__name__}.{field}" 

69 ) 

70 

71 event_fields[field_type] = field 

72 

73 return event_fields 

74 

75 async def update( 

76 self, 

77 entity: EntityImpl, 

78 *events: Event, 

79 publish_state=True, 

80 return_snapshot=False, 

81 ): 

82 """Apply events to the state, emit them on the entity's stream, and optionally publish the state to KV. 

83 

84 Returns a deep copy of the updated state if return_snapshot is True, else None. 

85 """ 

86 async with self.updating(entity) as update: 

87 return await update( 

88 *events, publish_state=publish_state, return_snapshot=return_snapshot 

89 ) 

90 

91 @contextlib.asynccontextmanager 

92 async def updating(self, entity: EntityImpl) -> AsyncIterator[StateUpdate[Self]]: 

93 """Hold the update lock while reading state and publishing derived events. 

94 

95 Use the yielded updater for writes in this scope. 

96 It accepts `update`'s event and publication arguments and raises `RuntimeError` 

97 after the scope exits. 

98 Within the scope, calling `update` or entering another update scope on this state 

99 would deadlock. 

100 """ 

101 async with self._update_lock: 

102 active = True 

103 

104 async def update(*events: Event, publish_state=True, return_snapshot=False): 

105 if not active: 

106 raise RuntimeError("State update scope has exited") 

107 

108 return await self._apply(entity, events, publish_state, return_snapshot) 

109 

110 try: 

111 yield update 

112 finally: 

113 active = False 

114 

115 async def _apply( 

116 self, 

117 entity: EntityImpl, 

118 events: Iterable[Event], 

119 publish_state: bool, 

120 return_snapshot: bool, 

121 ): 

122 for event in events: 

123 field = self._event_fields.get(type(event)) 

124 

125 if field is None: 

126 raise KeyError(f"No {event.event_model} event field exists") 

127 

128 setattr(self, field, event) 

129 await entity.emit_event(event) 

130 

131 # Events are the source of truth and precede the KV snapshot. 

132 if publish_state: 

133 await entity.kv_put_model(self) 

134 

135 if not return_snapshot: 

136 return None 

137 

138 # Give the snapshot a fresh lock so runtime waiters are excluded from the copy. 

139 return copy.deepcopy(self, {id(self._update_lock): asyncio.Lock()}) 

140 

141 @classmethod 

142 async def event_stream[T: Event](cls, entity: EntityClient, event_type: type[T]): 

143 """Yield a continuous stream of events of the given type, starting from the current stored state.""" 

144 field = cls._event_fields[event_type] 

145 stream = await entity.monitor_event(event_type) 

146 state = await entity.kv_get_model(cls) 

147 original: T | None = getattr(state, field) 

148 original_id = original.event_id.int if original is not None else 0 

149 

150 yield original 

151 

152 # TODO: Add backend support for resuming an event stream from a snapshot. 

153 # Subscribe before reading the snapshot, then filter events already reflected in it. 

154 # 

155 # Skip any stream events already reflected in `original` (or that produced it), then yield 

156 # everything after. We order by the full uuid7 event_id rather than timestamp(): the latter 

157 # is only millisecond-resolution, so two events emitted in the same millisecond compare 

158 # equal and a genuinely newer event would be silently dropped, hanging the consumer. 

159 async for event in stream: 

160 if event.event_id.int > original_id: 

161 yield event 

162 break 

163 

164 async for event in stream: 

165 yield event 

166 

167 raise RuntimeError("unexpected end of stream") 

168 

169 @classmethod 

170 async def recover(cls, entity: EntityBase) -> Self: 

171 """Recover state from the KV store and validate Event fields are up to date.""" 

172 # Retrieve the stored data from KV. 

173 obj = await entity.kv_get_model(cls) 

174 

175 # Verify that each cached event is the latest event of that type. If it isn't, retrieve 

176 # the latest event. 

177 for field in cls._event_fields.values(): 

178 event: Event = getattr(obj, field) 

179 newer = await cls._get_latest_event_if_newer(entity, event) 

180 

181 if newer is not None: 

182 setattr(obj, field, newer) 

183 

184 return obj 

185 

186 @classmethod 

187 async def recover_or_init(cls, entity: EntityBase, **kwargs): 

188 """Recover state from KV, or create and publish a new instance using kwargs if none exists.""" 

189 try: 

190 return await cls.recover(entity) 

191 except KVError: 

192 new = cls(**kwargs) 

193 await entity.kv_put_model(new) 

194 return new 

195 

196 @staticmethod 

197 async def _get_latest_event_if_newer(entity: EntityBase, event: Event): 

198 # TODO: Implement. 

199 return event or None