Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 44 additions & 6 deletions src/tabpfn_common_utils/telemetry/core/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from datetime import datetime, timezone
from pathlib import Path
from platformdirs import user_config_dir
from typing import Any
from typing import Any, Optional


# Check if filelock is available
Expand Down Expand Up @@ -44,6 +44,21 @@
}


def _safe_state_path() -> Optional[Path]:
"""Get the path to the state file safely.

If an exception is raised in the underlying _state_path() function,
return None.

Returns:
Optional[Path]: The path to the state file or None.
"""
try:
return _state_path()
except Exception:
return None


def _state_path() -> Path:
"""Get the path to the state file.

Expand Down Expand Up @@ -97,7 +112,7 @@ def _write_with_filelock(path: Path, data: dict[str, Any]) -> None:
lock = filelock.FileLock(lock_path, timeout=10)

with lock:
_write_data_to_file(path, data)
_safe_write_data_to_file(path, data)


def _write_without_lock(path: Path, data: dict[str, Any]) -> None:
Expand All @@ -107,7 +122,20 @@ def _write_without_lock(path: Path, data: dict[str, Any]) -> None:
path: The path to the state file.
data: The data to write to the state file.
"""
_write_data_to_file(path, data)
_safe_write_data_to_file(path, data)


def _safe_write_data_to_file(path: Path, data: dict[str, Any]) -> None:
"""Write data to file atomically safely.

Args:
path: The path to the state file.
data: The data to write to the state file.
"""
try:
_write_data_to_file(path, data)
except Exception:
pass


def _write_data_to_file(path: Path, data: dict[str, Any]) -> None:
Expand Down Expand Up @@ -236,7 +264,10 @@ def load_state() -> dict[str, Any]:
Returns:
The telemetry state (schema-normalized).
"""
path = _state_path()
path = _safe_state_path()
if path is None:
return _normalize({})

raw = _read(path)
return _normalize(raw)

Expand All @@ -251,8 +282,15 @@ def save_state(state: dict[str, Any]) -> None:
if not normalized.get("created_at"):
normalized["created_at"] = datetime.now(timezone.utc).isoformat()

path = _state_path()
_write_with_lock(path, normalized)
path = _safe_state_path()
if path is None:
return

try:
# Safely write, silently ignore any errors
_write_with_lock(path, normalized)
except Exception:
pass


def get_property(key: str, default: Any = None, data_type: type | None = None) -> Any:
Expand Down