Skip to content

Add task instance management commands to airflowctl CLI - #63889

Closed
Suraj-kumar00 wants to merge 6 commits into
apache:mainfrom
Suraj-kumar00:feat/task-instance-cli-support
Closed

Suraj-kumar00 wants to merge 6 commits into
apache:mainfrom
Suraj-kumar00:feat/task-instance-cli-support

Conversation

@Suraj-kumar00

@Suraj-kumar00 Suraj-kumar00 commented Mar 18, 2026 •

Copy link
Copy Markdown

Adds Task Instance management support to the airflowctl CLI, enabling users to get, list, clear, and update task instances directly from the terminal.

Closes: #61547
Related: #66173

Changes

airflowctl/api/operations.py

  • Introduced TaskInstanceOperations class with the following methods: get, list, clear, update
  • Reuses existing auto-generated Pydantic models for request and response validation
  • Handles Airflow's nested TaskInstanceCollectionResponse for get and update operations to prevent Pydantic validation errors

airflowctl/api/client.py

  • Added task_instances property to the Client, enabling proper wiring of auto-generated CLI commands

airflowctl/ctl/cli_config.py

  • Added "clear" to output_command_list for correct CLI output handling
  • Improved API field parsing to automatically convert comma-separated CLI inputs into lists when required by Pydantic models (e.g. --task-ids t1,t2 → ["t1", "t2"])

tests/airflow_ctl/api/test_operations.py

  • Added TestTaskInstanceOperations with 6 unit tests covering get, list, clear (default and with options), and update (state and note)
  • Follows the existing XCom testing pattern from Add XCom CLI commands to airflowctl #61021

airflow-ctl-tests/tests/airflowctl_tests/test_airflowctl_commands.py

  • Added end-to-end integration tests for all 4 taskinstance commands

New CLI Commands

airflowctl taskinstance list   --dag-id <dag_id> --dag-run-id <run_id>
airflowctl taskinstance get    --dag-id <dag_id> --dag-run-id <run_id> --task-id <task_id>
airflowctl taskinstance clear  --dag-id <dag_id> [--dry-run] [--only-failed] [--task-ids ...]
airflowctl taskinstance update --dag-id <dag_id> --dag-run-id <run_id> --task-id <task_id> [--new-state <state>] [--note <note>]
Screenshot 2026-03-18 at 9 32 30 PM Screenshot 2026-04-02 at 12 12 25 AM
Was generative AI tooling used to co-author this PR?
  • Yes (please specify the tool below)

  • Read the 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) is needed.
  • When adding dependency, check compliance with the ASF 3rd Party License Policy.
  • For significant user-facing changes create newsfragment: {pr_number}.significant.rst, in airflow-core/newsfragments. You can add this file in a follow-up commit after the PR is created so you know the PR number.

@potiuk

potiuk commented Mar 20, 2026 •

Copy link
Copy Markdown
Member

@Suraj-kumar00 Converting to draft — this PR doesn't yet meet our Pull Request quality criteria.

  • ❌ Pre-commit / static checks: Failing: CI image checks / Static checks. Run prek run --from-ref main locally to find and fix issues. See Pre-commit / static checks docs.
  • ❌ Other failing CI checks: Failing: Additional PROD image tests / Airflow CTL integration tests with PROD image. Run prek run --from-ref main locally to reproduce. See static checks docs.

See the linked criteria for how to fix each item, then mark the PR "Ready for review". This is not a rejection — just an invitation to bring the PR up to standard. No rush.


Note: This comment was drafted by an AI-assisted triage tool and may contain mistakes. Once you have addressed the points above, an Apache Airflow maintainer — a real person — will take the next look at your PR. We use this two-stage triage process so that our maintainers' limited time is spent where it matters most: the conversation with you.

@potiuk
potiuk marked this pull request as draft March 20, 2026 08:01
@Suraj-kumar00
Suraj-kumar00 marked this pull request as ready for review March 26, 2026 15:46
@potiuk

potiuk commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

