Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Make batched_update DAG resistent to mid-update failures (#2570)
Staci Mullins4c3e6ac46768
diff --git a/catalog/DAGs.md b/catalog/DAGs.mdindex a537c5319..8ca21abe2 100644--- a/catalog/DAGs.md+++ b/catalog/DAGs.md@@ -256,8 +256,6 @@ Optional params:- batch_size: int number of records to process in each batch. By default, 10_000- update_timeout: int number of seconds to run an individual batch update beforetiming out. By default, 3600 (or one hour)-- batch_start: int index into the temp table at which to start the update. By- default, this is 0 and all rows in the temp table are updated.- resume_update: boolean indicating whether to attempt to resume an update usingan existing temp table matching the `query_id`. When True, a new temp table isnot created.@@ -276,24 +274,19 @@ to null would look like this:}```-It is possible to resume an update from an arbitrary starting point on an-existing temp table, for example if a DAG succeeds in creating the temp table-but fails midway through the update. To do so, set the `resume_update` param to-True and select your desired `batch_start`. For instance, if the example DAG-given above failed after processing the first 50_000 records, you might run:--```-{- "query_id": "my_flickr_query",- "table_name": "image",- "select_query": "WHERE provider='flickr'",- "update_query": "SET thumbnail=null",- "batch_size": 10,- "batch_start": 50000,- "resume_update": true,- "dry_run": false-}-```+The `update_batches` task automatically keeps track of its progress in an+Airflow variable suffixed with the `query_id`. If the task fails, when it+resumes (either through a retry or by being manually cleared), it will pick up+from where it left off. Manually managing this Airflow variable should not be+necessary.++It is also possible to start an entirely new DagRun using an existing temp+table, by setting the `resume_update` param to True. With this option enabled,+the DAG will skip creating the temp table and instead attempt to run an update+with an existing temp table matching the `query_id`. This option should only be+used when the DagRun configuration needs to be changed after the table was+already created: for example, if there was a problem with the `update_query`+which caused DAG failures during the `update_batches` step.## `check_silenced_dags`diff --git a/catalog/dags/database/batched_update/batched_update.py b/catalog/dags/database/batched_update/batched_update.pyindex ec7923722..6044a81e5 100644--- a/catalog/dags/database/batched_update/batched_update.py+++ b/catalog/dags/database/batched_update/batched_update.py@@ -2,6 +2,7 @@ import loggingfrom datetime import timedeltafrom airflow.decorators import task+from airflow.models import Variablefrom airflow.models.abstractoperator import AbstractOperatorfrom common import slack@@ -36,22 +37,24 @@ def resume_update(@task-def get_expected_update_count(query_id: str, batch_start: int | None, dry_run: bool):- """- Get the number of records left to update, when resuming an update- on an existing temp table.- """- total_count = run_sql.function(+def get_expected_update_count(+ query_id: str, total_row_count: int | None, dry_run: bool+):+ """Get the number of records in the temp table."""+ # If we created the temp table as part of this DagRun, the total row count is+ # passed in through XComs and is simply forwarded.+ if total_row_count is not None:+ return total_row_count++ # If `resume_update` is True, we skip the table creation task and the count will+ # not be available in XComs. We instead explicitly query the table for the count.+ return run_sql.function(dry_run=dry_run,- sql_template=constants.SELECT_TEMP_TABLE_QUERY,+ sql_template=constants.SELECT_TEMP_TABLE_COUNT_QUERY,query_id=query_id,handler=_single_value,)- if batch_start:- total_count -= batch_start- return max(total_count, 0)-@taskdef run_sql(@@ -89,23 +92,27 @@ def run_sql(@taskdef update_batches(- expected_row_count: int,+ total_row_count: int,batch_size: int,dry_run: bool,table_name: str,query_id: str,update_query: str,update_timeout: int,- batch_start: int = 0,+ batch_start_var: str,postgres_conn_id: str = POSTGRES_CONN_ID,task: AbstractOperator = None,**kwargs,):- updated_count = 0- if batch_start is None:- batch_start = 0+ # Progress is tracked in an Airflow variable. When the task run starts, we resume+ # from the start point set by this variable (defaulted to 0). This prevents the+ # task from starting over at the beginning on retries.+ initial_batch_start = Variable.get(batch_start_var, 0, deserialize_json=True)+ logger.info(f"Starting at {initial_batch_start}")- while batch_start <= expected_row_count:+ updated_count = 0+ batch_start = initial_batch_start+ while batch_start <= total_row_count:batch_end = batch_start + batch_sizelogger.info(f"Updating rows with id {batch_start} through {batch_end}.")@@ -114,7 +121,7 @@ def update_batches(sql_template=constants.UPDATE_BATCH_QUERY,query_id=query_id,# Only log the query the first time, so as not to spam the logs- log_sql=batch_start == 1,+ log_sql=batch_start == initial_batch_start,postgres_conn_id=postgres_conn_id,task=task,timeout=update_timeout,@@ -126,14 +133,21 @@ def update_batches(updated_count += countbatch_start = batch_end- logger.info(- f"Updated {updated_count} rows. {expected_row_count - updated_count}"- " remaining."- )++ # Update the Airflow variable to the next value of batch_start.+ Variable.set(batch_start_var, batch_end)++ remaining_count = max(total_row_count - initial_batch_start - updated_count, 0)+ logger.info(f"Updated {updated_count} rows. {remaining_count} remaining.")return updated_count+@task+def drop_temp_airflow_variable(airflow_var: str):+ Variable.delete(airflow_var)++@taskdef notify_slack(text: str, dry_run: bool) -> None:if not dry_run:diff --git a/catalog/dags/database/batched_update/batched_update_dag.py b/catalog/dags/database/batched_update/batched_update_dag.pyindex 6a137a22c..b86d8591f 100644--- a/catalog/dags/database/batched_update/batched_update_dag.py+++ b/catalog/dags/database/batched_update/batched_update_dag.py@@ -31,8 +31,6 @@ Optional params:* batch_size: int number of records to process in each batch. By default, 10_000* update_timeout: int number of seconds to run an individual batch update before timingout. By default, 3600 (or one hour)-* batch_start: int index into the temp table at which to start the update. By default,- this is 0 and all rows in the temp table are updated.* resume_update: boolean indicating whether to attempt to resume an update using anexisting temp table matching the `query_id`. When True, a new temptable is not created.@@ -51,24 +49,18 @@ null would look like this:}```-It is possible to resume an update from an arbitrary starting point on an existing-temp table, for example if a DAG succeeds in creating the temp table but fails midway-through the update. To do so, set the `resume_update` param to True and select your-desired `batch_start`. For instance, if the example DAG given above failed after-processing the first 50_000 records, you might run:--```-{- "query_id": "my_flickr_query",- "table_name": "image",- "select_query": "WHERE provider='flickr'",- "update_query": "SET thumbnail=null",- "batch_size": 10,- "batch_start": 50000,- "resume_update": true,- "dry_run": false-}-```+The `update_batches` task automatically keeps track of its progress in an Airflow+variable suffixed with the `query_id`. If the task fails, when it resumes (either+through a retry or by being manually cleared), it will pick up from where it left+off. Manually managing this Airflow variable should not be necessary.++It is also possible to start an entirely new DagRun using an existing temp table,+by setting the `resume_update` param to True. With this option enabled, the+DAG will skip creating the temp table and instead attempt to run an update with an+existing temp table matching the `query_id`. This option should only be used when+the DagRun configuration needs to be changed after the table was already created:+for example, if there was a problem with the `update_query` which caused DAG+failures during the `update_batches` step."""@@ -81,6 +73,7 @@ from airflow.utils.trigger_rule import TriggerRulefrom common.constants import AUDIO, DAG_DEFAULT_ARGS, MEDIA_TYPESfrom database.batched_update import constantsfrom database.batched_update.batched_update import (+ drop_temp_airflow_variable,get_expected_update_count,notify_slack,resume_update,@@ -102,10 +95,7 @@ logger = logging.getLogger(__name__)max_active_runs=10,dagrun_timeout=constants.DAGRUN_TIMEOUT,doc_md=__doc__,- default_args={- **DAG_DEFAULT_ARGS,- "retries": 0,- },+ default_args=DAG_DEFAULT_ARGS,render_template_as_native_obj=True,params={"query_id": Param(@@ -152,22 +142,12 @@ logger = logging.getLogger(__name__)" should take for a single batch to be updated."),),- "batch_start": Param(- default=None,- type=["integer", "null"],- description=(- "Optionally, a row_id from which to begin updating records. By"- " default, all records matching the SELECT will be updated."- ),- minimum=0,- ),"resume_update": Param(default=False,type="boolean",description=(- "Whether to resume an existing update. When True, the DAG will skip"- " creating a temp table, and instead try to use an existing temp table"- " matching the `query_id`."+ "Whether to skip creating the temp table. When enabled, the DAG will"+ " try to use an existing temp table matching the `query_id`."),),"dry_run": Param(@@ -181,6 +161,9 @@ logger = logging.getLogger(__name__)},)def batched_update():+ # Unique Airflow variable name for tracking the batch_start for this query+ BATCH_START_VAR = "batched_update_start_{{ params.query_id }}"+check_for_resume_update = resume_update(resume_update="{{ params.resume_update }}",)@@ -208,25 +191,25 @@ def batched_update():trigger_rule=TriggerRule.NONE_FAILED,)(query_id="{{ params.query_id }}",- batch_start="{{ params.batch_start }}",+ total_row_count=select_rows_to_update,dry_run="{{ params.dry_run }}",)- check_for_resume_update >> [select_rows_to_update, expected_count]- select_rows_to_update >> create_index >> expected_count-notify_before_update = notify_slack.override(task_id="notify_before_update")(text=f"Preparing to update {select_rows_to_update} rows for update:"" {{ params.query_id }}",dry_run="{{ params.dry_run}}",)+ check_for_resume_update >> [select_rows_to_update, expected_count]+ select_rows_to_update >> [create_index, expected_count]+perform_batched_update = update_batches.override(execution_timeout=constants.UPDATE_TIMEOUT)(- expected_row_count=expected_count,+ total_row_count=expected_count,batch_size="{{ params.batch_size }}",- batch_start="{{ params.batch_start }}",+ batch_start_var=BATCH_START_VAR,dry_run="{{ params.dry_run }}",table_name="{{ params.table_name }}",query_id="{{ params.query_id }}",@@ -253,6 +236,11 @@ def batched_update():query_id="{{ params.query_id }}",)+ # Clean up the variable we used for tracking the last row+ drop_variable = drop_temp_airflow_variable(+ airflow_var=BATCH_START_VAR,+ )+# If there was an error, notify to Slack that the temporary table must be# dropped manually or the DAG retried.notify_failure = notify_slack.override(@@ -266,6 +254,7 @@ def batched_update():perform_batched_update >> [notify_updated_count,drop_temporary_table,+ drop_variable,notify_failure,]diff --git a/catalog/dags/database/batched_update/constants.py b/catalog/dags/database/batched_update/constants.pyindex 4d74d86b4..5bc6d960f 100644--- a/catalog/dags/database/batched_update/constants.py+++ b/catalog/dags/database/batched_update/constants.py@@ -26,7 +26,7 @@ CREATE_TEMP_TABLE_QUERY = """{select_query};"""CREATE_TEMP_TABLE_INDEX_QUERY = "CREATE INDEX ON {temp_table_name}(row_id)"-SELECT_TEMP_TABLE_QUERY = """+SELECT_TEMP_TABLE_COUNT_QUERY = """SELECT COUNT(*)FROM {temp_table_name};"""diff --git a/catalog/tests/dags/database/test_batched_update.py b/catalog/tests/dags/database/test_batched_update.pyindex fe2bb1a83..d92c70422 100644--- a/catalog/tests/dags/database/test_batched_update.py+++ b/catalog/tests/dags/database/test_batched_update.py@@ -3,6 +3,7 @@ import uuidimport psycopg2import pytest+from airflow.models import Variablefrom catalog.tests.test_utils import sqlfrom common.storage import columns as col@@ -32,6 +33,11 @@ def identifier(request):return f"{hash(request.node.name)}".replace("-", "_")+def batch_start_var(identifier):+ return f"test_{identifier}_batch_start"++@pytest.fixturedef image_table(identifier):# Parallelized tests need to use distinct database tables@@ -44,7 +50,7 @@ def temp_table(identifier):@pytest.fixture-def postgres_with_image_and_temp_table(image_table, temp_table):+def postgres_with_image_and_temp_table(batch_start_var, image_table, temp_table):conn = psycopg2.connect(sql.POSTGRES_TEST_URI)cur = conn.cursor()drop_table_query = f"""@@ -61,6 +67,9 @@ def postgres_with_image_and_temp_table(image_table, temp_table):yield sql.PostgresRef(cursor=cur, connection=conn)cur.execute(drop_table_query)+ # Drop the test airflow variable+ Variable.delete(batch_start_var)+cur.close()conn.commit()conn.close()@@ -116,23 +125,23 @@ def _load_sample_data_into_image_table(image_table, postgres):@pytest.mark.parametrize(- "batch_start, expected_count",- [- (None, 3),- (0, 3),- (1, 2),- (2, 1),- # Batch start greater than the total number of records- (4, 0),- ],+ "total_row_count",+ (+ # Simulate a 'normal' flow, where the total count is passed into+ # the task via XCOM after creating the table+ 3,+ # Simulate a DagRun that is using `resume_update` to skip creating a+ # new table, so None is passed in from XCOM and we need to run a+ # `SELECT COUNT(*)` on the temp table+ None,+ ),)def test_get_expected_update_count(postgres_with_image_and_temp_table,image_table,temp_table,identifier,- batch_start,- expected_count,+ total_row_count,):# Load sample data into the image table_load_sample_data_into_image_table(@@ -149,10 +158,10 @@ def test_get_expected_update_count(postgres_with_image_and_temp_table.connection.commit()total_count = get_expected_update_count.function(- query_id=f"test_{identifier}", batch_start=batch_start, dry_run=False+ query_id=f"test_{identifier}", total_row_count=total_row_count, dry_run=False)- assert total_count == expected_count+ assert total_count == 3def test_update_batches(@@ -160,6 +169,7 @@ def test_update_batches(image_table,temp_table,identifier,+ batch_start_var,):# Load sample data into the image table_load_sample_data_into_image_table(@@ -181,10 +191,11 @@ def test_update_batches(dry_run=False,query_id=f"test_{identifier}",table_name=image_table,- expected_row_count=2,+ total_row_count=2,batch_size=1,update_query=update_query,update_timeout=3600,+ batch_start_var=batch_start_var,postgres_conn_id=sql.POSTGRES_CONN_ID,)@@ -212,6 +223,7 @@ def test_update_batches_dry_run(image_table,temp_table,identifier,+ batch_start_var,):# Load sample data into the image table_load_sample_data_into_image_table(@@ -232,12 +244,12 @@ def test_update_batches_dry_run(updated_count = update_batches.function(dry_run=True,query_id=f"test_{identifier}",- batch_start=None,table_name=image_table,- expected_row_count=2,+ total_row_count=2,batch_size=1,update_query=update_query,update_timeout=3600,+ batch_start_var=batch_start_var,postgres_conn_id=sql.POSTGRES_CONN_ID,)@@ -252,11 +264,12 @@ def test_update_batches_dry_run(assert row[sql.title_idx] == OLD_TITLE-def test_update_batches_from_batch_start(+def test_update_batches_resuming_from_batch_start(postgres_with_image_and_temp_table,image_table,temp_table,identifier,+ batch_start_var,):# Load sample data into the image table_load_sample_data_into_image_table(@@ -272,17 +285,20 @@ def test_update_batches_from_batch_start(postgres_with_image_and_temp_table.cursor.execute(create_temp_table_query)postgres_with_image_and_temp_table.connection.commit()- # Test update query, setting batch_start to 1+ # Set the batch_start Airflow variable to 1, to skip the first+ # record+ Variable.set(batch_start_var, 1)+update_query = f"SET title='{NEW_TITLE}'"updated_count = update_batches.function(dry_run=False,query_id=f"test_{identifier}",table_name=image_table,- expected_row_count=2,+ total_row_count=3,batch_size=1,- batch_start=1,update_query=update_query,update_timeout=3600,+ batch_start_var=batch_start_var,postgres_conn_id=sql.POSTGRES_CONN_ID,)