Repository navigation
fix(platform): stop re-storing an email attachment on every mail poll - #3000
Merged
Merged
Conversation
A mail poll re-fetches the message sitting on the sync cursor, every time. `cursorFromMessage` derives the cursor from the newest message's own timestamp (`deliveredAt ?? sentAt`, both stamped from the same `email.date`), and the connector filters with `sentAt >= cursor` — so that message satisfies its own filter indefinitely, until newer mail displaces it. Nothing about storing an attachment is idempotent. Blob keys are `prefix/orgSlug/randomUUID()`, so identical bytes always get a fresh object, and `saveFileMetadata` dedupes on `storageId`, so a fresh key always means a fresh row. One attachment on the message at the cursor therefore minted one blob and one `fileMetadata` row per poll, forever — measured in one deployment as a new copy every five minutes for over a day, of a single file. The bytes are immutable, so a message whose attachments are already stored needs nothing stored: `reuseStoredAttachments` looks the message up by its normalized Message-ID and hands back the pointers it already has, leaving the materializer with nothing to do. Runs before materialization in `fetchBodies`, and is provider-agnostic — Gmail and Outlook re-list their boundary message too (`after:` and `ge` are both inclusive), they simply never carried inline bytes for it to duplicate. Matching is by filename, the only identifier that survives the round trip: the wire `id` is a per-fetch part handle and `storageId` is what we are avoiding re-minting. Every uncertain case falls through to storing — a part with no stored `storageId` (a metadata-only chip, or a materialization that failed), a fetch whose parts do not all match, or a lookup that throws. A missed reuse costs a duplicate blob; a wrong reuse would cost a broken download link, so the bias is deliberate. Cursor semantics are untouched, so no mail can be skipped. The redundant body fetch remains: identity only exists after parsing, and excluding at list time needs the UID threaded through the cursor, which is a separate change.
This was referenced Aug 19, 2026
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Fixes the duplication reported in #2996 and #2985. Not by the fix #2996 proposed — see Why not the cursor below.
The defect
Every mail poll re-fetches the message sitting on the sync cursor.
cursorFromMessage(sync_mailbox.ts:154-167) derives the cursor from the newest message's own timestamp, and the connector filters inclusively:Same field, same source,
>=. That message satisfies its own filter until newer mail displaces it.And nothing about storing an attachment is idempotent: blob keys are
prefix/orgSlug/randomUUID()(lib/storage/object_store.ts:207), so identical bytes always get a fresh object, andsaveFileMetadatadedupes onstorageId, so a fresh key always means a fresh row.So one attachment on the message at the cursor minted one blob and one
fileMetadatarow per poll, indefinitely. Observed on a deployment: a new copy every five minutes for over a day, of a single file. Since #2995 those rows carryragStatusunset, so they no longer consume the RAG indexing cap — but the duplication itself continued.The fix
The bytes are immutable, so a message whose attachments are already stored needs nothing stored.
reuseStoredAttachmentslooks the message up by its normalized Message-ID and hands back the pointers it already holds, so the materializer downstream has nothing to do. It runs before materialization infetchBodies.Provider-agnostic by construction: Gmail and Outlook re-list their boundary message too (
after:andgeare both inclusive) — they simply never carried inline bytes for it to duplicate, since connectorctx.filesis unwired.Matching is on filename, the only identifier that survives the round trip. The wire
idis a per-fetch part handle (an IMAP part number), andstorageIdis precisely what we are avoiding re-minting.Every uncertain case falls through to storing normally:
storageId— a metadata-only chip from before attachment storage shipped, or a materialization that failed. This pass is its chance to be fixed, so it must not read as "already stored".Cursor semantics are untouched, so no mail can be skipped.
Why not the cursor
#2996 proposed excluding the boundary message by the id the cursor already carries. That does not work: the cursor's
messageIdisexternalMessageId, the RFCMessage-IDheader, while a listing summary isMailMessageSummary { uid, from, subject, sentAt }— no message id at all, and for IMAP the id used to fetch is the UID. The RFC Message-ID only exists after the body is parsed, so excluding at list time by it would require the very fetch it was meant to avoid.What this leaves unfixed: the redundant body fetch still happens each poll. That is a wasted round-trip rather than duplicated data, and closing it means threading the UID through the cursor — worth doing separately, at lower priority. #2996 should be retitled to that narrower scope rather than closed by this PR.
Tests
reuse_stored_attachments.test.ts— reuse on an already-ingested message; store on a new one; store when the stored part has nostorageId; store when parts don't all match; store when the lookup throws; no lookup at all for an attachment-free email.sync_mailbox.test.ts— through the real sync path: re-fetching an ingested message produces['list_messages', 'get:1']with nostore:hop, while the metadata-only case still stores.Every assertion mutation-tested. Removing the reuse step, reusing without a stored
storageId, and reusing partially each turn the relevant tests red. The throw case needed a second look — the catch path and the not-found path both pass the email through, so it initially proved nothing; the mutation that kills it is making the catch rethrow, which is the behaviour that matters (a failed lookup must not abort the whole sync pass).The harness keys existing messages by the normalized id, without angle brackets — the first draft keyed it by the wire form and passed for the wrong reason, since a lookup miss and a successful reuse both leave the email untouched at that level.