Skip to content

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

Clean up Popularity Refresh notifications and adjust poke interval (#2740)

Staci Mullinsf3098b9df7f0
diff --git a/catalog/dags/data_refresh/reporting.py b/catalog/dags/data_refresh/reporting.py
index e82c4adc9..967ef32fa 100644
--- a/catalog/dags/data_refresh/reporting.py
+++ b/catalog/dags/data_refresh/reporting.py
@@ -11,7 +11,7 @@ def report_status(media_type: str, message: str, dag_id: str):
slack.send_message(
text=message,
dag_id=dag_id,
- username="Data Refresh Notification",
+ username=f"{dag_id.replace('_', ' ').title()} Notification",
icon_emoji="arrows_counterclockwise",
)
return message
diff --git a/catalog/dags/database/batched_update/batched_update.py b/catalog/dags/database/batched_update/batched_update.py
index 6044a81e5..4d644ee09 100644
--- a/catalog/dags/database/batched_update/batched_update.py
+++ b/catalog/dags/database/batched_update/batched_update.py
@@ -108,14 +108,14 @@ def update_batches(
# 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}")
+ logger.info(f"Starting at {initial_batch_start:,}")
updated_count = 0
batch_start = initial_batch_start
while batch_start <= total_row_count:
batch_end = batch_start + batch_size
- logger.info(f"Updating rows with id {batch_start} through {batch_end}.")
+ logger.info(f"Updating rows with id {batch_start:,} through {batch_end:,}.")
count = run_sql.function(
dry_run=dry_run,
sql_template=constants.UPDATE_BATCH_QUERY,
@@ -137,8 +137,10 @@ def update_batches(
# 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.")
+ percent_complete = (min(batch_end, total_row_count) / total_row_count) * 100
+ logger.info(
+ f"Updated {updated_count:,} rows. {percent_complete:.2f}% complete."
+ )
return updated_count
@@ -149,7 +151,18 @@ def drop_temp_airflow_variable(airflow_var: str):
@task
-def notify_slack(text: str, dry_run: bool) -> None:
+def notify_slack(text: str, dry_run: bool, count: int | None = None) -> str:
+ """
+ Send a message to Slack, or simply log if this is a dry run.
+ If a `count` is supplied, it is formatted and inserted into the text. This is
+ necessary because `count` is a value pulled from XComs, and cannot be formatted
+ in the task arguments.
+ """
+
+ if count is not None:
+ # Print integers with comma separator
+ text = text.format(count=f"{count:,}")
+
if not dry_run:
slack.send_message(
text,
@@ -159,3 +172,5 @@ def notify_slack(text: str, dry_run: bool) -> None:
)
else:
logger.info(text)
+
+ return text
diff --git a/catalog/dags/database/batched_update/batched_update_dag.py b/catalog/dags/database/batched_update/batched_update_dag.py
index b86d8591f..a698d79eb 100644
--- a/catalog/dags/database/batched_update/batched_update_dag.py
+++ b/catalog/dags/database/batched_update/batched_update_dag.py
@@ -196,9 +196,9 @@ def batched_update():
)
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 }}",
+ text="Preparing to update {count} rows for query: {{ params.query_id }}",
dry_run="{{ params.dry_run}}",
+ count=select_rows_to_update,
)
check_for_resume_update >> [select_rows_to_update, expected_count]
@@ -220,9 +220,9 @@ def batched_update():
expected_count >> [notify_before_update, perform_batched_update]
notify_updated_count = notify_slack.override(task_id="notify_updated_count")(
- text=f"Updated {perform_batched_update} records for update:"
- " {{ params.query_id }}",
+ text="Updated {count} records for query: {{ params.query_id }}",
dry_run="{{ params.dry_run}}",
+ count=perform_batched_update,
)
# The temporary table is only dropped if all updates were successful; this
diff --git a/catalog/dags/popularity/dag_factory.py b/catalog/dags/popularity/dag_factory.py
index 826c0a123..dfb55645e 100644
--- a/catalog/dags/popularity/dag_factory.py
+++ b/catalog/dags/popularity/dag_factory.py
@@ -37,7 +37,7 @@ from popularity.refresh_popularity_metrics_task_factory import (
)
from common import slack
-from common.constants import DAG_DEFAULT_ARGS, POSTGRES_CONN_ID, REFRESH_POKE_INTERVAL
+from common.constants import DAG_DEFAULT_ARGS, POSTGRES_CONN_ID
from common.popularity import sql
from database.batched_update.constants import DAG_ID as BATCHED_UPDATE_DAG_ID
@@ -49,7 +49,7 @@ logger = logging.getLogger(__name__)
def notify_slack(text: str, media_type: str, dag_id: str) -> None:
slack.send_message(
text,
- username=f"{media_type} Popularity Refresh",
+ username=f"{media_type.capitalize()} Popularity Refresh",
icon_emoji=":database:",
dag_id=dag_id,
)
@@ -165,7 +165,8 @@ def create_popularity_refresh_dag(popularity_refresh: PopularityRefresh):
wait_for_completion=True,
# Release the worker slot while waiting
deferrable=True,
- poke_interval=REFRESH_POKE_INTERVAL,
+ poke_interval=popularity_refresh.poke_interval,
+ execution_timeout=popularity_refresh.refresh_popularity_timeout,
retries=0,
).expand(
# Build the conf for each provider
diff --git a/catalog/dags/popularity/popularity_refresh_types.py b/catalog/dags/popularity/popularity_refresh_types.py
index a8aefd465..7d946493c 100644
--- a/catalog/dags/popularity/popularity_refresh_types.py
+++ b/catalog/dags/popularity/popularity_refresh_types.py
@@ -5,9 +5,12 @@ configuration for a Popularity Refresh DAG, and defines the actual
`POPULARITY_REFRESH_CONFIGS` for each of our media types. This configuration info
is used to generate the dynamic Popularity Refresh dags.
"""
+import os
from dataclasses import dataclass, field
from datetime import datetime, timedelta
+from common.constants import REFRESH_POKE_INTERVAL
+
@dataclass
class PopularityRefresh:
@@ -27,12 +30,17 @@ class PopularityRefresh:
schedule: string giving the schedule on which the DAG
should be run. Passed to the
airflow.dag.DAG __init__ method.
+ refresh_popularity_timeout: timedelta expressing amount of time the entire
+ popularity refresh batched update may take.
refresh_popularity_batch_timeout: timedelta expressing the amount of time
refreshing popularity scores for an individual
batch of records may take.
refresh_metrics_timeout: timedelta expressing amount of time the
refresh popularity metrics and constants
may take.
+ poke_interval: int number of seconds to wait between
+ checks to see if the batched updates have
+ completed.
"""
dag_id: str = field(init=False)
@@ -45,8 +53,10 @@ class PopularityRefresh:
schedule: str | None = None
# Initial timeouts are generous; they should be updated after assessing the
# performance in https://github.com/WordPress/openverse/issues/2092
+ refresh_popularity_timeout: timedelta = timedelta(days=30)
refresh_popularity_batch_timeout: timedelta = timedelta(hours=1)
refresh_metrics_timeout: timedelta = timedelta(hours=1)
+ poke_interval: int = REFRESH_POKE_INTERVAL
def __post_init__(self):
self.dag_id = f"{self.media_type}_popularity_refresh"
@@ -57,5 +67,9 @@ POPULARITY_REFRESH_CONFIGS = [
media_type="image",
refresh_metrics_timeout=timedelta(hours=24),
),
- PopularityRefresh(media_type="audio"),
+ PopularityRefresh(
+ media_type="audio",
+ # Poke every minute, instead of every thirty minutes
+ poke_interval=int(os.getenv("DATA_REFRESH_POKE_INTERVAL", 60)),
+ ),
]
diff --git a/catalog/tests/dags/database/test_batched_update.py b/catalog/tests/dags/database/test_batched_update.py
index d92c70422..4b08b3f01 100644
--- a/catalog/tests/dags/database/test_batched_update.py
+++ b/catalog/tests/dags/database/test_batched_update.py
@@ -11,6 +11,7 @@ from common.storage.db_columns import IMAGE_TABLE_COLUMNS
from database.batched_update import constants
from database.batched_update.batched_update import (
get_expected_update_count,
+ notify_slack,
update_batches,
)
@@ -318,3 +319,24 @@ def test_update_batches_resuming_from_batch_start(
assert actual_rows[1][sql.title_idx] == NEW_TITLE
assert actual_rows[2][sql.fid_idx] == FID_C
assert actual_rows[2][sql.title_idx] == NEW_TITLE
+
+
+ "text, count, expected_message",
+ [
+ ("Updated {count} records", 1000000, "Updated 1,000,000 records"),
+ (
+ "Updated {count} records",
+ 2,
+ "Updated 2 records",
+ ),
+ (
+ "A message without a count",
+ None,
+ "A message without a count",
+ ),
+ ],
+)
+def test_notify_slack(text, count, expected_message):
+ actual_message = notify_slack.function(text, True, count)
+ assert actual_message == expected_message