alytricality-airflow 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .venv-min/
5
+ .venv-af/
6
+ dist/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ smoke/out/
10
+ .claude/worktrees/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.5
2
+ Name: alytricality-airflow
3
+ Version: 0.1.0
4
+ Summary: Airflow task-instance tracing plugin for alytricality
5
+ Project-URL: Repository, https://github.com/seismiq-ai/alytricality
6
+ Project-URL: Issues, https://github.com/seismiq-ai/alytricality/issues
7
+ Author: Seismiq AI
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: Apache Airflow
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: System :: Monitoring
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: alytricality==0.1.0
23
+ Description-Content-Type: text/markdown
24
+
25
+ # alytricality-airflow
26
+
27
+ Airflow task-instance tracing for [`alytricality`](https://pypi.org/project/alytricality/),
28
+ the opinionated OpenTelemetry tracing distro for data pipelines. It registers an
29
+ Airflow listener that opens one span per task instance and links it to the trace
30
+ that triggered the DAG run, so a pipeline reads as a single trace from its
31
+ upstream trigger through every task.
32
+
33
+ > **Pre-launch naming.** `alytricality-airflow` is a placeholder distribution
34
+ > name. The project will be republished under its real brand at launch; the
35
+ > import package and the plugin entry-point name change with it.
36
+
37
+ ## Install
38
+
39
+ ```sh
40
+ pip install alytricality-airflow
41
+ ```
42
+
43
+ There is nothing to import and no file to copy into `plugins/`. The package
44
+ ships an `airflow.plugins` entry point, so installing it next to Airflow — in
45
+ the same environment as the scheduler and workers — is the entire installation.
46
+ On Composer, add `alytricality[gcp]` and `alytricality-airflow` to
47
+ `pypi_packages`; in a custom image, install the same two lines.
48
+
49
+ `apache-airflow` is a peer dependency supplied by the runtime and is
50
+ deliberately not pinned here. `alytricality` is pinned exactly: the two
51
+ distributions release in lockstep.
52
+
53
+ ## Configure
54
+
55
+ Configuration is the core package's standard `OTEL_*` environment, set on the
56
+ scheduler and workers:
57
+
58
+ ```sh
59
+ OTEL_EXPORTER_OTLP_ENDPOINT=https://collector.example.com
60
+ OTEL_SERVICE_NAME=airflow
61
+ OTEL_RESOURCE_ATTRIBUTES=deployment.environment=prod
62
+ ```
63
+
64
+ The listener applies two `setdefault`s of its own before its first hook —
65
+ `OTEL_SERVICE_NAME=airflow` and `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=flask`
66
+ (the Airflow webserver is Flask; its health-check spans are noise). A value you
67
+ set always wins.
68
+
69
+ ## Behavior
70
+
71
+ - One span per task instance, keyed by `(dag_id, run_id, task_id, map_index)`,
72
+ named after the bare `task_id` so mapped instances aggregate.
73
+ - Trace linkage from `ti.context_carrier` (native AIP-49) or a `traceparent` in
74
+ the DAG run's `conf` — a link, not a remote parent, since the trigger and the
75
+ DAG run are independently rooted.
76
+ - Task attributes under `airflow.task.*`; terminal state set at span end.
77
+ - Failures captured on the span *and* written to stderr, so a traceback survives
78
+ pod teardown under the KubernetesExecutor.
79
+ - Defers entirely to an existing tracer provider (e.g. Airflow-native
80
+ `otel_on=True`) — never fights another owner for the global provider.
81
+ - Bounded flush per task; a telemetry failure never fails the task.
82
+
83
+ ## Supported window
84
+
85
+ Python 3.10–3.13, Airflow 2.9+ and 3.x (2.9, 2.11, 3.1, and 3.2 covered in CI),
86
+ OpenTelemetry SDK 1.27–1.44.
87
+
88
+ ## License
89
+
90
+ Apache-2.0.
@@ -0,0 +1,66 @@
1
+ # alytricality-airflow
2
+
3
+ Airflow task-instance tracing for [`alytricality`](https://pypi.org/project/alytricality/),
4
+ the opinionated OpenTelemetry tracing distro for data pipelines. It registers an
5
+ Airflow listener that opens one span per task instance and links it to the trace
6
+ that triggered the DAG run, so a pipeline reads as a single trace from its
7
+ upstream trigger through every task.
8
+
9
+ > **Pre-launch naming.** `alytricality-airflow` is a placeholder distribution
10
+ > name. The project will be republished under its real brand at launch; the
11
+ > import package and the plugin entry-point name change with it.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ pip install alytricality-airflow
17
+ ```
18
+
19
+ There is nothing to import and no file to copy into `plugins/`. The package
20
+ ships an `airflow.plugins` entry point, so installing it next to Airflow — in
21
+ the same environment as the scheduler and workers — is the entire installation.
22
+ On Composer, add `alytricality[gcp]` and `alytricality-airflow` to
23
+ `pypi_packages`; in a custom image, install the same two lines.
24
+
25
+ `apache-airflow` is a peer dependency supplied by the runtime and is
26
+ deliberately not pinned here. `alytricality` is pinned exactly: the two
27
+ distributions release in lockstep.
28
+
29
+ ## Configure
30
+
31
+ Configuration is the core package's standard `OTEL_*` environment, set on the
32
+ scheduler and workers:
33
+
34
+ ```sh
35
+ OTEL_EXPORTER_OTLP_ENDPOINT=https://collector.example.com
36
+ OTEL_SERVICE_NAME=airflow
37
+ OTEL_RESOURCE_ATTRIBUTES=deployment.environment=prod
38
+ ```
39
+
40
+ The listener applies two `setdefault`s of its own before its first hook —
41
+ `OTEL_SERVICE_NAME=airflow` and `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=flask`
42
+ (the Airflow webserver is Flask; its health-check spans are noise). A value you
43
+ set always wins.
44
+
45
+ ## Behavior
46
+
47
+ - One span per task instance, keyed by `(dag_id, run_id, task_id, map_index)`,
48
+ named after the bare `task_id` so mapped instances aggregate.
49
+ - Trace linkage from `ti.context_carrier` (native AIP-49) or a `traceparent` in
50
+ the DAG run's `conf` — a link, not a remote parent, since the trigger and the
51
+ DAG run are independently rooted.
52
+ - Task attributes under `airflow.task.*`; terminal state set at span end.
53
+ - Failures captured on the span *and* written to stderr, so a traceback survives
54
+ pod teardown under the KubernetesExecutor.
55
+ - Defers entirely to an existing tracer provider (e.g. Airflow-native
56
+ `otel_on=True`) — never fights another owner for the global provider.
57
+ - Bounded flush per task; a telemetry failure never fails the task.
58
+
59
+ ## Supported window
60
+
61
+ Python 3.10–3.13, Airflow 2.9+ and 3.x (2.9, 2.11, 3.1, and 3.2 covered in CI),
62
+ OpenTelemetry SDK 1.27–1.44.
63
+
64
+ ## License
65
+
66
+ Apache-2.0.
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ # >=1.27 for PEP 639 (`license` as an SPDX expression + `license-files`).
3
+ requires = ["hatchling>=1.27"]
4
+ build-backend = "hatchling.build"
5
+
6
+ [project]
7
+ name = "alytricality-airflow"
8
+ version = "0.1.0"
9
+ description = "Airflow task-instance tracing plugin for alytricality"
10
+ readme = "README.md"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Seismiq AI" }]
14
+ requires-python = ">=3.10"
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Framework :: Apache Airflow",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: System :: Monitoring",
26
+ "Typing :: Typed",
27
+ ]
28
+ # Exact pin: the listener calls core internals (DESIGN §2.2). apache-airflow
29
+ # is a peer dependency supplied by the runtime — never pinned here.
30
+ dependencies = ["alytricality==0.1.0"]
31
+
32
+ [project.urls]
33
+ Repository = "https://github.com/seismiq-ai/alytricality"
34
+ Issues = "https://github.com/seismiq-ai/alytricality/issues"
35
+
36
+ [project.entry-points."airflow.plugins"]
37
+ alytricality = "alytricality_airflow.plugin:AlytricalityTracerPlugin"
@@ -0,0 +1 @@
1
+ from __future__ import annotations
@@ -0,0 +1,25 @@
1
+ """Airflow-owned attribute names (kept out of core — SPEC §3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ AIRFLOW_TASK_PREFIX = "airflow.task."
6
+ AIRFLOW_TASK_STATE = "airflow.task.state"
7
+ AIRFLOW_TASK_ERROR = "airflow.task.error"
8
+ AIRFLOW_TASK_CONTEXT_CARRIER = "airflow.task.context_carrier"
9
+
10
+ # The allowlist (DESIGN §5.1): identifies the task run and links to the UI;
11
+ # everything else on the TI is Pydantic-internals noise. dag_version_id is
12
+ # 3.x-only and getattr-skips on 2.x.
13
+ TI_SPAN_ATTRS = (
14
+ "dag_id",
15
+ "dag_version_id",
16
+ "run_id",
17
+ "task_id",
18
+ "try_number",
19
+ "map_index",
20
+ "is_mapped",
21
+ "hostname",
22
+ "id",
23
+ "log_url",
24
+ "start_date",
25
+ )
@@ -0,0 +1,168 @@
1
+ """Airflow task-instance listener. Telemetry must never break a task."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import logging
8
+ import os
9
+ import threading
10
+
11
+ from airflow.listeners import hookimpl
12
+ from alytricality import init
13
+ from alytricality._init import flush, runtime
14
+ from alytricality._propagation import link_from_carrier
15
+ from alytricality.attributes import TRACE_SOURCE_DAG_RUN_CONF
16
+
17
+ from . import attributes as af
18
+
19
+ log = logging.getLogger("alytricality.airflow")
20
+
21
+ _active: dict = {} # ti_key -> (span, context token)
22
+ _lock = threading.Lock()
23
+
24
+
25
+ def _env_defaults() -> None:
26
+ # SIMP §13: standard vars, setdefault so user config wins. flask stays
27
+ # disabled: the webserver is Flask (health-check span spam), the
28
+ # instrumentor's class-rebind misses the already-created app, and our
29
+ # span must stay outermost so the bounded flush covers the whole trace.
30
+ os.environ.setdefault("OTEL_SERVICE_NAME", "airflow")
31
+ os.environ.setdefault("OTEL_PYTHON_DISABLED_INSTRUMENTATIONS", "flask")
32
+
33
+
34
+ def _ti_key(ti):
35
+ # No try_number: on Airflow 2.x it is a property that shifts +1 once the
36
+ # TI leaves RUNNING, so the terminal hook would compute a different key
37
+ # and orphan the span. Two attempts of one TI can't overlap in a worker
38
+ # process, so the 4-tuple is unique enough (DESIGN §5.1).
39
+ return (
40
+ ti.dag_id,
41
+ getattr(ti, "run_id", None),
42
+ ti.task_id,
43
+ getattr(ti, "map_index", -1),
44
+ )
45
+
46
+
47
+ def _dag_run_conf(ti) -> dict:
48
+ try:
49
+ ctx = ti.get_template_context()
50
+ conf = getattr(ctx.get("dag_run"), "conf", None)
51
+ if conf:
52
+ return dict(conf)
53
+ except Exception:
54
+ pass
55
+ conf = getattr(getattr(ti, "dag_run", None), "conf", None)
56
+ return dict(conf) if conf else {}
57
+
58
+
59
+ def _resolve_carrier(ti) -> dict:
60
+ native = getattr(ti, "context_carrier", None)
61
+ if isinstance(native, dict) and native.get("traceparent"):
62
+ return {k: v for k, v in native.items() if k in ("traceparent", "tracestate")}
63
+ conf = _dag_run_conf(ti)
64
+ return {k: conf[k] for k in ("traceparent", "tracestate") if k in conf}
65
+
66
+
67
+ @hookimpl
68
+ def on_task_instance_running(previous_state, task_instance, *args, **kwargs):
69
+ try:
70
+ _env_defaults()
71
+ rt = init()
72
+ if rt.mode != "active":
73
+ return
74
+ from opentelemetry import context as otel_context
75
+ from opentelemetry import trace
76
+
77
+ ti = task_instance
78
+ carrier = _resolve_carrier(ti)
79
+ link = link_from_carrier(carrier, TRACE_SOURCE_DAG_RUN_CONF)
80
+ # Bare task_id: mapped instances share one span name and aggregate.
81
+ span = rt.tracer.start_span(
82
+ ti.task_id, kind=trace.SpanKind.SERVER, links=[link] if link else None
83
+ )
84
+ if carrier:
85
+ span.set_attribute(af.AIRFLOW_TASK_CONTEXT_CARRIER, json.dumps(carrier))
86
+ for attr in af.TI_SPAN_ATTRS:
87
+ try:
88
+ value = getattr(ti, attr, None)
89
+ except Exception:
90
+ continue
91
+ if value is None or callable(value):
92
+ continue
93
+ if not isinstance(value, (str, bool, int, float)):
94
+ value = str(value)
95
+ span.set_attribute(af.AIRFLOW_TASK_PREFIX + attr, value)
96
+ token = otel_context.attach(trace.set_span_in_context(span))
97
+ with _lock:
98
+ _active[_ti_key(ti)] = (span, token)
99
+ except Exception:
100
+ log.exception("on_task_instance_running failed")
101
+
102
+
103
+ def _end_span(ti, ok, error=None):
104
+ from opentelemetry import context as otel_context
105
+ from opentelemetry.trace import Status, StatusCode
106
+
107
+ with _lock:
108
+ entry = _active.pop(_ti_key(ti), None)
109
+ if entry is None:
110
+ return
111
+ span, token = entry
112
+ rt = runtime()
113
+ try:
114
+ span.set_attribute(af.AIRFLOW_TASK_STATE, str(getattr(ti, "state", "") or ""))
115
+ if ok:
116
+ span.set_status(Status(StatusCode.OK))
117
+ else:
118
+ # Dual-channel (SPEC §4 doctrine 7): span attrs+event AND stderr,
119
+ # because the pod's log file dies with the pod.
120
+ msg = str(error) if error else "task failed"
121
+ span.set_status(Status(StatusCode.ERROR, msg))
122
+ span.set_attribute(af.AIRFLOW_TASK_ERROR, msg[:2048])
123
+ if isinstance(error, BaseException):
124
+ span.set_attribute(
125
+ "exception.type", f"{type(error).__module__}.{type(error).__name__}"
126
+ )
127
+ try:
128
+ span.record_exception(error, escaped=True)
129
+ except Exception:
130
+ log.warning("record_exception failed", exc_info=True)
131
+ log.error("task %s failed", getattr(ti, "task_id", "?"), exc_info=error)
132
+ else:
133
+ log.error("task %s failed: %s", getattr(ti, "task_id", "?"), msg)
134
+ finally:
135
+ try:
136
+ span.end()
137
+ except Exception:
138
+ log.warning("span.end failed", exc_info=True)
139
+ with contextlib.suppress(Exception):
140
+ otel_context.detach(token)
141
+ if rt is not None and rt.mode == "active":
142
+ flush(rt.provider)
143
+
144
+
145
+ @hookimpl
146
+ def on_task_instance_success(previous_state, task_instance, *args, **kwargs):
147
+ try:
148
+ _end_span(task_instance, ok=True)
149
+ except Exception:
150
+ log.exception("on_task_instance_success failed")
151
+
152
+
153
+ @hookimpl
154
+ def on_task_instance_failed(previous_state, task_instance, error, *args, **kwargs):
155
+ # `error` MUST stay a named param: pluggy binds only named positionals
156
+ # and never splats leftover kwargs (AC-af-4).
157
+ try:
158
+ _end_span(task_instance, ok=False, error=error)
159
+ except Exception:
160
+ log.exception("on_task_instance_failed failed")
161
+
162
+
163
+ @hookimpl
164
+ def on_task_instance_skipped(previous_state, task_instance, *args, **kwargs):
165
+ try:
166
+ _end_span(task_instance, ok=True)
167
+ except Exception:
168
+ log.exception("on_task_instance_skipped failed")
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ from airflow.plugins_manager import AirflowPlugin
4
+
5
+ from . import listener
6
+
7
+
8
+ class AlytricalityTracerPlugin(AirflowPlugin):
9
+ name = "alytricality_tracer"
10
+ listeners = [listener] # noqa: RUF012 - AirflowPlugin reads this as a plain list attribute