Skip to content

Commit a3214a8

Browse files
committed
refactor: reduce cognitive complexity of _load_status_data
Code quality improvement: - Extract datetime parsing logic into _parse_datetime_field() helper - Extract datetime restoration logic into _restore_datetime_fields() helper - Use early return for file not found case to reduce nesting - Flatten control flow and remove deeply nested try-except blocks Benefits: - Reduced cognitive complexity from 26 to ~9-10 (below 15 threshold) - Improved readability and maintainability - Easier to test individual datetime parsing methods - Better separation of concerns All functionality preserved.
1 parent f8ed85d commit a3214a8

1 file changed

Lines changed: 50 additions & 37 deletions

File tree

src/api/agents/document/action_tools.py

Lines changed: 50 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -155,46 +155,59 @@ async def initialize(self):
155155
logger.error(f"Failed to initialize Document Action Tools: {_sanitize_log_data(str(e))}")
156156
raise
157157

158+
def _parse_datetime_field(self, value: Any, field_name: str, doc_id: str) -> Optional[datetime]:
159+
"""Parse a datetime string field, returning None if invalid."""
160+
if not isinstance(value, str):
161+
return None
162+
163+
try:
164+
return datetime.fromisoformat(value)
165+
except ValueError:
166+
logger.warning(
167+
f"Invalid datetime format for {field_name} in {_sanitize_log_data(doc_id)}"
168+
)
169+
return None
170+
171+
def _restore_datetime_fields(self, status_info: Dict[str, Any], doc_id: str) -> None:
172+
"""Restore datetime fields from ISO format strings in status_info."""
173+
# Restore upload_time
174+
if "upload_time" in status_info:
175+
parsed_time = self._parse_datetime_field(
176+
status_info["upload_time"], "upload_time", doc_id
177+
)
178+
if parsed_time is not None:
179+
status_info["upload_time"] = parsed_time
180+
181+
# Restore started_at for each stage
182+
for stage in status_info.get("stages", []):
183+
if "started_at" in stage:
184+
parsed_time = self._parse_datetime_field(
185+
stage["started_at"], "started_at", doc_id
186+
)
187+
if parsed_time is not None:
188+
stage["started_at"] = parsed_time
189+
158190
def _load_status_data(self):
159191
"""Load document status data from persistent storage."""
192+
if not self.status_file.exists():
193+
logger.info(
194+
"No persistent status file found, starting with empty status tracking"
195+
)
196+
self.document_statuses = {}
197+
return
198+
160199
try:
161-
if self.status_file.exists():
162-
with open(self.status_file, "r") as f:
163-
data = json.load(f)
164-
# Convert datetime strings back to datetime objects
165-
for doc_id, status_info in data.items():
166-
if "upload_time" in status_info and isinstance(
167-
status_info["upload_time"], str
168-
):
169-
try:
170-
status_info["upload_time"] = datetime.fromisoformat(
171-
status_info["upload_time"]
172-
)
173-
except ValueError:
174-
logger.warning(
175-
f"Invalid datetime format for upload_time in "
176-
f"{doc_id}"
177-
)
178-
for stage in status_info.get("stages", []):
179-
if stage.get("started_at") and isinstance(
180-
stage["started_at"], str
181-
):
182-
try:
183-
stage["started_at"] = datetime.fromisoformat(
184-
stage["started_at"]
185-
)
186-
except ValueError:
187-
logger.warning(
188-
f"Invalid datetime format for started_at in {doc_id}"
189-
)
190-
self.document_statuses = data
191-
logger.info(
192-
f"Loaded {len(self.document_statuses)} document statuses from persistent storage"
193-
)
194-
else:
195-
logger.info(
196-
"No persistent status file found, starting with empty status tracking"
197-
)
200+
with open(self.status_file, "r") as f:
201+
data = json.load(f)
202+
203+
# Convert datetime strings back to datetime objects
204+
for doc_id, status_info in data.items():
205+
self._restore_datetime_fields(status_info, doc_id)
206+
207+
self.document_statuses = data
208+
logger.info(
209+
f"Loaded {len(self.document_statuses)} document statuses from persistent storage"
210+
)
198211
except Exception as e:
199212
logger.error(f"Failed to load status data: {_sanitize_log_data(str(e))}")
200213
self.document_statuses = {}

0 commit comments

Comments
 (0)