Skip to content

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

Open

Description

@dragoangel

Version reviewed: 3.10.18 (lib/mail-queue.js)

Summary

While reading through the queue code I noticed that GridFS message bodies get orphaned: chunks
survive with no files document pointing at them. Nothing in the codebase can identify them as
orphans. The one pass that does eventually remove them works by age, without knowing what it is
removing, and cannot act until the whole queue has moved past them, which takes as long as the
oldest queued delivery lives. Three separate things produce that state, and the first needs no
delete at all, which is why it happens on installations where nothing has ever crashed.

1. An upload that never finishes orphans its chunks with no delete involved

store() at lib/mail-queue.js opens the upload before any data arrives:

let store = this.gridstore.openUploadStream('message ' + id, { ... });

GridFSBucketWriteStream assigns this.id in its constructor and inserts chunks as they are
written, while the files document is inserted only when the stream finishes. So for the whole
duration of an upload the database holds chunks with no parent, which is why an orphan collector
needs a safety window at all.

That state is meant to be transient. It stops being transient when the incoming stream neither
ends nor errors, because the only cleanup in store() hangs off an error:

stream.once('error', err => {
    ...
    store.once('finish', () => {
        this.removeMessage(id, () => callback(err));
    });
    store.end();
});

An SMTP client that disappears in the middle of DATA produces neither event. smtp-server
handles the socket error at session level and, in _onClose, calls this._dataStream.unpipe()
and drops the stream: it is never ended, never errored and never destroyed. Nothing downstream
of it is told anything at all, so:

  • the upload stream stays open and its chunks stay in <gfs>.chunks
  • the files document is never written, so nothing points at them
  • removeMessage is never called, because no delete ever happens
  • maildrop.add's callback never fires

The result is identical to an interrupted delete, but it is produced without any delete, without
a crash, and without anything unusual happening on the server. Any client timeout, connection
reset or abandoned session during DATA leaves one orphan behind, sized by however much of the
body had arrived.

This also means the orphan population skews towards large messages: the longer a body takes to
arrive, the wider the window in which the client can give up.

Reproducing, with no crash and no manual deletion

  1. Open an SMTP session, authenticate if required, and send DATA.
  2. Write a few megabytes of body.
  3. Reset the connection without sending the terminating ., for example socket.resetAndDestroy()
    in Node, or kill -9 on the client or break network connection between client and server.
  4. Count:
// uses the standard {files_id: 1, n: 1} index, does not read chunk payloads
db.getCollection('<gfs>.chunks').distinct('files_id').length
db.getCollection('<gfs>.files').estimatedDocumentCount()

Any gap between the two numbers is orphaned messages. It grows by one per aborted session and
narrows only once the water mark in section 3 has moved past them, because the sweep matches
chunk _id against that mark and cannot express "chunks whose parent file does not exist".

2. removeMessage deletes the file document before its chunks, non-atomically

lib/mail-queue.js:982:

removeMessage(id, callback) {
    log.verbose('Queue', '%s REMOVE', id);
    this.mongodb.collection(this.options.gfs + '.files').findOne(
        { filename: 'message ' + id },
        (err, entry) => {
            if (err) return callback(err);
            if (!entry) return callback(null, false);
            this.gridstore.delete(entry._id, callback);
        }
    );
}

GridFSBucket.delete() in mongodb@4.17.2 (the version pinned in package.json) performs two
independent operations, in this order:

  1. deleteOne on <gfs>.files
  2. deleteMany({ files_id }) on <gfs>.chunks

There is no transaction around them. If the process dies between the two, or the second call
fails, the files document is already gone and the chunks it pointed at become unreachable:
files_id is the only link to them and nothing else records it anywhere.

The exposure scales with message size. At the default 255 KB chunk size a 20 MB message is
roughly 80 chunk documents, so the second delete takes proportionally longer and the window
widens exactly for the messages that cost the most disk.

3. The GC sweep cannot target orphans, and a long-lived delivery holds it back

clearGarbage() at lib/mail-queue.js:1069-1106 is the only code besides removeMessage that
touches GridFS:

// Find the oldest queued message
let delivery = await collection.findOne({}, { sort: { _id: 1 }, projection: { _id: 1 } });

let clearUntil;
if (delivery) {
    clearUntil = delivery._id.getTimestamp().getTime();
} else {
    // empty queue, so delete everything
    clearUntil = Date.now();
}

// 10 minute shift just in case
clearUntil -= 10 * 60 * 1000;

let untilObjectId = ObjectId.createFromTime(Math.round(new Date(clearUntil).getTime() / 1000));
let query = { _id: { $lte: untilObjectId } };

r = await this.mongodb.collection(this.options.gfs + '.files').deleteMany(query);
r = await this.mongodb.collection(this.options.gfs + '.chunks').deleteMany(query);

Two properties of this stand out:

  • The chunks sweep matches on the chunk's own _id, not on files_id. It is purely
    time-based and cannot express "chunks whose parent file no longer exists", so it cannot target
    an orphan. It removes one only as a side effect of removing everything older than the mark.
  • Its upper bound is the ObjectId timestamp of the oldest row in the queue collection. A
    single delivery that keeps deferring holds clearUntil back for as long as it stays queued.
    With the default maxQueueTime of 30 days that can be a month. Everything newer than that
    row, orphans included, has to wait for the mark to reach it.