@Suraj-kumar00 A few things need addressing before review — see our Pull Request quality criteria.

  • ⚠️ Title quality: The PR title 'Feat/task instance cli support' is a branch-name pattern rather than a properly written PR title. While it does convey the general intent, the slash-separated format ('Feat/...') is unconventional and the wording is terse. A title like 'Add task instance management commands to airflowctl CLI' would be clearer and more consistent with project norms.
  • ⚠️ Code quality — pointless try/except blocks: In operations.py, the get, clear, and update methods all follow the pattern try: ... except ServerResponseError as e: raise e. A bare re-raise of the caught exception adds no value — it is identical to having no try/except at all. This is a common AI-generated code smell ('narrating' or boilerplate patterns) and should be removed.

No rush.


Note: This comment was drafted by an AI-assisted triage tool and may contain mistakes. Once you have addressed the points above, an Apache Airflow maintainer — a real person — will take the next look at your PR. We use this two-stage triage process so that our maintainers' limited time is spent where it matters most: the conversation with you.

@Suraj-kumar00 Suraj-kumar00 changed the title Feat/task instance cli support Add task instance management commands to airflowctl CLI Apr 1, 2026
@Suraj-kumar00

Copy link
Copy Markdown
Author

Hello @potiuk, I have made the changes accordingly. Could you please review and help me with feedback also I have tried passing the CI locally but need to check here and for that as I can see it needs approval.

Let me anythings needs else from my end.

Thanks for your help!!!

@bugraoz93 bugraoz93 added the full tests needed We need to run full set of tests for this PR to merge label Apr 1, 2026
@bugraoz93 bugraoz93 closed this Apr 1, 2026
@bugraoz93 bugraoz93 reopened this Apr 1, 2026

@bugraoz93 bugraoz93 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 for the PR! Let's see integration tests and I have some comments

expanded_parameter in args_dict.keys()
and args_dict[expanded_parameter] is not None
):
val = args_dict[expanded_parameter]

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.

Improved API field parsing to automatically convert comma-separated CLI inputs into lists when required by Pydantic models (e.g. --task-ids t1,t2 → ["t1", "t2"])

I don't quite follow your changes here. This is not the input part of the CLI. This part parses the Pydantic models from imported modules and files.

We should handle I/O in the link below. Because this is the only CLI part of auto-generated commands with client-generated. We also handle output here if you check there

https://github.com/bugraoz93/airflow/blob/ea552cb850b0e1ea66560197038d09608c7ef0b3/airflow-ctl/src/airflowctl/ctl/cli_config.py#L620-L666

Comment thread uv.lock Resolved
@kaxil
kaxil requested a review from Copilot April 2, 2026 00:45

Copilot AI 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.

Pull request overview

Adds Task Instance management support to the airflowctl CLI by introducing API operations and wiring them into the client/CLI, along with updated parsing and test coverage for the new commands.

Changes:

  • Added TaskInstanceOperations (get/list/clear/update) and exposed it via Client.task_instances.
  • Updated CLI config to treat clear as an output-producing command and added comma-separated string → list coercion.
  • Added unit and end-to-end tests for the new taskinstance commands; updated docs artifacts/screenshots.

Reviewed changes

Copilot reviewed 7 out of 9 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
airflow-ctl/src/airflowctl/api/operations.py Introduces TaskInstanceOperations and response-shape handling for task instance endpoints.
airflow-ctl/src/airflowctl/api/client.py Wires TaskInstanceOperations into the API client via task_instances property.
airflow-ctl/src/airflowctl/ctl/cli_config.py Adds clear to output commands and coerces comma-separated CLI values to lists for Pydantic models.
airflow-ctl/tests/airflow_ctl/api/test_operations.py Adds unit tests covering task instance operations.
airflow-ctl-tests/tests/airflowctl_tests/test_airflowctl_commands.py Adds E2E test coverage for taskinstance CLI commands.
airflow-ctl/tests/airflow_ctl/ctl/commands/test_pool_command.py Adjusts assertions to be resilient to Rich/ANSI output.
airflow-ctl/docs/images/output_main.svg Updates CLI help screenshot artifact to include the new command group.
airflow-ctl/docs/images/command_hashes.txt Updates command hash snapshot to match updated CLI output.

Comment on lines +658 to +668
if (
expanded_parameter in args_dict.keys()
and args_dict[expanded_parameter] is not None
):
val = args_dict[expanded_parameter]
# Automatically convert comma-separated strings to lists if the field expects a list
field_annotation = str(
datamodel.model_fields[expanded_parameter].annotation
).lower()
if "list" in field_annotation and isinstance(val, str):
val = [v.strip() for v in val.split(",") if v.strip()]

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

datamodel.model_fields[expanded_parameter] can raise KeyError when a CLI arg exists in args_dict but the Pydantic model uses a different field name/alias (or the arg is for a non-model parameter). Also, detecting “list-ness” via str(annotation).lower() + substring "list" is brittle and can misclassify types. Prefer guarding with if expanded_parameter in datamodel.model_fields, and use typing.get_origin() / typing.get_args() (or Pydantic field metadata) to reliably detect list[...] and Optional[list[...]].

Copilot uses AI. Check for mistakes.
Comment on lines +905 to +913
def get(self, dag_id: str, dag_run_id: str, task_id: str) -> Any:
"""Get a task instance."""
self.response = self.client.get(f"dags/{dag_id}/dagRuns/{dag_run_id}/taskInstances/{task_id}")
data = self.response.json()
if isinstance(data, list):
return [TaskInstanceResponse.model_validate(item) for item in data]
if "task_instances" in data:
return TaskInstanceCollectionResponse.model_validate(data)
return TaskInstanceResponse.model_validate(data)

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

The method docstring says “Get a task instance”, but the implementation can return three different shapes (list[TaskInstanceResponse], TaskInstanceCollectionResponse, or TaskInstanceResponse) while the signature is -> Any. This makes it harder for CLI/rendering code to behave predictably. Consider normalizing to a single return type for get (e.g., always return TaskInstanceResponse, unwrapping the collection/list when needed) or explicitly annotate a narrow union return type and ensure downstream formatting can handle it.

Copilot uses AI. Check for mistakes.
Comment on lines +932 to +943
def update(self, dag_id: str, dag_run_id: str, task_id: str, body: PatchTaskInstanceBody) -> Any:
"""Update a task instance."""
self.response = self.client.patch(
f"dags/{dag_id}/dagRuns/{dag_run_id}/taskInstances/{task_id}",
json=body.model_dump(mode="json", exclude_unset=True),
)
data = self.response.json()
if isinstance(data, list):
return [TaskInstanceResponse.model_validate(item) for item in data]
if "task_instances" in data:
return TaskInstanceCollectionResponse.model_validate(data)
return TaskInstanceResponse.model_validate(data)

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

The response-shape normalization logic is duplicated between get() and update(). Pulling this into a private helper (e.g., _parse_task_instance_response(data)) would reduce repetition and make it easier to keep behavior consistent if Airflow’s API responses change.

Copilot uses AI. Check for mistakes.
Comment on lines +1781 to +1782
def test_get(self):
"""Test fetching a single task instance."""

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

TaskInstanceOperations.get() and .update() include branches to handle responses shaped as a raw list and as a {"task_instances": ...} collection wrapper, but the unit tests only cover the “single object” response path. Add tests that return (1) a JSON list payload and (2) a TaskInstanceCollectionResponse payload for get/update to ensure those defensive branches behave as intended.

Copilot uses AI. Check for mistakes.
assert request.url.path == (
f"/api/v2/dags/{self.dag_id}/dagRuns/{self.dag_run_id}/taskInstances/{self.task_id}"
)
return httpx.Response(200, json=json.loads(self.task_instance_response.model_dump_json()))

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

TaskInstanceOperations.get() and .update() include branches to handle responses shaped as a raw list and as a {"task_instances": ...} collection wrapper, but the unit tests only cover the “single object” response path. Add tests that return (1) a JSON list payload and (2) a TaskInstanceCollectionResponse payload for get/update to ensure those defensive branches behave as intended.

Copilot uses AI. Check for mistakes.
Comment on lines +1860 to +1861
def test_update(self):
"""Test updating a task instance state."""

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

TaskInstanceOperations.get() and .update() include branches to handle responses shaped as a raw list and as a {"task_instances": ...} collection wrapper, but the unit tests only cover the “single object” response path. Add tests that return (1) a JSON list payload and (2) a TaskInstanceCollectionResponse payload for get/update to ensure those defensive branches behave as intended.

Copilot uses AI. Check for mistakes.
)
request_body = json.loads(request.content)
assert request_body["new_state"] == TaskInstanceState.FAILED.value
return httpx.Response(200, json=json.loads(self.task_instance_response.model_dump_json()))

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

