fix: stop masking runtime failures
This commit is contained in:
1 parent
afc65c086e
commit
dfc3919b52
22 files changed
+446
-300
No files matched your search
+28
-31
@@ -16,6 +16,10 @@ from loguru import logger
|
||||
_WORKING_TREE_DIFF_MAX_CHARS = 6000
|
||||
|
||||
|
||||
class GitStoreError(RuntimeError):
|
||||
"""Raised when the memory Git repository cannot complete an operation."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class CommitInfo:
|
||||
sha: str # Short SHA (8 chars)
|
||||
@@ -125,9 +129,8 @@ class GitStore:
|
||||
)
|
||||
logger.info("Git store initialized at {}", self._workspace)
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception("Git store init failed for {}", self._workspace)
|
||||
return False
|
||||
except Exception as exc:
|
||||
raise GitStoreError(f"Git store init failed for {self._workspace}") from exc
|
||||
|
||||
# -- daily operations ------------------------------------------------------
|
||||
|
||||
@@ -161,9 +164,8 @@ class GitStore:
|
||||
sha = sha_bytes.hex()[:8]
|
||||
logger.debug("Git auto-commit: {} ({})", sha, message)
|
||||
return sha
|
||||
except Exception:
|
||||
logger.exception("Git auto-commit failed: {}", message)
|
||||
return None
|
||||
except Exception as exc:
|
||||
raise GitStoreError(f"Git auto-commit failed: {message}") from exc
|
||||
|
||||
# -- internal helpers ------------------------------------------------------
|
||||
|
||||
@@ -190,8 +192,8 @@ class GitStore:
|
||||
break
|
||||
sha = commit.parents[0] if commit.parents else None
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
except Exception as exc:
|
||||
raise GitStoreError(f"Git SHA resolution failed: {short_sha}") from exc
|
||||
|
||||
def _is_inside_git_repo(self) -> bool:
|
||||
"""Check if self._workspace is already inside a git repository.
|
||||
@@ -268,16 +270,15 @@ class GitStore:
|
||||
sha = commit.parents[0] if commit.parents else None
|
||||
|
||||
return entries
|
||||
except Exception:
|
||||
logger.exception("Git log failed")
|
||||
return []
|
||||
except Exception as exc:
|
||||
raise GitStoreError("Git log failed") from exc
|
||||
|
||||
def line_ages(self, file_path: str) -> list[LineAge]:
|
||||
"""Compute the age of each line in a tracked file via git blame.
|
||||
|
||||
Returns one LineAge per line, in order.
|
||||
Returns an empty list if the repo is not initialized, the file is
|
||||
empty, or annotation fails.
|
||||
Returns an empty list if the repo is not initialized or the file is
|
||||
empty. Annotation failures raise :class:`GitStoreError`.
|
||||
"""
|
||||
|
||||
if not self.is_initialized():
|
||||
@@ -291,9 +292,8 @@ class GitStore:
|
||||
from dulwich import porcelain
|
||||
|
||||
annotated = porcelain.annotate(str(self._workspace), file_path)
|
||||
except Exception:
|
||||
logger.exception("Git line_ages annotate failed for {}", file_path)
|
||||
return []
|
||||
except Exception as exc:
|
||||
raise GitStoreError(f"Git line annotation failed for {file_path}") from exc
|
||||
|
||||
if not annotated:
|
||||
return []
|
||||
@@ -321,9 +321,8 @@ class GitStore:
|
||||
outstream=out,
|
||||
)
|
||||
return out.getvalue().decode("utf-8", errors="replace")
|
||||
except Exception:
|
||||
logger.exception("Git diff_commits failed")
|
||||
return ""
|
||||
except Exception as exc:
|
||||
raise GitStoreError(f"Git diff failed for {sha1}..{sha2}") from exc
|
||||
|
||||
def summarize_working_tree(self, paths: list[str]) -> str:
|
||||
"""Structured summary of working-tree changes vs HEAD for *paths*.
|
||||
@@ -354,8 +353,8 @@ class GitStore:
|
||||
import difflib
|
||||
|
||||
from dulwich.repo import Repo
|
||||
except ImportError:
|
||||
return ""
|
||||
except ImportError as exc:
|
||||
raise GitStoreError("Git working-tree summary dependencies are unavailable") from exc
|
||||
|
||||
summary_lines: list[str] = []
|
||||
diff_lines: list[str] = []
|
||||
@@ -409,9 +408,8 @@ class GitStore:
|
||||
total_removed += removed
|
||||
summary_lines.append(f"{path}: +{added} -{removed}")
|
||||
diff_lines.extend(hunks)
|
||||
except Exception:
|
||||
logger.exception("Git summarize_working_tree failed")
|
||||
return ""
|
||||
except Exception as exc:
|
||||
raise GitStoreError("Git working-tree summary failed") from exc
|
||||
|
||||
if changed == 0:
|
||||
return ""
|
||||
@@ -471,9 +469,8 @@ class GitStore:
|
||||
diff = self.diff_commits(parent.hex()[:8], c.sha) if parent else ""
|
||||
return c, diff
|
||||
return None
|
||||
except Exception:
|
||||
logger.exception("Git show_commit_diff failed")
|
||||
return None
|
||||
except Exception as exc:
|
||||
raise GitStoreError(f"Git commit display failed for {short_sha}") from exc
|
||||
|
||||
# -- restore ---------------------------------------------------------------
|
||||
|
||||
@@ -485,7 +482,8 @@ class GitStore:
|
||||
is provided, commits outside that history are rejected before any files
|
||||
are changed.
|
||||
|
||||
Returns the new commit SHA, or None on failure.
|
||||
Returns the new commit SHA, or ``None`` when the commit cannot be reverted.
|
||||
Repository and filesystem failures raise :class:`GitStoreError`.
|
||||
"""
|
||||
if not self.is_initialized():
|
||||
return None
|
||||
@@ -534,9 +532,8 @@ class GitStore:
|
||||
# Commit the restored state
|
||||
msg = f"revert: undo {commit}"
|
||||
return self.auto_commit(msg)
|
||||
except Exception:
|
||||
logger.exception("Git revert failed for {}", commit)
|
||||
return None
|
||||
except Exception as exc:
|
||||
raise GitStoreError(f"Git revert failed for {commit}") from exc
|
||||
|
||||
@staticmethod
|
||||
def _read_blob_from_tree(repo, tree, filepath: str) -> str | None:
|
||||
|
||||
+72
-49
@@ -278,11 +278,7 @@ def current_time_str(timezone: str | None = None) -> str:
|
||||
"""Return the current time string."""
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
try:
|
||||
tz = ZoneInfo(timezone) if timezone else None
|
||||
except (KeyError, Exception):
|
||||
tz = None
|
||||
|
||||
tz = ZoneInfo(timezone) if timezone else None
|
||||
now = datetime.now(tz=tz) if tz else datetime.now().astimezone()
|
||||
offset = now.strftime("%z")
|
||||
offset_fmt = f"{offset[:3]}:{offset[3:]}" if len(offset) == 5 else offset
|
||||
@@ -320,8 +316,7 @@ def truncate_text_to_tokens(text: str, max_tokens: int) -> str:
|
||||
|
||||
Unlike :func:`truncate_text`, this measures actual tokens, so the cap holds
|
||||
regardless of language or content (CJK and code cost more tokens per char).
|
||||
Falls back to a char-based estimate (~4 chars/token) if tiktoken is
|
||||
unavailable.
|
||||
Falls back to a conservative UTF-8 byte budget if tiktoken is unavailable.
|
||||
"""
|
||||
if max_tokens <= 0:
|
||||
return text
|
||||
@@ -340,11 +335,23 @@ def truncate_text_to_tokens(text: str, max_tokens: int) -> str:
|
||||
return result
|
||||
return enc.decode(tokens[:max_tokens])
|
||||
except Exception:
|
||||
max_chars = max_tokens * 4
|
||||
suffix_chars = len(_TRUNCATED_SUFFIX)
|
||||
if max_chars <= suffix_chars:
|
||||
return text[:max_chars]
|
||||
return truncate_text(text, max_chars - suffix_chars)
|
||||
if len(text.encode("utf-8")) <= max_tokens:
|
||||
return text
|
||||
suffix_bytes = len(_TRUNCATED_SUFFIX.encode("utf-8"))
|
||||
if max_tokens <= suffix_bytes:
|
||||
return _truncate_text_to_utf8_bytes(text, max_tokens)
|
||||
body = _truncate_text_to_utf8_bytes(text, max_tokens - suffix_bytes)
|
||||
return body + _TRUNCATED_SUFFIX
|
||||
|
||||
|
||||
def _truncate_text_to_utf8_bytes(text: str, max_bytes: int) -> str:
|
||||
"""Return the longest code-point prefix within a UTF-8 byte budget."""
|
||||
if max_bytes <= 0:
|
||||
return ""
|
||||
encoded = text.encode("utf-8")
|
||||
if len(encoded) <= max_bytes:
|
||||
return text
|
||||
return encoded[:max_bytes].decode("utf-8", errors="ignore")
|
||||
|
||||
|
||||
def recent_message_start_index(
|
||||
@@ -569,51 +576,67 @@ def build_assistant_message(
|
||||
return msg
|
||||
|
||||
|
||||
def estimate_prompt_tokens(
|
||||
def _estimate_prompt_tokens_with_source(
|
||||
messages: list[dict[str, Any]],
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> int:
|
||||
"""Estimate prompt tokens with tiktoken.
|
||||
) -> tuple[int, str]:
|
||||
"""Estimate prompt tokens and identify the counter used.
|
||||
|
||||
Counts all fields that providers send to the LLM: content, tool_calls,
|
||||
reasoning_content, tool_call_id, name, plus per-message framing overhead.
|
||||
"""
|
||||
parts: list[str] = []
|
||||
for msg in messages:
|
||||
content = msg.get("content")
|
||||
if isinstance(content, str):
|
||||
parts.append(content)
|
||||
elif isinstance(content, list):
|
||||
for part in content:
|
||||
if isinstance(part, dict) and part.get("type") == "text":
|
||||
txt = part.get("text", "")
|
||||
if txt:
|
||||
parts.append(txt)
|
||||
|
||||
tc = msg.get("tool_calls")
|
||||
if tc:
|
||||
parts.append(json.dumps(tc, ensure_ascii=False))
|
||||
|
||||
rc = msg.get("reasoning_content")
|
||||
if isinstance(rc, str) and rc:
|
||||
parts.append(rc)
|
||||
|
||||
for key in ("name", "tool_call_id"):
|
||||
value = msg.get(key)
|
||||
if isinstance(value, str) and value:
|
||||
parts.append(value)
|
||||
|
||||
message_payload = "\n".join(parts)
|
||||
per_message_overhead = len(messages) * 4
|
||||
try:
|
||||
enc = _get_token_encoding()
|
||||
parts: list[str] = []
|
||||
for msg in messages:
|
||||
content = msg.get("content")
|
||||
if isinstance(content, str):
|
||||
parts.append(content)
|
||||
elif isinstance(content, list):
|
||||
for part in content:
|
||||
if isinstance(part, dict) and part.get("type") == "text":
|
||||
txt = part.get("text", "")
|
||||
if txt:
|
||||
parts.append(txt)
|
||||
|
||||
tc = msg.get("tool_calls")
|
||||
if tc:
|
||||
parts.append(json.dumps(tc, ensure_ascii=False))
|
||||
|
||||
rc = msg.get("reasoning_content")
|
||||
if isinstance(rc, str) and rc:
|
||||
parts.append(rc)
|
||||
|
||||
for key in ("name", "tool_call_id"):
|
||||
value = msg.get(key)
|
||||
if isinstance(value, str) and value:
|
||||
parts.append(value)
|
||||
|
||||
tool_tokens = (
|
||||
_estimate_tools_tokens(enc, tools, leading_separator=bool(parts)) if tools else 0
|
||||
)
|
||||
|
||||
per_message_overhead = len(messages) * 4
|
||||
message_tokens = len(enc.encode("\n".join(parts))) if parts else 0
|
||||
return message_tokens + tool_tokens + per_message_overhead
|
||||
message_tokens = len(enc.encode(message_payload)) if message_payload else 0
|
||||
return message_tokens + tool_tokens + per_message_overhead, "tiktoken"
|
||||
except Exception:
|
||||
return 0
|
||||
tool_payload = (
|
||||
("\n" if message_payload else "") + json.dumps(tools, ensure_ascii=False)
|
||||
if tools
|
||||
else ""
|
||||
)
|
||||
payload = message_payload + tool_payload
|
||||
estimated = len(payload.encode("utf-8"))
|
||||
return estimated + per_message_overhead, "heuristic"
|
||||
|
||||
|
||||
def estimate_prompt_tokens(
|
||||
messages: list[dict[str, Any]],
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> int:
|
||||
"""Estimate prompt tokens with tiktoken and a conservative byte fallback."""
|
||||
estimated, _ = _estimate_prompt_tokens_with_source(messages, tools)
|
||||
return estimated
|
||||
|
||||
|
||||
def estimate_message_tokens(message: dict[str, Any]) -> int:
|
||||
@@ -651,7 +674,7 @@ def estimate_message_tokens(message: dict[str, Any]) -> int:
|
||||
enc = _get_token_encoding()
|
||||
return max(4, len(enc.encode(payload)) + 4)
|
||||
except Exception:
|
||||
return max(4, len(payload) // 4 + 4)
|
||||
return max(4, len(payload.encode("utf-8")) + 4)
|
||||
|
||||
|
||||
def estimate_prompt_tokens_chain(
|
||||
@@ -660,16 +683,16 @@ def estimate_prompt_tokens_chain(
|
||||
messages: list[dict[str, Any]],
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> tuple[int, str]:
|
||||
"""Estimate prompt tokens via provider counter first, then tiktoken fallback."""
|
||||
"""Estimate prompt tokens via provider, tiktoken, then a byte heuristic."""
|
||||
provider_counter = getattr(provider, "estimate_prompt_tokens", None)
|
||||
if callable(provider_counter):
|
||||
with suppress(Exception):
|
||||
tokens, source = provider_counter(messages, tools, model)
|
||||
if isinstance(tokens, (int, float)) and tokens > 0:
|
||||
return int(tokens), str(source or "provider_counter")
|
||||
estimated = estimate_prompt_tokens(messages, tools)
|
||||
estimated, source = _estimate_prompt_tokens_with_source(messages, tools)
|
||||
if estimated > 0:
|
||||
return int(estimated), "tiktoken"
|
||||
return int(estimated), source
|
||||
return 0, "none"
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user