Skip to content

Commit 3d858bf

Browse files
committed
Preserve explicit defaults in language SDK serialization
1 parent af76df3 commit 3d858bf

14 files changed

Lines changed: 168 additions & 169 deletions

File tree

‎airflow-core/adr/lang-sdk/0004-dag-parsing.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,12 @@ The language runtime must produce a `DagFileParsingResult` that matches Python A
231231
| `@continuous` | `airflow.timetables.simple.ContinuousTimetable` | `{}` |
232232
| cron expr | `airflow.timetables.trigger.CronTriggerTimetable` | `{expression, timezone, interval, run_immediately}` |
233233

234+
**Task config defaults:** Language SDKs write task fields the author sets, including values
235+
equal to the schema default. Core fills missing config-backed defaults through `client_defaults.tasks`;
236+
a value already present in the task or defaults table takes precedence. This keeps an explicit
237+
`retries=0` when `[core] default_task_retries` is nonzero. In Go, pointer fields can express an
238+
explicit zero; a non-pointer scalar zero is treated as unset.
239+
234240
**Task encoding:**
235241

236242
```

‎airflow-core/src/airflow/serialization/serialized_objects.py‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2153,12 +2153,12 @@ def from_dict(cls, serialized_obj: dict) -> SerializedDAG:
21532153
@classmethod
21542154
def fill_config_defaults(cls, serialized_obj: dict[str, Any]) -> None:
21552155
"""
2156-
Fill in the Dag settings a serialized Dag leaves unset from the Airflow config, as a Python Dag does.
2156+
Fill in config-backed defaults omitted by a Lang-SDK Dag.
21572157
2158-
A Lang-SDK runtime cannot read the Airflow config, so it leaves ``max_active_tasks``,
2159-
``max_active_runs``, ``max_consecutive_failed_dag_runs``, ``catchup``,
2160-
``disable_bundle_versioning`` and the tasks' default ``execution_timeout`` out unless the Dag
2161-
sets them. A value the Dag sets is kept. *serialized_obj* is changed in place.
2158+
Language SDKs cannot read Airflow's config, so core fills missing Dag settings and
2159+
adds task defaults to ``client_defaults.tasks``. Values already supplied by the
2160+
payload take precedence.
2161+
*serialized_obj* is changed in place.
21622162
"""
21632163
dag = serialized_obj.get("dag")
21642164
if not isinstance(dag, dict):
@@ -2178,10 +2178,15 @@ def fill_config_defaults(cls, serialized_obj: dict[str, Any]) -> None:
21782178
):
21792179
if key not in dag:
21802180
dag[key] = get(section, option)
2181-
if (execution_timeout := conf.gettimedelta("core", "default_task_execution_timeout")) is not None:
2182-
task_defaults = serialized_obj.setdefault("client_defaults", {}).setdefault("tasks", {})
2183-
task_defaults.setdefault("execution_timeout", execution_timeout.total_seconds())
2181+
task_defaults = OperatorSerialization.generate_client_defaults().copy()
2182+
if (execution_timeout := conf.gettimedelta("core", "default_task_execution_timeout")) is None:
2183+
task_defaults.pop("execution_timeout", None)
2184+
else:
2185+
task_defaults["execution_timeout"] = execution_timeout.total_seconds()
21842186

2187+
client_defaults = serialized_obj.setdefault("client_defaults", {}).setdefault("tasks", {})
2188+
for key, value in task_defaults.items():
2189+
client_defaults.setdefault(key, value)
21852190
@classmethod
21862191
def validate_serialized_dag(cls, serialized_obj: dict[str, Any]) -> SerializedDAG:
21872192
"""

‎airflow-core/tests/unit/serialization/test_dag_serialization.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5484,6 +5484,41 @@ def test_fills_the_default_execution_timeout_of_tasks_from_the_config(self):
54845484
"mapped": timedelta(seconds=300),
54855485
}
54865486

5487+
def test_fills_task_defaults_without_replacing_explicit_values(self, operator_defaults):
5488+
with operator_defaults({"retries": 3}):
5489+
with DAG(dag_id="native_dag", schedule=None) as dag:
5490+
BaseOperator(task_id="unset")
5491+
BaseOperator(task_id="explicit", retries=0)
5492+
5493+
data = DagSerialization.to_dict(dag)
5494+
data.pop("client_defaults", None)
5495+
task_vars = {task["__var"]["task_id"]: task["__var"] for task in data["dag"]["tasks"]}
5496+
task_vars["unset"].pop("retries", None)
5497+
task_vars["explicit"]["retries"] = 0
5498+
5499+
DagSerialization.fill_config_defaults(data)
5500+
tasks = DagSerialization.from_dict(data).task_dict
5501+
5502+
assert data["client_defaults"]["tasks"]["retries"] == 3
5503+
assert tasks["unset"].retries == 3
5504+
assert tasks["explicit"].retries == 0
5505+
5506+
def test_merges_task_defaults_without_replacing_existing_defaults(self, monkeypatch):
5507+
monkeypatch.setattr(
5508+
OperatorSerialization,
5509+
"generate_client_defaults",
5510+
classmethod(lambda _: {"retries": 3, "queue": "celery_q"}),
5511+
)
5512+
data = {
5513+
"__version": 3,
5514+
"dag": {"dag_id": "native_dag", "tasks": []},
5515+
"client_defaults": {"tasks": {"retries": 1}},
5516+
}
5517+
5518+
DagSerialization.fill_config_defaults(data)
5519+
5520+
assert data["client_defaults"]["tasks"]["retries"] == 1
5521+
assert data["client_defaults"]["tasks"]["queue"] == "celery_q"
54875522
def test_leaves_a_payload_without_a_dag_to_validation(self):
54885523
data = {"__version": 3}
54895524

‎go-sdk/airflow/serialize.go‎

Lines changed: 4 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -189,10 +189,6 @@ func serializeTimetable(schedule string) map[string]any {
189189
// keyed by the name of the field.
190190
type schemaField struct {
191191
key string
192-
// schemaDefault is the default that the schema gives the property, or nil when the schema has
193-
// none. writeSpecFields leaves out a value equal to the default, because Airflow reads a missing
194-
// property as its schema default.
195-
schemaDefault any
196192
}
197193

198194
// specRules says how the serializer writes the fields of one spec struct. A field that has no entry
@@ -234,10 +230,9 @@ var taskSpecRules = specRules{
234230
// from the defaults of Python's TaskGroup instead.
235231
var taskGroupSpecRules = specRules{fields: taskGroupSpecFields}
236232

237-
// writeSpecFields writes into data each field of spec that rules does not skip. It leaves out a
238-
// field that is unset or that holds its schema default. A field is unset when it holds its zero
239-
// value. A pointer field is unset only when it is nil, so a pointer field can set the zero value of
240-
// the type it points to, such as false or 0.
233+
// writeSpecFields writes into data each field of spec that rules does not skip.
234+
// A field is unset when it holds its zero value. A pointer field is unset only when nil,
235+
// so it can explicitly set the zero value of its type, such as false or 0.
241236
func writeSpecFields(data map[string]any, spec any, rules specRules) {
242237
value := reflect.ValueOf(spec)
243238
for i := range value.NumField() {
@@ -252,7 +247,7 @@ func writeSpecFields(data map[string]any, spec any, rules specRules) {
252247
continue
253248
}
254249
encoded, set := encodeSpecValue(value.Field(i), rules.set[name])
255-
if !set || (field.schemaDefault != nil && isSameJSON(encoded, field.schemaDefault)) {
250+
if !set {
256251
continue
257252
}
258253
data[field.key] = encoded
@@ -306,28 +301,6 @@ func encodeSpecValue(value reflect.Value, set bool) (any, bool) {
306301
panic(fmt.Sprintf("airflow: the serializer cannot write a spec field of type %s", value.Type()))
307302
}
308303

309-
// isSameJSON reports whether two encoded values are the same JSON value. Like Python, it takes 1
310-
// and 1.0 for the same number.
311-
func isSameJSON(a, b any) bool {
312-
if x, ok := jsonNumber(a); ok {
313-
y, ok := jsonNumber(b)
314-
return ok && x == y
315-
}
316-
return a == b
317-
}
318-
319-
func jsonNumber(value any) (float64, bool) {
320-
switch v := value.(type) {
321-
case int:
322-
return float64(v), true
323-
case float64:
324-
return v, true
325-
}
326-
return 0, false
327-
}
328-
329-
// encodeTime returns t as Python's serializer writes a datetime: the seconds since the Unix epoch,
330-
// to the microsecond. A Python datetime holds nothing finer than a microsecond.
331304
func encodeTime(t time.Time) float64 { return float64(t.UnixMicro()) / 1e6 }
332305

333306
// pythonStr returns t as Python's str(datetime) writes it in UTC, such as

‎go-sdk/airflow/serialize_test.go‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ func TestSerializeWritesTheFieldsOfTaskSpec(t *testing.T) {
283283
}`, withoutKeys(got, goTaskFields...))
284284
}
285285

