Coverage for src / invariant / protocol.py: 66.67%

21 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-02-25 10:05 +0100

1"""ICacheable Protocol definition.""" 

2 

3from typing import BinaryIO, Protocol, runtime_checkable 

4 

5try: 

6 from typing import Self 

7except ImportError: 

8 from typing_extensions import Self 

9 

10 

11@runtime_checkable 

12class ICacheable(Protocol): 

13 """Protocol for all cacheable data types. 

14 

15 All data passed between Nodes must implement this protocol to ensure 

16 valid Manifest construction and artifact storage. 

17 """ 

18 

19 def get_stable_hash(self) -> str: 

20 """Returns a deterministic SHA-256 hash of the object's structural state. 

21 

22 This represents the 'Identity' of the data. The hash must be: 

23 - Deterministic: Same inputs always produce same hash 

24 - Stable: Hash doesn't change across serialization/deserialization 

25 - Collision-resistant: Different inputs should produce different hashes 

26 

27 Returns: 

28 A hexadecimal SHA-256 hash string (64 characters). 

29 """ 

30 ... 

31 

32 def to_stream(self, stream: BinaryIO) -> None: 

33 """Serializes the object to a binary stream for persistent storage. 

34 

35 Args: 

36 stream: A binary I/O stream to write the serialized data to. 

37 

38 The serialization format must be deterministic and allow for 

39 complete reconstruction via from_stream. 

40 """ 

41 ... 

42 

43 @classmethod 

44 def from_stream(cls, stream: BinaryIO) -> "ICacheable": 

45 """Hydrates the object from a binary stream. 

46 

47 Args: 

48 stream: A binary I/O stream to read the serialized data from. 

49 

50 Returns: 

51 An instance of the class with state restored from the stream. 

52 

53 This must be the inverse operation of to_stream. 

54 """ 

55 ... 

56 

57 

58@runtime_checkable 

59class IJsonRepresentable(Protocol): 

60 """Optional: ICacheable types can implement this for human-readable JSON in graph serialization.""" 

61 

62 def to_json_value(self) -> dict: 

63 """Return a JSON-serializable dict representation of this object.""" 

64 ... 

65 

66 @classmethod 

67 def from_json_value(cls, obj: dict) -> Self: 

68 """Reconstruct an instance from a JSON dict.""" 

69 ...