kitaru-logfire-importer 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,305 @@
1
+ # iCloud conflict duplicates (pattern: "filename 2.ext" or "filename 2")
2
+ *[[:space:]]2.[!.]*
3
+ *[[:space:]]2
4
+
5
+ # Helm dependency artifacts (rebuilt via helm dep update)
6
+ helm/charts/
7
+ helm/Chart.lock
8
+
9
+ # Root TypeScript workspace
10
+ /node_modules/
11
+ /packages/*/node_modules/
12
+ /v2_examples/mastra_support_triage/node_modules/
13
+ /v2_examples/vercel_ai_support_triage/node_modules/
14
+ /packages/*/dist/
15
+ /typescript-dist/
16
+
17
+ # pnpm
18
+ **/.pnpm-store
19
+
20
+ # macOS
21
+ .DS_Store
22
+
23
+ # Byte-compiled / optimized / DLL files
24
+ __pycache__/
25
+ *.py[codz]
26
+ *$py.class
27
+
28
+ # C extensions
29
+ *.so
30
+
31
+ # Distribution / packaging
32
+ .Python
33
+ build/
34
+ develop-eggs/
35
+ dist/
36
+ plugins/candidate-wheels/*
37
+ !plugins/candidate-wheels/.gitkeep
38
+ downloads/
39
+ eggs/
40
+ .eggs/
41
+ lib/
42
+ !docs/lib/
43
+ lib64/
44
+ parts/
45
+ sdist/
46
+ var/
47
+ wheels/
48
+ share/python-wheels/
49
+ *.egg-info/
50
+ .installed.cfg
51
+ *.egg
52
+ MANIFEST
53
+
54
+ # PyInstaller
55
+ # Usually these files are written by a python script from a template
56
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
57
+ *.manifest
58
+ *.spec
59
+
60
+ # Installer logs
61
+ pip-log.txt
62
+ pip-delete-this-directory.txt
63
+
64
+ # Unit test / coverage reports
65
+ htmlcov/
66
+ .tox/
67
+ .nox/
68
+ .coverage
69
+ .coverage.*
70
+ .cache
71
+ nosetests.xml
72
+ coverage.xml
73
+ *.cover
74
+ *.py.cover
75
+ .hypothesis/
76
+ .pytest_cache/
77
+ cover/
78
+
79
+ # Translations
80
+ *.mo
81
+ *.pot
82
+
83
+ # Django stuff:
84
+ *.log
85
+ local_settings.py
86
+ db.sqlite3
87
+ db.sqlite3-journal
88
+
89
+ # Flask stuff:
90
+ instance/
91
+ .webassets-cache
92
+
93
+ # Scrapy stuff:
94
+ .scrapy
95
+
96
+ # Sphinx documentation
97
+ docs/_build/
98
+
99
+ # PyBuilder
100
+ .pybuilder/
101
+ target/
102
+
103
+ # Jupyter Notebook
104
+ .ipynb_checkpoints
105
+
106
+ # IPython
107
+ profile_default/
108
+ ipython_config.py
109
+
110
+ # pyenv
111
+ # For a library or package, you might want to ignore these files since the code is
112
+ # intended to run in multiple environments; otherwise, check them in:
113
+ # .python-version
114
+
115
+ # pipenv
116
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
117
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
118
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
119
+ # install all needed dependencies.
120
+ #Pipfile.lock
121
+
122
+ # UV
123
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
124
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
125
+ # commonly ignored for libraries.
126
+ #uv.lock
127
+
128
+ # poetry
129
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
130
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
131
+ # commonly ignored for libraries.
132
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
133
+ #poetry.lock
134
+ #poetry.toml
135
+
136
+ # pdm
137
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
138
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
139
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
140
+ #pdm.lock
141
+ #pdm.toml
142
+ .pdm-python
143
+ .pdm-build/
144
+
145
+ # pixi
146
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
147
+ #pixi.lock
148
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
149
+ # in the .venv directory. It is recommended not to include this directory in version control.
150
+ .pixi
151
+
152
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
153
+ __pypackages__/
154
+
155
+ # Celery stuff
156
+ celerybeat-schedule
157
+ celerybeat.pid
158
+
159
+ # SageMath parsed files
160
+ *.sage.py
161
+
162
+ # Environments
163
+ .env
164
+ .envrc
165
+ .venv
166
+ env/
167
+ venv/
168
+ ENV/
169
+ env.bak/
170
+ venv.bak/
171
+
172
+ # Spyder project settings
173
+ .spyderproject
174
+ .spyproject
175
+
176
+ # Rope project settings
177
+ .ropeproject
178
+
179
+ # mypy
180
+ .mypy_cache/
181
+ .dmypy.json
182
+ dmypy.json
183
+
184
+ # Pyre type checker
185
+ .pyre/
186
+
187
+ # pytype static type analyzer
188
+ .pytype/
189
+
190
+ # Cython debug symbols
191
+ cython_debug/
192
+
193
+ # PyCharm
194
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
195
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
196
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
197
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
198
+ #.idea/
199
+
200
+ # Abstra
201
+ # Abstra is an AI-powered process automation framework.
202
+ # Ignore directories containing user credentials, local state, and settings.
203
+ # Learn more at https://abstra.io/docs
204
+ .abstra/
205
+
206
+ # Visual Studio Code
207
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
208
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
209
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
210
+ # you could uncomment the following to ignore the entire vscode folder
211
+ # .vscode/
212
+
213
+ # Ruff stuff:
214
+ .ruff_cache/
215
+
216
+ # PyPI configuration file
217
+ .pypirc
218
+
219
+ # Cursor
220
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
221
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
222
+ # refer to https://docs.cursor.com/context/ignore-files
223
+ .cursorignore
224
+ .cursorindexingignore
225
+
226
+ # Marimo
227
+ marimo/_static/
228
+ marimo/_lsp/
229
+ __marimo__/
230
+
231
+ # Cloudflare local state
232
+ .wrangler/
233
+
234
+ # Local project markers
235
+ .kitaru/
236
+ .zen/
237
+
238
+ # Git worktrees (isolated workspaces created via git worktree add)
239
+ .worktrees/
240
+
241
+ # Design docs + Repoprompt
242
+ design/
243
+ dogfood-output/
244
+ prompt-exports/
245
+
246
+ # Local Kitaru UI build artifacts (used by docker/Dockerfile.server-dev)
247
+ docker/kitaru-ui-dist/
248
+
249
+ # MCP
250
+ .mcp.json
251
+
252
+ # Claude
253
+ **/.claude/settings.local.json
254
+ .claude/*
255
+ !.claude/settings.json
256
+ !.claude/skills/
257
+
258
+ # Playwright MCP
259
+ .playwright-mcp/
260
+
261
+ # Bundled Kitaru UI (generated at build time by scripts/download-ui.sh)
262
+ src/kitaru/_ui/dist/
263
+ src/kitaru/_ui/bundle_manifest.json
264
+ .kitaru-ui-bundles/
265
+
266
+ # Codex
267
+ .codex/*
268
+ !.codex/skills/
269
+ AGENTS.override.md
270
+ .agents/skills/*
271
+ !.agents/skills/kitaru-dev/
272
+ !.agents/skills/kitaru-dev/**
273
+ !.agents/skills/kitaru-docs/
274
+ !.agents/skills/kitaru-docs/**
275
+ !.agents/skills/kitaru-release/
276
+ !.agents/skills/kitaru-release/**
277
+ !.agents/skills/kitaru-evaluator-authoring/
278
+ !.agents/skills/kitaru-evaluator-authoring/**
279
+ !.agents/skills/kitaru-session-improvement/
280
+ !.agents/skills/kitaru-session-improvement/**
281
+ !.agents/skills/kitaru-tests-release/
282
+ !.agents/skills/kitaru-tests-release/**
283
+
284
+ # Agent Skills
285
+ .pi/
286
+ .claude/skills/building-pydantic-ai-agents
287
+ .claude/skills/instrumentation
288
+ skills-lock.json
289
+
290
+ # Local PR review screenshots
291
+ .pr-screenshots/
292
+
293
+ # Local scratch — single-developer scratch flow files at repo root
294
+ /my_flow.py
295
+ .claude/skills/logfire-instrumentation
296
+ .clawpatch/
297
+ docs/investigations/
298
+ docs/plans/
299
+ docs/reviews/
300
+ plans/
301
+ replay-verify-reports-live/
302
+ replay-verify-reports/
303
+
304
+ # OpenAPI baseline build output
305
+ openapi/.build/
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - First stable release of the Logfire records-query importer.
6
+
7
+ ## 0.1.0rc0
8
+
9
+ - Add the Logfire records-query importer.
@@ -0,0 +1,7 @@
1
+ Metadata-Version: 2.5
2
+ Name: kitaru-logfire-importer
3
+ Version: 0.1.0
4
+ Summary: Logfire records-query importer for Kitaru.
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.11
7
+ Requires-Dist: kitaru>=0.22.0
@@ -0,0 +1,14 @@
1
+ [project]
2
+ name = "kitaru-logfire-importer"
3
+ version = "0.1.0"
4
+ description = "Logfire records-query importer for Kitaru."
5
+ license = "Apache-2.0"
6
+ requires-python = ">=3.11"
7
+ dependencies = ["kitaru>=0.22.0"]
8
+
9
+ [build-system]
10
+ requires = ["hatchling==1.32.0"]
11
+ build-backend = "hatchling.build"
12
+
13
+ [tool.hatch.build.targets.wheel]
14
+ packages = ["src/kitaru_logfire_importer"]
@@ -0,0 +1,5 @@
1
+ """Logfire importer plugin for Kitaru."""
2
+
3
+ from kitaru_logfire_importer.importer import parse
4
+
5
+ __all__ = ["parse"]
@@ -0,0 +1,801 @@
1
+ # Copyright (c) ZenML GmbH 2026. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # /// script
15
+ # requires-python = ">=3.11"
16
+ # dependencies = []
17
+ # ///
18
+ """Logfire records-query importer plugin."""
19
+
20
+ import json
21
+ import re
22
+ from collections import defaultdict
23
+ from collections.abc import Iterator
24
+ from dataclasses import dataclass
25
+ from datetime import UTC, datetime
26
+ from decimal import Decimal, InvalidOperation
27
+ from typing import Any
28
+
29
+ from kitaru.api_models.v1.imports import ImportFailure
30
+ from kitaru.api_models.v1.session import SessionStatus, TokenUsage
31
+ from kitaru.api_models.v1.session_node import NodeStatus, NodeType
32
+ from kitaru.task.importer import ImportedNode, ImportedSession
33
+
34
+ MAX_UPLOAD_BYTES = 50 * 1024 * 1024
35
+ _DEFAULT_JOIN_PATHS = (
36
+ "attributes.session.id",
37
+ "attributes.session_id",
38
+ "attributes.conversation_id",
39
+ "attributes.thread_id",
40
+ "attributes.gen_ai.conversation.id",
41
+ "attributes.conversation.id",
42
+ )
43
+ _METADATA_COLUMNS = (
44
+ "deployment_environment",
45
+ "service_name",
46
+ "service_namespace",
47
+ "service_version",
48
+ "otel_scope_name",
49
+ "otel_scope_version",
50
+ "tags",
51
+ )
52
+ _ATTRIBUTE_METADATA_KEYS = {
53
+ "agent_name",
54
+ "deployment.environment.name",
55
+ "gen_ai.agent.name",
56
+ "gen_ai.conversation.id",
57
+ "gen_ai.operation.name",
58
+ "gen_ai.provider.name",
59
+ "gen_ai.request.model",
60
+ "gen_ai.response.model",
61
+ "gen_ai.system",
62
+ "service.name",
63
+ "service.version",
64
+ "session.id",
65
+ "session_id",
66
+ "thread_id",
67
+ "user.id",
68
+ }
69
+ _FRAMEWORK_PATTERNS = (
70
+ (re.compile(r"pydantic[._ -]?ai", re.IGNORECASE), "pydantic-ai"),
71
+ (re.compile(r"langgraph", re.IGNORECASE), "langgraph"),
72
+ (re.compile(r"openai[._ -]?agents?", re.IGNORECASE), "openai-agents"),
73
+ (re.compile(r"google[._ -]?adk", re.IGNORECASE), "google-adk"),
74
+ (
75
+ re.compile(r"claude[._ -]?agent[._ -]?sdk|claudeagentsdk", re.IGNORECASE),
76
+ "claude-agent-sdk",
77
+ ),
78
+ )
79
+
80
+
81
+ class InvalidImport(ValueError):
82
+ """Raised when a Logfire payload cannot be parsed."""
83
+
84
+
85
+ @dataclass(frozen=True, slots=True)
86
+ class _Turn:
87
+ """One Logfire trace within a session."""
88
+
89
+ trace_id: str
90
+ inputs: Any
91
+ outputs: Any
92
+ started_at: datetime | None
93
+ ended_at: datetime | None
94
+
95
+
96
+ def _decode_json(value: Any) -> Any:
97
+ """Decode JSON-encoded query columns while preserving ordinary strings."""
98
+ if not isinstance(value, str):
99
+ return value
100
+ stripped = value.strip()
101
+ if not stripped or stripped[0] not in '[{"':
102
+ return value
103
+ try:
104
+ return json.loads(stripped)
105
+ except json.JSONDecodeError:
106
+ return value
107
+
108
+
109
+ def _dict(value: Any) -> dict[str, Any]:
110
+ """Return a decoded dictionary or an empty dictionary."""
111
+ decoded = _decode_json(value)
112
+ return decoded if isinstance(decoded, dict) else {}
113
+
114
+
115
+ def _datetime(value: Any) -> datetime | None:
116
+ """Parse a Logfire timestamp."""
117
+ if isinstance(value, datetime):
118
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
119
+ if not isinstance(value, str) or not value.strip():
120
+ return None
121
+ try:
122
+ parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
123
+ except ValueError:
124
+ return None
125
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
126
+
127
+
128
+ def _integer(value: Any) -> int | None:
129
+ """Parse an integer attribute."""
130
+ if value in (None, ""):
131
+ return None
132
+ try:
133
+ return int(value)
134
+ except (TypeError, ValueError):
135
+ return None
136
+
137
+
138
+ def _decimal(value: Any) -> Decimal | None:
139
+ """Parse a decimal attribute."""
140
+ if value in (None, ""):
141
+ return None
142
+ try:
143
+ return Decimal(str(value))
144
+ except (InvalidOperation, ValueError):
145
+ return None
146
+
147
+
148
+ def _parse_records(content: bytes) -> list[dict[str, Any]]:
149
+ """Parse Logfire JSON, JSONL, or streaming NDJSON output."""
150
+ if len(content) > MAX_UPLOAD_BYTES:
151
+ raise InvalidImport("Logfire import exceeds the 50 MiB upload limit")
152
+ try:
153
+ text = content.decode("utf-8")
154
+ except UnicodeDecodeError as exc:
155
+ raise InvalidImport("Import file must be UTF-8 JSON or JSONL") from exc
156
+ if not text.strip():
157
+ raise InvalidImport("Import file contains no JSON records")
158
+ try:
159
+ decoded = json.loads(text)
160
+ except json.JSONDecodeError:
161
+ values: list[Any] = []
162
+ for line_number, line in enumerate(text.splitlines(), start=1):
163
+ if not line.strip():
164
+ continue
165
+ try:
166
+ values.append(json.loads(line))
167
+ except json.JSONDecodeError as exc:
168
+ raise InvalidImport(f"Line {line_number} is not valid JSON") from exc
169
+ else:
170
+ if isinstance(decoded, dict) and isinstance(decoded.get("data"), list):
171
+ values = decoded["data"]
172
+ elif isinstance(decoded, list):
173
+ values = decoded
174
+ else:
175
+ values = [decoded]
176
+
177
+ records: list[dict[str, Any]] = []
178
+ for line_number, value in enumerate(values, start=1):
179
+ if not isinstance(value, dict):
180
+ raise InvalidImport(f"Record {line_number} must be a JSON object")
181
+ message_type = value.get("type")
182
+ if message_type in {"schema", "explain", "end"}:
183
+ continue
184
+ if message_type == "error":
185
+ raise InvalidImport(
186
+ str(
187
+ value.get("message")
188
+ or value.get("error")
189
+ or "Logfire query export failed"
190
+ )
191
+ )
192
+ if message_type == "data" and isinstance(value.get("rows"), list):
193
+ rows = value["rows"]
194
+ if not all(isinstance(row, dict) for row in rows):
195
+ raise InvalidImport(
196
+ f"Record {line_number} contains a non-object Logfire row"
197
+ )
198
+ records.extend(rows)
199
+ elif message_type == "data" and isinstance(value.get("data"), dict):
200
+ records.append(value["data"])
201
+ else:
202
+ records.append(value)
203
+ if not records:
204
+ raise InvalidImport("Import file contains no Logfire data rows")
205
+ return records
206
+
207
+
208
+ def _path_parts(path: str) -> list[str]:
209
+ """Parse a dotted path or RFC 6901 JSON Pointer."""
210
+ if not path.strip():
211
+ raise InvalidImport("join path must be non-empty")
212
+ if not path.startswith("/"):
213
+ return path.split(".")
214
+ parts = path[1:].split("/")
215
+ if any(re.search(r"~(?:[^01]|$)", part) for part in parts):
216
+ raise InvalidImport("join path contains an invalid JSON Pointer escape")
217
+ return [part.replace("~1", "/").replace("~0", "~") for part in parts]
218
+
219
+
220
+ def _path_value(record: dict[str, Any], path: str) -> Any:
221
+ """Resolve a grouping path, including dotted OpenTelemetry attribute keys."""
222
+ parts = _path_parts(path)
223
+ current: Any = record
224
+ for index, part in enumerate(parts):
225
+ current = _decode_json(current)
226
+ if not isinstance(current, dict):
227
+ return None
228
+ if part in current:
229
+ current = current[part]
230
+ continue
231
+ remainder = ".".join(parts[index:])
232
+ return current.get(remainder)
233
+ return _decode_json(current)
234
+
235
+
236
+ def _is_missing_identity(value: Any) -> bool:
237
+ """Return whether a grouping value has no usable identity."""
238
+ if value in (None, ""):
239
+ return True
240
+ if not isinstance(value, str):
241
+ return False
242
+ return value.strip().casefold() in {"[redacted]", "[scrubbed]"}
243
+
244
+
245
+ def _join_value(
246
+ records: list[dict[str, Any]], params: dict[str, Any], trace_id: str
247
+ ) -> tuple[str, str, bool]:
248
+ """Select the stable session identity for one trace."""
249
+ configured = params.get("join_on")
250
+ if configured is not None and not isinstance(configured, str):
251
+ raise InvalidImport("join_on must be a dotted path or JSON pointer")
252
+ paths = (configured,) if configured else _DEFAULT_JOIN_PATHS
253
+ for path in paths:
254
+ values = {
255
+ str(value)
256
+ for record in records
257
+ if not _is_missing_identity(value := _path_value(record, path))
258
+ }
259
+ if len(values) > 1:
260
+ raise InvalidImport(
261
+ f"Trace '{trace_id}' has conflicting values at join path '{path}'"
262
+ )
263
+ if values:
264
+ return next(iter(values)), path, False
265
+ if configured:
266
+ raise InvalidImport(
267
+ f"Trace '{trace_id}' has no value at join path '{configured}'"
268
+ )
269
+ return trace_id, "trace_id", True
270
+
271
+
272
+ def _attributes(record: dict[str, Any]) -> dict[str, Any]:
273
+ """Return decoded span attributes."""
274
+ return _dict(record.get("attributes"))
275
+
276
+
277
+ def _attribute(record: dict[str, Any], *names: str) -> Any:
278
+ """Return the first non-empty span attribute."""
279
+ attributes = _attributes(record)
280
+ for name in names:
281
+ value = attributes.get(name)
282
+ if value not in (None, ""):
283
+ return _decode_json(value)
284
+ return None
285
+
286
+
287
+ def _node_type(record: dict[str, Any]) -> tuple[NodeType, str | None]:
288
+ """Map OpenTelemetry GenAI semantics to a Kitaru node type."""
289
+ operation = str(_attribute(record, "gen_ai.operation.name") or "").casefold()
290
+ span_name = str(record.get("span_name") or "")
291
+ tool_name = _attribute(
292
+ record,
293
+ "gen_ai.tool.name",
294
+ "tool.name",
295
+ "tool_name",
296
+ )
297
+ if operation in {"execute_tool", "tool", "tool_call"} or tool_name:
298
+ return NodeType.TOOL_CALL, str(tool_name or span_name or "tool")
299
+ if operation in {
300
+ "chat",
301
+ "completion",
302
+ "embeddings",
303
+ "generate_content",
304
+ "text_completion",
305
+ } or _attribute(
306
+ record,
307
+ "gen_ai.request.model",
308
+ "gen_ai.response.model",
309
+ "gen_ai.system",
310
+ ):
311
+ return NodeType.LLM_CALL, None
312
+ return NodeType.SPAN, None
313
+
314
+
315
+ def _node_status(record: dict[str, Any]) -> NodeStatus:
316
+ """Map Logfire status and level fields."""
317
+ status = str(
318
+ record.get("otel_status_code") or record.get("status_code") or ""
319
+ ).casefold()
320
+ level = record.get("level")
321
+ level_number = _integer(level)
322
+ if status == "error" or record.get("is_exception") is True:
323
+ return NodeStatus.FAILED
324
+ if isinstance(level, str) and level.casefold() in {"error", "fatal"}:
325
+ return NodeStatus.FAILED
326
+ if level_number is not None and level_number >= 17:
327
+ return NodeStatus.FAILED
328
+ return NodeStatus.COMPLETED
329
+
330
+
331
+ def _payload(record: dict[str, Any], *names: str) -> Any:
332
+ """Return the first decoded payload attribute."""
333
+ return _attribute(record, *names)
334
+
335
+
336
+ def _tokens(record: dict[str, Any]) -> TokenUsage | None:
337
+ """Map OpenTelemetry GenAI token attributes."""
338
+ values = (
339
+ _integer(
340
+ _attribute(
341
+ record,
342
+ "gen_ai.usage.input_tokens",
343
+ "gen_ai.usage.prompt_tokens",
344
+ )
345
+ ),
346
+ _integer(
347
+ _attribute(
348
+ record,
349
+ "gen_ai.usage.output_tokens",
350
+ "gen_ai.usage.completion_tokens",
351
+ )
352
+ ),
353
+ _integer(
354
+ _attribute(
355
+ record,
356
+ "gen_ai.usage.details.cache_read_tokens",
357
+ "gen_ai.usage.cached_input_tokens",
358
+ )
359
+ ),
360
+ _integer(_attribute(record, "gen_ai.usage.details.reasoning_tokens")),
361
+ )
362
+ if all(value is None for value in values):
363
+ return None
364
+ return TokenUsage(
365
+ input_tokens=values[0],
366
+ output_tokens=values[1],
367
+ cached_input_tokens=values[2],
368
+ reasoning_tokens=values[3],
369
+ )
370
+
371
+
372
+ def _source_metadata(record: dict[str, Any]) -> dict[str, Any]:
373
+ """Select bounded Logfire metadata for filtering and debugging."""
374
+ metadata = {
375
+ f"logfire.{column}": record[column]
376
+ for column in _METADATA_COLUMNS
377
+ if record.get(column) not in (None, "", [])
378
+ }
379
+ attributes = _attributes(record)
380
+ for key in _ATTRIBUTE_METADATA_KEYS:
381
+ if attributes.get(key) not in (None, ""):
382
+ metadata[f"logfire.attributes.{key}"] = attributes[key]
383
+ return metadata
384
+
385
+
386
+ def _detect_framework(records: list[dict[str, Any]], configured: Any) -> str | None:
387
+ """Detect one supported agent framework."""
388
+ evidence = [str(configured or "")]
389
+ for record in records:
390
+ evidence.extend(
391
+ str(value)
392
+ for value in (
393
+ record.get("otel_scope_name"),
394
+ record.get("span_name"),
395
+ _attribute(record, "gen_ai.agent.name"),
396
+ )
397
+ if value
398
+ )
399
+ joined = "\n".join(evidence)
400
+ matches = {
401
+ framework
402
+ for pattern, framework in _FRAMEWORK_PATTERNS
403
+ if pattern.search(joined)
404
+ }
405
+ return next(iter(matches)) if len(matches) == 1 else None
406
+
407
+
408
+ def _build_node_tree(
409
+ nodes_with_parents: list[tuple[ImportedNode, str | None]],
410
+ ) -> list[ImportedNode]:
411
+ """Build an acyclic node tree while preserving orphans as roots."""
412
+ ids = [node.external_id for node, _ in nodes_with_parents]
413
+ if len(ids) != len(set(ids)):
414
+ raise InvalidImport("The import contains duplicate span ids")
415
+ by_id = {node.external_id: node for node, _ in nodes_with_parents}
416
+ parents = {
417
+ node.external_id: parent
418
+ for node, parent in nodes_with_parents
419
+ if node.external_id is not None and parent in by_id
420
+ }
421
+ for node_id in parents:
422
+ seen: set[str] = set()
423
+ current: str | None = node_id
424
+ while current in parents:
425
+ if current in seen:
426
+ raise InvalidImport("The imported span graph contains a parent cycle")
427
+ seen.add(current)
428
+ current = parents[current]
429
+ roots: list[ImportedNode] = []
430
+ for node, parent in nodes_with_parents:
431
+ if parent in by_id:
432
+ by_id[parent].children.append(node)
433
+ else:
434
+ roots.append(node)
435
+ return roots
436
+
437
+
438
+ class LogfireRecordsImporter:
439
+ """Normalize exported rows from Logfire's records table."""
440
+
441
+ def parse(
442
+ self, content: bytes, params: dict[str, Any]
443
+ ) -> Iterator[ImportedSession | ImportFailure]:
444
+ """Parse Logfire records into sessions and isolated failures."""
445
+ records = _parse_records(content)
446
+ traces: dict[str, list[dict[str, Any]]] = defaultdict(list)
447
+ failures: list[ImportFailure] = []
448
+ for line_number, record in enumerate(records, start=1):
449
+ trace_id = record.get("trace_id")
450
+ span_id = record.get("span_id")
451
+ if trace_id in (None, "") or span_id in (None, ""):
452
+ failures.append(
453
+ ImportFailure(
454
+ line=line_number,
455
+ external_id=str(trace_id) if trace_id else None,
456
+ error="Logfire row lacks trace_id or span_id",
457
+ )
458
+ )
459
+ continue
460
+ traces[str(trace_id)].append(record)
461
+
462
+ grouped: dict[str, list[tuple[str, list[dict[str, Any]]]]] = defaultdict(list)
463
+ join_paths: dict[str, set[str]] = defaultdict(set)
464
+ fallback_sessions: set[str] = set()
465
+ for trace_id, rows in traces.items():
466
+ try:
467
+ session_id, join_path, fallback = _join_value(rows, params, trace_id)
468
+ except InvalidImport as exc:
469
+ failures.append(
470
+ ImportFailure(
471
+ line=len(failures) + 1,
472
+ external_id=trace_id,
473
+ error=str(exc),
474
+ )
475
+ )
476
+ continue
477
+ grouped[session_id].append((trace_id, rows))
478
+ join_paths[session_id].add(join_path)
479
+ if fallback:
480
+ fallback_sessions.add(session_id)
481
+
482
+ for session_id, session_traces in sorted(grouped.items()):
483
+ try:
484
+ yield self._parse_session(
485
+ session_id,
486
+ session_traces,
487
+ params,
488
+ join_paths=join_paths[session_id],
489
+ trace_fallback=session_id in fallback_sessions,
490
+ )
491
+ except InvalidImport as exc:
492
+ yield ImportFailure(
493
+ line=len(failures) + 1,
494
+ external_id=session_id,
495
+ error=str(exc),
496
+ )
497
+ yield from failures
498
+
499
+ def _parse_session(
500
+ self,
501
+ session_id: str,
502
+ traces: list[tuple[str, list[dict[str, Any]]]],
503
+ params: dict[str, Any],
504
+ *,
505
+ join_paths: set[str],
506
+ trace_fallback: bool,
507
+ ) -> ImportedSession:
508
+ """Normalize one grouped Logfire session."""
509
+ project_ids = {
510
+ str(row["project_id"])
511
+ for _, rows in traces
512
+ for row in rows
513
+ if row.get("project_id") not in (None, "")
514
+ }
515
+ if len(project_ids) > 1:
516
+ raise InvalidImport(
517
+ f"Session '{session_id}' contains conflicting Logfire project ids"
518
+ )
519
+ source_instance_value = (
520
+ params.get("source_instance")
521
+ or params.get("project_id")
522
+ or next(iter(project_ids), None)
523
+ )
524
+ source_instance = (
525
+ str(source_instance_value).strip() if source_instance_value else "logfire"
526
+ )
527
+ warnings: list[str] = []
528
+ if not source_instance_value:
529
+ warnings.append(
530
+ "No Logfire project identity supplied; using source_instance 'logfire'"
531
+ )
532
+ if trace_fallback:
533
+ warnings.append("No session attribute found; grouped by trace id")
534
+
535
+ turns: list[_Turn] = []
536
+ nodes_with_parents: list[tuple[ImportedNode, str | None]] = []
537
+ all_records: list[dict[str, Any]] = []
538
+ roots_by_trace: dict[str, dict[str, Any]] = {}
539
+ for trace_id, rows in traces:
540
+ ordered = sorted(
541
+ rows,
542
+ key=lambda row: (
543
+ _datetime(row.get("start_timestamp"))
544
+ or datetime.min.replace(tzinfo=UTC),
545
+ str(row.get("span_id")),
546
+ ),
547
+ )
548
+ ids = {str(row["span_id"]) for row in ordered}
549
+ roots = [
550
+ row
551
+ for row in ordered
552
+ if row.get("parent_span_id") in (None, "")
553
+ or str(row.get("parent_span_id")) not in ids
554
+ ]
555
+ if len(roots) != 1:
556
+ warnings.append(f"Trace '{trace_id}' has {len(roots)} root records")
557
+ root = roots[0] if roots else ordered[0]
558
+ roots_by_trace[trace_id] = root
559
+ trace_start = min(
560
+ (
561
+ timestamp
562
+ for row in ordered
563
+ if (timestamp := _datetime(row.get("start_timestamp")))
564
+ ),
565
+ default=None,
566
+ )
567
+ trace_end = max(
568
+ (
569
+ timestamp
570
+ for row in ordered
571
+ if (timestamp := _datetime(row.get("end_timestamp")))
572
+ ),
573
+ default=None,
574
+ )
575
+ turn_input = _payload(
576
+ root,
577
+ "input",
578
+ "inputs",
579
+ "raw_input",
580
+ "pydantic_ai.all_messages",
581
+ "gen_ai.input.messages",
582
+ "gen_ai.prompt",
583
+ )
584
+ turn_output = _payload(
585
+ root,
586
+ "output",
587
+ "outputs",
588
+ "final_result",
589
+ "gen_ai.output.messages",
590
+ "gen_ai.completion",
591
+ )
592
+ turns.append(
593
+ _Turn(trace_id, turn_input, turn_output, trace_start, trace_end)
594
+ )
595
+ for row in ordered:
596
+ span_id = str(row["span_id"])
597
+ parent_id = row.get("parent_span_id")
598
+ parent_external_id = (
599
+ f"{trace_id}:{parent_id}"
600
+ if parent_id not in (None, "") and str(parent_id) in ids
601
+ else None
602
+ )
603
+ if parent_id not in (None, "") and parent_external_id is None:
604
+ warnings.append(
605
+ f"Span '{span_id}' references missing parent '{parent_id}'"
606
+ )
607
+ node_type, tool_name = _node_type(row)
608
+ status = _node_status(row)
609
+ error = None
610
+ if status is NodeStatus.FAILED:
611
+ error_value = (
612
+ row.get("exception_message")
613
+ or row.get("otel_status_message")
614
+ or row.get("message")
615
+ )
616
+ error = str(error_value) if error_value else "Logfire span failed"
617
+ inputs = _payload(
618
+ row,
619
+ "input",
620
+ "inputs",
621
+ "raw_input",
622
+ "pydantic_ai.all_messages",
623
+ "gen_ai.input.messages",
624
+ "gen_ai.prompt",
625
+ "tool.arguments",
626
+ "gen_ai.tool.call.arguments",
627
+ )
628
+ outputs = _payload(
629
+ row,
630
+ "output",
631
+ "outputs",
632
+ "final_result",
633
+ "gen_ai.output.messages",
634
+ "gen_ai.completion",
635
+ "tool.result",
636
+ "gen_ai.tool.call.result",
637
+ )
638
+ nodes_with_parents.append(
639
+ (
640
+ ImportedNode(
641
+ external_id=f"{trace_id}:{span_id}",
642
+ trace_id=trace_id,
643
+ node_type=node_type,
644
+ name=str(
645
+ row.get("span_name")
646
+ or row.get("message")
647
+ or row.get("kind")
648
+ or "span"
649
+ ),
650
+ status=status,
651
+ error=error,
652
+ started_at=_datetime(row.get("start_timestamp")),
653
+ ended_at=_datetime(row.get("end_timestamp")),
654
+ inputs=inputs,
655
+ outputs=outputs,
656
+ requested_model=(
657
+ str(value)
658
+ if (value := _attribute(row, "gen_ai.request.model"))
659
+ else None
660
+ ),
661
+ model=(
662
+ str(value)
663
+ if (
664
+ value := _attribute(
665
+ row,
666
+ "gen_ai.response.model",
667
+ "gen_ai.request.model",
668
+ )
669
+ )
670
+ else None
671
+ ),
672
+ model_provider=(
673
+ str(value)
674
+ if (
675
+ value := _attribute(
676
+ row,
677
+ "gen_ai.provider.name",
678
+ "gen_ai.system",
679
+ )
680
+ )
681
+ else None
682
+ ),
683
+ tokens=_tokens(row),
684
+ cost=_decimal(
685
+ _attribute(
686
+ row,
687
+ "gen_ai.usage.cost",
688
+ "gen_ai.cost.total",
689
+ "operation.cost",
690
+ )
691
+ ),
692
+ model_params=_dict(
693
+ _attribute(
694
+ row,
695
+ "gen_ai.request.parameters",
696
+ "model_parameters",
697
+ "model_request_parameters",
698
+ "model_settings",
699
+ )
700
+ )
701
+ or None,
702
+ tool_name=tool_name,
703
+ attributes={
704
+ "logfire.kind": row.get("kind"),
705
+ "logfire.level": row.get("level"),
706
+ "logfire.message": row.get("message"),
707
+ "logfire.attributes": _attributes(row),
708
+ },
709
+ metadata=_source_metadata(row),
710
+ children=[],
711
+ ),
712
+ parent_external_id,
713
+ )
714
+ )
715
+ all_records.extend(ordered)
716
+
717
+ turns.sort(
718
+ key=lambda turn: (
719
+ turn.started_at or datetime.min.replace(tzinfo=UTC),
720
+ turn.trace_id,
721
+ )
722
+ )
723
+ nodes_with_parents.sort(
724
+ key=lambda item: (
725
+ item[0].started_at or datetime.min.replace(tzinfo=UTC),
726
+ item[0].external_id or "",
727
+ )
728
+ )
729
+ node_tree = _build_node_tree(nodes_with_parents)
730
+ latest_turn = turns[-1]
731
+ latest_root = roots_by_trace[latest_turn.trace_id]
732
+ session_status = (
733
+ SessionStatus.FAILED
734
+ if _node_status(latest_root) is NodeStatus.FAILED
735
+ else SessionStatus.COMPLETED
736
+ )
737
+ metadata: dict[str, Any] = {
738
+ "logfire.session_id": session_id,
739
+ "logfire.project_id": next(iter(project_ids), None),
740
+ "logfire.trace_ids": [turn.trace_id for turn in turns],
741
+ "logfire.join_paths": sorted(join_paths),
742
+ "logfire.services": sorted(
743
+ {
744
+ str(row["service_name"])
745
+ for row in all_records
746
+ if row.get("service_name") not in (None, "")
747
+ }
748
+ ),
749
+ "logfire.environments": sorted(
750
+ {
751
+ str(row["deployment_environment"])
752
+ for row in all_records
753
+ if row.get("deployment_environment") not in (None, "")
754
+ }
755
+ ),
756
+ "source_trace_count": len(turns),
757
+ "source_completeness": "query-dependent",
758
+ "normalization_warnings": warnings,
759
+ }
760
+ latest_error = (
761
+ latest_root.get("exception_message")
762
+ or latest_root.get("otel_status_message")
763
+ if session_status is SessionStatus.FAILED
764
+ else None
765
+ )
766
+ return ImportedSession(
767
+ external_id=f"{source_instance}:{session_id}",
768
+ name=str(
769
+ latest_root.get("span_name") or latest_root.get("message") or session_id
770
+ ),
771
+ status=session_status,
772
+ inputs={
773
+ "schema_version": 1,
774
+ "turns": [
775
+ {
776
+ "source_trace_id": turn.trace_id,
777
+ "inputs": turn.inputs,
778
+ "outputs": turn.outputs,
779
+ }
780
+ for turn in turns
781
+ ],
782
+ },
783
+ outputs=latest_turn.outputs,
784
+ error=str(latest_error) if latest_error else None,
785
+ started_at=min(
786
+ (turn.started_at for turn in turns if turn.started_at), default=None
787
+ ),
788
+ ended_at=max(
789
+ (turn.ended_at for turn in turns if turn.ended_at), default=None
790
+ ),
791
+ metadata=metadata,
792
+ framework=_detect_framework(all_records, params.get("framework")),
793
+ nodes=node_tree,
794
+ )
795
+
796
+
797
+ def parse(
798
+ content: bytes, params: dict[str, Any]
799
+ ) -> Iterator[ImportedSession | ImportFailure]:
800
+ """Parse a Logfire records-query export through the importer contract."""
801
+ yield from LogfireRecordsImporter().parse(content, params)