"""Durable, isolated conversation checkpoints. No business data synchronization here.""" from __future__ import annotations from contextlib import contextmanager from functools import lru_cache import hashlib from pathlib import Path import sqlite3 from threading import Lock from app.core.config import get_settings _registry_lock = Lock() _locks: dict[str, tuple[Lock, int]] = {} @contextmanager def thread_lock(key): # Reference counts bound the lock registry to currently active/waiting turns. with _registry_lock: lock, count = _locks.get(key, (Lock(), 0)) _locks[key] = (lock, count + 1) try: if not lock.acquire(timeout=2): raise ValueError("同一会话的上一条问题尚未处理完成。") try: yield finally: lock.release() finally: with _registry_lock: _, count = _locks[key] if count == 1: del _locks[key] else: _locks[key] = (lock, count - 1) @lru_cache(maxsize=4) def _backend(url): if url.startswith("sqlite:///"): from langgraph.checkpoint.sqlite import SqliteSaver file = url.removeprefix("sqlite:///") if file != ":memory:": Path(file).resolve().parent.mkdir(parents=True, exist_ok=True) connection = sqlite3.connect(file, check_same_thread=False, timeout=5) saver = SqliteSaver(connection) saver.setup() return saver, connection if url.startswith(("postgresql://", "postgresql+psycopg://")): from langgraph.checkpoint.postgres import PostgresSaver from psycopg.rows import dict_row from psycopg_pool import ConnectionPool pool = ConnectionPool(url.replace("postgresql+psycopg://", "postgresql://", 1), min_size=1, max_size=5, kwargs={"autocommit": True, "row_factory": dict_row, "prepare_threshold": 0}) saver = PostgresSaver(pool) saver.setup() return saver, pool raise ValueError("Unsupported assistant checkpoint database") @contextmanager def planning_session(payload): from app.modules.work_assistant.orchestration import build_planning_graph if not payload.conversation_id or not payload.actor_id or not payload.turn_number: yield build_planning_graph(), None return # actor_id comes from the authenticated Java bridge, never the chat request body. key = hashlib.sha256(("pms:" + payload.actor_id + ":" + payload.conversation_id).encode()).hexdigest() url = get_settings().work_assistant_state_url saver, connection = _backend(url) with thread_lock(key): if hasattr(connection, "connection"): # A dedicated session advisory lock covers workers without a transaction across model calls. # hash fits signed PostgreSQL BIGINT; connection returned only after unlock. lock_id = int(key[:15], 16) import psycopg from psycopg.rows import dict_row with psycopg.connect(url.replace("postgresql+psycopg://", "postgresql://", 1), autocommit=True, row_factory=dict_row) as guard: if not guard.execute("SELECT pg_try_advisory_lock(%s)", (lock_id,)).fetchone()["pg_try_advisory_lock"]: raise ValueError("同一会话正在处理中。") try: yield build_planning_graph(saver), {"configurable": {"thread_id": key}} finally: guard.execute("SELECT pg_advisory_unlock(%s)", (lock_id,)) else: yield build_planning_graph(saver), {"configurable": {"thread_id": key}}