Repository navigation
Add task instance management commands to airflowctl CLI - #63889
Suraj-kumar00 wants to merge 6 commits into
Conversation
|
@Suraj-kumar00 Converting to draft — this PR doesn't yet meet our Pull Request quality criteria.
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. |
|
@Suraj-kumar00 A few things need addressing before review — see our Pull Request quality criteria.
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. |
|
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
left a comment
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 viaClient.task_instances. - Updated CLI config to treat
clearas an output-producing command and added comma-separated string → list coercion. - Added unit and end-to-end tests for the new
taskinstancecommands; 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. |
| 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()] |
There was a problem hiding this comment.
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[...]].
| 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) |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| def test_get(self): | ||
| """Test fetching a single task instance.""" |
There was a problem hiding this comment.
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.
| 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())) |
There was a problem hiding this comment.
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.
| def test_update(self): | ||
| """Test updating a task instance state.""" |
There was a problem hiding this comment.
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.
| ) | ||
| 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())) |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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}").
|
There are still unaddressed comments, such as |
6e87db7 to
a53b31b
Compare
…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
a53b31b to
5b7452b
Compare
| 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()] |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
|
|
||
| @lru_cache() # type: ignore[prop-decorator] | ||
| @property | ||
| def tasks(self): |
There was a problem hiding this comment.
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.
| def tasks(self): | |
| def task_instances(self): |
| @lru_cache() # type: ignore[prop-decorator] | ||
| @property | ||
| def tasks(self): | ||
| """Operations related to task instances.""" | ||
| return TaskInstanceOperations(self) |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
I am not sure why this is needed 🤔
|
Still some conflicts and unresolved conversations. Converting this to draft. Feel free to mark it as ready when you think it is ready. Thanks! |
|
@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:
What to do next:
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. |
|
@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. |
Adds Task Instance management support to the
airflowctlCLI, enabling users to get, list, clear, and update task instances directly from the terminal.Closes: #61547
Related: #66173
Changes
airflowctl/api/operations.pyTaskInstanceOperationsclass with the following methods:get,list,clear,updateTaskInstanceCollectionResponseforgetandupdateoperations to prevent Pydantic validation errorsairflowctl/api/client.pytask_instancesproperty to theClient, enabling proper wiring of auto-generated CLI commandsairflowctl/ctl/cli_config.py"clear"tooutput_command_listfor correct CLI output handling--task-ids t1,t2→["t1", "t2"])tests/airflow_ctl/api/test_operations.pyTestTaskInstanceOperationswith 6 unit tests coveringget,list,clear(default and with options), andupdate(state and note)airflow-ctl-tests/tests/airflowctl_tests/test_airflowctl_commands.pytaskinstancecommandsNew CLI Commands
Was generative AI tooling used to co-author this PR?
{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.