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
« 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
6from pydantic import BaseModel, ConfigDict
8from ..usage import UsageLedger
10__all__ = [
11 "T",
12 "EntityMixin",
13 "PositionalFields",
14 "LenientAttributes",
15 "BaseEntity",
16 "Node",
17 "NodeStatus",
18 "TaskContext",
19]
21T = TypeVar("T")
24class TaskContext(BaseModel):
25 """Runtime context for task execution.
27 This provides tasks with runtime information without polluting
28 their function signatures or requiring global state.
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 """
38 model_config = ConfigDict(arbitrary_types_allowed=True)
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
47class EntityMixin:
48 """Naming and serialisation shared by artefacts and pydantic task models."""
50 def __str__(self) -> str:
51 return f"{self.name}\n{self.get_class_path()}"
53 def get_name(self) -> str:
54 """Get the name of the task.
56 Returns:
57 str: The name of the task.
58 """
59 return self.name
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
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}
77 def attributes_to_ignore(self) -> set:
78 return set()
80 @classmethod
81 def get_class_path(cls: type) -> str:
82 """Return the fully qualified path for a class.
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__}"
92class LenientAttributes:
93 """Keeps pydantic models usable like plain Python objects when assigning.
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 """
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)
118class PositionalFields:
119 """Lets a model's fields be given positionally, in declaration order.
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 """
125 _runtime_fields: ClassVar[frozenset[str]] = frozenset()
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)
149class BaseEntity(EntityMixin, ABC, Generic[T]):
151 def __init__(self, name: str) -> None:
152 self.name = name
154 @abstractmethod
155 def __call__(self) -> T:
156 pass
159class NodeStatus(enum.Enum):
160 NOT_READY = "not_ready"
161 READY = "ready"
162 RUNNING = "running"
163 COMPLETED = "completed"
164 FAILED = "failed"
166 def __str__(self) -> str:
167 return self.value
170class Node(PositionalFields, BaseModel):
171 """A node of the workflow graph."""
173 model_config = ConfigDict(
174 validate_assignment=True, arbitrary_types_allowed=True, extra="forbid"
175 )
176 _runtime_fields: ClassVar[frozenset[str]] = frozenset({"status"})
178 name: str
179 status: NodeStatus = NodeStatus.NOT_READY
181 def process(self) -> list:
182 return []