Skip to content

fix: make interrupted GridFS uploads and deletes recoverable - #516

Open
dragoangel wants to merge 4 commits into
zone-eu:masterfrom
dragoangel:gridfs-orphans
Open

dragoangel wants to merge 4 commits into
zone-eu:masterfrom
dragoangel:gridfs-orphans

Conversation

@dragoangel

@dragoangel dragoangel commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Implements #515.

What the problem is

GridFS chunks outlive the files document that names them. files_id is their only
link and it is recorded nowhere else, so once the files document is gone the chunks
are unreachable by any query the code can express. Three paths produce that state: an
upload that never finishes, a delete interrupted between its two non-atomic halves,
and the time-based GC pass itself on the rare message whose upload straddles the water
mark.

That pass does eventually remove them, by age: it deletes files and chunks whose own
_id is below a water mark taken from the oldest queue row, and an orphan's _id
sinks below that mark like anything else. What it cannot do is reason about
reachability, so it cannot tell an orphan from a message that is merely old, and it
can only act once the mark has moved past it. The mark is held back by the oldest
queued delivery, which is itself bounded by maxQueueTime, so collection is late
rather than absent: up to 30 days on the default setting, and indefinitely where
expiry is disabled.

What this changes

Every in-flight upload and delete writes a marker document keyed by files_id into
<gfs>.pending, and removes it once the operation is whole, so no interruption is
invisible. The GC reads those markers and finishes what was started, within minutes
rather than within maxQueueTime, and it acts only on an operation that is known not
to have completed.

The state on the marker is what makes that safe. A file with no chunks means
opposite things depending on which operation was in flight, and a collector that
deleted on sight would destroy a message that had been queued successfully. So the
collector has four outcomes and only three of them delete anything:

  • deleting with a files document still present: the delete stopped partway, finish
    it in the order it would have run in
  • writing with no files document: an upload that never produced one, so its chunks
    are unreachable and go
  • writing with a files document but no delivery naming it: the upload finished but
    the message never reached the queue, so nothing will ever deliver or delete it
  • anything else: a marker whose own removal was lost, and dropping it is the whole of
    the repair

The delete itself is reordered to remove chunks before the files document, so every
interruption leaves either a marker or a complete file and the collector can tell
which.

Both queues store

RemoteQueue is the queue a forked SMTP child stores through, which is the path every
submission arriving over the wire takes; MailQueue is the one behind the HTTP API.
Both write the marker, and both hold it until the message is queued rather than
until the upload finishes: a stored message with no delivery behind it is nobody's,
and only the caller knows when it stops being that. store() hands the upload id back
so the caller can say so, mail-drop clears it after the push, and PUT /store/:id
clears its own, because nothing on that path ever queues anything. That endpoint
answers 500 if the clear fails - unlike the same failure after a push, there is no
delivery to keep the body alive, so 200 would promise durability that will not hold.

How long a marker lives

A marker records when it stops being anybody's rather than when it was written, and
the process holding the operation pushes that moment forward once a minute for as long
as it is still holding it. The collector compares that against the clock and has
nothing to derive - which matters because the process that sweeps is generally not the
process that wrote, and in a split deployment the two do not share a configuration.

The heartbeat is a timer in the very process doing the writing, so it cannot outlive
it. A child killed, out of memory, or thrown out of its event loop takes its timers
with it and the marker goes stale on its own, with no cleanup path having to run
first. A timeout describes what should happen; a missed beat is what did.

It also covers the parts of an operation that write no chunks at all, which a deadline
tied to write progress would not: headers are parsed before the body reaches the
upload stream and are stored separately as file metadata, and after the stream
finishes the message still has to be scanned, have its metadata written and be pushed
to the queue.

The beat only extends, never creates. An operation can be ended by a different process
than the one beating for it, because a forked child hands its cleanup to the master
over IPC, and an upserting beat would raise the marker from the dead there and then
beat for it forever. Finding nothing to extend is also how a beat learns to stop.

The teardown half

An SMTP client that disappears mid-DATA is the producer that needs no crash at all.
smtp-server handles the socket error at session level and, in _onClose, calls
this._dataStream.unpipe() and drops the stream without ending, erroring or
destroying it, so nothing downstream is told anything: the upload stays open,
removeMessage is never called because no delete ever happens, and maildrop.add's
callback never fires.

