Skip to content

Add the telemetry POC counter store, registry, and sampler - #2118

Draft
vbabanin wants to merge 8 commits into
mongodb:mainfrom
vbabanin:instrumentation-poc
Draft

vbabanin wants to merge 8 commits into
mongodb:mainfrom
vbabanin:instrumentation-poc

Conversation

@vbabanin

@vbabanin vbabanin commented Dec 5, 2026 •

Copy link
Copy Markdown
Member

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:

  1. API-usage counters. Integer deltas for query construction and bulk-write tiers:
    queryBuilders, queryRaw, bulkWriteClient, bulkWriteCollection,
    bulkWriteLegacy.
  2. Feature labels. Boolean, latch-once signals: gridfs, changeStreams, csfle,
    convTxn, coreTxn. A label latches at the first real use and then reports on every
    window.

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:

public FeatureHandle register(String label)

MongoDriverInformation.register(label) returns a FeatureHandle with one method,
used(). A framework registers a label once, keeps the handle, and calls used() at
its execution sites. Nothing else is public. There is no label enum, no latch array, no
registration event.

Example for an external library or framework:

// At framework startup: register once, keep the handle.
FeatureHandle bulkHint = driverInformation.register("myFramework.bulkHint");

// At the execution site: report use. The first call latches.
// Every later call is one volatile read that changes nothing.
bulkHint.used();

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

  • Counter increment: one LongAdder.increment(). Under contention the LongAdder
    stripes across cells, so hot counters stay flat. No allocation on the hot path.
  • used() steady state: one volatile read on the handle's own AtomicBoolean. The
    handle never touches the store, the set, or any map on a use path.
  • The handle set has one writer: register. It runs once per label, cold. The sampler
    reads the set on its interval. Use paths never write.
  • The sampler runs on a daemon thread. It never runs on a customer call path. It calls
    sumThenReset() on each counter, prints one line, and sleeps. An idle interval
    prints nothing. The kill switch (mongodb.telemetryPoc.enabled=false) turns the
    whole mechanism into a no-op, and operations still succeed.
  • Instrumentation never throws. A broken counter cannot break the instrumented API.

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.

Label Latch site Never latches at
gridfs first bucket operation (upload, download, find) bucket creation
changeStreams any watch() call (database, collection, cluster) -
csfle first explicit encrypt call automatic encryption (config, not a label)
convTxn withTransaction entry -
coreTxn public startTransaction entry (without the wrapper) the wrapper's private overload

Example, from GridFSBucketImpl:

private static final FeatureHandle GRIDFS_FEATURE =
    MongoDriverInformation.builder().build().register("gridfs");

// At each bucket-operation choke point:
GRIDFS_FEATURE.used();

The counter registry

Each counter has one meaning and one count altitude. All counters are deltas per
window.

Counter Counts Counted at Unit
queryBuilders filter nodes built with the typed builder API render time, in each Filters class toBsonDocument one per rendered builder node
queryRaw raw Document / BsonDocument nodes inside a builder tree render time, in the combinator child check one per rendered raw node
bulkWriteClient cluster-level bulkWrite calls the client bulk-write entry one per executed call
bulkWriteCollection MongoCollection.bulkWrite calls the collection bulk-write entry one per executed call
bulkWriteLegacy legacy ordered and unordered bulk builders the legacy builder execute in driver-legacy one per executed batch

Documented semantics: a retried query renders twice and counts twice, because the
counter measures executions. Filters.where() and Filters.empty() count as
queryBuilders: they are typed-API invocations. A fully raw root filter counts nothing,
because it never enters a Filters class.

Query construction counts at render time, not at construction time. Each Filters
implementation increments queryBuilders once in its toBsonDocument, because that is
the point where the driver renders the customer filter into the command. A combinator
checks each child before the render call: a raw Document or BsonDocument child
increments queryRaw. This classifies provenance per rendered node. Known consequence,
accepted: a fully raw root filter counts nothing, because it never enters a Filters
class.

Bulk writes count at the three tiers: cluster-level bulkWrite (bulkWriteClient),
MongoCollection.bulkWrite (bulkWriteCollection), and the legacy ordered and
unordered 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"]
    end
Loading
  • A counter is a LongAdder in a fixed-size array, indexed by an internal enum. The
    increment is one striped add. Nothing else on this path.
  • A label is a FeatureHandle with one AtomicBoolean. The first used() flips it.
    Later calls read it and return.
  • The handle set lives in the store. register() is the only writer, once per label.
    The sampler reads it, never the use paths.
  • The sampler collects the two results into one JSON line and prints it. Then it sleeps.

The sampler as a stand-in delivery channel

A daemon ScheduledExecutorService wakes on the configured interval
(mongodb.telemetryPoc.intervalMs, default one hour). It drains every counter with
sumThenReset(), so each line is the delta of its own window. It collects the labels of
all 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

  • Unit: exact deltas, drain-and-reset, zero suppression, kill-switch no-op.
  • Concurrency: 16 threads on one counter and on one handle produce exact totals.
  • Labels: bucket creation latches nothing; the first bucket operation latches gridfs.
    convTxn-only, coreTxn-only, and nested cases follow the table above.
  • Regression: the full MongoCollectionSpecification suite (911 tests) is green.
  • Demo: ./gradlew :driver-legacy:telemetryPocDemo against a local mongod prints one
    line per 2-second interval with deltas and the sorted feature list.

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
vbabanin force-pushed the instrumentation-poc branch from 83a4a97 to df607e5 Compare December 5, 2026 03:06
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
vbabanin force-pushed the instrumentation-poc branch from af32ab7 to 723d734 Compare December 5, 2026 04:40

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant