Repository navigation
fix: make interrupted GridFS uploads and deletes recoverable - #516
dragoangel wants to merge 4 commits into
Conversation
c80c5d4 to
e0191e6
Compare
d823a2b to
8ee4802
Compare
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>
8ee4802 to
a5595ea
Compare
|
Deployed this version on my setup, good so far JFYI. |
|
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 What we run instead: resolve |
|
Hey! I've been thinking about this PR for a while now. 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 |
|
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? |
|
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! |
|
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 |
I think it would be good that each zone had own deferTimes exposed |
|
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, Below is what I would change before the merge. 1. A marker lives only as long as its operationThe 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
Proposal: keep one marker document per file, with
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 In practice I don't expect this to happen, because it needs three unlikely things at once:
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
An upload that takes this long is not a submission worth keeping. Proposal: refuse it instead of protecting it.
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 3. Delete order: the files document first, then chunksBoth orders can be recovered as long as the marker is written before the first delete and removed last. The marker alone holds The references run in one chain: delivery
Chunks-first leaves a files document whose chunks are gone. 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 4. An idea for later: transactions for the metadata stepsThe upload itself cannot run in a transaction. Its chunks arrive for as long as the client sends DATA, far beyond
Transactions need a replica set, so a standalone deployment would keep the markers as the fallback. They also add a commit, ideally with 5. Follow-up after this PROnce this PR is merged, I would open a few more, so that this one does not grow further. They would cover:
Proposal: I push 1-3 to this branch. Is that OK with you? |
|
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. |
Implements #515.
What the problem is
GridFS chunks outlive the
filesdocument that names them.files_idis their onlylink and it is recorded nowhere else, so once the
filesdocument is gone the chunksare 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
_idis below a water mark taken from the oldest queue row, and an orphan's_idsinks 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 laterather 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_idinto<gfs>.pending, and removes it once the operation is whole, so no interruption isinvisible. 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 notto have completed.
The
stateon the marker is what makes that safe. A file with no chunks meansopposite 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:
deletingwith a files document still present: the delete stopped partway, finishit in the order it would have run in
writingwith no files document: an upload that never produced one, so its chunksare unreachable and go
writingwith a files document but no delivery naming it: the upload finished butthe message never reached the queue, so nothing will ever deliver or delete it
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
RemoteQueueis the queue a forked SMTP child stores through, which is the path everysubmission arriving over the wire takes;
MailQueueis 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 backso the caller can say so,
mail-dropclears it after the push, andPUT /store/:idclears 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-serverhandles the socket error at session level and, in_onClose, callsthis._dataStream.unpipe()and drops the stream without ending, erroring ordestroying it, so nothing downstream is told anything: the upload stays open,
removeMessageis never called because no delete ever happens, andmaildrop.add'scallback never fires.
Erroring the size limiter from
onCloseis the whole fix, because the error thentakes 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 hadwritten. 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
ClientDisconnectrather than only coded, becausemail-droptreats anything whose name ends in
Erroras a storage failure worth logging andreporting 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.
onClosealso recordssession.connectionClosed, because a connection can be lostwhile the
smtp:datahooks are still running, before there is an in-flight messagefor 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.
collectPendingGridfsreads a collection that is emptywhenever nothing is in flight. The heartbeat is one small update a minute per
operation actually in flight. The time-based deletes are
_idrange scans on analways-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.jsis new: nineteen cases covering the collector's fouroutcomes, the marker lifecycle, the heartbeat, the delete order, and a delete taking
over a stale upload marker.
test/remote-queue-gridfs-test.jsadds six for the storepath every SMTP submission takes, including which stream failures count as storage
failures and which are outcomes.
test/api-store-marker-test.jsadds three for thestore-only endpoint, and
test/smtp-interface-test.jsgains 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 onexpiresthrough
indexes.yaml, and nothing outside the process that opened an operation needsa number to know. An index named
mailpending, oncreated, existed in an earlierrevision 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.