diff --git a/app/src/hooks/useSearchTask.ts b/app/src/hooks/useSearchTask.ts index 50335bf..c46d764 100644 --- a/app/src/hooks/useSearchTask.ts +++ b/app/src/hooks/useSearchTask.ts @@ -22,6 +22,8 @@ import { fetchJson } from '../utils/api'; import type { SearchResult } from '../types/search'; const POLL_INTERVAL_MS = 1000; +// The server cancels the search query at the same bound (STATEMENT_TIMEOUT_SECONDS +// in ord_interface/api/search.py). const POLL_TIMEOUT_MS = 120_000; // Bounds each request, so a stalled one fails the search instead of hanging it. // Longer than the proxy's 60-second proxy_read_timeout (ord_interface/nginx.conf), diff --git a/ord_interface/api/search.py b/ord_interface/api/search.py index 38b7e74..12cfef2 100644 --- a/ord_interface/api/search.py +++ b/ord_interface/api/search.py @@ -67,6 +67,9 @@ BOND_LENGTH = 20 MAX_RESULTS = 1000 +# Postgres cancels any statement that runs longer. Matches POLL_TIMEOUT_MS in +# app/src/hooks/useSearchTask.ts: past it, the client has stopped waiting. +STATEMENT_TIMEOUT_SECONDS = 120 @asynccontextmanager @@ -84,8 +87,11 @@ async def get_cursor() -> AsyncIterator[AsyncCursor[dict[str, Any]]]: host=os.environ["POSTGRES_HOST"], ), ) + options = ( + f"-c search_path=public,ord -c statement_timeout={STATEMENT_TIMEOUT_SECONDS}s" + ) async with await psycopg.AsyncConnection[dict[str, Any]].connect( - dsn, row_factory=dict_row, options="-c search_path=public,ord" + dsn, row_factory=dict_row, options=options ) as connection: await connection.set_read_only(True) async with connection.cursor() as cursor: diff --git a/ord_interface/api/search_test.py b/ord_interface/api/search_test.py index 1974a63..9560a9c 100644 --- a/ord_interface/api/search_test.py +++ b/ord_interface/api/search_test.py @@ -17,11 +17,13 @@ import gzip import json +import psycopg import pytest from ord_schema.proto import dataset_pb2 from rdkit import Chem from tenacity import retry, stop_after_attempt, wait_fixed +from ord_interface.api import search from ord_interface.api.queries import QueryResult @@ -194,6 +196,15 @@ def test_query_async(test_client, params, num_expected): assert len(wait_for_task(test_client, response.json())) == num_expected +@pytest.mark.asyncio +async def test_statement_timeout_cancels_slow_query(test_postgres, monkeypatch): + monkeypatch.setenv("ORD_INTERFACE_POSTGRES", test_postgres.url()) + monkeypatch.setattr(search, "STATEMENT_TIMEOUT_SECONDS", 1) + async with search.get_cursor() as cursor: + with pytest.raises(psycopg.errors.QueryCanceled): + await cursor.execute("SELECT pg_sleep(2)") + + def test_get_input_stats(test_client): response = test_client.get( "/api/input_stats",