jroachgolf84 commented on code in PR #67376: URL: https://github.com/apache/airflow/pull/67376#discussion_r3293247873
########## airflow-core/src/airflow/example_dags/example_task_state.py: ########## @@ -0,0 +1,90 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Example Dag that demonstrates the canonical AIP-103 task state pattern: a task submits a +long-running external job, stores the job handle in task state, and polls +until completion. + +The first attempt always fails after submitting the job (simulating a +worker crash / connection to external system being lost). The retry reads +the job ID from task state and reattaches to the already-running job instead +of submitting a duplicate. +""" + +from __future__ import annotations + +import json +import random +import string +import time +from datetime import datetime, timedelta, timezone + +from airflow.sdk import DAG, task +from airflow.sdk.execution_time.context import NEVER_EXPIRE + + +def _submit_job() -> str: + """Simulate submitting an external job. Returns a job ID.""" + time.sleep(1) + return "job-" + "".join(random.choices(string.ascii_lowercase + string.digits, k=8)) + + +def _poll_job(job_id: str) -> dict: + """Simulate polling an external job until complete.""" + time.sleep(1) + return {"job_id": job_id, "status": "succeeded", "rows_written": random.randint(100, 10_000)} + + +with DAG( + dag_id="example_task_state", + schedule=None, + start_date=datetime(2026, 1, 1), + catchup=False, + tags=["example", "task-state"], + doc_md=__doc__, +): + + @task(retries=2, retry_delay=timedelta(seconds=5)) + def run_job(**context): + ts = context["task_state"] Review Comment: This is seriously nit-picking, but would it make sense to use the variable name `task_state` instead of `ts`, just for verbosity for users? ########## airflow-core/src/airflow/example_dags/example_asset_state.py: ########## @@ -0,0 +1,100 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Example Dag that demonstrates using AIP-103 asset state to track a watermark across DAG runs. +The producer reads the last watermark, processes only new records, then +advances the watermark. The consumer is triggered by the asset event and +reads asset state to understand what the producer just loaded. + +Asset state persists on the asset across runs — unlike task state which is +scoped to a single task instance. This replaces the common pattern of +storing watermarks in Airflow Variables, which have no asset-level scoping. +""" + +from __future__ import annotations + +import json +import random +from datetime import datetime, timezone + +from airflow.sdk import DAG, Asset, task + +ORDERS = Asset(name="orders/daily", uri="s3://warehouse/orders/daily") + + +def _fetch_records(since: str) -> list[dict]: + """Simulate fetching records newer than `since`.""" + return [{"id": i} for i in range(random.randint(100, 5_000))] + + +with DAG( + dag_id="example_asset_state_producer", + schedule=None, + start_date=datetime(2026, 1, 1), + catchup=False, + tags=["example", "asset-state"], + doc_md=__doc__, +): + + @task(inlets=[ORDERS], outlets=[ORDERS]) + def load(**context): + state = context["asset_state"][ORDERS] + + # First run: watermark is None — fall back to epoch start. + watermark = state.get("watermark") or "2026-01-01T00:00:00+00:00" + records = _fetch_records(since=watermark) + row_count = len(records) + + now = datetime.now(tz=timezone.utc).isoformat() + state.set("watermark", now) + state.set("total_runs", str(int(state.get("total_runs") or 0) + 1)) + state.set( + "last_run_summary", + json.dumps( + { + "rows_loaded": row_count, + "prev_watermark": watermark, + "completed_at": now, + } Review Comment: +1 on not having to stringify things. In the DAGs that I've written using this, it does become a bit of a nuisance. -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
