Skip to content

Make start_date in Context nullable - #58175

Merged
ferruzzi merged 4 commits into
apache:mainfrom
aws-mwaa:ramitkataria/nullable-start-date
Feb 24, 2026
Merged

ferruzzi merged 4 commits into
apache:mainfrom
aws-mwaa:ramitkataria/nullable-start-date

Conversation

@ramitkataria

@ramitkataria ramitkataria commented Nov 11, 2025 •

Copy link
Copy Markdown
Contributor

If a deadline is missed before a DagRun is started (could be queued for a very long time), there would be an exception when creating the Context because start_date is currently non-nullable.

Note: this doesn't affect the current implementation of deadline alerts because the full context is currently not included in the context passed to deadline callbacks. Only deadline related info and the DagRun API response is included (which already allows for nullable start_date as we would expect). This change would be needed for future once there's deadline callbacks running in the executor and improved (full) context included for callbacks running on the triggerer.


^ Add meaningful description above
Read the Pull Request Guidelines for more information.
In case of fundamental code changes, an Airflow Improvement Proposal (AIP) is needed.
In case of a new dependency, check compliance with the ASF 3rd Party License Policy.
In case of backwards incompatible changes please leave a note in a newsfragment file, named {pr_number}.significant.rst or {issue_number}.significant.rst, in airflow-core/newsfragments.

@boring-cyborg boring-cyborg Bot added area:API Airflow's REST/HTTP API area:task-sdk labels Nov 11, 2025
@ramitkataria
ramitkataria force-pushed the ramitkataria/nullable-start-date branch from 8717e45 to cb643c4 Compare November 12, 2025 18:19

@o-nikolas o-nikolas left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a unit test that covers this please!

@ramitkataria

Copy link
Copy Markdown
Contributor Author

It seems like a unit test wouldn't be very useful here and I think we should test for this case once either deadline callbacks on executor or full context in triggerer is implemented (cc @ferruzzi). I also don't see other unit tests just for the API specs

@ramitkataria

Copy link
Copy Markdown
Contributor Author

Hey @kaxil and @amoghrajesh! I would ideally like to get an approval from either of you to ensure I'm not missing any unintended consequences of this change

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks good to me, but I would love to have the "experts" in the area to confirm it :)

@ferruzzi ferruzzi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as Jarek. Seems like a good change to me, but I don't have a full context on Context to know about any side-effects.

@amoghrajesh amoghrajesh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change makes sense, but we will have to have a cadywn migration for this.

Take a situation of using older task sdk client (v3.1) and new API server (v3.2 assuming this change is for that version). The scenario I have in mind a combination of backfills with max_active_runs. If multiple runs are created with backfills and max_active_runs set, there is a chance that later run starts before an earlier run and the earlier run is still in queued. If the later run is doing ti.get_previous_dagrun(state='queued'), theres a chance it might return None and the task crashing because the datamodel for that task cannot take None.

So we should add a cadwyn migration for this one, use this as a reference: https://github.com/apache/airflow/blob/main/contributing-docs/19_execution_api_versioning.rst

@uranusjr

uranusjr commented Jan 8, 2026

Copy link
Copy Markdown
Member

Any update here?

@ferruzzi

Copy link
Copy Markdown
Contributor

Any update here?

I'm going to take this one over; I'll try to get it done next week

@ferruzzi
ferruzzi force-pushed the ramitkataria/nullable-start-date branch from cb643c4 to f7e3752 Compare February 13, 2026 23:56
@ferruzzi

ferruzzi commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor

One very long week later 🙈

@amoghrajesh @uranusjr First time working with a cadwyn migration. I based it off the examples and the unit tests pass, but I'm not sure how to manually test it. Can you have a look when you get time?

@amoghrajesh amoghrajesh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ferruzzi the versioning looks good, but just to gain more confidence you can try running a situation where:

  1. Deploy changes in this PR for API server
  2. Undo changes for task sdk OR run old version of task sdk (pre 3.2)
  3. Run a dag that triggers / touches this flow

@ferruzzi
ferruzzi force-pushed the ramitkataria/nullable-start-date branch from f7e3752 to 508e9c4 Compare February 17, 2026 22:57
@Dev-iL

Dev-iL commented Feb 20, 2026

Copy link
Copy Markdown
Collaborator

Feedback from Opus:


PR Review: Make DagRun start_date Nullable in Execution API

PR Goal: Allow DagRun.start_date to be None across the execution API and Task SDK so that deadline alert callbacks can build a Context for DagRuns that are still queued (never started).

AIP Alignment: Deadline Alerts (Airflow 3.1)


Verdict: Approve with minor suggestions

This is a clean, well-scoped change that correctly prepares the ground for full-context deadline callbacks running on the executor/triggerer. The Cadwyn versioning is done properly, tests are meaningful, and the fallback logic is sound.


What the PR does well

  1. Aligns API with the database. The DB column dagrun.start_date is already nullable=True (mapped_column(UtcDateTime, nullable=True)). The execution API and Task SDK were more restrictive than the storage layer — this PR removes that mismatch.

  2. Safe backward-compatible fallback. For older API clients, start_date falls back to run_after, which is guaranteed non-null (nullable=False in DB, has a _default_run_after that always resolves to a value). This means old Task SDK versions will never receive null for a field they expect to be present.

  3. Dual converter coverage. The MakeDagRunStartDateNullable version change covers both:

    • TIRunContext (where DagRun is nested under response.body["dag_run"]) — used by /execution/task-instances/{id}/run
    • Direct DagRun responses — used by get_dag_run in dag_runs.py:68

    This matches the two distinct return paths that expose DagRun to clients.

  4. Test coverage hits the right scenarios: old-version fallback, head-version allows null, old-version preserves real values. The task-sdk-side tests verify model construction and TIRunContext compatibility.

  5. Correct AIP alignment. The AIP explicitly calls out that deadlines can fire before a DagRun starts (e.g. a run queued for a very long time). This change is a prerequisite for executing deadline callbacks with full context in that scenario.


