Skip to content

metricbeat/module/mongodb/collstats: add $collStats aggregation support with fallback - #48638

Merged
shmsr merged 55 commits into
elastic:mainfrom
shmsr:update-collstats-mongo
Jun 23, 2026
Merged

shmsr merged 55 commits into
elastic:mainfrom
shmsr:update-collstats-mongo

Conversation

@shmsr

@shmsr shmsr commented Feb 1, 2026 •

Copy link
Copy Markdown
Member

This PR is a recreation of #46681. The original PR was automatically closed by GitHub when I deleted my fork (shmsr/beats) and created a new one. Since GitHub cannot reopen PRs from deleted forks (the source branch no longer exists), this new PR was created with the same commits and content. All previous review discussions and context are preserved in #46681 for reference.

Proposed commit message

Replaces the deprecated collstats command with the recommended aggregate pipeline using the $collStats stage. The collstats command was deprecated in MongoDB 6.2, and this change ensures compatibility with current and future MongoDB versions while providing enhanced collection statistics. Now it transparently uses either the deprecated collStats database command (legacy) or the $collStats aggregation stage (MongoDB 6.2+) depending on server version and feature availability to collect collection-level operational and storage statistics from MongoDB.

The new approach provides additional metrics that were not available in the old command. A few of them have been enabled, while the rest are currently disabled, pending further development to add them when a need arises.

Implementation wise, these are the following things added:

  • Version detection: Added MongoDB version detection via buildInfo command
  • Smart routing: Implemented version-aware method selection:
    • MongoDB 6.2+: Uses $collStats aggregation with fallback to legacy command
    • MongoDB <6.2: Uses legacy collStats command
  • Aggregation pipeline
    • Constructs $collStats pipeline with storageStats and count options
    • Handles scale parameter correctly
    • Supports sharded collections with result merging
  • Result flattening: Flattens nested storageStats to maintain compatibility with existing event mapping
  • Sharded collection support: Merges statistics from multiple shards with proper aggregation logic

References

Note: This is a recreation of #46681 after fork recreation.

Checklist

  • My code follows the style guidelines of this project
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • I have made corresponding change to the default configuration files
  • I have added tests that prove my fix is effective or that my feature works
  • I have added an entry in CHANGELOG.next.asciidoc or CHANGELOG-developer.next.asciidoc.

Testing

Comprehensive testing performed across the MongoDB 6.2 deprecation boundary:

✅ MongoDB 5.0 (Pre-deprecation)

  • Backward compatibility verified
  • All core statistics captured correctly
  • New fields added (because of changed fields.yml)
  • No breaking changes to existing metrics

✅ MongoDB 7.0 (Post-deprecation)

  • Forward compatibility verified
  • Version-specific field numOrphanDocs correctly captured
  • Enhanced metrics all present
  • New fields correctly populated
  • Aggregation pipeline works as expected

✅ Cross-version Validation

  • Consistent behavior across MongoDB versions
  • Version-aware field handling (e.g., numOrphanDocs only in 6.0+)
  • Smart fallback mechanism tested
  • Sharded collection merging logic validated

Even scripts for future testing added — standalone, replica set and sharded setups. The same standalone setup is being used by the newly written integration tests that has tests against both 5.0 and 7.0.

Related issues

shmsr and others added 30 commits September 22, 2025 14:19
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
Co-authored-by: Colleen McGinnis <colleen.j.mcginnis@gmail.com>
@github-actions

This comment has been minimized.

shmsr added 3 commits June 10, 2026 14:32
Use NotEmpty for empty-string checks and InDelta for float assertions so the
collstats test suite passes the current lint configuration.
…move incorrect breaking-change notes

- Fix mongoVersion caching bug: failures are no longer cached as "unknown";
  the next Fetch retries version detection, so transient errors (MongoDB not
  yet ready) and live server upgrades are handled automatically.
- Fix isVersionAtLeast for major-only version strings (e.g. "6"): missing
  minor/patch parts are now treated as 0 instead of causing an early
  loop exit that incorrectly returned true.
- Guard against empty version string returned by versionGetter with no error.
- Extract cacheMongoVersion as a testable method; inject versionGetter via
  Metricset field for unit testing without a real MongoDB connection.
- Add unit tests: retry-on-error, empty-string-not-cached,
  permanent-failure-uses-legacy-path, major-only and major.minor version
  boundary cases for isVersionAtLeast.
- Extend standalone integration tests to cover MongoDB 4.4, 6.0, and 8.0
  in addition to 5.0 and 7.0, straddling the 6.2.0 aggregation boundary.
- Fix standalone docker-compose healthcheck to support MongoDB 4.4 which
  ships only the old mongo shell (mongosh || mongo fallback).
- Remove incorrect "In versions before 9.2.0" backward-compat notes from
  fields.yml and exported-fields-mongodb.md: git history confirms the field
  paths (mongodb.collstats.stats.*) were never changed by this PR; the
  stats.stats.* double-nesting never existed in production.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@shmsr

