mirror of
https://github.com/tiennm99/DocsGPT.git
synced 2026-10-04 16:13:23 +00:00
* feat: SSE notification system
Adds a per-user SSE pipe (GET /api/events) plus a per-message
chat-stream reconnect endpoint (GET /api/messages/<id>/events).
Backend substrate:
- application/events/ — durable journal (Redis Streams) + live
pub/sub for user-scoped events, with publish_user_event() as
the worker-side entrypoint.
- application/streaming/ — broadcast_channel for pub/sub fanout
and event_replay for the per-message snapshot+tail path.
- application/storage/db/repositories/message_events.py +
alembic 0007 — Postgres journal for chat-stream events.
- application/worker.py — ingest/reingest/remote/connector/
attachment/mcp_oauth tasks publish queued/progress/completed/
failed envelopes alongside their existing status updates.
Frontend client:
- frontend/src/events/ — connect/reconnect, Last-Event-ID cursor,
backoff with jitter. Each tab runs its own connection; no
cross-tab dedup (future work).
- frontend/src/notifications/ — recentEvents ring, cursor
tracking, tool-approval toast.
- frontend/src/upload/uploadSlice.ts — extraReducers for
source.ingest.* and attachment.* events.
Coverage: 132 SSE tests across events substrate, replay, journal,
routes, and worker publishes.
* refactor(attachments): remove polling, SSE-only
frontend/src/components/MessageInput.tsx no longer runs a 2s
setInterval against getTaskStatus for every processing
attachment. The attachment.* SSE reducers in uploadSlice.ts are
now the sole driver of attachment state transitions.
* feat(connector): consume source.ingest.* SSE, remove polling
frontend/src/components/ConnectorTree.tsx now mirrors FileTree's
slice-walking pattern: it watches notifications.recentEvents
for source.ingest.{completed,failed} envelopes matching the
sync's source id, and no longer polls /task_status every 2s.
* refactor(source-ingest): remove polling, SSE-only
frontend/src/upload/Upload.tsx and
frontend/src/components/FileTree.tsx no longer run getTaskStatus
polling fallbacks. The source.ingest.* SSE reducers in
uploadSlice.ts and FileTree's slice walk are now the sole
drivers of upload/reingest state transitions.
* refactor(mcp-oauth): carry authorization_url in SSE, remove polling
application/worker.py::mcp_oauth now publishes
authorization_url on the mcp.oauth.awaiting_redirect envelope.
frontend/src/modals/MCPServerModal.tsx consumes it from SSE
instead of polling /oauth_status/<task_id> every 1s.
The URL is generated inside DocsGPTOAuth.redirect_handler when
the FastMCP client triggers OAuth. The worker now plumbs a
publish callback through tool_config -> MCPTool -> DocsGPTOAuth
so the awaiting_redirect publish fires from inside the handler
at the exact point the URL becomes known. The legacy Redis
mcp_oauth_status setex writes and the GET
/api/mcp_server/oauth_status/<task_id> endpoint are kept as
belt-and-suspenders; nothing in the frontend reads them now.
* feat(source-ingest): plumb limited flag through SSE for token-cap UX
application/worker.py::ingest_worker and remote_worker now publish
``limited: bool`` on the source.ingest.completed envelope.
uploadSlice routes ``payload.limited === true`` to a failed status
with a ``tokenLimitReached`` flag, and UploadToast surfaces the
translated tokenLimit i18n string. No worker code path sets
limited=true today; this is a forward-looking contract so when
token-cap detection lands, the UX is already wired.
* refactor(mcp-oauth): read status from SSE journal, drop polling endpoint
MCPOAuthManager.get_oauth_status now walks the per-user SSE Streams
journal (user:{user_id}:stream) for the latest mcp.oauth.* envelope
matching the task id, returning the status string derived from the
event type suffix and the payload fields. The worker is the single
source of truth — its publish_user_event calls write the same
record the SSE client receives live.
Removed:
- /api/mcp_server/oauth_status/<task_id> route in
application/api/user/tools/mcp.py
- mcp_oauth_status worker function and mcp_oauth_status_task Celery
wrapper
- All mcp_oauth_status:{task_id} Redis setex writes (4 in mcp_oauth,
2 in DocsGPTOAuth.redirect_handler / callback_handler)
- The update_status closure in mcp_oauth that wrote the polling
payload
Tests updated:
- get_oauth_status now takes (task_id, user_id); new coverage walks
a fake xrevrange response for the completed envelope, the no-match
case, and a Redis-down case
- Removed TestMCPOAuthStatus route tests and TestMcpOauthStatusTask
celery-wrapper test
- Removed the two oauth_status methods from the integration runner
mcp_oauth:auth_url/state/code/error Redis keys remain — they are
the OAuth flow's own state (not the dropped polling payload).
* chore(mcp-oauth): delete orphaned getMCPOAuthStatus client
The /api/mcp_server/oauth_status/<task_id> endpoint was removed in
the prior commit; the corresponding userService method and the
MCP_OAUTH_STATUS endpoint constant had no remaining callers in the
frontend, so they're deleted along with it.
* fix(events): drop live publish when journal write fails
application/events/publisher.py returned an envelope to live
pubsub subscribers even when the XADD to the durable journal
failed. The envelope had no ``id`` field, which bypassed the SSE
route's dedup floor and broke ``Last-Event-ID`` semantics for any
reconnecting client.
Best-effort delivery means dropping consistently, not delivering
inconsistent state. Now: if the journal write fails the publisher
returns None and skips the live publish entirely.
* fix(notifications): dedupe sseEventReceived against immediate dupes
Snapshot replay + live tail can both deliver the same id when the
live pubsub frame and the replay XRANGE overlap. The route's own
dedup floor catches the common case, but consumers walking
``recentEvents`` (FileTree, ConnectorTree, MCPServerModal,
ToolApprovalToast) would otherwise act on the same envelope
twice when a duplicate slipped through.
Belt-and-suspenders: short-circuit when the most recent id in
the ring matches the incoming one.
* fix(events): skip replay budget INCR when no snapshot work possible
_allow_replay incremented the per-user counter on every
/api/events GET, including no-op connects from a fresh client
with no cursor against an empty backlog. React StrictMode dev
double-mounts plus a few tabs trivially tripped the default
30-per-60s budget on idle reconnects.
XLEN pre-check: when last_event_id is None and the user stream
is empty, the connect can't do snapshot work — return True
without INCR. Cursor-bearing connects still INCR unconditionally
(probing the cursor's relationship to stream contents would
require a redundant XRANGE).
* fix(streaming): tighten journal contract + recover from seq collisions
Two related fixes to application/streaming/message_journal.py.
1. record_event now rejects non-dict payloads at the gate. The
live path (base.py::_emit) wrapped non-dicts as
{"value": payload}; the replay path in event_replay synthesized
{"type": event_type}. A reconnecting client would receive a
different envelope than the one originally streamed. Now both
paths see byte-identical envelopes because non-dicts can't be
journaled at all. The corresponding event_replay fallback is
replaced with a warn-and-skip for any legacy rows.
2. record_event handles IntegrityError on (message_id, sequence_no)
collisions by reading latest_sequence_no and retrying once with
latest+1. The most likely cause is a stale seq seed on a
continuation retry where the route read MAX(seq) from a
separate connection before another writer committed past it.
Previously the error was swallowed and the event silently
dropped from the journal; now it lands at the next available
seq. The live pubsub publish uses the materialised seq so the
journal row and the live frame agree.
* perf(streaming): batch message_events INSERTs per stream
complete_stream previously opened a fresh db_session() per yielded
event, doing one Postgres INSERT + commit per chunk on the WSGI
thread. Streaming answers emit ~100s of answer chunks per response,
so the route was paying ~100 PG roundtrips per stream serialized on
commit latency.
New BatchedJournalWriter in application/streaming/message_journal.py
accumulates rows per stream and flushes on three triggers:
- size: buffer reaches 16 entries
- time: 100ms elapsed since the last flush
- lifecycle: close() at end-of-stream
Live pubsub publishes still fire synchronously per record(), so
subscribers see events in real time — only the durable journal write
is amortized. On bulk INSERT IntegrityError the writer falls back to
per-row record() with the existing seq+1 retry so a single colliding
seq doesn't drop the rest of the batch.
complete_stream wires journal_writer.close() into every exit path
(happy end, tool-approval-paused end, GeneratorExit, error handler)
so the terminal event is committed before the generator returns —
otherwise a reconnecting client could snapshot up to the last flush
boundary and live-tail waiting for an end that's still in memory.
Repository gets bulk_record() — one SQLAlchemy executemany INSERT
for the bulk path. All-or-nothing on collision (Postgres aborts the
whole batch); the writer's per-row fallback handles recovery.
* chore(upload): drop dead UploadTask.lastEventAt field
The lastEventAt field on UploadTask had no remaining consumers — the
matching Attachment.lastEventAt was cleaned up earlier. Remove the
field declaration and the slice write site.
* chore(frontend): drop orphaned getTaskStatus client
After the polling-removal sweep no caller in frontend/src/ references
userService.getTaskStatus or endpoints.USER.TASK_STATUS. The backend
route /api/task_status itself stays — agents, webhooks, e2e specs,
and the public docs still depend on it.
* docs(repo): remove stale planning docs from repo root
notification-channel-design.md, plan.md, and reminder-tool-design.md
were leftover Claude planning artifacts from the SSE substrate work
that landed accidentally. CLAUDE.md prohibits creating planning docs
unless asked — delete them.
* docs(message-events): clarify repo vs wrapper payload contract
MessageEventsRepository.record accepts any JSONB-compatible value; the
streaming wrapper record_event tightens this to dicts only because the
live and replay paths reconstruct non-dict payloads differently. Spell
the split out so the next reader of the repo method doesn't assume the
wrapper's contract applies here.
* refactor(events): raise on malformed stream id instead of lex fallback
stream_id_compare's lex-fallback branch was a footgun: a malformed id
that sorts lex-greater than a real one would pin live-tail dedup
forever, dropping every subsequent legitimate event silently. Both
current callers in application/api/events/routes.py pre-validate
inputs against _STREAM_ID_RE before calling, so changing the function
to raise ValueError is a no-op on the happy path and turns the future-
caller footgun into a loud failure.
* test(tasks): cover cleanup_message_events task body
Adds skipped-when-no-POSTGRES_URI and happy-path coverage for the
Celery janitor. The skipped path returns the documented short-circuit
shape without touching the repo. The happy path seeds a backdated
row, runs the task against the pg_conn fixture, and asserts the
retention window's row is deleted while in-window rows survive.
Mirrors the TestCleanupPendingToolState pattern.
* fix(notifications): treat /c/new as no current conversation
useMatch('/c/:conversationId') treats the literal URL /c/new as a
real conversation id, so the toast suppression check confused
'user is on /c/new' with 'user is on the conversation needing
approval'. Explicit guard: when the matched id is 'new', fall
through to the no-match case so approval toasts still surface.
* docs(events): enumerate publish_user_event None-return paths
The function returns Optional[str] today, with None conflating five
distinct outcomes (missing args / push disabled / unserialisable /
Redis down / XADD failed). Every current call site is fire-and-
forget and ignores the return, so the right move is to document the
five cases rather than promote to an enum return — keeps the API
small while making the diagnostic surface (logs) obvious. If a
future caller needs to react differently per reason, promote then.
* refactor(sources): move source-id derivation out of worker module
application/api/user/sources/upload.py imported _derive_source_id
from application.worker — pulling the entire Celery worker module
into the API process at import time just for a two-line helper.
Move DOCSGPT_INGEST_NAMESPACE and the derivation function to a
new application/storage/db/source_ids.py module that both layers
can import without that dependency edge. worker.py re-exports the
old names (_derive_source_id, DOCSGPT_INGEST_NAMESPACE) for
backward-compatible imports from tests and any other in-tree
callers; new code should import from the new module directly.
* fix(cache): enable Redis health_check_interval to surface half-open TCP
Without health_check_interval, a half-open TCP socket (NAT silently
dropped state, ELB idle-close) can leave pubsub.get_message hanging
past the SSE generator's keepalive cadence — the kernel never
surfaces the dead socket because no payload is in flight. Setting
health_check_interval=10 makes redis-py ping every 10s when
otherwise idle, so the next get_message after the dead window
raises and the SSE loop falls into its reconnect path instead of
silently freezing on the user.
* chore(events): rename attachment.processing.progress to attachment.progress
The event-type taxonomy was inconsistent: source ingest emits
source.ingest.progress (three segments) while attachments emitted
attachment.processing.progress (four segments). Drops the
.processing. infix for parity. Worker publish sites, the slice
reducer's match, and the worker tests all flip together.
No external consumers — the event type is purely internal between
the publisher and the in-tab slice; safe to rename in one commit.
* feat: events cleanup
* fix: better docs
* fix: e2e tests
874 lines
31 KiB
Python
874 lines
31 KiB
Python
"""Tests for application/api/answer/services/conversation_service.py."""
|
|
|
|
from contextlib import contextmanager
|
|
from datetime import datetime, timezone
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
|
|
@contextmanager
|
|
def _patch_db(conn):
|
|
@contextmanager
|
|
def _yield():
|
|
yield conn
|
|
|
|
with patch(
|
|
"application.api.answer.services.conversation_service.db_session",
|
|
_yield,
|
|
), patch(
|
|
"application.api.answer.services.conversation_service.db_readonly",
|
|
_yield,
|
|
):
|
|
yield
|
|
|
|
|
|
class TestConversationServiceGet:
|
|
def test_returns_none_when_no_conversation_id(self):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
assert ConversationService().get_conversation("", "u") is None
|
|
|
|
def test_returns_none_when_no_user_id(self):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
assert (
|
|
ConversationService().get_conversation(
|
|
"00000000-0000-0000-0000-000000000001", ""
|
|
)
|
|
is None
|
|
)
|
|
|
|
def test_returns_none_when_not_found(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
with _patch_db(pg_conn):
|
|
got = ConversationService().get_conversation(
|
|
"00000000-0000-0000-0000-000000000000", "u",
|
|
)
|
|
assert got is None
|
|
|
|
def test_returns_conversation_with_messages(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-get"
|
|
repo = ConversationsRepository(pg_conn)
|
|
conv = repo.create(user, name="hi")
|
|
conv_id = str(conv["id"])
|
|
repo.append_message(
|
|
conv_id, {"prompt": "q1", "response": "r1"}
|
|
)
|
|
|
|
with _patch_db(pg_conn):
|
|
got = ConversationService().get_conversation(conv_id, user)
|
|
assert got is not None
|
|
assert got["_id"] == conv_id
|
|
assert len(got["queries"]) == 1
|
|
|
|
def test_handles_exception_returns_none(self):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
|
|
@contextmanager
|
|
def _broken():
|
|
raise RuntimeError("boom")
|
|
yield
|
|
|
|
with patch(
|
|
"application.api.answer.services.conversation_service.db_readonly",
|
|
_broken,
|
|
):
|
|
got = ConversationService().get_conversation("abc", "u")
|
|
assert got is None
|
|
|
|
|
|
class TestConversationServiceSave:
|
|
def test_raises_for_none_token(self):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
with pytest.raises(ValueError):
|
|
ConversationService().save_conversation(
|
|
conversation_id=None,
|
|
question="q", response="r", thought="", sources=[],
|
|
tool_calls=[], llm=MagicMock(), model_id="gpt",
|
|
decoded_token=None,
|
|
)
|
|
|
|
def test_raises_when_no_user_in_token(self):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
with pytest.raises(ValueError):
|
|
ConversationService().save_conversation(
|
|
conversation_id=None,
|
|
question="q", response="r", thought="", sources=[],
|
|
tool_calls=[], llm=MagicMock(), model_id="gpt",
|
|
decoded_token={},
|
|
)
|
|
|
|
def test_creates_new_conversation(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-save-new"
|
|
mock_llm = MagicMock()
|
|
mock_llm.gen.return_value = "Title"
|
|
|
|
with _patch_db(pg_conn):
|
|
conv_id = ConversationService().save_conversation(
|
|
conversation_id=None,
|
|
question="q1", response="r1", thought="",
|
|
sources=[{"text": "x" * 2000}], tool_calls=[],
|
|
llm=mock_llm, model_id="gpt-4",
|
|
decoded_token={"sub": user},
|
|
)
|
|
got = ConversationsRepository(pg_conn).get_any(conv_id, user)
|
|
assert got is not None
|
|
assert got["name"] == "Title"
|
|
|
|
def test_appends_message_to_existing(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-append"
|
|
repo = ConversationsRepository(pg_conn)
|
|
conv = repo.create(user, name="existing")
|
|
conv_id = str(conv["id"])
|
|
|
|
with _patch_db(pg_conn):
|
|
got = ConversationService().save_conversation(
|
|
conversation_id=conv_id,
|
|
question="q-new", response="r-new", thought="",
|
|
sources=[], tool_calls=[],
|
|
llm=MagicMock(), model_id="gpt-4",
|
|
decoded_token={"sub": user},
|
|
)
|
|
assert got == conv_id
|
|
messages = repo.get_messages(conv_id)
|
|
assert any(m["prompt"] == "q-new" for m in messages)
|
|
|
|
def test_updates_message_at_index(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-update-at"
|
|
repo = ConversationsRepository(pg_conn)
|
|
conv = repo.create(user, name="edit")
|
|
conv_id = str(conv["id"])
|
|
repo.append_message(conv_id, {"prompt": "old", "response": "old"})
|
|
|
|
with _patch_db(pg_conn):
|
|
got = ConversationService().save_conversation(
|
|
conversation_id=conv_id,
|
|
question="updated", response="reply", thought="",
|
|
sources=[], tool_calls=[],
|
|
llm=MagicMock(), model_id="gpt-4",
|
|
decoded_token={"sub": user},
|
|
index=0,
|
|
)
|
|
assert got == conv_id
|
|
messages = repo.get_messages(conv_id)
|
|
assert messages[0]["prompt"] == "updated"
|
|
|
|
def test_raises_when_conversation_missing(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
with _patch_db(pg_conn), pytest.raises(ValueError):
|
|
ConversationService().save_conversation(
|
|
conversation_id="00000000-0000-0000-0000-000000000000",
|
|
question="q", response="r", thought="",
|
|
sources=[], tool_calls=[],
|
|
llm=MagicMock(), model_id="gpt",
|
|
decoded_token={"sub": "u"},
|
|
)
|
|
|
|
def test_save_with_empty_llm_title_falls_back(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-empty-title"
|
|
mock_llm = MagicMock()
|
|
mock_llm.gen.return_value = ""
|
|
|
|
with _patch_db(pg_conn):
|
|
conv_id = ConversationService().save_conversation(
|
|
conversation_id=None,
|
|
question="q-fallback", response="r", thought="",
|
|
sources=[], tool_calls=[],
|
|
llm=mock_llm, model_id="gpt-4",
|
|
decoded_token={"sub": user},
|
|
)
|
|
got = ConversationsRepository(pg_conn).get_any(conv_id, user)
|
|
assert got["name"] == "q-fallback"
|
|
|
|
|
|
class TestSaveUserQuestion:
|
|
def test_creates_conversation_and_reserves_message(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
TERMINATED_RESPONSE_PLACEHOLDER,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-wal-new"
|
|
with _patch_db(pg_conn):
|
|
result = ConversationService().save_user_question(
|
|
conversation_id=None,
|
|
question="what is python?",
|
|
decoded_token={"sub": user},
|
|
)
|
|
assert result["conversation_id"]
|
|
assert result["message_id"]
|
|
assert result["request_id"]
|
|
|
|
repo = ConversationsRepository(pg_conn)
|
|
conv = repo.get_any(result["conversation_id"], user)
|
|
assert conv is not None
|
|
messages = repo.get_messages(result["conversation_id"])
|
|
assert len(messages) == 1
|
|
assert messages[0]["status"] == "pending"
|
|
assert messages[0]["prompt"] == "what is python?"
|
|
assert messages[0]["response"] == TERMINATED_RESPONSE_PLACEHOLDER
|
|
assert messages[0]["request_id"] == result["request_id"]
|
|
|
|
def test_appends_to_existing_conversation(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-wal-existing"
|
|
repo = ConversationsRepository(pg_conn)
|
|
conv = repo.create(user, name="hi")
|
|
conv_id = str(conv["id"])
|
|
|
|
with _patch_db(pg_conn):
|
|
result = ConversationService().save_user_question(
|
|
conversation_id=conv_id,
|
|
question="follow-up",
|
|
decoded_token={"sub": user},
|
|
)
|
|
assert result["conversation_id"] == conv_id
|
|
msgs = repo.get_messages(conv_id)
|
|
assert len(msgs) == 1
|
|
assert msgs[0]["prompt"] == "follow-up"
|
|
|
|
def test_raises_when_token_missing(self):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
with pytest.raises(ValueError):
|
|
ConversationService().save_user_question(
|
|
conversation_id=None,
|
|
question="q",
|
|
decoded_token=None,
|
|
)
|
|
|
|
def test_regenerate_at_index_replaces_old_message(self, pg_conn):
|
|
"""Regenerate at ``index`` truncates the old message *and
|
|
everything after* before reserving the placeholder, so the new
|
|
WAL row lands at ``position=index`` rather than appending at
|
|
the end. Pre-fix the WAL path appended unconditionally and the
|
|
old answer survived alongside the regenerated one.
|
|
"""
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-wal-regen"
|
|
repo = ConversationsRepository(pg_conn)
|
|
conv = repo.create(user, name="regen-test")
|
|
conv_id = str(conv["id"])
|
|
|
|
# Seed five completed messages at positions 0..4.
|
|
for i in range(5):
|
|
repo.append_message(
|
|
conv_id,
|
|
{
|
|
"prompt": f"q{i}",
|
|
"response": f"a{i}",
|
|
"thought": "",
|
|
"sources": [],
|
|
"tool_calls": [],
|
|
"metadata": {},
|
|
},
|
|
)
|
|
seeded = repo.get_messages(conv_id)
|
|
assert len(seeded) == 5
|
|
assert [m["position"] for m in seeded] == [0, 1, 2, 3, 4]
|
|
|
|
with _patch_db(pg_conn):
|
|
result = ConversationService().save_user_question(
|
|
conversation_id=conv_id,
|
|
question="q3-regen",
|
|
decoded_token={"sub": user},
|
|
index=3,
|
|
)
|
|
|
|
msgs = repo.get_messages(conv_id)
|
|
# Positions 0,1,2 from the seed plus the new placeholder at 3.
|
|
assert [m["position"] for m in msgs] == [0, 1, 2, 3]
|
|
# The placeholder carries the regenerated prompt.
|
|
regen = next(m for m in msgs if m["position"] == 3)
|
|
assert regen["prompt"] == "q3-regen"
|
|
assert regen["status"] == "pending"
|
|
assert str(regen["id"]) == result["message_id"]
|
|
# The old answer at index 3 is gone.
|
|
assert not any(m["response"] == "a3" for m in msgs)
|
|
# And anything after index 3 was truncated.
|
|
assert not any(m["prompt"] == "q4" for m in msgs)
|
|
|
|
def test_regenerate_at_index_zero_truncates_everything(self, pg_conn):
|
|
"""``index=0`` is a valid edge: it should drop every prior
|
|
message and reseat the placeholder at position 0.
|
|
"""
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-wal-regen-zero"
|
|
repo = ConversationsRepository(pg_conn)
|
|
conv = repo.create(user, name="regen-zero")
|
|
conv_id = str(conv["id"])
|
|
for i in range(3):
|
|
repo.append_message(
|
|
conv_id,
|
|
{
|
|
"prompt": f"old-{i}",
|
|
"response": f"old-a-{i}",
|
|
"thought": "",
|
|
"sources": [],
|
|
"tool_calls": [],
|
|
"metadata": {},
|
|
},
|
|
)
|
|
|
|
with _patch_db(pg_conn):
|
|
ConversationService().save_user_question(
|
|
conversation_id=conv_id,
|
|
question="fresh-from-start",
|
|
decoded_token={"sub": user},
|
|
index=0,
|
|
)
|
|
|
|
msgs = repo.get_messages(conv_id)
|
|
assert len(msgs) == 1
|
|
assert msgs[0]["position"] == 0
|
|
assert msgs[0]["prompt"] == "fresh-from-start"
|
|
|
|
def test_regenerate_index_ignored_without_conversation_id(self, pg_conn):
|
|
"""``index`` only makes sense against an existing conversation;
|
|
the create-then-reserve path silently treats it as a no-op
|
|
rather than truncating a freshly-created conversation.
|
|
"""
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-wal-regen-no-conv"
|
|
with _patch_db(pg_conn):
|
|
result = ConversationService().save_user_question(
|
|
conversation_id=None,
|
|
question="brand new q",
|
|
decoded_token={"sub": user},
|
|
index=2,
|
|
)
|
|
|
|
repo = ConversationsRepository(pg_conn)
|
|
msgs = repo.get_messages(result["conversation_id"])
|
|
assert len(msgs) == 1
|
|
assert msgs[0]["position"] == 0
|
|
assert msgs[0]["prompt"] == "brand new q"
|
|
|
|
def test_raises_when_conversation_unauthorized(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
with _patch_db(pg_conn), pytest.raises(ValueError):
|
|
ConversationService().save_user_question(
|
|
conversation_id="00000000-0000-0000-0000-000000000000",
|
|
question="q",
|
|
decoded_token={"sub": "u"},
|
|
)
|
|
|
|
|
|
class TestFinalizeMessage:
|
|
def test_finalizes_complete(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-fin-ok"
|
|
with _patch_db(pg_conn):
|
|
svc = ConversationService()
|
|
res = svc.save_user_question(
|
|
conversation_id=None,
|
|
question="q",
|
|
decoded_token={"sub": user},
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
MessageUpdateOutcome,
|
|
)
|
|
assert svc.finalize_message(
|
|
res["message_id"],
|
|
"real answer",
|
|
thought="thinking",
|
|
sources=[{"text": "x" * 2000, "title": "doc"}],
|
|
tool_calls=[{"name": "search"}],
|
|
model_id="gpt-4",
|
|
metadata={"foo": "bar"},
|
|
status="complete",
|
|
) is MessageUpdateOutcome.UPDATED
|
|
|
|
msgs = ConversationsRepository(pg_conn).get_messages(
|
|
res["conversation_id"],
|
|
)
|
|
assert msgs[0]["response"] == "real answer"
|
|
assert msgs[0]["status"] == "complete"
|
|
assert msgs[0]["thought"] == "thinking"
|
|
assert msgs[0]["model_id"] == "gpt-4"
|
|
# source text trimmed to 1000 chars at finalize time
|
|
assert len(msgs[0]["sources"][0]["text"]) == 1000
|
|
assert msgs[0]["metadata"]["foo"] == "bar"
|
|
|
|
def test_finalizes_failed_records_error(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-fin-fail"
|
|
with _patch_db(pg_conn):
|
|
svc = ConversationService()
|
|
res = svc.save_user_question(
|
|
conversation_id=None,
|
|
question="q",
|
|
decoded_token={"sub": user},
|
|
)
|
|
err = RuntimeError("provider down")
|
|
from application.storage.db.repositories.conversations import (
|
|
MessageUpdateOutcome,
|
|
)
|
|
assert svc.finalize_message(
|
|
res["message_id"],
|
|
"fallback text",
|
|
status="failed",
|
|
error=err,
|
|
) is MessageUpdateOutcome.UPDATED
|
|
|
|
msgs = ConversationsRepository(pg_conn).get_messages(
|
|
res["conversation_id"],
|
|
)
|
|
assert msgs[0]["status"] == "failed"
|
|
assert msgs[0]["metadata"]["error"] == "RuntimeError: provider down"
|
|
|
|
def test_finalize_flips_executed_tool_calls(self, pg_conn):
|
|
"""finalize_message must mark tool_call_attempts.status='executed'
|
|
rows as 'confirmed' for the same message_id."""
|
|
from sqlalchemy import text as sql_text
|
|
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
|
|
user = "u-fin-tools"
|
|
with _patch_db(pg_conn):
|
|
svc = ConversationService()
|
|
res = svc.save_user_question(
|
|
conversation_id=None,
|
|
question="q",
|
|
decoded_token={"sub": user},
|
|
)
|
|
pg_conn.execute(
|
|
sql_text(
|
|
"INSERT INTO tool_call_attempts "
|
|
"(call_id, message_id, tool_name, action_name, arguments, status) "
|
|
"VALUES (:cid, CAST(:mid AS uuid), 't', 'a', '{}'::jsonb, 'executed')"
|
|
),
|
|
{"cid": "c1", "mid": res["message_id"]},
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
MessageUpdateOutcome,
|
|
)
|
|
assert svc.finalize_message(
|
|
res["message_id"], "ans", status="complete",
|
|
) is MessageUpdateOutcome.UPDATED
|
|
|
|
status = pg_conn.execute(
|
|
sql_text("SELECT status FROM tool_call_attempts WHERE call_id = :cid"),
|
|
{"cid": "c1"},
|
|
).scalar()
|
|
assert status == "confirmed"
|
|
|
|
def test_finalize_returns_not_found_for_unknown_message(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
MessageUpdateOutcome,
|
|
)
|
|
with _patch_db(pg_conn):
|
|
assert ConversationService().finalize_message(
|
|
"00000000-0000-0000-0000-000000000000",
|
|
"x",
|
|
status="complete",
|
|
) is MessageUpdateOutcome.NOT_FOUND
|
|
|
|
def test_finalize_rolls_back_tool_call_confirm_on_message_update_failure(
|
|
self, pg_conn
|
|
):
|
|
"""Atomicity: if ``update_message_by_id`` raises after the
|
|
tool_call_attempts confirm ran on the same connection, the
|
|
confirm rolls back with the rest of the transaction. The
|
|
``pg_conn`` fixture pins one connection inside an outer
|
|
rolled-back transaction; we patch ``db_session`` to wrap each
|
|
call in a SAVEPOINT so the production-code ``with`` block
|
|
actually rolls back when the message-update raises.
|
|
"""
|
|
from contextlib import contextmanager
|
|
|
|
from sqlalchemy import text as sql_text
|
|
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories import conversations as conv_module
|
|
|
|
user = "u-fin-rollback"
|
|
|
|
@contextmanager
|
|
def _savepoint_session():
|
|
nested = pg_conn.begin_nested()
|
|
try:
|
|
yield pg_conn
|
|
nested.commit()
|
|
except Exception:
|
|
nested.rollback()
|
|
raise
|
|
|
|
with patch(
|
|
"application.api.answer.services.conversation_service.db_session",
|
|
_savepoint_session,
|
|
), patch(
|
|
"application.api.answer.services.conversation_service.db_readonly",
|
|
_savepoint_session,
|
|
):
|
|
svc = ConversationService()
|
|
res = svc.save_user_question(
|
|
conversation_id=None,
|
|
question="q",
|
|
decoded_token={"sub": user},
|
|
)
|
|
pg_conn.execute(
|
|
sql_text(
|
|
"INSERT INTO tool_call_attempts "
|
|
"(call_id, message_id, tool_name, action_name, "
|
|
"arguments, status) VALUES (:cid, CAST(:mid AS uuid), "
|
|
"'t', 'a', '{}'::jsonb, 'executed')"
|
|
),
|
|
{"cid": "rb-1", "mid": res["message_id"]},
|
|
)
|
|
original = conv_module.ConversationsRepository.update_message_by_id
|
|
|
|
def boom(self, *args, **kwargs):
|
|
_ = (args, kwargs)
|
|
raise RuntimeError("simulated message-update failure")
|
|
|
|
conv_module.ConversationsRepository.update_message_by_id = boom
|
|
try:
|
|
with pytest.raises(RuntimeError):
|
|
svc.finalize_message(
|
|
res["message_id"], "answer", status="complete",
|
|
)
|
|
finally:
|
|
conv_module.ConversationsRepository.update_message_by_id = original
|
|
|
|
# The tool_call confirm rolled back: row stays at ``executed``.
|
|
status = pg_conn.execute(
|
|
sql_text(
|
|
"SELECT status FROM tool_call_attempts WHERE call_id = :cid"
|
|
),
|
|
{"cid": "rb-1"},
|
|
).scalar()
|
|
assert status == "executed"
|
|
msg_status = pg_conn.execute(
|
|
sql_text(
|
|
"SELECT status FROM conversation_messages "
|
|
"WHERE id = CAST(:mid AS uuid)"
|
|
),
|
|
{"mid": res["message_id"]},
|
|
).scalar()
|
|
assert msg_status == "pending"
|
|
|
|
def test_finalize_generates_title_when_provided(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-fin-title"
|
|
mock_llm = MagicMock()
|
|
mock_llm.gen.return_value = "Short Title"
|
|
with _patch_db(pg_conn):
|
|
svc = ConversationService()
|
|
res = svc.save_user_question(
|
|
conversation_id=None,
|
|
question="long question that becomes the fallback name",
|
|
decoded_token={"sub": user},
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
MessageUpdateOutcome,
|
|
)
|
|
assert svc.finalize_message(
|
|
res["message_id"],
|
|
"answer",
|
|
status="complete",
|
|
title_inputs={
|
|
"llm": mock_llm,
|
|
"question": "long question that becomes the fallback name",
|
|
"response": "answer",
|
|
"model_id": "gpt-4",
|
|
"fallback_name": (
|
|
"long question that becomes the fallback name"[:50]
|
|
),
|
|
},
|
|
) is MessageUpdateOutcome.UPDATED
|
|
|
|
repo = ConversationsRepository(pg_conn)
|
|
conv = repo.get_any(res["conversation_id"], user)
|
|
assert conv["name"] == "Short Title"
|
|
|
|
|
|
class TestSaveUserQuestionFinalizeFailedFlow:
|
|
"""LLM fails immediately; question stays queryable with status='failed' + error metadata."""
|
|
|
|
def test_failed_llm_leaves_question_persisted(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-acceptance"
|
|
with _patch_db(pg_conn):
|
|
svc = ConversationService()
|
|
# Simulates the WAL pre-persist before LLM call.
|
|
res = svc.save_user_question(
|
|
conversation_id=None,
|
|
question="why did this fail?",
|
|
decoded_token={"sub": user},
|
|
)
|
|
# Simulates the LLM raising immediately, caught by complete_stream.
|
|
try:
|
|
raise RuntimeError("upstream 503")
|
|
except RuntimeError as e:
|
|
svc.finalize_message(
|
|
res["message_id"],
|
|
"",
|
|
status="failed",
|
|
error=e,
|
|
)
|
|
|
|
msgs = ConversationsRepository(pg_conn).get_messages(
|
|
res["conversation_id"],
|
|
)
|
|
assert len(msgs) == 1
|
|
assert msgs[0]["prompt"] == "why did this fail?"
|
|
assert msgs[0]["status"] == "failed"
|
|
assert "RuntimeError" in msgs[0]["metadata"]["error"]
|
|
assert "upstream 503" in msgs[0]["metadata"]["error"]
|
|
|
|
|
|
class TestCompressionMetadata:
|
|
def test_update_compression_metadata(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-compress"
|
|
repo = ConversationsRepository(pg_conn)
|
|
conv = repo.create(user, name="c")
|
|
conv_id = str(conv["id"])
|
|
|
|
with _patch_db(pg_conn):
|
|
ConversationService().update_compression_metadata(
|
|
conv_id,
|
|
{
|
|
"timestamp": datetime.now(timezone.utc),
|
|
"compressed_summary": "summary",
|
|
"model_used": "gpt",
|
|
},
|
|
)
|
|
|
|
def test_update_compression_raises_on_error(self):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
|
|
@contextmanager
|
|
def _broken():
|
|
raise RuntimeError("boom")
|
|
yield
|
|
|
|
with patch(
|
|
"application.api.answer.services.conversation_service.db_session",
|
|
_broken,
|
|
), pytest.raises(RuntimeError):
|
|
ConversationService().update_compression_metadata("abc", {})
|
|
|
|
def test_append_compression_message_skips_empty_summary(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
|
|
with _patch_db(pg_conn):
|
|
ConversationService().append_compression_message(
|
|
"any-id", {"compressed_summary": ""}
|
|
)
|
|
|
|
def test_append_compression_message_appends_summary(self, pg_conn):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
from application.storage.db.repositories.conversations import (
|
|
ConversationsRepository,
|
|
)
|
|
|
|
user = "u-append-cs"
|
|
repo = ConversationsRepository(pg_conn)
|
|
conv = repo.create(user, name="c")
|
|
conv_id = str(conv["id"])
|
|
|
|
with _patch_db(pg_conn):
|
|
ConversationService().append_compression_message(
|
|
conv_id,
|
|
{
|
|
"compressed_summary": "A summary",
|
|
"timestamp": datetime.now(timezone.utc),
|
|
"model_used": "gpt-4",
|
|
},
|
|
)
|
|
|
|
messages = repo.get_messages(conv_id)
|
|
assert any(m["response"] == "A summary" for m in messages)
|
|
|
|
def test_append_compression_message_swallows_error(self):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
|
|
@contextmanager
|
|
def _broken():
|
|
raise RuntimeError("boom")
|
|
yield
|
|
|
|
with patch(
|
|
"application.api.answer.services.conversation_service.db_session",
|
|
_broken,
|
|
):
|
|
ConversationService().append_compression_message(
|
|
"abc", {"compressed_summary": "x"}
|
|
)
|
|
|
|
def test_get_compression_metadata_returns_none_for_missing(
|
|
self, pg_conn,
|
|
):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
with _patch_db(pg_conn):
|
|
got = ConversationService().get_compression_metadata(
|
|
"00000000-0000-0000-0000-000000000000"
|
|
)
|
|
assert got is None
|
|
|
|
def test_get_compression_metadata_non_uuid_does_not_raise(
|
|
self, pg_conn, caplog,
|
|
):
|
|
"""Non-UUID ids (legacy Mongo ObjectIds with no legacy_mongo_id row)
|
|
must return None without hitting ``CAST(:id AS uuid)`` — which
|
|
would raise and pollute logs with a stack trace every call."""
|
|
import logging
|
|
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
|
|
with caplog.at_level(logging.ERROR):
|
|
with _patch_db(pg_conn):
|
|
got = ConversationService().get_compression_metadata(
|
|
"507f1f77bcf86cd799439011"
|
|
)
|
|
assert got is None
|
|
assert not any(
|
|
"Error getting compression metadata" in r.message for r in caplog.records
|
|
)
|
|
|
|
def test_get_compression_metadata_handles_exception(self):
|
|
from application.api.answer.services.conversation_service import (
|
|
ConversationService,
|
|
)
|
|
|
|
@contextmanager
|
|
def _broken():
|
|
raise RuntimeError("boom")
|
|
yield
|
|
|
|
with patch(
|
|
"application.api.answer.services.conversation_service.db_readonly",
|
|
_broken,
|
|
):
|
|
got = ConversationService().get_compression_metadata("abc")
|
|
assert got is None
|