TaskInstanceOperations.get() and .update() include branches to handle responses shaped as a raw list and as a {"task_instances": ...} collection wrapper, but the unit tests only cover the “single object” response path. Add tests that return (1) a JSON list payload and (2) a TaskInstanceCollectionResponse payload for get/update to ensure those defensive branches behave as intended.

Copilot uses AI. Check for mistakes.
Comment on lines +177 to +181
out_str = captured.out.replace("\n", "")
# The output contains rich ANSI codes, so we check for key substrings instead
assert "Exported" in out_str
assert str(len(exported_data)) in out_str
assert "pool" in out_str

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

These assertions became very loose (any output containing those substrings will pass), which can hide regressions in the actual message/format. Since the motivation is ANSI styling, a more robust approach is to strip ANSI escape sequences first and then assert the full expected message (or a stricter, structured subset like f"Exported {len(exported_data)} pool(s) to {export_file}").

Copilot uses AI. Check for mistakes.
@potiuk potiuk added the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label Apr 2, 2026
@bugraoz93

bugraoz93 commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

There are still unaddressed comments, such as uv.lock, still in the PR, which shouldn't be. If you rebase and rollback the changes, it should be addressed. Could you please check them?

@bugraoz93 bugraoz93 removed the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label Apr 7, 2026
@Suraj-kumar00
Suraj-kumar00 force-pushed the feat/task-instance-cli-support branch from 6e87db7 to a53b31b Compare April 7, 2026 19:21
…tanceOperations

- Remove bare re-raise try/except from get, clear, and update methods
- Fix ruff E302: add missing blank line before TaskInstanceOperations class
- Fix ruff F841: remove unused variable in pool command export test
- Run ruff format on operations.py, cli_config.py, test_operations.py
@Suraj-kumar00
Suraj-kumar00 force-pushed the feat/task-instance-cli-support branch from a53b31b to 5b7452b Compare April 7, 2026 19:27
@Suraj-kumar00
Suraj-kumar00 requested a review from bugraoz93 April 8, 2026 12:10
@kaxil
kaxil requested a review from Copilot April 10, 2026 19:55

Copilot AI 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.

Pull request overview

Copilot reviewed 7 out of 8 changed files in this pull request and generated 4 comments.

Comment on lines +663 to +670
val = args_dict[expanded_parameter]
if isinstance(val, str) and expanded_parameter in datamodel.model_fields:
import typing

annotation = datamodel.model_fields[expanded_parameter].annotation
origin = typing.get_origin(annotation)
if origin is list or getattr(annotation, "__origin__", None) is list:
val = [v.strip() for v in val.split(",") if v.strip()]

Copilot AI Apr 10, 2026

Copy link

Choose a reason for hiding this comment

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

The comma-separated-to-list conversion logic won’t trigger for common Pydantic annotations like Optional[list[...]] / list[...] | None (and often Annotated[...]). For example, ClearTaskInstancesBody.task_ids is list[...] | None in api/datamodels/generated.py, so typing.get_origin(annotation) will be a union, not list, and the value will stay a string (causing model_validate to fail). Consider unwrapping Annotated, then handling unions by checking typing.get_args() for a list origin before splitting. Also, import typing can be moved to module scope to avoid repeated imports inside the arg loop.

Copilot uses AI. Check for mistakes.
Comment on lines +659 to +673
if (
expanded_parameter in args_dict.keys()
and args_dict[expanded_parameter] is not None
):
val = args_dict[expanded_parameter]
if isinstance(val, str) and expanded_parameter in datamodel.model_fields:
import typing

annotation = datamodel.model_fields[expanded_parameter].annotation
origin = typing.get_origin(annotation)
if origin is list or getattr(annotation, "__origin__", None) is list:
val = [v.strip() for v in val.split(",") if v.strip()]
method_params[parameter_key][
self._sanitize_method_param_key(expanded_parameter)
] = args_dict[expanded_parameter]
] = val

Copilot AI Apr 10, 2026

Copy link

Choose a reason for hiding this comment

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

New behavior is introduced here (auto-splitting comma-separated CLI inputs into list[...] fields) but there are no unit tests covering it. Since this impacts request-body validation (and new taskinstance clear options), please add a CLI-config test that proves e.g. --task-ids t1,t2 becomes ['t1','t2'] for ClearTaskInstancesBody.task_ids, and that non-list string fields are unaffected.