286-
func TestSerializeLeavesOutAFieldAtItsSchemaDefault(t *testing.T) {
286+
func TestSerializePreservesExplicitTaskFieldsAtTheirSchemaDefaults(t *testing.T) {
287287
dag := Dag("etl", DagSpec{Queue: "default"})
288288
dag.Task(ping, TaskSpec{
289289
DoXComPush: ptr(true),
@@ -300,7 +300,17 @@ func TestSerializeLeavesOutAFieldAtItsSchemaDefault(t *testing.T) {
300300

301301
got := serializedDag(t, dag)
302302

303-
assert.Empty(t, withoutKeys(serializedTask(t, got, "ping"), goTaskFields...))
303+
assertJSON(t, `{
304+
"do_xcom_push": true,
305+
"owner": "airflow",
306+
"pool": "default_pool",
307+
"pool_slots": 1,
308+
"priority_weight": 1,
309+
"queue": "default",
310+
"retry_delay": 300,
311+
"trigger_rule": "all_success",
312+
"weight_rule": "downstream"
313+
}`, withoutKeys(serializedTask(t, got, "ping"), goTaskFields...))
304314
assert.Empty(t, withoutKeys(serializedTask(t, got, "extract"), goTaskFields...))
305315
}
306316

‎go-sdk/airflow/spec_fields.gen.go‎

Lines changed: 22 additions & 22 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎go-sdk/internal/genspec/fields.go‎

Lines changed: 5 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import (
2424
"fmt"
2525
"go/format"
2626
"slices"
27-
"strconv"
2827
"strings"
2928
"unicode"
3029
)
@@ -60,14 +59,10 @@ func capitalize(part string) string {
6059
// fieldEntry is one property of a spec definition, as the generated table holds it.
6160
type fieldEntry struct {
6261
name, key string
63-
// schemaDefault is the Go literal of the default of the property, or empty when the
64-
// schema declares none.
65-
schemaDefault string
6662
}
6763

68-
// emitFields returns the Go source of the tables of schema defaults, one for each
69-
// definition of doc. doc is the schema that shapeForAuthoring and normalize wrote, so each
70-
// definition has the title of its struct and holds the properties that become its fields.
64+
// emitFields returns a Go table mapping each spec field to its serialized key. The schema
65+
// has already been shaped for authoring and normalized before this function is called.
7166
// A table is keyed by the name of the struct field, as go-jsonschema writes it.
7267
func emitFields(doc map[string]any) ([]byte, error) {
7368
definitions, ok := doc["definitions"].(map[string]any)
@@ -91,17 +86,13 @@ func emitFields(doc map[string]any) ([]byte, error) {
9186
}
9287
fmt.Fprintf(
9388
&body,
94-
"\n// %s holds the key and the schema default of each field of %s.\nvar %s = map[string]schemaField{\n",
89+
"\n// %s maps each field of %s to its serialized key.\nvar %s = map[string]schemaField{\n",
9590
tableName(title),
9691
title,
9792
tableName(title),
9893
)
9994
for _, field := range fields {
100-
fmt.Fprintf(&body, "\t%q: {key: %q", field.name, field.key)
101-
if field.schemaDefault != "" {
102-
fmt.Fprintf(&body, ", schemaDefault: %s", field.schemaDefault)
103-
}
104-
body.WriteString("},\n")
95+
fmt.Fprintf(&body, "\t%q: {key: %q},\n", field.name, field.key)
10596
}
10697
body.WriteString("}\n")
10798
}
@@ -125,45 +116,8 @@ func getFieldEntries(definition string, properties map[string]any) ([]fieldEntry
125116
)
126117
}
127118
byName[name] = key
128-
node, _ := properties[key].(map[string]any)
129-
literal, err := defaultLiteral(node["default"])
130-
if err != nil {
131-
return nil, fmt.Errorf("definitions/%s/properties/%s: %w", definition, key, err)
132-
}
133-
fields = append(fields, fieldEntry{name: name, key: key, schemaDefault: literal})
119+
fields = append(fields, fieldEntry{name: name, key: key})
134120
}
135121
slices.SortFunc(fields, func(a, b fieldEntry) int { return cmp.Compare(a.name, b.name) })
136122
return fields, nil
137123
}
138-
139-
// defaultLiteral returns the Go literal of a schema default. A number that the schema
140-
// writes with a fraction or an exponent stays a float64, such as retry_delay's 300.0, and
141-
// any other number is an int, because readSchema decodes a number as a json.Number. A null
142-
// default says the property has none, as an absent one does.
143-
func defaultLiteral(value any) (string, error) {
144-
switch value := value.(type) {
145-
case nil:
146-
return "", nil
147-
case bool:
148-
return strconv.FormatBool(value), nil
149-
case string:
150-
return strconv.Quote(value), nil
151-
case json.Number:
152-
if strings.ContainsAny(value.String(), ".eE") {
153-
number, err := value.Float64()
154-
if err != nil {
155-
return "", err
156-
}
157-
literal := strconv.FormatFloat(number, 'f', -1, 64)
158-
if !strings.Contains(literal, ".") {
159-
literal += ".0"
160-
}
161-
return literal, nil
162-
}
163-
if _, err := value.Int64(); err != nil {
164-
return "", err
165-
}
166-
return value.String(), nil
167-
}
168-
return "", fmt.Errorf("the default %v is a %T, which the table cannot hold", value, value)
169-
}

‎go-sdk/internal/genspec/fields_test.go‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,7 @@ func TestCapitalizationsMatchTheGenerateDirective(t *testing.T) {
5252
assert.Equal(t, capitalizations, flags)
5353
}
5454

55-
func TestEmitFieldsWritesTheKeyAndDefaultOfEachField(t *testing.T) {
56-
// readSchema decodes a number as a json.Number, which a plain Unmarshal does not.
55+
func TestEmitFieldsWritesTheKeyOfEachField(t *testing.T) {
5756
raw := `{"definitions": {"operator": {"title": "TaskSpec", "properties": {
5857
"retry_delay": {"default": 300.0},
5958
"retries": {"default": 0},
@@ -74,10 +73,10 @@ func TestEmitFieldsWritesTheKeyAndDefaultOfEachField(t *testing.T) {
7473
assert.Contains(t, got, "var taskSpecFields = map[string]schemaField{")
7574
for _, entry := range []string{
7675
`"DocMD":`, `{key: "doc_md"}`,
77-
`{key: "retry_delay", schemaDefault: 300.0}`,
78-
`{key: "retries", schemaDefault: 0}`,
79-
`{key: "do_xcom_push", schemaDefault: true}`,
80-
`{key: "owner", schemaDefault: "airflow"}`,
76+
`{key: "retry_delay"}`,
77+
`{key: "retries"}`,
78+
`{key: "do_xcom_push"}`,
79+
`{key: "owner"}`,
8180
`{key: "queue"}`,
8281
} {
8382
assert.Contains(t, got, entry)
@@ -95,10 +94,6 @@ func TestEmitFieldsRejects(t *testing.T) {
9594
`{"definitions": {"dag": {"title": "DagSpec", "properties": {"doc_md": {}, "doc-md": {}}}}}`,
9695
"both become the field DocMD",
9796
},
98-
"a default that is not a scalar": {
99-
`{"definitions": {"dag": {"title": "DagSpec", "properties": {"tags": {"default": []}}}}}`,
100-
"the table cannot hold",
101-
},
10297
} {
10398
t.Run(name, func(t *testing.T) {
10499
_, err := emitFields(schemaFrom(t, tt.schema))
@@ -122,5 +117,5 @@ func TestEmitFieldsReadsTheShapedCoreSchema(t *testing.T) {
122117
assert.Contains(t, got, "var "+table+" = ")
123118
}
124119
assert.Contains(t, got, `"RetryDelay"`)
125-
assert.Contains(t, got, "schemaDefault: 300.0")
120+
assert.Contains(t, got, `{key: "retry_delay"}`)
126121
}

0 commit comments

Comments
 (0)