页面简介
正文摘录
Home Reliability and operations Retry policies ↑↓ Navigate ⏎ Select Esc Close Retry policies¶ Note Requires Airflow >= 3.3.0. Two policies ask a model about a task failure and turn the answer into a retry decision. They are two layers of a ladder that runs from fully hardcoded to fully model-driven, with the SDK’s ExceptionRetryPolicy as the bottom rung: Layer What decides How you tune it Fallback rules (ExceptionRetryPolicy, or fallback_rules on either policy below) RetryRule matches on the exception type, then the task’s own retries and retry_delay. No model. Write the rules. Always the floor: whatever no layer above decides lands here. Classifier (ClassifierRetryPolicy) The model names one of your categories; the table says whether that category is retried, after how long, and how sure the model has to be. A decision model answers with its confidence; a text model can sit here too, without a bar. Category descriptions and the confidence bar. No reasoning, no prose. LLM (LLMRetryPolicy) A text model classifies the failure and decides whether to retry and how long to wait, guided by instructions, and explains itself. The instructions: your taxonomy, your retry rules, your delays, in prose. Each class has only the arguments its layer needs. LLMRetryPolicy is the policy this guide has always described and is unchanged. The layers chain: fallback_policy on a ClassifierRetryPolicy names the policy to consult when the classifier is unsure or unreachable, typically an LLMRetryPolicy on a text model, so the cheap typed model handles the clear cases and the reasoning model the rest, and the rules catch what neither decides. See Escalating to an LLM below. Both work with any LLM provider supported by pydantic-ai (OpenAI, Anthropic, Bedrock, Vertex, Ollama, etc.). This page is about deciding whether a failed task should retry. To make an agent’s retries cheap by replaying the model and tool calls that already succeeded, see Durable execution; a retried LLMBatchOperator re-attaches to its running batch instead of paying for it again (Retries re-attach instead of re-submitting). For the core retry policy concepts, see Tasks. If the task also needs to survive a worker crash without losing its progress, see Retry policies and durable execution. Setup¶ Install the provider with the LLM backend you need: pip install 'apache-airflow-providers-common-ai[anthropic]' Create a connection (Admin > Connections): Connection Id: pydanticai_default Connection Type: Pydantic AI Password: Your API key Extra: {"model": "anthropic:claude-haiku-4-5-20251001"} Usage¶ from airflow.providers.common.ai.policies.retry import LLMRetryPolicy from airflow.sdk.definitions.retry_policy import RetryAction, RetryRule from datetime import timedelta llm_policy = LLMRetryPolicy( llm_conn_id="pydanticai_default", timeout=30.0, # max seconds to wait for LLM response fallback_rules=[ # used when the LLM call fails RetryRule(exception=ConnectionError, action=RetryAction.RETRY, retry_delay=timedelta(seconds=10)), RetryRule(exception=PermissionError, action=RetryAction.FAIL), ], ) @task(retries=5, retry_policy=llm_policy) def call_external_api(): ... How it works¶ When a task fails, either policy: Sends the exception’s class name and message to the configured LLM, or the formatted traceback with include_traceback=True (see Sending the traceback). By default, the text is first masked through Airflow’s secrets masker (see redactor below) and truncated to max_exception_length characters before it is added to the prompt. With LLMRetryPolicy, the model returns an ErrorClassification: a category, whether to retry, a suggested delay, and its reasoning. With ClassifierRetryPolicy, it picks one of the names in categories; it sees each category’s name and description in the output schema and cannot answer with a name outside the set. The policy returns RETRY or FAIL. For LLMRetryPolicy that is the model’s should_retry and suggested_delay_seconds. For ClassifierRetryPolicy it is the picked category’s retry and delay, unless the policy has a confidence bar and the answer is under it, in which case the answer is discarded (see Confidence below). The decision is logged in the task logs and written to the task instance’s retry_reason, on a FAIL as well as a RETRY: <category>: <reasoning> from LLMRetryPolicy, or one line such as category=network confidence=0.91 threshold=0.60 action=retry delay=10s from ClassifierRetryPolicy. From Airflow 3.4 the REST API exposes it as state_reason on a task instance and on each try, and the Task Instance page shows it under Reason for state while the task is failed or up for retry. This classification call is a separate model request, made by the policy itself rather than by an operator – it is not subject to an operator’s usage_limits, and it runs on every task failure regardless of any cost cap configured on the failing task. It is bounded by timeout and max_exception_length, but not by a cost limit. If the model call fails (provider down, timeout, bad credentials), the policy falls back to fallback_rules if configured, or to the task’s standard retry behaviour. ClassifierRetryPolicy does the same when the model cannot produce one of the categories even after pydantic-ai re-prompts it, or when its answer is under the confidence bar, after consulting fallback_policy if set; its fallback decision’s reason then starts with classifier answer not applied (model_error), (below_threshold) or (missing_confidence) so a retry_reason read later is not mistaken for a classifier decision or a plain rule match. LLMRetryPolicy’s fallback decision is what fallback_rules returned, as it always was. This policy decides between attempts. Failing over to another vendor within an attempt is a separate mechanism on the connection; see Provider fallback, which also sets out how the two layers compose. ClassifierRetryPolicy¶ ClassifierRetryPolicy takes the retry decision away from the model. Its categories maps a category name to an ErrorCategory: what failures belong there (the description the model reads), whether it is retried, after what delay, and how sure the model has to be (min_confidence, covered below). Everything the model is told about a category, and everything the policy does with it, sits in that one entry, so the two cannot drift apart. This is also the policy a decision model needs: such a model refuses the free-text fields of ErrorClassification, so an LLMRetryPolicy pointed at one fails every classification and falls back, with a log line saying to use ClassifierRetryPolicy. DEFAULT_CATEGORIES is the default: the same seven categories the LLM policy’s default instructions describe, with the same retry/fail split and delays: Category What belongs there Action rate_limit API throttling or a quota exceeded. Retry after 60s network Transient connectivity issue: connection reset, DNS, TLS handshake. Retry after 10s transient Temporary issue likely to resolve on its own. Retry after 30s auth Credentials invalid, expired, or missing permissions. Fail data Schema validation, type mismatch, or bad input data. Fail resource Resource not found or unavailable, such as a missing table or bucket. Fail permanent Problem that will not resolve without a code or configuration change. Fail Pass your own to change any of it. It replaces the default rather than merging into it, so include every category you want offered – or spread the default and edit what you need: from dataclasses import replace from datetime import timedelta from airflow.providers.common.ai.policies.retry import ( ClassifierRetryPolicy, DEFAULT_CATEGORIES, ErrorCategory, ) ClassifierRetryPolicy( llm_conn_id="pydanticai_default", categories={ **DEFAULT_CATEGORIES, # The table is created upstream, so a missing one is worth another look. "resource": replace(DEFAULT_CATEGORIES["resource"], retry=True, delay=timedelta(minutes=5)), }, ) Or write a taxonomy for your stack. A Snowflake pipeline has kinds of failure the seven defaults can only approximate, and naming them is what lets the policy act on them differently: SNOWFLAKE_CATEGORIES = { "queued": ErrorCategory( "Statement queued or a concurrency limit reached; the warehouse is busy.", delay=timedelta(seconds=120), ), "warehouse_suspended": ErrorCategory( "The warehouse is suspended and will auto-resume.", delay=timedelta(seconds=30) ), "token_expired": ErrorCategory( "A JWT or session token expired; the token rotates on its own.", delay=timedelta(seconds=30) ), "schema_drift": ErrorCategory( "A referenced column, table or view does not exist; a person has to fix the schema.", retry=False, ), } snowflake_policy = ClassifierRetryPolicy(llm_conn_id="pydanticai_default", categories=SNOWFLAKE_CATEGORIES) Write descriptions as the boundary between categories: what belongs here and what does not. That is the whole of what the model reads about a category; the name alone gives it very little, and two categories with similar names and no descriptions are indistinguishable to it. A pick is relative: the model chooses the best fit among the categories offered, not whether any fits. If “none of these” or “not enough in the message to tell” is a real outcome for your pipeline, add a category for it (retry=True with no delay keeps the task’s own behaviour) rather than hoping the model refuses. When you change a description or the set of categories, treat the confidence values you measured before as stale: the distribution the model returns is over the options it was given. A delay is timedelta, not seconds, and is used as-is: a task’s own max_retry_delay does not clamp it. delay=None (the default) means no override, so the task’s own retry_delay / retry_exponential_backoff / max_retry_delay apply instead (see Tasks). retry=False ends the task straight away even when attempts were left, so a wrong classification into such a category costs the task the retries it would otherwise have had; that is what the confidence bar below is for. A bare int delay, a negati