~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(chat): allocate message sequences after attempt deletion (#6907)
LearningCircuit3e13629b832c
diff --git a/changelog.d/+chat-sequence-after-deletion.bugfix.md b/changelog.d/+chat-sequence-after-deletion.bugfix.mdnew file mode 100644index 0000000000..bf8e8328a7--- /dev/null+++ b/changelog.d/+chat-sequence-after-deletion.bugfix.md@@ -0,0 +1 @@+Keep chat sessions usable after deleting an older attempt by allocating new message sequence numbers independently of the remaining message count. Messages staged in the same transaction also retain distinct sequence numbers when automatic flushing is disabled.diff --git a/src/local_deep_research/chat/service.py b/src/local_deep_research/chat/service.pyindex fb7d2ca30c..b5f47e64c3 100644--- a/src/local_deep_research/chat/service.py+++ b/src/local_deep_research/chat/service.py@@ -391,12 +391,36 @@ class ChatService:ChatSession.status == ChatSessionStatus.ACTIVE.value)not_found_msg = f"Chat session {session_id} not found or not active"- sequence = self._atomic_increment(+ message_count = self._atomic_increment(db, ChatSession.message_count, where_clause)- if sequence is None:+ if message_count is None:raise ValueError(not_found_msg)+ # message_count tracks surviving rows, so deleting an older attempt+ # makes it smaller than the largest surviving sequence. The UPDATE+ # above holds SQLite's write lock until this transaction commits;+ # concurrent senders cannot allocate the same next sequence here.+ last_sequence = (+ db.query(func.max(ChatMessage.sequence_number))+ .filter(ChatMessage.session_id == session_id)+ .scalar()+ )+ # A caller may disable autoflush while staging several messages in+ # this transaction. Include those reservations without forcing its+ # pending work to flush or committing on its behalf.+ pending_sequence = max(+ (+ message.sequence_number+ for message in db.new+ if isinstance(message, ChatMessage)+ and message.session_id == session_id+ and message.sequence_number is not None+ ),+ default=0,+ )+ sequence = max(last_sequence or 0, pending_sequence) + 1+# created_at populated by column default (utcnow()).message = ChatMessage(id=message_id,diff --git a/src/local_deep_research/database/models/chat.py b/src/local_deep_research/database/models/chat.pyindex c951eac904..1cbcf588eb 100644--- a/src/local_deep_research/database/models/chat.py+++ b/src/local_deep_research/database/models/chat.py@@ -91,10 +91,13 @@ class ChatSession(Base):created_at = Column(UtcDateTime, nullable=False, default=utcnow())- # message_count is load-bearing: used with atomic UPDATE...RETURNING for- # safe sequence_number generation in add_message(). Step rows do NOT- # increment this counter (they live in chat_progress_steps with their- # own per-research counter on research_history.step_count).+ # message_count counts surviving chat messages. Its atomic increment+ # acquires the write lock, while sequence_number is allocated above both+ # persisted and pending messages. Deleting earlier messages therefore+ # reduces the count without reusing a surviving sequence number.+ # Step rows do NOT increment this counter (they live in+ # chat_progress_steps with their own per-research counter on+ # research_history.step_count).message_count = Column(Integer, nullable=False, default=0, server_default="0")diff --git a/tests/chat/conftest.py b/tests/chat/conftest.pyindex 47bfbf3d14..b22b0dfa0a 100644--- a/tests/chat/conftest.py+++ b/tests/chat/conftest.py@@ -185,6 +185,9 @@ def setup_query_mock_with_session(db_session_mock, session_obj):result.scalar_one_or_none.return_value = Noneelse:current = session_obj.message_count or 0+ # These mocks model a session without deleted messages. Real+ # sequence gaps are exercised by the service contract tests.+ query_mock.filter.return_value.scalar.return_value = currentsession_obj.message_count = current + 1result.scalar_one_or_none.return_value = session_obj.message_countreturn resultdiff --git a/tests/chat/test_chat_boundaries.py b/tests/chat/test_chat_boundaries.pyindex 26efc2d6b2..ccb2532129 100644--- a/tests/chat/test_chat_boundaries.py+++ b/tests/chat/test_chat_boundaries.py@@ -15,10 +15,6 @@ class TestMessageBoundaries:"""Test that empty message content is accepted."""from local_deep_research.chat.service import ChatService- mock_session_obj = MagicMock()- mock_session_obj.id = "test-session"- mock_session_obj.message_count = 0-added_messages = []@contextmanager@@ -30,8 +26,9 @@ class TestMessageBoundaries:mock_session.add = mock_addmock_session.commit = MagicMock()- mock_session.query.return_value.filter_by.return_value.with_for_update.return_value.first.return_value = mock_session_obj- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_session_obj+ mock_session.new = added_messages+ mock_session.execute.return_value.scalar_one_or_none.return_value = 1+ mock_session.query.return_value.filter.return_value.scalar.return_value = Noneyield mock_sessionwith patch(@@ -49,6 +46,7 @@ class TestMessageBoundaries:assert message_id is not Noneassert len(added_messages) == 1assert added_messages[0].content == ""+ assert added_messages[0].sequence_number == 1def test_message_with_none_content_is_rejected(self):"""chat_messages.content is NOT NULL.diff --git a/tests/chat/test_chat_concurrency.py b/tests/chat/test_chat_concurrency.pyindex d0b0a972ab..257b47c223 100644--- a/tests/chat/test_chat_concurrency.py+++ b/tests/chat/test_chat_concurrency.py@@ -11,6 +11,8 @@ from unittest.mock import MagicMock, patchfrom contextlib import contextmanagerimport threading+import pytest+from tests.chat.conftest import setup_query_mock_with_session@@ -415,18 +417,18 @@ class TestAddMessageSequenceRace:return engine, Session, session_id- def test_concurrent_add_message_unique_sequence_numbers(self, tmp_path):+ @pytest.mark.parametrize("existing_sequence", [0, 10])+ def test_concurrent_add_message_unique_sequence_numbers(+ self, tmp_path, existing_sequence+ ):"""10 concurrent add_message calls produce 10 unique sequence_numbers.- This exercises the add_message sequence-number race: without- retry-on-IntegrityError, two callers would both compute the same- `session.message_count + 1`- and one would fail with a 500 when the uq_chat_message_session_seq- constraint fires.+ Allocation must remain serialized even when deletions have left+ the message count below the largest surviving sequence number."""from contextlib import contextmanagerfrom local_deep_research.chat.service import ChatService- from local_deep_research.database.models import ChatMessage+ from local_deep_research.database.models import ChatMessage, ChatSessionengine, Session, session_id = self._setup_real_db(tmp_path)@@ -458,6 +460,17 @@ class TestAddMessageSequenceRace:"local_deep_research.chat.service.get_user_db_session",real_get_user_db_session,):+ if existing_sequence:+ # Model a session with one surviving high-sequence message,+ # as left by deleting earlier attempts. Count remains one.+ message_id = service.add_message(+ session_id, "user", "surviving message", "query"+ )+ with Session() as db:+ db.query(ChatMessage).filter_by(id=message_id).update(+ {ChatMessage.sequence_number: existing_sequence}+ )+ db.commit()with ThreadPoolExecutor(max_workers=num_messages) as executor:futures = [executor.submit(add_one, i) for i in range(num_messages)@@ -475,6 +488,13 @@ class TestAddMessageSequenceRace:.filter_by(session_id=session_id).all())- # 10 unique sequence numbers, 1..10, no collisions- assert sequences == list(range(1, num_messages + 1))+ assert db.get(ChatSession, session_id).message_count == (+ num_messages + bool(existing_sequence)+ )+ expected = list(+ range(existing_sequence + 1, existing_sequence + num_messages + 1)+ )+ if existing_sequence:+ expected.insert(0, existing_sequence)+ assert sequences == expectedengine.dispose()diff --git a/tests/chat/test_chat_fuzz.py b/tests/chat/test_chat_fuzz.pyindex eb93fbe6d4..fa49d30637 100644--- a/tests/chat/test_chat_fuzz.py+++ b/tests/chat/test_chat_fuzz.py@@ -212,16 +212,17 @@ class TestChatServiceFuzz:# Skip empty content for valid messagesassume(len(content.strip()) > 0)+ added_messages = []@contextmanagerdef mock_get_user_db_session(username, password=None):mock_session = MagicMock()- # Mock the session query to return a valid session- mock_chat_session = MagicMock()- mock_chat_session.message_count = 0- mock_session.query.return_value.filter_by.return_value.with_for_update.return_value.first.return_value = mock_chat_session- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_chat_session- mock_session.add = MagicMock()+ # Existing empty chat: the counter advances to one and the+ # retained-message query has no sequence yet.+ mock_session.execute.return_value.scalar_one_or_none.return_value = 1+ mock_session.query.return_value.filter.return_value.scalar.return_value = None+ mock_session.new = added_messages+ mock_session.add.side_effect = added_messages.appendmock_session.commit = MagicMock()yield mock_session@@ -241,6 +242,9 @@ class TestChatServiceFuzz:# Should return a UUID stringassert isinstance(message_id, str)assert len(message_id) > 0+ assert len(added_messages) == 1+ assert added_messages[0].content == content+ assert added_messages[0].sequence_number == 1except ValueError:# Session not found is expected in some casesdiff --git a/tests/chat/test_chat_research_history_integration.py b/tests/chat/test_chat_research_history_integration.pyindex 832eab90db..f33787bdfa 100644--- a/tests/chat/test_chat_research_history_integration.py+++ b/tests/chat/test_chat_research_history_integration.py@@ -21,22 +21,21 @@ class TestResearchHistoryLinking:from local_deep_research.chat.service import ChatServicemock_session = MagicMock()+ mock_session.new = []captured_message = Nonedef capture_add(obj):nonlocal captured_messageif hasattr(obj, "research_id"):captured_message = obj+ mock_session.new.append(obj)mock_session.add.side_effect = capture_addmock_session.commit = MagicMock()- # Mock session query for getting the session- mock_chat_session = MagicMock()- mock_chat_session.id = "test-session-123"- mock_chat_session.message_count = 0- mock_session.query.return_value.filter_by.return_value.with_for_update.return_value.first.return_value = mock_chat_session- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_chat_session+ # The atomic increment reserves a message in an empty session.+ mock_session.execute.return_value.scalar_one_or_none.return_value = 1+ mock_session.query.return_value.filter.return_value.scalar.return_value = None@contextmanagerdef mock_get_user_db_session(username, password=None):@@ -59,6 +58,7 @@ class TestResearchHistoryLinking:# Verify research_id was storedassert captured_message is not Noneassert captured_message.research_id == "research-abc-123"+ assert captured_message.sequence_number == 1def test_message_with_research_id_increments_message_count(self):"""Test that session message count is incremented when research_id is set."""diff --git a/tests/chat/test_chat_service_contracts.py b/tests/chat/test_chat_service_contracts.pyindex 7191cb6859..3902188b48 100644--- a/tests/chat/test_chat_service_contracts.py+++ b/tests/chat/test_chat_service_contracts.py@@ -35,7 +35,7 @@ the production code gets an XPASS telling them to delete the marker."""import threading-from contextlib import contextmanager+from contextlib import contextmanager, nullcontextfrom datetime import UTC, datetime, timedeltafrom unittest.mock import MagicMock, patch@@ -482,6 +482,118 @@ def paged_session(user_dbs):return service, session_id, ids+class TestCallerOwnedMessageTransactions:+ @pytest.mark.parametrize("flush_mode", ["enabled", "disabled", "context"])+ @pytest.mark.parametrize("existing_sequence", [0, 10])+ @pytest.mark.parametrize("finish", ["commit", "rollback"])+ def test_staged_messages_keep_distinct_sequences_and_caller_ownership(+ self, user_dbs, flush_mode, existing_sequence, finish+ ):+ service = user_dbs.service(OWNER)+ session_id = service.create_session(initial_query="staged messages")+ if existing_sequence:+ seed_message_at(+ user_dbs,+ OWNER,+ session_id,+ "survivor",+ _at(0),+ existing_sequence,+ "surviving message",+ )+ with user_dbs.raw(OWNER) as db:+ db.get(ChatSession, session_id).message_count = 1+ db.commit()++ before_count = int(bool(existing_sequence))+ with user_dbs.raw(OWNER) as db:+ db.autoflush = flush_mode != "disabled"+ guard = (+ db.no_autoflush if flush_mode == "context" else nullcontext()+ )+ with guard:+ ids = [+ service.insert_message_in_db(+ db, session_id, "user", f"staged {index}", "query"+ )+ for index in range(2)+ ]+ if flush_mode != "enabled":+ # Respect a caller deliberately constructing several rows+ # before flushing; the helper must not force that flush.+ pending = {+ row.id: row.sequence_number+ for row in db.new+ if isinstance(row, ChatMessage)+ }+ assert [pending[mid] for mid in ids] == [+ existing_sequence + 1,+ existing_sequence + 2,+ ]++ # Neither staged messages nor the counter updates are visible+ # outside the transaction before the caller chooses to commit.+ with user_dbs.raw(OWNER) as observer:+ assert (+ observer.get(ChatSession, session_id).message_count+ == before_count+ )+ assert observer.query(ChatMessage).count() == before_count++ if finish == "commit":+ db.commit()+ else:+ db.rollback()++ with user_dbs.raw(OWNER) as db:+ expected = [existing_sequence] if existing_sequence else []+ if finish == "commit":+ expected.extend([existing_sequence + 1, existing_sequence + 2])+ assert [+ row.sequence_number+ for row in db.query(ChatMessage)+ .filter_by(session_id=session_id)+ .order_by(ChatMessage.sequence_number)+ ] == expected+ assert db.get(ChatSession, session_id).message_count == len(+ expected+ )++ def test_pending_message_in_another_session_does_not_set_the_sequence(+ self, user_dbs+ ):+ service = user_dbs.service(OWNER)+ target = service.create_session(initial_query="target")+ sibling = service.create_session(initial_query="sibling")+ with user_dbs.raw(OWNER) as db:+ db.autoflush = False+ sibling_id = service.insert_message_in_db(+ db, sibling, "user", "sibling", "query"+ )+ sibling_message = next(+ row for row in db.new if row.id == sibling_id+ )+ sibling_message.sequence_number = 1000+ ids = [+ service.insert_message_in_db(+ db, target, "user", f"target {index}", "query"+ )+ for index in range(2)+ ]+ assert sibling_message in db.new+ db.commit()+ with user_dbs.raw(OWNER) as db:+ assert [+ db.get(ChatMessage, mid).sequence_number for mid in ids+ ] == [+ 1,+ 2,+ ]+ assert db.get(ChatMessage, sibling_id).sequence_number == 1000+ assert db.get(ChatSession, target).message_count == 2+ assert db.get(ChatSession, sibling).message_count == 1++class TestMessageOrdering:def test_page_is_returned_oldest_to_newest_within_the_newest_window(self, paged_session@@ -1107,14 +1219,6 @@ class TestResearchSlotInvariant:# 4. Attempt deletion and the message sequence counter# ----------------------------------------------------------------------_SEQUENCE_REUSE_DEFECT = (- "delete_attempt decrements ChatSession.message_count without "- "renumbering the surviving rows, so the next insert reuses a "- "sequence_number that still exists and trips "- "uq_chat_message_session_seq -- permanently, because the failed "- "insert also rolls back the counter increment"-)-def _seed_attempt(service, dbs, session_id, research_id, label):"""One attempt: user message (research_id NULL, linked via meta) plus@@ -1162,7 +1266,6 @@ class TestAttemptDeletion:] == ["first question", "first answer"]assert message_count_of(user_dbs, OWNER, session_id) == 2- @pytest.mark.xfail(strict=True, reason=_SEQUENCE_REUSE_DEFECT)def test_session_still_accepts_messages_after_deleting_an_old_attempt(self, user_dbs):@@ -1181,68 +1284,44 @@ class TestAttemptDeletion:service.add_message(session_id, "user", "third question", "query")- def test_blast_radius_deleting_an_old_attempt_bricks_the_session(- self, user_dbs+ @pytest.mark.parametrize(+ "deleted,expected_sequences",+ [+ ("brick-1", [3, 4, 5, 6, 7, 8]),+ ("brick-2", [1, 2, 5, 6, 7, 8]),+ ("brick-3", [1, 2, 3, 4, 5, 6]),+ ],+ )+ def test_repeated_sends_after_deletion_preserve_rows_and_exact_count(+ self, user_dbs, deleted, expected_sequences):- """Current behaviour, pinned.-- Sequence numbers 1..4 are handed out for two attempts. Deleting- the FIRST attempt removes 1 and 2, leaving 3 and 4, and drops- message_count from 4 to 2. The next insert asks the atomic- counter for 3 -- which the surviving user bubble still holds --- and ``uq_chat_message_session_seq`` rejects it. The IntegrityError- rolls back the whole transaction *including* the counter bump, so- message_count stays at 2 and every subsequent send repeats the- failure. The session can never accept another message.-- Deleting the NEWEST attempt is safe, which is why this survives- casual testing.- """service = user_dbs.service(OWNER)- session_id = service.create_session(initial_query="brick")- _seed_attempt(service, user_dbs, session_id, "brick-1", "first")- _seed_attempt(service, user_dbs, session_id, "brick-2", "second")-- with user_dbs.raw(OWNER) as db:- sequences = [- m.sequence_number- for m in db.query(ChatMessage)- .filter_by(session_id=session_id)- .order_by(ChatMessage.sequence_number)- .all()- ]- assert sequences == [1, 2, 3, 4]+ session_id = service.create_session(initial_query="sequence gaps")+ for number, label in enumerate(("first", "second", "third"), 1):+ _seed_attempt(+ service, user_dbs, session_id, f"brick-{number}", label+ )with (patch(f"{SERVICE}.is_research_thread_alive", return_value=False),patch(f"{SERVICE}.cleanup_research"),):- service.delete_attempt(session_id, "brick-1")- assert message_count_of(user_dbs, OWNER, session_id) == 2+ service.delete_attempt(session_id, deleted)+ assert message_count_of(user_dbs, OWNER, session_id) == 4- for _attempt in range(2):- with pytest.raises(IntegrityError) as excinfo:- service.add_message(- session_id, "user", "next question", "query"- )- assert "uq_chat_message_session_seq" in str(- excinfo.value- ) or "chat_messages.session_id" in str(excinfo.value)- # The counter never advances, so the failure is permanent.- assert message_count_of(user_dbs, OWNER, session_id) == 2-- # Contrast: deleting the NEWEST attempt leaves the session usable.- clean_session = service.create_session(initial_query="clean")- _seed_attempt(service, user_dbs, clean_session, "clean-1", "first")- _seed_attempt(service, user_dbs, clean_session, "clean-2", "second")- with (- patch(f"{SERVICE}.is_research_thread_alive", return_value=False),- patch(f"{SERVICE}.cleanup_research"),- ):- service.delete_attempt(clean_session, "clean-2")- assert service.add_message(- clean_session, "user", "next question", "query"- )+ for attempt in range(2):+ service.add_message(session_id, "user", "next question", "query")+ assert message_count_of(user_dbs, OWNER, session_id) == 5 + attempt++ with user_dbs.raw(OWNER) as db:+ rows = (+ db.query(ChatMessage)+ .filter_by(session_id=session_id)+ .order_by(ChatMessage.sequence_number)+ .all()+ )+ assert [row.sequence_number for row in rows] == expected_sequences+ assert len(rows) == 6# ---------------------------------------------------------------------diff --git a/tests/database/test_model_constraint_contracts.py b/tests/database/test_model_constraint_contracts.pyindex 9a99bad0a3..a726433c7b 100644--- a/tests/database/test_model_constraint_contracts.py+++ b/tests/database/test_model_constraint_contracts.py@@ -44,6 +44,7 @@ from sqlalchemy.orm import Sessionfrom local_deep_research.database.models import (Base,ChatMessage,+ ChatMessageType,ChatSession,DownloadTracker,NewsCard,@@ -452,22 +453,18 @@ def _seed_attempt(db, session_id, research_id, user_msg_id):def test_chat_message_sequence_collides_after_delete_attempt(engine, monkeypatch):- """DEFECT: deleting a non-final chat attempt permanently wedges the- session.-- ``sequence_number`` is allocated by an atomic- ``UPDATE chat_sessions SET message_count = message_count + 1- RETURNING message_count`` (``ChatService._atomic_increment``), but- ``delete_attempt`` DECREMENTS the same counter by the number of rows it- removed (chat/service.py, "Decrement message_count"), and- ``_cleanup_chat_send_rows`` decrements it by one- (web/routers/chat.py). When the removed rows are not the highest- numbered ones, the counter rewinds onto sequence numbers that are still- present and every subsequent write violates- ``uq_chat_message_session_seq``.-- The failing INSERT rolls its own increment back, so the counter stays- rewound: the session can never accept another message.+ """After deleting a non-final chat attempt, the session keeps+ accepting messages and the sequence UNIQUE constraint still holds.++ Premise history: sequence_number was originally allocated from the+ ``message_count`` counter, which ``delete_attempt`` rewinds — deleting+ a non-final attempt rewound the counter onto live rows and every+ subsequent write violated ``uq_chat_message_session_seq``, wedging the+ session. The fix in this PR allocates ``MAX(sequence_number) + 1``+ instead, so the manufactured collision is no longer reachable and this+ test now asserts the post-fix contract: the next message succeeds with+ the correct sequence, and the constraint itself still rejects a direct+ duplicate-sequence insert."""from local_deep_research.chat import service as chat_service@@ -519,20 +516,41 @@ def test_chat_message_sequence_collides_after_delete_attempt()) == [3, 4]- # Next write is handed sequence 3, which row `msg_b_user` still holds.- with pytest.raises(IntegrityError) as excinfo:- svc.add_message(session_id, "user", "q3", "followup")+ # Premise changed in this PR: sequence allocation moved from+ # ``message_count + 1`` (which rewound onto live rows after a+ # non-tail deletion and manufactured UNIQUE violations) to+ # ``MAX(sequence_number) + 1``, so the next write is handed 5 and+ # succeeds where the old allocation collided with row 3.+ next_msg = svc.add_message(session_id, "user", "q3", "followup")+ assert next_msg is not None+ with Session(engine) as check:+ assert check.get(ChatSession, session_id).message_count == 3+ assert sorted(+ r[0]+ for r in check.query(ChatMessage.sequence_number).filter_by(+ session_id=session_id+ )+ ) == [3, 4, 5]++ # The UNIQUE constraint itself is still the backstop: a direct+ # duplicate-sequence insert must raise exactly as before.+ with Session(engine) as dup, pytest.raises(IntegrityError) as excinfo:+ dup.add(+ ChatMessage(+ id=str(uuid.uuid4()),+ session_id=session_id,+ role="user",+ message_type=ChatMessageType.FOLLOWUP,+ content="duplicate sequence",+ sequence_number=5,+ )+ )+ dup.commit()assert ("UNIQUE constraint failed: chat_messages.session_id, ""chat_messages.sequence_number" in str(excinfo.value))- # And it stays broken: the rollback undid the increment too.- with Session(engine) as check:- assert check.get(ChatSession, session_id).message_count == 2- with pytest.raises(IntegrityError):- svc.add_message(session_id, "user", "q4", "followup")-# ===========================================================================# 3. FK ondelete vs what the deletion services assumediff --git a/tests/test_end_to_end_journeys.py b/tests/test_end_to_end_journeys.pyindex db4ba2b9b5..cb836ea88b 100644--- a/tests/test_end_to_end_journeys.py+++ b/tests/test_end_to_end_journeys.py@@ -780,17 +780,6 @@ class TestJourneyChatSession:== "completed"), "send again: the re-sent message's research did not complete"- @pytest.mark.xfail(- strict=True,- reason=(- "CONFIRMED DEFECT, journey-level consequence. Deleting an "- "attempt that is not the newest permanently bricks the chat "- "session: the very next send returns 500 and the user can "- "never post in that session again. The service-level mechanism "- "is pinned in tests/chat/test_chat_service_contracts.py; this "- "is what it does to a real user driving the product over HTTP."- ),- )def test_deleting_a_non_newest_attempt_leaves_the_session_usable(self, app, stubs):@@ -825,6 +814,10 @@ class TestJourneyChatSession:"the chat session is bricked after deleting a non-newest "f"attempt: {resent.status_code} {resent.text[:300]}")+ assert (+ _poll_until_terminal(client, resent.json()["research_id"])["status"]+ == "completed"+ )# ---------------------------------------------------------------------------diff --git a/tests/test_known_defect_pattern_sweep.py b/tests/test_known_defect_pattern_sweep.pyindex 27249c99c8..1a8142120f 100644--- a/tests/test_known_defect_pattern_sweep.py+++ b/tests/test_known_defect_pattern_sweep.py@@ -21,7 +21,9 @@ nothing is worse than no scanner at all:decorator, a moved helper) fails here rather than reporting "all clear".``test_p<N>_known_live_instance_is_refound``The site that motivated the pattern must appear in the results. If it does- not, the scanner is wrong -- not the codebase.+ not, the scanner is wrong -- not the codebase. Once repaired, that site+ instead has a regression assertion requiring it to remain absent; the+ synthetic positive control continues to prove the scanner detects the bug.``test_p<N>_inventory_is_pinned`` then locks the full result set, so a newoccurrence of an already-proven defect fails the build instead of shipping.@@ -1019,11 +1021,8 @@ def undo_entry(db, ledger_id):db.execute(update(Ledger).values(visible_count=Ledger.visible_count - 1))"""-P2_KNOWN_COUNTER = "ChatSession.message_count"-P2_EXPECTED = {- ("src/local_deep_research/chat/service.py", P2_KNOWN_COUNTER),- ("src/local_deep_research/web/routers/chat.py", P2_KNOWN_COUNTER),-}+P2_REPAIRED_COUNTER = "ChatSession.message_count"+P2_EXPECTED: set[tuple[str, str]] = set()# Same construction, never decremented anywhere -- an in-repo true negative.P2_SAFE_COUNTER = "ResearchHistory.step_count"@@ -1047,13 +1046,16 @@ def test_p2_examines_a_floor_of_sites():_, links, stats = scan_pattern_2(modules())assert stats["unique_int_columns"] >= 8, statsassert stats["decremented_columns"] >= 5, stats- assert len(links) >= 2, links+ # Chat now allocates from the highest retained sequence, leaving the+ # monotonic progress counter as the remaining counter-based allocator.+ assert len(links) >= 1, links-def test_p2_known_live_instance_is_refound():- sites, _links, _ = scan_pattern_2(modules())- assert P2_KNOWN_COUNTER in {s.tag for s in sites}, report(- "pattern 2: chat_messages.sequence_number must still be flagged",+def test_p2_chat_display_count_no_longer_allocates_a_sequence():+ sites, links, _ = scan_pattern_2(modules())+ assert P2_REPAIRED_COUNTER not in links, links+ assert P2_REPAIRED_COUNTER not in {s.tag for s in sites}, report(+ "pattern 2: chat sequence allocation must remain repaired",sites,)