Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Make the data refresh ride out an overloaded Elasticsearch cluster (#5830)
Olga Bulat2fcbcc32a581
diff --git a/catalog/dags/common/elasticsearch.py b/catalog/dags/common/elasticsearch.pyindex 97e80a254..5e3845f97 100644--- a/catalog/dags/common/elasticsearch.py+++ b/catalog/dags/common/elasticsearch.py@@ -1,12 +1,15 @@+import jsonimport logging+import timefrom datetime import timedeltafrom typing import Literalfrom airflow.decorators import task, task_groupfrom airflow.exceptions import AirflowFailException, AirflowSkipException+from airflow.models import BaseOperatorfrom airflow.models.connection import Connectionfrom airflow.providers.elasticsearch.hooks.elasticsearch import ElasticsearchPythonHook-from airflow.sensors.base import PokeReturnValue+from airflow.providers.standard.triggers.temporal import TimeDeltaTriggerfrom elasticsearch.exceptions import NotFoundErrorfrom common.constants import REFRESH_POKE_INTERVAL@@ -19,6 +22,19 @@ logger = logging.getLogger(__name__)# creating a new index.EXCLUDED_INDEX_SETTINGS = {"provided_name", "creation_date", "uuid", "version"}+# Reindex errors caused by an overloaded cluster rather than by the data: rejected+# searches or writes, a tripped memory circuit breaker, or a scroll lost while+# shards were busy. A reindex that fails only with these is restarted.+OVERLOAD_REINDEX_ERRORS = (+ "es_rejected_execution_exception",+ "circuit_breaking_exception",+ "search_context_missing_exception",+ "No search context found",+)+REINDEX_MAX_RESTARTS = 5+# Doubles on each restart: 10, 20, 40, 80 and 160 minutes+REINDEX_RESTART_BACKOFF = timedelta(minutes=10)+@taskdef get_es_host(environment: str):@@ -124,26 +140,41 @@ def get_record_count_group_by_sources(es_host: str, index: str):@task-def create_index(index_config, es_host: str):+def create_index(index_config, es_host: str, exist_ok: bool = False):+ """+ Create the index described by ``index_config``.++ With ``exist_ok``, an index of that name left by an earlier attempt is reused,+ so that clearing a failed run continues filling it. An index that an alias+ points to is in use, so it is never reused.+ """es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn+ index_name = index_config["index"]++ if exist_ok and es_conn.indices.exists(index=index_name):+ if aliases := es_conn.indices.get_alias(index=index_name)[index_name].get(+ "aliases"+ ):+ raise AirflowFailException(+ f"Index {index_name} already exists and is aliased by "+ f"{list(aliases)}, so it cannot be reused."+ )+ logger.info(f"Reusing the existing index {index_name}.")+ returnnew_index = es_conn.indices.create(**index_config).bodyreturn new_index-def raise_for_reindex_failure(response: dict) -> None:+def get_reindex_failure_reasons(response: dict) -> dict:"""- Raise if a finished reindex task failed.+ Return why a finished reindex task failed, or an empty dict if it succeeded.A reindex run with ``wait_for_completion=False`` still reports ``completed`` whenit fails, with the cause in ``error`` (for example, an expired scroll),``response.failures`` (rejected documents), ``response.canceled`` (cancelledthrough the tasks API) or ``response.timed_out``.-- Raises ``AirflowFailException`` so the sensor does not retry: polling the same- finished ES task again cannot succeed. To recover, clear the whole- ``trigger_and_wait_for_reindex`` group so the reindex is triggered again."""body = response.get("response", {})reasons = {@@ -152,14 +183,241 @@ def raise_for_reindex_failure(response: dict) -> None:"canceled": body.get("canceled"),"timed_out": body.get("timed_out"),}- reasons = {key: value for key, value in reasons.items() if value}- if reasons:+ return {key: value for key, value in reasons.items() if value}+++def raise_for_reindex_failure(response: dict) -> None:+ """+ Raise if a finished reindex task failed.++ Raises ``AirflowFailException`` so the task does not retry: polling the same+ finished ES task again cannot succeed. To recover, clear the whole+ ``trigger_and_wait_for_reindex`` group so the reindex is triggered again.+ """+ if reasons := get_reindex_failure_reasons(response):raise AirflowFailException(f"Reindex failed: {reasons}. Clear the trigger_and_wait_for_reindex ""task group to trigger the reindex again.")+def _is_overload_failure(failure: dict) -> bool:+ text = json.dumps(failure, default=str)+ return '"status": 429' in text or any(+ marker in text for marker in OVERLOAD_REINDEX_ERRORS+ )+++def is_retryable_reindex_failure(response: dict) -> bool:+ """+ Whether a finished reindex failed only because the cluster was overloaded, so+ restarting it later can succeed.++ A reindex that was cancelled or timed out, or that has any other kind of+ failure (such as a mapping error), is not retryable.+ """+ body = response.get("response", {})+ if body.get("canceled") or body.get("timed_out"):+ return False+ failures = [response["error"]] if response.get("error") else []+ failures += body.get("failures") or []+ return bool(failures) and all(_is_overload_failure(f) for f in failures)+++def start_reindex(+ es_conn,+ destination_index: str,+ source_index: str,+ query: dict | None,+ requests_per_second: int,+ max_docs: int | None,+ slices: int | Literal["auto"] | None,+ refresh: bool,+) -> str:+ """Start a reindex without waiting for it, and return its ES task ID."""+ source = {"index": source_index}+ # An empty query is not accepted; only pass it+ # if a query was actually supplied+ if query:+ source["query"] = query++ response = es_conn.reindex(+ source=source,+ # Only create documents that are missing from the destination, so that a+ # restarted reindex skips the ones an earlier attempt already copied.+ dest={"index": destination_index, "op_type": "create"},+ # Skipped documents are reported as version conflicts; count them+ # instead of failing on them.+ conflicts="proceed",+ max_docs=max_docs,+ # Parallelize indexing when not None+ slices=slices,+ # The default 5m scroll keep-alive expires while slow bulk writes to the+ # destination index hold up a slice, failing the whole reindex with+ # "No search context found".+ scroll="1h",+ # Do not hold the slot while awaiting completion+ wait_for_completion=False,+ # Whether to immediately refresh the index after completion to make+ # the data available for search+ refresh=refresh,+ # Throttle+ requests_per_second=requests_per_second,+ )+ return response["task"]+++class WaitForReindexOperator(BaseOperator):+ """+ Wait for a reindex started by ``trigger_reindex``, restarting it when it fails+ because the cluster is overloaded.++ It defers between checks, which frees the worker slot and carries the current+ ES task ID from one check to the next. Each restart waits twice as long as the+ one before, and only creates the documents that are still missing.+ """++ template_fields = ("es_host", "reindex")++ def __init__(+ self,+ *,+ es_host: str,+ reindex: dict,+ reindex_timeout: timedelta,+ poke_interval: int = REFRESH_POKE_INTERVAL,+ max_restarts: int = REINDEX_MAX_RESTARTS,+ restart_backoff: timedelta = REINDEX_RESTART_BACKOFF,+ **kwargs,+ ):+ super().__init__(**kwargs)+ self.es_host = es_host+ # The output of `trigger_reindex`: the ES task ID and the reindex arguments+ self.reindex = reindex+ self.reindex_timeout = reindex_timeout+ self.poke_interval = poke_interval+ self.max_restarts = max_restarts+ self.restart_backoff = restart_backoff++ def execute(self, context):+ deadline = time.time() + self.reindex_timeout.total_seconds()+ self.check_reindex(+ context,+ es_task_id=self.reindex["es_task_id"],+ restarts=0,+ created_before=0,+ deadline=deadline,+ )++ def check_reindex(+ self,+ context,+ event=None,+ *,+ es_task_id: str,+ restarts: int,+ created_before: int,+ deadline: float,+ ):+ """+ Check the reindex task, and defer until the next check, defer until a+ restart, or finish.++ ``created_before`` is the number of documents earlier attempts created.+ """+ es_conn = ElasticsearchPythonHook(hosts=[self.es_host]).get_conn+ response = es_conn.tasks.get(task_id=es_task_id)+ status = response.get("task", {}).get("status", {})+ created = created_before + (status.get("created") or 0)+ logger.info(+ f"Reindex task {es_task_id}: {created} documents created so far, "+ f"{status.get('version_conflicts') or 0} already present, "+ f"{restarts} restarts."+ )++ if not response.get("completed"):+ if time.time() > deadline:+ raise AirflowFailException(+ f"Reindex did not finish within {self.reindex_timeout}."+ )+ self._defer(+ "check_reindex",+ timedelta(seconds=self.poke_interval),+ es_task_id=es_task_id,+ restarts=restarts,+ created_before=created_before,+ deadline=deadline,+ )++ if not get_reindex_failure_reasons(response):+ expected_docs = self.reindex["kwargs"].get("max_docs")+ if expected_docs and created != expected_docs:+ logger.info(+ f"Reindexed {created} documents, but {expected_docs} were expected."+ )+ else:+ logger.info(f"Reindexed {created} documents.")+ return++ if restarts < self.max_restarts and is_retryable_reindex_failure(response):+ backoff = self.restart_backoff * 2**restarts+ logger.warning(+ "Reindex failed because the cluster is overloaded: "+ f"{get_reindex_failure_reasons(response)}. Restarting in {backoff} "+ f"(restart {restarts + 1} of {self.max_restarts})."+ )+ self._defer(+ "restart_reindex",+ backoff,+ restarts=restarts + 1,+ created_before=created,+ deadline=deadline,+ )++ raise_for_reindex_failure(response)++ def restart_reindex(+ self,+ context,+ event=None,+ *,+ restarts: int,+ created_before: int,+ deadline: float,+ ):+ if time.time() > deadline:+ raise AirflowFailException(+ f"Reindex did not finish within {self.reindex_timeout}."+ )++ reindex_kwargs = dict(self.reindex["kwargs"])+ if max_docs := reindex_kwargs.get("max_docs"):+ # The earlier attempts already created some of the requested documents+ reindex_kwargs["max_docs"] = max_docs - created_before+ if reindex_kwargs["max_docs"] <= 0:+ logger.info(f"Reindexed {created_before} documents.")+ return++ es_conn = ElasticsearchPythonHook(hosts=[self.es_host]).get_conn+ es_task_id = start_reindex(es_conn, **reindex_kwargs)+ logger.info(f"Restarted the reindex as task {es_task_id}.")+ self._defer(+ "check_reindex",+ timedelta(seconds=self.poke_interval),+ es_task_id=es_task_id,+ restarts=restarts,+ created_before=created_before,+ deadline=deadline,+ )++ def _defer(self, method_name: str, delay: timedelta, **kwargs):+ self.defer(+ trigger=TimeDeltaTrigger(delay),+ method_name=method_name,+ kwargs=kwargs,+ )++@task_group(group_id="trigger_and_wait_for_reindex")def trigger_and_wait_for_reindex(es_host: str,@@ -170,7 +428,7 @@ def trigger_and_wait_for_reindex(query: dict | None = None,max_docs: int | None = None,refresh: bool = True,- slices: int | Literal["auto"] = "auto",+ slices: int | Literal["auto"] | None = "auto",poke_interval: int = REFRESH_POKE_INTERVAL,):@task@@ -181,58 +439,21 @@ def trigger_and_wait_for_reindex(query: dict,requests_per_second: int,max_docs: int | None,- slices: int | Literal["auto"],+ slices: int | Literal["auto"] | None,):+ reindex_kwargs = {+ "destination_index": destination_index,+ "source_index": source_index,+ "query": query,+ "requests_per_second": requests_per_second,+ "max_docs": max_docs,+ "slices": slices,+ "refresh": refresh,+ }es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn- source = {"index": source_index}- # An empty query is not accepted; only pass it- # if a query was actually supplied- if query:- source["query"] = query-- response = es_conn.reindex(- source=source,- dest={"index": destination_index},- max_docs=max_docs,- # Parallelize indexing when not None- slices=slices,- # The default 5m scroll keep-alive expires while slow bulk writes to the- # destination index hold up a slice, failing the whole reindex with- # "No search context found".- scroll="1h",- # Do not hold the slot while awaiting completion- wait_for_completion=False,- # Whether to immediately refresh the index after completion to make- # the data available for search- refresh=refresh,- # Throttle- requests_per_second=requests_per_second,- )- return response["task"]-- @task.sensor(- poke_interval=REFRESH_POKE_INTERVAL, timeout=timeout, mode="reschedule"- )- def wait_for_reindex(- es_host: str, task_id: str, expected_docs: int | None = None- ) -> PokeReturnValue:- es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn-- response = es_conn.tasks.get(task_id=task_id)- logger.info(response)-- count = response.get("task", {}).get("status", {}).get("total")- if expected_docs and count != expected_docs:- logger.info(- f"Reindexed {count} documents, but {expected_docs} were expected."- )- else:- logger.info(f"Reindexed {count} documents.")-- is_done = response.get("completed") is True- if is_done:- raise_for_reindex_failure(response)- return PokeReturnValue(is_done=is_done)+ es_task_id = start_reindex(es_conn, **reindex_kwargs)+ # Return the rendered arguments too, so a restart uses the same ones+ return {"es_task_id": es_task_id, "kwargs": reindex_kwargs}trigger_reindex_task = trigger_reindex(es_host,@@ -244,12 +465,14 @@ def trigger_and_wait_for_reindex(slices,)- wait_for_reindex_task = wait_for_reindex.override(poke_interval=poke_interval)(- task_id=trigger_reindex_task, expected_docs=max_docs, es_host=es_host+ WaitForReindexOperator(+ task_id="wait_for_reindex",+ es_host=es_host,+ reindex=trigger_reindex_task,+ reindex_timeout=timeout,+ poke_interval=poke_interval,)- trigger_reindex_task >> wait_for_reindex_task-@taskdef refresh_index(es_host: str, index_name: str):diff --git a/catalog/dags/data_refresh/create_and_populate_filtered_index.py b/catalog/dags/data_refresh/create_and_populate_filtered_index.pyindex b263183ef..5d606057e 100644--- a/catalog/dags/data_refresh/create_and_populate_filtered_index.py+++ b/catalog/dags/data_refresh/create_and_populate_filtered_index.py@@ -65,6 +65,9 @@ def create_and_populate_filtered_index("body": index_settings(media_type),},es_host=es_host,+ # A cleared run fills the index a failed attempt left, skipping the+ # documents already in it.+ exist_ok=True,)sensitive_terms = HttpOperator(@@ -81,6 +84,11 @@ def create_and_populate_filtered_index(source_index=origin_index_name,timeout=timeout,requests_per_second="{{ var.value.get('ES_INDEX_THROTTLING_RATE', 20_000) }}",+ # The number of scrolls that read the origin index in parallel. "auto" uses+ # one per shard. With fewer slices than shards, each slice still sends its+ # searches to every shard, so ES_INDEX_THROTTLING_RATE is the more direct+ # way to reduce load.+ slices="{{ var.value.get('ES_FILTERED_INDEX_REINDEX_SLICES', 'auto') }}",query={"bool": {"must_not": [diff --git a/catalog/tests/dags/common/test_elasticsearch.py b/catalog/tests/dags/common/test_elasticsearch.pyindex 0d60aa57b..39dfe6166 100644--- a/catalog/tests/dags/common/test_elasticsearch.py+++ b/catalog/tests/dags/common/test_elasticsearch.py@@ -1,7 +1,19 @@+import time+from datetime import timedelta+from types import SimpleNamespace+from unittest import mock+import pytest-from airflow.exceptions import AirflowFailException+from airflow.exceptions import AirflowFailException, TaskDeferred+from airflow.utils import timezone-from common.elasticsearch import raise_for_reindex_failure+from common import elasticsearch as es+from common.elasticsearch import (+ REINDEX_RESTART_BACKOFF,+ WaitForReindexOperator,+ is_retryable_reindex_failure,+ raise_for_reindex_failure,+)@pytest.mark.parametrize(@@ -61,3 +73,232 @@ def test_raise_for_reindex_failure_passes(response):def test_raise_for_reindex_failure_raises(response):with pytest.raises(AirflowFailException, match="Reindex failed"):raise_for_reindex_failure(response)+++def _hook(monkeypatch, es_conn):+ monkeypatch.setattr(+ es, "ElasticsearchPythonHook", lambda hosts: SimpleNamespace(get_conn=es_conn)+ )+++def _task_response(completed=True, created=0, error=None, **body):+ response = {+ "completed": completed,+ "task": {"status": {"created": created, "version_conflicts": 0}},+ }+ if error:+ response["error"] = error+ if completed:+ response["response"] = {"failures": [], **body}+ return response+++REJECTED_SEARCH = {+ "type": "search_phase_execution_exception",+ "caused_by": {"type": "es_rejected_execution_exception", "reason": "rejected"},+}+LOST_SCROLL = {+ "type": "search_phase_execution_exception",+ "reason": "No search context found for id [42]",+}+REJECTED_DOC = {"index": "dest", "id": "1", "status": 429, "cause": {}}+MAPPING_ERROR = {+ "index": "dest",+ "id": "2",+ "status": 400,+ "cause": {"type": "mapper_parsing_exception"},+}+++ "response, expected",+ [+ pytest.param(_task_response(error=REJECTED_SEARCH), True, id="rejected_search"),+ pytest.param(_task_response(error=LOST_SCROLL), True, id="lost_scroll"),+ pytest.param(+ _task_response(failures=[REJECTED_DOC]), True, id="rejected_documents"+ ),+ pytest.param(+ _task_response(failures=[REJECTED_DOC, MAPPING_ERROR]),+ False,+ id="rejected_and_mapping_error",+ ),+ pytest.param(_task_response(failures=[MAPPING_ERROR]), False, id="mapping"),+ pytest.param(+ _task_response(error=REJECTED_SEARCH, canceled="by user request"),+ False,+ id="canceled",+ ),+ pytest.param(_task_response(timed_out=True), False, id="timed_out"),+ pytest.param(_task_response(), False, id="succeeded"),+ ],+)+def test_is_retryable_reindex_failure(response, expected):+ assert is_retryable_reindex_failure(response) is expected+++REINDEX_KWARGS = {+ "destination_index": "image-new-filtered",+ "source_index": "image-new",+ "query": {"match_all": {}},+ "requests_per_second": 20_000,+ "max_docs": None,+ "slices": "auto",+ "refresh": False,+}+++def _operator(max_docs=None, max_restarts=2):+ return WaitForReindexOperator(+ task_id="wait_for_reindex",+ es_host="http://es:9200",+ reindex={+ "es_task_id": "node:1",+ "kwargs": {**REINDEX_KWARGS, "max_docs": max_docs},+ },+ reindex_timeout=timedelta(hours=1),+ poke_interval=60,+ max_restarts=max_restarts,+ )+++def test_wait_for_reindex_defers_while_running(monkeypatch):+ es_conn = mock.Mock()+ es_conn.tasks.get.return_value = _task_response(completed=False, created=5)+ _hook(monkeypatch, es_conn)++ with pytest.raises(TaskDeferred) as deferred:+ _operator().execute({})++ assert deferred.value.method_name == "check_reindex"+ assert deferred.value.kwargs["es_task_id"] == "node:1"+ assert deferred.value.kwargs["restarts"] == 0+++def test_wait_for_reindex_finishes_on_success(monkeypatch):+ es_conn = mock.Mock()+ es_conn.tasks.get.return_value = _task_response(created=10)+ _hook(monkeypatch, es_conn)++ _operator().execute({})++ es_conn.reindex.assert_not_called()+++def test_wait_for_reindex_restarts_after_overload(monkeypatch):+ es_conn = mock.Mock()+ es_conn.tasks.get.return_value = _task_response(created=7, error=REJECTED_SEARCH)+ _hook(monkeypatch, es_conn)++ with pytest.raises(TaskDeferred) as deferred:+ _operator().execute({})++ assert deferred.value.method_name == "restart_reindex"+ assert deferred.value.kwargs["restarts"] == 1+ assert deferred.value.kwargs["created_before"] == 7+ wait = deferred.value.trigger.moment - timezone.utcnow()+ assert REINDEX_RESTART_BACKOFF - timedelta(minutes=1) < wait+ assert wait <= REINDEX_RESTART_BACKOFF+++ "max_docs, expected_max_docs", [(None, None), (100, 93)], ids=["all", "max_docs"]+)+def test_restart_reindex_creates_only_missing_documents(+ monkeypatch, max_docs, expected_max_docs+):+ es_conn = mock.Mock()+ es_conn.reindex.return_value = {"task": "node:2"}+ _hook(monkeypatch, es_conn)++ with pytest.raises(TaskDeferred) as deferred:+ _operator(max_docs=max_docs).restart_reindex(+ {}, restarts=1, created_before=7, deadline=time.time() + 60+ )++ reindex_call = es_conn.reindex.call_args.kwargs+ assert reindex_call["dest"] == {"index": "image-new-filtered", "op_type": "create"}+ assert reindex_call["conflicts"] == "proceed"+ assert reindex_call["max_docs"] == expected_max_docs+ assert deferred.value.method_name == "check_reindex"+ assert deferred.value.kwargs["es_task_id"] == "node:2"+ assert deferred.value.kwargs["created_before"] == 7+++def test_restart_reindex_skips_when_max_docs_reached(monkeypatch):+ es_conn = mock.Mock()+ _hook(monkeypatch, es_conn)++ _operator(max_docs=7).restart_reindex(+ {}, restarts=1, created_before=7, deadline=time.time() + 60+ )++ es_conn.reindex.assert_not_called()+++ "response, restarts",+ [+ pytest.param(_task_response(failures=[MAPPING_ERROR]), 0, id="not_retryable"),+ pytest.param(_task_response(error=REJECTED_SEARCH), 2, id="out_of_restarts"),+ ],+)+def test_wait_for_reindex_fails(monkeypatch, response, restarts):+ es_conn = mock.Mock()+ es_conn.tasks.get.return_value = response+ _hook(monkeypatch, es_conn)++ with pytest.raises(AirflowFailException, match="Reindex failed"):+ _operator(max_restarts=2).check_reindex(+ {},+ es_task_id="node:1",+ restarts=restarts,+ created_before=0,+ deadline=time.time() + 60,+ )+++def test_wait_for_reindex_fails_after_deadline(monkeypatch):+ es_conn = mock.Mock()+ es_conn.tasks.get.return_value = _task_response(completed=False)+ _hook(monkeypatch, es_conn)++ with pytest.raises(AirflowFailException, match="did not finish"):+ _operator().check_reindex(+ {},+ es_task_id="node:1",+ restarts=0,+ created_before=0,+ deadline=time.time() - 1,+ )+++ "exists, aliases, exist_ok, should_create",+ [+ pytest.param(False, {}, True, True, id="new_index"),+ pytest.param(True, {}, True, False, id="reuse_existing"),+ pytest.param(True, {}, False, True, id="existing_without_exist_ok"),+ ],+)+def test_create_index(monkeypatch, exists, aliases, exist_ok, should_create):+ es_conn = mock.Mock()+ es_conn.indices.exists.return_value = exists+ es_conn.indices.get_alias.return_value = {"image-new": {"aliases": aliases}}+ _hook(monkeypatch, es_conn)++ es.create_index.function({"index": "image-new"}, "http://es:9200", exist_ok)++ assert es_conn.indices.create.called is should_create+++def test_create_index_does_not_reuse_aliased_index(monkeypatch):+ es_conn = mock.Mock()+ es_conn.indices.exists.return_value = True+ es_conn.indices.get_alias.return_value = {"image-new": {"aliases": {"image": {}}}}+ _hook(monkeypatch, es_conn)++ with pytest.raises(AirflowFailException, match="aliased by"):+ es.create_index.function({"index": "image-new"}, "http://es:9200", True)++ es_conn.indices.create.assert_not_called()diff --git a/indexer_worker/indexer_worker/indexer.py b/indexer_worker/indexer_worker/indexer.pyindex 13bc5d42c..79350efd8 100644--- a/indexer_worker/indexer_worker/indexer.py+++ b/indexer_worker/indexer_worker/indexer.py@@ -1,6 +1,5 @@import logging as logimport time-from collections import dequeimport elasticsearchfrom decouple import config@@ -17,6 +16,14 @@ from indexer_worker.queries import get_reindex_query# The number of database records to load in memory at once.DB_BUFFER_SIZE = config("DB_BUFFER_SIZE", default=100000, cast=int)+# Bulk statuses that mean the cluster is overloaded or briefly unavailable, so+# the rejected docs are sent again after a backoff.+RETRYABLE_BULK_STATUSES = {429, 502, 503, 504}+# With the default backoff, 10 retries wait about 25 minutes in total.+BULK_MAX_RETRIES = config("BULK_MAX_RETRIES", default=10, cast=int)+BULK_INITIAL_BACKOFF = config("BULK_INITIAL_BACKOFF", default=5, cast=int) # seconds+BULK_MAX_BACKOFF = config("BULK_MAX_BACKOFF", default=300, cast=int) # seconds+def launch_reindex(model_name: str,@@ -107,10 +114,7 @@ def reindex(# Bulk upload to Elasticsearch in parallel.log.info(f"Pushing {len(es_batch)} docs to Elasticsearch.")push_start_time = time.time()- try:- _bulk_upload(es_conn, es_batch)- except ValueError:- log.error("Failed to index chunk.")+ _bulk_upload(es_conn, es_batch)upload_time = time.time() - push_start_timeupload_rate = len(es_batch) / upload_time@@ -154,26 +158,64 @@ def pg_chunk_to_es(pg_chunk, columns, model_name, target_index):return documents+class BulkUploadError(Exception):+ """Documents could not be indexed, so the worker must fail rather than skip them."""++def _bulk_upload(es_conn, es_batch):- max_attempts = 4- attempts = 0- # Initial time to wait between indexing attempts- # Grows exponentially- cooloff = 5- while True:- try:- deque(helpers.parallel_bulk(es_conn, es_batch, chunk_size=400))- except elasticsearch.ApiError:- # Something went wrong during indexing.+ """+ Index ``es_batch``, retrying the documents Elasticsearch rejects while overloaded.++ Only the rejected documents are sent again, with exponential backoff. Any other+ document failure, or a rejection that outlasts every retry, raises+ ``BulkUploadError`` so that no documents are silently left out of the index.+ """+ pending = es_batch+ for attempt in range(BULK_MAX_RETRIES + 1):+ if attempt:+ backoff = min(BULK_MAX_BACKOFF, BULK_INITIAL_BACKOFF * 2 ** (attempt - 1))log.warning(- f"Elasticsearch rejected bulk query. We will retry in"- f" {cooloff}s. Attempt {attempts}. Details: ",- exc_info=True,+ f"Elasticsearch rejected {len(pending)} docs. Retrying in {backoff}s "+ f"(retry {attempt} of {BULK_MAX_RETRIES})."+ )+ time.sleep(backoff)++ # Bulk responses return `_id` as a string+ pending_by_id = {str(doc["_id"]): doc for doc in pending}+ rejected = []+ failed = []+ try:+ for ok, item in helpers.parallel_bulk(+ es_conn,+ pending,+ chunk_size=400,+ raise_on_error=False,+ raise_on_exception=False,+ ):+ if ok:+ continue+ info = next(iter(item.values()))+ if info.get("status") in RETRYABLE_BULK_STATUSES:+ rejected.append(pending_by_id[str(info["_id"])])+ else:+ failed.append(+ {key: info.get(key) for key in ("_id", "status", "error")}+ )+ except elasticsearch.TransportError:+ # The connection failed, so it is unknown which docs were indexed.+ # Indexing a doc again is harmless, so retry all of them.+ log.warning("Bulk request to Elasticsearch failed.", exc_info=True)+ rejected = pending++ if failed:+ raise BulkUploadError(+ f"{len(failed)} docs failed to index. First failures: {failed[:5]}")- time.sleep(cooloff)- cooloff *= 2- if attempts >= max_attempts:- raise ValueError("Exceeded maximum bulk index retries")- attempts += 1- continue- break+ if not rejected:+ return+ pending = rejected++ raise BulkUploadError(+ f"Elasticsearch still rejected {len(pending)} docs after "+ f"{BULK_MAX_RETRIES} retries."+ )diff --git a/indexer_worker/tests/test_bulk_upload.py b/indexer_worker/tests/test_bulk_upload.pynew file mode 100644index 000000000..6791ba995--- /dev/null+++ b/indexer_worker/tests/test_bulk_upload.py@@ -0,0 +1,103 @@+import elastic_transport+import pytest++from indexer_worker import indexer+from indexer_worker.indexer import BulkUploadError, _bulk_upload+++DOCS = [{"_index": "image-test", "_id": doc_id, "title": "x"} for doc_id in (1, 2, 3)]+++def _item(doc_id, status):+ # Shaped like a bulk response item; `_id` comes back as a string+ return {"index": {"_index": "image-test", "_id": str(doc_id), "status": status}}+++def sleeps(monkeypatch):+ calls = []+ monkeypatch.setattr(indexer.time, "sleep", calls.append)+ return calls+++def bulk(monkeypatch):+ """+ Replace ``parallel_bulk`` with a fake that answers each call with the next+ scripted response: a dict of doc ID to status, or an exception to raise.+ """+ calls = []+ responses = []++ def fake_parallel_bulk(client, actions, **kwargs):+ actions = list(actions)+ calls.append([doc["_id"] for doc in actions])+ response = responses.pop(0)+ if isinstance(response, Exception):+ raise response+ for doc in actions:+ status = response.get(doc["_id"], 201)+ yield 200 <= status < 300, _item(doc["_id"], status)++ monkeypatch.setattr(indexer.helpers, "parallel_bulk", fake_parallel_bulk)+ return calls, responses+++def test_bulk_upload_succeeds_first_time(bulk, sleeps):+ calls, responses = bulk+ responses.append({})++ _bulk_upload(None, DOCS)++ assert calls == [[1, 2, 3]]+ assert sleeps == []+++def test_bulk_upload_retries_only_rejected_docs(bulk, sleeps):+ calls, responses = bulk+ responses.extend([{2: 429, 3: 503}, {3: 429}, {}])++ _bulk_upload(None, DOCS)++ assert calls == [[1, 2, 3], [2, 3], [3]]+ assert sleeps == [indexer.BULK_INITIAL_BACKOFF, indexer.BULK_INITIAL_BACKOFF * 2]+++def test_bulk_upload_retries_all_docs_after_connection_error(bulk, sleeps):+ calls, responses = bulk+ responses.extend([elastic_transport.ConnectionTimeout("timed out"), {}])++ _bulk_upload(None, DOCS)++ assert calls == [[1, 2, 3], [1, 2, 3]]+++def test_bulk_upload_fails_on_non_retryable_error(bulk, sleeps):+ calls, responses = bulk+ responses.append({2: 400})++ with pytest.raises(BulkUploadError, match="1 docs failed to index"):+ _bulk_upload(None, DOCS)++ assert len(calls) == 1+++def test_bulk_upload_fails_when_rejections_outlast_retries(bulk, sleeps, monkeypatch):+ monkeypatch.setattr(indexer, "BULK_MAX_RETRIES", 2)+ calls, responses = bulk+ responses.extend([{1: 429}] * 3)++ with pytest.raises(BulkUploadError, match="still rejected 1 docs after 2 retries"):+ _bulk_upload(None, DOCS)++ assert calls == [[1, 2, 3], [1], [1]]+++def test_bulk_upload_caps_backoff(bulk, sleeps, monkeypatch):+ monkeypatch.setattr(indexer, "BULK_MAX_BACKOFF", 12)+ calls, responses = bulk+ responses.extend([{1: 429}] * 3 + [{}])++ _bulk_upload(None, DOCS)++ assert sleeps == [5, 10, 12]