hermes_state_sessions_model_config.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """Conversation-wide ``sessions.model_config`` keys: read-modify-write at the compression tip and the
  2. key scan. Bodies of :class:`hermes_state_sessions.SessionSessionsMixin`'s two methods of the same names."""
  3. from __future__ import annotations
  4. import json
  5. from typing import Any, Callable, Optional
  6. from hermes_state_common import _sql_json_extract
  7. def update_conversation_model_config_value(db, session_id: str, key: str,
  8. update: Callable[[Any], Any]) -> Optional[str]:
  9. """Read a conversation-wide ``key`` at *session_id*'s compression tip and write ``update(value)``
  10. back, in one write transaction: a concurrent writer of the key cannot be overwritten with a stale
  11. copy, and a rotation cannot publish between finding the tip and writing it (the child would keep
  12. the old copy). ``update`` may run more than once (lock retry) and must be pure; returning None
  13. removes the key. Returns the id written, None when the row does not exist."""
  14. from hermes_state_sessions import _parse_model_config
  15. def _do(conn) -> Optional[str]:
  16. tip = db._compression_tip_on(conn, session_id)
  17. row = conn.execute("SELECT model_config FROM sessions WHERE id = ?", (tip,)).fetchone()
  18. if row is None:
  19. return None
  20. config = _parse_model_config(row[0])
  21. if (value := update(config.get(key))) is None:
  22. config.pop(key, None)
  23. else:
  24. config[key] = value
  25. conn.execute("UPDATE sessions SET model_config = ? WHERE id = ?", (json.dumps(config), tip))
  26. return tip
  27. return db._execute_write(_do)
  28. def session_ids_with_model_config_key(db, key: str) -> list[str]:
  29. """Ids of the sessions whose model_config carries ``key``, newest first."""
  30. with db._read_ctx() as conn:
  31. rows = conn.execute(
  32. f"SELECT id FROM sessions WHERE {_sql_json_extract('model_config', '$.' + key)} IS NOT NULL "
  33. "ORDER BY started_at DESC").fetchall()
  34. return [row["id"] for row in rows]