Erroring the size limiter from onClose is the whole fix, because the error then
takes the same route a size limit or a plugin rejection takes and the existing
handlers unwind the pipeline down to store(), which removes the chunks it had
written. A message that reached the terminating dot is left alone: DATA ends before
the connection closes, so it is complete even if the client never waited for the
response.

The error is named ClientDisconnect rather than only coded, because mail-drop
treats anything whose name ends in Error as a storage failure worth logging and
reporting as NOQUEUE. A client that hung up is neither, and on a busy receiver it is
routine - it is logged at info as an outcome, so the error channel stays useful for
real storage faults.

onClose also records session.connectionClosed, because a connection can be lost
while the smtp:data hooks are still running, before there is an in-flight message
for the teardown to find. Piping a dead stream into a pipeline that is only being
built would suspend it for the life of the process with no way back, so that case
destroys the stream instead.

Existing orphans, and why there is no migration step

The time-based pass stays exactly where it was, as the coarse backstop. It is what
collects anything orphaned before the markers existed, and the chunks it strands
itself on a straddling upload, neither of which any marker describes. So this needs no
operator action on upgrade: the old backlog ages out the way it always has, and
everything new is collected in minutes.

Cost

The two passes do not compete. collectPendingGridfs reads a collection that is empty
whenever nothing is in flight. The heartbeat is one small update a minute per
operation actually in flight. The time-based deletes are _id range scans on an
always-indexed field, and the water mark sits below the oldest queued message, so
nothing a live message owns is ever in range.

Tests

test/mail-queue-gridfs-test.js is new: nineteen cases covering the collector's four
outcomes, the marker lifecycle, the heartbeat, the delete order, and a delete taking
over a stale upload marker. test/remote-queue-gridfs-test.js adds six for the store
path every SMTP submission takes, including which stream failures count as storage
failures and which are outcomes. test/api-store-marker-test.js adds three for the
store-only endpoint, and test/smtp-interface-test.js gains four for the teardown.
All of them fail on the code before this change.

Compatibility

No new configuration. The marker collection is <gfs>.pending, indexed on expires
through indexes.yaml, and nothing outside the process that opened an operation needs
a number to know. An index named mailpending, on created, existed in an earlier
revision of this branch and can be dropped by anyone who deployed from it once every
process is upgraded; a fresh deployment never sees it.

Fixes #515.

@dragoangel
dragoangel force-pushed the gridfs-orphans branch 2 times, most recently from c80c5d4 to e0191e6 Compare September 13, 2026 17:03
@dragoangel

dragoangel commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @andris9 @NickOvt, could you please take a look at this PR and the issue it closes?

GridFS chunks outlive the files document that names them. files_id is
their only link and it is recorded nowhere else, so once the files
document is gone the chunks are unreachable by any query the code can
express. Three paths produce that state: an upload that never finishes,
a delete interrupted between its two non-atomic halves, and the
time-based GC pass itself on a message whose upload straddles its water
mark.

Every in-flight upload and delete now writes a marker document keyed by
files_id and removes it once the operation is whole, so no interruption
is invisible. The GC reads those markers and finishes what was started,
within minutes rather than within maxQueueTime, and acts only on an
operation known not to have completed. The state on the marker is what
makes that safe: a file with no chunks means opposite things depending on
which operation was in flight, and a collector that deleted on sight
would destroy a message that had been queued successfully.

A marker records when it stops being anybody's rather than when it was
written, and the process holding the operation pushes that moment forward
every minute for as long as it is still holding it. The timer lives in
the very process doing the writing, so it cannot outlive it: a child
killed, out of memory, or thrown out of its event loop takes its timers
with it and the marker goes stale with no cleanup path having to run
first. The beat only extends, never creates - an operation can be ended
by a different process than the one beating for it, because a forked
child hands its cleanup to the master over IPC, and an upserting beat
would raise the marker from the dead and then beat for it forever.

Both queues store: RemoteQueue is the one every SMTP submission takes,
MailQueue the one behind the HTTP API, and the marker covers both. It is
held until the message is queued rather than until the upload finishes,
because a stored message with no delivery behind it is nobody's, and
PUT /store/:id clears its own because nothing on that path ever queues
one.

An SMTP client that disappears mid-DATA needs no crash to reach the same
state. smtp-server handles the socket error at session level and, in
_onClose, calls this._dataStream.unpipe() and drops the stream without
ending, erroring or destroying it, so nothing downstream is told
anything: the upload stays open, removeMessage is never called, and
maildrop.add's callback never fires. Erroring the size limiter from
onClose is the whole fix, because the error then takes the route a size
limit or a plugin rejection takes and the existing handlers unwind down
to store(). A message that reached the terminating dot is left alone.

