Repository navigation
Conversation
Add com.mongodb.internal.telemetry in driver-core. The package holds the ApiCounter registry, the TelemetryStore global counter store, and the TelemetrySampler background job. The sampler drains the counters on an interval, resets them, and writes one JSON line to System.out. The line imitates a delivery channel. The store uses one LongAdder per ApiCounter ordinal. Increment never throws and never allocates. A drain returns the deltas and omits zero counters. A broken counter cannot break an instrumented call. The system properties mongodb.telemetryPoc.enabled and mongodb.telemetryPoc.intervalMs control the kill switch and the sample interval. POC scope: one global static store serves all clients. The real design uses one store per MongoClient. Tests cover 16-thread exactness, drain-and-reset deltas, zero suppression, the kill switch, fault injection, and the sampler output.
Instrument the static helper methods of Filters with the queryBuilders
counter. Each helper call counts one use. The instrumented methods are
the leaf methods: a method that constructs the filter product or calls
a private helper. The delegating overloads stay uninstrumented. This
rule makes one helper call count exactly one use, also for a nested
expression such as and(eq("x", 1), lt("y", 3)).
Filters lives in driver-core and has no MongoClient reference. A
per-client store cannot bind to a Filters call. The POC therefore uses
the global static store. The findings file records the options for the
real design.
Instrument MongoCollectionImpl with the queryRaw counter. A query method counts one raw use when the caller passes a Document or a BsonDocument filter. The check is one instanceof pair at the entry. The method does not walk the document. A hand-built document counts as raw. The counter measures the paradigm, not the correctness. The no-filter overloads of find, countDocuments, and distinct now call the private helpers directly. A synthetic empty filter must not count as a raw query. Update-side methods stay out of scope. The Product question covers query construction only. Instrument the private bulkWrite choke of MongoCollectionImpl with the bulkWriteCollection counter. Instrument the private bulkWrite choke of MongoClusterImpl with the bulkWriteClient counter. Instrument initializeOrderedBulkOperation and initializeUnorderedBulkOperation of DBCollection with the bulkWriteLegacy counter. Tests use TestOperationExecutor, so they need no server. One test uses a lazy client: the initialize methods build the bulk operation without server access.
Add InstrumentationPocDemo in driver-legacy. The legacy module sees driver-core, driver-sync, and the legacy API, so one demo covers every counter. The demo.md plan asks for a demo in driver-core, but driver-core cannot see the sync and legacy call sites. The findings file records this deviation. The demo sets the interval property before the store initializes. The sampler then starts at the configured interval. The demo offsets the round grid by a quarter of the sample interval. Each sample window then holds exactly four rounds, and the deltas match the workload plan exactly. The Gradle task telemetryPocDemo runs the demo with one command. The task forwards the mongodb.telemetryPoc system properties. The operator proves the kill switch with -Dmongodb.telemetryPoc.enabled=false: the demo prints no lines, and the operations still succeed.
The first design counted construction calls in the Filters statics. Review found two defects. First, a combinator around raw documents, for example nor(rawDocument, rawDocument), counted as builder although the content was raw. Second, empty() and where() return a plain BsonDocument, so a query with them counted as builder and raw. The corrected design counts the nodes at the render. The toBsonDocument methods of the Filters leaf classes increment queryBuilders once per builder node. The combinator loops check each child class before the child renders: a Document or a BsonDocument child increments queryRaw. A combinator does not count itself. The classification measures the content, not the wrapper. The design uses no gate. A customer render outside a query execution counts too. The design accepts this noise. A raw root never passes through a Filters class. The entry check in MongoCollectionImpl keeps the raw root. It reads the filter object at the call, so the lazy iterable of find is not a problem. empty() and where() classify as raw through the entry check. The counter measures executions. A retried query renders again and counts again. The demo output is unchanged: the demo queries are single-node.
The only instrumentation for query construction now lives inside the Filters classes. Each inner class counts itself once in its toBsonDocument method: queryBuilders. The combinator loops check each child before the child renders: a Document or a BsonDocument child increments queryRaw. NotFilter and the elemMatch wrapper render one child each. They follow the same rule. The design removes the entry check from MongoCollectionImpl. No entry checks, no render context, no thread-local. The no-filter overload bypass reverts with it: the overloads delegate again as upstream. Known consequence, accepted: a raw root filter never enters a Filters class and counts nothing. For example find(new Document(...)) gives no count. empty() and where() return a plain BsonDocument, so they count nothing too. queryRaw measures raw nodes inside builder-wrapped trees. Full raw-root coverage needs the MongoCollectionImpl entry check. The spec discussion decides whether to add it. A retried query renders again and counts again. The counter measures executions. The demo output shows the consequence: the demo raw queries are raw roots, so their lines carry no queryRaw key.
vbabanin
force-pushed
the
instrumentation-poc
branch
from
December 5, 2026 03:06
83a4a97 to
df607e5
Compare
Filters.where and Filters.empty returned a plain BsonDocument. They never entered a Filters class, so they counted nothing at render. Both now return an anonymous Bson wrapper, the same pattern as elemMatch. The wrapper implements Bson directly, never BsonDocument. Its toBsonDocument increments queryBuilders and builds the same document as before. The public return type stays Bson, so the change keeps source and binary compatibility. The wrapper never fires the combinator child check, so no method double-counts. Every Filters static method now bumps the counter at render. where and empty count as builder usage: they are typed-API invocations. A plain raw root still counts nothing. The known consequence stands. Tests: where and empty through find count queryBuilders 1 and queryRaw 0 on execution. and(where(...), eq(...)) counts queryBuilders 3: the where wrapper, the eq leaf, and the and shell.
- Adds MongoDriverInformation.register(label) returning the public FeatureHandle interface as the entire public label surface; the store keeps only a handle set, register is the only writer, and used() is one volatile read on the handle - Latches driver-internal labels at first real use: gridfs at the first bucket operation, changeStreams at the watch choke points, csfle at the explicit encrypt entries, convTxn/coreTxn at invocation; registration alone never counts - Extends the sampler line with the deduplicated, sorted feature list and extends the demo with transaction rounds and a GridFS upload JAVA-6904
vbabanin
force-pushed
the
instrumentation-poc
branch
from
December 5, 2026 04:40
af32ab7 to
723d734
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Instrumentation POC: API-usage counters and feature labels
Branch:
instrumentation-poc. Local proof of concept only. Do not push.The concept
The driver counts how its API surface is used, and it reports which features are in use.
Two signals exist:
queryBuilders,queryRaw,bulkWriteClient,bulkWriteCollection,bulkWriteLegacy.gridfs,changeStreams,csfle,convTxn,coreTxn. A label latches at the first real use and then reports on everywindow.
The sampler drains the counters and prints one JSON line. The line imitates a delivery
channel. This POC does not touch SDAM, the wire protocol, or the server. The deliverable
is feasibility: can we instrument the surface, and what does the mechanism cost?
{"driver":"java","ts":"2026-12-04T10:00:02Z","intervalMs":2000, "apiUsage":{"queryBuilders":12,"queryRaw":8,"bulkWriteCollection":4}, "features":["convTxn","coreTxn","gridfs"]}The public API: one method
The entire public telemetry surface is one method on the existing public class:
MongoDriverInformation.register(label)returns aFeatureHandlewith one method,used(). A framework registers a label once, keeps the handle, and callsused()atits execution sites. Nothing else is public. There is no label enum, no latch array, no
registration event.
Example for an external library or framework:
The sampler emits a latched label in every window, resend-always. Counters answer "how
much", labels answer "which features are present".
Why the overhead is low
LongAdder.increment(). Under contention the LongAdderstripes across cells, so hot counters stay flat. No allocation on the hot path.
used()steady state: one volatile read on the handle's ownAtomicBoolean. Thehandle never touches the store, the set, or any map on a use path.
register. It runs once per label, cold. The samplerreads the set on its interval. Use paths never write.
sumThenReset()on each counter, prints one line, and sleeps. An idle intervalprints nothing. The kill switch (
mongodb.telemetryPoc.enabled=false) turns thewhole mechanism into a no-op, and operations still succeed.
The performance measurements are out of POC scope and are skipped. The analysis above is
theoretical and is marked "unverified" in the findings.
How the driver is instrumented
The driver uses the same public path as any framework. The label handles are private
static fields in the classes that own the features. There is no internal holder class.
gridfschangeStreamswatch()call (database, collection, cluster)csfleencryptcallconvTxnwithTransactionentrycoreTxnstartTransactionentry (without the wrapper)Example, from
GridFSBucketImpl:The counter registry
Each counter has one meaning and one count altitude. All counters are deltas per
window.
queryBuildersFiltersclasstoBsonDocumentqueryRawDocument/BsonDocumentnodes inside a builder treebulkWriteClientbulkWritecallsbulkWriteCollectionMongoCollection.bulkWritecallsbulkWriteLegacyDocumented semantics: a retried query renders twice and counts twice, because the
counter measures executions.
Filters.where()andFilters.empty()count asqueryBuilders: they are typed-API invocations. A fully raw root filter counts nothing,because it never enters a
Filtersclass.Query construction counts at render time, not at construction time. Each
Filtersimplementation increments
queryBuildersonce in itstoBsonDocument, because that isthe point where the driver renders the customer filter into the command. A combinator
checks each child before the render call: a raw
DocumentorBsonDocumentchildincrements
queryRaw. This classifies provenance per rendered node. Known consequence,accepted: a fully raw root filter counts nothing, because it never enters a
Filtersclass.
Bulk writes count at the three tiers: cluster-level
bulkWrite(bulkWriteClient),MongoCollection.bulkWrite(bulkWriteCollection), and the legacy ordered andunordered builders in driver-legacy (
bulkWriteLegacy).How it is implemented, in short
One increment path and one drain path. The customer thread only increments. The sampler
thread only drains.
flowchart LR subgraph "customer thread" A["API call: Filters.eq / bulkWrite / used()"] --> B{"counter or label?"} B -->|counter| C["LongAdder.increment()"] B -->|label| D["AtomicBoolean set to true, once"] end subgraph "sampler daemon thread" E["wake on interval"] --> F["sumThenReset() on every LongAdder"] F --> G["read every latched handle"] C -.-> F D -.-> G G --> H["print one JSON line to System.out"] endLongAdderin a fixed-size array, indexed by an internal enum. Theincrement is one striped add. Nothing else on this path.
FeatureHandlewith oneAtomicBoolean. The firstused()flips it.Later calls read it and return.
register()is the only writer, once per label.The sampler reads it, never the use paths.
The sampler as a stand-in delivery channel
A daemon
ScheduledExecutorServicewakes on the configured interval(
mongodb.telemetryPoc.intervalMs, default one hour). It drains every counter withsumThenReset(), so each line is the delta of its own window. It collects the labels ofall latched handles, dedups and sorts them, and prints one JSON line to
System.out.Zero suppression applies: a 0-delta counter is omitted, and an empty window prints no
line. The POC stops at the console line. Real delivery is out of scope.
Testing
gridfs.convTxn-only,coreTxn-only, and nested cases follow the table above.MongoCollectionSpecificationsuite (911 tests) is green../gradlew :driver-legacy:telemetryPocDemoagainst a local mongod prints oneline per 2-second interval with deltas and the sorted feature list.