Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AIP-83 Logical date should be required field when triggering run via API #46390

Merged
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
d0e22ad
restore unique constraint on logical date and make it nullable
vatsrahul1001 Jan 29, 2025
2b11aed
restore unique constraint on logical date and make it nullable
vatsrahul1001 Jan 29, 2025
237360d
fix migration file
vatsrahul1001 Jan 29, 2025
6f423c1
Merge branch 'main' into restore-unique-constraint-logical-date
vatsrahul1001 Jan 29, 2025
18efafb
fix migration file
vatsrahul1001 Jan 29, 2025
8f9e076
Merge branch 'restore-unique-constraint-logical-date' of github.com:a…
vatsrahul1001 Jan 29, 2025
1c47c75
Merge branch 'main' into restore-unique-constraint-logical-date
vatsrahul1001 Jan 29, 2025
d3bfe20
Merge branch 'main' of github.com:astronomer/airflow into restore-uni…
vatsrahul1001 Jan 30, 2025
0fa2477
Merge branch 'restore-unique-constraint-logical-date' of github.com:a…
vatsrahul1001 Jan 30, 2025
75a684a
fixing tests
vatsrahul1001 Jan 30, 2025
cefc9a3
refactor backfill reprocess logic
vatsrahul1001 Jan 30, 2025
8f84606
fixing tests
vatsrahul1001 Jan 30, 2025
f239846
Merge branch 'main' into refactor-backfill-reprocess-logic
vatsrahul1001 Jan 30, 2025
322b25c
fix tests
vatsrahul1001 Feb 1, 2025
0c24eff
fix tests
vatsrahul1001 Feb 1, 2025
f74c84b
Merge branch 'main' into refactor-backfill-reprocess-logic
vatsrahul1001 Feb 1, 2025
53d329b
resolve conflict
vatsrahul1001 Feb 3, 2025
c3e29c7
remove default date from logical date in dag run model
vatsrahul1001 Feb 3, 2025
0830d58
Merge branch 'main' of github.com:astronomer/airflow into restore-uni…
vatsrahul1001 Feb 3, 2025
2b4251d
fix task_filter
vatsrahul1001 Feb 3, 2025
3ec1ecd
merge main
vatsrahul1001 Feb 3, 2025
c05c19e
Merge branch 'restore-unique-constraint-logical-date' of github.com:a…
vatsrahul1001 Feb 3, 2025
4b223d8
Merge branch 'refactor-backfill-reprocess-logic' of github.com:astron…
vatsrahul1001 Feb 3, 2025
16cdaa1
Merge branch 'main' into refactor-backfill-reprocess-logic
vatsrahul1001 Feb 3, 2025
a4bc83d
Merge branch 'main' into refactor-backfill-reprocess-logic
vatsrahul1001 Feb 3, 2025
90595d6
fix failing tests
vatsrahul1001 Feb 3, 2025
8b654b5
Merge branch 'main' into refactor-backfill-reprocess-logic
vatsrahul1001 Feb 3, 2025
fd4c069
make logical date as required field
vatsrahul1001 Feb 3, 2025
78f8f43
refactor
vatsrahul1001 Feb 3, 2025
7dd4320
Merge branch 'main' into make-logical-date-as-required-field-to-trigg…
vatsrahul1001 Feb 3, 2025
54bbbe5
Merge branch 'main' of github.com:astronomer/airflow into make-logica…
vatsrahul1001 Feb 6, 2025
fab917d
Merge branch 'make-logical-date-as-required-field-to-trigger-dag-api'…
vatsrahul1001 Feb 7, 2025
15dfbf9
Merge branch 'main' of github.com:astronomer/airflow into make-logica…
vatsrahul1001 Feb 7, 2025
c8b8577
remove backfill related changes
vatsrahul1001 Feb 7, 2025
5467412
implement review comments
vatsrahul1001 Feb 7, 2025
d521d4d
add time now to var
vatsrahul1001 Feb 7, 2025
3da8eae
Merge branch 'main' into make-logical-date-as-required-field-to-trigg…
vatsrahul1001 Feb 7, 2025
afc7383
fix tests
vatsrahul1001 Feb 7, 2025
a8bd93a
Merge branch 'make-logical-date-as-required-field-to-trigger-dag-api'…
vatsrahul1001 Feb 7, 2025
92d4c00
Merge branch 'main' into make-logical-date-as-required-field-to-trigg…
vatsrahul1001 Feb 7, 2025
590b55d
Merge branch 'main' into make-logical-date-as-required-field-to-trigg…
vatsrahul1001 Feb 10, 2025
b91f3fa
fix review comments
vatsrahul1001 Feb 10, 2025
8ce5073
Merge branch 'main' into make-logical-date-as-required-field-to-trigg…
vatsrahul1001 Feb 10, 2025
ccb7ed1
Update tests/api_fastapi/core_api/routes/public/test_dag_run.py
vatsrahul1001 Feb 10, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 6 additions & 9 deletions airflow/api_fastapi/core_api/datamodels/dag_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
from datetime import datetime
from enum import Enum

