Skip to content

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

Add alter data step to the data refresh DAG (#4684)

Madison Swain-Bowden716f68c8ba1e
diff --git a/catalog/dags/data_refresh/alter_data.py b/catalog/dags/data_refresh/alter_data.py
new file mode 100644
index 000000000..fb0ab98ac
--- /dev/null
+++ b/catalog/dags/data_refresh/alter_data.py
@@ -0,0 +1,209 @@
+"""
+# Alter Data Task
+
+This module contains the Airflow tasks used for filtering, transforming, and augmenting
+data from the newly created temporary table in the downstream (API) database.
+Currently, this provides an entrypoint for filtering tags that do not meet a certain
+minimum accuracy, are malformed, or are from unvetted providers.
+"""
+
+import logging
+from textwrap import dedent
+
+from airflow.decorators import task, task_group
+from airflow.models.abstractoperator import AbstractOperator
+from airflow.providers.common.sql.hooks.sql import fetch_all_handler, fetch_one_handler
+from psycopg2.extras import Json
+
+from common.constants import POSTGRES_API_CONN_IDS, Environment
+from common.sql import PGExecuteQueryOperator, PostgresHook
+from data_refresh.data_refresh_types import DataRefreshConfig
+
+
+logger = logging.getLogger(__name__)
+
+
+DEFAULT_BATCH_SIZE = 100_000
+# Filter out tags that exactly match these terms. All terms should be lowercase.
+TAG_DENYLIST = {
+ "no person",
+ "squareformat",
+ "uploaded:by=flickrmobile",
+ "uploaded:by=instagram",
+ "flickriosapp:filter=flamingo",
+ "by",
+}
+
+# Filter out tags that contain the following terms. All entries should be
+# lowercase.
+TAG_CONTAINS_DENYLIST = {
+ "flickriosapp",
+ "uploaded",
+ ":",
+ "=",
+ "cc0",
+ "by-nc",
+ "by-nd",
+ "by-sa",
+ "by-nc-nd",
+ "by-nc-sa",
+ "pdm",
+}
+
+# Filter out low-confidence tags, which indicate that the machine-generated tag
+# may be inaccurate.
+TAG_MIN_CONFIDENCE = 0.90
+# Filter out tags that match the following providers (either because they haven't
+# been vetted or because they are known to be low-quality).
+FILTERED_TAG_PROVIDERS = {"rekognition"}
+# Select the data within a given batch
+QUERY_SELECTION = dedent("""
+ SELECT id, identifier, tags
+ FROM {temp_table}
+ WHERE id BETWEEN {batch_start} AND {batch_end}
+""")
+# Update the tags for a given ID
+QUERY_UPDATE = dedent("""
+ UPDATE {temp_table}
+ SET tags = {tags_fragment}
+ WHERE id = {_id}
+""")
+# Get an estimate of total rows based on the min and max auto-assigned ID
+QUERY_ROW_ESTIMATE = dedent("""
+ SELECT min(id), max(id) FROM {temp_table}
+""")
+
+
+def _tag_denylisted(tag):
+ """Check if a tag is banned or contains a banned substring."""
+
+ if tag in TAG_DENYLIST:
+ return True
+ for denylisted_substring in TAG_CONTAINS_DENYLIST:
+ if denylisted_substring in tag:
+ return True
+ return False
+
+
+def generate_tag_updates(tags) -> list[dict] | None:
+ """Filter denylisted, low-accuracy, and unverified provider tags."""
+ update_required = False
+ tag_output = []
+ if not tags:
+ return None
+ for tag in tags:
+ should_filter = False
+ lower_tag = None
+ if (
+ # Malformed tag
+ not ("name" in tag and isinstance(tag["name"], str))
+ # Does not meet accuracy criteria
+ or ("accuracy" in tag and float(tag["accuracy"]) < TAG_MIN_CONFIDENCE)
+ # Provider must be excluded
+ or ("provider" in tag and tag["provider"] in FILTERED_TAG_PROVIDERS)
+ ):
+ should_filter = True
+ else:
+ lower_tag = tag["name"].lower()
+ if should_filter or _tag_denylisted(lower_tag):
+ update_required = True
+ else:
+ tag_output.append(tag)
+
+ if update_required:
+ return tag_output
+ return None
+
+
+@task
+def get_alter_batches(
+ id_bounds: tuple[int, int], batch_size: int | None
+) -> list[tuple[int, int]]:
+ start, stop = id_bounds
+ batch_size = batch_size or DEFAULT_BATCH_SIZE
+ return [(x, x + batch_size - 1) for x in range(start, stop, batch_size)]
+
+
+@task
+def alter_data_batch(
+ batch: tuple[int, int],
+ temp_table: str,
+ postgres_conn_id: str,
+ task: AbstractOperator = None,
+ timeout: float = None,
+) -> int:
+ logger.info(f"Starting data altering on batch: {batch}")
+ batch_start, batch_end = batch
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=(
+ timeout if timeout else PostgresHook.get_execution_timeout(task)
+ ),
+ )
+ rows = postgres.run(
+ QUERY_SELECTION.format(
+ temp_table=temp_table, batch_start=batch_start, batch_end=batch_end
+ ),
+ handler=fetch_all_handler,
+ )
+ worker_conn = postgres.get_conn()
+ logger.info("Data altering worker connected to database")
+ with worker_conn.cursor() as write_cur:
+ logger.info(f"Filtering {len(rows)} rows")
+
+ altered_count = 0
+ for row in rows:
+ _id, identifier, tags = row
+ tags_fragment = generate_tag_updates(tags)
+ if not tags_fragment:
+ continue
+ altered_count += 1
+ logger.debug(
+ f"Updated tags for {identifier}\n\t"
+ f"from '{tags}' \n\tto '{tags_fragment}'"
+ )
+ update_query = QUERY_UPDATE.format(
+ temp_table=temp_table, tags_fragment=Json(tags_fragment), _id=_id
+ )
+ logger.debug(f"Executing update query: \n\t{update_query}")
+ write_cur.execute(update_query)
+ logger.info("Worker committing changes...")
+ worker_conn.commit()
+ worker_conn.close()
+ return altered_count
+
+
+@task
+def report(counts: list[int]):
+ total_count = sum(counts)
+ logger.info(f"Filtered tags for a total of {total_count} records")
+ return total_count
+
+
+@task_group(group_id="alter_table_data")
+def alter_table_data(
+ environment: Environment,
+ data_refresh_config: DataRefreshConfig,
+):
+ """Perform data altering across a number of tasks."""
+ postgres_conn_id = POSTGRES_API_CONN_IDS.get(environment)
+ temp_table = data_refresh_config.table_mappings[0].temp_table_name
+
+ estimated_record_count = PGExecuteQueryOperator(
+ task_id="get_estimated_record_count",
+ conn_id=postgres_conn_id,
+ sql=QUERY_ROW_ESTIMATE.format(temp_table=temp_table),
+ handler=fetch_one_handler,
+ return_last=True,
+ )
+
+ batches = get_alter_batches(
+ estimated_record_count.output,
+ batch_size="{{ var.value.get('DATA_REFRESH_ALTER_BATCH_SIZE', none) }}",
+ )
+
+ alter_data = alter_data_batch.partial(
+ temp_table=temp_table, postgres_conn_id=postgres_conn_id
+ ).expand(batch=batches)
+
+ report(alter_data)
diff --git a/catalog/dags/data_refresh/dag_factory.py b/catalog/dags/data_refresh/dag_factory.py
index 474c57545..32533ac3a 100644
--- a/catalog/dags/data_refresh/dag_factory.py
+++ b/catalog/dags/data_refresh/dag_factory.py
@@ -42,6 +42,7 @@ from common.constants import DAG_DEFAULT_ARGS, ENVIRONMENTS, Environment
from common.sensors.constants import ES_CONCURRENCY_TAGS
from common.sensors.single_run_external_dags_sensor import SingleRunExternalDAGsSensor
from common.sensors.utils import wait_for_external_dags_with_tag
+from data_refresh.alter_data import alter_table_data
from data_refresh.copy_data import copy_upstream_tables
from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefreshConfig
from data_refresh.reporting import report_record_difference
@@ -115,6 +116,7 @@ def create_data_refresh_dag(
default_args=default_args,
start_date=data_refresh_config.start_date,
schedule=data_refresh_config.schedule,
+ render_template_as_native_obj=True,
max_active_runs=1,
catchup=False,
doc_md=__doc__,
@@ -145,7 +147,9 @@ def create_data_refresh_dag(
environment=environment, data_refresh_config=data_refresh_config
)
- # TODO Cleaning steps
+ alter_data = alter_table_data(
+ environment=environment, data_refresh_config=data_refresh_config
+ )
# Disable Cloudwatch alarms that are noisy during the reindexing steps of a
# data refresh.
@@ -198,7 +202,13 @@ def create_data_refresh_dag(
)
# Set up task dependencies
- before_record_count >> wait_for_dags >> copy_data >> disable_alarms
+ (
+ before_record_count
+ >> wait_for_dags
+ >> copy_data
+ >> alter_data
+ >> disable_alarms
+ )
# TODO: this will include reindex/etc once added
disable_alarms >> [enable_alarms, after_record_count]
after_record_count >> report_counts
diff --git a/catalog/env.template b/catalog/env.template
index be5bc5000..44136341e 100644
--- a/catalog/env.template
+++ b/catalog/env.template
@@ -124,6 +124,8 @@ AIRFLOW_VAR_ES_INDEX_THROTTLING_RATE=20000
# Warning in dependency, nothing we can do
# https://docs.sqlalchemy.org/en/20/errors.html#error-b8d9
SQLALCHEMY_SILENCE_UBER_WARNING=1
+# Default size of batches for the data refresh altering step
+AIRFLOW_VAR_DATA_REFRESH_ALTER_BATCH_SIZE=1000
AIRFLOW_VAR_AIRFLOW_RDS_ARN=unset
AIRFLOW_VAR_AIRFLOW_RDS_SNAPSHOTS_TO_RETAIN=7
diff --git a/catalog/tests/dags/data_refresh/test_alter_data.py b/catalog/tests/dags/data_refresh/test_alter_data.py
new file mode 100644
index 000000000..5dba5d648
--- /dev/null
+++ b/catalog/tests/dags/data_refresh/test_alter_data.py
@@ -0,0 +1,99 @@
+from unittest import mock
+
+import pytest
+
+from data_refresh.alter_data import (
+ DEFAULT_BATCH_SIZE,
+ FILTERED_TAG_PROVIDERS,
+ alter_data_batch,
+ generate_tag_updates,
+ get_alter_batches,
+)
+
+
+ "tags, expected",
+ [
+ # Valid tag returns no updates
+ ([{"name": "valid", "accuracy": 0.92}], None),
+ # Denylisted tags get filtered
+ (
+ [
+ {"name": "cc0"},
+ {"name": " cc0"},
+ {"name": "valid", "accuracy": 0.99},
+ {"name": "valid_no_accuracy"},
+ {
+ "name": "garbage:=metacrap",
+ },
+ ],
+ [
+ {"name": "valid", "accuracy": 0.99},
+ {"name": "valid_no_accuracy"},
+ ],
+ ),
+ # Inaccurate tags are filtered
+ (
+ [
+ {"name": "inaccurate", "accuracy": 0.5},
+ {"name": "accurate", "accuracy": 0.999},
+ ],
+ [{"name": "accurate", "accuracy": 0.999}],
+ ),
+ # Tags from unvetted providers get filtered
+ (
+ [
+ {"name": "valid", "provider": "provider1"},
+ *[
+ {"name": "invalid", "provider": provider}
+ for provider in FILTERED_TAG_PROVIDERS
+ ],
+ ],
+ [{"name": "valid", "provider": "provider1"}],
+ ),
+ ],
+)
+def test_generate_tag_updates(tags, expected):
+ actual = generate_tag_updates(tags)
+ assert actual == expected
+
+
+ "id_bounds, batch_size, expected",
+ [
+ ((1, 100), 50, [(1, 50), (51, 100)]),
+ # None respects default
+ ((1, 100), None, [(1, DEFAULT_BATCH_SIZE)]),
+ ],
+)
+def test_get_alter_batches(id_bounds, batch_size, expected):
+ actual = get_alter_batches.function(id_bounds, batch_size)
+ assert actual == expected
+
+
+def test_alter_data_batch():
+ batch = (50, 100)
+ temp_table = "temp_foobar"
+ postgres_conn_id = "fake_conn_id"
+ sample_data = [
+ (50, "aaa", False),
+ (51, "bbb", True),
+ (52, "ccc", False),
+ ]
+ with mock.patch("data_refresh.alter_data.PostgresHook") as HookMock, mock.patch(
+ "data_refresh.alter_data.generate_tag_updates"
+ ) as tag_updates_mock:
+ mock_pg = HookMock.return_value
+ mock_pg.run.return_value = sample_data
+ mock_cursor = (
+ mock_pg.get_conn.return_value.cursor.return_value.__enter__.return_value
+ )
+ tag_updates_mock.side_effect = lambda x: x or None
+
+ count = alter_data_batch.function(
+ batch=batch, temp_table=temp_table, postgres_conn_id=postgres_conn_id
+ )
+
+ assert count == 1
+ assert mock_cursor.execute.call_count == 1
+ assert "BETWEEN 50 AND 100" in mock_pg.run.call_args.args[0]