narrativetrace-otel 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.
- narrativetrace_otel-0.1.0/.gitignore +28 -0
- narrativetrace_otel-0.1.0/LICENSE +99 -0
- narrativetrace_otel-0.1.0/PKG-INFO +26 -0
- narrativetrace_otel-0.1.0/README.md +11 -0
- narrativetrace_otel-0.1.0/pyproject.toml +32 -0
- narrativetrace_otel-0.1.0/src/narrativetrace_otel/__init__.py +17 -0
- narrativetrace_otel-0.1.0/src/narrativetrace_otel/attributes.py +250 -0
- narrativetrace_otel-0.1.0/src/narrativetrace_otel/exporter.py +68 -0
- narrativetrace_otel-0.1.0/src/narrativetrace_otel/listener.py +111 -0
- narrativetrace_otel-0.1.0/src/narrativetrace_otel/py.typed +0 -0
- narrativetrace_otel-0.1.0/tests/conftest.py +20 -0
- narrativetrace_otel-0.1.0/tests/otel_harness.py +36 -0
- narrativetrace_otel-0.1.0/tests/test_attributes.py +182 -0
- narrativetrace_otel-0.1.0/tests/test_attributes_props.py +36 -0
- narrativetrace_otel-0.1.0/tests/test_exporter.py +203 -0
- narrativetrace_otel-0.1.0/tests/test_listener.py +278 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
.venv/
|
|
4
|
+
.pytest_cache/
|
|
5
|
+
.mypy_cache/
|
|
6
|
+
.ruff_cache/
|
|
7
|
+
.hypothesis/
|
|
8
|
+
.mutmut-cache
|
|
9
|
+
mutants/
|
|
10
|
+
# pytest-benchmark autosave (poe bench-gate): per-machine comparison history, never comparable
|
|
11
|
+
# across machines -- stays local to whichever machine runs the nightly, like .venv/.uv-cache.
|
|
12
|
+
.benchmarks/
|
|
13
|
+
htmlcov/
|
|
14
|
+
.coverage
|
|
15
|
+
.coverage.*
|
|
16
|
+
dist/
|
|
17
|
+
build/
|
|
18
|
+
*.egg-info/
|
|
19
|
+
|
|
20
|
+
# Cache for security-tool binaries auto-fetched by scripts/run_security_tool.py
|
|
21
|
+
.tools/
|
|
22
|
+
|
|
23
|
+
# Local tooling state (contains credentials — never commit)
|
|
24
|
+
.devcontainer/claude-home/
|
|
25
|
+
.agent-run*
|
|
26
|
+
|
|
27
|
+
# Local tooling state (holds host-absolute paths)
|
|
28
|
+
.claude/settings.local.json
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
Business Source License 1.1
|
|
2
|
+
|
|
3
|
+
License text copyright © 2017 MariaDB Corporation Ab, All Rights Reserved.
|
|
4
|
+
"Business Source License" is a trademark of MariaDB Corporation Ab.
|
|
5
|
+
|
|
6
|
+
Parameters
|
|
7
|
+
|
|
8
|
+
Licensor: Empower Agile
|
|
9
|
+
|
|
10
|
+
Licensed Work: NarrativeTrace for Python (the narrativetrace PyPI distributions) version {{VERSION}}. The Licensed Work is (c) 2026 Empower Agile.
|
|
11
|
+
|
|
12
|
+
Additional Use Grant: You may make production use of the Licensed Work for any
|
|
13
|
+
purpose, including internal use and use in products and
|
|
14
|
+
services you provide to your own customers, provided that
|
|
15
|
+
such production use does not include offering the
|
|
16
|
+
Licensed Work, or a product or service whose value
|
|
17
|
+
derives substantially from the Licensed Work, to third
|
|
18
|
+
parties as a logging, tracing, or code-narrative product
|
|
19
|
+
or service.
|
|
20
|
+
|
|
21
|
+
Change Date: Four years from the date the Licensed Work is published. ({{CHANGE_DATE}} for this version)
|
|
22
|
+
|
|
23
|
+
Change License: Apache License, Version 2.0
|
|
24
|
+
|
|
25
|
+
For information about alternative licensing arrangements for the Licensed
|
|
26
|
+
Work, please contact Empower Agile at hello@narrativetrace.ai.
|
|
27
|
+
|
|
28
|
+
Notice
|
|
29
|
+
|
|
30
|
+
The Business Source License (this document, or the "License") is not an Open
|
|
31
|
+
Source license. However, the Licensed Work will eventually be made available
|
|
32
|
+
under an Open Source License, as stated in this License.
|
|
33
|
+
|
|
34
|
+
Terms
|
|
35
|
+
|
|
36
|
+
The Licensor hereby grants you the right to copy, modify, create derivative
|
|
37
|
+
works, redistribute, and make non-production use of the Licensed Work. The
|
|
38
|
+
Licensor may make an Additional Use Grant, above, permitting limited
|
|
39
|
+
production use.
|
|
40
|
+
|
|
41
|
+
Effective on the Change Date, or the fourth anniversary of the first publicly
|
|
42
|
+
available distribution of a specific version of the Licensed Work under this
|
|
43
|
+
License, whichever comes first, the Licensor hereby grants you rights under
|
|
44
|
+
the terms of the Change License, and the rights granted in the paragraph
|
|
45
|
+
above terminate.
|
|
46
|
+
|
|
47
|
+
If your use of the Licensed Work does not comply with the requirements
|
|
48
|
+
currently in effect as described in this License, you must purchase a
|
|
49
|
+
commercial license from the Licensor, its affiliated entities, or authorized
|
|
50
|
+
resellers, or you must refrain from using the Licensed Work.
|
|
51
|
+
|
|
52
|
+
All copies of the original and modified Licensed Work, and derivative works
|
|
53
|
+
of the Licensed Work, are subject to this License. This License applies
|
|
54
|
+
separately for each version of the Licensed Work and the Change Date may vary
|
|
55
|
+
for each version of the Licensed Work released by Licensor.
|
|
56
|
+
|
|
57
|
+
You must conspicuously display this License on each original or modified copy
|
|
58
|
+
of the Licensed Work. If you receive the Licensed Work in original or
|
|
59
|
+
modified form from a third party, the terms and conditions set forth in this
|
|
60
|
+
License apply to your use of that work.
|
|
61
|
+
|
|
62
|
+
Any use of the Licensed Work in violation of this License will automatically
|
|
63
|
+
terminate your rights under this License for the current and all other
|
|
64
|
+
versions of the Licensed Work.
|
|
65
|
+
|
|
66
|
+
This License does not grant you any right in any trademark or logo of
|
|
67
|
+
Licensor or its affiliates (provided that you may use a trademark or logo of
|
|
68
|
+
Licensor as expressly required by this License).
|
|
69
|
+
|
|
70
|
+
TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
|
|
71
|
+
AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
|
|
72
|
+
EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
|
|
73
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
|
|
74
|
+
TITLE.
|
|
75
|
+
|
|
76
|
+
MariaDB hereby grants you permission to use this License’s text to license
|
|
77
|
+
your works, and to refer to it using the trademark “Business Source License”,
|
|
78
|
+
as long as you comply with the Covenants of Licensor below.
|
|
79
|
+
|
|
80
|
+
Covenants of Licensor
|
|
81
|
+
|
|
82
|
+
In consideration of the right to use this License’s text and the “Business
|
|
83
|
+
Source License” name and trademark, Licensor covenants to MariaDB, and to all
|
|
84
|
+
other recipients of the licensed work to be provided by Licensor:
|
|
85
|
+
|
|
86
|
+
1. To specify as the Change License the GPL Version 2.0 or any later version,
|
|
87
|
+
or a license that is compatible with GPL Version 2.0 or a later version,
|
|
88
|
+
where “compatible” means that software provided under the Change License can
|
|
89
|
+
be included in a program with software provided under GPL Version 2.0 or a
|
|
90
|
+
later version. Licensor may specify additional Change Licenses without
|
|
91
|
+
limitation.
|
|
92
|
+
|
|
93
|
+
2. To either: (a) specify an additional grant of rights to use that does not
|
|
94
|
+
impose any additional restriction on the right granted in this License, as
|
|
95
|
+
the Additional Use Grant; or (b) insert the text “None”.
|
|
96
|
+
|
|
97
|
+
3. To specify a Change Date.
|
|
98
|
+
|
|
99
|
+
4. Not to modify this License in any other way.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: narrativetrace-otel
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: OpenTelemetry span bridge for narrativetrace traces
|
|
5
|
+
Project-URL: Homepage, https://github.com/narrativetrace/narrativetrace-python
|
|
6
|
+
Project-URL: Source, https://github.com/narrativetrace/narrativetrace-python
|
|
7
|
+
Author: narrativetrace contributors
|
|
8
|
+
License-Expression: BUSL-1.1
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.12
|
|
12
|
+
Requires-Dist: narrativetrace
|
|
13
|
+
Requires-Dist: opentelemetry-api>=1.20
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# narrativetrace-otel
|
|
17
|
+
|
|
18
|
+
OpenTelemetry span bridge for [narrativetrace](../narrativetrace) traces.
|
|
19
|
+
|
|
20
|
+
Two entry points:
|
|
21
|
+
|
|
22
|
+
* `OtelTraceEventListener` — a live event consumer that opens a span on each enter and
|
|
23
|
+
closes it on the matching exit, anchored to the **event timestamps** (not processing
|
|
24
|
+
time). Orphaned spans are evicted by a bounded `PerishableMap`.
|
|
25
|
+
* `TraceSpanExporter` — a batch exporter that walks a completed `TraceTree`/`TraceNode`
|
|
26
|
+
forest and emits a nested span per node.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# narrativetrace-otel
|
|
2
|
+
|
|
3
|
+
OpenTelemetry span bridge for [narrativetrace](../narrativetrace) traces.
|
|
4
|
+
|
|
5
|
+
Two entry points:
|
|
6
|
+
|
|
7
|
+
* `OtelTraceEventListener` — a live event consumer that opens a span on each enter and
|
|
8
|
+
closes it on the matching exit, anchored to the **event timestamps** (not processing
|
|
9
|
+
time). Orphaned spans are evicted by a bounded `PerishableMap`.
|
|
10
|
+
* `TraceSpanExporter` — a batch exporter that walks a completed `TraceTree`/`TraceNode`
|
|
11
|
+
forest and emits a nested span per node.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "narrativetrace-otel"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "OpenTelemetry span bridge for narrativetrace traces"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
license = "BUSL-1.1"
|
|
8
|
+
# See packages/narrativetrace/pyproject.toml: one byte-identical copy of the root LICENSE per
|
|
9
|
+
# distribution, because PEP 639 forbids reaching out of the project directory.
|
|
10
|
+
license-files = ["LICENSE"]
|
|
11
|
+
authors = [{ name = "narrativetrace contributors" }]
|
|
12
|
+
classifiers = ["Typing :: Typed"]
|
|
13
|
+
dependencies = [
|
|
14
|
+
"narrativetrace",
|
|
15
|
+
"opentelemetry-api>=1.20",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Homepage = "https://github.com/narrativetrace/narrativetrace-python"
|
|
20
|
+
Source = "https://github.com/narrativetrace/narrativetrace-python"
|
|
21
|
+
|
|
22
|
+
[build-system]
|
|
23
|
+
requires = ["hatchling"]
|
|
24
|
+
build-backend = "hatchling.build"
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.wheel]
|
|
27
|
+
packages = ["src/narrativetrace_otel"]
|
|
28
|
+
|
|
29
|
+
[dependency-groups]
|
|
30
|
+
dev = [
|
|
31
|
+
"opentelemetry-sdk>=1.20",
|
|
32
|
+
]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""OpenTelemetry span bridge for narrativetrace traces.
|
|
2
|
+
|
|
3
|
+
Two entry points share the :mod:`narrativetrace_otel.attributes` mapper:
|
|
4
|
+
|
|
5
|
+
* :class:`~narrativetrace_otel.listener.OtelTraceEventListener` — live, span-per-event.
|
|
6
|
+
* :class:`~narrativetrace_otel.exporter.TraceSpanExporter` — batch, tree-to-spans.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from narrativetrace_otel.exporter import TraceSpanExporter
|
|
10
|
+
from narrativetrace_otel.listener import OtelTraceEventListener
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"OtelTraceEventListener",
|
|
16
|
+
"TraceSpanExporter",
|
|
17
|
+
]
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Maps NarrativeTrace signatures, span contexts, and outcomes to OTel span attributes.
|
|
2
|
+
|
|
3
|
+
``SpanContextAttributeMapper`` — the single source of truth shared by the live
|
|
4
|
+
:class:`~narrativetrace_otel.listener.OtelTraceEventListener` and the batch
|
|
5
|
+
:class:`~narrativetrace_otel.exporter.TraceSpanExporter`.
|
|
6
|
+
|
|
7
|
+
Trace-level attributes (``narrative.service.*``, ``narrative.http.*``, user identity) apply only
|
|
8
|
+
to root spans; span-level attributes (class, method, params) apply to every span. Structured
|
|
9
|
+
:class:`~narrativetrace.values.RenderedValue` values flatten to natively-typed OTel attributes
|
|
10
|
+
(int, float, bool, homogeneous arrays); object fields dot-flatten to depth 3. When a structured
|
|
11
|
+
value is absent, a string-inference fallback parses the flat rendered string.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from typing import TYPE_CHECKING
|
|
18
|
+
|
|
19
|
+
from opentelemetry.trace import Span, Status, StatusCode
|
|
20
|
+
|
|
21
|
+
from narrativetrace.canonical import SCHEMA_VERSION
|
|
22
|
+
from narrativetrace.context_export import export as context_export
|
|
23
|
+
from narrativetrace.outcomes import Incomplete, Returned, Threw, TraceOutcome
|
|
24
|
+
from narrativetrace.values import (
|
|
25
|
+
BoolVal,
|
|
26
|
+
FloatVal,
|
|
27
|
+
InstantVal,
|
|
28
|
+
IntVal,
|
|
29
|
+
ListVal,
|
|
30
|
+
ObjectVal,
|
|
31
|
+
RenderedValue,
|
|
32
|
+
StringVal,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from narrativetrace.concurrency import ConcurrencyInfo
|
|
37
|
+
from narrativetrace.nodes import TraceNode
|
|
38
|
+
from narrativetrace.signature import MethodSignature, ParameterCapture
|
|
39
|
+
from narrativetrace.span import SpanContext
|
|
40
|
+
|
|
41
|
+
MAX_FLATTEN_DEPTH = 3
|
|
42
|
+
|
|
43
|
+
# OTel attribute values are str | bool | int | float | sequences thereof.
|
|
44
|
+
AttributeValue = str | bool | int | float | list[str] | list[bool] | list[int] | list[float]
|
|
45
|
+
Sink = Callable[[str, AttributeValue], None]
|
|
46
|
+
|
|
47
|
+
# Root-only trace-level fields: attribute key -> SpanContext extractor.
|
|
48
|
+
_TRACE_LEVEL_FIELDS: list[tuple[str, Callable[[SpanContext], object]]] = [
|
|
49
|
+
("narrative.service.name", lambda sc: sc.service_name),
|
|
50
|
+
("narrative.service.version", lambda sc: sc.service_version),
|
|
51
|
+
("narrative.service.environment", lambda sc: sc.environment),
|
|
52
|
+
("narrative.http.method", lambda sc: sc.http_method),
|
|
53
|
+
("narrative.http.route", lambda sc: sc.http_route),
|
|
54
|
+
("narrative.client_ip", lambda sc: sc.client_ip),
|
|
55
|
+
("narrative.enduser.id", lambda sc: sc.enduser_id),
|
|
56
|
+
("narrative.session.id", lambda sc: sc.session_id),
|
|
57
|
+
("narrative.tenant.id", lambda sc: sc.tenant_id),
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def set_span_attributes(sig: MethodSignature, span: Span) -> None:
|
|
62
|
+
"""Sets span-level attributes (class, method, params) from ``sig``."""
|
|
63
|
+
span.set_attribute("narrative.class", sig.class_name)
|
|
64
|
+
span.set_attribute("narrative.method", sig.method_name)
|
|
65
|
+
for param in sig.parameters:
|
|
66
|
+
_set_param(span.set_attribute, f"narrative.param.{param.name}", param)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def set_concurrency_attributes(info: ConcurrencyInfo | None, span: Span) -> None:
|
|
70
|
+
"""Sets concurrency attributes from ``info`` when present."""
|
|
71
|
+
if info is None:
|
|
72
|
+
return
|
|
73
|
+
span.set_attribute("narrative.concurrency.groupId", info.group_id)
|
|
74
|
+
span.set_attribute("narrative.concurrency.kind", info.kind.name)
|
|
75
|
+
span.set_attribute("narrative.concurrency.threadId", info.thread_id)
|
|
76
|
+
if info.thread_name is not None:
|
|
77
|
+
span.set_attribute("narrative.concurrency.threadName", info.thread_name)
|
|
78
|
+
span.set_attribute("narrative.concurrency.virtual", info.virtual)
|
|
79
|
+
if info.task_label is not None:
|
|
80
|
+
span.set_attribute("narrative.concurrency.taskLabel", info.task_label)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def set_outcome_attributes(outcome: TraceOutcome | None, span: Span) -> None:
|
|
84
|
+
"""Sets outcome attributes/status from ``outcome``."""
|
|
85
|
+
if isinstance(outcome, Returned):
|
|
86
|
+
if outcome.rendered_value is not None:
|
|
87
|
+
span.set_attribute("narrative.outcome", outcome.rendered_value)
|
|
88
|
+
elif isinstance(outcome, Threw):
|
|
89
|
+
span.set_status(Status(StatusCode.ERROR, str(outcome.exception)))
|
|
90
|
+
span.record_exception(outcome.exception)
|
|
91
|
+
elif isinstance(outcome, Incomplete):
|
|
92
|
+
span.set_attribute("narrative.outcome", "in-flight")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def set_trace_identity_attributes(sc: SpanContext | None, span: Span) -> None:
|
|
96
|
+
"""Sets ``narrative.trace_id`` / ``narrative.trace_name`` on every span for correlation."""
|
|
97
|
+
if sc is None:
|
|
98
|
+
return
|
|
99
|
+
span.set_attribute("narrative.trace_id", str(sc.trace_id))
|
|
100
|
+
span.set_attribute("narrative.trace_name", sc.trace_id.human_name())
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def set_nt_schema_attributes(sc: SpanContext | None, span: Span) -> None:
|
|
104
|
+
"""Sets canonical ``nt.*`` schema attributes on the span."""
|
|
105
|
+
if sc is None:
|
|
106
|
+
return
|
|
107
|
+
span.set_attribute("nt.entryType", "entry")
|
|
108
|
+
span.set_attribute("nt.schemaVersion", SCHEMA_VERSION)
|
|
109
|
+
if sc.story_id is not None:
|
|
110
|
+
span.set_attribute("nt.storyId", sc.story_id)
|
|
111
|
+
if sc.chapter_id is not None:
|
|
112
|
+
span.set_attribute("nt.chapterId", sc.chapter_id)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def set_trace_level_attributes(sc: SpanContext | None, span: Span) -> None:
|
|
116
|
+
"""Sets root-only trace-level attributes (service/http/user identity) from ``sc``.
|
|
117
|
+
|
|
118
|
+
Adversarial-audit mirror (2026-09-02): a value set programmatically through
|
|
119
|
+
``set_request_context``/``set_user_context`` (a custom integration, a test, a framework this
|
|
120
|
+
runtime ships no filter for) never passes through the HTTP middleware's own normalisation, so
|
|
121
|
+
this is the last point before it becomes a telemetry attribute -- control-stripped and
|
|
122
|
+
length-capped here regardless of how it arrived.
|
|
123
|
+
"""
|
|
124
|
+
if sc is None:
|
|
125
|
+
return
|
|
126
|
+
for key, extractor in _TRACE_LEVEL_FIELDS:
|
|
127
|
+
value = extractor(sc)
|
|
128
|
+
if value is not None:
|
|
129
|
+
span.set_attribute(key, context_export(str(value)))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def build_event_attributes(
|
|
133
|
+
sig: MethodSignature, outcome: TraceOutcome | None
|
|
134
|
+
) -> dict[str, AttributeValue]:
|
|
135
|
+
"""Builds parent-span event attributes from a child's signature and outcome."""
|
|
136
|
+
attrs: dict[str, AttributeValue] = {}
|
|
137
|
+
for param in sig.parameters:
|
|
138
|
+
if param.redacted or param.rendered_value == "":
|
|
139
|
+
continue
|
|
140
|
+
_set_param(_dict_sink(attrs), f"narrative.param.{param.name}", param, allow_lists=False)
|
|
141
|
+
_add_outcome_to_event(attrs, outcome)
|
|
142
|
+
return attrs
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def emit_child_event(parent_span: Span, child: TraceNode) -> None:
|
|
146
|
+
"""Emits a child method completion as a timestamped event on the parent span."""
|
|
147
|
+
attrs = build_event_attributes(child.signature, child.outcome)
|
|
148
|
+
name = f"{child.signature.class_name}.{child.signature.method_name}"
|
|
149
|
+
timestamp = child.start_time_nanos + child.duration_nanos
|
|
150
|
+
parent_span.add_event(name, attributes=attrs, timestamp=timestamp)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _dict_sink(attrs: dict[str, AttributeValue]) -> Sink:
|
|
154
|
+
def sink(key: str, value: AttributeValue) -> None:
|
|
155
|
+
attrs[key] = value
|
|
156
|
+
|
|
157
|
+
return sink
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _set_param(
|
|
161
|
+
sink: Sink, prefix: str, param: ParameterCapture, *, allow_lists: bool = True
|
|
162
|
+
) -> None:
|
|
163
|
+
if param.redacted or param.rendered_value == "":
|
|
164
|
+
return
|
|
165
|
+
structured = param.structured_value
|
|
166
|
+
if structured is None:
|
|
167
|
+
sink(prefix, _typed_from_string(param.rendered_value))
|
|
168
|
+
else:
|
|
169
|
+
_flatten(structured, prefix, 0, sink, allow_lists=allow_lists)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _flatten(
|
|
173
|
+
value: RenderedValue, prefix: str, depth: int, sink: Sink, *, allow_lists: bool
|
|
174
|
+
) -> None:
|
|
175
|
+
scalar = _scalar_native(value)
|
|
176
|
+
if scalar is not None:
|
|
177
|
+
sink(prefix, scalar)
|
|
178
|
+
return
|
|
179
|
+
if isinstance(value, ObjectVal) and depth < MAX_FLATTEN_DEPTH:
|
|
180
|
+
for key, field_value in value.fields.items():
|
|
181
|
+
_flatten(field_value, f"{prefix}.{key}", depth + 1, sink, allow_lists=allow_lists)
|
|
182
|
+
elif allow_lists and isinstance(value, ListVal):
|
|
183
|
+
array = _list_native(value)
|
|
184
|
+
if array is not None:
|
|
185
|
+
sink(prefix, array)
|
|
186
|
+
# NullVal, depth-exceeded ObjectVal, and (in events) ListVal are skipped.
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _scalar_native(value: RenderedValue) -> AttributeValue | None:
|
|
190
|
+
if isinstance(value, StringVal):
|
|
191
|
+
return value.value
|
|
192
|
+
if isinstance(value, BoolVal):
|
|
193
|
+
return value.value
|
|
194
|
+
if isinstance(value, IntVal):
|
|
195
|
+
return value.value
|
|
196
|
+
if isinstance(value, FloatVal):
|
|
197
|
+
return value.value
|
|
198
|
+
if isinstance(value, InstantVal):
|
|
199
|
+
return value.epoch_millis
|
|
200
|
+
return None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
# Java emits homogeneous arrays only for these scalar types; all carry a ``.value`` field.
|
|
204
|
+
_ARRAY_ELEMENT_TYPES = (StringVal, BoolVal, IntVal, FloatVal)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _list_native(value: ListVal) -> AttributeValue | None:
|
|
208
|
+
if not value.elements:
|
|
209
|
+
return None
|
|
210
|
+
first = type(value.elements[0])
|
|
211
|
+
if first not in _ARRAY_ELEMENT_TYPES:
|
|
212
|
+
return None
|
|
213
|
+
if any(type(element) is not first for element in value.elements):
|
|
214
|
+
return None
|
|
215
|
+
return [element.value for element in value.elements] # type: ignore[attr-defined]
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _typed_from_string(rendered: str) -> AttributeValue:
|
|
219
|
+
if rendered in ("true", "false"):
|
|
220
|
+
return rendered == "true"
|
|
221
|
+
parsed_int = _try_int(rendered)
|
|
222
|
+
if parsed_int is not None:
|
|
223
|
+
return parsed_int
|
|
224
|
+
parsed_float = _try_float(rendered)
|
|
225
|
+
if parsed_float is not None:
|
|
226
|
+
return parsed_float
|
|
227
|
+
if len(rendered) >= 2 and rendered.startswith('"') and rendered.endswith('"'):
|
|
228
|
+
return rendered[1:-1]
|
|
229
|
+
return rendered
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _try_int(text: str) -> int | None:
|
|
233
|
+
try:
|
|
234
|
+
return int(text)
|
|
235
|
+
except ValueError:
|
|
236
|
+
return None
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _try_float(text: str) -> float | None:
|
|
240
|
+
try:
|
|
241
|
+
return float(text)
|
|
242
|
+
except ValueError:
|
|
243
|
+
return None
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _add_outcome_to_event(attrs: dict[str, AttributeValue], outcome: TraceOutcome | None) -> None:
|
|
247
|
+
if isinstance(outcome, Returned) and outcome.rendered_value is not None:
|
|
248
|
+
attrs["narrative.outcome"] = outcome.rendered_value
|
|
249
|
+
elif isinstance(outcome, Threw):
|
|
250
|
+
attrs["narrative.outcome"] = f"error: {outcome.exception}"
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Batch exporter for completed NarrativeTrace trees.
|
|
2
|
+
|
|
3
|
+
``TraceSpanExporter``. Use this after capture when a full
|
|
4
|
+
:class:`~narrativetrace.nodes.TraceNode` forest is in hand and should be published to an OTel
|
|
5
|
+
backend. Parent-child structure is recreated by nesting span scopes during export; the exporter
|
|
6
|
+
does not reuse the original span-context ids as OTel span ids. Nodes with
|
|
7
|
+
:class:`~narrativetrace.outcomes.Incomplete` outcome export with ``narrative.outcome="in-flight"``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
|
+
|
|
14
|
+
from opentelemetry.trace import Span, Tracer, use_span
|
|
15
|
+
|
|
16
|
+
from narrativetrace.tree_walk import CYCLE_MARKER, DEPTH_LIMIT_MARKER, TreeWalk
|
|
17
|
+
from narrativetrace_otel import attributes
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from collections.abc import Iterable
|
|
21
|
+
|
|
22
|
+
from narrativetrace.nodes import TraceNode
|
|
23
|
+
|
|
24
|
+
_NANOS_PER_MILLI = 1_000_000.0
|
|
25
|
+
|
|
26
|
+
_TRUNCATED_REASON = {DEPTH_LIMIT_MARKER: "depth-limit", CYCLE_MARKER: "cycle"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class TraceSpanExporter:
|
|
30
|
+
"""Exports completed :class:`~narrativetrace.nodes.TraceNode` trees as nested OTel spans."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, tracer: Tracer) -> None:
|
|
33
|
+
self._tracer = tracer
|
|
34
|
+
|
|
35
|
+
def export(self, roots: Iterable[TraceNode]) -> None:
|
|
36
|
+
"""Exports each root node (and its subtree) as a span tree."""
|
|
37
|
+
walk = TreeWalk()
|
|
38
|
+
for root in roots:
|
|
39
|
+
self._export_node(root, is_root=True, walk=walk)
|
|
40
|
+
|
|
41
|
+
def _export_node(self, node: TraceNode, *, is_root: bool, walk: TreeWalk) -> None:
|
|
42
|
+
sig = node.signature
|
|
43
|
+
span = self._tracer.start_span(f"{sig.class_name}.{sig.method_name}")
|
|
44
|
+
attributes.set_span_attributes(sig, span)
|
|
45
|
+
attributes.set_trace_identity_attributes(node.span_context, span)
|
|
46
|
+
attributes.set_nt_schema_attributes(node.span_context, span)
|
|
47
|
+
span.set_attribute("narrative.duration_ms", node.duration_nanos / _NANOS_PER_MILLI)
|
|
48
|
+
attributes.set_outcome_attributes(node.outcome, span)
|
|
49
|
+
attributes.set_concurrency_attributes(node.concurrency, span)
|
|
50
|
+
if is_root:
|
|
51
|
+
attributes.set_trace_level_attributes(node.span_context, span)
|
|
52
|
+
self._export_children(node, span, walk)
|
|
53
|
+
span.end()
|
|
54
|
+
|
|
55
|
+
def _export_children(self, node: TraceNode, span: Span, walk: TreeWalk) -> None:
|
|
56
|
+
stop_reason = walk.stop_reason(node)
|
|
57
|
+
if stop_reason is not None:
|
|
58
|
+
if node.children:
|
|
59
|
+
span.set_attribute("narrative.truncated", _TRUNCATED_REASON[stop_reason])
|
|
60
|
+
return
|
|
61
|
+
walk.enter(node)
|
|
62
|
+
try:
|
|
63
|
+
with use_span(span, end_on_exit=False):
|
|
64
|
+
for child in node.children:
|
|
65
|
+
attributes.emit_child_event(span, child)
|
|
66
|
+
self._export_node(child, is_root=False, walk=walk)
|
|
67
|
+
finally:
|
|
68
|
+
walk.exit(node)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Live event-stream bridge from NarrativeTrace events to OpenTelemetry spans.
|
|
2
|
+
|
|
3
|
+
``OtelTraceEventListener``. Plug this into the core pipeline as an event consumer to
|
|
4
|
+
create spans as methods execute rather than after the whole tree is built. A
|
|
5
|
+
:class:`~narrativetrace.pipeline.perishable.PerishableMap` of active spans is keyed by
|
|
6
|
+
NarrativeTrace :class:`~narrativetrace.ids.SpanId`: an enter starts a span, the matching exit
|
|
7
|
+
ends it. Orphaned spans (enter without exit) are evicted by the map's TTL/capacity limits and
|
|
8
|
+
ended with :data:`~opentelemetry.trace.StatusCode.ERROR` description ``"orphaned"``.
|
|
9
|
+
|
|
10
|
+
Parent-child links are reconstructed from explicit NarrativeTrace parent span ids, not from
|
|
11
|
+
OTel's ambient context alone, so interleaved enter/exit pairs from concurrent traces resolve
|
|
12
|
+
correctly.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import TYPE_CHECKING
|
|
19
|
+
|
|
20
|
+
from opentelemetry.trace import Span, Status, StatusCode, Tracer, set_span_in_context
|
|
21
|
+
|
|
22
|
+
from narrativetrace.events import EnterEvent, ExitEvent, TraceEvent
|
|
23
|
+
from narrativetrace.pipeline.perishable import PerishableMap
|
|
24
|
+
from narrativetrace_otel import attributes
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from narrativetrace.ids import SpanId
|
|
28
|
+
from narrativetrace.signature import MethodSignature
|
|
29
|
+
|
|
30
|
+
_DEFAULT_MAX_ACTIVE_SPANS = 1024
|
|
31
|
+
_DEFAULT_TTL_SECONDS = 3600.0
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class _SpanFrame:
|
|
36
|
+
"""Pairs an OTel span with the signature captured at enter time."""
|
|
37
|
+
|
|
38
|
+
span: Span
|
|
39
|
+
signature: MethodSignature
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class OtelTraceEventListener:
|
|
43
|
+
"""Consumes :class:`~narrativetrace.events.TraceEvent` and produces OTel spans live."""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
tracer: Tracer,
|
|
48
|
+
max_active_spans: int = _DEFAULT_MAX_ACTIVE_SPANS,
|
|
49
|
+
ttl_seconds: float = _DEFAULT_TTL_SECONDS,
|
|
50
|
+
) -> None:
|
|
51
|
+
self._tracer = tracer
|
|
52
|
+
self._active_spans: PerishableMap[SpanId, _SpanFrame] = PerishableMap(
|
|
53
|
+
max_active_spans, ttl_seconds, lambda frame: _end_as_orphaned(frame.span)
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
def __call__(self, event: TraceEvent) -> None:
|
|
57
|
+
"""Dispatches an event; non enter/exit events are ignored."""
|
|
58
|
+
if isinstance(event, EnterEvent):
|
|
59
|
+
self._handle_enter(event)
|
|
60
|
+
elif isinstance(event, ExitEvent):
|
|
61
|
+
self._handle_exit(event)
|
|
62
|
+
|
|
63
|
+
def _handle_enter(self, enter: EnterEvent) -> None:
|
|
64
|
+
sig = enter.signature
|
|
65
|
+
sc = enter.span_context
|
|
66
|
+
name = f"{sig.class_name}.{sig.method_name}"
|
|
67
|
+
parent_frame = (
|
|
68
|
+
self._active_spans.get(sc.parent_span_id) if sc.parent_span_id is not None else None
|
|
69
|
+
)
|
|
70
|
+
context = set_span_in_context(parent_frame.span) if parent_frame is not None else None
|
|
71
|
+
span = self._tracer.start_span(name, context=context, start_time=enter.timestamp_nanos)
|
|
72
|
+
attributes.set_span_attributes(sig, span)
|
|
73
|
+
attributes.set_trace_identity_attributes(sc, span)
|
|
74
|
+
attributes.set_nt_schema_attributes(sc, span)
|
|
75
|
+
if sc.parent_span_id is None:
|
|
76
|
+
attributes.set_trace_level_attributes(sc, span)
|
|
77
|
+
self._active_spans.put(sc.span_id, _SpanFrame(span, sig))
|
|
78
|
+
|
|
79
|
+
def _handle_exit(self, exit_event: ExitEvent) -> None:
|
|
80
|
+
frame = self._active_spans.remove(exit_event.span_context.span_id)
|
|
81
|
+
if frame is None:
|
|
82
|
+
self._handle_exit_without_enter(exit_event)
|
|
83
|
+
return
|
|
84
|
+
attributes.set_outcome_attributes(exit_event.outcome, frame.span)
|
|
85
|
+
frame.span.end(end_time=exit_event.timestamp_nanos)
|
|
86
|
+
self._emit_event_on_parent(exit_event, frame.signature)
|
|
87
|
+
|
|
88
|
+
def _emit_event_on_parent(self, exit_event: ExitEvent, sig: MethodSignature) -> None:
|
|
89
|
+
parent_span_id = exit_event.span_context.parent_span_id
|
|
90
|
+
if parent_span_id is None:
|
|
91
|
+
return
|
|
92
|
+
parent_frame = self._active_spans.get(parent_span_id)
|
|
93
|
+
if parent_frame is None:
|
|
94
|
+
return
|
|
95
|
+
attrs = attributes.build_event_attributes(sig, exit_event.outcome)
|
|
96
|
+
name = f"{sig.class_name}.{sig.method_name}"
|
|
97
|
+
parent_frame.span.add_event(name, attributes=attrs, timestamp=exit_event.timestamp_nanos)
|
|
98
|
+
|
|
99
|
+
def _handle_exit_without_enter(self, exit_event: ExitEvent) -> None:
|
|
100
|
+
sc = exit_event.span_context
|
|
101
|
+
span = self._tracer.start_span(str(sc.span_id), start_time=exit_event.timestamp_nanos)
|
|
102
|
+
attributes.set_trace_identity_attributes(sc, span)
|
|
103
|
+
attributes.set_trace_level_attributes(sc, span)
|
|
104
|
+
attributes.set_outcome_attributes(exit_event.outcome, span)
|
|
105
|
+
span.set_status(Status(StatusCode.ERROR, "orphaned — enter event lost"))
|
|
106
|
+
span.end(end_time=exit_event.timestamp_nanos)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _end_as_orphaned(span: Span) -> None:
|
|
110
|
+
span.set_status(Status(StatusCode.ERROR, "orphaned — exit event lost"))
|
|
111
|
+
span.end()
|
|
File without changes
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Shared fixtures: an in-memory OTel tracer capturing finished spans for assertions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
9
|
+
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
|
10
|
+
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
|
11
|
+
from otel_harness import Harness
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.fixture
|
|
15
|
+
def otel() -> Iterator[Harness]:
|
|
16
|
+
exporter = InMemorySpanExporter()
|
|
17
|
+
provider = TracerProvider()
|
|
18
|
+
provider.add_span_processor(SimpleSpanProcessor(exporter))
|
|
19
|
+
yield Harness(provider.get_tracer("narrativetrace"), exporter)
|
|
20
|
+
provider.shutdown()
|