-
Notifications
You must be signed in to change notification settings - Fork 244
feat: Artifacts — attach binary blobs to spans #1931
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
adriangb
wants to merge
1
commit into
main
Choose a base branch
from
feat/artifacts
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| # Artifacts | ||
|
|
||
| Artifacts let you attach a **binary blob** — an image, audio clip, PDF, or a large JSON | ||
| payload — to a span. The blob is stored separately from your telemetry, so it is not | ||
| subject to span attribute size limits and does not bloat your traces. The span itself | ||
| carries only a small reference; Logfire uploads the blob out of band. | ||
|
|
||
| ## Logging an artifact | ||
|
|
||
| Wrap your data in `logfire.Artifact` and pass it as a span or log attribute: | ||
|
|
||
| ```python skip="true" | ||
| import logfire | ||
|
|
||
| logfire.configure() | ||
|
|
||
| with open('chart.png', 'rb') as f: | ||
| image_bytes = f.read() | ||
|
|
||
| logfire.info('chart generated', chart=logfire.Artifact(image_bytes, content_type='image/png')) | ||
| ``` | ||
|
|
||
| The `chart` argument renders as an image preview on the trace in the Logfire UI, with a | ||
| download link — not as a wall of base64. | ||
|
|
||
| ### From a file or a file handle | ||
|
|
||
| `Artifact.from_file` reads a path lazily (no need to load the bytes yourself), and | ||
| `Artifact.from_file_handle` accepts any open binary handle, including temporary files: | ||
|
|
||
| ```python skip="true" | ||
| import logfire | ||
|
|
||
| logfire.configure() | ||
|
|
||
| # From a path — the content type is guessed from the extension. | ||
| logfire.info('report ready', report=logfire.Artifact.from_file('report.pdf')) | ||
|
|
||
| # From an open binary handle. | ||
| with open('clip.mp3', 'rb') as handle: | ||
| logfire.info('audio processed', clip=logfire.Artifact.from_file_handle(handle)) | ||
| ``` | ||
|
|
||
| ## When the upload happens | ||
|
|
||
| Each artifact chooses when its bytes are uploaded, via the `upload` argument: | ||
|
|
||
| - **`background`** (the default) — the upload is handed to a background thread and the | ||
| logging call never blocks. If uploads cannot keep up, queued artifacts are dropped | ||
| with a warning rather than stalling your program. | ||
| - **`sync`** — the upload runs inline; the logging call returns only once the blob is | ||
| stored. Use this when you need delivery guaranteed, or when you want to free the | ||
| source bytes/file immediately afterwards. | ||
|
|
||
| ```python skip="true" | ||
| import logfire | ||
|
|
||
| logfire.configure() | ||
|
|
||
| # Block until this artifact is uploaded. | ||
| logfire.info('critical input', data=logfire.Artifact(payload, upload='sync')) | ||
| ``` | ||
|
|
||
| ## How it works | ||
|
|
||
| Artifacts are **content-addressed**: an artifact's identity is the sha256 of its bytes. | ||
| The same blob logged repeatedly — within a project — is uploaded and stored only once. | ||
| The reference embedded in the span looks like: | ||
|
|
||
| ```json | ||
| { | ||
| "type": "logfire.artifact", | ||
| "sha256": "9f86d0818...", | ||
| "filename": "chart.png", | ||
| "content_type": "image/png", | ||
| "size_bytes": 28421 | ||
| } | ||
| ``` | ||
|
|
||
| The blob never travels through the telemetry pipeline. On SaaS the SDK uploads it | ||
| directly to object storage via a signed URL; self-hosted deployments route it through | ||
| the Logfire backend. | ||
|
|
||
| ## Viewing artifacts | ||
|
|
||
| Open a span in the Logfire UI: any artifact-valued argument renders inline — images, | ||
| audio, video, and PDFs as previews, everything else as a download link — alongside its | ||
| filename, content type, and size. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| import os | ||
| from abc import ABC, abstractmethod | ||
| from typing import IO, Any | ||
|
|
||
| from _typeshed import Incomplete | ||
|
|
||
| __all__ = ['Artifact', 'UploadMode'] | ||
|
|
||
| UploadMode: Incomplete | ||
|
|
||
| class ArtifactSource(ABC): | ||
| """A source of artifact bytes — normalises bytes, files, and handles to one surface. | ||
|
|
||
| Deliberately small so that streaming sources can be added later as a new subclass | ||
| without touching `Artifact`, the upload handshake, or the backend. | ||
| """ | ||
| @abstractmethod | ||
| def digest(self) -> tuple[str, int]: | ||
| """Return `(sha256_hex, size_bytes)` for the content.""" | ||
| @abstractmethod | ||
| def read(self) -> bytes: | ||
| """Return the full content as bytes, for upload.""" | ||
|
|
||
| class _BytesSource(ArtifactSource): | ||
| """An in-memory blob.""" | ||
| def __init__(self, data: bytes) -> None: ... | ||
| def digest(self) -> tuple[str, int]: ... | ||
| def read(self) -> bytes: ... | ||
|
|
||
| class _PathSource(ArtifactSource): | ||
| """A file on disk. | ||
|
|
||
| Hashed and uploaded by reading the path, so a `background` upload of a file path | ||
| holds no bytes in memory. | ||
| """ | ||
| def __init__(self, path: str | os.PathLike[str]) -> None: ... | ||
| def digest(self) -> tuple[str, int]: ... | ||
| def read(self) -> bytes: ... | ||
|
|
||
| class Artifact: | ||
| """A binary blob to attach to a span — an image, audio clip, PDF, large JSON, etc. | ||
|
|
||
| Pass an `Artifact` as a span or log attribute value. Logfire uploads the blob to | ||
| object storage out of band and embeds a small reference in the span. | ||
|
|
||
| Examples: | ||
| ```python | ||
| import logfire | ||
|
|
||
| logfire.configure() | ||
|
|
||
| # From a file path. | ||
| logfire.info('chart generated', chart=logfire.Artifact.from_file('chart.png')) | ||
|
|
||
| # From in-memory bytes. | ||
| logfire.info('thumbnail', image=logfire.Artifact(png_bytes, content_type='image/png')) | ||
|
|
||
| # From an open binary handle (including temporary / spooled files). | ||
| with open('report.pdf', 'rb') as handle: | ||
| logfire.info('report', report=logfire.Artifact.from_file_handle(handle)) | ||
| ``` | ||
| """ | ||
| def __init__(self, data: bytes, *, filename: str | None = None, content_type: str | None = None, upload: UploadMode = 'background') -> None: | ||
| """Create an artifact from in-memory bytes. | ||
|
|
||
| Args: | ||
| data: The blob bytes. | ||
| filename: Optional original filename, shown in the UI and used to guess the | ||
| content type. | ||
| content_type: MIME type of the blob. Guessed from `filename` when omitted, | ||
| falling back to `application/octet-stream`. | ||
| upload: When to upload the blob — see [`UploadMode`][logfire.UploadMode]. | ||
| Defaults to `background`. | ||
| """ | ||
| @classmethod | ||
| def from_file(cls, path: str | os.PathLike[str], *, filename: str | None = None, content_type: str | None = None, upload: UploadMode = 'background') -> Artifact: | ||
| """Create an artifact from a file path. | ||
|
|
||
| The file is read once to hash it and again to upload it, so a `background` | ||
| upload of a file path holds no bytes in memory. | ||
|
|
||
| Args: | ||
| path: Path to the file. | ||
| filename: Original filename to record. Defaults to the basename of `path`. | ||
| content_type: MIME type. Guessed from the path/filename when omitted. | ||
| upload: When to upload the blob — see [`UploadMode`][logfire.UploadMode]. | ||
| """ | ||
| @classmethod | ||
| def from_file_handle(cls, handle: IO[bytes], *, filename: str | None = None, content_type: str | None = None, upload: UploadMode = 'background') -> Artifact: | ||
| """Create an artifact from an open binary file handle. | ||
|
|
||
| Works with any binary handle, including `tempfile.SpooledTemporaryFile` and | ||
| `tempfile.NamedTemporaryFile`. The handle is read in full immediately, so the | ||
| caller may close it as soon as this returns. | ||
|
|
||
| Args: | ||
| handle: An open binary (`'rb'`) file-like object. | ||
| filename: Original filename to record. Defaults to the handle's `name`. | ||
| content_type: MIME type. Guessed from the filename when omitted. | ||
| upload: When to upload the blob — see [`UploadMode`][logfire.UploadMode]. | ||
| """ | ||
| @property | ||
| def sha256(self) -> str: | ||
| """The hex sha256 of the blob — its content-addressed identity.""" | ||
| @property | ||
| def size_bytes(self) -> int: | ||
| """The size of the blob in bytes.""" | ||
| def read(self) -> bytes: | ||
| """Read the full blob into memory (used by the uploader).""" | ||
| def reference(self) -> dict[str, Any]: | ||
| """The reference object embedded into the span attribute in place of the blob.""" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Delivery is far from guaranteed with sync, it still just silently swallows request exceptions without retrying.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you think we should make the guarantee stronger (error) or make the docstrings match current impl?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i think we eventually want a stronger guarantee, but it doesn't have to be in the first pass. until then, the docs should be accurate.