Reviewer · Null Handling
Guard nullable attribute access
Several defects came from treating optional values as if they were always present. Follow these rules whenever a value can legitimately be `None`: 1. Annotate it honestly. If a parameter's default is `None`, its type must be `Optional[T]` (e.g. `metadata: Optional[Dict[str, Any]] = None`), not `T = None`. A wrong annotation hides the nullability from type...
Several defects came from treating optional values as if they were always present. Follow these rules whenever a value can legitimately be None:
-
Annotate it honestly. If a parameter’s default is
None, its type must beOptional[T](e.g.metadata: Optional[Dict[str, Any]] = None), notT = None. A wrong annotation hides the nullability from type checkers and from readers. - Bind-then-check instead of re-accessing
self.xor chained attributes repeatedly. Type narrowing from anif obj.attr:check does not survive across calls or threads, and a value can change between two reads. Capture it in a local first:path = self.memory_md_path if path and os.path.exists(path): size = os.path.getsize(path) - Never dereference a possibly-absent attribute or nested object unconditionally. Use
getattr(obj, "attr", default)(or an explicitis Noneguard) so a missing/None attribute degrades gracefully instead of raising: ```python isinstance(getattr(self.director, “llm”, None), LiteLLM)
sum_agent_usage([ getattr(self.knowledge_generator, “agent”, None), getattr(self.reasoner, “agent”, None), ])
4. Before using a nullable value in an operation (arithmetic, string formatting, dict keys), validate its type/truthiness rather than assuming the happy path:
```python
value = usage.get(key, 0)
if isinstance(value, (int, float)):
total[key] += value
role = agent.agent_name or "Worker"
Applying these checks consistently prevents AttributeError/TypeError crashes in code paths that run inside finally blocks, validation loops, or state-restore logic, where a silent failure or exception is especially costly.