Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add filtered index creation DAG (#1833)
sarayourfriend4d6e995d2268
diff --git a/catalog/DAGs.md b/catalog/DAGs.mdindex 0f8afaa43..b479a4dbd 100644--- a/catalog/DAGs.md+++ b/catalog/DAGs.md@@ -30,10 +30,12 @@ The following are DAGs grouped by their primary tag:## Data Refresh-| DAG ID | Schedule Interval |-| ------------------------------------------- | ----------------- |-| [`audio_data_refresh`](#audio_data_refresh) | `@weekly` |-| [`image_data_refresh`](#image_data_refresh) | `None` |+| DAG ID | Schedule Interval |+| ------------------------------------------------------------- | ----------------- |+| [`audio_data_refresh`](#audio_data_refresh) | `@weekly` |+| [`create_filtered_audio_index`](#create_filtered_audio_index) | `None` |+| [`create_filtered_image_index`](#create_filtered_image_index) | `None` |+| [`image_data_refresh`](#image_data_refresh) | `None` |## Database@@ -103,6 +105,8 @@ The following is documentation associated with each DAG (where available):1. [`airflow_log_cleanup`](#airflow_log_cleanup)1. [`audio_data_refresh`](#audio_data_refresh)1. [`check_silenced_dags`](#check_silenced_dags)+1. [`create_filtered_audio_index`](#create_filtered_audio_index)+1. [`create_filtered_image_index`](#create_filtered_image_index)1. [`europeana_reingestion_workflow`](#europeana_reingestion_workflow)1. [`europeana_workflow`](#europeana_workflow)1. [`finnish_museums_workflow`](#finnish_museums_workflow)@@ -196,7 +200,8 @@ process is necessary to make new content added to the Catalog by our providerDAGs available to the API. You can read more in the[README](https://github.com/WordPress/openverse-api/blob/main/ingestion_server/README.md)Importantly, the data refresh TaskGroup is also configured to handle concurrency-requirements of the data refresh server.+requirements of the data refresh server. Finally, once the origin indexes have+been refreshed, the corresponding filtered index creation DAG is triggered.You can find more background information on this process in the following issuesand related PRs:@@ -229,6 +234,112 @@ has been resolved.The DAG runs weekly.+## `create_filtered_audio_index`++### Create filtered index DAG factory++This module creates the filtered index creation DAGs for each media type using a+factory function.++Filtered index creation is handled by the ingestion server. The DAGs generated+by the `build_create_filtered_index_dag` function in this module are responsible+for triggering the ingestion server action to create and populate the filtered+index for a given media type. The DAG awaits the completion of the filtered+index creation and then points the filtered index alias for the media type to+the newly created index.++#### When this DAG runs++The DAGs generated in this module are triggered by the data refresh DAGs.+Maintaining this process separate from the data refresh DAGs, while still+triggering it there, allows us to run filtered index creation independently of+the full data refresh. This is primarily useful in two cases: for testing+changes to the filtered index creation; and for re-running filtered index+creation if an urgent change to the sensitive terms calls for an immediate+recreation of the filtered indexes.++#### Race conditions++Because filtered index creation employs the `reindex` Elasticsearch API to+derive the filtered index from an existing index, we need to be mindful of the+race condition that potentially exists between the data refresh DAG and this+DAG. The race condition is caused by the fact that the data refresh DAG always+deletes the previous index once the new index for the media type is finished+being created. Consider the situation where filtered index creation is triggered+to run during a data refresh. The filtered index is being derived from the+previous index for the media type. Once the data refresh is finished, it will+delete that index, causing the reindex to halt because suddenly it has no data+source from which to pull documents.++There are two mechanisms that prevent this from happening:++1. The filtered index creation DAGs are not allowed to run if a data refresh for+ the media type is already running.+2. The data refresh DAGs will wait for any pre-existing filtered index creation+ DAG runs for the media type to finish before continuing.++This ensures that neither are depending on or modifying the origin indexes+critical for the creation of the filtered indexes.++Because the data refresh DAG triggers the filtered index creation DAG, we do+allow a `force` param to be passed to the DAGs generated by this module. This+parameter is only for use by the data refresh DAG and should not be used when+manually triggering the DAG unless you are absolutely certain of what you are+doing.++## `create_filtered_image_index`++### Create filtered index DAG factory++This module creates the filtered index creation DAGs for each media type using a+factory function.++Filtered index creation is handled by the ingestion server. The DAGs generated+by the `build_create_filtered_index_dag` function in this module are responsible+for triggering the ingestion server action to create and populate the filtered+index for a given media type. The DAG awaits the completion of the filtered+index creation and then points the filtered index alias for the media type to+the newly created index.++#### When this DAG runs++The DAGs generated in this module are triggered by the data refresh DAGs.+Maintaining this process separate from the data refresh DAGs, while still+triggering it there, allows us to run filtered index creation independently of+the full data refresh. This is primarily useful in two cases: for testing+changes to the filtered index creation; and for re-running filtered index+creation if an urgent change to the sensitive terms calls for an immediate+recreation of the filtered indexes.++#### Race conditions++Because filtered index creation employs the `reindex` Elasticsearch API to+derive the filtered index from an existing index, we need to be mindful of the+race condition that potentially exists between the data refresh DAG and this+DAG. The race condition is caused by the fact that the data refresh DAG always+deletes the previous index once the new index for the media type is finished+being created. Consider the situation where filtered index creation is triggered+to run during a data refresh. The filtered index is being derived from the+previous index for the media type. Once the data refresh is finished, it will+delete that index, causing the reindex to halt because suddenly it has no data+source from which to pull documents.++There are two mechanisms that prevent this from happening:++1. The filtered index creation DAGs are not allowed to run if a data refresh for+ the media type is already running.+2. The data refresh DAGs will wait for any pre-existing filtered index creation+ DAG runs for the media type to finish before continuing.++This ensures that neither are depending on or modifying the origin indexes+critical for the creation of the filtered indexes.++Because the data refresh DAG triggers the filtered index creation DAG, we do+allow a `force` param to be passed to the DAGs generated by this module. This+parameter is only for use by the data refresh DAG and should not be used when+manually triggering the DAG unless you are absolutely certain of what you are+doing.+## `europeana_reingestion_workflow`Content Provider: Europeana@@ -327,7 +438,8 @@ process is necessary to make new content added to the Catalog by our providerDAGs available to the API. You can read more in the[README](https://github.com/WordPress/openverse-api/blob/main/ingestion_server/README.md)Importantly, the data refresh TaskGroup is also configured to handle concurrency-requirements of the data refresh server.+requirements of the data refresh server. Finally, once the origin indexes have+been refreshed, the corresponding filtered index creation DAG is triggered.You can find more background information on this process in the following issuesand related PRs:diff --git a/catalog/dags/common/ingestion_server.py b/catalog/dags/common/ingestion_server.pynew file mode 100644index 000000000..e31e74e0c--- /dev/null+++ b/catalog/dags/common/ingestion_server.py@@ -0,0 +1,126 @@+import logging+import os+from datetime import timedelta+from urllib.parse import urlparse++from airflow.exceptions import AirflowException+from airflow.providers.http.operators.http import SimpleHttpOperator+from airflow.providers.http.sensors.http import HttpSensor+from requests import Response++from common.constants import XCOM_PULL_TEMPLATE+++logger = logging.getLogger(__name__)+++POKE_INTERVAL = int(os.getenv("DATA_REFRESH_POKE_INTERVAL", 60 * 15))+++def response_filter_stat(response: Response) -> str:+ """+ Handle the response for the `get_current_index` task.++ This is used to extract the name of the current index that the concerned alias+ points to. This index name will be available via XCom in the downstream tasks.+ """+ index_name = response.json()["alt_names"]+ # Indices are named as '<media type>-<suffix>', so everything after the first+ # hyphen '-' is the suffix.+ _, index_suffix = index_name.split("-", maxsplit=1)+ return index_suffix+++def response_filter_status_check_endpoint(response: Response) -> str:+ """+ Handle the response for `trigger_task` task.++ This is used to grab the endpoint needed to poll for the status of the triggered+ data refresh. This information will then be available via XCom in the downstream+ tasks.+ """+ status_check_url = response.json()["status_check"]+ return urlparse(status_check_url).path+++def response_check_wait_for_completion(response: Response) -> bool:+ """+ Handle the response for `wait_for_completion` Sensor.++ Processes the response to determine whether the task can complete.+ """+ data = response.json()++ if data["active"]:+ # The data refresh is still running. Poll again later.+ return False++ if data["error"]:+ raise AirflowException(+ "Ingestion server encountered an error during data refresh."+ )++ logger.info(f"Data refresh done with {data['progress']}% completed.")+ return True+++def get_current_index(target_alias: str) -> SimpleHttpOperator:+ return SimpleHttpOperator(+ task_id="get_current_index",+ http_conn_id="data_refresh",+ endpoint=f"stat/{target_alias}",+ method="GET",+ response_check=lambda response: response.status_code == 200,+ response_filter=response_filter_stat,+ )+++def trigger_task(+ action: str,+ model: str,+ data: dict | None = None,+) -> SimpleHttpOperator:+ data = {+ **(data or {}),+ "model": model,+ "action": action.upper(),+ }+ return SimpleHttpOperator(+ task_id=f"trigger_{action.lower()}",+ http_conn_id="data_refresh",+ endpoint="task",+ data=data,+ response_check=lambda response: response.status_code == 202,+ response_filter=response_filter_status_check_endpoint,+ )+++def wait_for_task(+ action: str,+ task_trigger: SimpleHttpOperator,+ timeout: timedelta,+ poke_interval: int = POKE_INTERVAL,+) -> HttpSensor:+ return HttpSensor(+ task_id=f"wait_for_{action.lower()}",+ http_conn_id="data_refresh",+ endpoint=XCOM_PULL_TEMPLATE.format(task_trigger.task_id, "return_value"),+ method="GET",+ response_check=response_check_wait_for_completion,+ mode="reschedule",+ poke_interval=poke_interval,+ timeout=timeout.total_seconds(),+ )+++def trigger_and_wait_for_task(+ action: str,+ model: str,+ timeout: timedelta,+ data: dict | None = None,+ poke_interval: int = POKE_INTERVAL,+) -> tuple[SimpleHttpOperator, HttpSensor]:+ trigger = trigger_task(action, model, data)+ waiter = wait_for_task(action, trigger, timeout, poke_interval)+ trigger >> waiter+ return trigger, waiterdiff --git a/catalog/dags/common/sensors/utils.py b/catalog/dags/common/sensors/utils.pynew file mode 100644index 000000000..3cd3d72f3--- /dev/null+++ b/catalog/dags/common/sensors/utils.py@@ -0,0 +1,29 @@+from datetime import datetime++from airflow.models import DagRun+++def get_most_recent_dag_run(dag_id) -> list[datetime] | datetime:+ """+ Retrieve the most recent DAG run's execution date.++ For use as ``execution_date_fn`` argument to ``ExternalTaskSensor``.++ Adapted from https://stackoverflow.com/a/74017474+ CC BY-SA 4.0 by Stack Overflow user Nahid O.+ """+ dag_runs = DagRun.find(dag_id=dag_id)+ dag_runs.sort(key=lambda x: x.execution_date, reverse=True)+ if dag_runs:+ return dag_runs[0].execution_date++ # If there are no DAG runs, return an empty list to indicate that+ # there are no execution dates to check.+ # This works because the sensor waits until the number+ # of runs for the execution dates in the ``allowed_states`` matches the+ # length of the list of execution dates to check. If there are no runs+ # for this DAG, then the only possible number of required states+ # we can have is 0. See ``ExternalTaskSensor::poke`` and+ # ``ExternalTaskSensor::get_count``, especially the handling+ # of ``dttm_filter`` for the relevant implementation details.+ return []diff --git a/catalog/dags/data_refresh/create_filtered_index_dag.py b/catalog/dags/data_refresh/create_filtered_index_dag.pynew file mode 100644index 000000000..9c9a76f23--- /dev/null+++ b/catalog/dags/data_refresh/create_filtered_index_dag.py@@ -0,0 +1,232 @@+"""+# Create filtered index DAG factory++This module creates the filtered index creation DAGs for each media type+using a factory function.++Filtered index creation is handled by the ingestion server. The DAGs generated+by the ``build_create_filtered_index_dag`` function in this module are+responsible for triggering the ingestion server action to create and populate+the filtered index for a given media type. The DAG awaits the completion+of the filtered index creation and then points the filtered index alias for the+media type to the newly created index.++## When this DAG runs++The DAGs generated in this module are triggered by the data refresh DAGs.+Maintaining this process separate from the data refresh DAGs, while still+triggering it there, allows us to run filtered index creation independently+of the full data refresh. This is primarily useful in two cases: for testing+changes to the filtered index creation; and for re-running filtered index+creation if an urgent change to the sensitive terms calls for an immediate+recreation of the filtered indexes.++## Race conditions++Because filtered index creation employs the ``reindex`` Elasticsearch API+to derive the filtered index from an existing index, we need to be mindful+of the race condition that potentially exists between the data refresh DAG+and this DAG. The race condition is caused by the fact that the data refresh+DAG always deletes the previous index once the new index for the media type+is finished being created. Consider the situation where filtered index creation+is triggered to run during a data refresh. The filtered index is being derived+from the previous index for the media type. Once the data refresh is finished,+it will delete that index, causing the reindex to halt because suddenly it has+no data source from which to pull documents.++There are two mechanisms that prevent this from happening:++1. The filtered index creation DAGs are not allowed to run if a data refresh+for the media type is already running.+2. The data refresh DAGs will wait for any pre-existing filtered index creation+DAG runs for the media type to finish before continuing.++This ensures that neither are depending on or modifying the origin indexes+critical for the creation of the filtered indexes.++Because the data refresh DAG triggers the filtered index creation DAG, we do+allow a ``force`` param to be passed to the DAGs generated by this module.+This parameter is only for use by the data refresh DAG and should not be+used when manually triggering the DAG unless you are absolutely certain+of what you are doing.+"""+import uuid+from datetime import datetime++from airflow import DAG+from airflow.decorators import task+from airflow.exceptions import AirflowSensorTimeout+from airflow.models.param import Param+from airflow.sensors.external_task import ExternalTaskSensor++from common import ingestion_server+from common.constants import DAG_DEFAULT_ARGS, XCOM_PULL_TEMPLATE+from common.sensors.utils import get_most_recent_dag_run+from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefresh+++# Note: We can't use the TaskFlow `@dag` DAG factory decorator+# here because there's no way to set the media type as a static+# variable in the context of the DAG because all arguments+# passed to the DAG factory decorated by `@dag` are thrown+# away: `@dag` decorated functions' arguments are treated+# merely as DAG param aliases. We could use `@dag` inside+# this factory function, but it would require a redundant+# call to the decorated function and doesn't look like it would+# provide any additional value whatsoever.+def filtered_index_creation_dag_factory(data_refresh: DataRefresh):+ media_type = data_refresh.media_type+ target_alias = f"{media_type}-filtered"++ @task(+ task_id=f"prevent_concurrency_with_{media_type}_data_refresh",+ )+ def prevent_concurrency_with_data_refresh(force: bool, **context):+ if force:+ return++ data_refresh_dag_id = f"{media_type}_data_refresh"+ wait_for_filtered_index_creation = ExternalTaskSensor(+ task_id="check_for_running_data_refresh",+ external_dag_id=data_refresh_dag_id,+ # Set timeout to 0 to prevent retries. If the data refresh DAG is running,+ # immediately fail the filtered index creation DAG.+ timeout=0,+ # Wait for the whole DAG, not just a part of it+ external_task_id=None,+ check_existence=False,+ execution_date_fn=lambda _: get_most_recent_dag_run(data_refresh_dag_id),+ mode="reschedule",+ )+ try:+ wait_for_filtered_index_creation.execute(context)+ except AirflowSensorTimeout:+ raise ValueError(+ f"{media_type} data refresh concurrency check failed. "+ "Filtered index creation cannot start during a data refresh."+ )++ @task()+ def generate_index_suffix(default_suffix: str):+ return default_suffix or uuid.uuid4().hex++ def create_and_populate_filtered_index(+ origin_index_suffix: str | None,+ destination_index_suffix: str | None,+ ):+ create_payload = {}+ if origin_index_suffix:+ create_payload["origin_index_suffix"] = origin_index_suffix+ if destination_index_suffix:+ create_payload["destination_index_suffix"] = destination_index_suffix++ return ingestion_server.trigger_and_wait_for_task(+ action="CREATE_AND_POPULATE_FILTERED_INDEX",+ model=media_type,+ data=create_payload or None,+ timeout=data_refresh.create_filtered_index_timeout,+ )++ def point_alias(destination_index_suffix: str):+ point_alias_payload = {+ "alias": target_alias,+ "index_suffix": f"{destination_index_suffix}-filtered",+ }++ return ingestion_server.trigger_task(+ action="POINT_ALIAS",+ model=media_type,+ data=point_alias_payload,+ )++ with DAG(+ dag_id=f"create_filtered_{media_type}_index",+ default_args=DAG_DEFAULT_ARGS,+ schedule=None,+ start_date=datetime(2023, 4, 1),+ tags=["data_refresh"],+ max_active_runs=1,+ catchup=False,+ doc_md=__doc__,+ params={+ "force": Param(+ default=False,+ type="boolean",+ description=(+ "Bypass data refresh concurrency check. "+ "Should only ever be used by the data_refresh "+ "DAGs when triggering filtered index creation "+ "at the end of a data refresh. This should not "+ "be used when manually running this DAG "+ "unless you're absolutely sure of what you're "+ "doing. This check exists to prevent race "+ "conditions and should not be ignored lightly."+ ),+ ),+ "origin_index_suffix": Param(+ default=None,+ type=["string", "null"],+ description=(+ "See ``Indexer::create_and_populate_filtered_index`` in the "+ "Openverse ingestion server project. "+ "For manual runs this can be left out if the new "+ f"filtered alias should be based on the {media_type} alias."+ ),+ ),+ "destination_index_suffix": Param(+ default=None,+ type=["string", "null"],+ description=(+ "See ``Indexer::create_and_populate_filtered_index`` in the "+ "Openverse ingestion server project. "+ "For manual runs this should be left out. This setting should "+ "not conflict with another existing suffix or index creation "+ "will fail."+ ),+ ),+ },+ render_template_as_native_obj=True,+ ) as dag:+ prevent_concurrency = prevent_concurrency_with_data_refresh(+ force="{{ params.force }}",+ )++ # If a destination index suffix isn't provided, we need to generate+ # one so that we know where to point the alias+ destination_index_suffix = generate_index_suffix(+ "{{ params.destination_index_suffix }}"+ )++ get_current_index = ingestion_server.get_current_index(target_alias)++ do_create = create_and_populate_filtered_index(+ origin_index_suffix="{{ params.origin_index_suffix }}",+ destination_index_suffix=destination_index_suffix,+ )++ do_point_alias = point_alias(destination_index_suffix=destination_index_suffix)++ delete_old_index = ingestion_server.trigger_task(+ action="DELETE_INDEX",+ model=data_refresh.media_type,+ data={+ "index_suffix": XCOM_PULL_TEMPLATE.format(+ get_current_index.task_id, "return_value"+ ),+ },+ )++ (+ prevent_concurrency+ >> destination_index_suffix+ >> get_current_index+ >> do_create+ >> do_point_alias+ >> delete_old_index+ )++ return dag+++for data_refresh in DATA_REFRESH_CONFIGS:+ create_filtered_index_dag = filtered_index_creation_dag_factory(data_refresh)diff --git a/catalog/dags/data_refresh/dag_factory.py b/catalog/dags/data_refresh/dag_factory.pyindex 7dc7698c6..385998354 100644--- a/catalog/dags/data_refresh/dag_factory.py+++ b/catalog/dags/data_refresh/dag_factory.py@@ -21,7 +21,8 @@ necessary to make new content added to the Catalog by our provider DAGs availablto the API. You can read more in the [README](https://github.com/WordPress/openverse-api/blob/main/ingestion_server/README.md) Importantly, the data refresh TaskGroup is also configured to handle concurrency-requirements of the data refresh server.+requirements of the data refresh server. Finally, once the origin indexes have been+refreshed, the corresponding filtered index creation DAG is triggered.You can find more background information on this process in the followingissues and related PRs:@@ -37,6 +38,7 @@ from collections.abc import Sequencefrom airflow import DAGfrom airflow.models.dagrun import DagRunfrom airflow.operators.python import BranchPythonOperator, PythonOperator+from airflow.operators.trigger_dagrun import TriggerDagRunOperatorfrom airflow.settings import SASessionfrom airflow.utils.session import provide_sessionfrom airflow.utils.state import State@@ -261,11 +263,31 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc},)+ index_suffix = XCOM_PULL_TEMPLATE.format(+ data_refresh_group.get_child_by_label("generate_index_suffix").task_id,+ "return_value",+ )+ trigger_filtered_index_creation = TriggerDagRunOperator(+ task_id=f"trigger_create_filtered_{data_refresh.media_type}_index",+ trigger_dag_id=f"create_filtered_{data_refresh.media_type}_index",+ conf={+ # Force to skip data refresh DAG concurrency check+ # as the data refresh DAG will clearly already be running+ # as it is triggering the filtered index creation DAG.+ "force": True,+ "origin_index_suffix": index_suffix,+ # Match origin and destination suffixes so we can tell which+ # filtered indexes were created as part of a data refresh.+ "destination_index_suffix": index_suffix,+ },+ )+# Set up task dependenciesmonth_check >> [refresh_popularity_metrics, refresh_matview]before_record_count >> data_refresh_grouprefresh_popularity_metrics >> refresh_matview >> data_refresh_groupdata_refresh_group >> after_record_count >> report_counts+ data_refresh_group >> trigger_filtered_index_creationreturn dagdiff --git a/catalog/dags/data_refresh/data_refresh_task_factory.py b/catalog/dags/data_refresh/data_refresh_task_factory.pyindex 4c30c345f..5941328a6 100644--- a/catalog/dags/data_refresh/data_refresh_task_factory.py+++ b/catalog/dags/data_refresh/data_refresh_task_factory.py@@ -44,23 +44,21 @@ issues and related PRs:- [[Feature] Data refresh orchestration DAG](https://github.com/WordPress/openverse-catalog/issues/353)"""-import jsonimport loggingimport osimport uuidfrom collections.abc import Sequence-from urllib.parse import urlparse-from airflow.exceptions import AirflowExceptionfrom airflow.models.baseoperator import chainfrom airflow.operators.python import PythonOperator-from airflow.providers.http.operators.http import SimpleHttpOperator-from airflow.providers.http.sensors.http import HttpSensor+from airflow.sensors.external_task import ExternalTaskSensor+from airflow.utils.state import Statefrom airflow.utils.task_group import TaskGroup-from requests import Response+from common import ingestion_serverfrom common.constants import XCOM_PULL_TEMPLATEfrom common.sensors.single_run_external_dags_sensor import SingleRunExternalDAGsSensor+from common.sensors.utils import get_most_recent_dag_runfrom data_refresh.data_refresh_types import DataRefresh@@ -70,53 +68,6 @@ logger = logging.getLogger(__name__)DATA_REFRESH_POOL = "data_refresh"-def response_filter_stat(response: Response) -> str:- """- Handle the response for the `get_current_index` task.-- This is used to extract the name of the current index that the concerned alias- points to. This index name will be available via XCom in the downstream tasks.- """- index_name = response.json()["alt_names"]- # Indices are named as '<media type>-<suffix>', so everything after the first- # hyphen '-' is the suffix.- _, index_suffix = index_name.split("-", maxsplit=1)- return index_suffix---def response_filter_data_refresh(response: Response) -> str:- """- Handle the response for `trigger_data_refresh` task.-- This is used to grab the endpoint needed to poll for the status of the triggered- data refresh. This information will then be available via XCom in the downstream- tasks.- """- status_check_url = response.json()["status_check"]- return urlparse(status_check_url).path---def response_check_wait_for_completion(response: Response) -> bool:- """- Handle the response for `wait_for_completion` Sensor.-- Processes the response to determine whether the task can complete.- """- data = response.json()-- if data["active"]:- # The data refresh is still running. Poll again later.- return False-- if data["error"]:- raise AirflowException(- "Ingestion server encountered an error during data refresh."- )-- logger.info(f"Data refresh done with {data['progress']}% completed.")- return True--def create_data_refresh_task_group(data_refresh: DataRefresh, external_dag_ids: Sequence[str]):@@ -161,17 +112,38 @@ def create_data_refresh_task_group(mode="reschedule",pool=DATA_REFRESH_POOL,)- tasks.append(wait_for_data_refresh)- # Get the index currently mapped to our target alias, to delete later.- get_current_index = SimpleHttpOperator(- task_id="get_current_index",- http_conn_id="data_refresh",- endpoint=f"stat/{target_alias}",- method="GET",- response_check=lambda response: response.status_code == 200,- response_filter=response_filter_stat,+ # If filtered index creation was manually triggered before the data refresh+ # started, we need to wait for it to finish or the data refresh could destroy+ # the origin index. Realistically the data refresh is too slow to beat the+ # filtered index creation process, even if it was triggered immediately after+ # filtered index creation. However, it is safer to avoid the possibility+ # of the race condition altogether.+ # ``execution_date_fn`` is used to find the most recent run becuase+ # the filtered index createion DAGs are unscheduled so we can't derive+ # anything from the execution date of the current data refresh DAG.+ create_filtered_index_dag_id = (+ f"create_filtered_{data_refresh.media_type}_index"+ )+ wait_for_filtered_index_creation = ExternalTaskSensor(+ task_id="wait_for_create_and_populate_filtered_index",+ external_dag_id=create_filtered_index_dag_id,+ # Wait for the whole DAG, not just a part of it+ external_task_id=None,+ check_existence=False,+ poke_interval=poke_interval,+ execution_date_fn=lambda _: get_most_recent_dag_run(+ create_filtered_index_dag_id+ ),+ mode="reschedule",+ # Any "finished" state is sufficient for us to continue.+ allowed_states=[State.SUCCESS, State.FAILED],)++ tasks.append([wait_for_data_refresh, wait_for_filtered_index_creation])++ # Get the index currently mapped to our target alias, to delete later.+ get_current_index = ingestion_server.get_current_index(target_alias)tasks.append(get_current_index)# Generate a UUID suffix that will be used by the newly created index.@@ -186,56 +158,29 @@ def create_data_refresh_task_group(}for action, action_post_data in action_data_map.items():with TaskGroup(group_id=action) as task_group:- trigger = SimpleHttpOperator(- task_id=f"trigger_{action}",- http_conn_id="data_refresh",- endpoint="task",- method="POST",- headers={"Content-Type": "application/json"},- data=json.dumps(- action_post_data- | {- "model": data_refresh.media_type,- "action": action.upper(),- "index_suffix": XCOM_PULL_TEMPLATE.format(- generate_index_suffix.task_id, "return_value"- ),- }- ),- response_check=lambda response: response.status_code == 202,- response_filter=response_filter_data_refresh,- )- waiter = HttpSensor(- task_id=f"wait_for_{action}",- http_conn_id="data_refresh",- endpoint=XCOM_PULL_TEMPLATE.format(trigger.task_id, "return_value"),- method="GET",- response_check=response_check_wait_for_completion,- mode="reschedule",- poke_interval=poke_interval,- timeout=data_refresh.data_refresh_timeout.total_seconds(),+ ingestion_server.trigger_and_wait_for_task(+ action=action,+ model=data_refresh.media_type,+ data={+ "index_suffix": XCOM_PULL_TEMPLATE.format(+ generate_index_suffix.task_id, "return_value"+ ),+ }+ | action_post_data,+ timeout=data_refresh.data_refresh_timeout,)- trigger >> waitertasks.append(task_group)# Delete the alias' previous target index, now unused.- delete_old_index = SimpleHttpOperator(- task_id="delete_old_index",- http_conn_id="data_refresh",- endpoint="task",- method="POST",- headers={"Content-Type": "application/json"},- data=json.dumps(- {- "model": data_refresh.media_type,- "action": "DELETE_INDEX",- "index_suffix": XCOM_PULL_TEMPLATE.format(- get_current_index.task_id, "return_value"- ),- }- ),- response_check=lambda response: response.status_code == 202,+ delete_old_index = ingestion_server.trigger_task(+ action="DELETE_INDEX",+ model=data_refresh.media_type,+ data={+ "index_suffix": XCOM_PULL_TEMPLATE.format(+ get_current_index.task_id, "return_value"+ ),+ },)tasks.append(delete_old_index)diff --git a/catalog/dags/data_refresh/data_refresh_types.py b/catalog/dags/data_refresh/data_refresh_types.pyindex 4eb692bdf..4426453ca 100644--- a/catalog/dags/data_refresh/data_refresh_types.py+++ b/catalog/dags/data_refresh/data_refresh_types.py@@ -51,6 +51,7 @@ class DataRefresh:refresh_matview_timeout: timedelta = timedelta(hours=1)create_pop_constants_view_timeout: timedelta = timedelta(hours=1)create_materialized_view_timeout: timedelta = timedelta(hours=1)+ create_filtered_index_timeout: timedelta = timedelta(days=1)def __post_init__(self):self.dag_id = f"{self.media_type}_data_refresh"diff --git a/catalog/env.template b/catalog/env.templateindex 8c04388a8..204150827 100644--- a/catalog/env.template+++ b/catalog/env.template@@ -75,7 +75,7 @@ EMR_TEST_CONN_ID=emr_test# Connection to the Ingestion Server, used for managing data refreshes. Default is used to# connect to your locally running ingestion server.-AIRFLOW_CONN_DATA_REFRESH=http://172.17.0.1:8001+AIRFLOW_CONN_DATA_REFRESH=http://ingestion_server:8001# Django Admin url. Change the following line to use the appropriate environment.DJANGO_ADMIN_URL="https://localhost:8000/admin"diff --git a/catalog/justfile b/catalog/justfileindex 85cdadedb..4daf04650 100644--- a/catalog/justfile+++ b/catalog/justfile@@ -125,7 +125,7 @@ generate-dag-docs fail_on_diff="false":mv utilities/dag_doc_gen/DAGs.md DAGs.mdecho -n "Running linting..."# Linting step afterwards is necessary since the generated output differs greatly from what prettier expects- just ../lint &>/dev/null || true+ just ../lint prettier catalog/DAGs.md &>/dev/null || trueecho "Done!"if {{ fail_on_diff }}; thenset +ediff --git a/catalog/tests/dags/common/sensors/test_utils.py b/catalog/tests/dags/common/sensors/test_utils.pynew file mode 100644index 000000000..9cd721239--- /dev/null+++ b/catalog/tests/dags/common/sensors/test_utils.py@@ -0,0 +1,45 @@+from datetime import timedelta++import pytest+from airflow.models import DagRun+from airflow.models.dag import DAG+from airflow.utils.session import create_session+from airflow.utils.state import State+from airflow.utils.timezone import datetime+from airflow.utils.types import DagRunType++from common.sensors.utils import get_most_recent_dag_run+++TEST_DAG_ID = "data_refresh_dag_factory_test_dag"+TEST_DAG = DAG(TEST_DAG_ID, default_args={"owner": "airflow"})++[email protected](autouse=True)+def clean_db():+ with create_session() as session:+ session.query(DagRun).filter(DagRun.dag_id == TEST_DAG_ID).delete()+++def _create_dagrun(start_date, conf={}):+ return TEST_DAG.create_dagrun(+ start_date=start_date,+ execution_date=start_date,+ data_interval=(start_date, start_date),+ state=State.SUCCESS,+ run_type=DagRunType.MANUAL,+ conf=conf,+ )+++def test_get_most_recent_dag_run_returns_most_recent_execution_date():+ most_recent = datetime(2023, 5, 10)+ for i in range(3):+ _create_dagrun(most_recent - timedelta(days=i))++ assert get_most_recent_dag_run(TEST_DAG_ID) == most_recent+++def test_get_most_recent_dag_run_returns_empty_list_when_no_runs():+ # Relies on ``clean_db`` cleaning up DagRuns from other tests+ assert get_most_recent_dag_run(TEST_DAG_ID) == []diff --git a/catalog/tests/dags/test_dag_parsing.py b/catalog/tests/dags/test_dag_parsing.pyindex 361e0084c..e778f4a1f 100644--- a/catalog/tests/dags/test_dag_parsing.py+++ b/catalog/tests/dags/test_dag_parsing.py@@ -22,6 +22,7 @@ DAG_PATHS = ["maintenance/rotate_db_snapshots.py","database/recreate_popularity_calculation_dag_factory.py","data_refresh/dag_factory.py",+ "data_refresh/create_filtered_index_dag.py","oauth2/authorize_dag.py","oauth2/token_refresh_dag.py",]@@ -35,6 +36,7 @@ EXPECTED_COUNT = {),"database/recreate_popularity_calculation_dag_factory.py": len(MEDIA_TYPES),"data_refresh/dag_factory.py": len(MEDIA_TYPES),+ "data_refresh/create_filtered_index_dag.py": len(MEDIA_TYPES),}diff --git a/ingestion_server/ingestion_server/api.py b/ingestion_server/ingestion_server/api.pyindex 3103e0853..68d606e0d 100644--- a/ingestion_server/ingestion_server/api.py+++ b/ingestion_server/ingestion_server/api.py@@ -91,6 +91,8 @@ class TaskResource(BaseTaskResource):"index_suffix": {"type": "string"},"alias": {"type": "string"},"force_delete": {"type": "boolean"},+ "origin_index_suffix": {"type": "string"},+ "destination_index_suffix": {"type": "string"},},"required": ["model", "action"],"allOf": [diff --git a/ingestion_server/ingestion_server/indexer.py b/ingestion_server/ingestion_server/indexer.pyindex 3833a74a2..33e613690 100644--- a/ingestion_server/ingestion_server/indexer.py+++ b/ingestion_server/ingestion_server/indexer.py@@ -488,6 +488,21 @@ class TableIndexer:destination_index_suffix: str | None = None,**_,):+ """+ Create and populate a filtered index without documents with sensitive terms.++ :param model_name: The model/media type the filtered index is for.+ :param origin_index_suffix: The suffix of the origin index on which the+ filtered index should be based. If not supplied, the filtered index will be+ based upon the index aliased to ``model_name`` at the time of execution.+ :param destination_index_suffix: The suffix to use for the destination index.+ This can be configured independently of the origin index suffix to allow for+ multiple filtered index creations to occur against the same origin index, i.e.,+ in the case where sensitive terms change before a data refresh creates a new+ origin index and we wish to update the filtered index immediately. If not+ supplied, a UUID based suffix will be generated. This does not affect the+ final alias used.+ """# Allow relying on the model-name-based alias by# not suppliying `origin_index_suffix`source_index = (@@ -533,4 +548,6 @@ class TableIndexer:self.refresh(index_name=destination_index, change_settings=True)+ if self.progress is not None:+ self.progress.value = 100 # mark job as completedself.ping_callback()