agentleFS
MongoDBKnown publishermongodb/mongo-csharp-driver/src/MongoDB.Driver/GridFS/AGENTS.md

mongo-csharp-driver / GridFS

AGENTS.md3.2k starsChanged 4 months agoApache-2.0View on GitHub

GridFS stores binary files in two collections per bucket: <bucket>.files (metadata, one document per file) and <bucket>.chunks (binary data, many documents per file). Chunk size is configurable; default 255 KiB. GridFSBucket holds the cluster reference, an IBsonSerializer<GridFSFileInfo<TFileId>> (_fileInfoSerializer), and a BsonSerializationInfo for the _id field (_idSerializationInfo, which is what enforces the TFileId round-trip discussed in the pitfalls below). Mutating operations (Delete, Rename, OpenUploadStream, Drop) bind via GetSingleServerReadWriteBinding; reads (DownloadAsBytes*, DownloadToStream*, OpenDownloadStream*, Find) bind via GetSingleServerReadBinding. Either way, a single upload/download…

Trending

Quiet since September.about the whole repository

Dec 2025: 0 mentionsJan 2026: 1 mentionFeb 2026: 0 mentionsMar 2026: 1 mentionApr 2026: 1 mentionMay 2026: 2 mentionsJun 2026: 0 mentionsJul 2026: 1 mentionAug 2026: 1 mentionSep 2026: 2 mentionsOct 2026: 0 mentionsNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the mongodb/mongo-csharp-driver repository that our weekly crawl found. There is no adoption data for this file yet.

Who's talking about mongodb/mongo-csharp-driver

The biggest 5 of 40 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 40

Talked about on GitHub (40 times).

On GitHub · 40

35 more on GitHub

The file

We split this AGENTS.md into the rules it gives an agent

1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Generic file-ID mismatch: If you pick a custom TFileId (not ObjectId), make sure a serializer is registered.

    line 33

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

GridFS — AGENTS.md

GridFS stores binary files in two collections per bucket: <bucket>.files (metadata, one document per file) and <bucket>.chunks (binary data, many documents per file). Chunk size is configurable; default 255 KiB.

Public API

  • IGridFSBucket<TFileId> / GridFSBucket<TFileId> — generic over the file ID type. The non-generic IGridFSBucket / GridFSBucket is ObjectId-keyed.
  • Operations: UploadFromStream, UploadFromBytes, DownloadToStream, DownloadAsBytes, DownloadAsBytesByName, DownloadToStreamByName, OpenUploadStream, OpenDownloadStream, OpenDownloadStreamByName, Find, Delete, Drop, Rename. All have sync + async pairs. Return shapes worth flagging: Find returns an IAsyncCursor<GridFSFileInfo<TFileId>> (FindAsync returns a Task<…> of that), DownloadAsBytes* returns a byte[], and OpenUploadStream* / OpenDownloadStream* return the abstract stream types described below — the upload side returns a GridFSUploadStream<TFileId> whose Id property hands back the allocated files_id.
  • Streams: the public types are the abstract Stream subclasses GridFSUploadStream<TFileId> and GridFSDownloadStream<TFileId>, plus their non-generic compat shims GridFSUploadStream : DelegatingStream and GridFSDownloadStream : DelegatingStream (declared in GridFSUploadStreamCompat.cs / GridFSDownloadStreamCompat.cs) — these wrap the ObjectId-keyed bucket and are part of the public surface, paralleling the GridFSBucket / GridFSBucket<TFileId> compat split. The concrete runtime implementations — GridFSForwardOnlyUploadStream<TFileId> for uploads, and either GridFSForwardOnlyDownloadStream<TFileId> (default) or GridFSSeekableDownloadStream<TFileId> (selected via new GridFSDownloadOptions { Seekable = true }) for downloads — are all internal and not part of the public surface.
  • File metadata: GridFSFileInfo<TFileId> (with GridFSFileInfoSerializer<TFileId>).
  • Options: GridFSBucketOptions (bucket name, ChunkSizeBytes, read/write concern, read preference); GridFSUploadOptions (ChunkSizeBytes override — same property name as the bucket-level default — plus custom Metadata and BatchSize (chunks per bulk insert into .chunks)); GridFSDownloadOptions (Seekable); GridFSDownloadByNameOptions extends it with Revision; GridFSFindOptions<TFileId> (with a non-generic GridFSFindOptions : GridFSFindOptions<ObjectId> compat alias for the ObjectId-keyed bucket).

Architecture

GridFSBucket holds the cluster reference, an IBsonSerializer<GridFSFileInfo<TFileId>> (_fileInfoSerializer), and a BsonSerializationInfo for the _id field (_idSerializationInfo, which is what enforces the TFileId round-trip discussed in the pitfalls below). Mutating operations (Delete, Rename, OpenUploadStream, Drop) bind via GetSingleServerReadWriteBinding; reads (DownloadAsBytes*, DownloadToStream*, OpenDownloadStream*, Find) bind via GetSingleServerReadBinding. Either way, a single upload/download streams its chunks to the same server (avoids cross-server consistency surprises mid-operation). Note: Find returns an IAsyncCursor, and the single-server property holds for the initial query only — once the cursor's binding is disposed, subsequent getMore calls can be routed independently by the operations layer, so the "same server" guarantee does not extend across the cursor's full lifetime.