from pydantic import AwareDatetime, Field, NonNegativeInt, computed_field, model_validator
import pendulum
from pydantic import AwareDatetime, Field, NonNegativeInt, model_validator

from airflow.api_fastapi.core_api.base import BaseModel, StrictBaseModel
from airflow.models import DagRun
from airflow.utils import timezone
from airflow.utils.state import DagRunState
from airflow.utils.types import DagRunTriggeredByType, DagRunType

Expand Down Expand Up @@ -82,6 +82,7 @@ class TriggerDAGRunPostBody(StrictBaseModel):
"""Trigger DAG Run Serializer for POST body."""

dag_run_id: str | None = None
logical_date: AwareDatetime | None
data_interval_start: AwareDatetime | None = None
data_interval_end: AwareDatetime | None = None

Expand All @@ -99,15 +100,11 @@ def check_data_intervals(cls, values):
@model_validator(mode="after")
def validate_dag_run_id(self):
if not self.dag_run_id:
self.dag_run_id = DagRun.generate_run_id(DagRunType.MANUAL, self.logical_date)
self.dag_run_id = DagRun.generate_run_id(
DagRunType.MANUAL, self.logical_date if self.logical_date is not None else pendulum.now("UTC")
Lee-W marked this conversation as resolved.
Show resolved Hide resolved
)
uranusjr marked this conversation as resolved.
Show resolved Hide resolved
return self

# Mypy issue https://github.com/python/mypy/issues/1362
@computed_field # type: ignore[misc]
@property
def logical_date(self) -> datetime:
return timezone.utcnow()


class DAGRunsBatchBody(StrictBaseModel):
"""List DAG Runs body for batch endpoint."""
Expand Down
8 changes: 8 additions & 0 deletions airflow/api_fastapi/core_api/openapi/v1-generated.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10291,6 +10291,12 @@ components:
- type: string
- type: 'null'
title: Dag Run Id
logical_date:
anyOf:
- type: string
format: date-time
- type: 'null'
title: Logical Date
data_interval_start:
anyOf:
- type: string
Expand All @@ -10313,6 +10319,8 @@ components:
title: Note
additionalProperties: false
type: object
required:
- logical_date
title: TriggerDAGRunPostBody
description: Trigger DAG Run Serializer for POST body.
TriggerResponse:
Expand Down
17 changes: 10 additions & 7 deletions airflow/api_fastapi/core_api/routes/public/dag_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ def trigger_dag_run(
f"DAG with dag_id: '{dag_id}' has import errors and cannot be triggered",
)

logical_date = pendulum.instance(body.logical_date)
logical_date = pendulum.instance(body.logical_date) if body.logical_date is not None else None
vatsrahul1001 marked this conversation as resolved.
Show resolved Hide resolved

try:
dag: DAG = request.app.state.dag_bag.get_dag(dag_id)
Expand All @@ -362,16 +362,19 @@ def trigger_dag_run(
end=pendulum.instance(body.data_interval_end),
)
else:
data_interval = dag.timetable.infer_manual_data_interval(run_after=logical_date)
data_interval = dag.timetable.infer_manual_data_interval(
run_after=logical_date or pendulum.now("UTC")
vatsrahul1001 marked this conversation as resolved.
Show resolved Hide resolved
)

