Skip to content

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

Fail the data refresh counts when shards fail and count every source (#5858)

Olga Bulatba0f5e73a379
diff --git a/catalog/dags/common/elasticsearch.py b/catalog/dags/common/elasticsearch.py
index 982d7bd8d..5bf8aba4e 100644
--- a/catalog/dags/common/elasticsearch.py
+++ b/catalog/dags/common/elasticsearch.py
@@ -15,6 +15,29 @@ from common.constants import REFRESH_POKE_INTERVAL
logger = logging.getLogger(__name__)
+# More buckets than any media type has sources, so every source is counted.
+SOURCE_COUNT_BUCKETS = 1000
+
+
+class IncompleteResponseError(Exception):
+ """
+ Some shards failed to answer, so counts in the response are too low. A plain
+ exception, so that the task's retries ask again.
+ """
+
+
+def raise_for_failed_shards(response, action: str) -> None:
+ """
+ Raise if some shards failed to answer. Elasticsearch still answers with 200
+ and counts only the documents on the shards that did.
+ """
+ shards = response["_shards"]
+ if shards["failed"]:
+ raise IncompleteResponseError(
+ f"{action}: {shards['failed']} of {shards['total']} shards failed. "
+ f"First failures: {shards.get('failures', [])[:3]}"
+ )
+
# Index settings that should not be copied over from the base configuration when
# creating a new index.
@@ -114,7 +137,14 @@ def get_record_count_group_by_sources(es_host: str, index: str):
Return a dict where the keys are the sources, and the values are the counts.
Calls Elasticsearch to run an aggs query to do a count grouped by the field "source", and parses the result into a dict.
"""
- body = {"aggs": {"unique_sources": {"terms": {"field": "source"}}}}
+ body = {
+ "size": 0,
+ "aggs": {
+ "unique_sources": {
+ "terms": {"field": "source", "size": SOURCE_COUNT_BUCKETS}
+ }
+ },
+ }
# Unfornately the ElasticsearchPythonHook's search function doesn't work with aggs, because it returns the "hits" key only
# See source code at https://airflow.apache.org/docs/apache-airflow-providers-elasticsearch/stable/_modules/airflow/providers/elasticsearch/hooks/elasticsearch.html#ElasticsearchPythonHook
@@ -126,14 +156,21 @@ def get_record_count_group_by_sources(es_host: str, index: str):
logger.warning(f"Elasticsearch index: {index} does not exist. Error msg: {err}")
return {}
+ raise_for_failed_shards(es_result, f"Counting the sources of {index}")
+ aggregation = es_result["aggregations"]["unique_sources"]
+ if aggregation["sum_other_doc_count"]:
+ raise AirflowFailException(
+ f"{index} has more than {SOURCE_COUNT_BUCKETS} sources, so "
+ f"{aggregation['sum_other_doc_count']} documents were left out of the "
+ "counts. Raise SOURCE_COUNT_BUCKETS."
+ )
+
# es_buckets object looks like: [{'key': 'flickr', 'doc_count': 2500}, {'key': 'stocksnap', 'doc_count': 2500}]
- es_buckets = es_result["aggregations"]["unique_sources"]["buckets"]
- result = {
- source_count["key"]: source_count["doc_count"] for source_count in es_buckets
+ return {
+ source_count["key"]: source_count["doc_count"]
+ for source_count in aggregation["buckets"]
}
- return result
-
@task
def create_index(index_config, es_host: str, exist_ok: bool = False):
@@ -564,8 +601,12 @@ def assert_same_document_count(es_host: str, index: str, other_index: str) -> in
Both counts only include refreshed documents.
"""
es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn
- count = es_conn.count(index=index)["count"]
- other_count = es_conn.count(index=other_index)["count"]
+ response = es_conn.count(index=index)
+ raise_for_failed_shards(response, f"Counting {index}")
+ count = response["count"]
+ other_response = es_conn.count(index=other_index)
+ raise_for_failed_shards(other_response, f"Counting {other_index}")
+ other_count = other_response["count"]
if count != other_count:
raise AirflowFailException(
f"{index} has {count} documents, but {other_index} has {other_count}."
diff --git a/catalog/tests/dags/common/test_elasticsearch.py b/catalog/tests/dags/common/test_elasticsearch.py
index 3d08dc7a1..28f88a85f 100644
--- a/catalog/tests/dags/common/test_elasticsearch.py
+++ b/catalog/tests/dags/common/test_elasticsearch.py
@@ -463,7 +463,9 @@ def test_wait_for_delete_by_query_fails_with_its_group(monkeypatch):
)
def test_assert_same_document_count(monkeypatch, counts, should_fail):
es_conn = mock.Mock()
- es_conn.count.side_effect = [{"count": count} for count in counts]
+ es_conn.count.side_effect = [
+ {"count": count, "_shards": _shards()} for count in counts
+ ]
_hook(monkeypatch, es_conn)
if should_fail:
@@ -478,3 +480,83 @@ def test_assert_same_document_count(monkeypatch, counts, should_fail):
)
== 10
)
+
+
+def _shards(failed: int = 0) -> dict:
+ failures = [{"shard": 3, "reason": {"type": "es_rejected_execution_exception"}}]
+ return {
+ "total": 18,
+ "successful": 18 - failed,
+ "skipped": 0,
+ "failed": failed,
+ **({"failures": failures * failed} if failed else {}),
+ }
+
+
+def test_assert_same_document_count_fails_on_failed_shards(monkeypatch):
+ es_conn = mock.Mock()
+ es_conn.count.side_effect = [
+ {"count": 10, "_shards": _shards()},
+ {"count": 9, "_shards": _shards(failed=1)},
+ ]
+ _hook(monkeypatch, es_conn)
+
+ with pytest.raises(es.IncompleteResponseError, match="1 of 18 shards failed"):
+ es.assert_same_document_count.function(
+ "http://es:9200", "image-new", "image-new-filtered"
+ )
+
+
+def _source_count_response(failed: int = 0, sum_other_doc_count: int = 0) -> dict:
+ return {
+ "_shards": _shards(failed),
+ "aggregations": {
+ "unique_sources": {
+ "sum_other_doc_count": sum_other_doc_count,
+ "buckets": [
+ {"key": "flickr", "doc_count": 2500},
+ {"key": "stocksnap", "doc_count": 100},
+ ],
+ }
+ },
+ }
+
+
+def test_get_record_count_group_by_sources(monkeypatch):
+ es_conn = mock.Mock()
+ es_conn.search.return_value = _source_count_response()
+ _hook(monkeypatch, es_conn)
+
+ counts = es.get_record_count_group_by_sources.function("http://es:9200", "image")
+
+ assert counts == {"flickr": 2500, "stocksnap": 100}
+ aggregation = es_conn.search.call_args.kwargs["body"]["aggs"]["unique_sources"]
+ assert aggregation["terms"]["size"] == es.SOURCE_COUNT_BUCKETS
+
+
+ "response, error, match",
+ [
+ pytest.param(
+ _source_count_response(failed=3),
+ es.IncompleteResponseError,
+ "3 of 18 shards failed",
+ id="failed_shards",
+ ),
+ pytest.param(
+ _source_count_response(sum_other_doc_count=40),
+ AirflowFailException,
+ "40 documents were left out",
+ id="more_sources_than_buckets",
+ ),
+ ],
+)
+def test_get_record_count_group_by_sources_fails_on_incomplete_counts(
+ monkeypatch, response, error, match
+):
+ es_conn = mock.Mock()
+ es_conn.search.return_value = response
+ _hook(monkeypatch, es_conn)
+
+ with pytest.raises(error, match=match):
+ es.get_record_count_group_by_sources.function("http://es:9200", "image")