kaxil commented on code in PR #74275: URL: https://github.com/apache/airflow/pull/74275#discussion_r4198199305
########## airflow-core/src/airflow/migrations/versions/0143_3_4_0_add_dynamic_region_storage.py: ########## @@ -0,0 +1,209 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Add dynamic region storage. + +Revision ID: 54a27b6f9d01 +Revises: e7c2a91bd540 +Create Date: 2026-09-27 20:00:00.000000 +""" + +from __future__ import annotations + +from textwrap import dedent + +import sqlalchemy as sa +from alembic import op + +from airflow.migrations.utils import raise_if_rows_exist +from airflow.models.base import StringID +from airflow.utils.sqlalchemy import UtcDateTime + +revision = "54a27b6f9d01" +down_revision = "e7c2a91bd540" +branch_labels = None +depends_on = None +airflow_version = "3.4.0" + +_SENTINEL = "00000000000000000000000000000000" +_KEYS = ( + ( + "task_instance", + "task_instance_current_key", + ("dag_id", "task_id", "run_id", "map_index", "working_set"), + "working_set IS NOT NULL", + ), + ( + "task_instance", + "task_instance_try_key", + ("dag_id", "task_id", "run_id", "map_index", "try_number"), + None, + ), + ("task_state_store", "task_state_store_uq", ("dag_run_id", "task_id", "map_index", "key"), None), +) + + +def _replace_unique(table_name, constraint_name, columns): + context = op.get_context() + dialect = context.dialect.name + if dialect in ("postgresql", "mysql"): + quote = context.dialect.identifier_preparer.quote + column_list = ", ".join(quote(name) for name in columns) + if dialect == "postgresql": + sql = f""" + ALTER TABLE {table_name} + DROP CONSTRAINT {constraint_name}, + ADD CONSTRAINT {constraint_name} UNIQUE ({column_list}) + """ + else: + sql = f""" + ALTER TABLE {table_name} + DROP INDEX {constraint_name}, + ADD UNIQUE KEY {constraint_name} ({column_list}) + """ + op.execute(dedent(sql)) + else: + with op.get_context().autocommit_block(): + foreign_keys = op.get_bind().exec_driver_sql("PRAGMA foreign_keys").scalar_one() + op.execute("PRAGMA foreign_keys=OFF") + try: + with op.batch_alter_table(table_name) as batch_op: + batch_op.drop_constraint(constraint_name, type_="unique") + batch_op.create_unique_constraint(constraint_name, columns) + finally: + op.execute(f"PRAGMA foreign_keys={foreign_keys}") + + +def _build_collision_query(table_name, columns, where): + """Select old-key groups holding more than one row, scanning only DagRuns that have regions.""" + table = sa.table(table_name, *(sa.column(name) for name in columns)) + region = sa.table("dynamic_region", sa.column("dag_id"), sa.column("run_id")) + if table_name == "task_state_store": + dag_run = sa.table("dag_run", sa.column("id"), sa.column("dag_id"), sa.column("run_id")) + has_region = ( + sa.select(1) + .select_from( + dag_run.join( + region, sa.and_(region.c.dag_id == dag_run.c.dag_id, region.c.run_id == dag_run.c.run_id) + ) + ) + .where(dag_run.c.id == table.c.dag_run_id) + .exists() + ) + else: + has_region = ( + sa.select(1) + .select_from(region) + .where(region.c.dag_id == table.c.dag_id, region.c.run_id == table.c.run_id) + .exists() + ) + query = sa.select(1).select_from(table).where(has_region) + if where: + query = query.where(sa.text(where)) + return query.group_by(*(table.c[name] for name in columns)).having(sa.func.count() > 1).limit(1) + + +def _assert_downgrade_is_lossless(): + """ + Abort the downgrade if dropping ``region_id`` would merge rows, before any DDL runs. + + MySQL DDL cannot be rolled back, so every check has to happen first. The SQL guard also works + in offline mode but does not support SQLite, which is checked by running the query directly. + The query scans the whole ``task_instance`` table, so expect it to be slow on very large installations. + """ + dialect = op.get_context().dialect + for table_name, _, columns, where in _KEYS: + query = _build_collision_query(table_name, columns, where) + message = ( + f"Cannot downgrade: {table_name} has region rows colliding on the old key. " + "Delete the affected DagRuns first." + ) + if dialect.name == "sqlite": + if op.get_bind().execute(query).scalar_one_or_none() is not None: + raise RuntimeError(message) + else: + sql = str(query.compile(dialect=dialect, compile_kwargs={"literal_binds": True})) + raise_if_rows_exist(sql, message, op) + + +def _configure_index_builds(): + if op.get_bind().dialect.name == "postgresql": + op.execute("SET LOCAL statement_timeout = 0") + op.execute("SET LOCAL maintenance_work_mem = '256MB'") + + +def upgrade(): + _configure_index_builds() + op.create_table( + "dynamic_region", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("dag_id", StringID(), nullable=False), + sa.Column("run_id", StringID(), nullable=False), + sa.Column("node_id", StringID(), nullable=False), + sa.Column("parent_region_id", sa.Uuid(), nullable=True), + sa.Column("parent_region_index", sa.Integer(), nullable=True), + sa.Column("forked_from_region_id", sa.Uuid(), nullable=True), + sa.Column("resumes_from_index", sa.Integer(), nullable=False, server_default="0"), + sa.Column("created_at", UtcDateTime(), nullable=False), + sa.PrimaryKeyConstraint("id", name="dynamic_region_pkey"), + sa.ForeignKeyConstraint( + ["dag_id", "run_id"], + ["dag_run.dag_id", "dag_run.run_id"], + name="dynamic_region_dag_run_fkey", + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["parent_region_id"], + ["dynamic_region.id"], + name="dynamic_region_parent_region_id_fkey", + ondelete="CASCADE", + ), + # Fork lineage is unbounded; a cascading self-FK would exceed MySQL's cascade depth limit. + sa.UniqueConstraint("forked_from_region_id", name="dynamic_region_forked_from_region_id_uq"), + sa.CheckConstraint( + "(parent_region_id IS NULL AND parent_region_index IS NULL) OR " + "(parent_region_id IS NOT NULL AND parent_region_index IS NOT NULL)", + name="parent_coordinates_paired", + ), + sa.CheckConstraint("resumes_from_index >= 0", name="resumes_from_index_nonnegative"), + ) + op.create_index( + "idx_dynamic_region_slot", + "dynamic_region", + ["dag_id", "run_id", "node_id", "parent_region_id", "parent_region_index"], + ) + op.create_index("idx_dynamic_region_parent_region_id", "dynamic_region", ["parent_region_id"]) + for table_name in ("task_instance", "task_state_store"): + op.add_column( + table_name, + sa.Column("region_id", sa.Uuid(), nullable=False, server_default=_SENTINEL), Review Comment: With the default `utf8mb3_bin` id collation these keys still fit on MySQL, but with `[database] sql_engine_collation_for_ids` set to a utf8mb4 collation, `task_instance_current_key` is about 3005 bytes today and `task_state_store_uq` about 3056. A `CHAR(32)` utf8mb4 `region_id` adds 128 bytes, which puts both over InnoDB's 3072-byte limit. By the time `ADD UNIQUE KEY` fails, `create_table` and the `add_column`s have already committed, so a rerun stops at the existing table. Could `region_id` use an ascii or binary variant on MySQL, or could the upgrade check the key width before any DDL? ########## airflow-core/src/airflow/migrations/versions/0143_3_4_0_add_dynamic_region_storage.py: ########## @@ -0,0 +1,209 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Add dynamic region storage. + +Revision ID: 54a27b6f9d01 +Revises: e7c2a91bd540 +Create Date: 2026-09-27 20:00:00.000000 +""" + +from __future__ import annotations + +from textwrap import dedent + +import sqlalchemy as sa +from alembic import op + +from airflow.migrations.utils import raise_if_rows_exist +from airflow.models.base import StringID +from airflow.utils.sqlalchemy import UtcDateTime + +revision = "54a27b6f9d01" +down_revision = "e7c2a91bd540" +branch_labels = None +depends_on = None +airflow_version = "3.4.0" + +_SENTINEL = "00000000000000000000000000000000" +_KEYS = ( + ( + "task_instance", + "task_instance_current_key", + ("dag_id", "task_id", "run_id", "map_index", "working_set"), + "working_set IS NOT NULL", + ), + ( + "task_instance", + "task_instance_try_key", + ("dag_id", "task_id", "run_id", "map_index", "try_number"), + None, + ), + ("task_state_store", "task_state_store_uq", ("dag_run_id", "task_id", "map_index", "key"), None), +) + + +def _replace_unique(table_name, constraint_name, columns): + context = op.get_context() + dialect = context.dialect.name + if dialect in ("postgresql", "mysql"): + quote = context.dialect.identifier_preparer.quote + column_list = ", ".join(quote(name) for name in columns) + if dialect == "postgresql": + sql = f""" + ALTER TABLE {table_name} + DROP CONSTRAINT {constraint_name}, + ADD CONSTRAINT {constraint_name} UNIQUE ({column_list}) + """ + else: + sql = f""" + ALTER TABLE {table_name} + DROP INDEX {constraint_name}, + ADD UNIQUE KEY {constraint_name} ({column_list}) + """ + op.execute(dedent(sql)) + else: + with op.get_context().autocommit_block(): + foreign_keys = op.get_bind().exec_driver_sql("PRAGMA foreign_keys").scalar_one() + op.execute("PRAGMA foreign_keys=OFF") + try: + with op.batch_alter_table(table_name) as batch_op: + batch_op.drop_constraint(constraint_name, type_="unique") + batch_op.create_unique_constraint(constraint_name, columns) + finally: + op.execute(f"PRAGMA foreign_keys={foreign_keys}") + + +def _build_collision_query(table_name, columns, where): + """Select old-key groups holding more than one row, scanning only DagRuns that have regions.""" + table = sa.table(table_name, *(sa.column(name) for name in columns)) + region = sa.table("dynamic_region", sa.column("dag_id"), sa.column("run_id")) + if table_name == "task_state_store": + dag_run = sa.table("dag_run", sa.column("id"), sa.column("dag_id"), sa.column("run_id")) + has_region = ( + sa.select(1) + .select_from( + dag_run.join( + region, sa.and_(region.c.dag_id == dag_run.c.dag_id, region.c.run_id == dag_run.c.run_id) + ) + ) + .where(dag_run.c.id == table.c.dag_run_id) + .exists() + ) + else: + has_region = ( + sa.select(1) + .select_from(region) + .where(region.c.dag_id == table.c.dag_id, region.c.run_id == table.c.run_id) + .exists() + ) + query = sa.select(1).select_from(table).where(has_region) + if where: + query = query.where(sa.text(where)) + return query.group_by(*(table.c[name] for name in columns)).having(sa.func.count() > 1).limit(1) + + +def _assert_downgrade_is_lossless(): + """ + Abort the downgrade if dropping ``region_id`` would merge rows, before any DDL runs. + + MySQL DDL cannot be rolled back, so every check has to happen first. The SQL guard also works + in offline mode but does not support SQLite, which is checked by running the query directly. + The query scans the whole ``task_instance`` table, so expect it to be slow on very large installations. + """ + dialect = op.get_context().dialect + for table_name, _, columns, where in _KEYS: + query = _build_collision_query(table_name, columns, where) + message = ( + f"Cannot downgrade: {table_name} has region rows colliding on the old key. " + "Delete the affected DagRuns first." + ) + if dialect.name == "sqlite": + if op.get_bind().execute(query).scalar_one_or_none() is not None: + raise RuntimeError(message) + else: + sql = str(query.compile(dialect=dialect, compile_kwargs={"literal_binds": True})) + raise_if_rows_exist(sql, message, op) + + +def _configure_index_builds(): + if op.get_bind().dialect.name == "postgresql": + op.execute("SET LOCAL statement_timeout = 0") + op.execute("SET LOCAL maintenance_work_mem = '256MB'") Review Comment: This also lowers `maintenance_work_mem` on instances that already run with more than 256MB (managed Postgres often sizes it from instance memory), so the two `task_instance` unique index rebuilds would sort in less memory on exactly the large installs this is meant to help. Could it only raise the value, e.g. `SELECT set_config('maintenance_work_mem', '256MB', true) WHERE (SELECT setting::bigint FROM pg_settings WHERE name = 'maintenance_work_mem') < 262144`? ########## airflow-core/src/airflow/migrations/versions/0143_3_4_0_add_dynamic_region_storage.py: ########## @@ -0,0 +1,209 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Add dynamic region storage. + +Revision ID: 54a27b6f9d01 +Revises: e7c2a91bd540 +Create Date: 2026-09-27 20:00:00.000000 +""" + +from __future__ import annotations + +from textwrap import dedent + +import sqlalchemy as sa +from alembic import op + +from airflow.migrations.utils import raise_if_rows_exist +from airflow.models.base import StringID +from airflow.utils.sqlalchemy import UtcDateTime + +revision = "54a27b6f9d01" +down_revision = "e7c2a91bd540" +branch_labels = None +depends_on = None +airflow_version = "3.4.0" + +_SENTINEL = "00000000000000000000000000000000" +_KEYS = ( + ( + "task_instance", + "task_instance_current_key", + ("dag_id", "task_id", "run_id", "map_index", "working_set"), + "working_set IS NOT NULL", + ), + ( + "task_instance", + "task_instance_try_key", + ("dag_id", "task_id", "run_id", "map_index", "try_number"), + None, + ), + ("task_state_store", "task_state_store_uq", ("dag_run_id", "task_id", "map_index", "key"), None), +) + + +def _replace_unique(table_name, constraint_name, columns): + context = op.get_context() + dialect = context.dialect.name + if dialect in ("postgresql", "mysql"): + quote = context.dialect.identifier_preparer.quote + column_list = ", ".join(quote(name) for name in columns) + if dialect == "postgresql": + sql = f""" + ALTER TABLE {table_name} + DROP CONSTRAINT {constraint_name}, + ADD CONSTRAINT {constraint_name} UNIQUE ({column_list}) + """ + else: + sql = f""" + ALTER TABLE {table_name} + DROP INDEX {constraint_name}, + ADD UNIQUE KEY {constraint_name} ({column_list}) + """ + op.execute(dedent(sql)) + else: + with op.get_context().autocommit_block(): + foreign_keys = op.get_bind().exec_driver_sql("PRAGMA foreign_keys").scalar_one() + op.execute("PRAGMA foreign_keys=OFF") + try: + with op.batch_alter_table(table_name) as batch_op: + batch_op.drop_constraint(constraint_name, type_="unique") + batch_op.create_unique_constraint(constraint_name, columns) + finally: + op.execute(f"PRAGMA foreign_keys={foreign_keys}") + + +def _build_collision_query(table_name, columns, where): + """Select old-key groups holding more than one row, scanning only DagRuns that have regions.""" + table = sa.table(table_name, *(sa.column(name) for name in columns)) + region = sa.table("dynamic_region", sa.column("dag_id"), sa.column("run_id")) + if table_name == "task_state_store": + dag_run = sa.table("dag_run", sa.column("id"), sa.column("dag_id"), sa.column("run_id")) + has_region = ( + sa.select(1) + .select_from( + dag_run.join( + region, sa.and_(region.c.dag_id == dag_run.c.dag_id, region.c.run_id == dag_run.c.run_id) + ) + ) + .where(dag_run.c.id == table.c.dag_run_id) + .exists() + ) + else: + has_region = ( + sa.select(1) + .select_from(region) + .where(region.c.dag_id == table.c.dag_id, region.c.run_id == table.c.run_id) + .exists() + ) + query = sa.select(1).select_from(table).where(has_region) + if where: + query = query.where(sa.text(where)) + return query.group_by(*(table.c[name] for name in columns)).having(sa.func.count() > 1).limit(1) + + +def _assert_downgrade_is_lossless(): + """ + Abort the downgrade if dropping ``region_id`` would merge rows, before any DDL runs. + + MySQL DDL cannot be rolled back, so every check has to happen first. The SQL guard also works + in offline mode but does not support SQLite, which is checked by running the query directly. + The query scans the whole ``task_instance`` table, so expect it to be slow on very large installations. + """ + dialect = op.get_context().dialect + for table_name, _, columns, where in _KEYS: + query = _build_collision_query(table_name, columns, where) + message = ( + f"Cannot downgrade: {table_name} has region rows colliding on the old key. " + "Delete the affected DagRuns first." + ) + if dialect.name == "sqlite": + if op.get_bind().execute(query).scalar_one_or_none() is not None: + raise RuntimeError(message) + else: + sql = str(query.compile(dialect=dialect, compile_kwargs={"literal_binds": True})) + raise_if_rows_exist(sql, message, op) + + +def _configure_index_builds(): + if op.get_bind().dialect.name == "postgresql": + op.execute("SET LOCAL statement_timeout = 0") + op.execute("SET LOCAL maintenance_work_mem = '256MB'") + + +def upgrade(): + _configure_index_builds() + op.create_table( + "dynamic_region", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("dag_id", StringID(), nullable=False), + sa.Column("run_id", StringID(), nullable=False), + sa.Column("node_id", StringID(), nullable=False), + sa.Column("parent_region_id", sa.Uuid(), nullable=True), + sa.Column("parent_region_index", sa.Integer(), nullable=True), + sa.Column("forked_from_region_id", sa.Uuid(), nullable=True), + sa.Column("resumes_from_index", sa.Integer(), nullable=False, server_default="0"), + sa.Column("created_at", UtcDateTime(), nullable=False), + sa.PrimaryKeyConstraint("id", name="dynamic_region_pkey"), + sa.ForeignKeyConstraint( + ["dag_id", "run_id"], + ["dag_run.dag_id", "dag_run.run_id"], + name="dynamic_region_dag_run_fkey", + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["parent_region_id"], + ["dynamic_region.id"], + name="dynamic_region_parent_region_id_fkey", + ondelete="CASCADE", + ), + # Fork lineage is unbounded; a cascading self-FK would exceed MySQL's cascade depth limit. + sa.UniqueConstraint("forked_from_region_id", name="dynamic_region_forked_from_region_id_uq"), + sa.CheckConstraint( + "(parent_region_id IS NULL AND parent_region_index IS NULL) OR " + "(parent_region_id IS NOT NULL AND parent_region_index IS NOT NULL)", + name="parent_coordinates_paired", + ), + sa.CheckConstraint("resumes_from_index >= 0", name="resumes_from_index_nonnegative"), + ) + op.create_index( + "idx_dynamic_region_slot", + "dynamic_region", + ["dag_id", "run_id", "node_id", "parent_region_id", "parent_region_index"], + ) + op.create_index("idx_dynamic_region_parent_region_id", "dynamic_region", ["parent_region_id"]) + for table_name in ("task_instance", "task_state_store"): + op.add_column( + table_name, + sa.Column("region_id", sa.Uuid(), nullable=False, server_default=_SENTINEL), + ) + for table_name, constraint_name, columns, _ in _KEYS: + new_columns = list(columns) + new_columns.insert(new_columns.index("map_index"), "region_id") + _replace_unique(table_name, constraint_name, new_columns) + + +def downgrade(): + _assert_downgrade_is_lossless() + _configure_index_builds() Review Comment: The collision check is the slowest statement in this downgrade (the docstring says as much), but it runs before `_configure_index_builds()` lifts `statement_timeout`. On a Postgres role or connection with a timeout configured, `airflow db downgrade` would fail with a statement-timeout error from the guard rather than a real collision. `SET LOCAL` isn't DDL and is a no-op on MySQL, so swapping the two keeps the check ahead of every schema change. ```suggestion _configure_index_builds() _assert_downgrade_is_lossless() ``` ########## airflow-core/tests/unit/models/test_taskinstance.py: ########## @@ -2615,6 +2615,7 @@ def test_refresh_from_db(self, create_task_instance): "task_id": "test_refresh_from_db_task", "dag_id": "test_refresh_from_db_dag", "run_id": "test", + "region_id": uuid6.UUID(int=0), Review Comment: `UUID(int=0)` is also what a fresh `TI(...)` gets by default, so this round trip passes whether or not `refresh_from_db` loads `region_id`. A non-default value would make it bind: ```suggestion "region_id": uuid6.uuid7(), ``` ########## airflow-core/tests/unit/migrations/test_0143_add_dynamic_region_storage.py: ########## @@ -0,0 +1,142 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +from contextlib import nullcontext +from importlib import import_module +from uuid import UUID, uuid4 + +import pytest +from alembic.migration import MigrationContext +from alembic.operations import Operations +from sqlalchemy import inspect, select +from sqlalchemy.exc import DBAPIError + +from airflow._shared.timezones import timezone +from airflow.models.dagrun import DagRun +from airflow.models.dynamic_region import DynamicRegion +from airflow.models.task_state_store import TaskStateStoreModel +from airflow.models.taskinstance import TaskInstance +from airflow.providers.standard.operators.empty import EmptyOperator + +from tests_common.test_utils.db import clear_db_runs + +pytestmark = pytest.mark.db_test + +_migration = import_module("airflow.migrations.versions.0143_3_4_0_add_dynamic_region_storage") +MODELS = (TaskInstance, TaskStateStoreModel) + + [email protected](autouse=True) +def clean_db(): + clear_db_runs() + yield + clear_db_runs() + + [email protected] +def stored_rows(dag_maker, session): + with dag_maker(serialized=True): + EmptyOperator(task_id="task") + dr = dag_maker.create_dagrun() + ti = dr.task_instances[0] + session.add( + TaskStateStoreModel( + dag_run_id=dr.id, + dag_id=ti.dag_id, + run_id=ti.run_id, + task_id=ti.task_id, + map_index=-1, + key="state", + value="value", + ) + ) + session.flush() + return ti + + [email protected] +def migration_connection(stored_rows, session): + session.commit() + with session.get_bind().connect() as connection: + try: + yield connection + finally: + if connection.dialect.name == "sqlite": + connection.rollback() + connection.exec_driver_sql("PRAGMA foreign_keys=ON") + + [email protected]("sqlite_foreign_keys", [True, False]) +def test_downgrade_then_upgrade_keeps_existing_rows_in_the_sentinel_region( + stored_rows, session, migration_connection, sqlite_foreign_keys +): + connection = migration_connection + if not sqlite_foreign_keys and connection.dialect.name != "sqlite": + pytest.skip("SQLite foreign-key setting") + context = MigrationContext.configure(connection, opts={"transaction_per_migration": True}) + with Operations.context(context), context.begin_transaction(_per_migration=True): + if connection.dialect.name == "sqlite": + connection.exec_driver_sql(f"PRAGMA foreign_keys={int(sqlite_foreign_keys)}") + _migration.downgrade() + _migration.upgrade() + if connection.dialect.name == "sqlite": + assert connection.exec_driver_sql("PRAGMA foreign_keys").scalar_one() == sqlite_foreign_keys + session.expire_all() + for model in MODELS: + row = session.scalars(select(model)).one() + assert row.region_id == UUID(int=0) + assert row.map_index == -1 + + [email protected]("model", MODELS) +def test_downgrade_refuses_each_old_coordinate_collision_before_ddl(stored_rows, session, model): Review Comment: The two guard tests either have no region rows at all or a full duplicate on the old key, so nothing checks that the guard lets a lossless downgrade through. If the `working_set IS NOT NULL` filter on `task_instance_current_key` were dropped, two retired attempts in different regions (both `working_set` NULL, different `try_number`) would group together and the downgrade would be refused, and this suite would still pass. Could you add a case with region rows that differ from the sentinel rows on an old-key column and assert the downgrade/upgrade round trip succeeds? ########## airflow-core/tests/unit/migrations/test_0143_add_dynamic_region_storage.py: ########## @@ -0,0 +1,142 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +from contextlib import nullcontext +from importlib import import_module +from uuid import UUID, uuid4 + +import pytest +from alembic.migration import MigrationContext +from alembic.operations import Operations +from sqlalchemy import inspect, select +from sqlalchemy.exc import DBAPIError + +from airflow._shared.timezones import timezone +from airflow.models.dagrun import DagRun +from airflow.models.dynamic_region import DynamicRegion +from airflow.models.task_state_store import TaskStateStoreModel +from airflow.models.taskinstance import TaskInstance +from airflow.providers.standard.operators.empty import EmptyOperator + +from tests_common.test_utils.db import clear_db_runs + +pytestmark = pytest.mark.db_test + +_migration = import_module("airflow.migrations.versions.0143_3_4_0_add_dynamic_region_storage") +MODELS = (TaskInstance, TaskStateStoreModel) + + [email protected](autouse=True) +def clean_db(): + clear_db_runs() + yield + clear_db_runs() + + [email protected] +def stored_rows(dag_maker, session): + with dag_maker(serialized=True): + EmptyOperator(task_id="task") + dr = dag_maker.create_dagrun() + ti = dr.task_instances[0] + session.add( + TaskStateStoreModel( + dag_run_id=dr.id, + dag_id=ti.dag_id, + run_id=ti.run_id, + task_id=ti.task_id, + map_index=-1, + key="state", + value="value", + ) + ) + session.flush() + return ti + + [email protected] +def migration_connection(stored_rows, session): + session.commit() + with session.get_bind().connect() as connection: + try: + yield connection + finally: + if connection.dialect.name == "sqlite": + connection.rollback() + connection.exec_driver_sql("PRAGMA foreign_keys=ON") + + [email protected]("sqlite_foreign_keys", [True, False]) +def test_downgrade_then_upgrade_keeps_existing_rows_in_the_sentinel_region( + stored_rows, session, migration_connection, sqlite_foreign_keys +): + connection = migration_connection + if not sqlite_foreign_keys and connection.dialect.name != "sqlite": + pytest.skip("SQLite foreign-key setting") Review Comment: On PostgreSQL and MySQL the `[False]` case always skips and `[True]` ignores the parameter, so those jobs report a skipped test for a SQLite-only setting. `pytest.param(False, marks=pytest.mark.backend("sqlite"))` would keep it out of the other backends. `stored_rows` also isn't used in the body, since `migration_connection` already pulls it in. ########## shared/state/src/airflow_shared/state/__init__.py: ########## @@ -37,13 +38,19 @@ class TaskScope: ``map_index`` defaults to ``-1`` for non-mapped tasks. For mapped tasks, set it to the actual mapped index. ``get``/``set``/``delete`` always match - on ``(dag_id, run_id, task_id, map_index)`` exactly. + on ``(dag_id, run_id, task_id, region_id, map_index)`` exactly. The zero + region UUID preserves the namespace of legacy callers. """ dag_id: str run_id: str task_id: str map_index: int = -1 + region_id: UUID = UUID(int=0) Review Comment: Now that `region_id` is part of the task scope identity, the custom-backend skeleton in `task-and-asset-state-store.rst` still builds refs from `{dag_id}/{run_id}/{task_id}/{map_index}/{key}`, and the common.io `state_store_objectstorage_path` description (provider.yaml, `get_provider_info.py`, `state_store_backend.rst`) still shows the 4-part layout without the new `region=<uuid>/` segment. A backend written from that skeleton would let two regions with the same task and index overwrite each other's objects. Worth updating those docs in this change? ########## airflow-core/src/airflow/models/task_state_store.py: ########## @@ -43,6 +44,10 @@ class TaskStateStoreModel(Base): dag_run_id: Mapped[int] = mapped_column(Integer, nullable=False) task_id: Mapped[str] = mapped_column(StringID(), nullable=False) map_index: Mapped[int] = mapped_column(Integer, nullable=False, server_default="-1") + region_index = synonym("map_index") + region_id: Mapped[UUID] = mapped_column( + Uuid(), nullable=False, default=UUID(int=0), server_default="00000000000000000000000000000000" + ) Review Comment: Small one: `TaskInstance.region_id` uses `SENTINEL_REGION_ID` and `SENTINEL_REGION_ID.hex`, while this column repeats `UUID(int=0)` and the 32-zero literal. `airflow.models.dynamic_region` only imports base, timezone and `utils.sqlalchemy`, so importing the constant here shouldn't create a cycle. ########## airflow-core/src/airflow/models/taskinstance.py: ########## @@ -2364,13 +2409,22 @@ def _get_num_task_instances_of_state( @staticmethod def filter_for_tis(tis: Iterable[TaskInstance | TaskInstanceKey]) -> ColumnElement[bool] | None: """Return SQLAlchemy filter to query selected task instances.""" - # DictKeys type, (what we often pass here from the scheduler) is not directly indexable :( - # Or it might be a generator, but we need to be able to iterate over it more than once - tis = list(tis) - - if not tis: + by_region: dict[UUID, list[TaskInstance | TaskInstanceKey]] = defaultdict(list) + for ti in tis: + by_region[SENTINEL_REGION_ID if isinstance(ti, TaskInstanceKey) else ti.region_id].append(ti) + if not by_region: return None + return or_( + *( + and_(TaskInstance.region_id == region_id, TaskInstance._filter_for_tis(group)) + for region_id, group in by_region.items() + ) + ) + @staticmethod + def _filter_for_tis(tis: list[TaskInstance | TaskInstanceKey]) -> ColumnElement[bool]: + # DictKeys type, (what we often pass here from the scheduler) is not directly indexable :( + # Or it might be a generator, but we need to be able to iterate over it more than once Review Comment: This comment explained the `tis = list(tis)` removed above. `_filter_for_tis` only ever gets the lists that `filter_for_tis` builds, so I'd drop it here, or move a reworded note above the grouping loop, which is now what consumes the iterable once. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
