You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "vincbeck (via GitHub)" <gi...@apache.org> on 2026/09/24 18:37:49 UTC

[PR] Filter jobs API `is_alive` in SQL so pagination stays correct [airflow]

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

   The `/jobs` endpoint evaluated liveness in Python on the page returned by `paginated_select`, so `total_entries` counted rows the filter would drop and a page could come back short whenever `is_alive` was combined with another filter. The same post-filter also kept only alive jobs for every value of the flag, so `is_alive=false` returned alive jobs instead of dead ones.
   
   Resolving liveness in SQL lets the count and the page agree and makes the flag mean what it says. `Job.alive_filter()` mirrors `Job._is_alive` and reads its thresholds from `health_check_threshold`, so the endpoint and the health check cannot drift apart.
   
    <!-- 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] Filter jobs API `is_alive` in SQL so pagination stays correct [airflow]

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


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/job.py:
##########
@@ -106,6 +106,11 @@ def get_jobs(
     """Get all jobs."""
     base_select = select(Job).order_by(Job.latest_heartbeat.desc()).options(joinedload(Job.dag_model))
 
+    if is_alive is not None:
+        # Filter in SQL rather than on the fetched page so total_entries and the page agree.
+        alive = Job.alive_filter()
+        base_select = base_select.where(alive if is_alive else ~alive)
+

Review Comment:
   This is not how filters should be implemented. 
   
   We should create an `IsAliveFilter` following the common parameters interface we have in the app.
   
   And then provide the filter to `paginated_select`. 
   
   The custom impl for `alive_filter` wouldn't leak on the model (job definition). 
   
   The view wouldn't implement any custom logic for one specific filter while all others are properly handled through the pagination utility.



-- 
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] Filter jobs API `is_alive` in SQL so pagination stays correct [airflow]

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


-- 
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] Filter jobs API `is_alive` in SQL so pagination stays correct [airflow]

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


##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_job.py:
##########
@@ -222,6 +224,38 @@ def test_get_jobs_includes_team_names_and_bundle_names(
         assert response_json["jobs"][0]["team_names"] == sorted([testing_team.name, extra_team.name])
         assert response_json["jobs"][0]["bundle_names"] == ["bundle-a", "bundle-b"]
 
+    @time_machine.travel(datetime(2024, 1, 1, tzinfo=timezone.utc), tick=False)
+    def test_get_jobs_is_alive_filter_is_consistent_with_pagination(self, test_client, session: Session):
+        clear_db_jobs()
+        now = datetime(2024, 1, 1, tzinfo=timezone.utc)
+        session.add_all(
+            [
+                Job(state=JobState.RUNNING, job_type="SchedulerJob", latest_heartbeat=now),
+                Job(state=JobState.RUNNING, job_type="SchedulerJob", latest_heartbeat=now),
+                # RUNNING but the heartbeat is older than the health-check threshold -> not alive.
+                Job(
+                    state=JobState.RUNNING,
+                    job_type="SchedulerJob",
+                    latest_heartbeat=now - timedelta(days=1),
+                ),
+                # Not RUNNING -> not alive.
+                Job(state=JobState.FAILED, job_type="SchedulerJob", latest_heartbeat=now),
+            ]
+        )
+        session.commit()
+
+        alive = test_client.get("/jobs", params={"is_alive": True}).json()
+        assert alive["total_entries"] == 2
+        assert {job["state"] for job in alive["jobs"]} == {JobState.RUNNING}
+
+        not_alive = test_client.get("/jobs", params={"is_alive": False}).json()
+        assert not_alive["total_entries"] == 2

Review Comment:
   Very good point, thanks for the review! Updated :)



-- 
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] Filter jobs API `is_alive` in SQL so pagination stays correct [airflow]

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


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/job.py:
##########
@@ -106,6 +106,11 @@ def get_jobs(
     """Get all jobs."""
     base_select = select(Job).order_by(Job.latest_heartbeat.desc()).options(joinedload(Job.dag_model))
 
+    if is_alive is not None:
+        # Filter in SQL rather than on the fetched page so total_entries and the page agree.
+        alive = Job.alive_filter()
+        base_select = base_select.where(alive if is_alive else ~alive)
+

Review Comment:
   You're 100% right boss! Thanks for the review :) I updated the PR with your recommendations



-- 
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] Filter jobs API `is_alive` in SQL so pagination stays correct [airflow]

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


##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_job.py:
##########
@@ -222,6 +224,38 @@ def test_get_jobs_includes_team_names_and_bundle_names(
         assert response_json["jobs"][0]["team_names"] == sorted([testing_team.name, extra_team.name])
         assert response_json["jobs"][0]["bundle_names"] == ["bundle-a", "bundle-b"]
 
+    @time_machine.travel(datetime(2024, 1, 1, tzinfo=timezone.utc), tick=False)
+    def test_get_jobs_is_alive_filter_is_consistent_with_pagination(self, test_client, session: Session):
+        clear_db_jobs()
+        now = datetime(2024, 1, 1, tzinfo=timezone.utc)
+        session.add_all(
+            [
+                Job(state=JobState.RUNNING, job_type="SchedulerJob", latest_heartbeat=now),
+                Job(state=JobState.RUNNING, job_type="SchedulerJob", latest_heartbeat=now),
+                # RUNNING but the heartbeat is older than the health-check threshold -> not alive.
+                Job(
+                    state=JobState.RUNNING,
+                    job_type="SchedulerJob",
+                    latest_heartbeat=now - timedelta(days=1),
+                ),
+                # Not RUNNING -> not alive.
+                Job(state=JobState.FAILED, job_type="SchedulerJob", latest_heartbeat=now),
+            ]
+        )
+        session.commit()
+
+        alive = test_client.get("/jobs", params={"is_alive": True}).json()
+        assert alive["total_entries"] == 2
+        assert {job["state"] for job in alive["jobs"]} == {JobState.RUNNING}
+
+        not_alive = test_client.get("/jobs", params={"is_alive": False}).json()
+        assert not_alive["total_entries"] == 2

Review Comment:
   It looks like you are checking the count for the dead job but not the jobs themselves. Please see the below for inspiration:
   
   ```
   jobs = [
       Job(state=JobState.RUNNING, job_type="SchedulerJob", latest_heartbeat=now),
       Job(state=JobState.RUNNING, job_type="SchedulerJob", latest_heartbeat=now),
       Job(state=JobState.RUNNING, job_type="SchedulerJob", latest_heartbeat=now - timedelta(days=1)),
       Job(state=JobState.FAILED, job_type="SchedulerJob", latest_heartbeat=now),
   ]
   session.add_all(jobs)
   session.commit()
   
   assert {job["id"] for job in not_alive["jobs"]} == {jobs[2].id, jobs[3].id}
   ```
   
   basically add the jobs and then cross-ref the IDs.



-- 
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] Filter jobs API `is_alive` in SQL so pagination stays correct [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #73684:
URL: https://github.com/apache/airflow/pull/73684#issuecomment-5892502347

   @pierrejeambrun 


-- 
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