So the only backstop for the first two problems runs as far behind as the oldest queued delivery.
That is bounded by maxQueueTime, since the expiry pass in the same function removes anything
older, which makes collection late rather than absent: up to 30 days on the default setting. It
is unbounded only where expiry cannot run at all, with maxQueueTime: 0 or disableGC: true.

grep -rn files_id lib/ returns nothing, and so does grep -rni orphan lib/, which confirms
there is no other cleanup path.

Being time-based also makes the sweep a producer in its own right, not only a failed collector.
files._id is generated when openUploadStream is called, while each chunk gets its own _id
as it is inserted, so the chunk ids of a large message are spread across the whole upload. A
message whose upload spans the second that clearUntil lands on has its files document swept
while its later chunks survive. That heals itself on a later pass while clearUntil keeps
advancing, and stops healing the moment the water mark is pinned, which is this same problem.

Reproducing

This part is deterministic:

  1. Configure a zone whose target always defers, for example a sink that answers 4xx.
  2. Submit one message to that zone. It stays in the queue, retrying.
  3. Create an orphan. Either kill the process during removeMessage for a large message, or
    simply run db.getCollection('<gfs>.files').deleteOne({ _id: <id> }) by hand, which leaves
    exactly the state an interrupted delete leaves behind.
  4. Wait. The GC runs every 60 s and leaves those chunks alone for as long as the message from
    step 2 stays queued, because clearUntil stays pinned to it.

The counting snippet in section 1 makes the general case visible on any existing deployment.

Consequence

Orphaned chunks accumulate for as long as the water mark is held back, and nothing reports them
while they do. Because they no longer appear in <gfs>.files they
are invisible to anything that reasons in terms of messages: the total size of <gfs>.chunks
can grow to many times the sum of <gfs>.files.length while every message-level view of the
system looks perfectly healthy.

Two things that look like they should help, and do not:

  • Clearing the queue collection does not help. The garbage is not in the queue.
  • A WiredTiger compact does not help either. From the storage engine's point of view the
    chunks are live documents, so there is little free space inside the files to reclaim.

Suggested fix

One record makes all three producers recoverable, because in every case the damage is the same:
chunks exist and nothing names them. Give every upload and every delete a small marker document,
keyed by files_id, that exists exactly while the operation is in flight.

{ _id: <files_id>, state: 'writing' | 'deleting', created: <Date> }

Writing

openUploadStream assigns the id in its constructor, so the marker can be inserted before the
first chunk is written, and removed once the files document exists. Order matters and is the
whole point:

  1. insert the marker
  2. stream the chunks
  3. the driver inserts the files document on finish
  4. remove the marker

Removing the marker before step 3 would reopen the same hole: a crash in between would leave
chunks with neither a marker nor a parent. Done in this order, no interruption at any point is
invisible.

Deleting

The same marker, with state: 'deleting', inserted before the first delete. Then chunks, then
the files document, then the marker. An interruption anywhere leaves the marker behind and the
operation can be finished later. This subsumes reordering the two deletes: the order still
matters, but it is no longer the only thing standing between an interruption and a permanent
orphan.

Collecting

The collector reads the marker collection, not the chunks collection. For each marker older than
a threshold:

marker files exists files missing
writing the upload finished and only the marker removal was lost: remove the marker only a true orphan: delete chunks by files_id, then the marker
deleting an interrupted delete: finish it, chunks then files, then the marker the delete all but finished: remove the marker

The writing plus files exists case is why the marker needs a direction. Without it the same
observable state means opposite things, and a collector that deletes on sight would destroy a
message that had been queued successfully.

The threshold does not need to be invented, or configured. An upload cannot outlive the session
carrying it, and that is bounded by socketTimeout in lib/smtp-interface.js, ten minutes by
default, so the longest socketTimeout among enabled interfaces plus a margin is the whole of
it. Anything older than that cannot belong to an upload still in progress.

This costs one small document per message, written and removed on a path that already writes
several, and the collector reads a collection that is empty whenever nothing is in flight.

The time-based pass stays

Not as the orphan collector, which it never was, but as the coarse backstop next to it. It is
the only thing that can remove what has no marker to describe it: anything orphaned before the
markers existed, and the chunks the pass itself strands on a message whose upload straddles the
mark. Its water mark is not a meaningful statement about whether a body is still referenced,
which is exactly why the markers are needed, but collecting by age needs no such statement.

Keeping it also means there is nothing to migrate. The existing backlog ages out the way it
always has, so the markers can be introduced without asking anyone to run anything.

Tearing the pipeline down when a client disappears

Worth fixing next to the above, in its own right. lib/smtp-interface.js bridges an error on the
DATA stream into the size limiter, but as described in section 1 that stream never errors when a
client is lost, so the bridge never fires and everything downstream of it, including the pending
GridFS upload, is left suspended rather than torn down. With a teardown in place, an aborted
session cleans itself up immediately and the collector only has to catch processes that died
outright.

Activity

  1. changed the title [-]GridFS chunks can be orphaned permanently: removeMessage is not atomic and the GC sweep cannot collect orphans[/-] [+]GridFS chunks are orphaned on write as well as on delete, and the GC cannot collect either[/+] on Sep 12, 2026
  2. added 3 commits that reference this issue on Sep 13, 2026
    650a5d8
    c80c5d4
    e0191e6
  3. changed the title [-]GridFS chunks are orphaned on write as well as on delete, and the GC cannot collect either[/-] [+]GridFS chunks are orphaned on write as well as on delete, and the GC only clears them by age[/+] on Sep 13, 2026
  4. added a commit that references this issue on Sep 13, 2026
    29a6e80
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions