Coverage for collectra/commons/base.py: 96.34%

82 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1import enum 

2from abc import ABC, abstractmethod 

3from pathlib import Path 

4from typing import Any, ClassVar, Generic, TypeVar 

5 

6from pydantic import BaseModel, ConfigDict 

7 

8from ..usage import UsageLedger 

9 

10__all__ = [ 

11 "T", 

12 "EntityMixin", 

13 "PositionalFields", 

14 "LenientAttributes", 

15 "BaseEntity", 

16 "Node", 

17 "NodeStatus", 

18 "TaskContext", 

19] 

20 

21T = TypeVar("T") 

22 

23 

24class TaskContext(BaseModel): 

25 """Runtime context for task execution. 

26 

27 This provides tasks with runtime information without polluting 

28 their function signatures or requiring global state. 

29 

30 Attributes: 

31 usage_file: Optional path to write LLM usage statistics. 

32 usage_ledger: Adds up the LLM usage of the whole run, for its summary. 

33 render: Whether to render workflow visualizations. 

34 file_path: Current file being processed. 

35 single_run: Whether to stop after first task execution. 

36 """ 

37 

38 model_config = ConfigDict(arbitrary_types_allowed=True) 

39 

40 usage_file: Path | None = None 

41 usage_ledger: UsageLedger | None = None 

42 render: bool = False 

43 file_path: Path | None = None 

44 single_run: bool = False 

45 

46 

47class EntityMixin: 

48 """Naming and serialisation shared by artefacts and pydantic task models.""" 

49 

50 def __str__(self) -> str: 

51 return f"{self.name}\n{self.get_class_path()}" 

52 

53 def get_name(self) -> str: 

54 """Get the name of the task. 

55 

56 Returns: 

57 str: The name of the task. 

58 """ 

59 return self.name 

60 

61 def serialize(self) -> dict: 

62 serialized = dict(type=self.get_class_path()) 

63 for key, value in self.attributes.items(): 

64 if isinstance(value, Path): 

65 value = value.name 

66 serialized[key] = value 

67 return serialized 

68 

69 @property 

70 def attributes(self) -> dict: 

71 ignore = self.attributes_to_ignore() 

72 values = dict(self.__dict__) 

73 # Pydantic keeps undeclared (extra) attributes outside ``__dict__``. 

74 values.update(getattr(self, "__pydantic_extra__", None) or {}) 

75 return {k: v for k, v in values.items() if k not in ignore} 

76 

77 def attributes_to_ignore(self) -> set: 

78 return set() 

79 

80 @classmethod 

81 def get_class_path(cls: type) -> str: 

82 """Return the fully qualified path for a class. 

83 

84 Example: 

85 >>> from collectra.images import Image 

86 >>> get_class_path(Image) 

87 'collectra.images.Image' 

88 """ 

89 return f"{cls.__module__.split('.')[0]}.{cls.__name__}" 

90 

91 

92class LenientAttributes: 

93 """Keeps pydantic models usable like plain Python objects when assigning. 

94 

95 - A method or property can be replaced on an instance (tests and callers do 

96 this), without that being treated as a field assignment. 

97 - Validated assignment rebuilds ``__dict__`` from the declared fields; state 

98 held there outside the fields (cached properties, ad-hoc attributes) is 

99 carried over rather than lost. 

100 """ 

101 

102 def __setattr__(self, name: str, value: Any) -> None: 

103 cls = type(self) 

104 declared = name in cls.model_fields or name in cls.__private_attributes__ 

105 if not declared and hasattr(cls, name): 

106 object.__setattr__(self, name, value) 

107 return 

108 lazy = { 

109 key: held 

110 for key, held in self.__dict__.items() 

111 if key not in cls.model_fields 

112 } 

113 super().__setattr__(name, value) 

114 for key, held in lazy.items(): 

115 self.__dict__.setdefault(key, held) 

116 

117 

118class PositionalFields: 

119 """Lets a model's fields be given positionally, in declaration order. 

120 

121 Fields named in ``_runtime_fields`` are set or measured at runtime and are 

122 skipped, as they were when these classes were dataclasses. 

123 """ 

124 

125 _runtime_fields: ClassVar[frozenset[str]] = frozenset() 

126 

127 def __init__(self, *args: Any, **kwargs: Any) -> None: 

128 if args: 

129 names = [ 

130 field 

131 for field in type(self).model_fields 

132 if field not in self._runtime_fields 

133 ] 

134 if len(args) > len(names): 

135 raise TypeError( 

136 f"{type(self).__name__} takes at most {len(names)} positional " 

137 f"arguments but {len(args)} were given" 

138 ) 

139 for field_name, value in zip(names, args): 

140 if field_name in kwargs: 

141 raise TypeError( 

142 f"{type(self).__name__} got multiple values for " 

143 f"argument {field_name!r}" 

144 ) 

145 kwargs[field_name] = value 

146 super().__init__(**kwargs) 

147 

148 

149class BaseEntity(EntityMixin, ABC, Generic[T]): 

150 

151 def __init__(self, name: str) -> None: 

152 self.name = name 

153 

154 @abstractmethod 

155 def __call__(self) -> T: 

156 pass 

157 

158 

159class NodeStatus(enum.Enum): 

160 NOT_READY = "not_ready" 

161 READY = "ready" 

162 RUNNING = "running" 

163 COMPLETED = "completed" 

164 FAILED = "failed" 

165 

166 def __str__(self) -> str: 

167 return self.value 

168 

169 

170class Node(PositionalFields, BaseModel): 

171 """A node of the workflow graph.""" 

172 

173 model_config = ConfigDict( 

174 validate_assignment=True, arbitrary_types_allowed=True, extra="forbid" 

175 ) 

176 _runtime_fields: ClassVar[frozenset[str]] = frozenset({"status"}) 

177 

178 name: str 

179 status: NodeStatus = NodeStatus.NOT_READY 

180 

181 def process(self) -> list: 

182 return []