Indexes ({filename:1, uploadDate:1} on .files, {files_id:1, n:1} unique on .chunks) are created lazily on the first upload only if the files collection is empty (via an IsFilesCollectionEmpty check). The bool flag _ensureIndexesDone is the actual one-shot guarantor — once set, the short-circuit makes the path a single no-op for the rest of the bucket's lifetime. The accompanying SemaphoreSlim (_ensureIndexesSemaphore) only serializes concurrent first-upload callers so they don't race on the IsFilesCollectionEmpty check; without the bool flag, the semaphore alone would let every caller re-enter the slow path.

Delete can leave orphan chunks if interrupted between its two operations — that is the user-visible hazard, so handle it first. The implementation removes the .files document first (GridFS calls new DeleteRequest(filter) with no explicit Limit; the DeleteRequest constructor's default Limit=1 is what caps the match to a single .files document — there is no Limit = 1 literal in the GridFS code itself), then — after that .files delete returns (whether it matched anything or not) — unconditionally removes any matching chunks. The chunks delete uses an explicit Limit = 0 to remove every matching chunk for the file (the deliberate asymmetry vs. the singular .files delete). There is no try/catch around either call: an exception from the .files delete simply propagates and the chunks delete never runs. After both calls succeed, if the .files deletion matched zero documents, GridFSFileNotFoundException is thrown. The orphan window is any interruption between the two operations — a network error during the chunks delete, but equally a process crash after the .files delete succeeds and before the chunks call is issued. Drop is the only safe full cleanup.

GridFS JSON spec tests run through UnifiedTestSpecRunner.GridFS ([UnifiedTestsTheory("gridfs.tests")]), which picks up everything under specifications/gridfs/tests/ automatically, and the spec's prose tests live in tests/MongoDB.Driver.Tests/Specifications/gridfs/prose-tests/. GridFS coverage also lives in the regular xUnit tests under tests/MongoDB.Driver.Tests/GridFS/, plus the JSON-driven runners pulled in by other specs: tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenGridFs*.cs and tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedGridFs*Operation.cs exercise GridFS as part of the unified / JSON-driven runners used by transactions, retryable reads/writes, etc.

Common pitfalls

  • Unwrapped file IDs in filters. Every driver-built filter carrying a user-provided file id must go through GridFSIdFilter.Create, which wraps the value in $eq. A serialized TFileId can itself be a document, whose keys the server would otherwise read as query operators (CSHARP-6190 / CVE-2026-88025). The spec requires this for _id on .files and files_id on .chunks.
  • Generic file-ID mismatch. If you pick a custom TFileId (not ObjectId), make sure a serializer is registered. Mismatched serializers silently corrupt the _id field on .files.
  • Chunk size vs throughput. The default 255 KiB optimizes for typical web payloads. Very large files with the default size cause many round-trips; bump ChunkSizeBytes (must stay well below the 16 MiB BSON document limit, since each chunk is a BSON document) for large-file workloads.
  • Orphaned chunks on interrupted upload. OpenUploadStream allocates a files_id; aborted uploads (exception, cancellation) leave the chunk documents but no metadata. There is no automatic cleanup unless the caller invokes GridFSUploadStream<TFileId>.Abort / AbortAsync (public abstract on the upload stream, implemented by GridFSForwardOnlyUploadStream), which deletes any chunks already written for the in-flight files_id. If the upload is interrupted before Abort is called — exception caught and swallowed, process crash, unmanaged cancellation — the chunks survive. Log + reconcile, or use Drop for periodic cleanup of test buckets.
  • Concurrent indexes. First write under load can serialize on the index-creation semaphore. After indexes exist, the cost vanishes — but in fresh test environments expect a one-time delay.
  • Revision semantics. The DownloadAsBytesByName / DownloadToStreamByName / OpenDownloadStreamByName family takes a GridFSDownloadByNameOptions whose Revision property defaults to -1 (newest, matching the GridFS spec's default-revision semantics), so leaving the property at its default behaves identically to setting it explicitly to -1. Passing options: null likewise selects newest, since the bucket constructs a default GridFSDownloadByNameOptions internally. Revision = 0 is "oldest". Off-by-one mistakes produce wrong-file failures that look like data corruption — read the spec.
  • Stream ownership. Upload/download streams returned by the bucket must be disposed by the caller (using). Disposing closes the cursor and finalizes the upload metadata.

How to test

dotnet test tests/MongoDB.Driver.Tests/MongoDB.Driver.Tests.csproj -f net10.0 \
  --filter "FullyQualifiedName~GridFS"

GridFS uses a local MongoDB only — no extra environment variables required.

Boundary with operations-reviewer

Chunk-level bulk writes into .chunks, the underlying find cursors over .files / .chunks, and retry semantics for the underlying CRUD operations belong to operations-reviewer (Core/Operations/AGENTS.md). Bucket orchestration — upload/download stream lifecycle, the index-creation bootstrap, Abort semantics, and the two-step Delete ordering described above — belongs here.

Spec links

  • GridFS spec: https://github.com/mongodb/specifications/tree/master/source/gridfs

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.