Skip to content

perf(attachments): Stream file attachments when the envelope is written - #6777

Draft
sentry-junior[bot] wants to merge 4 commits into
mainfrom
perf/stream-file-attachments
Draft

sentry-junior[bot] wants to merge 4 commits into
mainfrom
perf/stream-file-attachments

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Follow-up to #6743. That PR is the narrow fix for Perfetto chunks. This one starts the broader change: file-backed envelope item payloads should be read only when the envelope is written, and streamed rather than built as a byte[] first.

What actually happens today

File-backed items are already read lazily. Every file factory (fromAttachment with a pathname, fromProfilingTrace, fromProfileChunk, fromPerfettoProfileChunk, fromReplay) wraps its read in a CachedItem. Nothing is read when the item is built. The first getData() happens in JsonSerializer.serialize(envelope, out). That is normally envelopeCache.storeEnvelope in AsyncHttpTransport.EnvelopeSender.flush(), on the transport thread.

The real costs are these:

  • The full payload stays in memory. After the first read, the byte[] lives in SentryEnvelopeItem.data / CachedItem.bytes for the whole life of the envelope: the cache write, then the HTTP send, until the envelope is collected.
  • Peak memory is a multiple of the file size. readBytesFromFile grows a ByteArrayOutputStream and then copies it with toByteArray(). Profiles add a base64 String and the serialized JSON on top. Replay adds msgpack copies.
  • Asking for the length reads the file. The item header's length is cachedItem.getBytes().length, so header.getLength() loads the whole file.

This PR: stream pathname attachments

The first slice covers an Attachment that has only a pathname. That is the simplest file item: raw bytes, no transformation.

  • fromAttachment returns a file-backed item that holds no bytes. Its header length is the file size, checked against maxAttachmentSize. Getting the length no longer reads the file.
  • JsonSerializer asks the item for a Payload through the new package-private openPayload(). For a file, openPayload() checks the file and fixes its length before anything is written, so a missing, unreadable, or too large file still drops only that item, with the same log as today. The header is then written with that length, and the file is copied to the output stream in 8 KB chunks.
  • If the file grows after it was opened, the copy stops at the fixed length.
  • If the file shrinks, or a read fails, while it is being copied, the remaining bytes are filled with zeros and an error is logged. The header has already promised length bytes, and writing fewer would make every later item in the envelope unreadable, so this keeps the event.
  • getData() keeps working for callers such as beforeEnvelope callbacks. For file items it reads the file on each call and no longer caches the result.
  • The checks now live in one place, FileUtils.ensureReadableFile, which readBytesFromFile also uses.
  • openPayload, Payload, and the new header serialize overload are package-private. The only .api change is FileUtils.ensureReadableFile, and FileUtils is already @ApiStatus.Internal.

Side effects of reading at send time

  • The file is read once per serialization, not once per envelope. With the disk cache on, that is the cache write, then the HTTP send. Spotlight adds another read. If the file changes or is deleted in between, the cached copy and the sent copy can differ, or the send can drop the attachment that the cache still has. The cached copy is discarded after a successful send.
  • Open-time errors still drop only the item. A missing, unreadable, or too large file is caught in the serializer and logged, as before, and the envelope is still sent. No client report is recorded for a dropped attachment, today or with this change. A read error in the middle of the copy is new; it's handled by the zero padding described above.
  • Reads can still run on the caller's thread. When the transport queue is full, the RejectedExecutionHandler stores the envelope on the thread that captured it, and that store now streams the file on that thread.
  • Size checks run at serialization, against the file size at that moment, as they did before.
  • Envelopes read back from disk (EnvelopeReader, outbox, offline cache) are still byte-backed and unaffected.

Follow-up slices

  1. Perfetto profile chunks (builds on perf(profiling): Read Perfetto trace straight into the envelope payload #6743): stream [metadata][trace]. This needs the trace file deleted after the envelope is done, not after the first read, because each serialization now reads the file.
  2. Legacy profiles and continuous profile chunks: base64-encode the trace into the JSON while streaming, instead of building a String. This needs a streaming JSON value for the sampled profile.
  3. Replay video: write the msgpack map with the video streamed from its file. The same deletion question applies.
  4. Cache-first send: when the disk cache is on, send the envelope by streaming its cache file. The source file is then read exactly once and can be deleted right after the cache write. This is the bigger CachedItem change Roman suggested.
  5. EnvelopeReader: read cached and outbox envelopes as a stream instead of loading the whole file and copying each item with copyOfRange.

Open questions

  • Zero padding when a file shrinks mid-stream. The alternative is to abort the whole envelope. That loses the event, and it can leave a corrupt cache file that is only cleaned up when it fails to parse later. Padding keeps the event but sends a corrupted attachment, with only a log line. Is padding acceptable, or would you rather abort?
  • Spotlight serializes the same envelope at the same time as the transport. SpotlightIntegration serializes the envelope on its own executor while AsyncHttpTransport serializes it on its thread. CachedItem isn't thread-safe, and the profile and replay factories delete their file after the first read. Two concurrent first reads can race: one may delete the file while the other is reading it. Streamed attachments avoid this because each serialization opens its own stream. The other slices need a decision here: lock the CachedItem resolution, or make SDK-owned files outlive the envelope and delete them when the envelope is done.
  • Who owns deleting SDK-owned files (profiles, replay) once reads happen per serialization: the item, the transport after a send or discard, or the cache?
  • Should a file item that fails at send time be recorded in a client report? Today it is only logged.

via markus.hintersteiner.

--

View Session [Sentry]

An attachment with only a pathname used to be read into a byte[] on the
first envelope serialization and kept for the envelope's lifetime, and
its header length read the whole file. Now the item holds only the file,
its header length is the file size, and JsonSerializer copies the file
straight into the output stream each time the envelope is written.
@github-actions github-actions Bot added the risk: medium PR risk score: medium label Nov 25, 2026
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

PR risk: medium

For commit 19c02b1.

Main concerns: reach, public contract, data sent to Sentry.

Rules that block low also fired:

  • R4: a public API record changed: sentry/api/sentry.api

This label is a hint for reviewers, not an approval.

@sentry

sentry Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

📲 Install Builds

Android

🔗 App Name App ID Version Configuration
SDK Size io.sentry.tests.size 8.66.0 (1) release

⚙️ sentry-android Build Distribution Settings

@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Nov 25, 2026
Replace zero padding with an abort: if a file attachment shrinks, grows,
or can't be read while it's streamed, serialization throws
SentryEnvelopeAbortedException. The cache deletes the partial file, the
HTTP connection disconnects before the buffered body is sent, and the
transport drops the envelope without retrying.

Record dropped items and aborted envelopes in client reports with the
new `invalid` discard reason, once per item across serializations.

Serialize the envelope for Spotlight on the calling thread, so it
finishes before the transport serializes the same envelope. Only the
HTTP post runs on Spotlight's executor.

Co-Authored-By: Markus Hintersteiner <markus.hintersteiner@sentry.io>
@github-actions github-actions Bot removed the risk: medium PR risk score: medium label Nov 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🚨 Detected changes in high risk code 🚨

High-risk code has higher potential to break the SDK and may be hard to test. To prevent severe bugs, apply the rollout process for releasing such changes and be extra careful when changing and reviewing these files:

  • sentry/src/main/java/io/sentry/transport/AsyncHttpTransport.java
  • sentry/src/main/java/io/sentry/transport/HttpConnection.java

@github-actions github-actions Bot added the risk: medium PR risk score: medium label Nov 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: medium PR risk score: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant