You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "ashb (via GitHub)" <gi...@apache.org> on 2026/10/05 16:35:55 UTC

[PR] Introduce the (internal/db level) concept of "dynamic regions" for TIs [airflow]

ashb opened a new pull request, #74275:
URL: https://github.com/apache/airflow/pull/74275

   <!-- SPDX-License-Identifier: Apache-2.0
         https://www.apache.org/licenses/LICENSE-2.0 -->
   
   <!--
   Thank you for contributing!
   
   Please provide above a brief description of the changes made in this pull request.
   Write a good git commit message following this guide: https://chris.beams.io/posts/git-commit/
   
   Please make sure that your code changes are covered with tests.
   And in case of new features or big changes remember to adjust the documentation.
   
   For user-facing UI changes, please attach before/after screenshots (or a short
   screen recording) so reviewers can assess the visual impact.
   
   Feel free to ping (in general) for the review if you do not see reaction for a few days
   (72 Hours is the minimum reaction time you can expect from volunteers) - we sometimes miss notifications.
   
   In case of an existing issue, reference it using one of the following:
   
   * closes: #ISSUE
   * related: #ISSUE
   -->
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   <!--
   If generative AI tooling has been used in the process of authoring this PR, please
   change below checkbox to `[X]` followed by the name of the tool, uncomment the "Generated-by".
   -->
   
   - [ ] Yes (please specify the tool below)
   
   <!--
   Generated-by: [Tool Name] following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
   -->
   
   ---
   
   * Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information. Note: commit author/co-author name and email in commits become permanently public when merged.
   * For fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   * When adding dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   * For significant user-facing changes create newsfragment: `{pr_number}.significant.rst`, in [airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments). You can add this file in a follow-up commit after the PR is created so you know the PR number.


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce the (internal/db level) concept of "dynamic regions" for TIs [airflow]

Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #74275:
URL: https://github.com/apache/airflow/pull/74275#discussion_r4222208774


##########
airflow-core/docs/core-concepts/task-state-store.rst:
##########
@@ -30,7 +30,7 @@ Task State Store
 
 .. versionadded:: 3.3
 
-Task store is a persistent key/value store scoped to a single task instance (``dag_id`` + ``run_id`` + ``task_id`` + ``map_index``). It survives worker crashes and task retries within the same Dag run, making it suitable for storing external job IDs, intra-task checkpoints, and progress metadata.
+Task store is a persistent key/value store scoped to a single task instance (``dag_id`` + ``run_id`` + ``task_id`` + ``region_id`` + ``map_index``). It survives worker crashes and task retries within the same Dag run, making it suitable for storing external job IDs, intra-task checkpoints, and progress metadata.

Review Comment:
   `region_id` is now listed as part of the task scope, but none of the docs say what a region is or when it differs from the all-zero default. One sentence here would help, since someone with a custom backend reading this has to decide whether their existing refs are still unique.



##########
airflow-core/src/airflow/utils/sqlalchemy.py:
##########
@@ -291,6 +292,58 @@ def load_dialect_impl(self, dialect):
         return super().load_dialect_impl(dialect)
 
 
+_MYSQL_DIALECT_NAMES = ("mysql", "mariadb")
+
+
+class CompactUUID(TypeDecorator):
+    """
+    A UUID that MySQL stores as ``BINARY(16)``; other dialects use SQLAlchemy's :class:`~sqlalchemy.types.Uuid`.
+
+    The default MySQL form, ``CHAR(32)``, takes 128 bytes in an index key under a utf8mb4 collation.
+    Keys that already approach InnoDB's 3072-byte limit, such as those holding several ``StringID`` columns,
+    overflow with it.
+    """
+
+    impl = Uuid
+    cache_ok = True
+
+    def load_dialect_impl(self, dialect):
+        if dialect.name in _MYSQL_DIALECT_NAMES:
+            return dialect.type_descriptor(mysql.BINARY(16))
+        return dialect.type_descriptor(Uuid())
+
+    def process_bind_param(self, value, dialect):
+        if value is None or dialect.name not in _MYSQL_DIALECT_NAMES:
+            return value
+        return (UUID(value) if isinstance(value, str) else value).bytes
+
+    def process_result_value(self, value, dialect):
+        if value is None or dialect.name not in _MYSQL_DIALECT_NAMES:
+            return value
+        return UUID(bytes=bytes(value))
+
+
+class compact_uuid_default(ColumnElement):
+    """Server default for a :class:`CompactUUID` column, rendered in the form each dialect stores."""
+
+    inherit_cache = True
+    type = NullType()
+
+    def __init__(self, value: UUID):
+        self.value = value
+
+
+@compiles(compact_uuid_default)
+def _compact_uuid_default(element, compiler, **kw):
+    return compiler.render_literal_value(element.value.hex, String())
+
+
+@compiles(compact_uuid_default, "mysql")
+@compiles(compact_uuid_default, "mariadb")
+def _compact_uuid_default_mysql(element, compiler, **kw):
+    return f"UNHEX({compiler.render_literal_value(element.value.hex, String())})"

