Repository navigation
Description
Summary
POST /api/agents/{name}/event-subscriptions with a (subscriber, source_agent, event_type) that already exists answers 500 on PostgreSQL, where SQLite answers 409.
| Database | Status | Body |
|---|---|---|
| SQLite | 409 | Subscription already exists for … |
| PostgreSQL | 500 | Internal Server Error |
The row is not duplicated on either database. The unique constraint holds; only the answer is wrong.
Context
Why it happens. src/backend/routers/event_subscriptions.py (the create_event_subscription handler) decides "this is a duplicate" by searching the text of whatever the database layer raised:
except Exception as e:
if "UNIQUE constraint" in str(e):
raise HTTPException(status_code=409, ...)
raise"UNIQUE constraint" is SQLite's wording (UNIQUE constraint failed: agent_event_subscriptions.…). PostgreSQL reports the same violation as
sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique
constraint "agent_event_subscriptions_subscriber_agent_source_agent_eve_key"
(from the backend log of a stack on PostgreSQL, 2026-11-26). The match is case-sensitive, so it does not fire, the exception is re-raised and the caller gets a 500.
Reproduce.
- On a stack that runs on PostgreSQL, create an agent.
POST /api/agents/<agent>/event-subscriptionswith{"source_agent": "<agent>", "event_type": "duplicate.test", "target_message": "First"}→ 201.- Send the same request again → 500. Expected: 409.
The existing live test does exactly this and fails on PostgreSQL: tests/test_event_subscriptions.py::TestCreateSubscription::test_create_duplicate_subscription (Expected status 409, got 500).
Why it matters.
- The default compose stack runs on PostgreSQL (
docker-compose.yml, Remove the SQLite backend: end-of-support passed 2026-09-01 and no issue owns the code removal #4175), so this is the answer most installs give. - A caller that retries a create, or a UI that offers "already subscribed", gets a server error instead.
- It is the last failure of the nightly Tier 3 live job (dev-nightly red: Tier 3 failed on dev #4620) that is not about the model credential: that one test stays red on PostgreSQL until this is fixed.
Acceptance Criteria
- A duplicate create answers 409 on SQLite and on PostgreSQL.
- The route no longer inspects exception text.
- A unit test covers both drivers' wording, and fails without the fix.
-
tests/test_event_subscriptions.py::TestCreateSubscription::test_create_duplicate_subscriptionpasses on a PostgreSQL stack.
Technical Notes
Scope checked. Searched src/backend for other places that recognise a database error by its text or by a sqlite3 exception type on a path that also runs on PostgreSQL ("UNIQUE constraint", duplicate key, in str(e) / in str(exc), sqlite3.IntegrityError, sqlite3.OperationalError). This route is the only one. The remaining hits are SQLite-only utilities (backup, vacuum, the SQLite-to-PostgreSQL copier) and unrelated HTTP error texts.
Suggested direction. The database layer already has a dialect-safe idiom: catch sqlalchemy.exc.IntegrityError, which both drivers raise (src/backend/db/public_chat.py, db/agents.py, db/peer_skill_grants.py, db/memory_facts.py). Catching it in src/backend/db/event_subscriptions.py::create_subscription and giving the route a typed signal keeps the route free of driver wording, which is also what Invariant #1 asks for (router → service → db; routers hold no database concerns).
A unit test that pins it without a database. It calls the route handler with the database layer raising sqlalchemy.exc.IntegrityError, once with each driver's text. On dev at 30ce96ecb the SQLite case passes and the PostgreSQL case fails (1 failed, 1 passed).
Test (place under tests/unit/)
from __future__ import annotations
import asyncio
import sys
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from sqlalchemy.exc import IntegrityError
pytestmark = pytest.mark.unit
_BACKEND = Path(__file__).resolve().parents[2] / "src" / "backend"
if str(_BACKEND) not in sys.path:
sys.path.insert(0, str(_BACKEND))
_INSERT = "INSERT INTO agent_event_subscriptions (...) VALUES (...)"
# What each driver says for the same UNIQUE(subscriber_agent, source_agent, event_type) violation.
SQLITE_TEXT = (
"UNIQUE constraint failed: agent_event_subscriptions.subscriber_agent, "
"agent_event_subscriptions.source_agent, agent_event_subscriptions.event_type"
)
POSTGRES_TEXT = (
'(psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint '
'"agent_event_subscriptions_subscriber_agent_source_agent_eve_key"\n'
"DETAIL: Key (subscriber_agent, source_agent, event_type)=(agent-a, agent-a, duplicate.test) already exists."
)
def _create_duplicate(driver_text: str):
from db_models import EventSubscriptionCreate
from routers.event_subscriptions import create_event_subscription
data = EventSubscriptionCreate(source_agent="agent-a", event_type="duplicate.test",
target_message="First")
mock_db = MagicMock()
mock_db.create_event_subscription.side_effect = IntegrityError(_INSERT, {}, Exception(driver_text))
with patch("routers.event_subscriptions.db", mock_db):
return asyncio.run(create_event_subscription("agent-a", data, SimpleNamespace(username="owner")))
@pytest.mark.parametrize("driver_text", [SQLITE_TEXT, POSTGRES_TEXT], ids=["sqlite", "postgresql"])
def test_a_duplicate_subscription_is_a_409_whatever_the_database_calls_it(driver_text):
from fastapi import HTTPException
with pytest.raises(HTTPException) as info:
_create_duplicate(driver_text)
assert info.value.status_code == 409
Activity