Issues and suggestions

1. _generated.py is codegen'd — verify regeneration (Low risk)

task-sdk/src/airflow/sdk/api/datamodels/_generated.py has the header:

# generated by datamodel-codegen:
#   filename:  http://0.0.0.0:8080/execution/openapi.json

The change to this file looks correct and consistent with the source model change in taskinstance.py, but confirm the file was regenerated (not hand-edited) after updating the source model. A hand-edit will be silently overwritten the next time someone runs the codegen.

2. make_ti_context fixture type hint is now slightly inaccurate (Nit)

In task-sdk/tests/conftest.py:270, the fixture signature is:

start_date: str | datetime = "2024-12-01T01:00:00Z",

The test calls make_ti_context(start_date=None), which works at runtime (Pydantic accepts it after the model change, and the # type: ignore suppresses static checking), but the fixture's own type annotation doesn't include None. Consider updating to str | datetime | None = "2024-12-01T01:00:00Z" for accuracy. Not blocking.

3. RuntimeTaskInstance.start_date is still non-nullable (Informational)

In task-sdk/src/airflow/sdk/execution_time/task_runner.py:157:

start_date: AwareDatetime  # TaskInstance start_date, not DagRun's

This is the TaskInstance start date (set when the TI begins running), not the DagRun start date. It's correct that this remains non-nullable — by the time a TI is running, it has a start date. No action needed, but worth noting to avoid confusion during review.

4. Consider a defensive comment on the run_after fallback (Nit)

In the converter:

dag_run["start_date"] = dag_run.get("run_after")

While run_after is guaranteed non-null in practice (DB constraint + default), a brief inline comment explaining why run_after is a safe fallback would help future readers:

# run_after is always non-null (DB NOT NULL + default), safe as a sentinel
dag_run["start_date"] = dag_run.get("run_after")

5. No test for the direct DagRun endpoint backward compat (Minor gap)

The ensure_start_date_in_dag_run converter handles the /execution/dag-runs/{dag_id}/{run_id} endpoint (get_dag_run), but the tests only exercise the TIRunContext path (via /execution/task-instances/{id}/run). Consider adding a test that hits the DagRun detail endpoint with an old API version and a queued (null start_date) DagRun to validate the second converter.

6. context["start_date"] is currently not populated in the template context (Observation)

Looking at get_template_context() in task_runner.py, the start_date key is never explicitly set in the context dict. The Context TypedDict has total=False, so all keys are optional. The PR description correctly notes this change is forward-looking — it won't affect current behavior. But when the "full context" is eventually wired into deadline callbacks, whoever adds start_date to the context dict should add a null-safety guard or document the semantics (is None expected to propagate to Jinja templates as {{ start_date }}?).


Version placement assessment

Adding MakeDagRunStartDateNullable to the existing Version("2026-03-31", ...) is correct. This is a backward-incompatible schema change (nullable field that was non-nullable), and grouping it with the current development version ensures old clients get the fallback via Cadwyn.

The alphabetical ordering of version changes within the Version() constructor (MakeDagRunStartDateNullable before ModifyDeferredTaskKwargsToJsonValue) follows the existing convention.


Risk assessment

Area Risk Rationale
Breaking old Task SDK clients None Cadwyn converter provides run_after fallback
Breaking current deadline alerts None Current callbacks don't use full Context
Future deadline callbacks Low Type change is in place; just needs context population
Codegen drift Low If _generated.py was regenerated, no risk; if hand-edited, will be overwritten

Summary

Solid preparatory change for the Deadline Alerts feature. The core logic is correct, backward compatibility is handled properly, and the test coverage is good. The only actionable suggestion is adding a test for the direct DagRun endpoint's backward compat path. Everything else is nit-level.

ramitkataria and others added 3 commits February 23, 2026 16:57
If a deadline is missed before a DagRun is started (could be queued for
a very long time), there would be an exception when creating the Context
because start_date is currently non-nullable.
Co-authored-by: Amogh Desai <[email protected]>"
@ferruzzi
ferruzzi force-pushed the ramitkataria/nullable-start-date branch from 508e9c4 to a714368 Compare February 24, 2026 02:19

@amoghrajesh amoghrajesh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @ferruzzi! LGTM +1

Feel free to validate it functionally once before merge as you mentioned earlier :)

@ferruzzi
ferruzzi merged commit 20c7002 into apache:main Feb 24, 2026
128 checks passed
@ferruzzi
ferruzzi deleted the ramitkataria/nullable-start-date branch February 24, 2026 20:15
dominikhei pushed a commit to dominikhei/airflow that referenced this pull request Mar 11, 2026
* Make start_date in Context nullable

If a deadline is missed before a DagRun is started (could be queued for
a very long time), there would be an exception when creating the Context
because start_date is currently non-nullable.

* Add cadwyn migration for nullable DagRun.start_date

* more explicit downgrade

Co-authored-by: Amogh Desai <[email protected]>"

* merge conflict static checks

---------

Co-authored-by: ferruzzi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:API Airflow's REST/HTTP API area:task-sdk

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants