airflow icon indicating copy to clipboard operation
airflow copied to clipboard

Feedback wanted: the TypeScript SDK interface for authoring Dags

Open pierrejeambrun opened this issue 4 weeks ago • 6 comments

Airflow Dags are no longer Python only. Language SDKs for Java, Go and TypeScript let you declare a whole Dag (schedule, tasks, options and dependencies) in another language, or implement the stub tasks of a Python Dag in it. The TypeScript SDK ships with Airflow 3.4 (release candidates are out now) as the @apache-airflow/ts-sdk npm package, currently in beta.

This issue collects community feedback on the interface the TypeScript SDK exposes for authoring Dags. Please comment with what feels natural, what feels awkward, and what is missing for your use case.

What it looks like

A Dag declared entirely in TypeScript, with no Python file:

A TypeScript Dag with a task group, typed task inputs and a dag.if branch
  • dag.task(...) returns a factory, and calling it places the task in the Dag. Passing one task's result to another draws the dependency and moves the value as an XCom.
  • Task inputs are type checked. A misspelled or missing argument fails at compile time, not at parse time or run time:
tsc reporting a misspelled task input

Running it locally

There is no project template yet, so start from an empty npm project: make it ESM (the SDK is ESM-only), install the SDK with esbuild and TypeScript, and add a tsconfig.json. airflow-ts-pack builds the Dag into a single bundle file but does not type check it, so run tsc for that. Then put the bundle in a Dag bundle and route a queue to the Node.js coordinator:

npm init, npm install, tsconfig.json, tsc, airflow-ts-pack and the [sdk] configuration

The workers and the Dag processor need Node.js 22 or later. From there it is a regular Dag: it is scheduled, it shows up in the UI with its task group and branches, and each task runs on Node.js:

Graph view of a TypeScript Dag run

The Code tab shows the TypeScript source embedded in the bundle:

Code view showing the TypeScript source

What is supported, and what is not yet

Not every Airflow feature has a TypeScript form yet. Supported today: Dag and task arguments, TaskFlow-style inputs, before / after dependencies, edge labels, task groups, dag.if and dag.switch branching, triggerDagRun, human-in-the-loop (approval() / hitl()), and Variables, Connections, XComs and the task state store from task code.

Still to come, among others: task loops, dynamic task mapping, Dag params, Dag and task callbacks, assets (definition, scheduling, inlets and outlets), and airflow dags test. Until then, a Dag that needs one of these can be declared in Python, with its tasks implemented in TypeScript through @task.stub.

The compatibility matrix tracks what each SDK supports, for Java, Go and TypeScript side by side.

Feedback we are looking for

Anything is welcome. These are the questions we would most like answers to:

  1. Wiring tasks. Does it feel natural ?
  2. Options. Dag and task options are Airflow's own arguments in camelCase (retryDelay, triggerRule, ...). Does that work for you, or would you expect something more idiomatic?
  3. Type safety. What else should the compiler catch for you?
  4. Build and deploy. Is building one bundle file with airflow-ts-pack and dropping it in a Dag bundle a good fit for how you ship TypeScript? Would a project template (npm create-style) help you get started?
  5. Missing features. Which of the features above would you need first to use it for real?

Short code snippets of what you would like to write are the most useful kind of feedback.

Links

The 3.4 documentation links point to the staged site and move to airflow.apache.org once 3.4.0 is released.

pierrejeambrun avatar Nov 03 '26 13:11 pierrejeambrun

One thing I would like us to spend more time on is making the case of "just run a single dag locally" for testing much, much better. We are looking at this now on the python side, and our UX/python API options are a bit more limited there, so I'd like us to not repeat the same mistake.

the tl;dr of what I'd like to see is how close can we get to "just write TS function, and run it":

function task1() {
  return 3.14519
}
function task2(pi, r) {
  return pi * r * r;
}

export function dag() {
  return task2(task1(), 3); 
}

if (import.meta.main) {
  let result = dag();
  console.log(`Dag result was {result}`);
}

This is obviously a long way from a workable solution (and how we get a runnable Exec API server etc), but this is sort of what I'd like the TS end user experience to be like.

ashb avatar Nov 04 '26 11:11 ashb

A few thoughts:

I think there are too many steps to declare a task:

const summarize = dag.task("summarize", async (...) => ...); // factory
const summary   = summarize({ eu: eu(), us: us() });         // TaskRef

We write summar(y/ize) three times. Then we also call eu so many times too. Also, const summary = summarize({ eu: eu(), us: us() }) reads like we are mixing execution inside of a declaration.

We're mixing classes and factory functions. I'd prefer we only do factory functions. I can't tell if Dag is a type or a class.

Our task name declaration is inconsistent which makes it hard to read the code. dag.if(hasOrders, { s: summary }, { taskId: "has_orders" }) should be dag.if("has_orders", ... Also .then(publish()) doesnt not read like proper async chaining.

Here is what I think the file could look like:

import { defineBundle, defineDag, getClient } from "@apache-airflow/ts-sdk";

type Orders = { region: string; count: number };
type Summary = { total: number };

// Task bodies: plain functions. Unit-test them directly.
const fetchEu = (): Orders => ({ region: "eu", count: 120 });
const fetchUs = (): Orders => ({ region: "us", count: 80 });
const summarize = ({ eu, us }: { eu: Orders; us: Orders }): Summary => ({
  total: eu.count + us.count,
});
const publish = async () => {
  const channel = await getClient().getVariable("report_channel");
  console.log(`Publishing the daily report to ${channel ?? "#data"}`);
};
const nothingToReport = () => console.log("No orders today");
const hasOrders = ({ summary }: { summary: Summary }) => summary.total > 0;

// The Dag: places tasks, with explicit ids.
const ordersReport = defineDag(
  "ts_orders_report",
  { schedule: "@daily", catchup: false, tags: ["typescript"], queue: "typescript" },
  (dag) => {
    const extract = dag.group("extract", (group) => ({
      eu: group.task("eu", fetchEu),
      us: group.task("us", fetchUs),
    }));
    const summary = dag.task("summarize", summarize, extract);

    dag.if("has_orders", {
      inputs: { summary },
      condition: hasOrders,
      then: dag.task("publish", publish),
      else: dag.task("nothing_to_report", nothingToReport),
    });
  },
);

const bundle = defineBundle(ordersReport);
await bundle.serve();
  1. We may need to make dag.task() all have object params to give us flexibility and improve readability when you have many props like display name

bbovenzi avatar Nov 05 '26 18:11 bbovenzi

tried @apache-airflow/[email protected] on node 24.22.1 (typescript 7.0.2, esbuild 0.28.2). the docs quick start typechecks, and airflow-ts-pack src/main.ts --outdir dist wrote dist/bundle.min.mjs. i also packed a small dag with a task group, dag.if, and { retries: 2, retryDelay: 30 }.

  1. wiring: the factory-then-call style works. writing
const summarize = dag.task("summarize", async ({ eu, us }: { eu: Orders; us: Orders }) => ({ total: eu.count + us.count }));
const summary = summarize({ eu: euRef, us: usRef });

felt a bit repetitive, but the types and the edges were clear once i did it.

  1. options: camelCase is fine. a typo like { retryyDelay: 10 } did not get a useful compile error. tsc said Argument of type '() => Promise<void>' is not assignable to parameter of type 'Operator<void, unknown>' and never mentioned retryyDelay. packing that file then failed at runtime with Error: Unknown option "retryyDelay" in the spec for Dag "ts_typo" task "load", which is the message i wanted from tsc.

  2. type safety: misspelled task inputs are great. report({ rowss: extract() }) failed with TS2561 Did you mean to write 'rows'?. option typos should get that same treatment. also confirmed pack does not typecheck: the same rowss typo packed cleanly when i skipped tsc.

  3. build: pack is straightforward. running the bundle without airflow exits 1 with Error: Missing --comm=host:port, which is expected. i didn't stand up a full airflow + NodeCoordinator. a npm create template would have saved the ESM / tsconfig setup. small docs nit: the package README says npm install @apache-airflow/[email protected] and "Status: 1.0.0", but npm only has 0.3.5, 1.0.0-beta2, and 1.0.0-rc1.

  4. missing: for actually running dags, airflow dags test on a typescript dag and a project template would help first. i didn't get far enough to miss dynamic mapping.

sreecharan-desu avatar Nov 10 '26 12:11 sreecharan-desu

Spent some time using the SDK and it feels solid overall, the error messages in particular are really good. A few things I ran into, happy to open PRs for any of them:

  1. Task inputs are not type checked against upstream outputs. TaskInputs accepts a bare TaskRef, so passing TaskRef<string> to a number input compiles and the task gets NaN at runtime. From the history it looks like the typed path was dropped when inputs became named only (#73437), since ADR 0002 says tsc checks every named input. Typing it as TaskRef<ReadonlyDeep<TArgs[K]>> fixes it, with unknown still working as an opt-out. Same for dag.if, dag.switch and triggerDagRun. If loose refs were intentional, it would be good to note why in the ADR.
  2. Return values aren't restricted to JSON compatible types, so a returned Map or Set silently arrives downstream as {}. A runtime check is an easy fix, but would you also want TReturn constrained at the type level? That could break some existing code.
  3. Some smaller things: there's no way to skip a task or fail it without retries, and TaskContext doesn't expose logicalDate or the data interval even though they're sent to the runtime. Would PRs for these be welcome, or are they planned already?

Separately, an out of range cron like 0 25 * * * passes airflow-ts-pack and the Dag import, and the Dag just never runs. I'll open a separate issue for that one.

Pebble32 avatar Nov 18 '26 14:11 Pebble32

A flag like airflow-ts-pack src/main.ts --print-manifest would be handy in CI. Pack already reads the manifest from the staged bundle, so printing it lets you check which Dag and task IDs will ship before deploying. Would help catch an accidental task ID change when moving task groups around.

rodneyg avatar Nov 19 '26 16:11 rodneyg

I built a small trial on Airflow 3.4.0 with ts-sdk 1.0.0, two TypeScript Dags and one Python Dag with a stub: https://github.com/JoelEmmanuelCloud/airflow-ts-sdk-trial. The F numbers below are entries in FRICTION.md there, with the exact errors.

An 11 task Dag with a task group, dag.if, dag.switch, approval and triggerDagRun ran on the first deploy, so the base is good.

What I missed most is what @ashb said, running and testing locally. Plain functions are easy to test, anything else is not:

  • bundle.getTaskHandler gives back the SDK's wrapper, so even a dag.if decider that only compares two dates throws getClient() is only available inside a task handler (F-07)
  • to test handlers that use getContext() or getClient() I had to put a fake scope in the SDK's private storage (F-09). It works, but any release could break it
  • airflow dags test on a TypeScript Dag says it could not be found, while the same Dag runs fine (F-18)

I would like to write something like this:

import { testTask } from "@apache-airflow/ts-sdk/testing";

const run = await testTask(bundle, "route_health_report", "check_freshness", {
  args: { batch },
  variables: { route_health_as_of: "2026-11-19T23:30:00-05:00" },
});
assert.equal(run.result, true);
assert.deepEqual(run.skipped, ["alert_stale"]);

It's close to the single task step in the "A public testing package for Dag authors" thread on the dev list, but that one is Python. Is something like this wanted for TypeScript too? I'd like to help with it.

On the questions:

  1. Wiring is fine for chains and fan-in. Joining after dag.switch is the awkward part. Only one case runs, so I ended up with .after(...), triggerRule: "none_failed_min_one_success" and getXCom by task id string (F-15). writeReport({ draft: branch.result() }) would fix it.
  2. camelCase works for me. Same misleading error as @sreecharan-desu for an unknown option (F-11).
  3. taskStateStore.set rejects an interface with Index signature for type 'string' is missing, though a task can return that same type (F-04). A misspelled triggerRule only shows up as Task deadlock (no runnable tasks) (F-10). #77392 handles that one, and a union type would also catch it in the editor.
  4. Smooth. I'd want source maps, because stack traces point at route-health.min.mjs:270:14599 (F-14), and an npm create template.
  5. In the order I needed them: local testing, mapping, Dag params, assets. A mapped @task.stub gets no arguments in 1.0.0 and logs nothing (F-17). #71062 and #70570 cover that already.

I also found that approval logs a warning about an argument called then on its first run when it has inputs (F-13). Opened #77587 for it.

JoelEmmanuelCloud avatar Nov 25 '26 09:11 JoelEmmanuelCloud