Coverage for collectra/tasks/base.py: 93.02%

86 statements  

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

1"""Base task class for Collectra workflows. 

2 

3This module defines the fundamental task interface used throughout the Collectra system. 

4It provides the base classes that all tasks must inherit from and implements the core task execution lifecycle. 

5 

6Classes: 

7 Task: Base class for all workflow tasks 

8""" 

9 

10__all__ = ["Task", "TaskNode"] 

11 

12import re 

13from itertools import product 

14from pathlib import Path 

15from typing import Annotated, Any, Generic 

16 

17from cappa import Arg 

18from pydantic import BaseModel, ConfigDict, Field 

19 

20from collectra.commons import ( 

21 EntityMixin, 

22 LenientAttributes, 

23 Node, 

24 NodeStatus, 

25 T, 

26 TaskContext, 

27) 

28from collectra.cli import command 

29 

30 

31class Task(LenientAttributes, EntityMixin, BaseModel, Generic[T]): 

32 """Abstract base class for all tasks in Collectra workflows. 

33 

34 Defines the common interface and behavior that all tasks must implement. 

35 

36 Attributes: 

37 name (str): Unique identifier for the task within the workflow. 

38 input (list[str]): List of input parameter names. 

39 output (list[str]): List of output names. 

40 context (TaskContext): Runtime context for task execution. 

41 fusion (bool): Opt-in feature fusion for task types that support it. 

42 """ 

43 

44 model_config = ConfigDict( 

45 extra="allow", 

46 validate_assignment=True, 

47 arbitrary_types_allowed=True, 

48 protected_namespaces=(), 

49 ) 

50 

51 name: str 

52 collective: bool = False 

53 fusion: bool = False 

54 batch_size: int = Field(default=1, ge=1) 

55 # Runtime wiring, set by the pipeline: neither validated, printed nor dumped. 

56 pipeline: Any = Field(default=None, exclude=True, repr=False) 

57 context: TaskContext = Field(default_factory=TaskContext, exclude=True, repr=False) 

58 

59 def __init__(self, name: str, **kwargs) -> None: 

60 super().__init__(name=name, **kwargs) 

61 

62 def attributes_to_ignore(self) -> set: 

63 return super().attributes_to_ignore() | {"pipeline", "context"} 

64 

65 def validate_resources(self, resources: dict[str, Any]) -> None: 

66 """Check that the pipeline resources this task refers to exist. 

67 

68 Called when the pipeline connects. Tasks that name resources override 

69 this to raise a clear error early rather than fail on the first file. 

70 """ 

71 

72 # Tasks are stateful, long-lived objects held by graph nodes: compare by identity. 

73 def __eq__(self, other: object) -> bool: 

74 return self is other 

75 

76 __hash__ = object.__hash__ 

77 

78 @property 

79 def input_dict(self) -> dict[str, list]: 

80 input_dict = dict() 

81 if hasattr(self, "input"): 

82 if not isinstance(self.input, list): 

83 input_list = [self.input] 

84 else: 

85 input_list = self.input.copy() 

86 input_dict = {k: [] for k in input_list} 

87 return input_dict 

88 

89 def prepare_inputs(self, parents: list) -> list: 

90 input_dict = self.input_dict 

91 input_keys = list(input_dict.keys()) 

92 for parent in parents: 

93 if parent.name in input_dict: 

94 input_dict[parent.name].extend(parent.items.values()) 

95 

96 if self.collective: 

97 collective_entries = [ 

98 item for values in input_dict.values() for item in values 

99 ] 

100 return [collective_entries] if collective_entries else [] 

101 

102 # Filter out empty inputs (READY but no items) 

103 non_empty_dict = {k: v for k, v in input_dict.items() if v} 

104 if not non_empty_dict: 

105 return [] 

106 non_empty_keys = list(non_empty_dict.keys()) 

107 value_lists = list(non_empty_dict.values()) 

108 entries = [list(combination) for combination in list(product(*value_lists))] 

109 

110 entries_to_remove = [] 

111 for entry_id, entry in enumerate(entries): 

112 entry_items_by_key = {f"{item.name}": item for item in entry} 

113 is_valid = True 

114 for item in entry: 

115 for parent_id in item.parents: 

116 parent_key = re.sub("-.*", "", parent_id) 

117 if ( 

118 parent_key in non_empty_keys 

119 ): # Only validate against non-empty inputs 

120 if ( 

121 parent_key not in entry_items_by_key 

122 or entry_items_by_key[parent_key].id != parent_id 

123 ): 

124 is_valid = False 

125 break 

126 if not is_valid: 

127 entries_to_remove.append(entry_id) 

128 

129 entries = [ 

130 entry for id, entry in enumerate(entries) if id not in entries_to_remove 

131 ] 

132 return entries 

133 

134 def run(self, *args) -> T | None: 

135 """Run the task execution logic. 

136 

137 This method contains the core task execution logic and must be 

138 implemented by all subclasses. 

139 

140 """ 

141 raise NotImplementedError("Subclasses must implement this method.") 

142 

143 def prefetch(self, entries: list[list]) -> None: 

144 """Optionally compute results for many input entries in one batch. 

145 

146 The pipeline calls this with the entries of several files (each entry is 

147 the list of artefacts a later ``run`` call will receive) when 

148 ``batch_size`` is above 1. Tasks that can batch their work override this 

149 to cache results for ``run`` to reuse; the default does nothing. 

150 """ 

151 

152 def clear_prefetch(self) -> None: 

153 """Discard anything cached by ``prefetch``.""" 

154 

155 def get_output_name(self) -> str: 

156 name = ( 

157 f"{self.get_name()}_output" 

158 if not hasattr(self, "output") 

159 else self.output[0] if isinstance(self.output, list) else self.output 

160 ) 

161 return name 

162 

163 def __call__(self, *args) -> T | None: 

164 """Run the task with the provided arguments. 

165 

166 Args: 

167 **kwargs: Keyword arguments for task execution. 

168 

169 Returns: 

170 

171 """ 

172 return self.run(*args) 

173 

174 @command(name="run") 

175 def cli_run( 

176 self, 

177 inputs: list[str], 

178 output: Path | None = None, 

179 verbose: bool = False, 

180 usage: bool = False, 

181 render: bool = False, 

182 force: Annotated[ 

183 bool, 

184 Arg( 

185 help="Rerun tasks whose outputs already exist, replacing those outputs. By default such tasks are skipped." 

186 ), 

187 ] = False, 

188 batch_size: Annotated[ 

189 int | None, 

190 Arg( 

191 help="Inputs to send to the model at once, for tasks that can batch their work. Omit to keep the task's own setting." 

192 ), 

193 ] = None, 

194 ) -> None: 

195 """Run this task for the supplied input files.""" 

196 if batch_size is not None: 

197 if batch_size < 1: 

198 raise ValueError("--batch-size must be at least 1") 

199 self.batch_size = batch_size 

200 if self.pipeline is None: 

201 raise RuntimeError(f"Task {self.name!r} is not attached to a pipeline") 

202 self.pipeline.cli_run( 

203 inputs, 

204 task=self.name, 

205 output=output, 

206 single=True, 

207 verbose=verbose, 

208 usage=usage, 

209 render=render, 

210 force=force, 

211 ) 

212 

213 

214class TaskNode(Node): 

215 

216 task: Task 

217 

218 def get_task(self) -> Task: 

219 return self.task