Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Build the filtered index on the indexer workers (#5849)
Olga Bulate4a1074490d0
diff --git a/catalog/dags/common/elasticsearch.py b/catalog/dags/common/elasticsearch.pyindex 807ec8308..982d7bd8d 100644--- a/catalog/dags/common/elasticsearch.py+++ b/catalog/dags/common/elasticsearch.py@@ -182,18 +182,22 @@ def get_reindex_failure_reasons(response: dict) -> dict:return {key: value for key, value in reasons.items() if value}-def raise_for_reindex_failure(response: dict) -> None:+def raise_for_reindex_failure(+ response: dict,+ action: str = "Reindex",+ group_id: str = "trigger_and_wait_for_reindex",+) -> None:"""- Raise if a finished reindex task failed.+ Raise if a finished reindex (or delete by query) 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.+ finished ES task again cannot succeed. To recover, clear the whole ``group_id``+ group so the task 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."+ f"{action} failed: {reasons}. Clear the {group_id} task group to "+ "trigger it again.")@@ -263,6 +267,27 @@ def start_reindex(return response["task"]+def start_delete_by_query(+ es_conn,+ index: str,+ query: dict,+ requests_per_second: int,+ slices: int | Literal["auto"] | None,+) -> str:+ """Start a delete by query without waiting for it, and return its ES task ID."""+ response = es_conn.delete_by_query(+ index=index,+ query=query,+ # A restarted delete finds only the documents an earlier attempt left+ conflicts="proceed",+ slices=slices,+ scroll="1h",+ wait_for_completion=False,+ 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@@ -274,6 +299,11 @@ class WaitForReindexOperator(BaseOperator):"""template_fields = ("es_host", "reindex")+ start = staticmethod(start_reindex)+ action = "Reindex"+ done = "Reindexed"+ count_field = "created"+ group_id_hint = "trigger_and_wait_for_reindex"def __init__(self,@@ -324,9 +354,10 @@ class WaitForReindexOperator(BaseOperator):es_conn = ElasticsearchPythonHook(hosts=[self.es_host]).get_connresponse = es_conn.tasks.get(task_id=es_task_id)status = response.get("task", {}).get("status", {})- created = created_before + (status.get("created") or 0)+ created = created_before + (status.get(self.count_field) or 0)logger.info(- f"Reindex task {es_task_id}: {created} documents created so far, "+ f"{self.action} task {es_task_id}: {created} documents "+ f"{self.count_field} so far, "f"{status.get('version_conflicts') or 0} already present, "f"{restarts} restarts.")@@ -334,7 +365,7 @@ class WaitForReindexOperator(BaseOperator):if not response.get("completed"):if time.time() > deadline:raise AirflowFailException(- f"Reindex did not finish within {self.reindex_timeout}."+ f"{self.action} did not finish within {self.reindex_timeout}.")self._defer("check_reindex",@@ -349,16 +380,17 @@ class WaitForReindexOperator(BaseOperator):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."+ f"{self.done} {created} documents, but {expected_docs} were "+ "expected.")else:- logger.info(f"Reindexed {created} documents.")+ logger.info(f"{self.done} {created} documents.")returnif restarts < self.max_restarts and is_retryable_reindex_failure(response):backoff = self.restart_backoff * 2**restartslogger.warning(- "Reindex failed because the cluster is overloaded: "+ f"{self.action} failed because the cluster is overloaded: "f"{get_reindex_failure_reasons(response)}. Restarting in {backoff} "f"(restart {restarts + 1} of {self.max_restarts}).")@@ -370,7 +402,7 @@ class WaitForReindexOperator(BaseOperator):deadline=deadline,)- raise_for_reindex_failure(response)+ raise_for_reindex_failure(response, self.action, self.group_id_hint)def restart_reindex(self,@@ -383,7 +415,7 @@ class WaitForReindexOperator(BaseOperator):):if time.time() > deadline:raise AirflowFailException(- f"Reindex did not finish within {self.reindex_timeout}."+ f"{self.action} did not finish within {self.reindex_timeout}.")reindex_kwargs = dict(self.reindex["kwargs"])@@ -391,12 +423,12 @@ class WaitForReindexOperator(BaseOperator):# The earlier attempts already created some of the requested documentsreindex_kwargs["max_docs"] = max_docs - created_beforeif reindex_kwargs["max_docs"] <= 0:- logger.info(f"Reindexed {created_before} documents.")+ logger.info(f"{self.done} {created_before} documents.")returnes_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}.")+ es_task_id = self.start(es_conn, **reindex_kwargs)+ logger.info(f"Restarted the {self.action.lower()} as task {es_task_id}.")self._defer("check_reindex",timedelta(seconds=self.poke_interval),@@ -470,6 +502,77 @@ def trigger_and_wait_for_reindex()+class WaitForDeleteByQueryOperator(WaitForReindexOperator):+ """+ Wait for a delete by query started by ``trigger_delete_by_query``, restarting+ it when it fails because the cluster is overloaded.+ """++ start = staticmethod(start_delete_by_query)+ action = "Delete by query"+ done = "Deleted"+ count_field = "deleted"+ group_id_hint = "trigger_and_wait_for_delete_by_query"+++@task_group(group_id="trigger_and_wait_for_delete_by_query")+def trigger_and_wait_for_delete_by_query(+ es_host: str,+ index: str,+ query: dict,+ timeout: timedelta,+ requests_per_second: int,+ slices: int | Literal["auto"] | None = "auto",+ poke_interval: int = REFRESH_POKE_INTERVAL,+):+ @task+ def trigger_delete_by_query(+ es_host: str,+ index: str,+ query: dict,+ requests_per_second: int,+ slices: int | Literal["auto"] | None,+ ):+ kwargs = {+ "index": index,+ "query": query,+ "requests_per_second": requests_per_second,+ "slices": slices,+ }+ es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn+ es_task_id = start_delete_by_query(es_conn, **kwargs)+ # Return the rendered arguments too, so a restart uses the same ones+ return {"es_task_id": es_task_id, "kwargs": kwargs}++ trigger_task = trigger_delete_by_query(+ es_host, index, query, requests_per_second, slices+ )++ WaitForDeleteByQueryOperator(+ task_id="wait_for_delete_by_query",+ es_host=es_host,+ reindex=trigger_task,+ reindex_timeout=timeout,+ poke_interval=poke_interval,+ )+++@task+def assert_same_document_count(es_host: str, index: str, other_index: str) -> int:+ """+ Fail unless both indices hold the same number of documents, and return it.+ 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"]+ if count != other_count:+ raise AirflowFailException(+ f"{index} has {count} documents, but {other_index} has {other_count}."+ )+ return count++@taskdef refresh_index(es_host: str, index_name: str):es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conndiff --git a/catalog/dags/data_refresh/create_and_populate_filtered_index.py b/catalog/dags/data_refresh/create_and_populate_filtered_index.pyindex 6234de66a..37504da09 100644--- a/catalog/dags/data_refresh/create_and_populate_filtered_index.py+++ b/catalog/dags/data_refresh/create_and_populate_filtered_index.py@@ -30,6 +30,27 @@ def response_filter_sensitive_terms_endpoint(response: Response) -> list[str]:return [term.decode("utf-8").strip() for term in response.iter_lines()]+def sensitive_terms_clauses(sensitive_terms) -> list[dict]:+ """+ One `terms` query per field that may hold sensitive terms. The `.raw` subfields+ use the standard analyzer, so a term matches one lowercased word of the field.+ """+ return [+ {"terms": {f"{field}.raw": sensitive_terms}}+ for field in ["tags.name", "title", "description"]+ ]+++def get_sensitive_terms() -> HttpOperator:+ return HttpOperator(+ task_id="get_sensitive_terms",+ http_conn_id=SENSITIVE_TERMS_CONN_ID,+ method="GET",+ response_check=lambda response: response.status_code == 200,+ response_filter=response_filter_sensitive_terms_endpoint,+ )++@task(trigger_rule=TriggerRule.NONE_FAILED)def get_filtered_index_name(media_type: str, destination_index_name: str) -> str:# If a destination index name is explicitly passed, use it.@@ -69,13 +90,7 @@ def create_and_populate_filtered_index(exist_ok=True,)- sensitive_terms = HttpOperator(- task_id="get_sensitive_terms",- http_conn_id=SENSITIVE_TERMS_CONN_ID,- method="GET",- response_check=lambda response: response.status_code == 200,- response_filter=response_filter_sensitive_terms_endpoint,- )+ sensitive_terms = get_sensitive_terms()populate_filtered_index = es.trigger_and_wait_for_reindex(es_host=es_host,@@ -88,15 +103,7 @@ def create_and_populate_filtered_index(# 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": [- # Use `terms` query for exact matching against unanalyzed raw fields- {"terms": {f"{field}.raw": sensitive_terms.output}}- for field in ["tags.name", "title", "description"]- ]- }- },+ query={"bool": {"must_not": sensitive_terms_clauses(sensitive_terms.output)}},refresh=False,poke_interval=poke_interval,)@@ -105,3 +112,48 @@ def create_and_populate_filtered_index(# sensitive_terms >> populate_filtered_indexcreate_filtered_index >> sensitive_terms >> populate_filtered_index >> refresh_index+++@task_group(group_id="filter_sensitive_documents")+def filter_sensitive_documents(+ es_host: str,+ origin_index_name: str,+ filtered_index_name: str,+ timeout: timedelta,+ poke_interval: int,+):+ """+ Delete the documents with sensitive terms from a filtered index that the indexer+ workers filled with a copy of every document in the origin index.++ The filtered index must hold exactly the origin index's documents first. An+ indexer worker that doesn't know about the filtered index leaves it empty, and+ promoting that would hide every result from default searches.+ """+ sensitive_terms = get_sensitive_terms()++ refresh_before = es.refresh_index.override(task_id="refresh_before_filtering")(+ es_host=es_host, index_name=filtered_index_name+ )++ same_count = es.assert_same_document_count(+ es_host=es_host, index=origin_index_name, other_index=filtered_index_name+ )++ delete_sensitive = es.trigger_and_wait_for_delete_by_query(+ es_host=es_host,+ index=filtered_index_name,+ query={+ "bool": {+ "should": sensitive_terms_clauses(sensitive_terms.output),+ "minimum_should_match": 1,+ }+ },+ timeout=timeout,+ requests_per_second="{{ var.value.get('ES_INDEX_THROTTLING_RATE', 20_000) }}",+ poke_interval=poke_interval,+ )++ refresh_after = es.refresh_index(es_host=es_host, index_name=filtered_index_name)++ sensitive_terms >> refresh_before >> same_count >> delete_sensitive >> refresh_afterdiff --git a/catalog/dags/data_refresh/dag_factory.py b/catalog/dags/data_refresh/dag_factory.pyindex ae1fb9cd9..1c6d99afa 100644--- a/catalog/dags/data_refresh/dag_factory.py+++ b/catalog/dags/data_refresh/dag_factory.py@@ -6,9 +6,9 @@ This file generates our data refresh DAGs for each media type and environment usThe data refresh has the following high level steps:* Copy Data: An FDW extension is used to connect the API database to the upstream (catalog) database. The entire contents of the upstream media table are copied into a new temp table in the API database. This temp table will later replace the main media table in the API.-* Create Index: Create a new Elasticsearch index, matching the configuration of the existing media index.-* Distributed Reindex: Convert each record from the new temp table to the format required by an Elasticsearch document, and then reindex them into the newly created index.-* Create and Populate Filtered Index: Create a new Elasticsearch index matching the configuration of the existing filtered index, and then reindex documents into it from the new media index, applying appropriate filtering for sensitive terms.+* Create Indices: Create a new Elasticsearch media index and a new filtered index, matching the configuration of the existing media index.+* Distributed Reindex: Convert each record from the new temp table to the format required by an Elasticsearch document, and then write it to both new indices.+* Filter Sensitive Documents: Check that both new indices hold the same documents, and then delete the documents with sensitive terms from the filtered index.* Enable Replicas: Give both new indices a replica of every shard, and wait for the replicas to be allocated.* Reapply Constraints: Recreate indices and constraints from the original API tables on the new temp tables.* Promote Table: Drop the old media table in the API and rename the temp table and its indices, which has the effect of promoting them/replacing the old table.@@ -52,7 +52,7 @@ from common.sensors.utils import wait_for_external_dags_with_tagfrom data_refresh.alter_data import alter_table_datafrom data_refresh.copy_data import copy_upstream_tablesfrom data_refresh.create_and_populate_filtered_index import (- create_and_populate_filtered_index,+ filter_sensitive_documents,get_filtered_index_name,)from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefreshConfig@@ -207,6 +207,11 @@ def create_data_refresh_dag(index_suffix="{{ params.index_suffix }}",)+ filtered_index_name = get_filtered_index_name(+ media_type=data_refresh_config.media_type,+ destination_index_name=f"{target_index_name}-filtered",+ )+# Create a new temporary index based off the configuration of the existing media index.# This will later replace the live index.target_index = es.create_index(@@ -217,6 +222,16 @@ def create_data_refresh_dag(es_host=es_host,)+ filtered_index_created = es.create_index.override(+ task_id="create_filtered_index"+ )(+ index_config={+ "index": filtered_index_name,+ "body": index_settings(data_refresh_config.media_type),+ },+ es_host=es_host,+ )+# Disable Cloudwatch alarms that are noisy during the reindexing steps of a# data refresh.disable_alarms = PythonOperator(@@ -233,18 +248,12 @@ def create_data_refresh_dag(environment="{{ var.value.ENVIRONMENT }}",target_environment=target_environment,target_index=target_index_name,+ filtered_target_index=filtered_index_name,data_refresh_config=data_refresh_config,)- filtered_index_name = get_filtered_index_name(- media_type=data_refresh_config.media_type,- destination_index_name=f"{target_index_name}-filtered",- )-- # Create and populate the filtered index- filtered_index = create_and_populate_filtered_index(+ filtered_index = filter_sensitive_documents(es_host=es_host,- media_type=data_refresh_config.media_type,origin_index_name=target_index_name,filtered_index_name=filtered_index_name,timeout=data_refresh_config.create_filtered_index_timeout,@@ -319,10 +328,11 @@ def create_data_refresh_dag(>> copy_data>> alter_data>> target_index_name+ >> filtered_index_name>> target_index+ >> filtered_index_created>> disable_alarms>> reindex- >> filtered_index_name>> filtered_index>> replicas>> replicas_readydiff --git a/catalog/dags/data_refresh/distributed_reindex.py b/catalog/dags/data_refresh/distributed_reindex.pyindex 03f3372ad..aeb290db9 100644--- a/catalog/dags/data_refresh/distributed_reindex.py+++ b/catalog/dags/data_refresh/distributed_reindex.py@@ -324,6 +324,7 @@ def assert_reindexing_success() -> EmptyOperator:def reindex(data_refresh_config: DataRefreshConfig,target_index: str,+ filtered_target_index: str,launch_template_version_number: int | str,start_id: int,end_id: int,@@ -358,6 +359,7 @@ def reindex("model_name": data_refresh_config.media_type,"table_name": data_refresh_config.table_mapping.temp_table_name,"target_index": target_index,+ "filtered_target_index": filtered_target_index,"start_id": start_id,"end_id": end_id,},@@ -390,9 +392,13 @@ def perform_distributed_reindex(environment: str,target_environment: Environment,target_index: str,+ filtered_target_index: str,data_refresh_config: DataRefreshConfig,):- """Perform the distributed reindex on a fleet of remote indexer workers."""+ """+ Perform the distributed reindex on a fleet of remote indexer workers. Each+ worker writes every document to both the target and the filtered target index.+ """id_range = PGExecuteQueryOperator(task_id="get_record_id_range",conn_id=POSTGRES_API_CONN_IDS.get(target_environment),@@ -422,6 +428,7 @@ def perform_distributed_reindex(perform_reindex = reindex.partial(data_refresh_config=data_refresh_config,target_index=target_index,+ filtered_target_index=filtered_target_index,launch_template_version_number=launch_template_version_number,environment=environment,target_environment=target_environment,diff --git a/catalog/tests/dags/common/test_elasticsearch.py b/catalog/tests/dags/common/test_elasticsearch.pyindex ef1b6c07f..3d08dc7a1 100644--- a/catalog/tests/dags/common/test_elasticsearch.py+++ b/catalog/tests/dags/common/test_elasticsearch.py@@ -11,6 +11,7 @@ from elasticsearch.exceptions import ApiErrorfrom common import elasticsearch as esfrom common.elasticsearch import (REINDEX_RESTART_BACKOFF,+ WaitForDeleteByQueryOperator,WaitForReindexOperator,is_retryable_reindex_failure,raise_for_reindex_failure,@@ -380,3 +381,100 @@ def test_wait_for_green_indices_survives_a_failed_explanation(monkeypatch):_hook(monkeypatch, es_conn)assert not es.wait_for_green_indices.function("http://es:9200", ["image-new"])+++DELETE_KWARGS = {+ "index": "image-new-filtered",+ "query": {"bool": {"should": [], "minimum_should_match": 1}},+ "requests_per_second": 20_000,+ "slices": "auto",+}+++def _delete_operator():+ return WaitForDeleteByQueryOperator(+ task_id="wait_for_delete_by_query",+ es_host="http://es:9200",+ reindex={"es_task_id": "node:1", "kwargs": DELETE_KWARGS},+ reindex_timeout=timedelta(hours=1),+ poke_interval=60,+ max_restarts=2,+ )+++def _delete_response(deleted, error=None):+ response = {+ "completed": True,+ "task": {"status": {"deleted": deleted, "version_conflicts": 0}},+ "response": {"failures": []},+ }+ if error:+ response["error"] = error+ return response+++def test_wait_for_delete_by_query_restarts_after_overload(monkeypatch):+ es_conn = mock.Mock()+ es_conn.tasks.get.return_value = _delete_response(4, error=REJECTED_SEARCH)+ _hook(monkeypatch, es_conn)++ with pytest.raises(TaskDeferred) as deferred:+ _delete_operator().execute({})++ assert deferred.value.method_name == "restart_reindex"+ assert deferred.value.kwargs["created_before"] == 4+++def test_restart_delete_by_query_starts_a_new_delete(monkeypatch):+ es_conn = mock.Mock()+ es_conn.delete_by_query.return_value = {"task": "node:2"}+ _hook(monkeypatch, es_conn)++ with pytest.raises(TaskDeferred) as deferred:+ _delete_operator().restart_reindex(+ {}, restarts=1, created_before=4, deadline=time.time() + 60+ )++ es_conn.reindex.assert_not_called()+ call = es_conn.delete_by_query.call_args.kwargs+ assert call["index"] == "image-new-filtered"+ assert call["query"] == DELETE_KWARGS["query"]+ assert call["conflicts"] == "proceed"+ assert call["wait_for_completion"] is False+ assert deferred.value.kwargs["es_task_id"] == "node:2"+++def test_wait_for_delete_by_query_fails_with_its_group(monkeypatch):+ es_conn = mock.Mock()+ es_conn.tasks.get.return_value = _delete_response(0, error=MAPPING_ERROR)+ _hook(monkeypatch, es_conn)++ with pytest.raises(+ AirflowFailException,+ match="Delete by query failed.*trigger_and_wait_for_delete_by_query",+ ):+ _delete_operator().execute({})+++ "counts, should_fail",+ [((10, 10), False), ((10, 0), True), ((10, 9), True)],+ ids=["same", "empty_filtered_index", "missing_documents"],+)+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]+ _hook(monkeypatch, es_conn)++ if should_fail:+ with pytest.raises(AirflowFailException, match="documents, but"):+ es.assert_same_document_count.function(+ "http://es:9200", "image-new", "image-new-filtered"+ )+ else:+ assert (+ es.assert_same_document_count.function(+ "http://es:9200", "image-new", "image-new-filtered"+ )+ == 10+ )diff --git a/catalog/tests/dags/data_refresh/test_task_dependencies.py b/catalog/tests/dags/data_refresh/test_task_dependencies.pyindex 33e7dfe16..926de62ed 100644--- a/catalog/tests/dags/data_refresh/test_task_dependencies.py+++ b/catalog/tests/dags/data_refresh/test_task_dependencies.py@@ -51,16 +51,19 @@ def test_dependencies_reindex_task():"copy_upstream_tables.copy_upstream_table.copy_data","alter_table_data.alter_data_range","create_index",+ "create_filtered_index",],)-def test_dependencies_create_and_populate_filtered_index_task():+def test_dependencies_filter_sensitive_documents_task():_assert_dependencies(- downstream_task_id="create_and_populate_filtered_index.trigger_and_wait_for_reindex.trigger_reindex",+ downstream_task_id="filter_sensitive_documents.trigger_and_wait_for_delete_by_query.trigger_delete_by_query",upstream_task_ids=["run_distributed_reindex.reindex.assert_reindexing_success","run_distributed_reindex.refresh_index",+ "filter_sensitive_documents.refresh_before_filtering",+ "filter_sensitive_documents.assert_same_document_count",],)@@ -70,7 +73,7 @@ def test_dependencies_promote_table_task():downstream_task_id="promote_tables.promote_table.promote",upstream_task_ids=["run_distributed_reindex.reindex.assert_reindexing_success",- "create_and_populate_filtered_index.refresh_index",+ "filter_sensitive_documents.refresh_index","enable_replicas","wait_for_green_indices","promote_tables.promote_table.remap_table_indices_to_table.create_table_indices",@@ -93,7 +96,7 @@ def test_dependenceis_promote_filtered_index_task():_assert_dependencies(downstream_task_id="promote_filtered_index.point_new_alias",upstream_task_ids=[- "create_and_populate_filtered_index.refresh_index",+ "filter_sensitive_documents.refresh_index","promote_tables.promote_table.promote",],)@@ -105,5 +108,5 @@ def test_alarms_do_not_wait_for_replicas():"enable_sensitive_cloudwatch_alarms").get_flat_relative_ids(upstream=True)- assert "create_and_populate_filtered_index.refresh_index" in upstream_tasks+ assert "filter_sensitive_documents.refresh_index" in upstream_tasksassert "wait_for_green_indices" not in upstream_tasksdiff --git a/documentation/catalog/reference/DAGs.md b/documentation/catalog/reference/DAGs.mdindex 03ac68b02..740d3e9fd 100644--- a/documentation/catalog/reference/DAGs.md+++ b/documentation/catalog/reference/DAGs.md@@ -1342,15 +1342,13 @@ The data refresh has the following high level steps:upstream (catalog) database. The entire contents of the upstream media tableare copied into a new temp table in the API database. This temp table willlater replace the main media table in the API.-- Create Index: Create a new Elasticsearch index, matching the configuration of- the existing media index.+- Create Indices: Create a new Elasticsearch media index and a new filtered+ index, matching the configuration of the existing media index.- Distributed Reindex: Convert each record from the new temp table to the format- required by an Elasticsearch document, and then reindex them into the newly- created index.-- Create and Populate Filtered Index: Create a new Elasticsearch index matching- the configuration of the existing filtered index, and then reindex documents- into it from the new media index, applying appropriate filtering for sensitive- terms.+ required by an Elasticsearch document, and then write it to both new indices.+- Filter Sensitive Documents: Check that both new indices hold the same+ documents, and then delete the documents with sensitive terms from the+ filtered index.- Enable Replicas: Give both new indices a replica of every shard, and wait forthe replicas to be allocated.- Reapply Constraints: Recreate indices and constraints from the original APIdiff --git a/indexer_worker/indexer_worker/api.py b/indexer_worker/indexer_worker/api.pyindex 5d1c7e77a..fc90fa47c 100644--- a/indexer_worker/indexer_worker/api.py+++ b/indexer_worker/indexer_worker/api.py@@ -55,6 +55,7 @@ class IndexingJobResource(BaseTaskResource):model_name = body.get("model_name")table_name = body.get("table_name")target_index = body.get("target_index")+ filtered_target_index = body.get("filtered_target_index")start_id = body.get("start_id")end_id = body.get("end_id")log.info(f"Received indexing request for records {start_id}-{end_id}")@@ -69,6 +70,7 @@ class IndexingJobResource(BaseTaskResource):"model_name": model_name,"table_name": table_name,"target_index": target_index,+ "filtered_target_index": filtered_target_index,"start_id": int(start_id),"end_id": int(end_id),# Task tracking argumentsdiff --git a/indexer_worker/indexer_worker/indexer.py b/indexer_worker/indexer_worker/indexer.pyindex 79350efd8..7fc8ff9ba 100644--- a/indexer_worker/indexer_worker/indexer.py+++ b/indexer_worker/indexer_worker/indexer.py@@ -33,6 +33,7 @@ def launch_reindex(end_id: int,progress: float,finish_time: int,+ filtered_target_index: str | None = None,):"""Copy data from the given PostgreSQL table to the given Elasticsearch index.@@ -46,9 +47,23 @@ def launch_reindex(end_id: the index of the last record to be copiedprogress: tracks the percentage of records that have been copied so farfinish_time: the time at which the task finishes++ Optional Arguments:++ filtered_target_index: the name of a second index that also gets every document.+ The data refresh deletes the sensitive documents from it+ afterwards to make the filtered index."""try:- reindex(model_name, table_name, target_index, start_id, end_id, progress)+ reindex(+ model_name,+ table_name,+ target_index,+ start_id,+ end_id,+ progress,+ filtered_target_index,+ )finish_time.value = time.time()except Exception as err:exception_type = f"{err.__class__.__module__}.{err.__class__.__name__}"@@ -67,6 +82,7 @@ def reindex(start_id: int,end_id: int,progress: float,+ filtered_target_index: str | None = None,):# Enable writing to Postgres so we can create a server-side cursor.pg_conn = database_connect()@@ -109,6 +125,7 @@ def reindex(columns=server_cur.description,model_name=model_name,target_index=target_index,+ filtered_target_index=filtered_target_index,)# Bulk upload to Elasticsearch in parallel.@@ -136,8 +153,13 @@ def reindex(pg_conn.close()-def pg_chunk_to_es(pg_chunk, columns, model_name, target_index):- """Convert the given list of psycopg2 results to Elasticsearch documents."""+def pg_chunk_to_es(+ pg_chunk, columns, model_name, target_index, filtered_target_index=None+):+ """+ Convert the given list of psycopg2 results to Elasticsearch documents, with a+ copy of each for `filtered_target_index` if it is given.+ """# Map column names to locations in the row tupleschema = {col[0]: idx for idx, col in enumerate(columns)}@@ -154,6 +176,8 @@ def pg_chunk_to_es(pg_chunk, columns, model_name, target_index):if target_index:converted["_index"] = target_indexdocuments.append(converted)+ if filtered_target_index:+ documents.append({**converted, "_index": filtered_target_index})return documents@@ -180,8 +204,9 @@ def _bulk_upload(es_conn, es_batch):)time.sleep(backoff)- # Bulk responses return `_id` as a string- pending_by_id = {str(doc["_id"]): doc for doc in pending}+ # A doc is written to both the main and the filtered index with the same+ # `_id`. Bulk responses return `_id` as a string.+ pending_by_key = {(doc["_index"], str(doc["_id"])): doc for doc in pending}rejected = []failed = []try:@@ -196,10 +221,13 @@ def _bulk_upload(es_conn, es_batch):continueinfo = next(iter(item.values()))if info.get("status") in RETRYABLE_BULK_STATUSES:- rejected.append(pending_by_id[str(info["_id"])])+ rejected.append(pending_by_key[(info["_index"], str(info["_id"]))])else:failed.append(- {key: info.get(key) for key in ("_id", "status", "error")}+ {+ key: info.get(key)+ for key in ("_index", "_id", "status", "error")+ })except elasticsearch.TransportError:# The connection failed, so it is unknown which docs were indexed.diff --git a/indexer_worker/tests/test_bulk_upload.py b/indexer_worker/tests/test_bulk_upload.pyindex 6791ba995..11e4ed3de 100644--- a/indexer_worker/tests/test_bulk_upload.py+++ b/indexer_worker/tests/test_bulk_upload.py@@ -1,3 +1,5 @@+from unittest import mock+import elastic_transportimport pytest@@ -8,9 +10,11 @@ from indexer_worker.indexer import BulkUploadError, _bulk_uploadDOCS = [{"_index": "image-test", "_id": doc_id, "title": "x"} for doc_id in (1, 2, 3)]-def _item(doc_id, status):+def _item(doc, status):# Shaped like a bulk response item; `_id` comes back as a string- return {"index": {"_index": "image-test", "_id": str(doc_id), "status": status}}+ return {+ "index": {"_index": doc["_index"], "_id": str(doc["_id"]), "status": status}+ }@pytest.fixture@@ -24,7 +28,8 @@ def sleeps(monkeypatch):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.+ scripted response: a dict of doc ID, or of (index, doc ID), to status, or an+ exception to raise."""calls = []responses = []@@ -36,8 +41,10 @@ def bulk(monkeypatch):if isinstance(response, Exception):raise responsefor doc in actions:- status = response.get(doc["_id"], 201)- yield 200 <= status < 300, _item(doc["_id"], status)+ status = response.get(+ (doc["_index"], doc["_id"]), response.get(doc["_id"], 201)+ )+ yield 200 <= status < 300, _item(doc, status)monkeypatch.setattr(indexer.helpers, "parallel_bulk", fake_parallel_bulk)return calls, responses@@ -101,3 +108,67 @@ def test_bulk_upload_caps_backoff(bulk, sleeps, monkeypatch):_bulk_upload(None, DOCS)assert sleeps == [5, 10, 12]+++def test_bulk_upload_retries_the_rejected_copy_of_a_doc(monkeypatch, sleeps):+ sent = []++ def fake_parallel_bulk(client, actions, **kwargs):+ actions = list(actions)+ sent.append([doc["_index"] for doc in actions])+ for doc in actions:+ rejected = len(sent) == 1 and doc["_index"] == "image-test"+ yield not rejected, _item(doc, 429 if rejected else 201)++ monkeypatch.setattr(indexer.helpers, "parallel_bulk", fake_parallel_bulk)+ docs = [+ {"_index": index, "_id": 1, "title": "x"}+ for index in ("image-test", "image-test-filtered")+ ]++ _bulk_upload(None, docs)++ assert sent == [["image-test", "image-test-filtered"], ["image-test"]]+++def _rows(*overrides):+ columns = [+ "id",+ "identifier",+ "title",+ "removed_from_source",+ "deleted",+ ]+ rows = [+ tuple(+ {"id": 1, "removed_from_source": False, "deleted": False, **o}.get(c)+ for c in columns+ )+ for o in overrides+ ]+ return rows, [(column,) for column in columns]+++ "filtered_target_index, expected_indices",+ [+ (None, ["image-test"]),+ ("image-test-filtered", ["image-test", "image-test-filtered"]),+ ],+)+def test_pg_chunk_to_es_copies_docs_to_filtered_index(+ monkeypatch, filtered_target_index, expected_indices+):+ converted = mock.Mock()+ converted.to_dict.return_value = {"_index": "image", "_id": 1, "_source": {}}+ model = mock.Mock()+ model.database_row_to_elasticsearch_doc.return_value = converted+ monkeypatch.setitem(indexer.media_type_to_elasticsearch_model, "image", model)+ rows, columns = _rows({}, {"removed_from_source": True}, {"deleted": True})++ docs = indexer.pg_chunk_to_es(+ rows, columns, "image", "image-test", filtered_target_index+ )++ assert [doc["_index"] for doc in docs] == expected_indices+ assert all(doc["_id"] == 1 for doc in docs)