Skip to content

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

Data refresh record difference reporting (#636)

Madison Swain-Bowden492ae8b521dd
diff --git a/openverse_catalog/dags/common/constants.py b/openverse_catalog/dags/common/constants.py
index e4fc08ad4..f5987ed76 100644
--- a/openverse_catalog/dags/common/constants.py
+++ b/openverse_catalog/dags/common/constants.py
@@ -24,3 +24,4 @@ DAG_DEFAULT_ARGS = {
XCOM_PULL_TEMPLATE = "{{{{ ti.xcom_pull(task_ids='{}', key='{}') }}}}"
POSTGRES_CONN_ID = os.getenv("OPENLEDGER_CONN_ID", "postgres_openledger_testing")
+OPENLEDGER_API_CONN_ID = os.getenv("OPENLEDGER_API_CONN_ID", "postgres_openledger_api")
diff --git a/openverse_catalog/dags/common/operators/__init__.py b/openverse_catalog/dags/common/operators/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/openverse_catalog/dags/common/operators/postgres_result.py b/openverse_catalog/dags/common/operators/postgres_result.py
new file mode 100644
index 000000000..56b2f4d28
--- /dev/null
+++ b/openverse_catalog/dags/common/operators/postgres_result.py
@@ -0,0 +1,81 @@
+from typing import TYPE_CHECKING, Callable, Iterable, List, Mapping, Optional, Union
+
+from airflow.providers.postgres.hooks.postgres import PostgresHook
+from airflow.providers.postgres.operators.postgres import PostgresOperator
+from psycopg2.sql import SQL, Identifier
+
+
+if TYPE_CHECKING:
+ from airflow.utils.context import Context
+
+
+class PostgresResultOperator(PostgresOperator):
+ """
+ Override for the PostgresOperator which is functionally identical except that a
+ handler can be specified for the PostgresHook. The value(s) accumulated from the
+ run function will then be pushed as an XCom.
+ """
+
+ def __init__(
+ self,
+ *,
+ sql: Union[str, List[str]],
+ handler: Callable,
+ postgres_conn_id: str = "postgres_default",
+ autocommit: bool = False,
+ parameters: Optional[Union[Mapping, Iterable]] = None,
+ database: Optional[str] = None,
+ runtime_parameters: Optional[Mapping] = None,
+ **kwargs,
+ ) -> None:
+ super().__init__(
+ sql=sql,
+ postgres_conn_id=postgres_conn_id,
+ autocommit=autocommit,
+ parameters=parameters,
+ database=database,
+ runtime_parameters=runtime_parameters,
+ **kwargs,
+ )
+ self.handler = handler
+
+ def execute(self, context: "Context"):
+ """
+ This almost exactly mirrors PostgresOperator::execute, except that it allows
+ passing a handler into the hook.
+ """
+ self.hook = PostgresHook(
+ postgres_conn_id=self.postgres_conn_id, schema=self.database
+ )
+ if self.runtime_parameters:
+ final_sql = []
+ sql_param = {}
+ for param in self.runtime_parameters:
+ set_param_sql = f"SET {{}} TO %({param})s;"
+ dynamic_sql = SQL(set_param_sql).format(Identifier(f"{param}"))
+ final_sql.append(dynamic_sql)
+ for param, val in self.runtime_parameters.items():
+ sql_param.update({f"{param}": f"{val}"})
+ if self.parameters:
+ sql_param.update(self.parameters)
+ if isinstance(self.sql, str):
+ final_sql.append(SQL(self.sql))
+ else:
+ final_sql.extend(list(map(SQL, self.sql)))
+ results = self.hook.run(
+ final_sql,
+ self.autocommit,
+ parameters=sql_param,
+ handler=self.handler,
+ )
+ else:
+ results = self.hook.run(
+ self.sql,
+ self.autocommit,
+ parameters=self.parameters,
+ handler=self.handler,
+ )
+ for output in self.hook.conn.notices:
+ self.log.info(output)
+
+ return results
diff --git a/openverse_catalog/dags/data_refresh/dag_factory.py b/openverse_catalog/dags/data_refresh/dag_factory.py
index b76b1bd95..0db6c9ae2 100644
--- a/openverse_catalog/dags/data_refresh/dag_factory.py
+++ b/openverse_catalog/dags/data_refresh/dag_factory.py
@@ -8,7 +8,7 @@ success or failure of that task.
Popularity data for each media type is collated in a materialized view. Before
initiating a data refresh, the DAG will first refresh the view in order to
update popularity data for records that have been ingested since the last refresh.
-On the first run of the the month, the DAG will also refresh the underlying tables,
+On the first run of the month, the DAG will also refresh the underlying tables,
including the percentile values and any new popularity metrics. The DAG can also
be run with the `force_refresh_metrics` option to run this refresh after the first
of the month.
@@ -36,13 +36,19 @@ from typing import Sequence
from airflow import DAG
from airflow.models.dagrun import DagRun
-from airflow.operators.python import BranchPythonOperator
+from airflow.operators.python import BranchPythonOperator, PythonOperator
from airflow.settings import SASession
from airflow.utils.session import provide_session
from airflow.utils.state import State
-from common.constants import DAG_DEFAULT_ARGS
+from common.constants import (
+ DAG_DEFAULT_ARGS,
+ OPENLEDGER_API_CONN_ID,
+ XCOM_PULL_TEMPLATE,
+)
+from common.operators.postgres_result import PostgresResultOperator
from data_refresh.data_refresh_task_factory import create_data_refresh_task_group
from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefresh
+from data_refresh.record_reporting import report_record_difference
from data_refresh.refresh_popularity_metrics_task_factory import (
GROUP_ID as REFRESH_POPULARITY_METRICS_GROUP_ID,
)
@@ -66,6 +72,14 @@ REFRESH_POPULARITY_METRICS_TASK_ID = (
)
+def _single_value(cursor):
+ try:
+ row = cursor.fetchone()
+ return row[0]
+ except Exception as e:
+ raise ValueError("Unable to extract expected row data from cursor") from e
+
+
@provide_session
def _month_check(dag_id: str, session: SASession = None) -> str:
"""
@@ -151,6 +165,20 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc
)
with dag:
+ # Count estimate SQL for determining the number of rows in the API table. While
+ # this query is not exact, it is close to accurate since the API media table
+ # does not receive many (if any) updates/insertions/deletions once the data
+ # refresh is complete. In testing this was shown to be accurate and fast
+ # (~0.000002% off and 1/14000th of the execution time). However, the reality is
+ # that this count is *not* exact, so we show it as an estimate in reports.
+ count_sql = f"""
+ SELECT c.reltuples::bigint AS estimate
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE c.relname = '{data_refresh.media_type}'
+ AND n.nspname = 'public';
+ """
+
# Check if this is the first DagRun of the month for this DAG.
month_check = BranchPythonOperator(
task_id="month_check",
@@ -160,6 +188,14 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc
},
)
+ # Get the current number of records in the target API table
+ before_record_count = PostgresResultOperator(
+ task_id="get_before_record_count",
+ postgres_conn_id=OPENLEDGER_API_CONN_ID,
+ sql=count_sql,
+ handler=_single_value,
+ )
+
# Refresh underlying popularity tables. This is required infrequently in order
# to update new popularity metrics and constants, so this branch is only taken
# if it is the first run of the month (or when forced).
@@ -177,9 +213,34 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc
data_refresh, external_dag_ids
)
+ # Get the final number of records in the API table after the refresh
+ after_record_count = PostgresResultOperator(
+ task_id="get_after_record_count",
+ postgres_conn_id=OPENLEDGER_API_CONN_ID,
+ sql=count_sql,
+ handler=_single_value,
+ )
+
+ # Report the count difference to Slack
+ report_counts = PythonOperator(
+ task_id="report_record_counts",
+ python_callable=report_record_difference,
+ op_kwargs={
+ "before": XCOM_PULL_TEMPLATE.format(
+ before_record_count.task_id, "return_value"
+ ),
+ "after": XCOM_PULL_TEMPLATE.format(
+ after_record_count.task_id, "return_value"
+ ),
+ "media_type": data_refresh.media_type,
+ },
+ )
+
# Set up task dependencies
month_check >> [refresh_popularity_metrics, refresh_matview]
+ before_record_count >> data_refresh_group
refresh_popularity_metrics >> refresh_matview >> data_refresh_group
+ data_refresh_group >> after_record_count >> report_counts
return dag
diff --git a/openverse_catalog/dags/data_refresh/record_reporting.py b/openverse_catalog/dags/data_refresh/record_reporting.py
new file mode 100644
index 000000000..fdd6c8a77
--- /dev/null
+++ b/openverse_catalog/dags/data_refresh/record_reporting.py
@@ -0,0 +1,24 @@
+import logging
+
+from common import slack
+
+
+log = logging.getLogger(__name__)
+
+
+def report_record_difference(before: str, after: str, media_type: str):
+ before = int(before)
+ after = int(after)
+ count_diff = after - before
+ percent_diff = (count_diff / before) * 100
+ # Note for formatting:
+ # '+' - number will always have a sign in front of it
+ # ',' - number is comma separated
+ # '.' - number is a float
+ message = f"""
+_Note: All values are row estimates and are not (but nearly) exact_
+*Record count difference for `{media_type}`*: {before:,} → {after:,}
+*Change*: {count_diff:+,} ({percent_diff:+}% Δ)
+"""
+ slack.send_message(text=message, username="Data refresh record difference")
+ return message
diff --git a/openverse_catalog/dags/database/report_pending_reported_media.py b/openverse_catalog/dags/database/report_pending_reported_media.py
index 089254026..45c6487aa 100644
--- a/openverse_catalog/dags/database/report_pending_reported_media.py
+++ b/openverse_catalog/dags/database/report_pending_reported_media.py
@@ -20,13 +20,17 @@ from airflow.models import TaskInstance
from airflow.operators.python import PythonOperator
from airflow.providers.postgres.hooks.postgres import PostgresHook
from common import slack
-from common.constants import DAG_DEFAULT_ARGS, MEDIA_TYPES, XCOM_PULL_TEMPLATE
+from common.constants import (
+ DAG_DEFAULT_ARGS,
+ MEDIA_TYPES,
+ OPENLEDGER_API_CONN_ID,
+ XCOM_PULL_TEMPLATE,
+)
logger = logging.getLogger(__name__)
DAG_ID = "report_pending_reported_media"
-DB_CONN_ID = os.getenv("OPENLEDGER_API_CONN_ID", "postgres_openledger_api")
ADMIN_URL = os.getenv("DJANGO_ADMIN_URL", "http://localhost:8000/admin")
REPORTS_TABLES = {
@@ -146,7 +150,10 @@ def create_dag():
get_reports = PythonOperator(
task_id=f"get_pending_{media_type}_reports",
python_callable=get_pending_report_counts,
- op_kwargs={"db_conn_id": DB_CONN_ID, "media_type": media_type},
+ op_kwargs={
+ "db_conn_id": OPENLEDGER_API_CONN_ID,
+ "media_type": media_type,
+ },
)
report_counts_by_media_type[media_type] = XCOM_PULL_TEMPLATE.format(
diff --git a/tests/dags/common/operators/__init__.py b/tests/dags/common/operators/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/dags/common/operators/test_postgres_result.py b/tests/dags/common/operators/test_postgres_result.py
new file mode 100644
index 000000000..73d20b39a
--- /dev/null
+++ b/tests/dags/common/operators/test_postgres_result.py
@@ -0,0 +1,72 @@
+"""
+Based on:
+https://airflow.apache.org/docs/apache-airflow/stable/best-practices.html#unit-tests
+"""
+import datetime
+import os
+
+import pendulum
+import pytest
+from airflow import DAG
+from airflow.models import DagRun, TaskInstance
+from airflow.utils.session import create_session
+from airflow.utils.state import DagRunState, TaskInstanceState
+from airflow.utils.types import DagRunType
+from common.operators.postgres_result import PostgresResultOperator
+
+
+DATA_INTERVAL_START = pendulum.datetime(2021, 9, 13, tz="UTC")
+DATA_INTERVAL_END = DATA_INTERVAL_START + datetime.timedelta(days=1)
+
+TEST_DAG_ID = "test_postgres_result_dag"
+TEST_TASK_ID = "test_postgres_result_task"
+DB_CONN_ID = os.getenv("OPENLEDGER_CONN_ID", "postgres_openledger_testing")
+
+
[email protected](autouse=True)
+def clean_db():
+ with create_session() as session:
+ session.query(DagRun).filter(DagRun.dag_id == TEST_DAG_ID).delete()
+ session.query(TaskInstance).filter(TaskInstance.dag_id == TEST_DAG_ID).delete()
+ yield
+ session.query(DagRun).filter(DagRun.dag_id == TEST_DAG_ID).delete()
+ session.query(TaskInstance).filter(TaskInstance.dag_id == TEST_DAG_ID).delete()
+
+
+def get_dag(sql, handler):
+ with DAG(
+ dag_id=TEST_DAG_ID,
+ schedule_interval="@daily",
+ start_date=DATA_INTERVAL_START,
+ ) as dag:
+ PostgresResultOperator(
+ task_id=TEST_TASK_ID, postgres_conn_id=DB_CONN_ID, sql=sql, handler=handler
+ )
+ return dag
+
+
+ "sql, handler, expected",
+ [
+ ["SELECT 1", lambda c: c.fetchone(), (1,)],
+ ["SELECT 1", lambda c: c.fetchone()[0], 1],
+ ["SELECT UNNEST(ARRAY[1, 2, 3])", lambda c: c.fetchone(), (1,)],
+ ["SELECT UNNEST(ARRAY[1, 2, 3])", lambda c: c.fetchall(), [(1,), (2,), (3,)]],
+ ["SELECT UNNEST(ARRAY[1, 2, 3])", lambda c: c.rowcount, 3],
+ ],
+)
+def test_postgres_result_operator(sql, handler, expected):
+ dag = get_dag(sql, handler)
+ dagrun = dag.create_dagrun(
+ state=DagRunState.RUNNING,
+ execution_date=DATA_INTERVAL_START,
+ data_interval=(DATA_INTERVAL_START, DATA_INTERVAL_END),
+ start_date=DATA_INTERVAL_END,
+ run_type=DagRunType.MANUAL,
+ )
+ ti: TaskInstance = dagrun.get_task_instance(task_id=TEST_TASK_ID)
+ ti.task = dag.get_task(task_id=TEST_TASK_ID)
+ ti.run(ignore_ti_state=True)
+ assert ti.state == TaskInstanceState.SUCCESS
+ value = ti.xcom_pull(TEST_TASK_ID)
+ assert value == expected
diff --git a/tests/dags/data_refresh/test_record_reporting.py b/tests/dags/data_refresh/test_record_reporting.py
new file mode 100644
index 000000000..b809609c8
--- /dev/null
+++ b/tests/dags/data_refresh/test_record_reporting.py
@@ -0,0 +1,21 @@
+import pytest
+from data_refresh.record_reporting import report_record_difference
+
+
+ "before, after, expected_in_message",
+ [
+ ["1", "2", ["1 → 2", "+1 (+100.0%"]],
+ ["1", "3", ["1 → 3", "+2 (+200.0%"]],
+ ["4", "2", ["4 → 2", "-2 (-50.0%"]],
+ ["4000", "2000", ["4,000 → 2,000", "-2,000 (-50.0%"]],
+ ],
+)
+def test_record_reporting(before, after, expected_in_message):
+ actual = report_record_difference(before, after, "media")
+ assert isinstance(expected_in_message, list), (
+ "Value for 'expected_in_message' should be a list, "
+ "a string may give a false positive"
+ )
+ for expected in expected_in_message:
+ assert expected in actual