The time-based pass stays where it was, as the coarse backstop for
anything orphaned before the markers existed. No operator action is
needed on upgrade.

Signed-off-by: Dmytro Alieksieiev <1865999+dragoangel@users.noreply.github.com>
@dragoangel

Copy link
Copy Markdown
Contributor Author

Deployed this version on my setup, good so far JFYI.

@dragoangel

Copy link
Copy Markdown
Contributor Author

Hi @NickOvt thank you for review and fixes on top, on days I found gap in this PR, that I not yet fixed, and I can ship a fix on top, or leave it to you, as you with?

Now in this state releaseDelivery removes the delivery before anything marks the body. Thedelivery document is deleted first, then comes the "does another delivery stillreference this message" check, and only then removeMessage, which is where thedeleting marker is written. An interruption anywhere in that gap leaves a bodythat nothing references and nothing describes: no delivery points at it, nomarker in <gfs>.pending, and the collector only ever looks at<gfs>.pending. That is the exact shape of leak the marker was introduced tomake recoverable, surviving on the path that produces it most often.

What we run instead: resolve filesId and write the deleting marker beforedeleting the delivery document. Writing it early is harmless when the body turnsout to still have deliveries, because the collector already distinguishes thatcase through its queued check. This should have been part of the patch and I didnot carry it over.

@NickOvt

NickOvt commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Hey!

I've been thinking about this PR for a while now.
I think it adds unneeded complexity. If GC is enabled, the orphanaged files will be cleaned up anyway at one point or another. If your zone-mta is properly configured and you do not have substantial problems with deliverability there should not be many really lingering queue entries and thus GC will clean the files at one point or another. That's why there is maxQueueTime and the GC conf.

I am not saying that this PR is not useful. It is, but I need some clarification or reasoning from your side whether that PR actually solves a problem that is real, and not a problem that may happen in 0.001%™️ cases.

Keep up the good work
Cheers

@dragoangel

dragoangel commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @NickOvt, in my case it was strongly necessary as my database grow up and doesn't cleanup till 2 days not passed - which thrown away all emails by GC, not before. On big queue and at high load - its ever much more garbage in db, in my case it was more then 150Gbs and I was forged to give it more space, and without this patch every failed delete, every cancel, including by user or by timeout etc - can and will leaves a chunks in db, basically it may be classified as DoS if push hard enough :) - any user can quickly fill db with bunch of trash and GC which exist in ZoneMTA now doesn't handle it right away. Details of why I created this described in issue linked to this PR.

P.s. as we speak about queue lifetime can you advice please? User can adjust it, f.e. put it to bigger value then 2 days - lets say 5 days, but on practice queue will never get longer then this - because 17 retries (which are hardcoded in ZoneMTA) is always equal to 48 hours (because retry intervals are also hardcoded), is this was done by design or they have may be tunable?

@NickOvt

NickOvt commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

Hello @dragoangel

I've pushed some changes. Please review them with your AI Agent (or yourself :D), if all good then I'll probably merge this PR soon.

Cheers!

@NickOvt

NickOvt commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Also regarding the queue question you had:

For example, this JavaScript configuration preserves the initial backoff and then retries every four hours, giving 35 retries spanning five days:

queue: {
    deferTimes: [
        5, 7, 8, 25, 75, 120,
        ...Array(29).fill(240)
    ].map(minutes => minutes * 60 * 1000),

    maxQueueTime: 6 * 24 * 60 * 60 * 1000
}

The 17 retries over ~48 hours are defaults, not fixed limits. Set queue.deferTimes (delays in milliseconds) to change both retry count and duration.

queue.maxQueueTime only controls cleanup. Increasing it alone won’t extend retries. For five days of retries, extend deferTimes and keep maxQueueTime above five days.

It is just the deferTimes is not configures in default.js or any toml files and probably that's why it seems it is hardcoded, when in reality it is not, and it is configurable

@dragoangel

dragoangel commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

It is just the deferTimes is not configures in default.js or any toml files and probably that's why it seems it is hardcoded, when in reality it is not, and it is configurable

I think it would be good that each zone had own deferTimes exposed ☺️, then everything would be clear.

@dragoangel

dragoangel commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @NickOvt, thanks a lot. I went through both of your commits.

