sqlite_runtime.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. """Import-safe helpers for inspecting a Python interpreter's linked SQLite.
  2. This module intentionally depends only on the standard library. Installer and update code must be
  3. able to use it before Hermes' third-party dependencies are healthy.
  4. """
  5. from __future__ import annotations
  6. import json
  7. import os
  8. import subprocess
  9. from dataclasses import dataclass
  10. from pathlib import Path
  11. from typing import Iterable
  12. def _version_tuple(parts: Iterable[object]) -> tuple[int, int, int]:
  13. values = [int(part) for part in parts]
  14. values.extend([0] * (3 - len(values)))
  15. return tuple(values[:3])
  16. def is_sqlite_wal_reset_vulnerable(version_info: tuple[int, ...]) -> bool:
  17. """Return whether *version_info* contains SQLite's WAL-reset bug."""
  18. info = _version_tuple(version_info)
  19. return not (
  20. info < (3, 7, 0)
  21. or info >= (3, 51, 3)
  22. or (3, 50, 7) <= info < (3, 51, 0)
  23. or (3, 44, 6) <= info < (3, 45, 0))
  24. @dataclass(frozen=True)
  25. class SQLiteRuntimeInfo:
  26. """SQLite details reported by one exact Python executable."""
  27. executable: Path
  28. base_prefix: Path
  29. python_version: tuple[int, int, int]
  30. sqlite_version: tuple[int, int, int]
  31. sqlite_version_string: str
  32. sqlite_source_id: str
  33. @property
  34. def wal_reset_vulnerable(self) -> bool:
  35. return is_sqlite_wal_reset_vulnerable(self.sqlite_version)
  36. _PROBE_SCRIPT = """
  37. import json, sqlite3, sys
  38. conn = sqlite3.connect(":memory:")
  39. try:
  40. row = conn.execute("SELECT sqlite_source_id()").fetchone()
  41. finally:
  42. conn.close()
  43. print(json.dumps({
  44. "base_prefix": sys.base_prefix, "executable": sys.executable,
  45. "python_version": list(sys.version_info[:3]), "sqlite_version": list(sqlite3.sqlite_version_info),
  46. "sqlite_version_string": sqlite3.sqlite_version,
  47. "sqlite_source_id": str(row[0]) if row and row[0] is not None else "",
  48. }))
  49. """
  50. def isolated_interpreter_env() -> dict[str, str]:
  51. """Copy of ``os.environ`` with conda/uv/venv/PYTHON* overrides stripped, so a child interpreter
  52. reports its *own* runtime rather than the caller's."""
  53. env = dict(os.environ)
  54. for key in ("CONDA_DEFAULT_ENV", "CONDA_PREFIX", "PYTHONHOME", "PYTHONPATH", "UV_PROJECT_ENVIRONMENT",
  55. "UV_PYTHON", "VIRTUAL_ENV"):
  56. env.pop(key, None)
  57. return env
  58. def probe_sqlite_runtime(python: str | Path, *, timeout: float = 30.0) -> SQLiteRuntimeInfo | None:
  59. """Probe SQLite in *python*, never the caller's linked SQLite."""
  60. try:
  61. result = subprocess.run(
  62. [str(python), "-I", "-c", _PROBE_SCRIPT], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout,
  63. check=False, env=isolated_interpreter_env())
  64. except (OSError, subprocess.TimeoutExpired):
  65. return None
  66. if result.returncode != 0:
  67. return None
  68. try:
  69. payload = json.loads(result.stdout)
  70. return SQLiteRuntimeInfo(
  71. executable=Path(str(payload["executable"])), base_prefix=Path(str(payload["base_prefix"])),
  72. python_version=_version_tuple(payload["python_version"]),
  73. sqlite_version=_version_tuple(payload["sqlite_version"]),
  74. sqlite_version_string=str(payload["sqlite_version_string"]),
  75. sqlite_source_id=str(payload.get("sqlite_source_id", "")))
  76. except (KeyError, TypeError, ValueError, json.JSONDecodeError):
  77. return None