Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Improved load reporting (#471)
Madison Swain-Bowdenc928589b9613
diff --git a/openverse_catalog/dags/common/loader/loader.py b/openverse_catalog/dags/common/loader/loader.pyindex 23815c9ed..21988097f 100644--- a/openverse_catalog/dags/common/loader/loader.py+++ b/openverse_catalog/dags/common/loader/loader.py@@ -1,5 +1,6 @@from common.loader import paths, s3, sqlfrom common.loader.paths import _extract_media_type+from common.loader.reporting import RecordMetricsdef copy_to_s3(output_dir, bucket, identifier, aws_conn_id):@@ -40,14 +41,12 @@ def load_from_s3(media_type,tsv_version,identifier,- ti,-):- loaded_count, cleaned_count = sql.load_s3_data_to_intermediate_table(+) -> RecordMetrics:+ loaded, missing_columns, foreign_id_dup = sql.load_s3_data_to_intermediate_table(postgres_conn_id, bucket, key, identifier, media_type)- upserted_count = sql.upsert_records_to_db_table(+ upserted = 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)+ url_dup = loaded - missing_columns - foreign_id_dup - upserted+ return RecordMetrics(upserted, missing_columns, foreign_id_dup, url_dup)diff --git a/openverse_catalog/dags/common/loader/reporting.py b/openverse_catalog/dags/common/loader/reporting.pyindex 6d52da3d0..b74ad8f09 100644--- a/openverse_catalog/dags/common/loader/reporting.py+++ b/openverse_catalog/dags/common/loader/reporting.py@@ -1,7 +1,7 @@from __future__ import annotationsimport logging-from typing import Optional+from typing import NamedTuple, Optionalfrom common.slack import send_message@@ -18,7 +18,16 @@ TIME_DURATION_UNITS = (("min", 60),("sec", 1),)-RecordCounts = dict[str, tuple[Optional[int], Optional[int], Optional[int]]]+++class RecordMetrics(NamedTuple):+ upserted: Optional[int]+ missing_columns: Optional[int]+ foreign_id_dup: Optional[int]+ url_dup: Optional[int]+++MediaTypeRecordMetrics = dict[str, RecordMetrics]def humanize_time_duration(seconds: float) -> str:@@ -35,7 +44,7 @@ def humanize_time_duration(seconds: float) -> str:def report_completion(provider_name: str,duration: float | str | None,- record_counts_by_media_type: RecordCounts,+ record_counts_by_media_type: MediaTypeRecordMetrics,) -> None:"""Send a Slack notification when the load_data task has completed.@@ -45,10 +54,12 @@ def report_completion(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,+ - `missing_columns`: The number of records that were removed after the data was+ loaded into a temporary table due to missing data in required columns.+ - `foreign_id_dup`: The number of records that were removed after the data was+ loaded into a temporary table due to multiple records having the same+ provider & foreign ID.+ - `url_dup`: 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@@ -61,24 +72,23 @@ def report_completion(# List record count per media typemedia_type_reports = ""for media_type, counts in record_counts_by_media_type.items():- loaded, cleaned, upserted = counts- if not upserted:+ if not counts.upserted:upserted_human_readable = "_No data_"else:- upserted_human_readable = f"{upserted:,}"+ upserted_human_readable = f"{counts.upserted:,}"media_type_reports += f" - `{media_type}`: {upserted_human_readable}"if any([count is None for count in counts]):# Can't make calculation without datacontinue- 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)})_"+ extras = []+ if counts.missing_columns:+ extras.append(f"{counts.missing_columns:,} missing columns")+ if counts.foreign_id_dup:+ extras.append(f"{counts.foreign_id_dup:,} duplicate foreign IDs")+ if counts.url_dup:+ extras.append(f"{counts.url_dup:,} duplicate URLs")+ if extras:+ media_type_reports += f" _({', '.join(extras)})_"media_type_reports += "\n"# Collect data into a single message@@ -86,9 +96,6 @@ def report_completion(*Provider*: `{provider_name}`*Duration of data pull task*: {duration or '_No data_'}*Number of records upserted per media type*:-{media_type_reports}--* _Duration includes time taken to pull data of all media types._-"""+{media_type_reports}"""send_message(message, username="Airflow DAG Load Data Complete")logger.info(message)diff --git a/openverse_catalog/dags/common/loader/sql.py b/openverse_catalog/dags/common/loader/sql.pyindex cb8b078bb..58528c0fd 100644--- a/openverse_catalog/dags/common/loader/sql.py+++ b/openverse_catalog/dags/common/loader/sql.py@@ -129,18 +129,31 @@ def load_local_data_to_intermediate_table(_clean_intermediate_table_data(postgres, load_table)+def _handle_s3_load_result(cursor) -> int:+ """+ Handle the results of the aws_s3.table_import_from_s3 function. Locally this will+ return an integer, but on AWS infrastructure it will return a string similar to:++ 500 rows imported into relation "..." from file ... of ... bytes+ """+ result = cursor.fetchone()[0]+ if isinstance(result, str):+ result = int(result.split(" ", maxsplit=1)[0])+ return result++def load_s3_data_to_intermediate_table(postgres_conn_id,bucket,s3_key,identifier,media_type=IMAGE,-) -> tuple[int, int]:+) -> tuple[int, 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)- loaded_count = postgres.run(+ loaded = postgres.run(dedent(f"""SELECT aws_s3.table_import_from_s3(@@ -153,14 +166,16 @@ def load_s3_data_to_intermediate_table();"""),- handler=lambda c: c.fetchone()[0],+ handler=_handle_s3_load_result,+ )+ logger.info(f"Successfully loaded {loaded} records from S3")+ missing_columns, foreign_id_dup = _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+ return loaded, missing_columns, foreign_id_dup-def _clean_intermediate_table_data(postgres_hook, load_table) -> int:+def _clean_intermediate_table_data(postgres_hook, load_table) -> tuple[int, int]:"""Necessary for old TSV files that have not been cleaned up,using `MediaStore` class:@@ -169,13 +184,13 @@ def _clean_intermediate_table_data(postgres_hook, load_table) -> int:Also removes any duplicate rows that have the same `provider`and `foreign_id`."""- affected_count = 0+ missing_columns = 0for column in required_columns:- affected_count += postgres_hook.run(+ missing_columns += postgres_hook.run(f"DELETE FROM {load_table} WHERE {column.db_name} IS NULL;",handler=RETURN_ROW_COUNT,)- affected_count += postgres_hook.run(+ foreign_id_dup = postgres_hook.run(dedent(f"""DELETE FROM {load_table} p1@@ -188,8 +203,11 @@ def _clean_intermediate_table_data(postgres_hook, load_table) -> int:),handler=RETURN_ROW_COUNT,)- logger.info(f"Cleaned {affected_count} rows")- return affected_count+ logger.info(+ f"{missing_columns} records missing columns, "+ f"{foreign_id_dup} records with duplicate foreign_ids"+ )+ return missing_columns, foreign_id_dupdef _is_tsv_column_from_different_version(diff --git a/openverse_catalog/dags/common/provider_dag_factory.py b/openverse_catalog/dags/common/provider_dag_factory.pyindex 43dfbba5e..9f83cabec 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: reporting.RecordCounts = {}+ record_counts_by_media_type: reporting.MediaTypeRecordMetrics = {}for media_type in media_types:with TaskGroup(group_id=f"load_{media_type}_data") as load_data:create_loading_table = PythonOperator(@@ -272,10 +272,8 @@ def create_provider_api_workflow([create_loading_table, copy_to_s3] >> load_from_s3load_from_s3 >> drop_loading_table- 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"),+ record_counts_by_media_type[media_type] = XCOM_PULL_TEMPLATE.format(+ load_from_s3.task_id, "return_value")load_tasks.append(load_data)diff --git a/tests/dags/common/loader/test_loader.py b/tests/dags/common/loader/test_loader.pynew file mode 100644index 000000000..3f0b500f8--- /dev/null+++ b/tests/dags/common/loader/test_loader.py@@ -0,0 +1,24 @@+from unittest import mock++import pytest+from common.loader import loader+from common.loader.reporting import RecordMetrics+++ "load_value, upsert_value, expected",+ [+ ((100, 10, 15), 75, RecordMetrics(75, 10, 15, 0)),+ ((100, 0, 15), 75, RecordMetrics(75, 0, 15, 10)),+ ((100, 10, 0), 75, RecordMetrics(75, 10, 0, 15)),+ ],+)+def test_load_from_s3_calculations(load_value, upsert_value, expected):+ with mock.patch("common.loader.loader.sql") as sql_mock:+ sql_mock.load_s3_data_to_intermediate_table.return_value = load_value+ sql_mock.upsert_records_to_db_table.return_value = upsert_value++ actual = loader.load_from_s3(+ mock.Mock(), "fake", "fake", "fake", "fake", "fake"+ )+ assert actual == expecteddiff --git a/tests/dags/common/loader/test_reporting.py b/tests/dags/common/loader/test_reporting.pyindex 3fc2a5e10..e09d8616f 100644--- a/tests/dags/common/loader/test_reporting.py+++ b/tests/dags/common/loader/test_reporting.py@@ -1,7 +1,11 @@from unittest import mockimport pytest-from common.loader.reporting import humanize_time_duration, report_completion+from common.loader.reporting import (+ RecordMetrics,+ humanize_time_duration,+ report_completion,+)@pytest.fixture(autouse=True)@@ -18,7 +22,7 @@ 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, 100, 100)})+ report_completion("Jamendo", None, {"audio": RecordMetrics(100, 0, 0, 0)})# Send message is only called if `should_send_message` is True.send_message_mock.called = should_send_message@@ -26,26 +30,54 @@ def test_report_completion(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: RecordMetrics(100, 0, 0, 0)}, f" - `{media_type}`: 100"),+ # Missing columns detected+ (+ {media_type: RecordMetrics(90, 10, 0, 0)},+ f" - `{media_type}`: 90 _(10 missing columns)_",+ ),+ # Foreign ID duplicates detected+ (+ {media_type: RecordMetrics(90, 0, 10, 0)},+ f" - `{media_type}`: 90 _(10 duplicate foreign IDs)_",+ ),+ # URL duplicates detected(- {media_type: (100, 10, 75)},- f" - `{media_type}`: 75 _(10 cleaned, 15 duplicates)_",+ {media_type: RecordMetrics(90, 0, 0, 10)},+ f" - `{media_type}`: 90 _(10 duplicate URLs)_",),- # Cleaned and duplicates, large numbers+ # Missing columns and foreign ID duplicates detected(- {media_type: (100_000, 10_000, 75_000)},- f" - `{media_type}`: 75,000 _(10,000 cleaned, 15,000 duplicates)_",+ {media_type: RecordMetrics(75, 10, 15, 0)},+ f" - `{media_type}`: 75 _(10 missing columns, 15 duplicate foreign IDs)_",+ ),+ # Both duplicates detected, large numbers+ (+ {media_type: RecordMetrics(75_000, 0, 10_000, 15_000)},+ f" - `{media_type}`: 75,000 _(10,000 duplicate foreign IDs, "+ f"15,000 duplicate URLs)_",),# 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"),+ (+ {media_type: RecordMetrics(None, None, None, None)},+ f" - `{media_type}`: _No data_",+ ),+ (+ {media_type: RecordMetrics(100, None, None, None)},+ f" - `{media_type}`: 100",+ ),+ (+ {media_type: RecordMetrics(None, 100, None, None)},+ f" - `{media_type}`: _No data_",+ ),+ (+ {media_type: RecordMetrics(None, None, 100, None)},+ f" - `{media_type}`: _No data_",+ ),+ (+ {media_type: RecordMetrics(None, None, None, 100)},+ f" - `{media_type}`: _No data_",+ ),]diff --git a/tests/dags/common/loader/test_sql.py b/tests/dags/common/loader/test_sql.pyindex c56d067a5..f08395163 100644--- a/tests/dags/common/loader/test_sql.py+++ b/tests/dags/common/loader/test_sql.py@@ -1307,3 +1307,17 @@ def test_image_expiration(assert not actual_row[removed_idx]else:assert actual_row[fid_idx] == "b" and actual_row[removed_idx]+++ "value, expected",+ [+ (123, 123),+ ("500 rows imported into relation '...' from file ... of ... bytes", 500),+ ],+)+def test_handle_s3_load_result(value, expected):+ cursor_mock = mock.Mock()+ cursor_mock.fetchone.return_value = (value,)+ actual = sql._handle_s3_load_result(cursor_mock)+ assert actual == expected