The fencing from the October commit stays as is: the collector's claim, renewPending before the answer and before insertMany, and onLost. It closes a real hole. The same goes for the shared gridfs-store.js, the guard against a stale heartbeat response, catching the dkimStream error before the message:store hooks finish, and the state check in the claim.

Below is what I would change before the merge.

1. A marker lives only as long as its operation

The marker is in effect a hand-made transaction. GridFS keeps one file in two collections and writes or deletes them without a transaction, so the marker records what a half-done operation needs to be finished by someone else. Like a transaction, it should end together with its operation. Once the operation has finished, the marker has nothing left to protect.

Markers are now kept after their operation: 'releasing' on every message that still has recipients left, and 'writing' on a slow upload until its last delivery is released. That turns .pending from a list of operations in flight into a list of references that grows with the deferred queue, and three problems follow from it:

  • A release depends on a marker write. releaseDeliveryAsync (lib/mail-queue.js:756) awaits files.findOne and markPending('releasing') before it deletes the delivery, and finally releases the lock either way. If either call fails, the delivery stays in the queue unlocked and is sent again. This needs no trouble on the Mongo side. A kept marker is expired, so every GC pass claims it, and an upsert against a claimed marker matches nothing and fails with E11000 on _id. If another recipient of the same message is released at that moment, that recipient gets the message twice.
  • GC load grows with the queue. On every instance, every minute, each kept marker is claimed, checked against files and the queue, and unclaimed. That is four round trips per partially delivered message in the queue.
  • One stuck marker blocks the coarse sweep. The sweep is bounded by the oldest marker, so a marker that never resolves holds the sweep back for good. An example is a filename that isQueued cannot map, which it reports as queued.

Proposal: keep one marker document per file, with _id equal to files_id, and remove it when its operation ends, in every state.

  • A release writes a 'deleting' marker only when no other delivery of the message is left. It checks that with one read before it deletes its own delivery. All other releases write nothing, so a message with 100 recipients costs 100 reads and one marker, instead of 100 marker writes. The 'releasing' state is then not needed.
  • A release writes its marker as best effort. If the write fails, the release logs it and deletes the delivery anyway. The worst outcome is then a body left for the coarse sweep, and never a second send.
  • clearPending keeps your state filter. A delivery can be released before the upload removes its 'writing' marker, and that upload must not remove the 'deleting' marker that now protects the delete.
  • When the collector finds an expired 'deleting' marker, it finishes the operation: it deletes the remaining deliveries of the message, then the files document, the chunks and the marker. That marker is written only by a release that saw no other delivery, or by a delete that has already decided to drop the message, so any deliveries left are leftovers of the interrupted operation. A delivery that already got its final response (2xx, 5xx or retries exceeded) is then not sent twice. An expired 'writing' marker whose file has deliveries is only removed, because the upload has handed the body over.
  • In the steady state .pending is empty again. The collector claims only operations that were really abandoned, so a release almost never meets a claimed marker.

This leaves one narrow window open. If the last two releases of a message run at the same time, each one sees the other's delivery, so neither writes a marker before it deletes its own delivery. The release that then finds no deliveries left writes the 'deleting' marker in removeGridfsFile, but only after its delivery is already gone. If it dies in those few round trips, the body has no marker.

In practice I don't expect this to happen, because it needs three unlikely things at once:

  • The last two deliveries of the same message must finish within a few milliseconds of each other, so that both pre-checks run before either delete. The GC expiry pass releases deliveries one by one, so only sends can race like this.
  • The master process that runs that release must die in a hard way, such as OOM, a crash or SIGKILL. A graceful shutdown waits for it: the sender child counts a send as finished only after the master has answered its RELEASE.
  • That death must land inside a window of three round trips: the delivery lookup, the files lookup and the marker upsert.

Even then, the result is a single body that nothing references, and the coarse sweep collects it. The message is never lost or sent twice. Closing this window would cost a marker write on every release, and I don't think that is worth it.

2. Slow uploads: limit the intake time instead of protecting them

completePending and GC_GRACE_PERIOD exist because the sweep takes its mark from the oldest delivery _id, which is the time the message was queued, while the files_id and the first chunks of a slow upload are older than that. Nothing limits that gap today. socketTimeout is an idle timeout and every byte resets it, so a client that trickles its DATA keeps the upload alive as long as it likes, and the heartbeat keeps its marker alive with it. Such a message gets its 250, and the sweep can then delete its body.

An upload that takes this long is not a submission worth keeping. Proposal: refuse it instead of protecting it.

  • Add a limit on the whole intake, from the start of the upload to the answer, on both SMTP and the HTTP API. When the limit is reached, the upload is aborted, the stored body is removed, and the client gets a retryable 451, or 503 on HTTP.
  • Check the limit once more right before push, so no delivery is ever created for a body older than the limit.
  • Keep GC_GRACE_PERIOD above the limit, for example a limit of 5 minutes with a grace of 10.

Then every body that got a 250 is younger than its delivery by less than the grace, and every live upload is younger than the grace. The sweep can stay as it is, and completePending, the marker bound on the sweep's mark and the kept 'writing' marker all go away.

3. Delete order: the files document first, then chunks

Both orders can be recovered as long as the marker is written before the first delete and removed last. The marker alone holds files_id, and from it the collector reaches both the files document and the chunks. So the order only decides what a reader sees in between.

The references run in one chain: delivery id, files filename, files _id, chunks files_id. The marker is written before the last delivery goes, and the rest is removed top-down: the files document, then the chunks, then the marker. An interruption then leaves one of two states:

  • A complete file that can still be found by name. The collector finishes the delete from the top: any remaining deliveries, found through the filename, then the files document, then the chunks.
  • Chunks that only the marker reaches by files_id. The collector deletes them.

Chunks-first leaves a files document whose chunks are gone. GridFSBucketReadStream ends without an error when the chunks run out before file.length, so anything that opens the body in that window can read an empty or truncated message as a success. The sender is such a reader, and it takes the headers from the metadata, so it would send a message with headers and an empty body, and nothing would report it. With files-first, the send fails with FileNotFound and nobody gets an empty message. It is also the order GridFSBucket.delete() uses.

The first commit of this PR argued for chunks-first, and that was wrong: the marker makes the files document unnecessary for recovery.

Proposal: delete the files document first in both removeGridfsFile and the collector. Nothing else has to change: when the file is already gone, the collector already deletes the chunks by the marker's files_id.

4. An idea for later: transactions for the metadata steps

The upload itself cannot run in a transaction. Its chunks arrive for as long as the client sends DATA, far beyond transactionLifetimeLimitSeconds, so the 'writing' marker stays. The two metadata steps around the upload could use one:

  • push: insert all deliveries and remove the 'writing' marker in one transaction. The message is then queued for all recipients or for none, and the body passes from the upload to its deliveries with no gap. Today an insertMany with ordered: false can fail partway, and the failure path then removes the body under the deliveries it did insert.
  • The last release: delete the delivery, the files document and the chunks in one transaction. The 'deleting' marker and the window described in point 1 are then not needed. If two last releases run at the same time, one of them gets a write conflict, and its retry finds no deliveries left.

Transactions need a replica set, so a standalone deployment would keep the markers as the fallback. They also add a commit, ideally with w: majority, to every push and every last release. Before I propose this for real, I want to measure that cost on a replica set under load, where Mongo latency is more likely to matter. So this is not for this PR.

5. Follow-up after this PR

Once this PR is merged, I would open a few more, so that this one does not grow further. They would cover:

  • A message whose client disconnects before it gets the answer is torn down on both the SMTP and the HTTP submission paths. The delivery documents are deleted first, then the body, through a new DISCARD command to the master.
  • When the marker write fails, the client gets a retryable answer: 451 on SMTP, 503 on the HTTP API.
  • Intake shedding while Mongo is too slow or gone. Each process keeps an in-memory view of its own write latency: the driver's command monitoring, the age of its oldest unfinished write, a topology with no writable server, and the PUSH round trip. While that is above a threshold, a plugin refuses new SMTP connections with 421 and /send with 503, so the client retries later and does not wait on a store that cannot finish.
  • The upload marker is removed only after the answer has reached the client. That fits point 1: an intake operation ends when the client has the answer, not at push. A client that disconnects before its 250 comes back and sends the message again, so the queued copy has to be torn down, and the marker covers the gap between deleting its deliveries and deleting its body. Without that teardown, keeping the marker past push protects nothing, which is why it belongs with the teardown and not in this PR.

Proposal: I push 1-3 to this branch. Is that OK with you?

@NickOvt

NickOvt commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Hello!

I've read the proposals 1-3, I think they can be pushed to this branch. After that I'll run a review once more and if all good then merge.

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.

GridFS chunks are orphaned on write as well as on delete, and the GC only clears them by age

2 participants