shmsr commented Jun 10, 2026

Copy link
Copy Markdown
Member Author

Analysis: How the incorrect stats.stats field names ended up in the docs

During the doc-update phase of this PR, I introduced backward-compatibility notes to the _meta/fields.yml fields that were moved/reorganised under the stats group. The notes read:

In versions before 9.2.0, this field is called `mongodb.collstats.stats.stats.SIZE`.

Those notes were wrong, and here is exactly why.

Root cause — a mental model slip during docs editing

The new fields (freeStorageSize, capped, scaleFactor, etc.) are declared under the YAML group stats in fields.yml:

```yaml

  • name: stats
    type: group
    fields:
    • name: freeStorageSize # → emitted as mongodb.collstats.stats.freeStorageSize
    • name: capped # → emitted as mongodb.collstats.stats.capped
      ...
      ```

When writing the backward-compat note, I mentally stitched together "the group is called stats" + "the legacy path starts with mongodb.collstats.stats.*" and wrote stats.stats.SIZE — doubling the stats segment.

What the actual emitted path has always been

Tracing back to PR #42171 (commit 0b5cfa9c76), the Go code maps the collStats command result directly into the event under a single "stats" key:

```go
event.MetricSetFields = mapstr.M{
"stats": mapstr.M{
"size": stats.Size,
"count": stats.Count,
"totalIndexSize": stats.TotalIndexSize,
// ...
},
}
```

That produces mongodb.collstats.stats.size, mongodb.collstats.stats.totalIndexSize, etc. — one stats level, never two.

How the error propagated

The notes were added one field at a time across 8 consecutive commits (c475e50a09 → 87f060f549), each time copy-pasting the same incorrect prefix. All 8 fields ended up with the same wrong stats.stats.* path. There was no underlying code change that justified those notes — it was a documentation error from start to finish.

Fix

Commit 860c239bee removed all 8 incorrect notes from both _meta/fields.yml and the rendered docs/reference/metricbeat/exported-fields-mongodb.md. No field names have changed; there is nothing to warn users about for these fields.

@github-actions

Copy link
Copy Markdown
Contributor

TL;DR

Metricbeat: Run check/update failed because make -C metricbeat check update leaves tracked files modified, so check-no-changes exits non-zero. Commit the generated update output for MongoDB metricbeat files.

Remediation

  • Run make -C metricbeat update (or cd metricbeat && mage update) and commit all resulting changes, including:
    • metricbeat/module/mongodb/collstats/collstats.go
    • metricbeat/module/mongodb/fields.go
  • Re-run make -C metricbeat check update and ensure make check-no-changes reports no modified files.
Investigation details

Root Cause

This is a configuration/generated-artifacts drift failure: CI ran the update/check pipeline and detected uncommitted generated changes. The failing step explicitly reports generated drift in:

  • metricbeat/module/mongodb/collstats/collstats.go
  • metricbeat/module/mongodb/fields.go

metricbeat/module/mongodb/fields.go:18 contains:
// Code generated by beats/dev-tools/cmd/asset/asset.go - DO NOT EDIT.

That confirms at least one failing file is generated output and must be refreshed/committed with source changes.

Evidence

Error: some files are not up-to-date. Run 'make update' then review and commit the changes. Modified: [metricbeat/module/mongodb/collstats/collstats.go metricbeat/module/mongodb/fields.go]
make: *** [../dev-tools/make/mage.mk:21: check] Error 1

Verification

  • Not run end-to-end in this environment (local make -C metricbeat update could not complete reliably due toolchain/bootstrap constraints), but the Buildkite failure output is definitive and names the exact files that require regeneration/commit.

Follow-up

If the files were already committed in a newer push, retrying the Buildkite pipeline should pass this step.

Note

🔒 Integrity filter blocked 2 items

The following items were blocked because they don't meet the GitHub integrity level.

To allow these resources, lower min-integrity in your GitHub frontmatter:

tools:
  github:
    min-integrity: approved  # merged | approved | unapproved | none

What is this? | From workflow: PR Buildkite Detective

Give us feedback! React with 🚀 if perfect, 👍 if helpful, 👎 if not.

…sset

- Fix goimports struct-field comment alignment in collstats.go
- Replace assert.Equal(t, "", ...) with assert.Empty(t, ...) per testifylint
- Regenerate metricbeat/module/mongodb/fields.go after fields.yml cleanup

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

@stefans-elastic stefans-elastic left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

shmsr and others added 2 commits June 11, 2026 20:10
…rious shardCount on standalone

Two bugs surfaced while exercising the metricset against live MongoDB
across the 6.2 deprecation boundary (standalone 4.4-8.0 and sharded
5.0/7.0):

1. scale broke the legacy collStats command path (MongoDB < 6.2).
   fetchCollStatsCommand built the command as an unordered bson.M and,
   when scale != 1, added a second key. The MongoDB driver requires the
   command name to be the first BSON field and rejects multi-key
   unordered maps ("multi-key map passed in for ordered parameter cmd"),
   so every collection errored and zero events were emitted. Switch to
   an ordered bson.D. The aggregation path (6.2+) was unaffected because
   it already builds an ordered pipeline.

2. Standalone deployments on 6.2+ emitted a spurious stats.shardCount=1.
   hasShardMetadata treated the top-level "host" field as a sharding
   signal, but $collStats always emits "host" (the serving node), even
   on standalone/replica set. This routed every standalone aggregation
   result through the sharded-merge path. Key off "shard" only, so
   standalone matches the legacy path while genuine sharded collections
   still report their shard count.

Both gaps escaped CI because no test set a non-default scale and no
assertion checked shardCount on standalone. Add regression coverage:
a scaled fetch in TestFetchStandaloneVersions across the full version
matrix, a standalone "must not report shardCount" assertion, and an
updated TestHasShardMetadata case for the host-only result.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@shmsr
shmsr enabled auto-merge (squash) June 11, 2026 15:14
@shmsr

shmsr commented Jun 12, 2026

Copy link
Copy Markdown
Member Author

@jmikell821 could you please review and approve; thank you!

@shmsr
shmsr requested a review from jmikell821 June 12, 2026 09:46

@jmikell821 jmikell821 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Everything LGTM!

@shmsr
shmsr merged commit e45acca into elastic:main Jun 23, 2026
44 of 45 checks passed
@shmsr shmsr added the backport-active-all Automated backport with mergify to all the active branches label Jun 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

@Mergifyio backport 9.4 9.3 8.19

@mergify

mergify Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

backport 9.4 9.3 8.19

✅ Backports have been created

Details

Cherry-pick of e45acca has failed:

On branch mergify/bp/8.19/pr-48638
Your branch is up to date with 'origin/8.19'.

You are currently cherry-picking commit e45acca9f.
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --skip" to skip this patch)
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Changes to be committed:
	new file:   changelog/fragments/1781012000-metricbeat-mongodb-collstats-aggregation.yaml
	modified:   metricbeat/module/mongodb/collstats/_meta/data.json
	modified:   metricbeat/module/mongodb/collstats/_meta/fields.yml
	modified:   metricbeat/module/mongodb/collstats/collstats.go
	modified:   metricbeat/module/mongodb/collstats/collstats_integration_test.go
	new file:   metricbeat/module/mongodb/collstats/collstats_test.go
	modified:   metricbeat/module/mongodb/collstats/data.go
	modified:   metricbeat/module/mongodb/collstats/data_test.go
	new file:   metricbeat/module/mongodb/collstats/testing/mongodb/README.md
	new file:   metricbeat/module/mongodb/collstats/testing/mongodb/replica_set/docker-compose.yml
	new file:   metricbeat/module/mongodb/collstats/testing/mongodb/replica_set/init-replica-set.sh
	new file:   metricbeat/module/mongodb/collstats/testing/mongodb/sharded/docker-compose.yml
	new file:   metricbeat/module/mongodb/collstats/testing/mongodb/sharded/init-sharded-cluster.sh
	new file:   metricbeat/module/mongodb/collstats/testing/mongodb/sharded/verify-sharding.sh
	new file:   metricbeat/module/mongodb/collstats/testing/mongodb/standalone/docker-compose.yml
	new file:   metricbeat/module/mongodb/collstats/testing/mongodb/standalone/seed-standalone.sh
	modified:   metricbeat/module/mongodb/fields.go

Unmerged paths:
  (use "git add/rm <file>..." as appropriate to mark resolution)
	deleted by us:   docs/reference/metricbeat/exported-fields-mongodb.md
	deleted by us:   docs/reference/metricbeat/metricbeat-metricset-mongodb-collstats.md
	deleted by us:   metricbeat/module/mongodb/collstats/_meta/docs.md

To fix up this pull request, you can check it out locally. See documentation: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/checking-out-pull-requests-locally

shmsr pushed a commit that referenced this pull request Jun 24, 2026
shmsr added a commit that referenced this pull request Jun 25, 2026
…rt with fallback (#48638) (#51469)

(cherry picked from commit e45acca)

Co-authored-by: subham sarkar <subham.sarkar@elastic.co>
shmsr added a commit that referenced this pull request Jun 25, 2026
…rt with fallback (#48638) (#51468)

(cherry picked from commit e45acca)

Co-authored-by: subham sarkar <subham.sarkar@elastic.co>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-active-all Automated backport with mergify to all the active branches Team:Obs-InfraObs Label for the Observability Infrastructure Monitoring team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

metricbeat/module/mongodb: Use $collStats from aggregate stage instead of collStats directly for Mongo 6.2+

4 participants