Skip to content

fix(platform): stop re-storing an email attachment on every mail poll - #3000

Merged
Israeltheminer merged 1 commit into
mainfrom
fix/mail-attachment-reingest
Aug 18, 2026
Merged

Israeltheminer merged 1 commit into
mainfrom
fix/mail-attachment-reingest

Conversation

@Israeltheminer

Copy link
Copy Markdown
Contributor

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:

// build_initial_message.ts:15,25,26 — both stamped from the same instant
const emailTimestamp = new Date(email.date).getTime();
sentAt: emailTimestamp,
deliveredAt: status === 'delivered' ? emailTimestamp : undefined,

// cursorFromMessage
const since = message.deliveredAt ?? message.sentAt ?? message._creationTime ?? null;

// imap-smtp.ts:1196
.filter((message) => cursor === undefined || message.sentAt >= cursor)

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, and saveFileMetadata dedupes on storageId, so a fresh key always means a fresh row.

So one attachment on the message at the cursor minted one blob and one fileMetadata row 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 carry ragStatus unset, 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. reuseStoredAttachments looks 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 in fetchBodies.

Provider-agnostic by construction: 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, since connector ctx.files is unwired.

Matching is on filename, the only identifier that survives the round trip. The wire id is a per-fetch part handle (an IMAP part number), and storageId is precisely what we are avoiding re-minting.

Every uncertain case falls through to storing normally:

  • a stored part with no 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".
  • a fetch whose parts do not all match what is stored — partial reuse would silently drop a genuinely new file.
  • a lookup that throws — a duplicate blob is recoverable, a dropped attachment is not.

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 messageId is externalMessageId, the RFC Message-ID header, while a listing summary is MailMessageSummary { 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 no storageId; 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 no store: 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.

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.
@Israeltheminer
Israeltheminer merged commit fd8b81f into main Aug 18, 2026
50 checks passed
@Israeltheminer
Israeltheminer deleted the fix/mail-attachment-reingest branch August 18, 2026 12:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: mail sync re-fetches the boundary message on every poll, forever

1 participant