Skip to content

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

Fix the new data refresh failures before the staging runs (#5816)

Olga Bulat0a4090af2568
diff --git a/catalog/dags/common/elasticsearch.py b/catalog/dags/common/elasticsearch.py
index b9c326ac1..2569a8d56 100644
--- a/catalog/dags/common/elasticsearch.py
+++ b/catalog/dags/common/elasticsearch.py
@@ -3,7 +3,7 @@ from datetime import timedelta
from typing import Literal
from airflow.decorators import task, task_group
-from airflow.exceptions import AirflowSkipException
+from airflow.exceptions import AirflowException, AirflowSkipException
from airflow.models.connection import Connection
from airflow.providers.elasticsearch.hooks.elasticsearch import ElasticsearchPythonHook
from airflow.sensors.base import PokeReturnValue
@@ -132,6 +132,20 @@ def create_index(index_config, es_host: str):
return new_index
+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).
+ """
+ error = response.get("error")
+ failures = response.get("response", {}).get("failures")
+ if error or failures:
+ raise AirflowException(f"Reindex failed: {error or failures[:5]}")
+
+
@task_group(group_id="trigger_and_wait_for_reindex")
def trigger_and_wait_for_reindex(
es_host: str,
@@ -168,6 +182,10 @@ def trigger_and_wait_for_reindex(
max_docs=max_docs,
# Parallelize indexing when not None
slices=slices,
+ # The default 5m scroll keep-alive expires while slow bulk writes to the
+ # destination index hold up a slice, failing the whole reindex with
+ # "No search context found".
+ scroll="1h",
# Do not hold the slot while awaiting completion
wait_for_completion=False,
# Whether to immediately refresh the index after completion to make
@@ -197,7 +215,10 @@ def trigger_and_wait_for_reindex(
else:
logger.info(f"Reindexed {count} documents.")
- return PokeReturnValue(is_done=response.get("completed") is True)
+ is_done = response.get("completed") is True
+ if is_done:
+ raise_for_reindex_failure(response)
+ return PokeReturnValue(is_done=is_done)
trigger_reindex_task = trigger_reindex(
es_host,
diff --git a/catalog/dags/data_refresh/alter_data.py b/catalog/dags/data_refresh/alter_data.py
index b7ee52aeb..5057af0a8 100644
--- a/catalog/dags/data_refresh/alter_data.py
+++ b/catalog/dags/data_refresh/alter_data.py
@@ -5,6 +5,9 @@ This module contains the Airflow tasks used for filtering, transforming, and aug
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.
+
+The filtering runs as one `UPDATE` per batch of ids inside the API database, so no
+rows are loaded into the Airflow worker.
"""
import logging
@@ -12,14 +15,10 @@ from textwrap import dedent
from airflow.decorators import task, task_group
from airflow.models.abstractoperator import AbstractOperator
-from airflow.providers.common.sql.hooks.handlers import (
- fetch_all_handler,
- fetch_one_handler,
-)
-from psycopg2.extras import Json
+from airflow.providers.common.sql.hooks.handlers import fetch_one_handler
from common.constants import POSTGRES_API_CONN_IDS, Environment
-from common.sql import PGExecuteQueryOperator, PostgresHook
+from common.sql import RETURN_ROW_COUNT, PGExecuteQueryOperator, PostgresHook
from data_refresh.data_refresh_types import DataRefreshConfig
@@ -59,17 +58,35 @@ 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}
+
+# 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.
+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
+ ELSE false
+ END
+ OR 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.
+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})
""")
# Get an estimate of total rows based on the min and max auto-assigned ID
QUERY_ROW_ESTIMATE = dedent("""
@@ -77,45 +94,20 @@ QUERY_ROW_ESTIMATE = dedent("""
""")
-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
+def _like_contains_pattern(term: str) -> str:
+ escaped = term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+ return f"%{escaped}%"
+
+
+def get_tag_filter_parameters() -> dict:
+ return {
+ "min_confidence": TAG_MIN_CONFIDENCE,
+ "filtered_providers": sorted(FILTERED_TAG_PROVIDERS),
+ "denylist": sorted(TAG_DENYLIST),
+ "contains_denylist": sorted(
+ _like_contains_pattern(term) for term in TAG_CONTAINS_DENYLIST
+ ),
+ }
@task
@@ -124,7 +116,7 @@ def get_alter_batches(
) -> 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)]
+ return [(x, x + batch_size - 1) for x in range(start, stop + 1, batch_size)]
@task(max_active_tis_per_dagrun=2)
@@ -143,36 +135,16 @@ def alter_data_batch(
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,
+ altered_count = 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,
)
- 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()
+ logger.info(f"Filtered tags for {altered_count} records in batch {batch}")
return altered_count
diff --git a/catalog/tests/dags/common/test_elasticsearch.py b/catalog/tests/dags/common/test_elasticsearch.py
new file mode 100644
index 000000000..0c9617159
--- /dev/null
+++ b/catalog/tests/dags/common/test_elasticsearch.py
@@ -0,0 +1,48 @@
+import pytest
+from airflow.exceptions import AirflowException
+
+from common.elasticsearch import raise_for_reindex_failure
+
+
+ "response",
+ [
+ pytest.param(
+ {"completed": True, "response": {"total": 10, "failures": []}},
+ id="succeeded",
+ ),
+ pytest.param({"completed": True}, id="no_response_body"),
+ ],
+)
+def test_raise_for_reindex_failure_passes(response):
+ raise_for_reindex_failure(response)
+
+
+ "response",
+ [
+ pytest.param(
+ {
+ "completed": True,
+ "error": {
+ "type": "search_phase_execution_exception",
+ "reason": "No search context found for id [42]",
+ },
+ },
+ id="task_error",
+ ),
+ pytest.param(
+ {
+ "completed": True,
+ "response": {
+ "total": 10,
+ "failures": [{"index": "dest", "id": "1", "status": 400}],
+ },
+ },
+ id="document_failures",
+ ),
+ ],
+)
+def test_raise_for_reindex_failure_raises(response):
+ with pytest.raises(AirflowException, 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.py
index 9b63e28fa..94754185b 100644
--- a/catalog/tests/dags/data_refresh/test_alter_data.py
+++ b/catalog/tests/dags/data_refresh/test_alter_data.py
@@ -1,67 +1,155 @@
-from unittest import mock
+import json
+import psycopg2
import pytest
from data_refresh.alter_data import (
DEFAULT_BATCH_SIZE,
FILTERED_TAG_PROVIDERS,
alter_data_batch,
- generate_tag_updates,
get_alter_batches,
)
+from tests.test_utils import sql
+
+
+def temp_table(request):
+ table = f"temp_import_{abs(hash(request.node.name))}"
+ 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)")
+ conn.commit()
+
+ yield sql.PostgresRef(cursor=cur, connection=conn), table
+
+ cur.execute(f"DROP TABLE IF EXISTS {table}")
+ conn.commit()
+ cur.close()
+ conn.close()
+
+
+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)),
+ )
+ postgres.connection.commit()
+
+
+def _tags_by_id(postgres, table) -> dict[int, object]:
+ postgres.cursor.execute(f"SELECT id, tags FROM {table} ORDER BY id")
+ return dict(postgres.cursor.fetchall())
+
+
+def _alter(table, batch):
+ return alter_data_batch.function(
+ batch=batch, temp_table=table, postgres_conn_id=sql.POSTGRES_CONN_ID
+ )
@pytest.mark.parametrize(
"tags, expected",
[
- # Valid tag returns no updates
- ([{"name": "valid", "accuracy": 0.92}], None),
- # Denylisted tags get filtered
- (
+ pytest.param(
+ [{"name": "valid", "accuracy": 0.92}],
+ [{"name": "valid", "accuracy": 0.92}],
+ id="valid_tag_kept",
+ ),
+ pytest.param(
[
{"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"},
+ {"name": "garbage:=metacrap"},
],
+ [{"name": "valid", "accuracy": 0.99}, {"name": "valid_no_accuracy"}],
+ id="denylisted_and_contains_denylisted",
+ ),
+ pytest.param(
+ [{"name": "By"}, {"name": "bypass"}, {"name": "CC-BY-NC"}],
+ [{"name": "bypass"}],
+ id="case_insensitive_exact_and_contains",
),
- # Inaccurate tags are filtered
- (
+ pytest.param(
[
{"name": "inaccurate", "accuracy": 0.5},
+ {"name": "inaccurate_string", "accuracy": "0.5"},
+ {"name": "accurate", "accuracy": 0.999},
+ {"name": "threshold", "accuracy": 0.9},
+ {"name": "null_accuracy", "accuracy": None},
+ ],
+ [
{"name": "accurate", "accuracy": 0.999},
+ {"name": "threshold", "accuracy": 0.9},
+ {"name": "null_accuracy", "accuracy": None},
],
- [{"name": "accurate", "accuracy": 0.999}],
+ id="low_accuracy",
),
- # Tags from unvetted providers get filtered
- (
+ pytest.param(
[
{"name": "valid", "provider": "provider1"},
+ {"name": "no_provider", "provider": None},
*[
{"name": "invalid", "provider": provider}
for provider in FILTERED_TAG_PROVIDERS
],
],
- [{"name": "valid", "provider": "provider1"}],
+ [
+ {"name": "valid", "provider": "provider1"},
+ {"name": "no_provider", "provider": None},
+ ],
+ id="filtered_providers",
+ ),
+ pytest.param(
+ [{"accuracy": 0.99}, {"name": 5}, {"name": None}, "bare", {"name": "ok"}],
+ [{"name": "ok"}],
+ id="malformed",
+ ),
+ pytest.param(
+ [{"name": "cc0"}, {"name": "squareformat"}],
+ [],
+ id="all_tags_filtered",
),
+ pytest.param(
+ [{"name": "b"}, {"name": "uploaded"}, {"name": "a"}, {"name": "c"}],
+ [{"name": "b"}, {"name": "a"}, {"name": "c"}],
+ id="order_preserved",
+ ),
+ pytest.param(None, None, id="null_tags"),
+ pytest.param([], [], id="empty_tags"),
+ pytest.param({"name": "cc0"}, {"name": "cc0"}, id="non_array_tags"),
],
)
-def test_generate_tag_updates(tags, expected):
- actual = generate_tag_updates(tags)
- assert actual == expected
+def test_alter_data_batch_filters_tags(temp_table, tags, expected):
+ postgres, table = temp_table
+ _insert(postgres, table, {1: tags})
+
+ count = _alter(table, (1, 1))
+
+ assert _tags_by_id(postgres, table) == {1: expected}
+ assert count == (0 if tags == expected else 1)
+
+
+def test_alter_data_batch_only_updates_rows_in_batch(temp_table):
+ postgres, table = temp_table
+ bad, good = [{"name": "cc0"}, {"name": "cat"}], [{"name": "cat"}]
+ _insert(postgres, table, {1: bad, 2: bad, 3: good, 4: bad})
+
+ count = _alter(table, (2, 3))
+
+ assert count == 1
+ assert _tags_by_id(postgres, table) == {1: bad, 2: good, 3: good, 4: bad}
@pytest.mark.parametrize(
"id_bounds, batch_size, expected",
[
((1, 100), 50, [(1, 50), (51, 100)]),
+ ((1, 101), 50, [(1, 50), (51, 100), (101, 150)]),
+ ((7, 7), 50, [(7, 56)]),
# None respects default
((1, 100), None, [(1, DEFAULT_BATCH_SIZE)]),
],
@@ -69,32 +157,3 @@ def test_generate_tag_updates(tags, expected):
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]