Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Prevent unnecessary post-process results recursion (#2418)

sarayourfriend21f09eb78e61
diff --git a/api/api/controllers/search_controller.py b/api/api/controllers/search_controller.py
index def66bb34..a723e52f9 100644
--- a/api/api/controllers/search_controller.py
+++ b/api/api/controllers/search_controller.py
@@ -205,10 +205,26 @@ def _post_process_results(
end = 90 + 45
```
"""
+ if end >= search_results.hits.total.value:
+ # Total available hits already exhausted in previous iteration
+ return results
+
end += int(end / 2)
- if start + end > ELASTICSEARCH_MAX_RESULT_WINDOW:
+ query_size = start + end
+ if query_size > ELASTICSEARCH_MAX_RESULT_WINDOW:
return results
+ # subtract start to account for the records skipped
+ # and which should not count towards the total
+ # available hits for the query
+ total_available_hits = search_results.hits.total.value - start
+ if query_size > total_available_hits:
+ # Clamp the query size to last available hit. On the next
+ # iteration, if results are still insufficient, the check
+ # to compare previous_query_size and total_available_hits
+ # will prevent further query attempts
+ end = search_results.hits.total.value
+
s = s[start:end]
search_response = s.execute()
diff --git a/api/api/utils/dead_link_mask.py b/api/api/utils/dead_link_mask.py
index 4d0cc281d..fdd1034b0 100644
--- a/api/api/utils/dead_link_mask.py
+++ b/api/api/utils/dead_link_mask.py
@@ -1,5 +1,5 @@
+import django_redis
from deepdiff import DeepHash
-from django_redis import get_redis_connection
from elasticsearch_dsl import Search
@@ -32,7 +32,7 @@ def get_query_mask(query_hash: str) -> list[int]:
:param query_hash: Unique value for a particular query.
:return: Boolean mask as a list of integers (0 or 1).
"""
- redis = get_redis_connection("default")
+ redis = django_redis.get_redis_connection("default")
key = f"{query_hash}:dead_link_mask"
return list(map(int, redis.lrange(key, 0, -1)))
@@ -44,7 +44,7 @@ def save_query_mask(query_hash: str, mask: list):
:param mask: Boolean mask as a list of integers (0 or 1).
:param query_hash: Unique value to be used as key.
"""
- redis_pipe = get_redis_connection("default").pipeline()
+ redis_pipe = django_redis.get_redis_connection("default").pipeline()
key = f"{query_hash}:dead_link_mask"
redis_pipe.delete(key)
diff --git a/api/test/factory/es_http.py b/api/test/factory/es_http.py
new file mode 100644
index 000000000..f80de2e06
--- /dev/null
+++ b/api/test/factory/es_http.py
@@ -0,0 +1,81 @@
+from uuid import uuid4
+
+
+MOCK_LIVE_RESULT_URL_PREFIX = "https://example.com/openverse-live-image-result-url"
+MOCK_DEAD_RESULT_URL_PREFIX = "https://example.com/openverse-dead-image-result-url"
+
+
+def create_mock_es_http_image_hit(_id: str, index: str, live: bool = True):
+ return {
+ "_index": index,
+ "_type": "_doc",
+ "_id": _id,
+ "_score": 7.607353,
+ "_source": {
+ "thumbnail": None,
+ "aspect_ratio": "wide",
+ "extension": "jpg",
+ "size": "large",
+ "authority_boost": 85,
+ "max_boost": 85,
+ "min_boost": 1,
+ "id": _id,
+ "identifier": str(uuid4()),
+ "title": "Bird Nature Photo",
+ "foreign_landing_url": "https://example.com/photo/LYTN21EBYO",
+ "creator": "Nature's Beauty",
+ "creator_url": "https://example.com/author/121424",
+ "url": f"{MOCK_LIVE_RESULT_URL_PREFIX}/{_id}"
+ if live
+ else f"{MOCK_DEAD_RESULT_URL_PREFIX}/{_id}",
+ "license": "cc0",
+ "license_version": "1.0",
+ "license_url": "https://creativecommons.org/publicdomain/zero/1.0/",
+ "provider": "example",
+ "source": "example",
+ "category": "photograph",
+ "created_on": "2022-02-26T08:48:33+00:00",
+ "tags": [{"name": "bird"}],
+ "mature": False,
+ },
+ }
+
+
+def create_mock_es_http_image_search_response(
+ index: str,
+ total_hits: int,
+ hit_count: int,
+ live_hit_count: int | None = None,
+ base_hits=None,
+):
+ live_hit_count = live_hit_count if live_hit_count is not None else hit_count
+ base_hits = base_hits or []
+
+ live_hits = [
+ create_mock_es_http_image_hit(
+ _id=len(base_hits) + i,
+ index=index,
+ live=True,
+ )
+ for i in range(live_hit_count)
+ ]
+
+ dead_hits = [
+ create_mock_es_http_image_hit(
+ _id=len(live_hits) + len(base_hits) + i,
+ index=index,
+ live=False,
+ )
+ for i in range(hit_count - live_hit_count)
+ ]
+
+ return {
+ "took": 3,
+ "timed_out": False,
+ "_shards": {"total": 18, "successful": 18, "skipped": 0, "failed": 0},
+ "hits": {
+ "total": {"value": total_hits, "relation": "eq"},
+ "max_score": 11.0007305,
+ "hits": base_hits + live_hits + dead_hits,
+ },
+ }
diff --git a/api/test/factory/models/media.py b/api/test/factory/models/media.py
index 8f47d12c3..8fc6505d6 100644
--- a/api/test/factory/models/media.py
+++ b/api/test/factory/models/media.py
@@ -156,7 +156,7 @@ class MediaFactory(DjangoModelFactory):
source_document = cls._create_es_source_document(media, mature)
es.create(
index=origin_index,
- id=media.pk,
+ id=str(media.pk),
document=source_document,
refresh=True,
)
@@ -172,7 +172,7 @@ class MediaFactory(DjangoModelFactory):
{
"_index": origin_index,
"_score": 1.0,
- "_id": media.pk,
+ "_id": str(media.pk),
"_source": source_document,
}
)
diff --git a/api/test/test_dead_link_filter.py b/api/test/test_dead_link_filter.py
index 6c3d4fc03..4c682dcc6 100644
--- a/api/test/test_dead_link_filter.py
+++ b/api/test/test_dead_link_filter.py
@@ -18,9 +18,6 @@ def redis(monkeypatch) -> FakeRedis:
def get_redis_connection(*args, **kwargs):
return fake_redis
- monkeypatch.setattr(
- "api.utils.dead_link_mask.get_redis_connection", get_redis_connection
- )
monkeypatch.setattr("django_redis.get_redis_connection", get_redis_connection)
yield fake_redis
diff --git a/api/test/unit/conftest.py b/api/test/unit/conftest.py
index 6f41dc40b..f838fb619 100644
--- a/api/test/unit/conftest.py
+++ b/api/test/unit/conftest.py
@@ -7,6 +7,7 @@ from rest_framework.test import APIClient, APIRequestFactory
import pytest
from elasticsearch import Elasticsearch
+from fakeredis import FakeRedis
from api.serializers.audio_serializers import (
AudioSearchRequestSerializer,
@@ -22,6 +23,19 @@ from api.serializers.media_serializers import (
)
+def redis(monkeypatch) -> FakeRedis:
+ fake_redis = FakeRedis()
+
+ def get_redis_connection(*args, **kwargs):
+ return fake_redis
+
+ monkeypatch.setattr("django_redis.get_redis_connection", get_redis_connection)
+
+ yield fake_redis
+ fake_redis.client().close()
+
+
@pytest.fixture
def api_client():
return APIClient()
@@ -54,8 +68,8 @@ class MediaTypeConfig:
model_serializer: MediaSerializer
-MEDIA_TYPE_CONFIGS = (
- MediaTypeConfig(
+MEDIA_TYPE_CONFIGS = {
+ "image": MediaTypeConfig(
media_type="image",
url_prefix="images",
origin_index="image",
@@ -65,7 +79,7 @@ MEDIA_TYPE_CONFIGS = (
search_request_serializer=ImageSearchRequestSerializer,
model_serializer=ImageSerializer,
),
- MediaTypeConfig(
+ "audio": MediaTypeConfig(
media_type="audio",
url_prefix="audio",
origin_index="audio",
@@ -75,11 +89,22 @@ MEDIA_TYPE_CONFIGS = (
search_request_serializer=AudioSearchRequestSerializer,
model_serializer=AudioSerializer,
),
-)
+}
+
+
+def image_media_type_config():
+ return MEDIA_TYPE_CONFIGS["image"]
+
+
+def audio_media_type_config():
+ return MEDIA_TYPE_CONFIGS["audio"]
@pytest.fixture(
- params=MEDIA_TYPE_CONFIGS, ids=lambda x: f"{x.media_type}_media_type_config"
+ params=MEDIA_TYPE_CONFIGS.values(),
+ ids=lambda x: f"{x.media_type}_media_type_config",
)
def media_type_config(request: pytest.FixtureRequest) -> MediaTypeConfig:
return request.param
diff --git a/api/test/unit/controllers/test_search_controller.py b/api/test/unit/controllers/test_search_controller.py
index bc38c0940..21feb62d1 100644
--- a/api/test/unit/controllers/test_search_controller.py
+++ b/api/test/unit/controllers/test_search_controller.py
@@ -1,9 +1,16 @@
import random
+import re
from collections.abc import Callable
from enum import Enum, auto
+from test.factory.es_http import (
+ MOCK_DEAD_RESULT_URL_PREFIX,
+ MOCK_LIVE_RESULT_URL_PREFIX,
+ create_mock_es_http_image_search_response,
+)
from unittest import mock
from uuid import uuid4
+import pook
import pytest
from django_redis import get_redis_connection
from elasticsearch_dsl import Search
@@ -11,6 +18,7 @@ from elasticsearch_dsl import Search
from api.controllers import search_controller
from api.utils import tallies
from api.utils.dead_link_mask import get_query_hash, save_query_mask
+from api.utils.search_context import SearchContext
pytestmark = pytest.mark.django_db
@@ -539,3 +547,212 @@ def test_resolves_index(
)
search_class.assert_called_once_with(index=searched_index)
+
+
+ "api.controllers.search_controller._post_process_results",
+ wraps=search_controller._post_process_results,
+)
[email protected]("api.controllers.search_controller.SearchContext")
+def test_no_post_process_results_recursion(
+ mock_search_context,
+ wrapped_post_process_results,
+ image_media_type_config,
+ settings,
+ # request the redis mock to auto-clean Redis between each test run
+ # otherwise the dead link query mask causes test details to leak
+ # between each run
+ redis,
+):
+ # Search context does not matter for this test, so we can mock it
+ # to avoid needing to account for additional ES requests
+ mock_search_context.build.return_value = SearchContext(set(), set())
+
+ hit_count = 5
+ mock_es_response = create_mock_es_http_image_search_response(
+ index=image_media_type_config.origin_index,
+ total_hits=45,
+ hit_count=hit_count,
+ )
+
+ es_host = settings.ES.transport.kwargs["host"]
+ es_port = settings.ES.transport.kwargs["port"]
+
+ # `origin_index` enforced by passing `exact_index=True` below.
+ es_endpoint = (
+ f"http://{es_host}:{es_port}/{image_media_type_config.origin_index}/_search"
+ )
+
+ mock_search = pook.post(es_endpoint).times(1).reply(200).json(mock_es_response).mock
+
+ # Ensure dead link filtering does not remove any results
+ pook.head(
+ pook.regex(rf"{MOCK_LIVE_RESULT_URL_PREFIX}/\d"),
+ ).times(
+ hit_count
+ ).reply(200)
+
+ serializer = image_media_type_config.search_request_serializer(
+ # This query string does not matter, ultimately, as pook is mocking
+ # the ES response regardless of the input
+ data={"q": "bird perched"}
+ )
+ serializer.is_valid()
+ results, _, _, _ = search_controller.search(
+ search_params=serializer,
+ ip=0,
+ origin_index=image_media_type_config.origin_index,
+ exact_index=True,
+ page=3,
+ page_size=20,
+ filter_dead=True,
+ )
+
+ assert {r["_source"]["identifier"] for r in mock_es_response["hits"]["hits"]} == {
+ r.identifier for r in results
+ }
+
+ assert wrapped_post_process_results.call_count == 1
+ assert mock_search.total_matches == 1
+
+
+ # both scenarios force `post_process_results`
+ # to recurse to fill the page due to the dead link
+ # configuration present in the test body
+ "page, page_size, mock_total_hits",
+ # Note the following
+ # - DEAD_LINK_RATIO causes all query sizes to start at double the page size
+ # - The test function is configured so that each request only returns 2 live
+ # results
+ # - We clear the redis cache between each test, meaning there is no query-based
+ # dead link mask. This forces `from` to 0 for each case.
+ # - Recursion should only continue while results still exist that could fulfill
+ # the requested page size. Once the available hits are exhaused, the function
+ # should stop recursing. This is why exceeding or matching the available
+ # hits is significant.
+ (
+ # First request: from: 0, size: 10
+ # Second request: from: 0, size: 15, exceeds max results
+ pytest.param(1, 5, 12, id="first_page"),
+ # First request: from: 0, size: 22
+ # Second request: from 0, size: 33, exceeds max results
+ pytest.param(3, 4, 32, id="last_page"),
+ # First request: from: 0, size: 22
+ # Second request: from 0, size: 33, matches max results
+ pytest.param(3, 4, 33, id="last_page_with_exact_max_results"),
+ ),
+)
+ "api.controllers.search_controller._post_process_results",
+ wraps=search_controller._post_process_results,
+)
[email protected]("api.controllers.search_controller.SearchContext")
+def test_post_process_results_recurses_as_needed(
+ mock_search_context,
+ wrapped_post_process_results,
+ image_media_type_config,
+ settings,
+ page,
+ page_size,
+ mock_total_hits,
+ # request the redis mock to auto-clean Redis between each test run
+ # otherwise the dead link query mask causes test details to leak
+ # between each run
+ redis,
+):
+ # Search context does not matter for this test, so we can mock it
+ # to avoid needing to account for additional ES requests
+ mock_search_context.build.return_value = SearchContext(set(), set())
+
+ mock_es_response_1 = create_mock_es_http_image_search_response(
+ index=image_media_type_config.origin_index,
+ total_hits=mock_total_hits,
+ hit_count=10,
+ live_hit_count=2,
+ )
+
+ mock_es_response_2 = create_mock_es_http_image_search_response(
+ index=image_media_type_config.origin_index,
+ total_hits=mock_total_hits,
+ hit_count=4,
+ live_hit_count=2,
+ base_hits=mock_es_response_1["hits"]["hits"],
+ )
+
+ es_host = settings.ES.transport.kwargs["host"]
+ es_port = settings.ES.transport.kwargs["port"]
+
+ # `origin_index` enforced by passing `exact_index=True` below.
+ es_endpoint = (
+ f"http://{es_host}:{es_port}/{image_media_type_config.origin_index}/_search"
+ )
+
+ # `from` is always 0 if there is no query mask
+ # see `_paginate_with_dead_link_mask` branch 1
+ # Testing this with a query mask would introduce far more complexity
+ # with no significant benefit
+ re.compile('from":0')
+
+ mock_first_es_request = (
+ pook.post(es_endpoint)
+ # The dead link ratio causes the initial query size to double
+ .body(re.compile(f'size":{(page_size * page) * 2}'))
+ .body(re.compile('from":0'))
+ .times(1)
+ .reply(200)
+ .json(mock_es_response_1)
+ .mock
+ )
+
+ mock_second_es_request = (
+ pook.post(es_endpoint)
+ # Size is clamped to the total number of available hits
+ .body(re.compile(f'size":{mock_total_hits}'))
+ .body(re.compile('from":0'))
+ .times(1)
+ .reply(200)
+ .json(mock_es_response_2)
+ .mock
+ )
+
+ live_results = [
+ r
+ for r in mock_es_response_2["hits"]["hits"]
+ if r["_source"]["url"].startswith(MOCK_LIVE_RESULT_URL_PREFIX)
+ ]
+
+ pook.head(pook.regex(rf"{MOCK_LIVE_RESULT_URL_PREFIX}/\d")).times(
+ len(live_results)
+ ).reply(200)
+
+ pook.head(pook.regex(rf"{MOCK_DEAD_RESULT_URL_PREFIX}/\d")).times(
+ len(mock_es_response_2["hits"]["hits"]) - len(live_results)
+ ).reply(400)
+
+ serializer = image_media_type_config.search_request_serializer(
+ # This query string does not matter, ultimately, as pook is mocking
+ # the ES response regardless of the input
+ data={"q": "bird perched"}
+ )
+ serializer.is_valid()
+ results, _, _, _ = search_controller.search(
+ search_params=serializer,
+ ip=0,
+ origin_index=image_media_type_config.origin_index,
+ exact_index=True,
+ page=page,
+ page_size=page_size,
+ filter_dead=True,
+ )
+
+ assert mock_first_es_request.total_matches == 1
+ assert mock_second_es_request.total_matches == 1
+
+ assert {r["_source"]["identifier"] for r in live_results} == {
+ r.identifier for r in results
+ }
+
+ assert wrapped_post_process_results.call_count == 2