DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
perf(session): flush buffered turn events in a single transaction (#678)
rncchendfbe2878a61e
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pyindex 792f3de7f..d0d52b39b 100644--- a/deeptutor/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -703,6 +703,73 @@ class SQLiteSessionStore:async def append_turn_event(self, turn_id: str, event: dict[str, Any]) -> dict[str, Any]:return await self._run(self._append_turn_event_sync, turn_id, event)+ def _append_turn_events_sync(+ self, turn_id: str, events: list[dict[str, Any]]+ ) -> list[dict[str, Any]]:+ # Batch variant of _append_turn_event_sync: one transaction for the whole+ # post-stream flush instead of one fsync'd commit per event. On slow+ # storage (e.g. NAS spinning disks) per-event commits stretch a turn's+ # finalisation to minutes while the client spinner keeps running.+ now = time.time()+ with self._connect() as conn:+ turn = conn.execute(+ "SELECT id, session_id FROM turns WHERE id = ?", (turn_id,)+ ).fetchone()+ if turn is None:+ raise ValueError(f"Turn not found: {turn_id}")+ row = conn.execute(+ "SELECT COALESCE(MAX(seq), 0) AS last_seq FROM turn_events WHERE turn_id = ?",+ (turn_id,),+ ).fetchone()+ next_seq = (int(row["last_seq"]) if row else 0) + 1+ payloads: list[dict[str, Any]] = []+ rows: list[tuple[Any, ...]] = []+ for event in events:+ provided_seq = int(event.get("seq") or 0)+ if provided_seq > 0:+ seq = provided_seq+ next_seq = max(next_seq, provided_seq + 1)+ else:+ seq = next_seq+ next_seq += 1+ payload = dict(event)+ payload["seq"] = seq+ payload["turn_id"] = payload.get("turn_id") or turn_id+ payload["session_id"] = payload.get("session_id") or turn["session_id"]+ payloads.append(payload)+ rows.append(+ (+ turn_id,+ seq,+ payload.get("type", ""),+ payload.get("source", ""),+ payload.get("stage", ""),+ payload.get("content", "") or "",+ _json_dumps(payload.get("metadata", {})),+ float(payload.get("timestamp") or now),+ now,+ )+ )+ conn.executemany(+ """+ INSERT OR REPLACE INTO turn_events (+ turn_id, seq, type, source, stage, content, metadata_json, timestamp, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ rows,+ )+ conn.execute(+ "UPDATE turns SET updated_at = ? WHERE id = ?",+ (now, turn_id),+ )+ conn.commit()+ return payloads++ async def append_turn_events(+ self, turn_id: str, events: list[dict[str, Any]]+ ) -> list[dict[str, Any]]:+ return await self._run(self._append_turn_events_sync, turn_id, events)+def _get_turn_events_sync(self, turn_id: str, after_seq: int = 0) -> list[dict[str, Any]]:with self._connect() as conn:rows = conn.execute(diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 3581eedf1..7e6c478f2 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -1992,20 +1992,46 @@ class TurnRuntimeManager:execution.events_flushed = Trueevents = list(execution.events)- for payload in events:+ # Prefer the store's batch append (single transaction) when available:+ # per-event commits fsync once per event, which on slow storage (NAS+ # spinning disks) stretches this flush — and the visible spinner — to+ # minutes for a long turn.+ append_batch = getattr(self.store, "append_turn_events", None)+ if callable(append_batch):+ try:+ persisted_batch = await append_batch(execution.turn_id, events)+ except ValueError as exc:+ # A turn can disappear when the session is deleted while the+ # turn task is draining post-stream persistence.+ if "Turn not found:" not in str(exc):+ raise+ logger.warning(+ "Skip persisting %d buffered event(s) for missing turn %s",+ len(events),+ execution.turn_id,+ )+ return+ for persisted in persisted_batch:+ self._mirror_event_to_workspace(execution, persisted)+ return++ for index, payload in enumerate(events):try:persisted = await self.store.append_turn_event(execution.turn_id, payload)except ValueError as exc:# A turn can disappear when the session is deleted while the turn task- # is draining post-stream persistence. Avoid cascading failures.+ # is draining post-stream persistence. Avoid cascading failures. The+ # turn will not come back, so drop the whole remaining batch with one+ # summary line instead of logging once per buffered event.if "Turn not found:" not in str(exc):raiselogger.warning(- "Skip persisting event for missing turn %s (%s)",+ "Skip persisting %d buffered event(s) for missing turn %s (first: %s)",+ len(events) - index,execution.turn_id,payload.get("type", ""),)- continue+ breakself._mirror_event_to_workspace(execution, persisted)@staticmethod