<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrii Roiko on Medium]]></title>
        <description><![CDATA[Stories by Andrii Roiko on Medium]]></description>
        <link>https://medium.com/@roykoand?source=rss-8d42747e4465------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rSy0ffg-i32tlSarGzxgzQ.jpeg</url>
            <title>Stories by Andrii Roiko on Medium</title>
            <link>https://medium.com/@roykoand?source=rss-8d42747e4465------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:08:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roykoand/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Airflow Common AI 1.0 in Practice: Agents, Tools and Approvals, with Examples]]></title>
            <link>https://medium.com/@roykoand/airflow-common-ai-1-0-in-practice-agents-tools-and-approvals-with-examples-61e1bbdf71fc?source=rss-8d42747e4465------2</link>
            <guid isPermaLink="false">https://medium.com/p/61e1bbdf71fc</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <dc:creator><![CDATA[Andrii Roiko]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 16:07:13 GMT</pubDate>
            <atom:updated>2026-11-21T16:07:13.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsMx9A8DgyUQ78n50xStlg.png" /></figure><p>More and more data pipelines include an AI step: classifying records, pulling fields out of documents, summarizing reports or running an agent that queries other systems. Doing that well takes more than an API call: credentials, retries, cost limits and a way for a person to review risky actions.</p><p>The <strong>Common AI</strong> (apache-airflow-providers-common-ai) provider brings that step into Airflow itself and as of 1.0 it&#39;s officially stable. The idea fits in one sentence: <strong>an AI call should be just another Airflow task.</strong> It gets scheduled, retried, logged, approved and monitored like everything else in your pipeline.</p><p>Under the hood, Common AI is built on Pydantic AI, an open-source agent framework from the team behind Pydantic. It gives one interface to Claude, GPT, Gemini, Bedrock, Ollama and many other models, validates their output into typed Python objects and runs the tool-calling loop that agents need. Common AI layers Airflow on top of that: API keys stay in Airflow connections and never reach the model, risky actions can wait for human approval, retries can tell a rate limit from a revoked key, and a crashed agent resumes from its last completed step instead of paying for the same tokens twice.</p><p>This guide goes from a single model call to a production-ready agent, step by step, and ends with real pipelines you can adapt.</p><h3>Level 0: Setup (30 seconds, promise)</h3><pre>pip install &#39;apache-airflow-providers-common-ai[anthropic]&#39;   # or [openai], [google], [bedrock]</pre><p>In the Airflow UI, add a connection called pydanticai_default of type <strong>Pydantic AI</strong>, paste your API key, and set the model to anthropic:claude-sonnet-5-5. The model lives in the connection, not your code, so switching from Sonnet to Haiku (or to another vendor entirely) never touches a Dag. Works on Airflow 2.11 and up.</p><h3>Level 1: Ask a question, get real data back</h3><p>The simplest building block is @task.llm. Your function returns a prompt — the decorator sends it to the model. Hand it a Pydantic model as output_type, and the next task receives validated, typed data instead of a chatty paragraph you have to regex your way through.</p><pre>from pydantic import BaseModel<br>from airflow.providers.common.compat.sdk import dag, task<br><br>class Triage(BaseModel):<br>    category: str<br>    urgency: str<br>    summary: str<br><br>@dag(schedule=None)<br>def support_inbox():<br>    @task.llm(<br>        llm_conn_id=&quot;pydanticai_default&quot;,<br>        system_prompt=&quot;Classify support tickets by category and urgency.&quot;,<br>        output_type=Triage,<br>    )<br>    <br>    def triage(ticket: str) -&gt; str:<br>        return ticket  # the return value is the prompt<br>    <br>    @task<br>    def page_someone(t: dict):<br>        print(f&quot;Waking up the {t[&#39;category&#39;]} team. Urgency: {t[&#39;urgency&#39;]}&quot;)<br>    page_someone(triage(&quot;Invoice exports have been broken since yesterday&#39;s deploy.&quot;))<br><br>support_inbox()</pre><p>It has siblings for common chores: @task.llm_sql turns plain English into validated SQL (without running it), @task.llm_file_analysis reads files on object storage, PDFs and images included, and @task.llm_schema_compare spots schema drift before your pager does.</p><h3>Level 2: Let it make the call</h3><p>Pipelines are full of forks in the road. @task.llm_branch is a branch operator with opinions: the model reads the input and picks which downstream task(s) run. The rest are skipped, exactly like a normal branch.</p><pre>@task.llm_branch(<br>    llm_conn_id=&quot;pydanticai_default&quot;,<br>    system_prompt=&quot;Route the review to the right team.&quot;,<br>)<br>def pick_team(review: str) -&gt; str:<br>    return review<br><br>pick_team(&quot;Box arrived crushed, but the cake survived.&quot;) &gt;&gt; [refunds(), shipping(), say_thanks()]</pre><p>For small decisions made thousands of times a day, a full LLM is overkill. Meet <strong>Jev</strong> by TypeSafe, the model that refuses to write sentences. It’s a decision model: you give it text and a typed question and it answers with one option from your list plus a confidence score, in a few hundred milliseconds. Ask it for prose and the request is refused before it leaves your worker.</p><pre>from typing import Literal<br>from airflow.providers.common.ai.hooks.pydantic_ai import PydanticAIHook<br><br>@task<br>def why_did_it_fail(log_line: str) -&gt; str:<br>    agent = PydanticAIHook(llm_conn_id=&quot;jev_default&quot;).create_agent(<br>        output_type=Literal[&quot;transient&quot;, &quot;resource&quot;, &quot;permanent&quot;],<br>        instructions=&quot;Classify why this Airflow task failed.&quot;,<br>    )<br>    return agent.run_sync(log_line).output</pre><p>Setup is pip install &#39;apache-airflow-providers-common-ai[typesafe]&#39; plus a connection with {&quot;model&quot;: &quot;typesafe:jev-1.13.0&quot;}. Pin that version: a confidence threshold you tuned on one release may not mean the same thing on the next.</p><p>Every Jev answer includes a confidence score and a DecisionPolicy lets you act on it. Set a minimum confidence on a branch task: answers above it route automatically, and answers below it pause the task for human review instead of guessing. The review form shows the input, the proposed branch, its confidence compared with the threshold, and the probability of each option, with Approve and Reject buttons.</p><pre>@task.llm_branch(<br>    llm_conn_id=&quot;jev_default&quot;,<br>    decision_policy=DecisionPolicy(min_confidence=0.9, on_uncertain=&quot;review&quot;),<br>)<br>def route_ticket(ticket: str) -&gt; str:<br>    return ticket</pre><p>That’s a pipeline that knows when it doesn’t know. It works with any model the provider supports, not just Jev, and it’s still marked experimental in 1.0.</p><h3>Level 3: Give it hands</h3><p>An agent is a model that can use tools in a loop: look something up, read the result, decide what to do next. In Common AI that’s AgentOperator (or @task.agent), and the fun part is where the tools come from: <strong>the Airflow connections you already have.</strong></p><p>HookToolset turns methods of any Airflow hook into agent tools. The credential never leaves the task, secrets that sneak into tool output are masked as *** before the model sees them and pinned_arguments glues down values the model isn&#39;t allowed to choose.</p><pre>from airflow.providers.amazon.aws.hooks.s3 import S3Hook<br>from airflow.providers.common.ai.operators.agent import AgentOperator<br>from airflow.providers.common.ai.toolsets.hook import HookToolset<br><br>AgentOperator(<br>    task_id=&quot;finance_digest&quot;,<br>    prompt=&quot;Summarize the September finance report in 5 bullets.&quot;,<br>    llm_conn_id=&quot;pydanticai_default&quot;,<br>    toolsets=[<br>        HookToolset(<br>            S3Hook(aws_conn_id=&quot;aws_reports_reader&quot;),<br>            allowed_methods=[&quot;list_keys&quot;, &quot;read_key&quot;],<br>            pinned_arguments={&quot;bucket_name&quot;: &quot;acme-reports&quot;},  # no bucket tourism<br>            tool_prefix=&quot;s3&quot;,<br>        )<br>    ],<br>)</pre><p>Prefer databases? SQLToolset enforces a table allowlist on every query and caps the rows. When a query fails, the error goes back to the agent, which fixes its own typo and tries again instead of crashing your task.</p><pre>from airflow.providers.common.ai.toolsets.sql import SQLToolset<br><br>AgentOperator(<br>    task_id=&quot;why_did_revenue_dip&quot;,<br>    prompt=&quot;Revenue for {{ ds }} dropped 12%. Find out why.&quot;,<br>    llm_conn_id=&quot;pydanticai_default&quot;,<br>    toolsets=[SQLToolset(db_conn_id=&quot;warehouse&quot;, allowed_tables=[&quot;analytics.orders&quot;], max_rows=500)],<br>)</pre><p>No warehouse at all? DataFusionToolset lets an agent run SQL straight over Parquet, CSV or Avro files sitting in object storage, or over Iceberg tables, without loading them anywhere first. Register several sources and the agent can even join across them.</p><pre>from airflow.providers.common.ai.toolsets.datafusion import DataFusionToolset<br>from airflow.providers.common.sql.config import DataSourceConfig<br><br>lake = DataFusionToolset(<br>    datasource_configs=[<br>        DataSourceConfig(conn_id=&quot;aws_default&quot;, table_name=&quot;clicks&quot;, uri=&quot;s3://lake/clicks/&quot;, format=&quot;parquet&quot;),<br>        DataSourceConfig(conn_id=&quot;aws_default&quot;, table_name=&quot;signups&quot;, uri=&quot;s3://lake/signups/&quot;, format=&quot;csv&quot;),<br>    ],<br>    max_rows=100,<br>)</pre><p>Speed trick: add capabilities=[CodeMode()] (from pydantic_ai_harness, install the [code-mode] extra) and instead of a dozen tool-call round trips, the model writes one small Python script that calls the tools itself, loops and all.</p><h3>Level 4: Keep it on a leash</h3><p>An agent with hands is great until it uses them on a production table. Common AI 1.0 ships three leashes.</p><p><strong>It asks “may I?”</strong> Mark risky tools as needing approval. When the agent reaches for one, the task pauses without holding a worker slot, and the exact call (tool name and arguments) shows up on the task’s <strong>Required Actions</strong> page. Approve and it runs. Reject and the agent is told “no” and has to find another way, like a toddler at a cookie jar. Nothing is ever auto-approved because someone went to lunch. Needs Airflow 3.3+.</p><pre>from datetime import timedelta<br>from pydantic_ai.toolsets import FunctionToolset<br><br>shop = FunctionToolset(tools=[lookup_order, refund_order]).approval_required(<br>    lambda ctx, tool_def, args: tool_def.name == &quot;refund_order&quot;<br>)<br>AgentOperator(<br>    task_id=&quot;handle_ticket&quot;,<br>    llm_conn_id=&quot;pydanticai_default&quot;,<br>    prompt=&quot;Order 7 never arrived. Sort it out.&quot;,<br>    toolsets=[shop],<br>    tool_approval_timeout=timedelta(hours=4),<br>)</pre><p><strong>It gets its own throwaway computer.</strong> Agents doing open-ended analysis write code, and that code shouldn’t run on your Airflow worker. SandboxToolset gives the model a disposable workspace with no internet by default. It&#39;s created on the first tool call and destroyed when the run ends.</p><pre>from airflow.providers.common.ai.toolsets.sandbox import SandboxToolset<br><br>AgentOperator(<br>    task_id=&quot;investigate&quot;,<br>    prompt=&quot;Revenue for {{ ds }} moved more than 10%. Dig in and explain why.&quot;,<br>    llm_conn_id=&quot;pydanticai_default&quot;,<br>    toolsets=[<br>        SQLToolset(db_conn_id=&quot;warehouse&quot;, allowed_tables=[&quot;analytics.orders&quot;], max_rows=500),<br>        SandboxToolset(<br>            SbxSandboxBackend(image=&quot;python:3.12-slim&quot;, host_network_policy=&quot;deny-all&quot;),<br>            spec=SandboxSpec(block_network=True),<br>        ),<br>    ],<br>)</pre><p><strong>It has an allowance.</strong> usage_limits caps tokens and requests on every LLM and agent operator, so a chatty agent can&#39;t quietly run up the bill.</p><h3>Level 5: Survive production</h3><p>This is where living inside an orchestrator really pays off.</p><p><strong>Crash on step ten, pay for one step.</strong> With durable=True, every model response and tool result is saved as it finishes. When the task retries, the finished steps replay for free and only the missing ones make live calls. Zero setup on Airflow 3.3+.</p><pre>AgentOperator(<br>    task_id=&quot;quarterly_analyst&quot;,<br>    prompt=&quot;Analyze quarterly trends across all regions.&quot;,<br>    llm_conn_id=&quot;pydanticai_default&quot;,<br>    toolsets=[SQLToolset(db_conn_id=&quot;warehouse&quot;)],<br>    durable=True,<br>    retries=3,<br>)</pre><p><strong>Retries that read the stack trace.</strong> Classic retries are polite but clueless: a revoked API key gets retried five times. LLMRetryPolicy shows the exception to a model, which decides whether to wait and retry or give up right away. Secrets are scrubbed from the error first. Its cheaper cousin, ClassifierRetryPolicy, puts Jev in front and only asks an LLM when Jev isn&#39;t sure. Needs Airflow 3.3+.</p><pre>from airflow.providers.common.ai.policies.retry import LLMRetryPolicy<br><br>@task(retries=5, retry_policy=LLMRetryPolicy(llm_conn_id=&quot;pydanticai_default&quot;, timeout=30.0))<br>def call_partner_api(): ...</pre><p><strong>A plan B for your model.</strong> Add fallback_conn_ids=[&quot;claude_on_bedrock&quot;] to any LLM task and it fails over to another connection (say, the same Claude served through AWS Bedrock) when the primary has a bad day.</p><p><strong>Half-price bulk jobs.</strong> @task.llm_batch sends thousands of prompts as one Anthropic (or OpenAI) batch job at 50% of normal prices. The sneaky part: if the task retries with the same inputs, it reattaches to the batch it already submitted instead of paying twice.</p><h3>Level 6: Steal these pipelines</h3><p>Enough tricks. Here’s what they look like glued together into things you could actually ship this week.</p><p><strong>The 6 a.m. data detective.</strong> A sensor notices revenue moved more than 10%. An agent with SQLToolset and a SandboxToolset digs through the warehouse, crunches numbers in its scratch computer, and returns a typed Findings object. You read the explanation with your coffee instead of writing the query yourself.</p><p><strong>The schema bouncer.</strong> Before every load, @task.llm_schema_compare checks the upstream source against the warehouse. If a column quietly changed type, a branch pages the data team instead of loading garbage. The bouncer doesn&#39;t let anyone in without a matching schema.</p><p><strong>The invoice whisperer.</strong> @task.llm_file_analysis reads PDF and image invoices from S3 and returns an Invoice model with vendor, total and due date, ready to insert as rows. Got a backlog of old invoices? Push them through @task.llm_batch overnight at half price.</p><p><strong>The catalog glow-up.</strong> A nightly @task.llm_batch job rewrites thousands of dull product descriptions in your brand voice. If the worker dies halfway, the retry reattaches to the batch already running, so you never pay for the same glow-up twice.</p><p><strong>Ask the warehouse.</strong> People type questions in plain English; @task.llm_sql turns them into validated SQL. With require_approval=True, an analyst glances at the query before anything runs. Junior analysts love it; senior analysts love not being asked for the hundredth time.</p><p><strong>The on-call sidekick.</strong> Put ClassifierRetryPolicy on every flaky API task. Rate limits wait politely, revoked keys fail immediately, and a weekly @task.llm summarizes why things broke, so the on-call handoff writes itself.</p><p><strong>Release notes that write themselves.</strong> A HookToolset over your Git hosting hook reads merged PRs, @task.llm turns them into release notes in your house style, and allow_modifications=True lets a human polish the draft before it ships.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61e1bbdf71fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python 3.15: An Overview of What’s New]]></title>
            <link>https://medium.com/@roykoand/python-3-15-an-overview-of-whats-new-4ec14306513e?source=rss-8d42747e4465------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ec14306513e</guid>
            <category><![CDATA[python-libraries]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Andrii Roiko]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 18:32:05 GMT</pubDate>
            <atom:updated>2026-10-12T18:40:20.293Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lazy imports, frozendict, a built-in sampling profiler and the other changes worth your time</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3Jeu_Jg5l6YW5j5XRA-fQ.png" /></figure><p>Python 3.15 came out on October 9, 2026 and it’s packed with useful changes: lazy imports that load modules only when you actually use them, a built-in sampling profiler that attaches to programs that are already running, a frozen dictionary, a proper way to say “no value was passed”, unpacking inside comprehensions, UTF-8 as the default encoding everywhere, friendlier error messages and noticeable speedups across the standard library.</p><p>Each section below covers one change, with a short example and where you’d use it.</p><h3>1. lazy import: Procrastination, Now a Language Feature (<a href="https://peps.python.org/pep-0810/">PEP 810</a>)</h3><p>Normally every import runs immediately, even if your CLI only needs pandas for one rarely used command. A lazy import binds the name now and does the real import the first time you <em>use</em> it.</p><pre>import sys<br>lazy import pandas as pd<br><br>def export_report(rows):<br>    return pd.DataFrame(rows).to_csv(index=False)<br><br>print(&quot;pandas loaded at startup?&quot;, &quot;pandas&quot; in sys.modules)<br>print(export_report([{&quot;city&quot;: &quot;Lviv&quot;, &quot;temp&quot;: 18}, {&quot;city&quot;: &quot;Oslo&quot;, &quot;temp&quot;: 9}]), end=&quot;&quot;)<br>print(&quot;pandas loaded now?&quot;, &quot;pandas&quot; in sys.modules)</pre><pre>pandas loaded at startup? False<br>city,temp<br>Lviv,18<br>Oslo,9<br>pandas loaded now? True</pre><h3>Turning it on everywhere</h3><pre>python -X lazy_imports=all my_cli.py      # or PYTHON_LAZY_IMPORTS=all</pre><p>Supporting older Pythons too? __lazy_modules__ = [&quot;json&quot;, &quot;pathlib&quot;] makes those imports lazy on 3.15 and is simply ignored on 3.14.</p><p>lazy only works at module level: inside a function, class or try block you get a clear SyntaxError (e.g. lazy import not allowed inside functions).</p><p><strong>Use it for:</strong> CLIs, serverless cold starts, test suites and annotation-only imports (they never load at runtime, so some if TYPE_CHECKING: blocks can go).</p><h3>2. frozendict: The Dictionary That Says &quot;No&quot; (<a href="https://peps.python.org/pep-0814/">PEP 814</a>)</h3><p>Sets have frozenset, lists have tuples and dicts finally have frozendict, a builtin.</p><pre>&gt;&gt;&gt; defaults = frozendict(theme=&quot;light&quot;, autosave=True)<br>&gt;&gt;&gt; defaults[&quot;theme&quot;] = &quot;dark&quot;<br>TypeError: &#39;frozendict&#39; object does not support item assignment<br>&gt;&gt;&gt; defaults | {&quot;theme&quot;: &quot;dark&quot;}             # merging returns a NEW frozendict<br>frozendict({&#39;theme&#39;: &#39;dark&#39;, &#39;autosave&#39;: True})</pre><p>It’s hashable, so it finally works with caches:</p><pre>from functools import cache<br><br>@cache<br>def price_for(options):<br>    return 100 + 10 * len(options)<br><br>price_for({&quot;color&quot;: &quot;red&quot;})                          # TypeError: unhashable type: &#39;dict&#39;<br>print(price_for(frozendict(color=&quot;red&quot;, size=&quot;L&quot;)))  # 120</pre><p>Combine it with the new array_hook in json.loads() for fully immutable config:</p><pre>import json<br>raw = &#39;{&quot;servers&quot;: [{&quot;host&quot;: &quot;a&quot;}, {&quot;host&quot;: &quot;b&quot;}], &quot;retries&quot;: 3}&#39;<br>print(json.loads(raw, object_pairs_hook=frozendict, array_hook=tuple))<br># frozendict({&#39;servers&#39;: (frozendict({&#39;host&#39;: &#39;a&#39;}), frozendict({&#39;host&#39;: &#39;b&#39;})), &#39;retries&#39;: 3})</pre><p><strong>Gotcha:</strong> it’s <em>not</em> a dict subclass, so isinstance(fd, dict) is False. Check against collections.abc.Mapping instead.</p><h3>3. sentinel: A Proper Name for &quot;Nothing Was Passed&quot; (<a href="https://peps.python.org/pep-0661/">PEP 661</a>)</h3><p>Goodbye _MISSING = object() and its useless &lt;object object at 0x7fc31469c5b0&gt; repr:</p><pre>MISSING = sentinel(&quot;MISSING&quot;)<br><br>def get_option(options, name, default=MISSING):<br>    value = options.get(name, default)<br>    if value is MISSING:<br>        raise KeyError(name)<br>    return value<br><br>print(get_option({&quot;retries&quot;: None}, &quot;retries&quot;))   # None  (a real value!)<br>get_option({}, &quot;timeout&quot;)                         # KeyError: &#39;timeout&#39;</pre><p>It has a readable repr (MISSING), survives copy, deepcopy and pickling, and works in type hints. Both mypy and Pyright narrow it correctly:</p><pre>def connect(timeout: float | None | MISSING = MISSING) -&gt; None:<br>    if timeout is MISSING:<br>        timeout = 30.0<br>    reveal_type(timeout)        # float | None</pre><p>Perfect for PATCH-style APIs where “set to null” and “don’t touch” mean different things. Define each sentinel once at module level; every sentinel(&quot;MISSING&quot;) call creates a new object.</p><h3>4. Unpacking in Comprehensions (<a href="https://peps.python.org/pep-0798/">PEP 798</a>)</h3><p>* and ** now work inside comprehensions:</p><pre>&gt;&gt;&gt; [*L for L in [[1, 2], [3, 4], [5]]]<br>[1, 2, 3, 4, 5]<br>&gt;&gt;&gt; {*s for s in [{1, 2}, {2, 3}, {3, 4}]}<br>{1, 2, 3, 4}<br>&gt;&gt;&gt; layers = [{&quot;host&quot;: &quot;localhost&quot;, &quot;port&quot;: 8000}, {&quot;port&quot;: 5432}, {&quot;debug&quot;: True}]<br>&gt;&gt;&gt; {**layer for layer in layers}    # later keys win<br>{&#39;host&#39;: &#39;localhost&#39;, &#39;port&#39;: 5432, &#39;debug&#39;: True}</pre><p>So this:</p><pre>all_tags = set(chain.from_iterable(post.tags for post in posts))</pre><p>becomes this:</p><pre>all_tags = {*post.tags for post in posts}</pre><p>Great for flattening paginated API results and merging layered config.</p><h3>5. Tachyon: A Profiler That Attaches to Running Processes (<a href="https://peps.python.org/pep-0799/">PEP 799</a>)</h3><p>The new profiling.sampling module, nicknamed Tachyon, samples your program from the <em>outside</em>, so it barely slows it down. It can even attach to a program that&#39;s already running, without restarting it.</p><p>The quickest way to see where the time goes is a flame graph:</p><pre>python -m profiling.sampling run --flamegraph -o profile.html script.py</pre><p>Here’s a screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMgr8JSvQa4Dwy7z7YZF9g.png" /></figure><p>To watch a running program live, like top, use its process ID:</p><pre>python -m profiling.sampling attach --live 12345</pre><p>And if a program seems stuck, this shows what every thread is doing right now:</p><pre>python -m profiling.sampling dump -a 12345</pre><p>(cProfile still works and now also lives at profiling.tracing)</p><h3>6. UTF-8 by Default (<a href="https://peps.python.org/pep-0686/">PEP 686</a>)</h3><p>open() without encoding= now uses UTF-8 everywhere instead of the system locale. On a real Latin-1 machine:</p><pre># menu.txt contains: Crème brûlée — 7 €<br>&gt;&gt;&gt; open(&quot;menu.txt&quot;).read()        # Python 3.14<br>&#39;CrÃ¨me brÃ»lÃ©e â\x80\x94 7 â\x82¬\n&#39;<br>&gt;&gt;&gt; open(&quot;menu.txt&quot;).read()        # Python 3.15<br>&#39;Crème brûlée — 7 €\n&#39;</pre><p>The flip side: old files written in a legacy encoding may now fail.</p><pre>&gt;&gt;&gt; open(&quot;legacy_report.txt&quot;).read()<br>UnicodeDecodeError: &#39;utf-8&#39; codec can&#39;t decode byte 0xe9 in position 3: invalid continuation byte<br>&gt;&gt;&gt; open(&quot;legacy_report.txt&quot;, encoding=&quot;cp1252&quot;).read()<br>&#39;Café € 5\n&#39;</pre><p>To find risky calls, run python -X warn_default_encoding app.py. For an emergency escape hatch, use PYTHONUTF8=0 (or encoding=&quot;locale&quot; per call).</p><h3>7. Typing Improvements</h3><p><strong>TypeForm (</strong><a href="https://peps.python.org/pep-0747/"><strong>PEP 747</strong></a><strong>)</strong> lets functions accept any type expression, not just classes:</p><pre>from typing import TypeForm<br><br>def env[T](name: str, typ: TypeForm[T]) -&gt; T:<br>    raise NotImplementedError   # parsing code skipped<br><br>port = env(&quot;PORT&quot;, int)                  # type checker sees: int<br>timeout = env(&quot;TIMEOUT&quot;, float | None)   # type checker sees: float | None</pre><p><strong>Closed </strong><strong>TypedDicts (</strong><a href="https://peps.python.org/pep-0728/"><strong>PEP 728</strong></a><strong>)</strong> reject or constrain extra keys:</p><pre>class Movie(TypedDict, closed=True):         # no extra keys allowed<br>    title: str<br>    year: int<br><br>class Headers(TypedDict, extra_items=str):   # extra keys OK, values must be str<br>    content_type: str</pre><p>Pyright supports both. mypy 2.4.0 handles closed=True but still rejects extra_items.</p><h3>8. Error Messages That Speak JavaScript</h3><pre>&gt;&gt;&gt; [1, 2, 3].push(4)<br>AttributeError: &#39;list&#39; object has no attribute &#39;push&#39;. Did you mean &#39;.append&#39;?<br>&gt;&gt;&gt; &#39;hello&#39;.toUpperCase()<br>AttributeError: &#39;str&#39; object has no attribute &#39;toUpperCase&#39;. Did you mean &#39;.upper&#39;?<br>&gt;&gt;&gt; {}.put(&quot;a&quot;, 1)<br>AttributeError: &#39;dict&#39; object has no attribute &#39;put&#39;. Use d[k] = v.<br>&gt;&gt;&gt; container.area<br>AttributeError: &#39;Container&#39; object has no attribute &#39;area&#39;. Did you mean &#39;.inner.area&#39; instead of &#39;.area&#39;?<br>&gt;&gt;&gt; pip install requests<br>SyntaxError: invalid syntax<br>The Python package manager (pip) can only be used outside of the Python REPL.</pre><p>argparse now suggests fixes by default too:</p><pre>deploy: error: argument env: invalid choice: &#39;prodution&#39;, maybe you meant &#39;production&#39;? (choose from &#39;staging&#39;, &#39;production&#39;)</pre><h3>9. Speed</h3><ul><li><strong>Windows:</strong> the official builds use a faster interpreter, 15–20% faster on average (up to 40% for small scripts), with no code changes. (<a href="https://docs.python.org/3/whatsnew/3.15.html#whatsnew315-windows-tail-calling-interpreter">What’s New</a>, <a href="https://fidget-spinner.github.io/posts/no-longer-sorry.html">Ken Jin’s write-up</a>)</li><li><strong>JIT:</strong> about 7–8% faster on Linux and 11–12% on Apple-silicon Macs, but still experimental and off by default (PYTHON_JIT=1 to try it). (<a href="https://docs.python.org/3/whatsnew/3.15.html#upgraded-experimental-jit-compiler">What&#39;s New</a>)</li><li><strong>Standard library:</strong> base64 encodes 2× and decodes 3× faster, and csv.Sniffer is up to 1.6× faster. (<a href="https://docs.python.org/3/whatsnew/3.15.html#optimizations">What&#39;s New</a>)</li><li><strong>Startup:</strong> lazy imports (section 1) can cut it dramatically. (<a href="https://docs.python.org/3/whatsnew/3.15.html#whatsnew315-lazy-imports">What’s New</a>)</li></ul><h3>10. Small Things You’ll Use Weekly</h3><p><strong>Colorful REPL by default:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*RzwovuYcVtND-BwtGHj0dA.gif" /></figure><p><strong>Cancel a whole TaskGroup:</strong></p><pre>import asyncio<br><br>async def fetch(i):<br>    await asyncio.sleep(i * 0.1)<br>    return i<br><br>async def main():<br>    results = []<br>    async with asyncio.TaskGroup() as tg:<br>        async def worker(i):<br>            results.append(await fetch(i))<br>            if len(results) &gt;= 3:<br>                tg.cancel()            # got enough answers, stop the rest<br>        for i in range(10):<br>            tg.create_task(worker(i))<br>    print(results)                     # [0, 1, 2]<br><br>asyncio.run(main())</pre><p><strong>@contextmanager on a generator now actually wraps it:</strong></p><pre>from contextlib import contextmanager<br><br>@contextmanager<br>def logged(label):<br>    print(f&quot;enter {label}&quot;)<br>    yield<br>    print(f&quot;exit {label}&quot;)<br><br>@logged(&quot;reading&quot;)<br>def read_lines():<br>    yield &quot;first&quot;<br>    yield &quot;second&quot;<br><br>for line in read_lines():<br>    print(line)</pre><pre>Python 3.14.8:            Python 3.15.0:<br>enter reading             enter reading<br>exit reading              first<br>first                     second<br>second                    exit reading</pre><p><strong>Unicode-safe text with graphemes</strong>:</p><pre>&gt;&gt;&gt; import unicodedata<br>&gt;&gt;&gt; text = &quot;Hi 🇺🇦!&quot;<br>&gt;&gt;&gt; [str(g) for g in unicodedata.iter_graphemes(text)]<br>[&#39;H&#39;, &#39;i&#39;, &#39; &#39;, &#39;🇺🇦&#39;, &#39;!&#39;]<br>&gt;&gt;&gt; sum(1 for _ in unicodedata.iter_graphemes(text))<br>5</pre><p><strong>Thread-safe shared generators</strong>, handy with free-threading:</p><pre>import threading<br>from concurrent.futures import ThreadPoolExecutor<br><br>@threading.synchronized_iterator<br>def job_ids():<br>    for i in range(10_000):<br>        yield f&quot;job-{i}&quot;<br><br>jobs = job_ids()   # one generator shared by all workers<br><br>with ThreadPoolExecutor(max_workers=8) as pool:<br>    print(sum(pool.map(lambda _: sum(1 for _ in jobs), range(8))))   # 10000</pre><h3>Wrapping up</h3><p>Python 3.15 doesn’t have one giant headline feature. It fixes many small, long-standing annoyances instead: imports load when needed, dicts can freeze, “missing” has a name, text decodes the same everywhere, and you can profile production without restarting it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ec14306513e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airflow Tasks Used to Be Goldfish. Task/Asset Stores Gave Them a Memory.]]></title>
            <link>https://medium.com/@roykoand/airflow-tasks-used-to-be-goldfish-task-asset-stores-gave-them-a-memory-73733a657577?source=rss-8d42747e4465------2</link>
            <guid isPermaLink="false">https://medium.com/p/73733a657577</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Andrii Roiko]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 18:03:29 GMT</pubDate>
            <atom:updated>2026-10-02T18:21:38.182Z</atom:updated>
            <content:encoded><![CDATA[<h3>The goldfish problem</h3><p>It’s 3:07 AM. Your DAG launches an Athena query that scans 400 GB and takes 20 minutes. At minute 7, the worker is evicted. Airflow does exactly what you told it to — it retries.</p><p>The retry wakes up with no idea that a healthy query is still running and almost done. So it starts a brand-new one. You now pay for two identical scans of the same 400 GB.</p><p>For years, Airflow tasks have been goldfish: every attempt starts with a blank memory. We worked around it with XCom tricks, Variables abused as a key-value store or a DynamoDB table added “temporarily” in 2022 that is still there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuVn_2p1VYJJVWUuZRQ0YQ@2x.png" /></figure><p><a href="https://airflow.apache.org/blog/airflow-3.3.0/">Airflow 3.3</a>, released July 6, 2026, gives tasks a real memory: the task and asset state stores. This article covers how they work and walks through four examples.</p><h3>How the task state store works</h3><p>It’s a key-value store attached to one task instance:</p><ul><li><strong>Scope:</strong> dag_id + run_id + task_id + map_index.</li><li><strong>Survives:</strong> worker crashes and retries in the same DAG run.</li><li><strong>Expires:</strong> after retention, never with NEVER_EXPIRE or after 30 days by default.</li><li><strong>Use it for:</strong> job IDs, checkpoints and progress.</li></ul><p>It has four methods: get, set, delete and clear. Async versions (aget, aset and so on) exist too. Values must be JSON-compatible and None raises a ValueError.</p><p>Get it from the context or let TaskFlow inject it:</p><pre>@task(retries=3)<br>def load(task_state_store=None):<br>    done = task_state_store.get(&quot;done&quot;, default=0)</pre><p>Values live in the metadata database by default. You can move them to S3 or a custom backend (see <em>Cleanup and configuration</em>).</p><p>The docs call this <strong>durable execution</strong>: a task that survives the process running it. It doesn’t replace XCom. XCom is cleared on retry and it’s still the tool for passing data between tasks.</p><h3>What it doesn’t promise</h3><p>Airflow was always durable <strong><em>between</em></strong> tasks. 3.3 adds durability <strong><em>inside</em></strong> a task. It has two limits:</p><ul><li><strong>A crash isn’t free.</strong> You still redo the work that was in flight.</li><li><strong>It’s at-least-once, not exactly-once.</strong> If the worker dies between an external call and set, the call may repeat. Make side effects safe to repeat.</li></ul><h3>Check first: your operators may already do this</h3><p>Before you write code, check your operators. Many providers already save the job ID and reattach on retry. Their durable flag defaults to True:</p><ul><li>SparkSubmitOperator (Apache Spark 6.2.0+): driver or application ID.</li><li>KubernetesPodOperator (CNCF Kubernetes 10.20.0+): pod name and namespace.</li><li>EksPodOperator and GKEStartPodOperator: inherit the same behaviour from KubernetesPodOperator, so they also need CNCF Kubernetes 10.20.0+.</li><li>BigQueryInsertJobOperator (Google 22.3.0+): job ID.</li><li>DatabricksSubmitRunOperator, DatabricksRunNowOperator (Databricks 7.17.0+): run ID.</li><li>SnowflakeSqlApiOperator (Snowflake 6.15.0+): statement handles.</li><li>RedshiftDataOperator (Amazon 9.34.0+): statement ID.</li><li>GlueJobOperator (Amazon 9.35.0+): job run ID.</li><li>LivyOperator (Apache Livy 4.6.0+): batch ID.</li></ul><p>One exception to the default: AgentOperator and @task.agent from the Common AI provider are opt-in. With durable=True, they cache each model response and tool result, so a retry replays finished steps instead of paying for them again. Since Common AI 0.7.0 on Airflow 3.3, that cache lives in the task state store with no extra configuration.</p><p>Three notes:</p><ul><li><strong>Upgrade both.</strong> Before Airflow 3.3, durable does nothing.</li><li><strong>It replaces old flags,</strong> such as reattach_on_restart on the Kubernetes operator.</li><li><strong>It’s ignored with </strong><strong>deferrable=True.</strong> The triggerer already tracks the job.</li></ul><p>Athena isn’t on the list. That’s exactly why it makes a good first example: we’ll build the same protection by hand.</p><h3>Example 1 — Analytics: the Athena query you only pay for once</h3><p>Each duplicate costs real money. Athena charges $5 per TB scanned, so every extra 400 GB scan adds about $2. The duplicate also competes with the original query for the same workgroup capacity.</p><p>The fix rests on one fact. StartQueryExecution returns a QueryExecutionId within milliseconds, long before the query finishes. With that ID, a retry can call GetQueryExecution, see the query is still RUNNING and keep waiting. So the task writes the ID to the task state store under athena_query_id right after submitting, before it starts polling:</p><pre>import time<br>from datetime import timedelta<br><br>import boto3<br>from airflow.sdk import DAG, task<br><br><br>REPORT_SQL = &quot;&quot;&quot;<br>SELECT app, country, count(*) AS installs<br>FROM analytics.install_events<br>WHERE dt = date &#39;{{ ds }}&#39;<br>GROUP BY 1, 2<br>&quot;&quot;&quot;<br><br>with DAG(&quot;daily_installs_report&quot;, schedule=&quot;@daily&quot;):<br>    @task(retries=3, retry_delay=timedelta(minutes=1))<br>    def build_report(sql: str, **context) -&gt; str:<br>        store = context[&quot;task_state_store&quot;]<br>        athena = boto3.client(&quot;athena&quot;)<br>        query_id = store.get(&quot;athena_query_id&quot;)<br>        <br>        if query_id is None:<br>            query_id = athena.start_query_execution(<br>                QueryString=sql,<br>                WorkGroup=&quot;analytics&quot;,<br>            )[&quot;QueryExecutionId&quot;]<br>       <br>            # Remember it immediately: this is the only fragile moment.<br>            store.set(&quot;athena_query_id&quot;, query_id, retention=timedelta(days=1))<br>            print(f&quot;New query submitted: {query_id}&quot;)<br>        else:<br>            print(f&quot;Welcome back! Reattaching to {query_id}&quot;)<br>        <br>        while True:<br>            status = athena.get_query_execution(QueryExecutionId=query_id)<br>            state = status[&quot;QueryExecution&quot;][&quot;Status&quot;][&quot;State&quot;]<br>            <br>            if state == &quot;SUCCEEDED&quot;:<br>                return query_id<br>            <br>            if state in (&quot;FAILED&quot;, &quot;CANCELLED&quot;):<br>                # Forget the dead query so the next retry starts fresh.<br>                store.delete(&quot;athena_query_id&quot;)<br>                raise RuntimeError(f&quot;Athena query {query_id} ended as {state}&quot;)<br>            <br>            time.sleep(10)<br>    <br>    build_report(REPORT_SQL)</pre><p>On retry, the task asks Athena what happened to the query whose ID it saved:</p><ul><li><strong>QUEUED or </strong><strong>RUNNING:</strong> reattach and wait for the completion.</li><li><strong>SUCCEEDED:</strong> return at once.</li><li><strong>FAILED or </strong><strong>CANCELLED:</strong> delete the key, so the next attempt submits fresh.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ne_YOsulU7E3SMNYweTzog.png" /></figure><p><em>build_report succeeded on try 3. The query ID was saved before the earlier attempt crashed and it expires a day later.</em></p><p>One tiny window is still risky: the few milliseconds between Athena starting the query and the ID being saved. A crash there loses the ID and the retry submits a duplicate. Once the ID is saved, a crash at any point during polling is recoverable.</p><p>Athena happens to offer a fix for that last gap: a stable ClientRequestToken, such as a hash of dag_id, run_id and task_id. Many job APIs have no such option; EMR&#39;s AddJobFlowSteps, for example, takes no token at all. There, the alternatives are workarounds, like searching the cluster for a running step with the same name before submitting. The task state store is much simpler. For Athena alone, a stable token could do most of the job, but it has two limits. Athena doesn&#39;t document how long it remembers a token. And a reused token returns the same query ID, so after a failed query you&#39;d have to change the token to get a fresh one. With the stored ID, you just delete the key.</p><h3>Example 2 — API ingestion: surviving the rate limiter</h3><p>Paginated APIs fail halfway through. Say page 347 of 500 returns HTTP 429. Without a checkpoint, the retry starts at page 1 and hits the limit even sooner. With one, it picks up at page 347:</p><pre>from datetime import timedelta<br><br>import requests<br>from airflow.sdk import DAG, task<br><br>API_URL = &quot;https://api.example-ads.com/v2/campaign_stats&quot;<br><br>with DAG(&quot;ads_ingest&quot;, schedule=&quot;@daily&quot;):<br>    @task(retries=10, retry_delay=timedelta(minutes=5))<br>    def ingest_campaign_stats(**context):<br>        store = context[&quot;task_state_store&quot;]<br>        checkpoint = store.get(&quot;checkpoint&quot;, default={&quot;page&quot;: 0, &quot;cursor&quot;: None})<br>        page_no, cursor = checkpoint[&quot;page&quot;], checkpoint[&quot;cursor&quot;]<br>        <br>        if cursor:<br>            print(f&quot;Resuming at page {page_no + 1}. The rate limiter can wait.&quot;)<br>        <br>        while True:<br>            params = {&quot;date&quot;: context[&quot;ds&quot;]}<br>            <br>            if cursor:<br>                params[&quot;cursor&quot;] = cursor<br>            resp = requests.get(API_URL, params=params, timeout=30)<br>            resp.raise_for_status()  # a 429 fails the attempt; the retry resumes here<br>            body = resp.json()<br>            <br>            # Deterministic file name, so re-writing a page is harmless.<br>            write_page_to_s3(context[&quot;ds&quot;], page_no, body[&quot;data&quot;])<br>            page_no += 1<br>            cursor = body.get(&quot;next_cursor&quot;)<br><br>            if not cursor:<br>                store.delete(&quot;checkpoint&quot;)<br>                break<br><br>            # One set for both values, so page and cursor never disagree.<br>            store.set(&quot;checkpoint&quot;, {&quot;page&quot;: page_no, &quot;cursor&quot;: cursor})<br><br>    ingest_campaign_stats()</pre><p>After page 346, the store holds {&quot;page&quot;: 346, &quot;cursor&quot;: &quot;…&quot;}. When page 347 returns 429, the retry reads that checkpoint and sends the saved cursor, so the next request is page 347, not page 1.</p><p>The retry_delay of 5 minutes matters too. It gives the rate limiter time to reset before the retry asks for page 347 again. Retry too soon and you just get another 429.</p><p>Wherever the crash lands, the retry ends up in the right place:</p><ul><li><strong>During the request:</strong> nothing was saved for page 347, so the retry simply asks for it again.</li><li><strong>After the S3 write, before </strong><strong>set:</strong> the retry redoes page 347. The S3 key is built from the page number, so the redo overwrites the same file instead of adding a duplicate.</li></ul><p>Page number and cursor are saved in one set on purpose. As two keys, a crash between the writes could leave page 347 paired with page 348&#39;s cursor.</p><h3>From task to operator: the ResumableJobMixin</h3><p>Copying Example 1 into every DAG doesn’t scale. ResumableJobMixin packages the pattern. It saves the job ID before polling and reconnects on retry. Built-in operators like SparkSubmitOperator use it.</p><h3>The contract: six methods</h3><p>Add the mixin to your operator, call execute_resumable(context) from execute and implement six methods:</p><ol><li>submit_job(context) submits the job and returns its external ID. The mixin stores this value.</li><li>get_job_status(external_id, context) returns the external system&#39;s raw status string.</li><li>is_job_active(status) returns True if the job is still running and can be reconnected to.</li><li>is_job_succeeded(status) returns True if the job finished successfully.</li><li>poll_until_complete(external_id, context) blocks until the job is terminal and raises on failure.</li><li>get_job_result(external_id, context) returns the result after success or None.</li></ol><h3>What happens on a retry</h3><p>On retry, the mixin checks the stored job:</p><ul><li><strong>Still running:</strong> it reconnects and keeps polling.</li><li><strong>Already succeeded:</strong> it returns the result. No polling, no resubmit.</li><li><strong>Failed or gone:</strong> it submits a new job.</li></ul><p>The middle case is the one people miss.</p><h3>Example: a crash-safe Athena operator</h3><p>Here’s Example 1 as a reusable operator:</p><pre>import time<br>from functools import cached_property<br>from typing import Any<br><br>import boto3<br>from botocore.exceptions import ClientError<br>from airflow.sdk import BaseOperator, ResumableJobMixin<br>from pydantic import JsonValue<br><br>class ResumableAthenaOperator(ResumableJobMixin, BaseOperator):<br>    external_id_key = &quot;athena_query_id&quot;<br>    template_fields = (&quot;sql&quot;,)<br>    def __init__(self, *, sql: str, workgroup: str = &quot;primary&quot;,<br>                 poll_interval: int = 10, **kwargs):<br>        super().__init__(**kwargs)<br>        self.sql = sql<br>        self.workgroup = workgroup<br>        self.poll_interval = poll_interval<br><br>    @cached_property<br>    def athena(self):<br>        return boto3.client(&quot;athena&quot;)<br><br>    def execute(self, context):<br>        return self.execute_resumable(context)<br><br>    def submit_job(self, context) -&gt; JsonValue:<br>        return self.athena.start_query_execution(<br>            QueryString=self.sql, WorkGroup=self.workgroup<br>        )[&quot;QueryExecutionId&quot;]<br><br>    def get_job_status(self, external_id: JsonValue, context) -&gt; str:<br>        try:<br>            resp = self.athena.get_query_execution(QueryExecutionId=external_id)<br>        except ClientError as e:<br>            # Only &quot;this ID doesn&#39;t exist&quot; means the job is gone.<br>            # Throttling, auth or network errors must NOT trigger a resubmit:<br>            # raise, fail this attempt, and let the next retry check again.<br>            if e.response[&quot;Error&quot;][&quot;Code&quot;] == &quot;InvalidRequestException&quot;:<br>                return &quot;NOT_FOUND&quot;<br>            raise<br>        return resp[&quot;QueryExecution&quot;][&quot;Status&quot;][&quot;State&quot;]<br>    <br>    def is_job_active(self, status: str) -&gt; bool:<br>        return status in (&quot;QUEUED&quot;, &quot;RUNNING&quot;)<br>    <br>    def is_job_succeeded(self, status: str) -&gt; bool:<br>        return status == &quot;SUCCEEDED&quot;<br>    <br>    def poll_until_complete(self, external_id: JsonValue, context) -&gt; None:<br>        while True:<br>            status = self.get_job_status(external_id, context)<br>            <br>            if self.is_job_succeeded(status):<br>                return<br>            <br>            if not self.is_job_active(status):<br>                raise RuntimeError(f&quot;Athena query {external_id} ended as {status}&quot;)<br>            <br>            time.sleep(self.poll_interval)<br>    <br>    def get_job_result(self, external_id: JsonValue, context) -&gt; Any:<br>        return external_id</pre><p>In a DAG, it’s one call:</p><pre>daily_report = ResumableAthenaOperator(<br>    task_id=&quot;daily_installs_report&quot;,<br>    sql=REPORT_SQL,<br>    workgroup=&quot;analytics&quot;,<br>    retries=3,<br>)</pre><p>No manual get, set or delete anymore. The mixin owns the state.</p><p>Three things to know before you write your own:</p><ul><li><strong>It still holds a worker while it waits.</strong> The mixin makes polling crash-safe, not cheaper: the task sits on a worker slot for the whole query. If you’d rather free the slot during the wait, write a deferrable operator, which hands the waiting to the triggerer.</li><li><strong>Clearing a successful task may not rerun it.</strong> State survives a clear on purpose. A cleared task finds the old job ID, sees SUCCEEDED and returns the old result. To really recompute, delete the key in the Storage tab first or set durable=False.</li><li><strong>Check your </strong><strong>on_kill.</strong> Many older operators cancel the external job when the worker shuts down. In a durable operator, that kills the very job the retry wants to reattach to. Leave it running.</li></ul><h3>The sibling: the asset state store</h3><p>The task state store answers “where did the last <em>attempt</em> stop?” Data engineers more often ask <strong>“where did the last <em>run</em> stop?”</strong> That’s the asset state store.</p><p>It fixes a real pain. Without state, asset watchers rescanned whole buckets on every poll. AIP-103, the design proposal behind the feature, names this as a reason watchers were slow to catch on.</p><h3>How it differs</h3><ul><li><strong>Scope:</strong> an asset. Every task using it, in any DAG, shares the state.</li><li><strong>Survives:</strong> all runs, until you delete it.</li><li><strong>Access:</strong> context[&quot;asset_state_store&quot;] or self.asset_state_store in a watcher&#39;s run().</li><li><strong>Expiry:</strong> none. Cleanup and clear_on_success don&#39;t touch it.</li><li><strong>UI:</strong> in the asset’s details in the asset graph.</li></ul><h3>Two rules</h3><ul><li><strong>Declare the asset</strong> as an inlet or outlet. Otherwise you get a KeyError. @asset functions do this automatically.</li><li><strong>Subscript when there are several.</strong> With one asset, call the methods directly. With more, use context[&quot;asset_state_store&quot;][orders]. Otherwise you get a ValueError.</li></ul><h3>Example 3 — CDC: a watermark that remembers yesterday</h3><p>An hourly job loads changed orders and each run should start where the last one stopped. That’s a watermark and it has a classic trap. A row can commit late with an older updated_at and a strict updated_at &gt; watermark skips it forever. So the job re-reads a small overlap and upserts:</p><pre>from datetime import datetime, timedelta<br><br>from airflow.sdk import Asset, DAG, task<br><br>orders = Asset(&quot;orders&quot;, uri=&quot;s3://lake/orders/&quot;)<br>OVERLAP = timedelta(minutes=5)<br><br>with DAG(&quot;orders_cdc&quot;, schedule=&quot;@hourly&quot;):<br>    @task(inlets=[orders], outlets=[orders])<br>    def load_new_orders(**context):<br>        state = context[&quot;asset_state_store&quot;]  # one asset: shorthand works<br>        watermark = datetime.fromisoformat(<br>            state.get(&quot;watermark&quot;, default=&quot;1970-01-01T00:00:00+00:00&quot;)<br>        )<br>        <br>        # Re-read a few minutes before the watermark to catch late commits.<br>        rows = fetch_orders_changed_since(watermark - OVERLAP)<br>        if not rows:<br>            return<br>        <br>        # Upsert by primary key, so re-reading the overlap never duplicates rows.<br>        merge_into_lake(rows, key=&quot;order_id&quot;)<br>        <br>        # Advance only after the write succeeded.<br>        state.set(&quot;watermark&quot;, max(r[&quot;updated_at&quot;] for r in rows).isoformat())<br>        state.set(&quot;last_run&quot;, {&quot;rows&quot;: len(rows), &quot;run_id&quot;: context[&quot;run_id&quot;]})</pre><p>The watermark only moves after the write succeeds, so a failed run simply retries the same window. Upserting by order_id makes the overlap harmless. And last_run leaves a small audit trail in the asset&#39;s details: which run moved the watermark and by how much.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7Jj6GvAEXsfvF2glsWwXA.png" /></figure><p><em>The </em><em>orders asset after a run: the </em><em>watermark and the </em><em>last_run audit key, each with the task and DAG that last wrote it.</em></p><h3>Example 4 — Event-driven: a watcher that never loses its place</h3><p>A partner drops files into S3 at random times and a DAG should run once per file. The watcher that spots them runs in the triggerer and triggerers restart. Without a bookmark, a restarted watcher fires again for old files. Watcher triggers can keep that bookmark in the asset state store, through self.asset_state_store:</p><pre>import asyncio<br>from collections.abc import AsyncIterator<br>from typing import Any<br><br>import boto3<br>from airflow.sdk import Asset, AssetWatcher, DAG, task<br>from airflow.triggers.base import BaseEventTrigger, TriggerEvent<br><br>def find_next_key(bucket: str, prefix: str, after: str) -&gt; str | None:<br>    s3 = boto3.client(&quot;s3&quot;)<br>    resp = s3.list_objects_v2(Bucket=bucket, Prefix=prefix, StartAfter=after or prefix, MaxKeys=1)<br>    contents = resp.get(&quot;Contents&quot;, [])<br>    return contents[0][&quot;Key&quot;] if contents else None<br><br>class NewS3FileTrigger(BaseEventTrigger):<br>    def __init__(self, bucket: str, prefix: str, poll_seconds: int = 30, **kwargs):<br>        super().__init__(**kwargs)<br>        self.bucket, self.prefix, self.poll_seconds = bucket, prefix, poll_seconds<br><br>    def serialize(self) -&gt; tuple[str, dict[str, Any]]:<br>        return (<br>            f&quot;{self.__class__.__module__}.{self.__class__.__qualname__}&quot;,<br>            {&quot;bucket&quot;: self.bucket, &quot;prefix&quot;: self.prefix, &quot;poll_seconds&quot;: self.poll_seconds},<br>        )<br>    <br>    async def run(self) -&gt; AsyncIterator[TriggerEvent]:<br>        while True:<br>            # Async accessors: every trigger shares one event loop.<br>            last_key = await self.asset_state_store.aget(&quot;last_key&quot;, default=&quot;&quot;)<br>            new_key = await asyncio.to_thread(find_next_key, self.bucket, self.prefix, last_key)<br>            <br>            if new_key:<br>                await self.asset_state_store.aset(&quot;last_key&quot;, new_key)<br>                yield TriggerEvent({&quot;key&quot;: new_key})<br>                return<br><br>            await asyncio.sleep(self.poll_seconds)<br><br>partner_files = Asset(<br>    name=&quot;partner_files&quot;,<br>    uri=&quot;s3://landing/partner/&quot;,<br>    watchers=[AssetWatcher(name=&quot;partner_files_watcher&quot;,<br>              trigger=NewS3FileTrigger(bucket=&quot;landing&quot;, prefix=&quot;partner/&quot;))],<br>)<br><br>with DAG(&quot;process_partner_file&quot;, schedule=[partner_files]):<br>    @task(inlets=[partner_files])<br>    def process(**context):<br>        print(&quot;Watcher bookmark:&quot;, context[&quot;asset_state_store&quot;].get(&quot;last_key&quot;))<br>    <br>    process()</pre><p>The bookmark, last_key, lives on the asset. A restarted triggerer reads it and carries on. The task sees the same key, because both are attached to partner_files.</p><p>Two practical rules apply. Stay async, because all triggers share one event loop; that’s why the code uses aget, aset and asyncio.to_thread. And name files so they sort by arrival time, since the watcher looks for the next key alphabetically.</p><h3>Lifecycle of asset state</h3><p>Asset state never expires. It’s removed only when:</p><ul><li><strong>You delete it,</strong> from a task, the UI or the REST API.</li><li><strong>The asset is deleted.</strong> Its state goes with it.</li><li><strong>The asset is deactivated,</strong> usually because no DAG uses it. The next cleanup pass removes it.</li></ul><p><strong>Renaming an asset can reset its state.</strong> Airflow treats the new name as a new asset, so copy the keys you need first.</p><h3>Cleanup and configuration</h3><p>This section is about the task state store. Writing state is half the story; here’s when it expires and who deletes it.</p><h3>The life of a key</h3><p>Each key gets an expires_at when it&#39;s written. The worker computes it:</p><ul><li>set(key, value, retention=timedelta(days=2)) expires 2 days from now.</li><li>set(key, value) with no retention expires after default_retention_days (30 by default).</li><li>set(key, value, retention=NEVER_EXPIRE) stores no expiry at all, plus a flag that makes cleanup skip the key unconditionally.</li></ul><p>The timestamp is fixed at write time. Changing default_retention_days later only affects new writes.</p><p>Expired keys don’t vanish. get() still returns them until cleanup deletes the row. &quot;Expired&quot; just means &quot;eligible for deletion.&quot;</p><h3>Nothing is purged automatically</h3><p><strong>Airflow never purges task state on its own.</strong> You run cleanup yourself:</p><pre># Preview what would be deleted<br>airflow state-store clean --dry-run<br><br># Delete every row whose expires_at is in the past<br>airflow state-store clean</pre><p>It deletes every row whose expires_at has passed.</p><h3>clear_on_success: clean as you go</h3><p>With clear_on_success = True, a task&#39;s keys are deleted when it succeeds. The default is False, so you can still see the job ID after the run.</p><p>It also fires when someone marks a task as success by hand. That wipes saved job IDs too.</p><p>Keep False if people debug from the Storage tab. Use True if you write lots of state and never read it after success.</p><h3>Configuration reference</h3><p>Options live under [state_store], not [task_state_store]:</p><ul><li>backend: a custom BaseStoreBackend class.</li><li>default_retention_days: 30 by default. 0 turns off time-based cleanup.</li><li>clear_on_success: False by default.</li><li>state_cleanup_batch_size: rows per cleanup batch. 0 means one big delete.</li><li>max_value_storage_bytes: 65,535 by default. Enforced only for REST API writes.</li></ul><h3>Custom and worker-side backends</h3><p>Two options move state out of the metadata database.</p><p><strong>A custom backend</strong> ([state_store] backend) replaces the storage entirely. Built-in cleanup skips it, so implement BaseStoreBackend.cleanup() yourself.</p><p><strong>A worker-side backend</strong> stores values elsewhere and keeps only a reference in the database. It suits large or sensitive values. The Common IO provider ships one for object storage. Put the connection ID in the URL:</p><pre>[workers]<br>state_store_backend = airflow.providers.common.io.state_store.backend.StateStoreObjectStorageBackend<br><br>[common.io]<br>state_store_objectstorage_path = s3://aws_default@my-airflow-state/task-state/</pre><p>The setting is [workers] state_store_backend, as named in the 3.3 release notes. The provider offloads values above a size threshold; at its default of 0, every value goes to object storage.</p><p>Writing your own? <strong>Use deterministic paths.</strong> On delete, Airflow removes the database row first. If the backend call then fails, the next set overwrites a deterministic path. A random path stays orphaned.</p><p>Also check what cleanup does to external objects. If it leaves them, add a storage lifecycle rule.</p><h3>Cheat sheet: which memory do I need?</h3><ul><li><strong>An external job ID across retries:</strong> the task state store (Example 1).</li><li><strong>Where the last attempt stopped, so a retry can resume:</strong> the task state store (Example 2).</li><li><strong>The same, in a reusable operator:</strong> ResumableJobMixin.</li><li><strong>Where the last run stopped, so the next run can continue:</strong> the asset state store (Example 3).</li><li><strong>A watcher’s position:</strong> the asset state store, from the trigger (Example 4).</li><li><strong>A result for the next task:</strong> XCom.</li><li><strong>Settings that rarely change</strong> (bucket names, feature flags): Airflow Variables, as before. They’re for configuration, not for retry state.</li></ul><h3>Sources</h3><ul><li><a href="https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/task-state-store.html">Task State Store</a></li><li><a href="https://airflow.apache.org/docs/apache-airflow/3.3.2/core-concepts/asset-state-store.html">Asset State Store</a></li><li><a href="https://airflow.apache.org/docs/apache-airflow/3.3.2/administration-and-deployment/task-and-asset-state-store.html">Task and Asset State Store Configuration</a></li><li><a href="https://airflow.apache.org/docs/apache-airflow/3.3.2/administration-and-deployment/task-and-asset-state-store-cleanup.html">Task and Asset State Store Cleanup</a></li><li><a href="https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/resumable-tasks.html">Resumable Tasks and durable execution</a></li><li><a href="https://airflow.apache.org/docs/task-sdk/stable/resumable-job-mixin.html">ResumableJobMixin (Task SDK docs)</a></li><li><a href="https://airflow.apache.org/docs/apache-airflow/stable/_modules/airflow/example_dags/example_task_state_store.html">Official example DAG: example_task_state_store.py</a></li><li><a href="https://www.astronomer.io/docs/learn/airflow-task-state-store">Astronomer: Task state store guide</a></li><li><a href="https://www.astronomer.io/blog/durable-execution-with-apache-airflow/">Astronomer: Durable execution with Apache Airflow</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73733a657577" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Мілітарні некрополі подій 1910–20х років на Львівщині]]></title>
            <link>https://medium.com/@roykoand/%D0%BC%D1%96%D0%BB%D1%96%D1%82%D0%B0%D1%80%D0%BD%D1%96-%D0%BD%D0%B5%D0%BA%D1%80%D0%BE%D0%BF%D0%BE%D0%BB%D1%96-%D0%BF%D0%BE%D0%B4%D1%96%D0%B9-1910-20%D1%85-%D1%80%D0%BE%D0%BA%D1%96%D0%B2-%D0%BD%D0%B0-%D0%BB%D1%8C%D0%B2%D1%96%D0%B2%D1%89%D0%B8%D0%BD%D1%96-f1803f4e803e?source=rss-8d42747e4465------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1803f4e803e</guid>
            <category><![CDATA[історія]]></category>
            <category><![CDATA[military-history]]></category>
            <category><![CDATA[history]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[історія-україни]]></category>
            <dc:creator><![CDATA[Andrii Roiko]]></dc:creator>
            <pubDate>Fri, 01 May 2026 20:09:15 GMT</pubDate>
            <atom:updated>2026-05-07T18:09:25.536Z</atom:updated>
            <content:encoded><![CDATA[<p>Землі Галичини у ХХ столітті пройшли через десятки виснажливих випробувань — від розпаду імперій та масштабних світових воєн до локальних збройних конфліктів. Кожна зміна влади, кожна лінія фронту, що проходила через ці терени, залишала по собі не лише зруйновані міста, а й специфічний ландшафт пам’яті — мілітарні некрополі.</p><p>Сьогодні військові поховання Львова та його околиць є мовчазними свідками геополітичних катастроф минулого століття. Вони — це не просто місця спочинку солдатів різних армій, а складна мозаїка ідеологій, архітектурних стилів та політичних жестів. Від монументальних меморіалів Личакова до занедбаних цвинтарів Першої світової у розлогих галицьких лісах — ці об’єкти демонструють, як кожна епоха намагалася «зафіксувати» свою правду в камені та бетоні.</p><p>За останні декілька місяців я відвідав деякі з військових поховань у Львові та поблизу. Про те, що вдалося побачити та дізнатися, розповім у цьому дописі.</p><h3>Поховання бійців УСС/УГА на Янівському цвинтарі</h3><blockquote>“Тут спочивають Українські Січові Стрільці та воїни Української Галицької Армії“ — з таблички на вході до меморіалу</blockquote><p>Меморіал є місцем масового поховання близько 700 стрільців та старшин УГА та УСС, які загинули або брали участь в українсько-польської війни 1918–1919 рр. Тут пліч-о-пліч, в єдиному почесному ряду, спочивають як бойові генерали, так і рядові солдати. Окрім військових, упродовж наступних років тут було поховано також окремих діячів ОУН.</p><p>Автором проекту меморіалу є відомий львівський архітектор Євген Нагірний. Цвинтар упорядкувано в 1934 р. та повністю знищено в 70–80х роках радянською владою. З могильних хрестів мостили доріжки, зокрема на теперішній вулиці Сахарова. В 1990-х деякі уламки було віднайдено та з них зробили композицію у верхній частині меморіалу. Велика частина уламків стрілецьких хрестів і досі залишається під асфальтовим покриттям (більше про це в замітці <a href="https://www.istpravda.com.ua/columns/2025/02/19/164749/">Романа Гуцула</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cSUypq1XLpgWlcw8.jpeg" /></figure><p>Серед найвідоміших постатей, що знайшли тут спочинок:</p><ul><li>Генерал Армії УГА — <strong>Мирон Тарнавський</strong>. Його поховання у 1938-му перетворилося на справжній маніфест українського духу в міжвоєнному Львові (більше <a href="https://localhistory.org.ua/rubrics/video/ostannia-defiliada-generala-tarnavskogo-video/">про це</a>).</li><li>Прем’єр-міністр ЗУНР, співзасновник УНДП — <strong>Кость Левицький</strong></li><li>Старшина армії УНР, ад’ютант Симона Петлюри — <strong>Василь Бень</strong></li><li>Член ОУН — <strong>Ілярій Кук</strong>, рідний брат останнього головнокомандувача УПА — Василя Кука. Його було повішено за участь в нападі на власників фільварку Ясінських в Золочівському повіті. Більше про це та його останні хвилини життя можна прочитати в оповіданні Степана Шухевича “<a href="https://www.istpravda.com.ua/reviews/64a3cf3017684/view_news/">Mater Dolorosa. Скорботна мати</a>“.</li></ul><h3>Перший пам’ятник воїнам УГА у Винниках</h3><p>Пам’ятник воїнам УГА у Винниках посідає особливе місце в історії, адже це найперший скульптурний монумент, зведений на честь УГА на теренах Галичини. Авторства Павла Ковжуна та Левка Лепкого, відкритий у червні 1922 року, він став безпрецедентним актом національної пам’яті. Попри польську окупацію, громада зуміла увічнити героїв у камені ще тоді, коли рани війни були зовсім свіжими. Біля самого пам’ятника знаходиться стрілецьке поховання декількох десятків українських воїнів.</p><p>Пам’ятник являє собою велику кулю, центральним елементом якої є щит з тризубом накладений на схрещені шаблі та оповитий терновим вінком. У радянські часи монумент не наважилися зруйнувати, натомість знищили лише “тризуб“. Його відновленням на початку 90-х зайнявся Тарас Левків із студентами Львівського державного коледжу декоративного і ужиткового мистецтва імені Івана Труша.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*7sWljtDgFN6J6ea1.jpeg" /></figure><h3>Меморіал Львівським орлятам на Личаківському цвинтарі</h3><p>В період правління Другої Речі Посполити на українських землях Галичини був споруджений польський військовий пантеон, що вшановує пам’ять молодих добровольців, які загинули під час українсько-польської війни 1918–1919 років та у боях проти більшовиків у 1920-му. Архітектурний ансамбль, спроектований Рудольфом Індрухом, вражає своєю монументальністю: центральне місце займає каплиця-ротонда, до якої веде колонада з Тріумфальною аркою. Для міжвоєнної Польщі це місце було головним символом польського національного героїзму, де поруч із підлітками-”орлятами” спочивали американські пілоти та французькі піхотинці, що воювали на боці польських сил.</p><p>Історія меморіалу в радянський період стала символом тоталітарної боротьби з історичною пам’яттю: у 1971 році радянська влада за допомогою важкої будівельної техніки зруйнувала колони, розтрощила кам’яних левів та засипала могили сміттям. Протягом десятиліть меморіал перебував у стані руїни, проте після проголошення незалежності України та тривалих дипломатичних зусиль його було повністю реставровано та офіційно відкрито у 2005 році.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u7b4nJesY_wjputx.jpeg" /></figure><h3>Австрійське поховання біля селища Жовтанці</h3><p>Військовий некрополь у селі Жовтанці, розташований за 30 км від Львова, є черговим мовчазним свідком кривавих боїв Першої світової війни у Галичині. Заснований у червні 1915 року, він став місцем останнього спочинку для понад 337 солдатів, які представляли три ворогуючі імперії: Австро-Угорську (233 воїни), Російську (90 воїнів) та Німецьку (14 воїнів). Багато могил і досі залишаються безіменними, вказуючи лише на приналежність полеглого до тієї чи іншої армії. На деяких могильних хрестах чітко видно українські прізвища та імена, себто “Viktor Musiak“.</p><p>Після десятиліть повного забуття та занедбаності в радянський період, меморіал отримав шанс на друге життя завдяки співпраці<strong> </strong>Австрійського Чорного Хреста та місцевої влади. У 2017 році некрополь було повністю реставровано, що дозволило зберегти автентичну атмосферу військового поховання Великої війни.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KnTX6FVDFtuNzORp.jpeg" /></figure><h3>Австрійське поховання біля селища Івано-Франкове</h3><p>Меморіальне поховання в селищі Івано-Франкове (до 1946 року — Янів) є місцем спочинку декілька сотень солдатів Австро-Угорської та Російської імперій, які загинули під час запеклих боїв Першої світової війни. Найбільша кількість полеглих пов’язана з Городоцькою битвою 1914 року та масштабними операціями за контроль над Львовом у 1915 році. Тривалий час, за радянської доби, цвинтар перебував у занедбаному та сплюндрованому стані, проте до 100-річчя початку війни його було повністю відновлено за підтримки австрійської організації «Чорний хрест» та місцевої влади.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w5A_WAJQwLN5CDyB.jpeg" /></figure><p>Архітектурною домінантою меморіалу є стела з майстерно виконаною копією австро-угорського драгунського шолома з імперським гербом.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1803f4e803e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>