Skip to content

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

Show duplicate record count in completion slack message (#442)

Madison Swain-Bowden8c87749f833b
diff --git a/openverse_catalog/dags/common/loader/loader.py b/openverse_catalog/dags/common/loader/loader.py
index 06614bbe9..23815c9ed 100644
--- a/openverse_catalog/dags/common/loader/loader.py
+++ b/openverse_catalog/dags/common/loader/loader.py
@@ -40,11 +40,14 @@ def load_from_s3(
media_type,
tsv_version,
identifier,
+ ti,
):
- sql.load_s3_data_to_intermediate_table(
+ loaded_count, cleaned_count = sql.load_s3_data_to_intermediate_table(
postgres_conn_id, bucket, key, identifier, media_type
)
- # Returns record count
- return sql.upsert_records_to_db_table(
+ upserted_count = sql.upsert_records_to_db_table(
postgres_conn_id, identifier, media_type=media_type, tsv_version=tsv_version
)
+ ti.xcom_push(key="loaded_count", value=loaded_count)
+ ti.xcom_push(key="cleaned_count", value=cleaned_count)
+ ti.xcom_push(key="upserted_count", value=upserted_count)
diff --git a/openverse_catalog/dags/common/loader/reporting.py b/openverse_catalog/dags/common/loader/reporting.py
index 466c1f77c..6d52da3d0 100644
--- a/openverse_catalog/dags/common/loader/reporting.py
+++ b/openverse_catalog/dags/common/loader/reporting.py
@@ -1,4 +1,7 @@
+from __future__ import annotations
+
import logging
+from typing import Optional
from common.slack import send_message
@@ -15,9 +18,10 @@ TIME_DURATION_UNITS = (
("min", 60),
("sec", 1),
)
+RecordCounts = dict[str, tuple[Optional[int], Optional[int], Optional[int]]]
-def humanize_time_duration(seconds):
+def humanize_time_duration(seconds: float) -> str:
if seconds == 0:
return "inf"
parts = []
@@ -28,21 +32,54 @@ def humanize_time_duration(seconds):
return ", ".join(parts)
-def report_completion(provider_name, duration, record_counts_by_media_type):
+def report_completion(
+ provider_name: str,
+ duration: float | str | None,
+ record_counts_by_media_type: RecordCounts,
+) -> None:
"""
Send a Slack notification when the load_data task has completed.
Messages are only sent out in production and if a Slack connection is defined.
In all cases the data is logged.
+
+ The following data is reported:
+ - `duration`: The time the pull data task took to complete. This value is
+ "No data" in cases where the pull data task failed.
+ - `cleaned`: The number of records that were removed after the data was loaded
+ into a temporary table. This could be the result of missing columns, or
+ due to multiple records that have the same provider & foreign ID.
+ - `duplicates`: The number of records that have unique provider & foreign IDs,
+ but are duplicated across URL. This can occur when a provider makes multiple,
+ discrete references to the same source media within their API.
+ - `upserted`: The final number of records that made it into the media table
+ within the catalog database.
"""
# Truncate the duration value if it's provided
if isinstance(duration, float):
duration = humanize_time_duration(duration)
# List record count per media type
- media_type_reports = "\n".join(
- f" - `{media_type}`: {record_count or '_No data_'}"
- for media_type, record_count in record_counts_by_media_type.items()
- )
+ media_type_reports = ""
+ for media_type, counts in record_counts_by_media_type.items():
+ loaded, cleaned, upserted = counts
+ if not upserted:
+ upserted_human_readable = "_No data_"
+ else:
+ upserted_human_readable = f"{upserted:,}"
+ media_type_reports += f" - `{media_type}`: {upserted_human_readable}"
+ if any([count is None for count in counts]):
+ # Can't make calculation without data
+ continue
+ duplicates = loaded - cleaned - upserted
+ if duplicates or cleaned:
+ extras = []
+ if cleaned:
+ extras.append(f"{cleaned:,} cleaned")
+ if duplicates:
+ extras.append(f"{duplicates:,} duplicates")
+ if extras:
+ media_type_reports += f" _({', '.join(extras)})_"
+ media_type_reports += "\n"
# Collect data into a single message
message = f"""
diff --git a/openverse_catalog/dags/common/loader/sql.py b/openverse_catalog/dags/common/loader/sql.py
index 0972a4637..cb8b078bb 100644
--- a/openverse_catalog/dags/common/loader/sql.py
+++ b/openverse_catalog/dags/common/loader/sql.py
@@ -48,6 +48,7 @@ TSV_COLUMNS = {
IMAGE: CURRENT_IMAGE_TSV_COLUMNS,
}
CURRENT_TSV_VERSION = "001"
+RETURN_ROW_COUNT = lambda c: c.rowcount # noqa: E731
def create_column_definitions(table_columns: List[Column], is_loading=True):
@@ -134,12 +135,12 @@ def load_s3_data_to_intermediate_table(
s3_key,
identifier,
media_type=IMAGE,
-):
+) -> tuple[int, int]:
load_table = _get_load_table_name(identifier, media_type=media_type)
logger.info(f"Loading {s3_key} from S3 Bucket {bucket} into {load_table}")
postgres = PostgresHook(postgres_conn_id=postgres_conn_id)
- postgres.run(
+ loaded_count = postgres.run(
dedent(
f"""
SELECT aws_s3.table_import_from_s3(
@@ -151,12 +152,15 @@ def load_s3_data_to_intermediate_table(
'us-east-1'
);
"""
- )
+ ),
+ handler=lambda c: c.fetchone()[0],
)
- _clean_intermediate_table_data(postgres, load_table)
+ logger.info(f"Succesfully loaded {loaded_count} records from S3")
+ cleaned_count = _clean_intermediate_table_data(postgres, load_table)
+ return loaded_count, cleaned_count
-def _clean_intermediate_table_data(postgres_hook, load_table):
+def _clean_intermediate_table_data(postgres_hook, load_table) -> int:
"""
Necessary for old TSV files that have not been cleaned up,
using `MediaStore` class:
@@ -165,9 +169,13 @@ def _clean_intermediate_table_data(postgres_hook, load_table):
Also removes any duplicate rows that have the same `provider`
and `foreign_id`.
"""
+ affected_count = 0
for column in required_columns:
- postgres_hook.run(f"DELETE FROM {load_table} WHERE {column.db_name} IS NULL;")
- postgres_hook.run(
+ affected_count += postgres_hook.run(
+ f"DELETE FROM {load_table} WHERE {column.db_name} IS NULL;",
+ handler=RETURN_ROW_COUNT,
+ )
+ affected_count += postgres_hook.run(
dedent(
f"""
DELETE FROM {load_table} p1
@@ -177,8 +185,11 @@ def _clean_intermediate_table_data(postgres_hook, load_table):
AND p1.{col.PROVIDER.db_name} = p2.{col.PROVIDER.db_name}
AND p1.{col.FOREIGN_ID.db_name} = p2.{col.FOREIGN_ID.db_name};
"""
- )
+ ),
+ handler=RETURN_ROW_COUNT,
)
+ logger.info(f"Cleaned {affected_count} rows")
+ return affected_count
def _is_tsv_column_from_different_version(
@@ -265,7 +276,7 @@ def upsert_records_to_db_table(
{upsert_conflict_string}
"""
)
- return postgres.run(upsert_query, handler=lambda c: c.rowcount)
+ return postgres.run(upsert_query, handler=RETURN_ROW_COUNT)
def drop_load_table(
diff --git a/openverse_catalog/dags/common/provider_dag_factory.py b/openverse_catalog/dags/common/provider_dag_factory.py
index 485401ba7..43dfbba5e 100644
--- a/openverse_catalog/dags/common/provider_dag_factory.py
+++ b/openverse_catalog/dags/common/provider_dag_factory.py
@@ -217,7 +217,7 @@ def create_provider_api_workflow(
)
load_tasks = []
- record_counts_by_media_type = {}
+ record_counts_by_media_type: reporting.RecordCounts = {}
for media_type in media_types:
with TaskGroup(group_id=f"load_{media_type}_data") as load_data:
create_loading_table = PythonOperator(
@@ -272,8 +272,10 @@ def create_provider_api_workflow(
[create_loading_table, copy_to_s3] >> load_from_s3
load_from_s3 >> drop_loading_table
- record_counts_by_media_type[media_type] = XCOM_PULL_TEMPLATE.format(
- load_from_s3.task_id, "return_value"
+ record_counts_by_media_type[media_type] = (
+ XCOM_PULL_TEMPLATE.format(load_from_s3.task_id, "loaded_count"),
+ XCOM_PULL_TEMPLATE.format(load_from_s3.task_id, "cleaned_count"),
+ XCOM_PULL_TEMPLATE.format(load_from_s3.task_id, "upserted_count"),
)
load_tasks.append(load_data)
diff --git a/tests/dags/common/loader/test_reporting.py b/tests/dags/common/loader/test_reporting.py
index 0f7c57622..3fc2a5e10 100644
--- a/tests/dags/common/loader/test_reporting.py
+++ b/tests/dags/common/loader/test_reporting.py
@@ -18,11 +18,56 @@ def test_report_completion(should_send_message):
with mock.patch(
"common.slack.should_send_message", return_value=should_send_message
):
- report_completion("Jamendo", None, {"audio": 100})
+ report_completion("Jamendo", None, {"audio": (100, 100, 100)})
# Send message is only called if `should_send_message` is True.
send_message_mock.called = should_send_message
+def _make_report_completion_contents_data(media_type: str):
+ return [
+ # Happy path
+ ({media_type: (100, 0, 100)}, f" - `{media_type}`: 100"),
+ # Cleaned detected
+ ({media_type: (100, 10, 90)}, f" - `{media_type}`: 90 _(10 cleaned)_"),
+ # Duplicates detected
+ ({media_type: (100, 0, 90)}, f" - `{media_type}`: 90 _(10 duplicates)_"),
+ # Cleaned and duplicates detected
+ (
+ {media_type: (100, 10, 75)},
+ f" - `{media_type}`: 75 _(10 cleaned, 15 duplicates)_",
+ ),
+ # Cleaned and duplicates, large numbers
+ (
+ {media_type: (100_000, 10_000, 75_000)},
+ f" - `{media_type}`: 75,000 _(10,000 cleaned, 15,000 duplicates)_",
+ ),
+ # Cases with missing data
+ ({media_type: (None, None, None)}, f" - `{media_type}`: _No data_"),
+ ({media_type: (100, None, None)}, f" - `{media_type}`: _No data_"),
+ ({media_type: (None, 100, None)}, f" - `{media_type}`: _No data_"),
+ ({media_type: (None, None, 100)}, f" - `{media_type}`: 100"),
+ ]
+
+
+# This sets up parameterizations for both audio and image simultaneously, in order
+# to test that the statistics are reported accurately independent of each other.
+ "audio_data, audio_expected", _make_report_completion_contents_data("audio")
+)
+ "image_data, image_expected", _make_report_completion_contents_data("image")
+)
+def test_report_completion_contents(
+ audio_data, audio_expected, image_data, image_expected
+):
+ with mock.patch("common.loader.reporting.send_message") as send_message_mock:
+ report_completion("Jamendo", None, {**audio_data, **image_data})
+ for expected in [audio_expected, image_expected]:
+ assert (
+ expected in send_message_mock.call_args.args[0]
+ ), "Completion message doesn't contain expected text"
+
+
@pytest.mark.parametrize(
"seconds, expected",
[