-
Notifications
You must be signed in to change notification settings - Fork 16.6k
Fix task-level audit logs missing success/running events in Airflow 3.1.x #61932
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
Open
sjyangkevin
wants to merge
7
commits into
apache:main
Choose a base branch
from
sjyangkevin:issues/58381/success-running-audit-logs-missing
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+206
−6
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
faf7708
create audit log records in ti_run and ti_update_state
sjyangkevin 37424cc
cleanup and merge test cases
sjyangkevin 49cb7db
retrive from dag and from dag run, and add extra with only host_name
sjyangkevin c2e1737
update ui end-to-end test to be more stable
sjyangkevin 51c2b55
clean up
sjyangkevin c013aaf
remove serial config for tests
sjyangkevin 9d89ebe
revert change made to the UI end-to-end test as sequential trigger/wa…
sjyangkevin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -34,6 +34,7 @@ | |
| from airflow.exceptions import AirflowSkipException | ||
| from airflow.models import RenderedTaskInstanceFields, TaskReschedule, Trigger | ||
| from airflow.models.asset import AssetActive, AssetAliasModel, AssetEvent, AssetModel | ||
| from airflow.models.log import Log | ||
| from airflow.models.taskinstance import TaskInstance | ||
| from airflow.models.taskinstancehistory import TaskInstanceHistory | ||
| from airflow.providers.standard.operators.empty import EmptyOperator | ||
|
|
@@ -44,6 +45,7 @@ | |
| from tests_common.test_utils.db import ( | ||
| clear_db_assets, | ||
| clear_db_dags, | ||
| clear_db_logs, | ||
| clear_db_runs, | ||
| clear_db_serialized_dags, | ||
| clear_rendered_ti_fields, | ||
|
|
@@ -127,11 +129,13 @@ def side_effect(cred, validators): | |
|
|
||
| class TestTIRunState: | ||
| def setup_method(self): | ||
| clear_db_logs() | ||
| clear_db_runs() | ||
| clear_db_serialized_dags() | ||
| clear_db_dags() | ||
|
|
||
| def teardown_method(self): | ||
| clear_db_logs() | ||
| clear_db_runs() | ||
| clear_db_serialized_dags() | ||
| clear_db_dags() | ||
|
|
@@ -793,14 +797,57 @@ def test_ti_run_with_triggering_user_name( | |
| assert dag_run["run_id"] == "test" | ||
| assert dag_run["state"] == "running" | ||
|
|
||
| def test_ti_run_creates_audit_log(self, client, session, create_task_instance, time_machine): | ||
| """Test that transitioning to RUNNING creates an audit log record.""" | ||
| instant_str = "2024-09-30T12:00:00Z" | ||
| instant = timezone.parse(instant_str) | ||
| time_machine.move_to(instant, tick=False) | ||
|
|
||
| ti = create_task_instance( | ||
| task_id="test_ti_run_creates_audit_log", | ||
| state=State.QUEUED, | ||
| dagrun_state=DagRunState.RUNNING, | ||
| session=session, | ||
| start_date=instant, | ||
| dag_id=str(uuid4()), | ||
| ) | ||
| session.commit() | ||
|
|
||
| response = client.patch( | ||
| f"/execution/task-instances/{ti.id}/run", | ||
| json={ | ||
| "state": "running", | ||
| "hostname": "random-hostname", | ||
| "unixname": "random-unixname", | ||
| "pid": 100, | ||
| "start_date": instant_str, | ||
| }, | ||
| ) | ||
|
|
||
| assert response.status_code == 200 | ||
|
|
||
| logs = session.scalars(select(Log).where(Log.dag_id == ti.dag_id)).all() | ||
| assert len(logs) == 1 | ||
| assert logs[0].event == TaskInstanceState.RUNNING.value | ||
| assert logs[0].task_id == ti.task_id | ||
| assert logs[0].dag_id == ti.dag_id | ||
| assert logs[0].run_id == ti.run_id | ||
| assert logs[0].map_index == ti.map_index | ||
| assert logs[0].try_number == ti.try_number | ||
| assert logs[0].logical_date == instant | ||
| assert logs[0].owner == ti.task.owner | ||
| assert logs[0].extra == '{"host_name": "random-hostname"}' | ||
|
|
||
|
|
||
| class TestTIUpdateState: | ||
| def setup_method(self): | ||
| clear_db_assets() | ||
| clear_db_logs() | ||
| clear_db_runs() | ||
|
|
||
| def teardown_method(self): | ||
| clear_db_assets() | ||
| clear_db_logs() | ||
| clear_db_runs() | ||
|
|
||
| @pytest.mark.parametrize( | ||
|
|
@@ -838,6 +885,82 @@ def test_ti_update_state_to_terminal( | |
| assert ti.state == expected_state | ||
| assert ti.end_date == end_date | ||
|
|
||
| @pytest.mark.parametrize( | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consolidate all the test cases into a parameterized one. |
||
| ("payload", "expected_event"), | ||
| [ | ||
| pytest.param( | ||
| {"state": State.SUCCESS, "end_date": DEFAULT_END_DATE.isoformat()}, | ||
| State.SUCCESS, | ||
| id="success", | ||
| ), | ||
| pytest.param( | ||
| {"state": State.FAILED, "end_date": DEFAULT_END_DATE.isoformat()}, | ||
| State.FAILED, | ||
| id="failed", | ||
| ), | ||
| pytest.param( | ||
| {"state": State.SKIPPED, "end_date": DEFAULT_END_DATE.isoformat()}, | ||
| State.SKIPPED, | ||
| id="skipped", | ||
| ), | ||
| pytest.param( | ||
| {"state": State.UP_FOR_RETRY, "end_date": DEFAULT_END_DATE.isoformat()}, | ||
| TaskInstanceState.UP_FOR_RETRY.value, | ||
| id="up_for_retry", | ||
| ), | ||
| pytest.param( | ||
| { | ||
| "state": "deferred", | ||
| "trigger_kwargs": {"key": "value", "moment": "2026-02-18T00:00:00Z"}, | ||
| "trigger_timeout": "P1D", | ||
| "classpath": "my-classpath", | ||
| "next_method": "execute_callback", | ||
| }, | ||
| TaskInstanceState.DEFERRED.value, | ||
| id="deferred", | ||
| ), | ||
| pytest.param( | ||
| { | ||
| "state": "up_for_reschedule", | ||
| "reschedule_date": "2026-02-18T11:03:00+00:00", | ||
| "end_date": DEFAULT_END_DATE.isoformat(), | ||
| }, | ||
| TaskInstanceState.UP_FOR_RESCHEDULE.value, | ||
| id="up_for_reschedule", | ||
| ), | ||
| ], | ||
| ) | ||
| def test_ti_update_state_creates_audit_log( | ||
| self, client, session, create_task_instance, payload, expected_event | ||
| ): | ||
| """Test that state transition creates an audit log record.""" | ||
| ti = create_task_instance( | ||
| task_id="test_ti_update_state_creates_audit_log", | ||
| start_date=DEFAULT_START_DATE, | ||
| state=State.RUNNING, | ||
| hostname="random-hostname", | ||
| ) | ||
| session.commit() | ||
|
|
||
| response = client.patch( | ||
| f"/execution/task-instances/{ti.id}/state", | ||
| json=payload, | ||
| ) | ||
|
|
||
| assert response.status_code == 204 | ||
|
|
||
| logs = session.scalars(select(Log).where(Log.dag_id == ti.dag_id)).all() | ||
| assert len(logs) == 1 | ||
| assert logs[0].event == expected_event | ||
| assert logs[0].task_id == ti.task_id | ||
| assert logs[0].dag_id == ti.dag_id | ||
| assert logs[0].run_id == ti.run_id | ||
| assert logs[0].map_index == ti.map_index | ||
| assert logs[0].try_number == ti.try_number | ||
| assert logs[0].logical_date == ti.dag_run.logical_date | ||
| assert logs[0].owner == ti.task.owner | ||
| assert logs[0].extra == '{"host_name": "random-hostname"}' | ||
|
|
||
| @pytest.mark.parametrize( | ||
| ("state", "end_date", "expected_state", "rendered_map_index"), | ||
| [ | ||
|
|
@@ -1063,8 +1186,34 @@ def test_ti_update_state_database_error(self, client, session, create_task_insta | |
| mock.patch( | ||
| "airflow.api_fastapi.common.db.common.Session.execute", | ||
| side_effect=[ | ||
| mock.Mock(one=lambda: ("running", 1, 0, "dag")), # First call returns "queued" | ||
| mock.Mock(one=lambda: ("running", 1, 0, "dag")), # Second call returns "queued" | ||
| mock.Mock( | ||
| one=lambda: ( | ||
| "running", | ||
| 1, | ||
| 0, | ||
| "dag", | ||
| "task", | ||
| "run", | ||
| -1, | ||
| "localhost", | ||
| timezone.utcnow(), | ||
| "test_owner", | ||
| ) | ||
| ), # First call returns "queued" | ||
| mock.Mock( | ||
| one=lambda: ( | ||
| "running", | ||
| 1, | ||
| 0, | ||
| "dag", | ||
| "task", | ||
| "run", | ||
| -1, | ||
| "localhost", | ||
| timezone.utcnow(), | ||
| "test_owner", | ||
| ) | ||
| ), # Second call returns "queued" | ||
|
Comment on lines
+1189
to
+1216
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. because the TI query return more values, update the mock. |
||
| SQLAlchemyError("Database error"), # Last call raises an error | ||
| ], | ||
| ), | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I updated the query to join with
DagModelandDagRunto fetchlogical_dateandowner, and updatewith_for_updateto lock onlyTIin the join query. Construct a JSON string only withhost_nameinextra, which is also present in earlier version of Airflow.