Skip to content

perf(mongodb): decode BSON once and stop the extra reads on every page #4548

Done

Description

@datlechin

Problem

Opening a MongoDB collection converts each document many times, keeps a second copy of every document for an export that may never happen, and adds a sequential round trip on every first page:

  • Each document goes BSON, canonical Extended JSON text, JSONSerialization, an unwrap pass into a second [String: Any] tree, then several walks for columns and kinds, the flatten, and another parse for the export copy. Estimated 100-200 µs per 10-field document against 5-20 µs for one bson_iter pass, not measured.
  • Every first page and refresh sends listCollections after the find to re-read the validator: one more RTT, sequential with the find (about 50 ms at +50 ms, more through a tunnel).
  • Every browse page, including app-built ones, runs through the JavaScriptCore shell. Its share of the open is not measured.
  • A filtered tab counts with an uncapped countDocuments (5 s budget) on the same serial libmongoc queue that serves the next page.

Cause

  • iterateCursorJson turns each document into canonical Extended JSON and keeps [String] (apple/Plugins/MongoDBDriverPlugin/MongoDBConnection+ScriptHelpers.swift:329-354, bsonToJson at apple/Plugins/MongoDBDriverPlugin/MongoDBConnection.swift:1003-1009). readDocuments parses each text with JSONSerialization and builds a second tree with unwrapExtendedJson (MongoDBConnection+ScriptHelpers.swift:23-34, MongoDBConnection.swift:1013).
  • buildPluginResult walks the documents again for columns, kinds, filter kinds, identity kinds, binary subtypes, field kinds and number kinds, then flattens (apple/Plugins/MongoDBDriverPlugin/MongoDBPluginDriver.swift:1056-1107).
  • It always sets exportDocuments (MongoDBPluginDriver.swift:1105). MongoExportDocument.read parses each text again and runs bson_new_from_json on the whole text only to read its size (apple/Plugins/MongoDBDriverPlugin/MongoExportDocument.swift:11, :29). The documents travel with the rows (apple/TablePro/Core/Plugins/PluginDriverAdapter.swift:1302) and stay in the tab (apple/TablePro/Models/Query/TableRows.swift:208, :394-408).
  • runScript evaluates every statement in MongoScriptRuntime and then awaits declaredColumns (MongoDBPluginDriver.swift:227-271). declaredColumns reuses the cached schema only when skip > 0; a first page always calls declaredSchema, which sends listCollections (:275-291, :421-432).
  • An unfiltered open already uses estimatedDocumentCount (MongoDBPluginDriver.swift:503-512, chosen by rowCountPlan in apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift:915-916). A filtered count calls mongoc_collection_count_documents with only maxTimeMS and an _id_ hint, no limit (apple/Plugins/MongoDBDriverPlugin/MongoDBConnection+SyncHelpers.swift:241-262). Because Mongo sets filtersTypedByReadRows, the count runs on the page's own driver (apple/TablePro/Core/Database/DatabaseManager+ScopedDriver.swift:249-258).

Overlaps #4444: M2 (build export documents only when exporting) and M3 (read BSON once instead of five parses a document) already cover the decode and the export copy. This issue keeps them as the first two steps and adds the validator read, the shell on browse pages and the filtered count.

Change

  • M3: read the cursor's bson_t with bson_iter, the documented way to read BSON, in one pass per document that yields the typed cell, the kind per field (feeding every kind cache from one place), the absent-cell bits and the _id locator. Produce Extended JSON only for nested documents and arrays, from the sub-document. Keep the raw BSON bytes as the stored form for editing and export. Keep JSONSerialization out of every hot loop.
  • M2: derive PluginExportDocument from the stored bytes when an export or copy asks, through a PluginKit requirement with a default, so export and copy still match the rows the grid showed. Take the size from the bson_t length prefix.
  • Use the cached declared schema for tab open, filter and sort reloads; re-read it on an explicit Refresh and drop it in tableDefinitionDidChange and after a collMod or create the shell runs.
  • Measure the shell's share of a browse page with a signpost. If it is a real share, have the table browse path, which builds its own find (filter, sort, skip, limit) and never needs JavaScript, call mongoc_collection_find_with_opts directly, and keep the shell for statements the user writes.
  • Give the filtered count the documented limit option (threshold + 1), the same capped count SQL engines use, so the server stops at the threshold.

Measure

  • Signposts around the find, iterateCursorJson, readDocuments, buildPluginResult and the shell evaluation. A 1,000-document and a 100,000-document find on 10-field and 50-field collections: time and persistent bytes after the result lands (Instruments Allocations), before and after.
  • Round trips per collection open with the mongod profiler: one find, no listCollections.
  • A filtered tab on a 1M-document collection: count time and next-page latency while the count runs.

Part of the performance plan.

Activity

  1. added
    enhancement
    platform-macos
    on Nov 25, 2026
  2. datlechin commented on Nov 25, 2026

    @datlechin
    MemberAuthor

    What the first PR for this issue ships, and what is left:

    • Shipped: M3, one bson_iter pass per document into the values, the canonical tree, the locator and the size, BSON bytes kept as the batch's stored form, Extended JSON only when JavaScript reads it. The export copy is built from that tree with the size from the length prefix (no second parse, no bson_new_from_json). Signposts around the shell, the cursor read, the decode and the grid build.
    • Left, M2 lazy export documents: the host keeps a PluginExportDocument per row (TableRows.exportSnapshots, masking included), so deriving it on demand needs a PluginKit requirement that turns stored bytes into export documents and a place in the tab's row store for the bytes. That is the row store perf(results): hold every Mac result in the core's columnar store #4521 is replacing; it belongs with that work.
    • Left, declared schema reuse: the session driver cannot tell an explicit Refresh from a tab open, a filter or a sort reload; all of them arrive as a first page. Reusing the cached validator without that signal would stop a Refresh from picking up a changed validator. It needs a PluginKit hook the host calls on Refresh, plus dropping the cache after a shell collMod or create.
    • Left, capped filtered count: fetchFilteredRowCount takes no limit, so the threshold + 1 cap needs a new PluginKit requirement with a default and RowCountPlan.filteredNonSQL carrying the limit.
    • Left, browse without the shell: the signposts are in; the shell's share of a page has to be read from a trace on a live server before the table path calls mongoc_collection_find_with_opts itself.
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

    enhancementplatform-macos

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions