Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Address review feedback on the data refresh fixes (#5828)
Olga Bulat53399a0dc3f1
diff --git a/catalog/dags/common/elasticsearch.py b/catalog/dags/common/elasticsearch.pyindex 2569a8d56..2c55cd840 100644--- a/catalog/dags/common/elasticsearch.py+++ b/catalog/dags/common/elasticsearch.py@@ -3,7 +3,7 @@ from datetime import timedeltafrom typing import Literalfrom airflow.decorators import task, task_group-from airflow.exceptions import AirflowException, AirflowSkipException+from airflow.exceptions import AirflowFailException, AirflowSkipExceptionfrom airflow.models.connection import Connectionfrom airflow.providers.elasticsearch.hooks.elasticsearch import ElasticsearchPythonHookfrom airflow.sensors.base import PokeReturnValue@@ -137,13 +137,27 @@ def raise_for_reindex_failure(response: dict) -> None:Raise if a finished reindex task failed.A reindex run with ``wait_for_completion=False`` still reports ``completed`` when- it fails, with the cause in ``error`` (for example, an expired scroll) or in- ``response.failures`` (rejected documents).+ it fails, with the cause in ``error`` (for example, an expired scroll),+ ``response.failures`` (rejected documents), ``response.canceled`` (cancelled+ through the tasks API) or ``response.timed_out``.++ Raises ``AirflowFailException`` so the sensor does not retry: polling the same+ finished ES task again cannot succeed. To recover, clear the whole+ ``trigger_and_wait_for_reindex`` group so the reindex is triggered again."""- error = response.get("error")- failures = response.get("response", {}).get("failures")- if error or failures:- raise AirflowException(f"Reindex failed: {error or failures[:5]}")+ body = response.get("response", {})+ reasons = {+ "error": response.get("error"),+ "failures": (body.get("failures") or [])[:5],+ "canceled": body.get("canceled"),+ "timed_out": body.get("timed_out"),+ }+ reasons = {key: value for key, value in reasons.items() if value}+ if reasons:+ raise AirflowFailException(+ f"Reindex failed: {reasons}. Clear the trigger_and_wait_for_reindex "+ "task group to trigger the reindex again."+ )@task_group(group_id="trigger_and_wait_for_reindex")diff --git a/catalog/dags/data_refresh/alter_data.py b/catalog/dags/data_refresh/alter_data.pyindex 5057af0a8..b22e8b6b2 100644--- a/catalog/dags/data_refresh/alter_data.py+++ b/catalog/dags/data_refresh/alter_data.py@@ -15,10 +15,14 @@ from textwrap import dedentfrom airflow.decorators import task, task_groupfrom airflow.models.abstractoperator import AbstractOperator-from airflow.providers.common.sql.hooks.handlers import fetch_one_handler+from airflow.providers.common.sql.hooks.handlers import (+ fetch_all_handler,+ fetch_one_handler,+)from common.constants import POSTGRES_API_CONN_IDS, Environment-from common.sql import RETURN_ROW_COUNT, PGExecuteQueryOperator, PostgresHook+from common.sql import PGExecuteQueryOperator, PostgresHook+from common.storage.media import TAG_CONTAINS_DENYLIST, TAG_DENYLISTfrom data_refresh.data_refresh_types import DataRefreshConfig@@ -26,67 +30,61 @@ 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"}+# A string accuracy that `::numeric` accepts. Casting any other string would raise+# and abort the whole batch.+NUMERIC_PATTERN = r"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$"# True when a tag is malformed, below the confidence threshold, from a filtered# provider, or has a denylisted name. Every branch must be non-null, because-# `NOT NULL` would drop a tag that should be kept.+# `NOT NULL` would drop a tag that should be kept. The accuracy cast sits inside+# CASE, which, unlike OR, guarantees the guard is evaluated first. A string+# accuracy that is not a number is treated as below the threshold.TAG_IS_FILTERED = """(jsonb_typeof(tag -> 'name') IS DISTINCT FROM 'string'- OR CASE- WHEN jsonb_typeof(tag -> 'accuracy') IN ('number', 'string')- THEN (tag ->> 'accuracy')::numeric < %(min_confidence)s+ OR CASE jsonb_typeof(tag -> 'accuracy')+ WHEN 'number' THEN (tag ->> 'accuracy')::numeric < %(min_confidence)s+ WHEN 'string' THEN CASE+ WHEN tag ->> 'accuracy' ~ %(numeric_pattern)s+ THEN (tag ->> 'accuracy')::numeric < %(min_confidence)s+ ELSE true+ ENDELSE falseENDOR coalesce(tag ->> 'provider' = ANY(%(filtered_providers)s), false)OR lower(tag ->> 'name') = ANY(%(denylist)s)OR lower(tag ->> 'name') LIKE ANY(%(contains_denylist)s))"""-TAG_ELEMENTS = """jsonb_array_elements(- CASE jsonb_typeof(tags) WHEN 'array' THEN tags ELSE '[]'::jsonb END-) WITH ORDINALITY AS elements(tag, position)"""# Rewrite the tags of each record in the batch that has at least one tag to drop,-# keeping the order of the remaining tags.+# keeping the order of the remaining tags. Each tag is checked once.QUERY_FILTER_TAGS = dedent(f"""- UPDATE {{temp_table}}- SET tags = (- SELECT coalesce(jsonb_agg(tag ORDER BY position), '[]'::jsonb)- FROM {TAG_ELEMENTS}- WHERE NOT {TAG_IS_FILTERED}- )- WHERE id BETWEEN %(batch_start)s AND %(batch_end)s- AND EXISTS (SELECT FROM {TAG_ELEMENTS} WHERE {TAG_IS_FILTERED})+ UPDATE {{temp_table}} AS target+ SET tags = filtered.tags+ FROM (+ SELECT+ id,+ coalesce(+ jsonb_agg(tag ORDER BY position) FILTER (WHERE NOT is_filtered),+ '[]'::jsonb+ ) AS tags+ FROM (+ SELECT id, tag, position, {TAG_IS_FILTERED} AS is_filtered+ FROM {{temp_table}},+ jsonb_array_elements(+ CASE jsonb_typeof(tags) WHEN 'array' THEN tags ELSE '[]'::jsonb END+ ) WITH ORDINALITY AS elements(tag, position)+ WHERE id BETWEEN %(batch_start)s AND %(batch_end)s+ ) AS checked+ GROUP BY id+ HAVING bool_or(is_filtered)+ ) AS filtered+ WHERE target.id = filtered.id+ RETURNING target.identifier""")# Get an estimate of total rows based on the min and max auto-assigned IDQUERY_ROW_ESTIMATE = dedent("""@@ -102,6 +100,7 @@ def _like_contains_pattern(term: str) -> str:def get_tag_filter_parameters() -> dict:return {"min_confidence": TAG_MIN_CONFIDENCE,+ "numeric_pattern": NUMERIC_PATTERN,"filtered_providers": sorted(FILTERED_TAG_PROVIDERS),"denylist": sorted(TAG_DENYLIST),"contains_denylist": sorted(@@ -112,9 +111,12 @@ def get_tag_filter_parameters() -> dict:@taskdef get_alter_batches(- id_bounds: tuple[int, int], batch_size: int | None+ id_bounds: tuple[int | None, int | None], batch_size: int | None) -> list[tuple[int, int]]:start, stop = id_bounds+ if start is None or stop is None:+ logger.info("The table is empty, so there is no data to alter.")+ return []batch_size = batch_size or DEFAULT_BATCH_SIZEreturn [(x, x + batch_size - 1) for x in range(start, stop + 1, batch_size)]@@ -135,17 +137,20 @@ def alter_data_batch(timeout if timeout else PostgresHook.get_execution_timeout(task)),)- altered_count = postgres.run(+ altered = postgres.run(QUERY_FILTER_TAGS.format(temp_table=temp_table),parameters={"batch_start": batch_start,"batch_end": batch_end,**get_tag_filter_parameters(),},- handler=RETURN_ROW_COUNT,+ handler=fetch_all_handler,)- logger.info(f"Filtered tags for {altered_count} records in batch {batch}")- return altered_count+ if logger.isEnabledFor(logging.DEBUG):+ for (identifier,) in altered:+ logger.debug(f"Filtered tags for {identifier}")+ logger.info(f"Filtered tags for {len(altered)} records in batch {batch}")+ return len(altered)@taskdiff --git a/catalog/tests/dags/common/test_elasticsearch.py b/catalog/tests/dags/common/test_elasticsearch.pyindex 0c9617159..0d60aa57b 100644--- a/catalog/tests/dags/common/test_elasticsearch.py+++ b/catalog/tests/dags/common/test_elasticsearch.py@@ -1,5 +1,5 @@import pytest-from airflow.exceptions import AirflowException+from airflow.exceptions import AirflowFailExceptionfrom common.elasticsearch import raise_for_reindex_failure@@ -12,6 +12,10 @@ from common.elasticsearch import raise_for_reindex_failureid="succeeded",),pytest.param({"completed": True}, id="no_response_body"),+ pytest.param(+ {"completed": True, "response": {"canceled": "", "timed_out": False}},+ id="not_canceled_or_timed_out",+ ),],)def test_raise_for_reindex_failure_passes(response):@@ -41,8 +45,19 @@ def test_raise_for_reindex_failure_passes(response):},id="document_failures",),+ pytest.param(+ {+ "completed": True,+ "response": {"failures": [], "canceled": "by user request"},+ },+ id="canceled",+ ),+ pytest.param(+ {"completed": True, "response": {"failures": [], "timed_out": True}},+ id="timed_out",+ ),],)def test_raise_for_reindex_failure_raises(response):- with pytest.raises(AirflowException, match="Reindex failed"):+ with pytest.raises(AirflowFailException, match="Reindex failed"):raise_for_reindex_failure(response)diff --git a/catalog/tests/dags/data_refresh/test_alter_data.py b/catalog/tests/dags/data_refresh/test_alter_data.pyindex 94754185b..9c98c8675 100644--- a/catalog/tests/dags/data_refresh/test_alter_data.py+++ b/catalog/tests/dags/data_refresh/test_alter_data.py@@ -1,4 +1,5 @@import json+import loggingimport psycopg2import pytest@@ -13,12 +14,14 @@ from tests.test_utils import sql@pytest.fixture-def temp_table(request):- table = f"temp_import_{abs(hash(request.node.name))}"+def temp_table(identifier):+ table = f"temp_import_{identifier}"conn = psycopg2.connect(sql.POSTGRES_TEST_URI)cur = conn.cursor()cur.execute(f"DROP TABLE IF EXISTS {table}")- cur.execute(f"CREATE TABLE {table} (id integer PRIMARY KEY, tags jsonb)")+ cur.execute(+ f"CREATE TABLE {table} (id integer PRIMARY KEY, identifier text, tags jsonb)"+ )conn.commit()yield sql.PostgresRef(cursor=cur, connection=conn), table@@ -32,8 +35,8 @@ def temp_table(request):def _insert(postgres, table, rows: dict[int, object]):for _id, tags in rows.items():postgres.cursor.execute(- f"INSERT INTO {table} (id, tags) VALUES (%s, %s)",- (_id, None if tags is None else json.dumps(tags)),+ f"INSERT INTO {table} (id, identifier, tags) VALUES (%s, %s, %s)",+ (_id, f"identifier-{_id}", None if tags is None else json.dumps(tags)),)postgres.connection.commit()@@ -68,6 +71,16 @@ def _alter(table, batch):[{"name": "valid", "accuracy": 0.99}, {"name": "valid_no_accuracy"}],id="denylisted_and_contains_denylisted",),+ pytest.param(+ [+ {"name": "undefined"},+ {"name": "Creative Commons license"},+ {"name": "public domain"},+ {"name": "domain"},+ ],+ [{"name": "domain"}],+ id="ingestion_denylists",+ ),pytest.param([{"name": "By"}, {"name": "bypass"}, {"name": "CC-BY-NC"}],[{"name": "bypass"}],@@ -88,6 +101,20 @@ def _alter(table, batch):],id="low_accuracy",),+ pytest.param(+ [+ {"name": "word_accuracy", "accuracy": "high"},+ {"name": "comma_accuracy", "accuracy": "0,95"},+ {"accuracy": "high"},+ {"name": "padded_accuracy", "accuracy": " 0.95 "},+ {"name": "exponent_accuracy", "accuracy": "9.5e-1"},+ ],+ [+ {"name": "padded_accuracy", "accuracy": " 0.95 "},+ {"name": "exponent_accuracy", "accuracy": "9.5e-1"},+ ],+ id="non_numeric_string_accuracy",+ ),pytest.param([{"name": "valid", "provider": "provider1"},@@ -144,6 +171,17 @@ def test_alter_data_batch_only_updates_rows_in_batch(temp_table):assert _tags_by_id(postgres, table) == {1: bad, 2: good, 3: good, 4: bad}+def test_alter_data_batch_logs_altered_identifiers(temp_table, caplog):+ postgres, table = temp_table+ _insert(postgres, table, {1: [{"name": "cc0"}], 2: [{"name": "cat"}]})++ with caplog.at_level(logging.DEBUG, logger="data_refresh.alter_data"):+ _alter(table, (1, 2))++ assert "Filtered tags for identifier-1" in caplog.text+ assert "identifier-2" not in caplog.text++@pytest.mark.parametrize("id_bounds, batch_size, expected",[@@ -152,6 +190,8 @@ def test_alter_data_batch_only_updates_rows_in_batch(temp_table):((7, 7), 50, [(7, 56)]),# None respects default((1, 100), None, [(1, DEFAULT_BATCH_SIZE)]),+ # An empty table has no id bounds+ ((None, None), 50, []),],)def test_get_alter_batches(id_bounds, batch_size, expected):