Skip to content

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

Enable replicas before promotion and fan alter_data out over fixed ranges (#5848)

Olga Bulat4f62f9501dfe
diff --git a/catalog/dags/common/elasticsearch.py b/catalog/dags/common/elasticsearch.py
index b6174b4de..807ec8308 100644
--- a/catalog/dags/common/elasticsearch.py
+++ b/catalog/dags/common/elasticsearch.py
@@ -8,7 +8,7 @@ from airflow.providers.elasticsearch.hooks.elasticsearch import ElasticsearchPyt
from airflow.providers.standard.triggers.temporal import TimeDeltaTrigger
from airflow.sdk import BaseOperator, Connection, task, task_group
from airflow.sdk.exceptions import AirflowFailException, AirflowSkipException
-from elasticsearch.exceptions import NotFoundError
+from elasticsearch.exceptions import ApiError, NotFoundError
from common.constants import REFRESH_POKE_INTERVAL
@@ -476,6 +476,77 @@ def refresh_index(es_host: str, index_name: str):
return es_conn.indices.refresh(index=index_name).body
+@task
+def enable_replicas(es_host: str, index_names: list[str]):
+ """
+ Give each index one replica of every shard. Indices are built without replicas
+ to speed up reindexing, but serving one without them leaves a single copy of
+ the data and half the shards to spread searches over.
+
+ A replica is never allocated to the node that holds its primary, so a cluster
+ with a single data node, like the local one, keeps its indices without
+ replicas. They would otherwise never turn green.
+ """
+ es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn
+ data_nodes = es_conn.cluster.health()["number_of_data_nodes"]
+ replicas = 1 if data_nodes > 1 else 0
+ if not replicas:
+ logger.info(
+ f"The cluster has {data_nodes} data node(s), so {index_names} are left "
+ "without replicas."
+ )
+ return es_conn.indices.put_settings(
+ index=",".join(index_names),
+ settings={"index": {"number_of_replicas": replicas}},
+ ).body
+
+
+def _log_unassigned_reason(es_conn, index_names: list[str]):
+ """Log why Elasticsearch has not allocated one of the unassigned shards."""
+ shards = es_conn.cat.shards(
+ index=",".join(index_names), h="index,shard,prirep,state", format="json"
+ )
+ shard = next((s for s in shards if s["state"] == "UNASSIGNED"), None)
+ if shard is None:
+ return
+ try:
+ explanation = es_conn.cluster.allocation_explain(
+ index=shard["index"],
+ shard=int(shard["shard"]),
+ primary=shard["prirep"] == "p",
+ )
+ except ApiError as err:
+ # The shard may have been assigned since it was listed.
+ logger.info(f"Could not explain the allocation of {shard}: {err}")
+ return
+ reasons = sorted(
+ {
+ decider["explanation"]
+ for node in explanation.get("node_allocation_decisions", [])
+ for decider in node.get("deciders", [])
+ }
+ )
+ logger.info(
+ f"Shard {shard['shard']} of {shard['index']} is unassigned "
+ f"({explanation.get('allocate_explanation')}): {reasons}"
+ )
+
+
[email protected](mode="reschedule")
+def wait_for_green_indices(es_host: str, index_names: list[str]) -> bool:
+ """Wait until every shard of the indices, replicas included, is allocated."""
+ es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conn
+ health = es_conn.cluster.health(index=",".join(index_names))
+ logger.info(
+ f"{index_names} are {health['status']}: "
+ f"{health['initializing_shards']} shards initializing, "
+ f"{health['unassigned_shards']} unassigned."
+ )
+ if health["unassigned_shards"]:
+ _log_unassigned_reason(es_conn, index_names)
+ return health["status"] == "green"
+
+
@task_group(group_id="point_alias")
def point_alias(
es_host: str,
diff --git a/catalog/dags/data_refresh/alter_data.py b/catalog/dags/data_refresh/alter_data.py
index 0eaf67003..2c4f88c96 100644
--- a/catalog/dags/data_refresh/alter_data.py
+++ b/catalog/dags/data_refresh/alter_data.py
@@ -7,17 +7,21 @@ Currently, this provides an entrypoint for filtering tags that do not meet a cer
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.
+rows are loaded into the Airflow worker. The id range is split into a fixed number
+of mapped tasks, each of which works through its share in batches, so the number of
+tasks doesn't grow with the table. Each task records the batches it has committed in
+an Airflow variable, so a retry carries on from where the last attempt stopped.
"""
import logging
+import math
from textwrap import dedent
from airflow.providers.common.sql.hooks.handlers import (
fetch_all_handler,
fetch_one_handler,
)
-from airflow.sdk import BaseOperator, task, task_group
+from airflow.sdk import BaseOperator, Variable, task, task_group
from common.constants import POSTGRES_API_CONN_IDS, Environment
from common.sql import PGExecuteQueryOperator, PostgresHook
@@ -29,6 +33,7 @@ logger = logging.getLogger(__name__)
DEFAULT_BATCH_SIZE = 100_000
+ALTER_DATA_RANGE_COUNT = 8
# Filter out low-confidence tags, which indicate that the machine-generated tag
# may be inaccurate.
TAG_MIN_CONFIDENCE = 0.90
@@ -108,48 +113,104 @@ def get_tag_filter_parameters() -> dict:
}
+def get_progress_variable(progress_prefix: str, map_index: int) -> str:
+ return f"{progress_prefix}_{map_index}"
+
+
@task
-def get_alter_batches(
- id_bounds: tuple[int | None, int | None], batch_size: int | None
+def get_alter_ranges(
+ id_bounds: tuple[int | None, int | None],
+ progress_prefix: str,
+ range_count: int = ALTER_DATA_RANGE_COUNT,
) -> list[tuple[int, int]]:
+ """
+ Split the ids into at most `range_count` contiguous, inclusive ranges.
+
+ This runs once for each copy of the temp table, so it also drops the progress
+ that `alter_data_range` recorded against an earlier copy.
+ """
+ for map_index in range(range_count):
+ Variable.delete(get_progress_variable(progress_prefix, map_index))
+
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_SIZE
- return [(x, x + batch_size - 1) for x in range(start, stop + 1, batch_size)]
+ range_size = math.ceil((stop - start + 1) / range_count)
+ return [
+ (x, min(x + range_size - 1, stop)) for x in range(start, stop + 1, range_size)
+ ]
+
+
+def get_batches(id_range: tuple[int, int], batch_size: int) -> list[tuple[int, int]]:
+ start, stop = id_range
+ return [
+ (x, min(x + batch_size - 1, stop)) for x in range(start, stop + 1, batch_size)
+ ]
@task(max_active_tis_per_dagrun=2)
-def alter_data_batch(
- batch: tuple[int, int],
+def alter_data_range(
+ id_range: tuple[int, int],
+ batch_size: int | None,
temp_table: str,
postgres_conn_id: str,
+ progress_prefix: str,
+ ti=None,
task: BaseOperator = None,
timeout: float = None,
) -> int:
- logger.info(f"Starting data altering on batch: {batch}")
- batch_start, batch_end = batch
+ """
+ Filter the tags of the rows in `id_range`, one `UPDATE` and commit per batch,
+ and return how many rows were altered.
+
+ The next id to alter and the running count are saved after each batch, so that
+ a retry neither repeats the committed batches nor loses their count.
+ """
postgres = PostgresHook(
postgres_conn_id=postgres_conn_id,
default_statement_timeout=(
timeout if timeout else PostgresHook.get_execution_timeout(task)
),
)
- 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=fetch_all_handler,
+ progress_variable = get_progress_variable(progress_prefix, ti.map_index)
+ progress = Variable.get(
+ progress_variable,
+ {"next_start": id_range[0], "altered": 0},
+ deserialize_json=True,
)
- 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)
+ next_start, total = progress["next_start"], progress["altered"]
+ if next_start != id_range[0]:
+ logger.info(f"Resuming {id_range} at {next_start}: {total} records altered")
+
+ for batch_start, batch_end in get_batches(
+ (next_start, id_range[1]), batch_size or DEFAULT_BATCH_SIZE
+ ):
+ 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=fetch_all_handler,
+ )
+ 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 "
+ f"({batch_start}, {batch_end})"
+ )
+ total += len(altered)
+ Variable.set(
+ progress_variable,
+ {"next_start": batch_end + 1, "altered": total},
+ serialize_json=True,
+ )
+
+ Variable.delete(progress_variable)
+ return total
@task
@@ -176,14 +237,22 @@ def alter_table_data(
return_last=True,
)
- batches = get_alter_batches(
- estimated_record_count.output,
- batch_size=data_refresh_config.alter_data_batch_size,
+ progress_prefix = f"{postgres_conn_id}_{temp_table}_alter_data_progress"
+ ranges = get_alter_ranges(
+ estimated_record_count.output, progress_prefix=progress_prefix
)
- alter_data = alter_data_batch.partial(
- temp_table=temp_table,
- postgres_conn_id=postgres_conn_id,
- ).expand(batch=batches)
+ alter_data = (
+ alter_data_range.override(
+ execution_timeout=data_refresh_config.alter_data_timeout,
+ )
+ .partial(
+ batch_size=data_refresh_config.alter_data_batch_size,
+ temp_table=temp_table,
+ postgres_conn_id=postgres_conn_id,
+ progress_prefix=progress_prefix,
+ )
+ .expand(id_range=ranges)
+ )
report(alter_data)
diff --git a/catalog/dags/data_refresh/dag_factory.py b/catalog/dags/data_refresh/dag_factory.py
index 497b2b457..ae1fb9cd9 100644
--- a/catalog/dags/data_refresh/dag_factory.py
+++ b/catalog/dags/data_refresh/dag_factory.py
@@ -9,6 +9,7 @@ The data refresh has the following high level steps:
* Create Index: Create a new Elasticsearch index, matching the configuration of the existing media index.
* Distributed Reindex: Convert each record from the new temp table to the format required by an Elasticsearch document, and then reindex them into the newly created index.
* Create and Populate Filtered Index: Create a new Elasticsearch index matching the configuration of the existing filtered index, and then reindex documents into it from the new media index, applying appropriate filtering for sensitive terms.
+* Enable Replicas: Give both new indices a replica of every shard, and wait for the replicas to be allocated.
* Reapply Constraints: Recreate indices and constraints from the original API tables on the new temp tables.
* Promote Table: Drop the old media table in the API and rename the temp table and its indices, which has the effect of promoting them/replacing the old table.
* Promote Index: Promote the new Elasticsearch index by unlinking the given alias from the existing index and moving it to the new one. (Used for both the main and filtered indices.)
@@ -250,6 +251,13 @@ def create_data_refresh_dag(
poke_interval=data_refresh_config.reindex_poke_interval,
)
+ new_indices = [target_index_name, filtered_index_name]
+ replicas = es.enable_replicas(es_host=es_host, index_names=new_indices)
+ replicas_ready = es.wait_for_green_indices.override(
+ poke_interval=data_refresh_config.reindex_poke_interval,
+ timeout=data_refresh_config.index_readiness_timeout.total_seconds(),
+ )(es_host=es_host, index_names=new_indices)
+
# Re-enable Cloudwatch alarms once reindexing is complete, even if it
# failed.
enable_alarms = PythonOperator(
@@ -316,10 +324,13 @@ def create_data_refresh_dag(
>> reindex
>> filtered_index_name
>> filtered_index
+ >> replicas
+ >> replicas_ready
)
- # Note filtered_index must be directly upstream of promote_table to
- # ensure that table promotion does not run if there was an error during reindexing
- filtered_index >> [enable_alarms, promote_table]
+ # The alarms only cover reindexing, so they don't wait for the replicas
+ filtered_index >> enable_alarms
+ # Table promotion must not run if reindexing or replication failed
+ replicas_ready >> promote_table
promote_table >> [promote_index, promote_filtered_index]
promote_index >> after_record_count >> report_counts
diff --git a/catalog/dags/data_refresh/data_refresh_types.py b/catalog/dags/data_refresh/data_refresh_types.py
index c08af151b..960d90e43 100644
--- a/catalog/dags/data_refresh/data_refresh_types.py
+++ b/catalog/dags/data_refresh/data_refresh_types.py
@@ -9,8 +9,6 @@ import os
from dataclasses import dataclass, field
from datetime import datetime, timedelta
-from airflow.sdk import Variable
-
from common.constants import (
AUDIO,
DATA_REFRESH_ALTER_BATCH_SIZE,
@@ -80,6 +78,8 @@ class DataRefreshConfig:
add the primary key to the temp table
alter_data_batch_size: int number of records to process per batch in alter_data
tasks
+ alter_data_timeout: timedelta expressing the amount of time it may take to
+ alter one of the id ranges of the temp table
indexer_worker_timeout: timedelta expressing the amount of time it may take for
any individual indexer worker to perform its portion of
the distributed reindex
@@ -107,6 +107,7 @@ class DataRefreshConfig:
copy_data_timeout: timedelta = timedelta(hours=1)
add_primary_key_timeout: timedelta = timedelta(hours=1)
alter_data_batch_size: int = DATA_REFRESH_ALTER_BATCH_SIZE
+ alter_data_timeout: timedelta = timedelta(hours=1)
indexer_worker_timeout: timedelta = timedelta(hours=12)
index_readiness_timeout: timedelta = timedelta(days=1)
create_filtered_index_timeout: timedelta = timedelta(days=1)
@@ -137,12 +138,7 @@ DATA_REFRESH_CONFIGS = {
dag_timeout=timedelta(days=6),
copy_data_timeout=timedelta(hours=12),
add_primary_key_timeout=timedelta(hours=12),
- # Larger batches for image data refresh to avoid overloading XCOMs
- alter_data_batch_size=Variable.get(
- "IMAGE_DATA_REFRESH_ALTER_BATCH_SIZE",
- default=DATA_REFRESH_ALTER_BATCH_SIZE,
- deserialize_json=True,
- ),
+ alter_data_timeout=timedelta(hours=12),
indexer_worker_timeout=timedelta(days=3),
concurrency_check_poke_interval=int(
os.getenv("DATA_REFRESH_POKE_INTERVAL", 60 * 5)
diff --git a/catalog/env.template b/catalog/env.template
index de5ba618a..2f0a6f3b5 100644
--- a/catalog/env.template
+++ b/catalog/env.template
@@ -133,7 +133,7 @@ AIRFLOW_VAR_ES_INDEX_THROTTLING_RATE=20000
# 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
+DATA_REFRESH_ALTER_BATCH_SIZE=1000
# S3 prefix location for the Rekognition dataset
AIRFLOW_VAR_REKOGNITION_DATASET_PREFIX=image_analysis_labels.jsonl
diff --git a/catalog/tests/dags/common/test_elasticsearch.py b/catalog/tests/dags/common/test_elasticsearch.py
index 24bd62994..ef1b6c07f 100644
--- a/catalog/tests/dags/common/test_elasticsearch.py
+++ b/catalog/tests/dags/common/test_elasticsearch.py
@@ -6,6 +6,7 @@ from unittest import mock
import pytest
from airflow.sdk import timezone
from airflow.sdk.exceptions import AirflowFailException, TaskDeferred
+from elasticsearch.exceptions import ApiError
from common import elasticsearch as es
from common.elasticsearch import (
@@ -302,3 +303,80 @@ def test_create_index_does_not_reuse_aliased_index(monkeypatch):
es.create_index.function({"index": "image-new"}, "http://es:9200", True)
es_conn.indices.create.assert_not_called()
+
+
[email protected]("data_nodes, expected_replicas", [(1, 0), (2, 1), (3, 1)])
+def test_enable_replicas(monkeypatch, data_nodes, expected_replicas):
+ es_conn = mock.Mock()
+ es_conn.cluster.health.return_value = {"number_of_data_nodes": data_nodes}
+ _hook(monkeypatch, es_conn)
+
+ es.enable_replicas.function("http://es:9200", ["image-new", "image-new-filtered"])
+
+ es_conn.indices.put_settings.assert_called_once_with(
+ index="image-new,image-new-filtered",
+ settings={"index": {"number_of_replicas": expected_replicas}},
+ )
+
+
+ "status, expected",
+ [("green", True), ("yellow", False), ("red", False)],
+)
+def test_wait_for_green_indices(monkeypatch, status, expected):
+ es_conn = mock.Mock()
+ es_conn.cluster.health.return_value = {
+ "status": status,
+ "initializing_shards": 0,
+ "unassigned_shards": 0,
+ }
+ _hook(monkeypatch, es_conn)
+
+ assert (
+ es.wait_for_green_indices.function("http://es:9200", ["image-new"]) is expected
+ )
+ es_conn.cluster.health.assert_called_once_with(index="image-new")
+ es_conn.cluster.allocation_explain.assert_not_called()
+
+
+def _unassigned_es_conn():
+ es_conn = mock.Mock()
+ es_conn.cluster.health.return_value = {
+ "status": "yellow",
+ "initializing_shards": 0,
+ "unassigned_shards": 1,
+ }
+ es_conn.cat.shards.return_value = [
+ {"index": "image-new", "shard": "0", "prirep": "p", "state": "STARTED"},
+ {"index": "image-new", "shard": "3", "prirep": "r", "state": "UNASSIGNED"},
+ ]
+ return es_conn
+
+
+def test_wait_for_green_indices_logs_why_a_shard_is_unassigned(monkeypatch, caplog):
+ es_conn = _unassigned_es_conn()
+ es_conn.cluster.allocation_explain.return_value = {
+ "allocate_explanation": "cannot allocate",
+ "node_allocation_decisions": [
+ {"deciders": [{"explanation": "the node is above the high watermark"}]}
+ ],
+ }
+ _hook(monkeypatch, es_conn)
+
+ with caplog.at_level("INFO", logger="common.elasticsearch"):
+ assert not es.wait_for_green_indices.function("http://es:9200", ["image-new"])
+
+ es_conn.cluster.allocation_explain.assert_called_once_with(
+ index="image-new", shard=3, primary=False
+ )
+ assert "the node is above the high watermark" in caplog.text
+
+
+def test_wait_for_green_indices_survives_a_failed_explanation(monkeypatch):
+ es_conn = _unassigned_es_conn()
+ es_conn.cluster.allocation_explain.side_effect = ApiError(
+ "no unassigned shard", mock.Mock(status=400), {}
+ )
+ _hook(monkeypatch, es_conn)
+
+ assert not es.wait_for_green_indices.function("http://es:9200", ["image-new"])
diff --git a/catalog/tests/dags/data_refresh/test_alter_data.py b/catalog/tests/dags/data_refresh/test_alter_data.py
index 9c98c8675..8dba01507 100644
--- a/catalog/tests/dags/data_refresh/test_alter_data.py
+++ b/catalog/tests/dags/data_refresh/test_alter_data.py
@@ -1,16 +1,32 @@
import json
import logging
+from itertools import pairwise
+from types import SimpleNamespace
+from unittest import mock
import psycopg2
import pytest
from data_refresh.alter_data import (
- DEFAULT_BATCH_SIZE,
FILTERED_TAG_PROVIDERS,
- alter_data_batch,
- get_alter_batches,
+ alter_data_range,
+ get_alter_ranges,
+ get_batches,
+ get_progress_variable,
)
from tests.test_utils import sql
+from tests.test_utils.variable import FakeVariable
+
+
+PROGRESS_PREFIX = "test_alter_data_progress"
+PROGRESS_VARIABLE = get_progress_variable(PROGRESS_PREFIX, 0)
+
+
[email protected](autouse=True)
+def fake_variable():
+ FakeVariable.values = {}
+ with mock.patch("data_refresh.alter_data.Variable", FakeVariable):
+ yield FakeVariable
@pytest.fixture
@@ -46,9 +62,14 @@ def _tags_by_id(postgres, table) -> dict[int, object]:
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
+def _alter(table, id_range, batch_size=None):
+ return alter_data_range.function(
+ id_range=id_range,
+ batch_size=batch_size,
+ temp_table=table,
+ postgres_conn_id=sql.POSTGRES_CONN_ID,
+ progress_prefix=PROGRESS_PREFIX,
+ ti=SimpleNamespace(map_index=0),
)
@@ -150,7 +171,7 @@ def _alter(table, batch):
pytest.param({"name": "cc0"}, {"name": "cc0"}, id="non_array_tags"),
],
)
-def test_alter_data_batch_filters_tags(temp_table, tags, expected):
+def test_alter_data_range_filters_tags(temp_table, tags, expected):
postgres, table = temp_table
_insert(postgres, table, {1: tags})
@@ -160,7 +181,7 @@ def test_alter_data_batch_filters_tags(temp_table, tags, expected):
assert count == (0 if tags == expected else 1)
-def test_alter_data_batch_only_updates_rows_in_batch(temp_table):
+def test_alter_data_range_only_updates_rows_in_range(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})
@@ -171,7 +192,56 @@ 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):
[email protected]("batch_size", [1, 2, 10])
+def test_alter_data_range_updates_every_batch(temp_table, batch_size):
+ postgres, table = temp_table
+ bad, good = [{"name": "cc0"}, {"name": "cat"}], [{"name": "cat"}]
+ _insert(postgres, table, {_id: bad for _id in range(1, 6)})
+
+ count = _alter(table, (1, 5), batch_size)
+
+ assert count == 5
+ assert _tags_by_id(postgres, table) == {_id: good for _id in range(1, 6)}
+
+
+def test_alter_data_range_resumes_after_a_failed_batch(temp_table, fake_variable):
+ postgres, table = temp_table
+ bad, good = [{"name": "cc0"}, {"name": "cat"}], [{"name": "cat"}]
+ _insert(postgres, table, {_id: bad for _id in range(1, 6)})
+
+ real_set, calls = fake_variable.set, []
+
+ def fail_on_second_batch(*args, **kwargs):
+ real_set(*args, **kwargs)
+ calls.append(args)
+ if len(calls) == 2:
+ raise RuntimeError("The database went away")
+
+ with mock.patch.object(fake_variable, "set", fail_on_second_batch):
+ with pytest.raises(RuntimeError):
+ _alter(table, (1, 5), batch_size=2)
+
+ assert fake_variable.get(PROGRESS_VARIABLE, deserialize_json=True) == {
+ "next_start": 5,
+ "altered": 4,
+ }
+ # Make a committed row look unaltered, to show that the retry skips it
+ postgres.cursor.execute(
+ f"UPDATE {table} SET tags = %s WHERE id = 1", (json.dumps(bad),)
+ )
+ postgres.connection.commit()
+
+ count = _alter(table, (1, 5), batch_size=2)
+
+ assert count == 5
+ assert _tags_by_id(postgres, table) == {
+ 1: bad,
+ **{_id: good for _id in range(2, 6)},
+ }
+ assert PROGRESS_VARIABLE not in fake_variable.values
+
+
+def test_alter_data_range_logs_altered_identifiers(temp_table, caplog):
postgres, table = temp_table
_insert(postgres, table, {1: [{"name": "cc0"}], 2: [{"name": "cat"}]})
@@ -183,17 +253,48 @@ def test_alter_data_batch_logs_altered_identifiers(temp_table, caplog):
@pytest.mark.parametrize(
- "id_bounds, batch_size, expected",
+ "id_bounds, range_count, 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)]),
+ ((1, 100), 2, [(1, 50), (51, 100)]),
+ ((1, 101), 2, [(1, 51), (52, 101)]),
+ ((1, 10), 3, [(1, 4), (5, 8), (9, 10)]),
+ # Never more ranges than ids
+ ((7, 8), 8, [(7, 7), (8, 8)]),
+ ((7, 7), 8, [(7, 7)]),
# An empty table has no id bounds
- ((None, None), 50, []),
+ ((None, None), 8, []),
+ ],
+)
+def test_get_alter_ranges(id_bounds, range_count, expected):
+ assert (
+ get_alter_ranges.function(id_bounds, PROGRESS_PREFIX, range_count) == expected
+ )
+
+
+def test_get_alter_ranges_stays_under_map_length():
+ ranges = get_alter_ranges.function((1, 947_411_826), PROGRESS_PREFIX)
+
+ assert len(ranges) == 8
+ assert ranges[0][0] == 1
+ assert ranges[-1][1] == 947_411_826
+ assert all(end + 1 == start for (_, end), (start, _) in pairwise(ranges))
+
+
+def test_get_alter_ranges_drops_earlier_progress(fake_variable):
+ fake_variable.set(PROGRESS_VARIABLE, {"next_start": 50}, serialize_json=True)
+
+ get_alter_ranges.function((1, 100), PROGRESS_PREFIX)
+
+ assert fake_variable.values == {}
+
+
+ "id_range, batch_size, expected",
+ [
+ ((1, 100), 50, [(1, 50), (51, 100)]),
+ ((1, 101), 50, [(1, 50), (51, 100), (101, 101)]),
+ ((7, 7), 50, [(7, 7)]),
],
)
-def test_get_alter_batches(id_bounds, batch_size, expected):
- actual = get_alter_batches.function(id_bounds, batch_size)
- assert actual == expected
+def test_get_batches(id_range, batch_size, expected):
+ assert get_batches(id_range, batch_size) == expected
diff --git a/catalog/tests/dags/data_refresh/test_task_dependencies.py b/catalog/tests/dags/data_refresh/test_task_dependencies.py
index 72f592999..33e7dfe16 100644
--- a/catalog/tests/dags/data_refresh/test_task_dependencies.py
+++ b/catalog/tests/dags/data_refresh/test_task_dependencies.py
@@ -39,7 +39,7 @@ def _assert_dependencies(downstream_task_id: str, upstream_task_ids: list[str]):
def test_dependencies_alter_data_task():
_assert_dependencies(
- downstream_task_id="alter_table_data.alter_data_batch",
+ downstream_task_id="alter_table_data.alter_data_range",
upstream_task_ids=["copy_upstream_tables.copy_upstream_table.copy_data"],
)
@@ -49,7 +49,7 @@ def test_dependencies_reindex_task():
downstream_task_id="run_distributed_reindex.reindex.trigger_reindexing_task",
upstream_task_ids=[
"copy_upstream_tables.copy_upstream_table.copy_data",
- "alter_table_data.alter_data_batch",
+ "alter_table_data.alter_data_range",
"create_index",
],
)
@@ -71,6 +71,8 @@ def test_dependencies_promote_table_task():
upstream_task_ids=[
"run_distributed_reindex.reindex.assert_reindexing_success",
"create_and_populate_filtered_index.refresh_index",
+ "enable_replicas",
+ "wait_for_green_indices",
"promote_tables.promote_table.remap_table_indices_to_table.create_table_indices",
"promote_tables.promote_table.remap_table_constraints_to_table.apply_constraints_to_table",
],
@@ -95,3 +97,13 @@ def test_dependenceis_promote_filtered_index_task():
"promote_tables.promote_table.promote",
],
)
+
+
+def test_alarms_do_not_wait_for_replicas():
+ dag = DagBag().get_dag("staging_image_data_refresh")
+ upstream_tasks = dag.get_task(
+ "enable_sensitive_cloudwatch_alarms"
+ ).get_flat_relative_ids(upstream=True)
+
+ assert "create_and_populate_filtered_index.refresh_index" in upstream_tasks
+ assert "wait_for_green_indices" not in upstream_tasks
diff --git a/catalog/tests/dags/database/test_batched_update.py b/catalog/tests/dags/database/test_batched_update.py
index e8186f152..f3c44ad4f 100644
--- a/catalog/tests/dags/database/test_batched_update.py
+++ b/catalog/tests/dags/database/test_batched_update.py
@@ -1,12 +1,8 @@
-import json
import logging
from unittest import mock
import psycopg2
import pytest
-from airflow.sdk.definitions._internal.types import NOTSET
-from airflow.sdk.exceptions import AirflowRuntimeError, ErrorType
-from airflow.sdk.execution_time.comms import ErrorResponse, PutVariable
from common.storage import columns as col
from database.batched_update import constants
@@ -16,6 +12,7 @@ from database.batched_update.batched_update import (
update_batches,
)
from tests.test_utils import sql
+from tests.test_utils.variable import FakeVariable
logger = logging.getLogger(__name__)
@@ -31,40 +28,6 @@ NEW_TITLE = "new title"
LICENSE = "by"
-class FakeVariable:
- """
- Stand-in for `airflow.sdk.Variable`, whose `set` only works inside a running task.
-
- Like the real one, it stores values as strings, rejects non-string values unless
- `serialize_json` is set, and raises for a missing key without a default.
- """
-
- values: dict[str, str] = {}
-
- @classmethod
- def get(cls, key, default=NOTSET, deserialize_json=False):
- if key not in cls.values:
- if default is NOTSET:
- raise AirflowRuntimeError(
- ErrorResponse(error=ErrorType.VARIABLE_NOT_FOUND, detail={})
- )
- return default
- value = cls.values[key]
- return json.loads(value) if deserialize_json else value
-
- @classmethod
- def set(cls, key, value, description=None, serialize_json=False):
- if serialize_json:
- value = json.dumps(value)
- cls.values[key] = PutVariable(
- key=key, value=value, description=description
- ).value
-
- @classmethod
- def delete(cls, key):
- cls.values.pop(key, None)
-
-
@pytest.fixture(autouse=True)
def fake_variable():
FakeVariable.values = {}
diff --git a/catalog/tests/test_utils/variable.py b/catalog/tests/test_utils/variable.py
new file mode 100644
index 000000000..f8613bc11
--- /dev/null
+++ b/catalog/tests/test_utils/variable.py
@@ -0,0 +1,39 @@
+import json
+
+from airflow.sdk.definitions._internal.types import NOTSET
+from airflow.sdk.exceptions import AirflowRuntimeError, ErrorType
+from airflow.sdk.execution_time.comms import ErrorResponse, PutVariable
+
+
+class FakeVariable:
+ """
+ Stand-in for `airflow.sdk.Variable`, whose `set` only works inside a running task.
+
+ Like the real one, it stores values as strings, rejects non-string values unless
+ `serialize_json` is set, and raises for a missing key without a default.
+ """
+
+ values: dict[str, str] = {}
+
+ @classmethod
+ def get(cls, key, default=NOTSET, deserialize_json=False):
+ if key not in cls.values:
+ if default is NOTSET:
+ raise AirflowRuntimeError(
+ ErrorResponse(error=ErrorType.VARIABLE_NOT_FOUND, detail={})
+ )
+ return default
+ value = cls.values[key]
+ return json.loads(value) if deserialize_json else value
+
+ @classmethod
+ def set(cls, key, value, description=None, serialize_json=False):
+ if serialize_json:
+ value = json.dumps(value)
+ cls.values[key] = PutVariable(
+ key=key, value=value, description=description
+ ).value
+
+ @classmethod
+ def delete(cls, key):
+ cls.values.pop(key, None)
diff --git a/documentation/catalog/reference/DAGs.md b/documentation/catalog/reference/DAGs.md
index 4b5c0332e..03ac68b02 100644
--- a/documentation/catalog/reference/DAGs.md
+++ b/documentation/catalog/reference/DAGs.md
@@ -1351,6 +1351,8 @@ The data refresh has the following high level steps:
the configuration of the existing filtered index, and then reindex documents
into it from the new media index, applying appropriate filtering for sensitive
terms.
+- Enable Replicas: Give both new indices a replica of every shard, and wait for
+ the replicas to be allocated.
- Reapply Constraints: Recreate indices and constraints from the original API
tables on the new temp tables.
- Promote Table: Drop the old media table in the API and rename the temp table