Review Comment:
   In offline mode (`airflow db migrate --show-sql-only`) SQLAlchemy has no server version, so it doesn't add the parentheses MySQL needs around an expression default. Compiling an `ADD COLUMN` with this default against a bare `mysql.dialect()` gives `NOT NULL DEFAULT UNHEX('000...0')`; only once `server_version_info` is set does it become `DEFAULT (UNHEX(...))`. MySQL rejects the unparenthesized form, so the generated script stops at the first `region_id` column after `dynamic_region` has already been created. A hex literal (`X'000...0'`) needs no parentheses, and `test_server_default_per_dialect` only compiles the bare expression, so a test that compiles the column DDL against a MySQL dialect with no server version would pin this.



##########
airflow-core/src/airflow/migrations/versions/0143_3_4_0_add_dynamic_region_storage.py:
##########
@@ -0,0 +1,215 @@
+# 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
+from uuid import UUID
+
+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 CompactUUID, UtcDateTime, compact_uuid_default
+
+revision = "54a27b6f9d01"
+down_revision = "e7c2a91bd540"
+branch_labels = None
+depends_on = None
+airflow_version = "3.4.0"
+
+_SENTINEL = UUID(int=0)
+_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():

Review Comment:
   On SQLite this `autocommit_block()` commits everything the migration has done so far (`dynamic_region`, its indexes and both `region_id` columns), and the batch rebuild then runs outside a transaction. If a later rebuild fails, the DB is left half-migrated and a rerun stops on `dynamic_region` already existing. `_sqlite_rebuilds()` in 0142 keeps only the PRAGMAs in autocommit and runs the rebuild under `begin_nested()`; could that move to `migrations/utils.py` and be reused here?



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce the (internal/db level) concept of "dynamic regions" for TIs [airflow]

Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #74275:
URL: https://github.com/apache/airflow/pull/74275#discussion_r4199240660


##########
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:
   Oh ugh i forgot all about that when designing this. 



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce the (internal/db level) concept of "dynamic regions" for TIs [airflow]

Posted by "kaxil (via GitHub)" <gi...@apache.org>.
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)
+
+
+@pytest.fixture(autouse=True)
+def clean_db():
+    clear_db_runs()
+    yield
+    clear_db_runs()
+
+
+@pytest.fixture
+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
+
+
+@pytest.fixture
+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")
+
+
+@pytest.mark.parametrize("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
+
+
+@pytest.mark.parametrize("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)
+
+
+@pytest.fixture(autouse=True)
+def clean_db():
+    clear_db_runs()
+    yield
+    clear_db_runs()
+
+
+@pytest.fixture
+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
+
+
+@pytest.fixture
+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")
+
+
+@pytest.mark.parametrize("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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce the (internal/db level) concept of "dynamic regions" for TIs [airflow]

Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #74275:
URL: https://github.com/apache/airflow/pull/74275#discussion_r4206033972


##########
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:
   Turns out there is _just_ enough space left on the task_state_store unique index for 16 bytes, so the documented-on-mysqls-site of storing uuid as BINARY(16) is the path I'm taking. And I'll create a custom SQLA data type called `CompactUUID` that is just uuid on sqlite and postgres.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Introduce the (internal/db level) concept of "dynamic regions" for TIs [airflow]

Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb merged PR #74275:
URL: https://github.com/apache/airflow/pull/74275


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org