Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add option to skip specific ingestion errors (#1011)
Staci Mullins4527fbe7af76
diff --git a/DAGs.md b/DAGs.mdindex 3cd097300..58c5156f4 100644--- a/DAGs.md+++ b/DAGs.md@@ -210,21 +210,24 @@ and related PRs:### Silenced DAGs check-Check for DAGs that have silenced Slack alerts which may need to be turned back-on.+Check for DAGs that have silenced Slack alerts or skipped errors which may need+to be turned back on.When a DAG has known failures, it can be ommitted from Slack error reporting by-adding an entry to the `SILENCED_SLACK_NOTIFICATIONS` Airflow variable. This is-a dictionary where thekey is the `dag_id` of the affected DAG, and the value is-a list of SilencedSlackNotifications (which map silenced notifications to GitHub-URLs) for that DAG.+adding an entry to the `SILENCED_SLACK_NOTIFICATIONS` Airflow variable.+Similarly, errors that occur during the `pull_data` step may be configured to+skip and allow ingestion to continue, using the `SKIPPED_INGESTION_ERRORS`+Airflow variable. These variables are dictionaries where the key is the `dag_id`+of the affected DAG, and the value is a list of configuration dictionaries+mapping an error `predicate` to be skipped/silenced to an open GitHub issue.The `check_silenced_dags` DAG iterates over the entries in the-`SILENCED_SLACK_NOTIFICATIONS` configuration and verifies that the associated-GitHub issues are still open. If an issue has been closed, it is assumed that-the DAG should have Slack reporting reenabled, and an alert is sent to prompt-manual update of the configuration. This prevents developers from forgetting to-reenable Slack reporting after the issue has been resolved.+`SILENCED_SLACK_NOTIFICATIONS` and `SKIPPED_INGESTION_ERRORS` configurations and+verifies that the associated GitHub issues are still open. If an issue has been+closed, it is assumed that the entry should be removed, and an alert is sent to+prompt manual update of the configuration. This prevents developers from+forgetting to reenable Slack reporting or turnoff error skipping after the issue+has been resolved.The DAG runs weekly.diff --git a/openverse_catalog/dags/maintenance/check_silenced_dags.py b/openverse_catalog/dags/maintenance/check_silenced_dags.pyindex 1276bfff4..f130f9789 100644--- a/openverse_catalog/dags/maintenance/check_silenced_dags.py+++ b/openverse_catalog/dags/maintenance/check_silenced_dags.py@@ -1,20 +1,23 @@"""# Silenced DAGs check-Check for DAGs that have silenced Slack alerts which may need to be turned back on.+Check for DAGs that have silenced Slack alerts or skipped errors which may need to be+turned back on.When a DAG has known failures, it can be ommitted from Slack error reporting by adding-an entry to the `SILENCED_SLACK_NOTIFICATIONS` Airflow variable. This is a dictionary-where thekey is the `dag_id` of the affected DAG, and the value is a list of-SilencedSlackNotifications (which map silenced notifications to GitHub URLs) for that-DAG.+an entry to the `SILENCED_SLACK_NOTIFICATIONS` Airflow variable. Similarly, errors that+occur during the `pull_data` step may be configured to skip and allow ingestion to+continue, using the `SKIPPED_INGESTION_ERRORS` Airflow variable. These variables are+dictionaries where the key is the `dag_id` of the affected DAG, and the value is a list+of configuration dictionaries mapping an error `predicate` to be skipped/silenced to an+open GitHub issue.The `check_silenced_dags` DAG iterates over the entries in the-`SILENCED_SLACK_NOTIFICATIONS` configuration and verifies that the associated GitHub-issues are still open. If an issue has been closed, it is assumed that the DAG should-have Slack reporting reenabled, and an alert is sent to prompt manual update of the-configuration. This prevents developers from forgetting to reenable Slack reporting-after the issue has been resolved.+`SILENCED_SLACK_NOTIFICATIONS` and `SKIPPED_INGESTION_ERRORS` configurations and+verifies that the associated GitHub issues are still open. If an issue has been closed,+it is assumed that the entry should be removed, and an alert is sent to prompt manual+update of the configuration. This prevents developers from forgetting to reenable Slack+reporting or turnoff error skipping after the issue has been resolved.The DAG runs weekly."""@@ -28,6 +31,7 @@ from airflow.operators.python import PythonOperatorfrom common.constants import DAG_DEFAULT_ARGSfrom common.github import GitHubAPIfrom common.slack import SilencedSlackNotification, send_alert+from providers.provider_api_scripts.provider_data_ingester import SkippedIngestionErrorlogger = logging.getLogger(__name__)@@ -35,6 +39,7 @@ logger = logging.getLogger(__name__)DAG_ID = "check_silenced_dags"MAX_ACTIVE = 1+CONFIGURATIONS = ["SILENCED_SLACK_NOTIFICATIONS", "SKIPPED_INGESTION_ERRORS"]def get_issue_info(issue_url: str) -> tuple[str, str, str]:@@ -46,7 +51,8 @@ def get_issue_info(issue_url: str) -> tuple[str, str, str]:def get_dags_with_closed_issues(- github_pat: str, silenced_dags: dict[str, list[SilencedSlackNotification]]+ github_pat: str,+ silenced_dags: dict[str, list[SilencedSlackNotification | SkippedIngestionError]],) -> list[tuple[str, str, str, str | None]]:gh = GitHubAPI(github_pat)@@ -71,26 +77,28 @@ def get_dags_with_closed_issues(return dags_to_reenable-def check_configuration(github_pat: str):- silenced_dags = Variable.get(- "SILENCED_SLACK_NOTIFICATIONS", default_var={}, deserialize_json=True+def check_configuration(github_pat: str, airflow_variable: str):+ configuration = Variable.get(+ airflow_variable, default_var={}, deserialize_json=True)- dags_to_reenable = get_dags_with_closed_issues(github_pat, silenced_dags)++ dags_to_reenable = get_dags_with_closed_issues(github_pat, configuration)if not dags_to_reenable:raise AirflowSkipException(- "All DAGs configured to silence messages have work still in progress."- " No configuration updates needed."+ f"No configuration updates to {airflow_variable} needed.")message = (- "The following DAGs have Slack messages silenced, but the associated issue is"- " closed. Please remove them from the silenced_slack_notifications Airflow"- " variable or assign a new issue."+ "The following DAG configurations are associated to a closed GitHub issue."+ f" Please remove them from the {airflow_variable} Airflow variable or assign"+ " a new issue.")+for (dag, issue, predicate, task_id_pattern) in dags_to_reenable:dag_name = f"{dag} ({task_id_pattern})" if task_id_pattern else dagmessage += f"\n - <{issue}|{dag_name}: '{predicate}'>"+send_alert(message, dag_id=DAG_ID, username="Silenced DAG Check", unfurl_links=False)@@ -112,11 +120,14 @@ dag = DAG(tags=["maintenance"],)+with dag:- PythonOperator(- task_id="check_silenced_dags_configuration",- python_callable=check_configuration,- op_kwargs={- "github_pat": "{{ var.value.get('GITHUB_API_KEY', 'not_set') }}",- },- )+ for airflow_variable in CONFIGURATIONS:+ PythonOperator(+ task_id=f"check_{airflow_variable.lower()}",+ python_callable=check_configuration,+ op_kwargs={+ "github_pat": "{{ var.value.get('GITHUB_API_KEY', 'not_set') }}",+ "airflow_variable": airflow_variable,+ },+ )diff --git a/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.py b/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.pyindex b7007ebb6..5339e6580 100644--- a/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.py+++ b/openverse_catalog/dags/providers/provider_api_scripts/provider_data_ingester.py@@ -3,6 +3,7 @@ import loggingimport tracebackfrom abc import ABC, abstractmethodfrom datetime import datetime+from typing import TypedDictfrom airflow.exceptions import AirflowExceptionfrom airflow.models import Variable@@ -47,6 +48,20 @@ class IngestionError(Exception):return f"{str(self)}\n{self.traceback}"+class SkippedIngestionError(TypedDict):+ """+ Configuration for a silenced ingestion error.++ issue: A link to a GitHub issue which describes why the error+ is silenced and tracks resolving the problem.+ predicate: Errors whose classname or message contain the predicate will be+ skipped. Matching is case-insensitive.+ """++ issue: str+ predicate: str++class ProviderDataIngester(ABC):"""ABC which initializes media stores and ingests records from a given provider.@@ -147,11 +162,6 @@ class ProviderDataIngester(ABC):if self.date:logger.info(f"Using date {self.date}.")- # Used to skip over errors and continue ingestion. When enabled, errors- # are not reported until ingestion has completed.- self.skip_ingestion_errors = conf.get("skip_ingestion_errors", False)- self.ingestion_errors: list[IngestionError] = [] # Keep track of errors-# An optional set of initial query params from which to begin ingestion.self.initial_query_params = conf.get("initial_query_params")@@ -162,6 +172,21 @@ class ProviderDataIngester(ABC):# Create a generator to facilitate fetching the next set of query_params.self.override_query_params = (qp for qp in query_params_list)+ # A configuration option that is used to skip over ALL errors and continue+ # ingestion, reporting errors in aggregate when ingestion has completed. This+ # option should be used sparingly and can only be enabled at the level of an+ # individual DagRun.+ self.skip_all_ingestion_errors = conf.get("skip_ingestion_errors", False)++ # Global configuration for particular errors that should be skipped across all+ # runs of this DAG. Only errors matching the configuration will be skipped, and+ # reported in aggregate when ingestion has completed.+ self.skipped_ingestion_errors: list[SkippedIngestionError] = Variable.get(+ "SKIPPED_INGESTION_ERRORS", default_var={}, deserialize_json=True+ ).get(self.dag_id, [])++ self.ingestion_errors: list[IngestionError] = [] # Keep track of skipped errors+def _init_media_stores(self, day_shift: int = None) -> dict[str, MediaStore]:"""Initialize a media store for each media type supported by this provider."""@@ -226,7 +251,7 @@ class ProviderDataIngester(ABC):error, traceback.format_exc(), query_params)- if self.skip_ingestion_errors:+ if self._should_skip_ingestion_error(error):# Add this to the errors list but continue processingself.ingestion_errors.append(ingestion_error)logger.error(f"Skipping batch due to ingestion error: {error}")@@ -248,6 +273,18 @@ class ProviderDataIngester(ABC):if error_summary := self._get_ingestion_errors():raise error_summary+ def _should_skip_ingestion_error(self, error: Exception) -> bool:+ """Determine whether an error should be skipped."""+ if self.skip_all_ingestion_errors:+ return True++ for skipped_error in self.skipped_ingestion_errors:+ # Check if the predicate matches+ if skipped_error["predicate"].lower() in repr(error).lower():+ return True++ return False+def _get_ingestion_errors(self) -> AggregateIngestionError | None:"""Retrieve all ingestion errors that have been caught during processing.diff --git a/tests/dags/maintenance/test_check_silenced_dags.py b/tests/dags/maintenance/test_check_silenced_dags.pyindex b96a7dc5a..7ed42859a 100644--- a/tests/dags/maintenance/test_check_silenced_dags.py+++ b/tests/dags/maintenance/test_check_silenced_dags.py@@ -120,7 +120,7 @@ def test_check_configuration(silenced_dags, dags_to_reenable, should_send_alert)) as get_dags_with_closed_issues_mock,mock.patch("maintenance.check_silenced_dags.send_alert") as send_alert_mock,):- message = check_configuration("not_set")+ message = check_configuration("not_set", "my_variable")assert send_alert_mock.called == should_send_alertassert get_dags_with_closed_issues_mock.called_with("not_set", silenced_dags)@@ -154,7 +154,7 @@ def test_check_configuration_formats_dag_correctly():),mock.patch("maintenance.check_silenced_dags.send_alert"),):- message = check_configuration("not_set")+ message = check_configuration("not_set", "my_variable")# Called with correct dag_idsassert f"<{issue}|{dag} ({task_id_pattern}): '{predicate}'>" in messagediff --git a/tests/dags/providers/provider_api_scripts/test_provider_data_ingester.py b/tests/dags/providers/provider_api_scripts/test_provider_data_ingester.pyindex ab3b98c5b..7e193abb6 100644--- a/tests/dags/providers/provider_api_scripts/test_provider_data_ingester.py+++ b/tests/dags/providers/provider_api_scripts/test_provider_data_ingester.py@@ -102,7 +102,10 @@ def test_batch_limit_is_capped_to_ingestion_limit():with patch("providers.provider_api_scripts.provider_data_ingester.Variable") as MockVariable:- MockVariable.get.side_effect = [20]+ MockVariable.get.side_effect = [+ 20, # ingestion_limit+ {}, # skipped_ingestion_errors+ ]ingester = MockProviderDataIngester()assert ingester.batch_limit == 20@@ -274,7 +277,10 @@ def test_ingest_records_stops_after_reaching_limit():"providers.provider_api_scripts.provider_data_ingester.Variable") as MockVariable:# Mock the calls to Variable.get, in order- MockVariable.get.side_effect = [3]+ MockVariable.get.side_effect = [+ 3, # ingestion_limit+ {}, # skipped_ingestion_errors+ ]ingester = MockProviderDataIngester()@@ -399,10 +405,13 @@ def test_ingest_records_raises_IngestionError():# Multiple errors are skipped([- Exception("Mock exception 1"),- (EXPECTED_BATCH_DATA, True), # First error- Exception("Mock exception 2"),- (EXPECTED_BATCH_DATA, False), # Second error, `should_continue` False+ Exception("Mock exception 1"), # First error+ (EXPECTED_BATCH_DATA, True), # 'Good' batch+ Exception("Mock exception 2"), # Second error+ (+ EXPECTED_BATCH_DATA,+ False,+ ), # 'Good' batch, but `should_continue` False],4, # get_batch is called until `should_continue` is False, ignoring errorsAggregateIngestionError,@@ -429,14 +438,15 @@ def test_ingest_records_raises_IngestionError():),],)-def test_ingest_records_with_skip_ingestion_errors(+def test_ingest_records_handles_skipped_ingestion_errors(batches, expected_call_count, expected_error):- ingester = MockProviderDataIngester({"skip_ingestion_errors": True})+ ingester = MockProviderDataIngester()with (patch.object(ingester, "get_batch") as get_batch_mock,patch.object(ingester, "process_batch", return_value=10),+ patch.object(ingester, "_should_skip_ingestion_error", return_value=True),):get_batch_mock.side_effect = batches@@ -449,6 +459,101 @@ def test_ingest_records_with_skip_ingestion_errors(assert get_batch_mock.call_count == expected_call_count+ "skip_all_ingestion_errors, skipped_ingestion_errors, error, should_skip",+ [+ # When `skip_ingestion_errors` is enabled:+ # No specific configured errors+ (True, [], ValueError("Test error"), True),+ # The error is also specifically configured to skip+ (+ True,+ [+ {+ "issue": "https://github.com/WordPress/openverse/issues/1",+ "predicate": "Test",+ }+ ],+ ValueError("Test error"),+ True,+ ),+ # When `skip_ingestion_errors` is not enabled:+ # No errors are configured to skip+ (False, [], ValueError("Test error"), False),+ # There are some configured skipped errors, but they do not match+ (+ False,+ [+ {+ "issue": "https://github.com/WordPress/openverse/issues/1",+ "predicate": "KeyError",+ },+ {+ "issue": "https://github.com/WordPress/openverse/issues/1",+ "predicate": "Foo",+ },+ ],+ ValueError("Test error"),+ False,+ ),+ # Match on the error message+ (+ False,+ [+ {+ "issue": "https://github.com/WordPress/openverse/issues/1",+ "predicate": "My mock error",+ },+ ],+ ValueError("My mock error"),+ True,+ ),+ # Match on the error class+ (+ False,+ [+ {+ "issue": "https://github.com/WordPress/openverse/issues/1",+ "predicate": "KeyError",+ },+ ],+ KeyError("A message that does not otherwise match the predicate"),+ True,+ ),+ # Match is partial and not case-sensitive+ (+ False,+ [+ {+ "issue": "https://github.com/WordPress/openverse/issues/1",+ "predicate": "fOo",+ },+ ],+ ValueError("This error message contains the predicate FOO"),+ True,+ ),+ ],+)+def test_should_skip_ingestion_error(+ skip_all_ingestion_errors, skipped_ingestion_errors, error, should_skip+):+ with patch(+ "providers.provider_api_scripts.provider_data_ingester.Variable"+ ) as MockVariable:+ # Mock the calls to Variable.get in order+ MockVariable.get.side_effect = [+ None, # ingestion_limit+ {"my_dag_id": skipped_ingestion_errors}, # skipped_ingestion_errors+ ]++ ingester = MockProviderDataIngester(+ conf={"skip_ingestion_errors": skip_all_ingestion_errors},+ dag_id="my_dag_id",+ )++ assert ingester._should_skip_ingestion_error(error) == should_skip++def test_ingest_records_exits_immediately_if_limit_already_reached():# A child class may override `ingest_records` to run multiple times.# Once the ingestion limit has been reached, subsequent calls to@@ -458,7 +563,10 @@ def test_ingest_records_exits_immediately_if_limit_already_reached():"providers.provider_api_scripts.provider_data_ingester.Variable") as MockVariable:# Mock the calls to Variable.get to set an ingestion limit- MockVariable.get.side_effect = [5]+ MockVariable.get.side_effect = [+ 5, # ingestion_limit+ {}, # skipped_ingestion_errors+ ]ingester = MockProviderDataIngester()