Coverage for dao/ai_conversation_dao.py: 69.07%
77 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""MT AI conversation DAO (SB-1143).
3Unlike most DAOs, these methods raise on failure instead of returning a
4default. A swallowed error here would look like "no conversation" or "no
5history" — and the caller would silently start over, which is exactly the
6absent-vs-empty confusion SB-1142 removed from the tools. The service maps
7exceptions to a controlled error response.
8"""
10from __future__ import annotations
12from datetime import UTC, datetime
13from typing import Any
15import structlog
17from dao.base_dao import BaseDAO
19logger = structlog.get_logger()
21CONVERSATIONS = "ai_conversations"
22MESSAGES = "ai_messages"
23TOOL_CALLS = "ai_tool_calls"
25# Every row in a bulk insert must carry every column. PostgREST inserts the
26# union of the rows' keys and sends NULL — not the column DEFAULT — for a key
27# a row lacks, so a user row without `status` violated NOT NULL (SB-1143,
28# caught against local Supabase).
29MESSAGE_COLUMNS = ("content", "status", "model", "agent_version", "llm_calls", "tool_calls")
31# Read by the admin conversation view (SB-1197). duration_ms / llm_ms only
32# exist once the SB-1197 migration has run; the service falls back without them.
33MESSAGE_DETAIL = (
34 "turn, role, content, status, model, agent_version, llm_calls, tool_calls, duration_ms, llm_ms, created_at"
35)
36TOOL_CALL_COLUMNS = ("turn", "seq", "tool_name", "args", "result", "error_kind", "duration_ms")
37# The "what MT couldn't answer" report (SB-1308) needs the result's verdict only.
38GAP_CALL_COLUMNS = "tool_name, args, error_kind, status:result->>status, created_at"
39GAP_PAGE = 1000
42class AIConversationDAO(BaseDAO):
43 """Conversations and their turns. Every read is scoped to the owner."""
45 def create_conversation(self, user_id: str, agent_version: str) -> dict:
46 response = (
47 self.client.table(CONVERSATIONS).insert({"user_id": user_id, "agent_version": agent_version}).execute()
48 )
49 if not response.data:
50 raise RuntimeError("ai_conversations insert returned no row")
51 return response.data[0]
53 def get_conversation(self, conversation_id: str, user_id: str | None) -> dict | None:
54 """The conversation if it exists and belongs to this user, else None.
56 `user_id=None` means any owner: for admins only, decided by the caller.
57 """
58 query = (
59 self.client.table(CONVERSATIONS)
60 .select("id, user_id, agent_version, created_at, updated_at")
61 .eq("id", conversation_id)
62 )
63 if user_id is not None:
64 query = query.eq("user_id", user_id)
65 response = query.limit(1).execute()
66 return response.data[0] if response.data else None
68 def list_conversations(self, user_id: str | None, limit: int, offset: int) -> list[dict]:
69 """Newest activity first, each with its first question. `user_id=None`: everyone's."""
70 query = self.client.table(CONVERSATIONS).select("id, user_id, agent_version, created_at, updated_at")
71 if user_id is not None:
72 query = query.eq("user_id", user_id)
73 conversations = query.order("updated_at", desc=True).range(offset, offset + limit - 1).execute().data or []
74 if not conversations:
75 return []
76 firsts = (
77 self.client.table(MESSAGES)
78 .select("conversation_id, content")
79 .in_("conversation_id", [c["id"] for c in conversations])
80 .eq("turn", 1)
81 .eq("role", "user")
82 .execute()
83 .data
84 or []
85 )
86 first_by_id = {m["conversation_id"]: m["content"] for m in firsts}
87 return [{**c, "first_question": first_by_id.get(c["id"])} for c in conversations]
89 def list_messages_detail(self, conversation_id: str) -> list[dict]:
90 """Every column the admin view shows, including SB-1197's timings."""
91 response = (
92 self.client.table(MESSAGES)
93 .select(MESSAGE_DETAIL)
94 .eq("conversation_id", conversation_id)
95 .order("turn")
96 .order("role", desc=True)
97 .execute()
98 )
99 return response.data or []
101 def list_tool_calls(self, conversation_id: str) -> list[dict]:
102 response = (
103 self.client.table(TOOL_CALLS)
104 .select(", ".join(TOOL_CALL_COLUMNS))
105 .eq("conversation_id", conversation_id)
106 .order("turn")
107 .order("seq")
108 .execute()
109 )
110 return response.data or []
112 def gap_tool_calls(
113 self, since: str, outcomes: tuple[str, ...], tool: str | None = None, max_rows: int = 5000
114 ) -> list[dict]:
115 """Every owner's tool calls since `since` whose error kind or status is one of
116 `outcomes`, newest first (SB-1308). Admin only: arguments can name minors.
118 Only the result's `status` is read, not the result itself.
119 """
120 wanted = ",".join(outcomes)
121 rows: list[dict] = []
122 while len(rows) < max_rows:
123 query = (
124 self.client.table(TOOL_CALLS)
125 .select(GAP_CALL_COLUMNS)
126 .gte("created_at", since)
127 .or_(f"error_kind.in.({wanted}),result->>status.in.({wanted})")
128 )
129 if tool:
130 query = query.eq("tool_name", tool)
131 page = query.order("created_at", desc=True).range(len(rows), len(rows) + GAP_PAGE - 1).execute().data or []
132 rows.extend(page)
133 if len(page) < GAP_PAGE:
134 break
135 return rows[:max_rows]
137 def count_tool_calls(self, since: str, tool: str | None = None) -> int:
138 """Every owner's tool calls since `since`, any outcome: the gap report's denominator."""
139 query = self.client.table(TOOL_CALLS).select("id", count="exact").gte("created_at", since)
140 if tool:
141 query = query.eq("tool_name", tool)
142 return query.limit(1).execute().count or 0
144 def record_trace(
145 self, conversation_id: str, turn: int, timings: dict[str, int | None], calls: list[dict[str, Any]]
146 ) -> None:
147 """The turn's timings on its assistant row, and its tool calls (SB-1197).
149 Called after `add_turn`, best-effort: the caller logs a failure and
150 moves on, so an environment without the SB-1197 migration still chats.
151 """
152 self.client.table(MESSAGES).update(
153 {"duration_ms": timings.get("duration_ms"), "llm_ms": timings.get("llm_ms")}
154 ).eq("conversation_id", conversation_id).eq("turn", turn).eq("role", "assistant").execute()
155 if calls:
156 rows = [
157 {**{c: call.get(c) for c in TOOL_CALL_COLUMNS}, "conversation_id": conversation_id, "turn": turn}
158 for call in calls
159 ]
160 self.client.table(TOOL_CALLS).insert(rows).execute()
162 def list_messages(self, conversation_id: str) -> list[dict]:
163 response = (
164 self.client.table(MESSAGES)
165 .select("turn, role, content, status")
166 .eq("conversation_id", conversation_id)
167 .order("turn")
168 .order("role", desc=True) # 'user' before 'assistant' within a turn
169 .execute()
170 )
171 return response.data or []
173 def add_turn(
174 self, conversation_id: str, turn: int, user_row: dict[str, Any], assistant_row: dict[str, Any]
175 ) -> None:
176 """Write both halves of a turn in one request, so a turn is never half-saved."""
177 user = {"status": "ok", **user_row}
178 rows = [
179 {**_message_row(user), "conversation_id": conversation_id, "turn": turn, "role": "user"},
180 {**_message_row(assistant_row), "conversation_id": conversation_id, "turn": turn, "role": "assistant"},
181 ]
182 self.client.table(MESSAGES).insert(rows).execute()
183 self.client.table(CONVERSATIONS).update({"updated_at": datetime.now(UTC).isoformat()}).eq(
184 "id", conversation_id
185 ).execute()
188def _message_row(values: dict[str, Any]) -> dict[str, Any]:
189 unknown = set(values) - set(MESSAGE_COLUMNS)
190 if unknown:
191 raise ValueError(f"unknown ai_messages columns: {sorted(unknown)}")
192 return {column: values.get(column) for column in MESSAGE_COLUMNS}