if body.dag_run_id:
run_id = body.dag_run_id
else:
run_id = dag.timetable.generate_run_id(
run_id = (
body.dag_run_id
if body.dag_run_id
else dag.timetable.generate_run_id(
vatsrahul1001 marked this conversation as resolved.
Show resolved Hide resolved
run_type=DagRunType.MANUAL,
logical_date=logical_date,
logical_date=logical_date or pendulum.now("UTC"),
data_interval=data_interval,
)
)

dag_run = dag.create_dagrun(
run_id=run_id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
# under the License.

"""
Drop ``execution_date`` unique constraint on DagRun.
Make logical_date nullable.
vatsrahul1001 marked this conversation as resolved.
Show resolved Hide resolved

The column has also been renamed to logical_date, although the Python model is
The column has been renamed to logical_date, although the Python model is
not changed. This allows us to not need to fix all the Python code at once, but
still do the two changes in one migration instead of two.

Expand Down Expand Up @@ -49,10 +49,15 @@ def upgrade():
"execution_date",
new_column_name="logical_date",
existing_type=TIMESTAMP(timezone=True),
existing_nullable=False,
existing_nullable=True,
)

with op.batch_alter_table("dag_run", schema=None) as batch_op:
batch_op.drop_constraint("dag_run_dag_id_execution_date_key", type_="unique")
batch_op.create_unique_constraint(
"dag_run_dag_id_logical_date_key",
columns=["dag_id", "logical_date"],
)


def downgrade():
Expand All @@ -63,7 +68,9 @@ def downgrade():
existing_type=TIMESTAMP(timezone=True),
existing_nullable=False,
)

with op.batch_alter_table("dag_run", schema=None) as batch_op:
batch_op.drop_constraint("dag_run_dag_id_logical_date_key", type_="unique")
batch_op.create_unique_constraint(
"dag_run_dag_id_execution_date_key",
columns=["dag_id", "execution_date"],
Expand Down
26 changes: 24 additions & 2 deletions airflow/models/backfill.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#
# 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
Expand Down Expand Up @@ -141,6 +140,7 @@ class BackfillDagRunExceptionReason(str, Enum):
IN_FLIGHT = "in flight"
ALREADY_EXISTS = "already exists"
UNKNOWN = "unknown"
CLEARED_RUN = "cleared existing run"

vatsrahul1001 marked this conversation as resolved.
Show resolved Hide resolved

class BackfillDagRun(Base):
Expand Down Expand Up @@ -194,7 +194,11 @@ def _get_latest_dag_run_row_query(info, session):
def _get_dag_run_no_create_reason(dr, reprocess_behavior: ReprocessBehavior) -> str | None:
non_create_reason = None
if dr.state not in (DagRunState.SUCCESS, DagRunState.FAILED):
non_create_reason = BackfillDagRunExceptionReason.IN_FLIGHT
if dr.clear_number == 0:
non_create_reason = BackfillDagRunExceptionReason.IN_FLIGHT
else:
non_create_reason = BackfillDagRunExceptionReason.CLEARED_RUN

elif reprocess_behavior is ReprocessBehavior.NONE:
non_create_reason = BackfillDagRunExceptionReason.ALREADY_EXISTS
elif reprocess_behavior is ReprocessBehavior.FAILED:
Expand Down Expand Up @@ -262,7 +266,23 @@ def _create_backfill_dag_run(
dag_run_conf,
backfill_sort_ordinal,
session,
from_date,
to_date,
):
from airflow.models import DAG

vatsrahul1001 marked this conversation as resolved.
Show resolved Hide resolved
dr = session.scalar(_get_latest_dag_run_row_query(info, session))
if (
dr
and dr.state not in {DagRunState.RUNNING}
and reprocess_behavior in {ReprocessBehavior.COMPLETED, ReprocessBehavior.FAILED}
):
DAG.clear_dags(
[dag],
start_date=from_date,
end_date=to_date,
dag_run_state=DagRunState.QUEUED,
)
with session.begin_nested() as nested:
dr = session.scalar(
with_row_locks(
Expand Down Expand Up @@ -412,6 +432,8 @@ def _create_backfill(
reprocess_behavior=br.reprocess_behavior,
backfill_sort_ordinal=backfill_sort_ordinal,
session=session,
from_date=from_date,
to_date=to_date,
)
log.info(
"created backfill dag run dag_id=%s backfill_id=%s, info=%s",
Expand Down
5 changes: 3 additions & 2 deletions airflow/models/dag.py
Original file line number Diff line number Diff line change
Expand Up @@ -1722,7 +1722,7 @@ def create_dagrun(
self,
*,
run_id: str,
logical_date: datetime,
logical_date: datetime | None,
data_interval: tuple[datetime, datetime],
run_after: datetime,
conf: dict | None = None,
Expand All @@ -1747,7 +1747,8 @@ def create_dagrun(

:meta private:
"""
logical_date = timezone.coerce_datetime(logical_date)
if logical_date is not None:
logical_date = timezone.coerce_datetime(logical_date)
vatsrahul1001 marked this conversation as resolved.
Show resolved Hide resolved

if data_interval and not isinstance(data_interval, DataInterval):
data_interval = DataInterval(*map(timezone.coerce_datetime, data_interval))
Expand Down
11 changes: 8 additions & 3 deletions airflow/models/dagrun.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ class DagRun(Base, LoggingMixin):
id = Column(Integer, primary_key=True)
dag_id = Column(StringID(), nullable=False)
queued_at = Column(UtcDateTime)
logical_date = Column(UtcDateTime, default=timezone.utcnow, nullable=False)
logical_date = Column(UtcDateTime, nullable=True)
start_date = Column(UtcDateTime)
end_date = Column(UtcDateTime)
_state = Column("state", String(50), default=DagRunState.QUEUED)
Expand Down Expand Up @@ -186,6 +186,7 @@ class DagRun(Base, LoggingMixin):
__table_args__ = (
Index("dag_id_state", dag_id, _state),
UniqueConstraint("dag_id", "run_id", name="dag_run_dag_id_run_id_key"),
UniqueConstraint("dag_id", "logical_date", name="dag_run_dag_id_logical_date_key"),
Index("idx_dag_run_dag_id", dag_id),
Index("idx_dag_run_run_after", run_after),
Index(
Expand Down Expand Up @@ -1315,8 +1316,12 @@ def verify_integrity(self, *, session: Session = NEW_SESSION) -> None:
def task_filter(task: Operator) -> bool:
return task.task_id not in task_ids and (
self.run_type == DagRunType.BACKFILL_JOB
or (task.start_date is None or task.start_date <= self.logical_date)
and (task.end_date is None or self.logical_date <= task.end_date)
or (
task.start_date is None
or self.logical_date is None
or task.start_date <= self.logical_date
)
and (task.end_date is None or self.logical_date is None or self.logical_date <= task.end_date)
)

created_counts: dict[str, int] = defaultdict(int)
Expand Down
13 changes: 13 additions & 0 deletions airflow/ui/openapi-gen/requests/schemas.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5752,6 +5752,18 @@ export const $TriggerDAGRunPostBody = {
],
title: "Dag Run Id",
},
logical_date: {
anyOf: [
{
type: "string",
format: "date-time",
},
{
type: "null",
},
],
title: "Logical Date",
},
data_interval_start: {
anyOf: [
{
Expand Down Expand Up @@ -5794,6 +5806,7 @@ export const $TriggerDAGRunPostBody = {
},
additionalProperties: false,
type: "object",
required: ["logical_date"],
title: "TriggerDAGRunPostBody",
description: "Trigger DAG Run Serializer for POST body.",
} as const;
Expand Down
1 change: 1 addition & 0 deletions airflow/ui/openapi-gen/requests/types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1402,6 +1402,7 @@ export type TimeDelta = {
*/
export type TriggerDAGRunPostBody = {
dag_run_id?: string | null;
logical_date: string | null;
data_interval_start?: string | null;
data_interval_end?: string | null;
conf?: {
Expand Down
1 change: 1 addition & 0 deletions airflow/ui/src/queries/useTrigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export const useTrigger = ({ dagId, onSuccessConfirm }: { dagId: string; onSucce
dag_run_id: checkDagRunId,
data_interval_end: formattedDataIntervalEnd,
data_interval_start: formattedDataIntervalStart,
logical_date: null,
note: checkNote,
},
});
Expand Down
2 changes: 1 addition & 1 deletion docs/apache-airflow/img/airflow_erd.sha256
Original file line number Diff line number Diff line change
@@ -1 +1 @@
232f2f252ce0d3889fa5a9ceb00c88788e12083a6ea0c155c74d3fe61ad02412
c27770b242bc31b945e731d3b82844c02a1a9a4974061e55af1d957985741881
1 change: 0 additions & 1 deletion docs/apache-airflow/img/airflow_erd.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion docs/apache-airflow/migrations-ref.rst
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ Here's the list of all the Database Migrations that are executed via when you ru
+-------------------------+------------------+-------------------+--------------------------------------------------------------+
| ``522625f6d606`` | ``1cdc775ca98f`` | ``3.0.0`` | Add tables for backfill. |
+-------------------------+------------------+-------------------+--------------------------------------------------------------+
| ``1cdc775ca98f`` | ``a2c32e6c7729`` | ``3.0.0`` | Drop ``execution_date`` unique constraint on DagRun. |
| ``1cdc775ca98f`` | ``a2c32e6c7729`` | ``3.0.0`` | Make logical_date nullable. |
+-------------------------+------------------+-------------------+--------------------------------------------------------------+
| ``a2c32e6c7729`` | ``0bfc26bc256e`` | ``3.0.0`` | Add triggered_by field to DagRun. |
+-------------------------+------------------+-------------------+--------------------------------------------------------------+
Expand Down
18 changes: 13 additions & 5 deletions tests/api_fastapi/core_api/routes/public/test_assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def _create_dag_run(session, num: int = 2):
dag_id="source_dag_id",
run_id=f"source_run_id_{i}",
run_type=DagRunType.MANUAL,
logical_date=DEFAULT_DATE,
logical_date=DEFAULT_DATE + timedelta(days=i),
start_date=DEFAULT_DATE,
data_interval=(DEFAULT_DATE, DEFAULT_DATE),
external_trigger=True,
Expand Down Expand Up @@ -554,7 +554,9 @@ def test_should_respond_200(self, test_client, session):
{
"run_id": "source_run_id_1",
"dag_id": "source_dag_id",
"logical_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"logical_date": from_datetime_to_zulu_without_ms(
DEFAULT_DATE + timedelta(days=1)
),
"start_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"end_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"state": "success",
Expand All @@ -579,7 +581,9 @@ def test_should_respond_200(self, test_client, session):
{
"run_id": "source_run_id_2",
"dag_id": "source_dag_id",
"logical_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"logical_date": from_datetime_to_zulu_without_ms(
DEFAULT_DATE + timedelta(days=2)
),
"start_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"end_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"state": "success",
Expand Down Expand Up @@ -722,7 +726,9 @@ def test_should_mask_sensitive_extra(self, test_client, session):
{
"run_id": "source_run_id_1",
"dag_id": "source_dag_id",
"logical_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"logical_date": from_datetime_to_zulu_without_ms(
DEFAULT_DATE + timedelta(days=1)
),
"start_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"end_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"state": "success",
Expand All @@ -747,7 +753,9 @@ def test_should_mask_sensitive_extra(self, test_client, session):
{
"run_id": "source_run_id_2",
"dag_id": "source_dag_id",
"logical_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"logical_date": from_datetime_to_zulu_without_ms(
DEFAULT_DATE + timedelta(days=2)
),
"start_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"end_date": from_datetime_to_zulu_without_ms(DEFAULT_DATE),
"state": "success",
Expand Down
Loading
Loading