Copilot generated this review using guidance from repository custom instructions.

@lru_cache() # type: ignore[prop-decorator]
@property
def tasks(self):

Copilot AI Apr 10, 2026

Copy link

Choose a reason for hiding this comment

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

The new Client property is named tasks, but it actually exposes task instance operations (and the PR description says task_instances). tasks is ambiguous (could mean DAG tasks, not instances) and doesn’t match the naming style of other resource properties (dag_runs, backfills, etc.). Consider renaming this property to something explicit like task_instances (or taskinstance to mirror the CLI group), and update call sites/tests accordingly.

Suggested change
def tasks(self):
def task_instances(self):

Copilot uses AI. Check for mistakes.
Comment on lines +438 to +442
@lru_cache() # type: ignore[prop-decorator]
@property
def tasks(self):
"""Operations related to task instances."""
return TaskInstanceOperations(self)

Copilot AI Apr 10, 2026

Copy link

Choose a reason for hiding this comment

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

PR description says a task_instances property was added to Client, but the implementation adds tasks. Please either update the PR description or align the code to avoid confusion for reviewers and API consumers.

Copilot uses AI. Check for mistakes.
captured = capsys.readouterr()
expected_output = f"Exported {len(exported_data)} pool(s) to {export_file}"
assert expected_output in captured.out.replace("\n", "")
import re

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.

I am not sure why this is needed 🤔

@bugraoz93

bugraoz93 commented Apr 12, 2026 •

Copy link
Copy Markdown
Contributor

Still some conflicts and unresolved conversations. Converting this to draft. Feel free to mark it as ready when you think it is ready. Thanks!

@bugraoz93
bugraoz93 marked this pull request as draft April 12, 2026 16:08
@potiuk

potiuk commented Apr 23, 2026

Copy link
Copy Markdown
Member

@Suraj-kumar00 This draft PR has not had author activity for 14 days. Before anyone can review it, it needs to meet our Pull Request quality criteria. Here is a summary of what still needs work; once those items are addressed, mark the PR ready for review.

Issues found:

  • ❌ Merge conflicts: this branch has conflicts with main and cannot be merged as-is. Rebase: git fetch upstream main && git rebase upstream/main, resolve, force-push.
  • ❌ Failing CI: Additional PROD image tests / Airflow CTL integration tests with PROD image, Low dep tests: providers / All-prov:LowestDeps:14:3.10:segment...zendesk, CI image checks / Static checks. Please investigate and fix.
  • ❌ Unresolved review comments (14 threads (from maintainers)): please walk through each unresolved review thread. Even if a suggestion looks incorrect or irrelevant — and some of them will be, especially any comments left by automated reviewers like GitHub Copilot — it is still the author's responsibility to respond: apply the fix, reply in-thread with a brief explanation of why the suggestion does not apply, or resolve the thread if the feedback is no longer relevant. Once you believe a thread is resolved — whether by pushing a fix or by explaining why the suggestion doesn't apply — please mark it as resolved yourself by clicking the 'Resolve conversation' button at the bottom of each thread. Reviewers don't auto-close their own threads, so an addressed-but-unresolved thread reads as 'still waiting on the author' and keeps the PR from moving forward.

What to do next:

  • Address the items above.
  • Make sure static checks pass locally: prek run --from-ref main --stage pre-commit.
  • Mark the PR as "Ready for review" when you are done.

There is no rush — take your time and work at your own pace. We appreciate your contribution and are happy to wait for updates. If you have questions, feel free to ask on the Airflow Slack.

@potiuk

potiuk commented May 5, 2026

Copy link
Copy Markdown
Member

@Suraj-kumar00 This draft PR has been inactive for 12 days since the last triage comment and no response from the author. Closing to keep the queue clean.

You are welcome to reopen this PR when you resume work, or to open a new one addressing the issues previously raised. There is no rush — take your time.


Note: This comment was drafted by an AI-assisted triage tool and may contain mistakes. Once you have addressed the points above, an Apache Airflow maintainer — a real person — will take the next look at your PR. We use this two-stage triage process so that our maintainers' limited time is spent where it matters most: the conversation with you.

@potiuk potiuk closed this May 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:airflow-ctl full tests needed We need to run full set of tests for this PR to merge kind:documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

airflowctl: Add support to manage Task Instances

4 participants