mdbkit 0.8.0__tar.gz → 0.8.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. {mdbkit-0.8.0 → mdbkit-0.8.1}/PKG-INFO +51 -11
  2. {mdbkit-0.8.0 → mdbkit-0.8.1}/README.md +50 -10
  3. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/__init__.py +1 -1
  4. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/analysis.py +25 -0
  5. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/cli.py +51 -14
  6. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/filtering.py +27 -0
  7. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/rebuild.py +26 -1
  8. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/render.py +39 -11
  9. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/sharding.py +16 -3
  10. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit.egg-info/PKG-INFO +51 -11
  11. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit.egg-info/SOURCES.txt +1 -0
  12. {mdbkit-0.8.0 → mdbkit-0.8.1}/pyproject.toml +1 -1
  13. mdbkit-0.8.1/tests/test_query_hash.py +144 -0
  14. {mdbkit-0.8.0 → mdbkit-0.8.1}/LICENSE +0 -0
  15. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/advisor.py +0 -0
  16. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/audit.py +0 -0
  17. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/compare.py +0 -0
  18. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/demo.py +0 -0
  19. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/explain.py +0 -0
  20. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/ftdc.py +0 -0
  21. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/host.py +0 -0
  22. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/indexusage.py +0 -0
  23. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/lab.py +0 -0
  24. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/oslog.py +0 -0
  25. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/parser.py +0 -0
  26. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/report.py +0 -0
  27. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/scripts.py +0 -0
  28. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/serverstatus.py +0 -0
  29. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/shelljson.py +0 -0
  30. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit/triage.py +0 -0
  31. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit.egg-info/dependency_links.txt +0 -0
  32. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit.egg-info/entry_points.txt +0 -0
  33. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit.egg-info/requires.txt +0 -0
  34. {mdbkit-0.8.0 → mdbkit-0.8.1}/mdbkit.egg-info/top_level.txt +0 -0
  35. {mdbkit-0.8.0 → mdbkit-0.8.1}/setup.cfg +0 -0
  36. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_demo_lab.py +0 -0
  37. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_explain.py +0 -0
  38. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_ftdc.py +0 -0
  39. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_host.py +0 -0
  40. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_indexes.py +0 -0
  41. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_mdbkit.py +0 -0
  42. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_oslog_serverstatus.py +0 -0
  43. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_real_failures.py +0 -0
  44. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_real_servers.py +0 -0
  45. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_rebuild_report.py +0 -0
  46. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_render_e2e.py +0 -0
  47. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_sharded.py +0 -0
  48. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_triage.py +0 -0
  49. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_v060_hardening.py +0 -0
  50. {mdbkit-0.8.0 → mdbkit-0.8.1}/tests/test_v080.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mdbkit
3
- Version: 0.8.0
3
+ Version: 0.8.1
4
4
  Summary: Offline toolkit for MongoDB 4.4 to 9.0 logs and diagnostics: slow-query shapes, index advice and index usage, incident triage, sharded clusters, multi-instance hosts, startup configuration audit, FTDC decoding. A spiritual successor to mtools' log tools.
5
5
  Author: Saqib Ameen Subhan
6
6
  License: MIT
@@ -47,7 +47,8 @@ triage, sharded clusters, hosts running many mongods, a startup
47
47
  configuration audit, and diagnostic-data (FTDC) decoding. For MongoDB 4.4
48
48
  through 9.0, from the terminal, without connecting to anything.
49
49
  **[Tested against real MongoDB 9.0.2, 8.3.11, 8.0.32, 7.0.43 and 6.0.29](#compatibility)**
50
- — replica sets, standalones and sharded clusters (October 2026).
50
+ — replica sets, standalones and sharded clusters (October 2026) — and
51
+ re-checked on 9.0.8, 8.3.17, 8.0.38 and 7.0.48 (December 2026).
51
52
 
52
53
  A spiritual successor to mtools' log tools, which never learned to read the
53
54
  JSON log format introduced in 4.4.
@@ -279,7 +280,15 @@ updates — upgrades are always explicit.
279
280
  **Tested against (October 2026):** MongoDB **9.0.2**, **8.3.11**, **8.0.32**
280
281
  (LTS), **7.0.43** (LTS) and **6.0.29**, the newest release in each series at
281
282
  the time: replica sets and standalones on all five, and sharded clusters
282
- (mongos, shards and config servers) on 6.0, 7.0, 8.0 and 9.0. mdbkit reads the structured JSON log format, so anything
283
+ (mongos, shards and config servers) on 6.0, 7.0, 8.0 and 9.0.
284
+
285
+ **Re-checked (December 2026)** on the newest patches, **9.0.8**, **8.3.17**,
286
+ **8.0.38** and **7.0.48**: each was run as a replica set (seeded, its primary
287
+ killed and restarted, stepped down) and every command was run on the result;
288
+ 9.0.8 and 8.0.38 also as a sharded cluster. None of these patches changed a
289
+ log field, message or metric that mdbkit reads.
290
+
291
+ mdbkit reads the structured JSON log format, so anything
283
292
  from **4.4** onwards works; 4.2 and earlier wrote plain text logs and are not
284
293
  supported.
285
294
 
@@ -679,6 +688,7 @@ query with different parameters is counted once.
679
688
  | `--min-ms N` | 0 | Ignore operations faster than N milliseconds |
680
689
  | `--include-system` | off | Include internal `admin`/`config`/`local` namespaces (hidden by default — they are server housekeeping, not your workload) |
681
690
  | `--report FILE` | | Write a shareable `.md` or `.html` report instead (see [Shareable reports](#shareable-reports----report-file)) |
691
+ | `--shape N` or `--shape HASH` | | Full detail on one shape: row N of the table, or the shape with this `queryHash`, `planCacheShapeHash`, `planCacheKey` or `queryShapeHash` |
682
692
  | `--json` | | Machine-readable output |
683
693
 
684
694
  **Reading the columns:**
@@ -690,6 +700,7 @@ query with different parameters is counted once.
690
700
  | `docsEx` | Documents examined, summed across all occurrences |
691
701
  | `scan` | Documents examined per document returned. `1:1` is ideal; `3444:1` means a missing or weak index |
692
702
  | `plan` | The plan MongoDB chose: `COLLSCAN` (no index), `IXSCAN{fields}` (index used), `IDHACK` (`_id` lookup), `+SORT` (in-memory sort), `+SPILL` (wrote temporary files to disk). `?` = the plan was not recorded on that line |
703
+ | `queryHash` | MongoDB's own identifier for the shape, from the log (called `planCacheShapeHash` from 8.0, which logs both names). `+N` = mongod gave this shape N more. `-` = the log lines carry none (inserts, some updates, and 8.0+ `EXPRESS` lookups, which skip the planner) |
693
704
  | `shape` | Fields and operators queried, with the sort |
694
705
 
695
706
  Two kinds of row are worth knowing about. A `getMore(find)` or
@@ -713,6 +724,7 @@ mdbkit queries mongod.log --sort scanRatio --limit 10
713
724
  mdbkit queries mongod.log --min-ms 500 --json
714
725
  mdbkit queries "mongod.log*" # rotated logs as one stream
715
726
  mdbkit queries mongod.log --shape 1 # drill into the worst offender
727
+ mdbkit queries mongod.log --shape 0F877C7D # the same, by its queryHash
716
728
  ```
717
729
 
718
730
  `--shape N` expands one row of the table. On an 8.0+ log it also shows where
@@ -746,17 +758,37 @@ resources
746
758
  disk spills : 159 (13.6 GiB written)
747
759
  CPU time : 5.5m total
748
760
 
749
- server identifiers
761
+ server identifiers (find this shape's log lines, plan cache entry or query settings)
762
+ queryHash : 0F877C7D
763
+ (named planCacheShapeHash from 8.0, which logs both)
764
+ planCacheKey : 8F21BC04
750
765
  queryShapeHash : BDC6B796B132EBAF671210F40FC5155C05ED250F79996E68DC6C620CBD8972AE
751
- pin or block this shape without a code change (8.0+):
752
- db.adminCommand({setQuerySettings: "BDC6...72AE", settings: {...}})
753
- planCacheShapeHash : 0F877C7D (queryHash before 8.0)
766
+ the full log lines : mdbkit filter <log> --query-hash 0F877C7D --last 5
767
+ as runnable explain: mdbkit filter <log> --query-hash 0F877C7D --last 1 --as-explain
768
+ plan cache entry : db.getSiblingDB("shop").getCollection("events").aggregate([{$planCacheStats: {}}, {$match: {queryHash: "0F877C7D"}}])
769
+ (run on the member that logged it; only queries that had more than one candidate plan are cached)
770
+ pin or block this shape without a code change (8.0+):
771
+ db.adminCommand({setQuerySettings: "BDC6B796...", settings: {...}})
754
772
  ```
755
773
 
756
- The `queryShapeHash` is the same value MongoDB shows in `explain`, the
757
- profiler, `$currentOp` and `$queryStats`, so you can follow one shape
758
- across all of them. mdbkit only prints the `setQuerySettings` command. It
759
- never runs it.
774
+ **From a shape back to the query.** The table groups thousands of log lines
775
+ into a few shapes; the hashes take you back to the lines themselves.
776
+ `queryHash` (8 characters) is in the slow-query lines of operations that
777
+ went through the query planner, on mongod and on mongos (checked on 6.0 to
778
+ 9.0); for a find, the mongos value matches the shards' (checked on 9.0). `filter --query-hash` prints those
779
+ lines, or rebuilds the latest as a runnable `explain`:
780
+
781
+ ```bash
782
+ mdbkit queries mongod.log # note the queryHash of the shape you want
783
+ mdbkit filter mongod.log --query-hash 0F877C7D --last 5 # its full log lines
784
+ mdbkit filter mongod.log --query-hash 0F877C7D --last 1 --as-explain
785
+ ```
786
+
787
+ The same `queryHash` finds the shape's plan cache entry (checked on real
788
+ 7.0 and 9.0 servers), and the 8.0+ `queryShapeHash` is the value MongoDB
789
+ shows in `explain`, the profiler, `$currentOp` and `$queryStats`, and that
790
+ `setQuerySettings` takes. mdbkit only prints those commands. It never runs
791
+ them.
760
792
 
761
793
  ---
762
794
 
@@ -811,6 +843,7 @@ it chains with other tools (including mdbkit itself).
811
843
  | `--to TIMESTAMP` | Upper time bound (inclusive) |
812
844
  | `--msg TEXT` | Substring match on the message field |
813
845
  | `--failed` | Only operations that ended in an error (logged with an `errName`) |
846
+ | `--query-hash HASH` | Only operations with this `queryHash`, `planCacheShapeHash`, `planCacheKey` or `queryShapeHash` (as `queries` shows them; case ignored, and a `queryShapeHash` may be shortened to its first 8+ characters) |
814
847
  | `--limit N` | Print only the **first** N matches |
815
848
  | `--last N` | Print only the **last** N matches — usually what you want during an incident |
816
849
  | `--as-explain` | Rebuild each matching slow query as a runnable `mongosh` `.explain()` command instead of printing the raw log line |
@@ -1562,6 +1595,13 @@ Linux box the database actually runs on.
1562
1595
  are still read, and misread log lines are still the most useful thing to
1563
1596
  send.
1564
1597
 
1598
+ **Shipped in v0.8.1:** the `queryHash` of each shape in the `queries`
1599
+ table, `queries --shape <hash>` and `filter --query-hash`, to go from a
1600
+ shape back to its full log lines
1601
+ ([#1](https://github.com/saqibameen86/mdbkit/issues/1)). Checked against
1602
+ MongoDB 9.0.8, 8.3.17, 8.0.38 and 7.0.48, the newest patches in December
1603
+ 2026.
1604
+
1565
1605
  **Shipped in v0.8:**
1566
1606
 
1567
1607
  * **Sharded clusters.** mongos logs show how many shards each query shape
@@ -11,7 +11,8 @@ triage, sharded clusters, hosts running many mongods, a startup
11
11
  configuration audit, and diagnostic-data (FTDC) decoding. For MongoDB 4.4
12
12
  through 9.0, from the terminal, without connecting to anything.
13
13
  **[Tested against real MongoDB 9.0.2, 8.3.11, 8.0.32, 7.0.43 and 6.0.29](#compatibility)**
14
- — replica sets, standalones and sharded clusters (October 2026).
14
+ — replica sets, standalones and sharded clusters (October 2026) — and
15
+ re-checked on 9.0.8, 8.3.17, 8.0.38 and 7.0.48 (December 2026).
15
16
 
16
17
  A spiritual successor to mtools' log tools, which never learned to read the
17
18
  JSON log format introduced in 4.4.
@@ -243,7 +244,15 @@ updates — upgrades are always explicit.
243
244
  **Tested against (October 2026):** MongoDB **9.0.2**, **8.3.11**, **8.0.32**
244
245
  (LTS), **7.0.43** (LTS) and **6.0.29**, the newest release in each series at
245
246
  the time: replica sets and standalones on all five, and sharded clusters
246
- (mongos, shards and config servers) on 6.0, 7.0, 8.0 and 9.0. mdbkit reads the structured JSON log format, so anything
247
+ (mongos, shards and config servers) on 6.0, 7.0, 8.0 and 9.0.
248
+
249
+ **Re-checked (December 2026)** on the newest patches, **9.0.8**, **8.3.17**,
250
+ **8.0.38** and **7.0.48**: each was run as a replica set (seeded, its primary
251
+ killed and restarted, stepped down) and every command was run on the result;
252
+ 9.0.8 and 8.0.38 also as a sharded cluster. None of these patches changed a
253
+ log field, message or metric that mdbkit reads.
254
+
255
+ mdbkit reads the structured JSON log format, so anything
247
256
  from **4.4** onwards works; 4.2 and earlier wrote plain text logs and are not
248
257
  supported.
249
258
 
@@ -643,6 +652,7 @@ query with different parameters is counted once.
643
652
  | `--min-ms N` | 0 | Ignore operations faster than N milliseconds |
644
653
  | `--include-system` | off | Include internal `admin`/`config`/`local` namespaces (hidden by default — they are server housekeeping, not your workload) |
645
654
  | `--report FILE` | | Write a shareable `.md` or `.html` report instead (see [Shareable reports](#shareable-reports----report-file)) |
655
+ | `--shape N` or `--shape HASH` | | Full detail on one shape: row N of the table, or the shape with this `queryHash`, `planCacheShapeHash`, `planCacheKey` or `queryShapeHash` |
646
656
  | `--json` | | Machine-readable output |
647
657
 
648
658
  **Reading the columns:**
@@ -654,6 +664,7 @@ query with different parameters is counted once.
654
664
  | `docsEx` | Documents examined, summed across all occurrences |
655
665
  | `scan` | Documents examined per document returned. `1:1` is ideal; `3444:1` means a missing or weak index |
656
666
  | `plan` | The plan MongoDB chose: `COLLSCAN` (no index), `IXSCAN{fields}` (index used), `IDHACK` (`_id` lookup), `+SORT` (in-memory sort), `+SPILL` (wrote temporary files to disk). `?` = the plan was not recorded on that line |
667
+ | `queryHash` | MongoDB's own identifier for the shape, from the log (called `planCacheShapeHash` from 8.0, which logs both names). `+N` = mongod gave this shape N more. `-` = the log lines carry none (inserts, some updates, and 8.0+ `EXPRESS` lookups, which skip the planner) |
657
668
  | `shape` | Fields and operators queried, with the sort |
658
669
 
659
670
  Two kinds of row are worth knowing about. A `getMore(find)` or
@@ -677,6 +688,7 @@ mdbkit queries mongod.log --sort scanRatio --limit 10
677
688
  mdbkit queries mongod.log --min-ms 500 --json
678
689
  mdbkit queries "mongod.log*" # rotated logs as one stream
679
690
  mdbkit queries mongod.log --shape 1 # drill into the worst offender
691
+ mdbkit queries mongod.log --shape 0F877C7D # the same, by its queryHash
680
692
  ```
681
693
 
682
694
  `--shape N` expands one row of the table. On an 8.0+ log it also shows where
@@ -710,17 +722,37 @@ resources
710
722
  disk spills : 159 (13.6 GiB written)
711
723
  CPU time : 5.5m total
712
724
 
713
- server identifiers
725
+ server identifiers (find this shape's log lines, plan cache entry or query settings)
726
+ queryHash : 0F877C7D
727
+ (named planCacheShapeHash from 8.0, which logs both)
728
+ planCacheKey : 8F21BC04
714
729
  queryShapeHash : BDC6B796B132EBAF671210F40FC5155C05ED250F79996E68DC6C620CBD8972AE
715
- pin or block this shape without a code change (8.0+):
716
- db.adminCommand({setQuerySettings: "BDC6...72AE", settings: {...}})
717
- planCacheShapeHash : 0F877C7D (queryHash before 8.0)
730
+ the full log lines : mdbkit filter <log> --query-hash 0F877C7D --last 5
731
+ as runnable explain: mdbkit filter <log> --query-hash 0F877C7D --last 1 --as-explain
732
+ plan cache entry : db.getSiblingDB("shop").getCollection("events").aggregate([{$planCacheStats: {}}, {$match: {queryHash: "0F877C7D"}}])
733
+ (run on the member that logged it; only queries that had more than one candidate plan are cached)
734
+ pin or block this shape without a code change (8.0+):
735
+ db.adminCommand({setQuerySettings: "BDC6B796...", settings: {...}})
718
736
  ```
719
737
 
720
- The `queryShapeHash` is the same value MongoDB shows in `explain`, the
721
- profiler, `$currentOp` and `$queryStats`, so you can follow one shape
722
- across all of them. mdbkit only prints the `setQuerySettings` command. It
723
- never runs it.
738
+ **From a shape back to the query.** The table groups thousands of log lines
739
+ into a few shapes; the hashes take you back to the lines themselves.
740
+ `queryHash` (8 characters) is in the slow-query lines of operations that
741
+ went through the query planner, on mongod and on mongos (checked on 6.0 to
742
+ 9.0); for a find, the mongos value matches the shards' (checked on 9.0). `filter --query-hash` prints those
743
+ lines, or rebuilds the latest as a runnable `explain`:
744
+
745
+ ```bash
746
+ mdbkit queries mongod.log # note the queryHash of the shape you want
747
+ mdbkit filter mongod.log --query-hash 0F877C7D --last 5 # its full log lines
748
+ mdbkit filter mongod.log --query-hash 0F877C7D --last 1 --as-explain
749
+ ```
750
+
751
+ The same `queryHash` finds the shape's plan cache entry (checked on real
752
+ 7.0 and 9.0 servers), and the 8.0+ `queryShapeHash` is the value MongoDB
753
+ shows in `explain`, the profiler, `$currentOp` and `$queryStats`, and that
754
+ `setQuerySettings` takes. mdbkit only prints those commands. It never runs
755
+ them.
724
756
 
725
757
  ---
726
758
 
@@ -775,6 +807,7 @@ it chains with other tools (including mdbkit itself).
775
807
  | `--to TIMESTAMP` | Upper time bound (inclusive) |
776
808
  | `--msg TEXT` | Substring match on the message field |
777
809
  | `--failed` | Only operations that ended in an error (logged with an `errName`) |
810
+ | `--query-hash HASH` | Only operations with this `queryHash`, `planCacheShapeHash`, `planCacheKey` or `queryShapeHash` (as `queries` shows them; case ignored, and a `queryShapeHash` may be shortened to its first 8+ characters) |
778
811
  | `--limit N` | Print only the **first** N matches |
779
812
  | `--last N` | Print only the **last** N matches — usually what you want during an incident |
780
813
  | `--as-explain` | Rebuild each matching slow query as a runnable `mongosh` `.explain()` command instead of printing the raw log line |
@@ -1526,6 +1559,13 @@ Linux box the database actually runs on.
1526
1559
  are still read, and misread log lines are still the most useful thing to
1527
1560
  send.
1528
1561
 
1562
+ **Shipped in v0.8.1:** the `queryHash` of each shape in the `queries`
1563
+ table, `queries --shape <hash>` and `filter --query-hash`, to go from a
1564
+ shape back to its full log lines
1565
+ ([#1](https://github.com/saqibameen86/mdbkit/issues/1)). Checked against
1566
+ MongoDB 9.0.8, 8.3.17, 8.0.38 and 7.0.48, the newest patches in December
1567
+ 2026.
1568
+
1529
1569
  **Shipped in v0.8:**
1530
1570
 
1531
1571
  * **Sharded clusters.** mongos logs show how many shards each query shape
@@ -1,3 +1,3 @@
1
1
  """mdbkit — an offline toolkit for MongoDB structured logs and index advice."""
2
2
 
3
- __version__ = "0.8.0"
3
+ __version__ = "0.8.1"
@@ -230,6 +230,7 @@ class ShapeStats:
230
230
  # MongoDB 8.0+ server-computed identifiers for this shape.
231
231
  query_shape_hashes: Counter = field(default_factory=Counter)
232
232
  plan_cache_hashes: Counter = field(default_factory=Counter)
233
+ plan_cache_keys: Counter = field(default_factory=Counter)
233
234
  query_frameworks: Counter = field(default_factory=Counter)
234
235
  # Disk spilling: hasSortStage+usedDisk on older versions, <stage>Spills
235
236
  # counters from 8.1.
@@ -285,6 +286,7 @@ class ShapeStats:
285
286
 
286
287
  for key, bucket in (("queryShapeHash", self.query_shape_hashes),
287
288
  ("planCacheShapeHash", self.plan_cache_hashes),
289
+ ("planCacheKey", self.plan_cache_keys),
288
290
  ("queryFramework", self.query_frameworks)):
289
291
  value = attr.get(key)
290
292
  if key == "planCacheShapeHash" and value is None:
@@ -336,6 +338,28 @@ class ShapeStats:
336
338
  def max_shards(self) -> int:
337
339
  return max(self.shard_counts) if self.shard_counts else 0
338
340
 
341
+ @property
342
+ def query_hash(self) -> str:
343
+ """The queryHash (planCacheShapeHash from 8.0) seen most often for
344
+ this shape, as the table shows it: "-" if the log has none, and
345
+ "+N" when mongod gave the shape more than one."""
346
+ if not self.plan_cache_hashes:
347
+ return "-"
348
+ top = self.plan_cache_hashes.most_common(1)[0][0]
349
+ more = len(self.plan_cache_hashes) - 1
350
+ return top if not more else "%s+%d" % (top, more)
351
+
352
+ def has_hash(self, wanted: str) -> bool:
353
+ """Whether any line of this shape carried this queryHash,
354
+ planCacheShapeHash, planCacheKey or queryShapeHash (case ignored; a
355
+ queryShapeHash may be given by its first 8+ characters)."""
356
+ wanted = wanted.strip().upper()
357
+ for bucket in (self.plan_cache_hashes, self.plan_cache_keys):
358
+ if any(h.upper() == wanted for h in bucket):
359
+ return True
360
+ return len(wanted) >= 8 and any(h.upper().startswith(wanted)
361
+ for h in self.query_shape_hashes)
362
+
339
363
  def all_shard_runs(self, total_shards: int) -> int:
340
364
  """Executions sent to every shard (scatter-gather)."""
341
365
  if total_shards < 2:
@@ -397,6 +421,7 @@ class ShapeStats:
397
421
  "queuedMicros": self.queued_us or None,
398
422
  "queryShapeHashes": dict(self.query_shape_hashes.most_common()),
399
423
  "planCacheShapeHashes": dict(self.plan_cache_hashes.most_common()),
424
+ "planCacheKeys": dict(self.plan_cache_keys.most_common()),
400
425
  "queryFrameworks": dict(self.query_frameworks),
401
426
  "spills": self.spills,
402
427
  "spilledBytes": self.spilled_bytes,
@@ -68,15 +68,32 @@ def cmd_queries(args) -> int:
68
68
  file=sys.stderr)
69
69
  if getattr(args, "shape", None):
70
70
  from .render import render_shape_detail
71
- idx = args.shape - 1
72
- if idx < 0 or idx >= len(results):
73
- print("error: --shape %d is out of range (1..%d)"
74
- % (args.shape, len(results)), file=sys.stderr)
75
- return 2
71
+ if isinstance(args.shape, str):
72
+ # by hash: look through every shape, not only the --limit shown
73
+ every = agg.results(sort_by=args.sort, limit=0)
74
+ found = [r for r in every if r.has_hash(args.shape)]
75
+ if not found:
76
+ print("error: no slow operation in this log has %s as its "
77
+ "queryHash, planCacheShapeHash, planCacheKey or "
78
+ "queryShapeHash" % args.shape, file=sys.stderr)
79
+ return 2
80
+ if len(found) > 1 and not args.json:
81
+ print("note: %d rows of the table carry %s (a query and the "
82
+ "getMores reading its cursor, or shapes mdbkit splits where "
83
+ "mongod does not); showing each" % (len(found), args.shape),
84
+ file=sys.stderr)
85
+ else:
86
+ idx = args.shape - 1
87
+ if idx < 0 or idx >= len(results):
88
+ print("error: --shape %d is out of range (1..%d)"
89
+ % (args.shape, len(results)), file=sys.stderr)
90
+ return 2
91
+ found = [results[idx]]
76
92
  if args.json:
77
- print(dump_json(results[idx].to_dict()))
93
+ data = [r.to_dict() for r in found]
94
+ print(dump_json(data[0] if len(data) == 1 else data))
78
95
  else:
79
- print(render_shape_detail(results[idx], stats))
96
+ print("\n\n".join(render_shape_detail(r, stats) for r in found))
80
97
  return 0
81
98
  if args.report:
82
99
  from .report import Report, stamp
@@ -89,18 +106,18 @@ def cmd_queries(args) -> int:
89
106
  round(s.mean_ms), s.max_ms, _shards_label(s),
90
107
  ("%d/%d" % (s.all_shard_runs(total), s.count))
91
108
  if total >= 2 and s.routed else "-",
92
- s.shape.pretty()[:80]] for s in results]
109
+ s.query_hash, s.shape.pretty()[:80]] for s in results]
93
110
  rep.table("Slow query shapes (mongos)",
94
111
  ["namespace", "op", "count", "cumMs", "mean", "max",
95
- "shards", "to all %d" % total, "shape"], rows)
112
+ "shards", "to all %d" % total, "queryHash", "shape"], rows)
96
113
  else:
97
114
  rows = [[s.shape.ns, s.shape.operation, s.count, s.total_ms,
98
115
  round(s.mean_ms), s.max_ms, s.docs_examined,
99
116
  ("%.0f:1" % s.scan_ratio) if s.n_returned else "-",
100
- s.shape.pretty()[:80]] for s in results]
117
+ s.query_hash, s.shape.pretty()[:80]] for s in results]
101
118
  rep.table("Slow query shapes",
102
119
  ["namespace", "op", "count", "cumMs", "mean", "max",
103
- "docsEx", "scan", "shape"], rows)
120
+ "docsEx", "scan", "queryHash", "shape"], rows)
104
121
  rep.text("Note",
105
122
  "cumMs is time summed across all occurrences of a shape, not "
106
123
  "a single query. Literal values are never included: these are "
@@ -154,6 +171,7 @@ def cmd_filter(args) -> int:
154
171
  ts_to=parse_when(args.ts_to) if args.ts_to else None,
155
172
  msg_contains=args.msg,
156
173
  failed=args.failed,
174
+ query_hash=args.query_hash,
157
175
  )
158
176
  except ValueError as exc:
159
177
  print(f"error: {exc}", file=sys.stderr)
@@ -330,6 +348,20 @@ NON_NEG = _int_range(0)
330
348
  POSITIVE = _int_range(1)
331
349
 
332
350
 
351
+ def _shape_ref(value: str):
352
+ """--shape takes a row number or one of mongod's hashes for the shape."""
353
+ value = value.strip()
354
+ # 8+ hex characters is a hash, even all digits ("08260234"): no table
355
+ # has ten million rows
356
+ if len(value) >= 8 and all(c in "0123456789abcdefABCDEF" for c in value):
357
+ return value.upper()
358
+ if value.isdigit():
359
+ return POSITIVE(value)
360
+ raise argparse.ArgumentTypeError(
361
+ "expected a row number from the table, or a queryHash / queryShapeHash "
362
+ "(hex, at least 8 characters), got %r" % value[:80])
363
+
364
+
333
365
  # ------------------------------------------------------- safe terminal ----
334
366
 
335
367
  class _SafeStream:
@@ -782,9 +814,10 @@ def build_parser() -> argparse.ArgumentParser:
782
814
  "not your workload)")
783
815
  sp.add_argument("--report", metavar="FILE",
784
816
  help="write a shareable .md or .html report instead")
785
- sp.add_argument("--shape", type=POSITIVE, metavar="N",
786
- help="show full detail for shape N from the table "
787
- "(plans, clients, timings, scan ratio)")
817
+ sp.add_argument("--shape", type=_shape_ref, metavar="N|HASH",
818
+ help="show full detail for shape N from the table, or for "
819
+ "the shape with this queryHash / planCacheShapeHash / "
820
+ "planCacheKey / queryShapeHash")
788
821
  sp.set_defaults(func=cmd_queries)
789
822
 
790
823
  sp = sub.add_parser("connections", help="connection churn by source IP and app")
@@ -801,6 +834,10 @@ def build_parser() -> argparse.ArgumentParser:
801
834
  sp.add_argument("--from", dest="ts_from", help="ISO timestamp lower bound")
802
835
  sp.add_argument("--to", dest="ts_to", help="ISO timestamp upper bound")
803
836
  sp.add_argument("--msg", help="substring match on the msg field")
837
+ sp.add_argument("--query-hash", metavar="HASH",
838
+ help="only operations with this queryHash, "
839
+ "planCacheShapeHash, planCacheKey or queryShapeHash "
840
+ "(as `queries` shows it)")
804
841
  sp.add_argument("--failed", action="store_true",
805
842
  help="only operations that failed (logged with an errName)")
806
843
  sp.add_argument("--limit", type=NON_NEG, metavar="N",
@@ -23,6 +23,7 @@ class Filter:
23
23
  ts_to: Optional[datetime] = None,
24
24
  msg_contains: Optional[str] = None,
25
25
  failed: bool = False,
26
+ query_hash: Optional[str] = None,
26
27
  ):
27
28
  self.component = component.upper() if component else None
28
29
  self.severity = severity.upper() if severity else None
@@ -32,6 +33,7 @@ class Filter:
32
33
  self.ts_to = ts_to
33
34
  self.msg_contains = msg_contains.lower() if msg_contains else None
34
35
  self.failed = failed
36
+ self.query_hash = query_hash.strip().upper() if query_hash else None
35
37
 
36
38
  def matches(self, entry: LogEntry) -> bool:
37
39
  if self.component and entry.component.upper() != self.component:
@@ -53,9 +55,34 @@ class Filter:
53
55
  return False
54
56
  if self.failed and not entry.attr.get("errName"):
55
57
  return False # operations that ended in an error
58
+ if self.query_hash and not matches_query_hash(entry.attr, self.query_hash):
59
+ return False
56
60
  return True
57
61
 
58
62
 
63
+ # The identifiers mongod puts on a slow operation's log line. queryHash
64
+ # (renamed planCacheShapeHash in 8.0, which logs both) and planCacheKey are
65
+ # 8 hex characters; queryShapeHash (8.0+) is 64.
66
+ HASH_FIELDS = ("queryHash", "planCacheShapeHash", "planCacheKey", "queryShapeHash")
67
+
68
+
69
+ def matches_query_hash(attr, wanted: str) -> bool:
70
+ """Whether a log line carries this hash in any of HASH_FIELDS. Case is
71
+ ignored, and a queryShapeHash may be given by its first 8+ characters."""
72
+ if not isinstance(attr, dict):
73
+ return False
74
+ wanted = wanted.upper()
75
+ for key in HASH_FIELDS:
76
+ value = attr.get(key)
77
+ if not isinstance(value, str) or not value:
78
+ continue
79
+ value = value.upper()
80
+ if value == wanted or (key == "queryShapeHash" and len(wanted) >= 8
81
+ and value.startswith(wanted)):
82
+ return True
83
+ return False
84
+
85
+
59
86
  def _lt(a: datetime, b: datetime) -> bool:
60
87
  """Compare two datetimes safely when one may be naive.
61
88
 
@@ -13,7 +13,7 @@ from __future__ import annotations
13
13
  import json
14
14
  from typing import Optional
15
15
 
16
- from .parser import LogEntry
16
+ from .parser import LogEntry, num
17
17
 
18
18
  # BSON/Extended-JSON wrappers we can render as mongosh constructors.
19
19
  _EJSON = {
@@ -89,6 +89,31 @@ def to_mongosh(entry: LogEntry, explain: bool = True,
89
89
  base = 'db.getSiblingDB("%s").getCollection("%s")' % (db, coll)
90
90
  suffix = '.explain("%s")' % verbosity if explain else ""
91
91
 
92
+ # A single update or delete logged by the WRITE component (every real
93
+ # update line from 7.0 to 9.0): the command is the statement itself,
94
+ # {q, u, multi, upsert} or {q, limit}, and attr.type says which.
95
+ wtype = str(attr.get("type") or "")
96
+ if wtype in ("update", "remove", "delete") and "q" in command \
97
+ and "update" not in command and "delete" not in command:
98
+ q = command.get("q")
99
+ if not isinstance(q, dict):
100
+ return None
101
+ if wtype == "update":
102
+ u = command.get("u")
103
+ if not isinstance(u, (dict, list)):
104
+ return None
105
+ method = "updateMany" if command.get("multi") is True else "updateOne"
106
+ stmt = "%s.%s(%s, %s)" % (base, method, _js(q), _js(u))
107
+ what = "update"
108
+ else:
109
+ method = "deleteOne" if num(command.get("limit"), 0) == 1 else "deleteMany"
110
+ stmt = "%s.%s(%s)" % (base, method, _js(q))
111
+ what = "delete"
112
+ if explain:
113
+ return "%s.find(%s)%s // %s predicate; the %s itself: %s" % (
114
+ base, _js(q), suffix, what, what, stmt)
115
+ return stmt
116
+
92
117
  if "find" in command:
93
118
  filt = command.get("filter")
94
119
  parts = [_js(filt if isinstance(filt, dict) else {})]
@@ -146,10 +146,12 @@ def render_queries(results: List[ShapeStats], stats: ParseStats,
146
146
  f"{s.docs_examined:,}" if s.docs_examined else "-",
147
147
  scan,
148
148
  _plan_label(s),
149
- s.shape.pretty()[:55],
149
+ s.query_hash,
150
+ s.shape.pretty()[:50],
150
151
  ))
151
152
  parts.append(_table(
152
- ["namespace", "op", "count", "cumMs", "mean", "max", "docsEx", "scan", "plan", "shape"],
153
+ ["namespace", "op", "count", "cumMs", "mean", "max", "docsEx", "scan", "plan",
154
+ "queryHash", "shape"],
153
155
  rows,
154
156
  ))
155
157
  parts.append("")
@@ -160,6 +162,9 @@ def render_queries(results: List[ShapeStats], stats: ParseStats,
160
162
  "plan = most common query plan; COLLSCAN/+SORT = index needed;\n"
161
163
  " +SPILL = wrote temporary files to disk (sort/group too big for memory)\n"
162
164
  " empty plan (?) = plan not present in log (below slowms threshold)\n"
165
+ "queryHash = mongod's own id for the shape (planCacheShapeHash from 8.0);\n"
166
+ " +N = the shape had N more. Full log lines for one:\n"
167
+ " mdbkit filter <log> --query-hash <hash>; details: --shape <hash>\n"
163
168
  "next : mdbkit advise <log> [--ns <namespace>] for index candidates"
164
169
  )
165
170
  timed = [r for r in results if r.timed_count]
@@ -199,10 +204,11 @@ def _render_router_queries(results: List[ShapeStats], parts: List[str],
199
204
  ("%d/%d" % (all_runs, s.count)) if total >= 2 and s.routed else "-",
200
205
  ("%.0f%%" % (100.0 * s.remote_wait_ms / s.total_ms))
201
206
  if s.routed and s.total_ms else "-",
202
- s.shape.pretty()[:55],
207
+ s.query_hash,
208
+ s.shape.pretty()[:50],
203
209
  ))
204
210
  parts.append(_table(["namespace", "op", "count", "cumMs", "mean", "max",
205
- "shards", "to all", "shard wait", "shape"], rows))
211
+ "shards", "to all", "shard wait", "queryHash", "shape"], rows))
206
212
  parts.append("")
207
213
  parts.append(
208
214
  "This is a mongos (router) log: it records how each query was routed,\n"
@@ -212,6 +218,8 @@ def _render_router_queries(results: List[ShapeStats], parts: List[str],
212
218
  " usually a filter without the shard key, or a range that\n"
213
219
  " spans every shard\n"
214
220
  "shard wait = share of the time spent waiting for the shards\n"
221
+ "queryHash = mongod's id for the shape, the same on the shards: find the\n"
222
+ " shape there with mdbkit queries <shard log> --shape <hash>\n"
215
223
  "next : mdbkit queries <shard log> for plans; mdbkit triage <this log>"
216
224
  % (total, "in this cluster" if known else
217
225
  "here: the most any query reached, since the log does not list the shards"))
@@ -653,19 +661,39 @@ def render_shape_detail(s, stats) -> str:
653
661
  parts.append("resources")
654
662
  parts.extend(" " + e for e in extra)
655
663
  parts.append("")
656
- if s.query_shape_hashes or s.plan_cache_hashes:
657
- parts.append("server identifiers")
664
+ if s.query_shape_hashes or s.plan_cache_hashes or s.plan_cache_keys:
665
+ parts.append("server identifiers (find this shape's log lines, plan cache entry or query settings)")
666
+
667
+ def listed(bucket, limit=4):
668
+ items = ["%s (%dx)" % kv for kv in bucket.most_common(limit)]
669
+ if len(bucket) > limit:
670
+ items.append("+%d more" % (len(bucket) - limit))
671
+ return ", ".join(items) if len(bucket) > 1 else bucket.most_common(1)[0][0]
672
+ if s.plan_cache_hashes:
673
+ parts.append(" queryHash : %s" % listed(s.plan_cache_hashes))
674
+ parts.append(" (named planCacheShapeHash from 8.0, which logs both)")
675
+ if s.plan_cache_keys:
676
+ parts.append(" planCacheKey : %s" % listed(s.plan_cache_keys))
677
+ if s.query_shape_hashes:
678
+ parts.append(" queryShapeHash : %s" % listed(s.query_shape_hashes, 2))
679
+ first = (s.plan_cache_hashes or s.query_shape_hashes).most_common(1)[0][0]
680
+ parts.append(" the full log lines : mdbkit filter <log> --query-hash %s --last 5" % first)
681
+ parts.append(" as runnable explain: mdbkit filter <log> --query-hash %s --last 1 --as-explain"
682
+ % first)
683
+ if s.plan_cache_hashes and not s.routed:
684
+ db, _, coll = s.shape.ns.partition(".")
685
+ parts.append(" plan cache entry : db.getSiblingDB(\"%s\").getCollection(\"%s\")"
686
+ ".aggregate([{$planCacheStats: {}}, {$match: {queryHash: \"%s\"}}])"
687
+ % (db, coll, s.plan_cache_hashes.most_common(1)[0][0]))
688
+ parts.append(" (run on the member that logged it; only queries that had "
689
+ "more than one candidate plan are cached)")
658
690
  if s.query_shape_hashes:
659
691
  h = s.query_shape_hashes.most_common(1)[0][0]
660
- parts.append(" queryShapeHash : %s" % h)
661
692
  # Query settings apply to find, distinct and aggregate only.
662
693
  base_op = s.shape.operation.replace("getMore(", "").rstrip(")")
663
694
  if base_op in ("find", "distinct", "aggregate"):
664
- parts.append(" pin or block this shape without a code change (8.0+):")
695
+ parts.append(" pin or block this shape without a code change (8.0+):")
665
696
  parts.append(" db.adminCommand({setQuerySettings: \"%s\", settings: {...}})" % h)
666
- if s.plan_cache_hashes:
667
- parts.append(" planCacheShapeHash : %s (queryHash before 8.0)"
668
- % s.plan_cache_hashes.most_common(1)[0][0])
669
697
  parts.append("")
670
698
  if s.shape.operation == "insert":
671
699
  if s.waiting_pct is not None and s.waiting_pct >= 40:
@@ -42,6 +42,8 @@ DATA_OPS = frozenset({"find", "aggregate", "getMore", "count", "distinct",
42
42
  "insert", "update", "delete", "findAndModify"})
43
43
  # Errors that mean the database could not serve the operation, as opposed
44
44
  # to a client mistake (DuplicateKey, a bad query) or a client hanging up.
45
+ SHUTDOWN_ERRORS = ("InterruptedAtShutdown", "ShutdownInProgress")
46
+
45
47
  SERIOUS_ERRORS = frozenset({
46
48
  "FailedToSatisfyReadPreference", "HostUnreachable", "NetworkTimeout",
47
49
  "MaxTimeMSExpired", "ExceededTimeLimit", "NotWritablePrimary",
@@ -325,10 +327,21 @@ def findings(st: ShardingState, routed_shapes=None) -> list:
325
327
  rs, host, len(events), _hm(min(stamps, default=None)),
326
328
  _hm(max(stamps, default=None)),
327
329
  " (%s)" % ", ".join(c for c, _ in codes.most_common(2)) if codes else ""))
330
+ # A member that was stopped or restarted tells its peers first: their
331
+ # first error from it is InterruptedAtShutdown / ShutdownInProgress.
332
+ stopped = [k for k, events in st.host_failures.items()
333
+ if events and events[0][1] in SHUTDOWN_ERRORS]
334
+ detail = "The replica set monitor could not reach %d member(s)." % len(st.host_failures)
335
+ if stopped:
336
+ detail += (" %s shutting down when first lost (%s), which is a stop "
337
+ "or a restart rather than a crash." % (
338
+ "All of them were" if len(stopped) == len(st.host_failures)
339
+ else "%d of them were" % len(stopped),
340
+ " / ".join(sorted({st.host_failures[k][0][1] for k in stopped}))))
341
+ all_stopped = len(stopped) == len(st.host_failures)
328
342
  out.append(Finding(
329
- "WARN" if not st.no_primary else "CRIT",
330
- "Members unreachable",
331
- "The replica set monitor could not reach %d member(s)." % len(st.host_failures),
343
+ "WARN" if not st.no_primary or all_stopped else "CRIT",
344
+ "Members unreachable", detail,
332
345
  rows, "Were they restarted, overloaded or partitioned at those times?"))
333
346
 
334
347
  # --- failed operations ---------------------------------------------
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mdbkit
3
- Version: 0.8.0
3
+ Version: 0.8.1
4
4
  Summary: Offline toolkit for MongoDB 4.4 to 9.0 logs and diagnostics: slow-query shapes, index advice and index usage, incident triage, sharded clusters, multi-instance hosts, startup configuration audit, FTDC decoding. A spiritual successor to mtools' log tools.
5
5
  Author: Saqib Ameen Subhan
6
6
  License: MIT
@@ -47,7 +47,8 @@ triage, sharded clusters, hosts running many mongods, a startup
47
47
  configuration audit, and diagnostic-data (FTDC) decoding. For MongoDB 4.4
48
48
  through 9.0, from the terminal, without connecting to anything.
49
49
  **[Tested against real MongoDB 9.0.2, 8.3.11, 8.0.32, 7.0.43 and 6.0.29](#compatibility)**
50
- — replica sets, standalones and sharded clusters (October 2026).
50
+ — replica sets, standalones and sharded clusters (October 2026) — and
51
+ re-checked on 9.0.8, 8.3.17, 8.0.38 and 7.0.48 (December 2026).
51
52
 
52
53
  A spiritual successor to mtools' log tools, which never learned to read the
53
54
  JSON log format introduced in 4.4.
@@ -279,7 +280,15 @@ updates — upgrades are always explicit.
279
280
  **Tested against (October 2026):** MongoDB **9.0.2**, **8.3.11**, **8.0.32**
280
281
  (LTS), **7.0.43** (LTS) and **6.0.29**, the newest release in each series at
281
282
  the time: replica sets and standalones on all five, and sharded clusters
282
- (mongos, shards and config servers) on 6.0, 7.0, 8.0 and 9.0. mdbkit reads the structured JSON log format, so anything
283
+ (mongos, shards and config servers) on 6.0, 7.0, 8.0 and 9.0.
284
+
285
+ **Re-checked (December 2026)** on the newest patches, **9.0.8**, **8.3.17**,
286
+ **8.0.38** and **7.0.48**: each was run as a replica set (seeded, its primary
287
+ killed and restarted, stepped down) and every command was run on the result;
288
+ 9.0.8 and 8.0.38 also as a sharded cluster. None of these patches changed a
289
+ log field, message or metric that mdbkit reads.
290
+
291
+ mdbkit reads the structured JSON log format, so anything
283
292
  from **4.4** onwards works; 4.2 and earlier wrote plain text logs and are not
284
293
  supported.
285
294
 
@@ -679,6 +688,7 @@ query with different parameters is counted once.
679
688
  | `--min-ms N` | 0 | Ignore operations faster than N milliseconds |
680
689
  | `--include-system` | off | Include internal `admin`/`config`/`local` namespaces (hidden by default — they are server housekeeping, not your workload) |
681
690
  | `--report FILE` | | Write a shareable `.md` or `.html` report instead (see [Shareable reports](#shareable-reports----report-file)) |
691
+ | `--shape N` or `--shape HASH` | | Full detail on one shape: row N of the table, or the shape with this `queryHash`, `planCacheShapeHash`, `planCacheKey` or `queryShapeHash` |
682
692
  | `--json` | | Machine-readable output |
683
693
 
684
694
  **Reading the columns:**
@@ -690,6 +700,7 @@ query with different parameters is counted once.
690
700
  | `docsEx` | Documents examined, summed across all occurrences |
691
701
  | `scan` | Documents examined per document returned. `1:1` is ideal; `3444:1` means a missing or weak index |
692
702
  | `plan` | The plan MongoDB chose: `COLLSCAN` (no index), `IXSCAN{fields}` (index used), `IDHACK` (`_id` lookup), `+SORT` (in-memory sort), `+SPILL` (wrote temporary files to disk). `?` = the plan was not recorded on that line |
703
+ | `queryHash` | MongoDB's own identifier for the shape, from the log (called `planCacheShapeHash` from 8.0, which logs both names). `+N` = mongod gave this shape N more. `-` = the log lines carry none (inserts, some updates, and 8.0+ `EXPRESS` lookups, which skip the planner) |
693
704
  | `shape` | Fields and operators queried, with the sort |
694
705
 
695
706
  Two kinds of row are worth knowing about. A `getMore(find)` or
@@ -713,6 +724,7 @@ mdbkit queries mongod.log --sort scanRatio --limit 10
713
724
  mdbkit queries mongod.log --min-ms 500 --json
714
725
  mdbkit queries "mongod.log*" # rotated logs as one stream
715
726
  mdbkit queries mongod.log --shape 1 # drill into the worst offender
727
+ mdbkit queries mongod.log --shape 0F877C7D # the same, by its queryHash
716
728
  ```
717
729
 
718
730
  `--shape N` expands one row of the table. On an 8.0+ log it also shows where
@@ -746,17 +758,37 @@ resources
746
758
  disk spills : 159 (13.6 GiB written)
747
759
  CPU time : 5.5m total
748
760
 
749
- server identifiers
761
+ server identifiers (find this shape's log lines, plan cache entry or query settings)
762
+ queryHash : 0F877C7D
763
+ (named planCacheShapeHash from 8.0, which logs both)
764
+ planCacheKey : 8F21BC04
750
765
  queryShapeHash : BDC6B796B132EBAF671210F40FC5155C05ED250F79996E68DC6C620CBD8972AE
751
- pin or block this shape without a code change (8.0+):
752
- db.adminCommand({setQuerySettings: "BDC6...72AE", settings: {...}})
753
- planCacheShapeHash : 0F877C7D (queryHash before 8.0)
766
+ the full log lines : mdbkit filter <log> --query-hash 0F877C7D --last 5
767
+ as runnable explain: mdbkit filter <log> --query-hash 0F877C7D --last 1 --as-explain
768
+ plan cache entry : db.getSiblingDB("shop").getCollection("events").aggregate([{$planCacheStats: {}}, {$match: {queryHash: "0F877C7D"}}])
769
+ (run on the member that logged it; only queries that had more than one candidate plan are cached)
770
+ pin or block this shape without a code change (8.0+):
771
+ db.adminCommand({setQuerySettings: "BDC6B796...", settings: {...}})
754
772
  ```
755
773
 
756
- The `queryShapeHash` is the same value MongoDB shows in `explain`, the
757
- profiler, `$currentOp` and `$queryStats`, so you can follow one shape
758
- across all of them. mdbkit only prints the `setQuerySettings` command. It
759
- never runs it.
774
+ **From a shape back to the query.** The table groups thousands of log lines
775
+ into a few shapes; the hashes take you back to the lines themselves.
776
+ `queryHash` (8 characters) is in the slow-query lines of operations that
777
+ went through the query planner, on mongod and on mongos (checked on 6.0 to
778
+ 9.0); for a find, the mongos value matches the shards' (checked on 9.0). `filter --query-hash` prints those
779
+ lines, or rebuilds the latest as a runnable `explain`:
780
+
781
+ ```bash
782
+ mdbkit queries mongod.log # note the queryHash of the shape you want
783
+ mdbkit filter mongod.log --query-hash 0F877C7D --last 5 # its full log lines
784
+ mdbkit filter mongod.log --query-hash 0F877C7D --last 1 --as-explain
785
+ ```
786
+
787
+ The same `queryHash` finds the shape's plan cache entry (checked on real
788
+ 7.0 and 9.0 servers), and the 8.0+ `queryShapeHash` is the value MongoDB
789
+ shows in `explain`, the profiler, `$currentOp` and `$queryStats`, and that
790
+ `setQuerySettings` takes. mdbkit only prints those commands. It never runs
791
+ them.
760
792
 
761
793
  ---
762
794
 
@@ -811,6 +843,7 @@ it chains with other tools (including mdbkit itself).
811
843
  | `--to TIMESTAMP` | Upper time bound (inclusive) |
812
844
  | `--msg TEXT` | Substring match on the message field |
813
845
  | `--failed` | Only operations that ended in an error (logged with an `errName`) |
846
+ | `--query-hash HASH` | Only operations with this `queryHash`, `planCacheShapeHash`, `planCacheKey` or `queryShapeHash` (as `queries` shows them; case ignored, and a `queryShapeHash` may be shortened to its first 8+ characters) |
814
847
  | `--limit N` | Print only the **first** N matches |
815
848
  | `--last N` | Print only the **last** N matches — usually what you want during an incident |
816
849
  | `--as-explain` | Rebuild each matching slow query as a runnable `mongosh` `.explain()` command instead of printing the raw log line |
@@ -1562,6 +1595,13 @@ Linux box the database actually runs on.
1562
1595
  are still read, and misread log lines are still the most useful thing to
1563
1596
  send.
1564
1597
 
1598
+ **Shipped in v0.8.1:** the `queryHash` of each shape in the `queries`
1599
+ table, `queries --shape <hash>` and `filter --query-hash`, to go from a
1600
+ shape back to its full log lines
1601
+ ([#1](https://github.com/saqibameen86/mdbkit/issues/1)). Checked against
1602
+ MongoDB 9.0.8, 8.3.17, 8.0.38 and 7.0.48, the newest patches in December
1603
+ 2026.
1604
+
1565
1605
  **Shipped in v0.8:**
1566
1606
 
1567
1607
  * **Sharded clusters.** mongos logs show how many shards each query shape
@@ -37,6 +37,7 @@ tests/test_host.py
37
37
  tests/test_indexes.py
38
38
  tests/test_mdbkit.py
39
39
  tests/test_oslog_serverstatus.py
40
+ tests/test_query_hash.py
40
41
  tests/test_real_failures.py
41
42
  tests/test_real_servers.py
42
43
  tests/test_rebuild_report.py
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "mdbkit"
10
- version = "0.8.0"
10
+ version = "0.8.1"
11
11
  description = "Offline toolkit for MongoDB 4.4 to 9.0 logs and diagnostics: slow-query shapes, index advice and index usage, incident triage, sharded clusters, multi-instance hosts, startup configuration audit, FTDC decoding. A spiritual successor to mtools' log tools."
12
12
  readme = "README.md"
13
13
  requires-python = ">=3.8"
@@ -0,0 +1,144 @@
1
+ """Issue #1: trace a query shape back to its full log lines with mongod's
2
+ own hashes. On real 7.0.43 (queryHash), 9.0.2 (queryHash, its 8.0 name
3
+ planCacheShapeHash, planCacheKey and queryShapeHash) and mongos logs."""
4
+
5
+ import contextlib
6
+ import io
7
+ import json
8
+ import os
9
+
10
+ import pytest
11
+
12
+ from mdbkit.cli import main
13
+
14
+ REAL = os.path.join(os.path.dirname(__file__), "fixtures", "real")
15
+ LOG90 = os.path.join(REAL, "mongod-9.0.2.log")
16
+ LOG70 = os.path.join(REAL, "mongod-7.0.43.log")
17
+ MONGOS = os.path.join(REAL, "sharded", "9.0.2", "manual", "mongos-mongos.log")
18
+
19
+
20
+ def run(argv):
21
+ out, err = io.StringIO(), io.StringIO()
22
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
23
+ try:
24
+ rc = main(argv)
25
+ except SystemExit as exc:
26
+ rc = exc.code
27
+ return rc, out.getvalue(), err.getvalue()
28
+
29
+
30
+ def rows(out):
31
+ return [l for l in out.splitlines() if l.startswith("shop.")]
32
+
33
+
34
+ def test_the_table_shows_each_shapes_query_hash():
35
+ rc, out, _ = run(["queries", LOG90])
36
+ assert rc == 0 and "queryHash" in out
37
+ where = [l for l in rows(out) if "{} [$where]" in l][0]
38
+ assert "A1D9218B" in where
39
+ # an EXPRESS lookup by a unique index has no plan cache entry, so no hash
40
+ assert [l for l in rows(out) if "{email:eq}" in l][0].split()[-2] == "-"
41
+
42
+
43
+ def test_before_80_the_field_is_called_queryhash_and_is_read_too():
44
+ rc, out, _ = run(["queries", LOG70])
45
+ hashes = [l.split()[-2] for l in rows(out)]
46
+ assert any(len(h) == 8 and h != "-" for h in hashes)
47
+
48
+
49
+ @pytest.mark.parametrize("ref", ["A1D9218B", "a1d9218b", "FEC5F3B7",
50
+ "218065CD9ABD6942"])
51
+ def test_shape_detail_by_hash_key_or_shape_hash_prefix(ref):
52
+ rc, out, _ = run(["queries", LOG90, "--shape", ref])
53
+ assert rc == 0
54
+ assert "$where" in out and "mdbkit filter <log> --query-hash A1D9218B" in out
55
+
56
+
57
+ def test_an_all_digit_hash_is_a_hash_not_a_row_number():
58
+ rc, out, err = run(["queries", LOG90, "--shape", "08260234"])
59
+ assert rc == 0 and "sort:{total:-1}" in out, err
60
+
61
+
62
+ def test_a_hash_that_is_not_in_the_log():
63
+ rc, _, err = run(["queries", LOG90, "--shape", "DEADBEEF"])
64
+ assert rc == 2 and "no slow operation" in err
65
+
66
+
67
+ def test_filter_returns_the_full_log_lines_for_a_hash():
68
+ rc, out, _ = run(["filter", LOG90, "--query-hash", "08260234"])
69
+ lines = [json.loads(l) for l in out.splitlines()]
70
+ assert rc == 0 and len(lines) == 6
71
+ assert all(l["attr"]["queryHash"] == "08260234" for l in lines)
72
+ # the find that opened the cursor and the getMores that read it
73
+ assert {"find", "getMore"} == {next(iter(l["attr"]["command"])) for l in lines}
74
+
75
+
76
+ def test_filter_by_plan_cache_key_and_as_explain():
77
+ rc, out, _ = run(["filter", LOG90, "--query-hash", "fec5f3b7", "--last", "1",
78
+ "--as-explain"])
79
+ assert rc == 0 and out.startswith('db.getSiblingDB("shop")')
80
+
81
+
82
+ def test_filter_with_an_unknown_hash_prints_nothing():
83
+ rc, out, err = run(["filter", LOG90, "--query-hash", "DEADBEEF"])
84
+ assert rc == 0 and out == "" and "matched 0" in err
85
+
86
+
87
+ def test_json_has_every_identifier():
88
+ rc, out, _ = run(["queries", LOG90, "--json"])
89
+ shape = [s for s in json.loads(out) if "A1D9218B" in s["planCacheShapeHashes"]][0]
90
+ assert shape["planCacheKeys"] == {"FEC5F3B7": 1}
91
+ assert len(next(iter(shape["queryShapeHashes"]))) == 64
92
+
93
+
94
+ def test_the_router_table_shows_the_hash_too():
95
+ rc, out, _ = run(["queries", MONGOS])
96
+ assert rc == 0 and "queryHash" in out and "9AD17EBD" in out
97
+
98
+
99
+ # A real 9.0.8 cluster (mdbkit lab --shards 2), December 2026: the mongos
100
+ # log, and one shard's.
101
+ C908 = os.path.join(REAL, "sharded", "9.0.8")
102
+
103
+
104
+ def test_a_router_hash_finds_the_same_query_on_the_shard():
105
+ rc, out, _ = run(["queries", os.path.join(C908, "mongos-stopped.log.gz")])
106
+ assert "F52B10EB" in [l for l in rows(out) if "sort:{createdAt:-1}" in l][0]
107
+ rc, out, _ = run(["queries", os.path.join(C908, "shard2.log.gz"), "--shape", "F52B10EB"])
108
+ assert rc == 0 and "{createdAt:gt, status:eq} sort:{createdAt:-1}" in out
109
+ assert "COLLSCAN" in out # the plan lives on the shard
110
+
111
+
112
+ def test_members_that_were_stopped_are_not_a_crash():
113
+ """The cluster was stopped; the mongos, stopped last, lost every member
114
+ with InterruptedAtShutdown first. 0.8.0 called that CRIT."""
115
+ from mdbkit.triage import run_triage
116
+ f, _, _ = run_triage(os.path.join(C908, "mongos-stopped.log.gz"), window_min=0,
117
+ no_sysprobe=True)
118
+ m = {x.title: x for x in f}["Members unreachable"]
119
+ assert m.severity == "WARN"
120
+ assert "All of them were shutting down when first lost" in m.detail
121
+
122
+
123
+ # A real update line from 9.0.8, logged by the WRITE component. --as-explain
124
+ # printed nothing for every such line (7.0 to 9.0) before 0.8.1.
125
+ UPDATE_908 = '{"t":{"$date":"2026-12-01T18:38:03.935+05:30"},"s":"I", "c":"WRITE", "id":51803, "ctx":"conn28","msg":"Slow query","attr":{"type":"update","isFromUserConnection":true,"isFromPriorityPortConnection":false,"ns":"shop.orders","collectionType":"normal","appName":"mongosh 2.14.3","queryShapeHash":"2D9B6F8B4677B5EF30DCFC80734249C5AE92CD6815A1B68664F0DA7A0D8020DD","command":{"q":{"customerId":"cust-14"},"u":{"$set":{"touched":{"$date":"2026-12-01T13:08:03.920Z"}}},"multi":true,"upsert":false},"opid":58503,"planSummary":"COLLSCAN","planningTimeMicros":115,"totalOplogSlotDurationMicros":1139,"keysExamined":0,"docsExamined":20000,"nMatched":4,"nModified":4,"nUpserted":0,"keysInserted":0,"keysDeleted":0,"numYields":1,"planCacheShapeHash":"7A3FB8B1","queryHash":"7A3FB8B1","planCacheKey":"C6388548","planRanker":"none","locks":{"Global":{"acquireCount":{"w":2}},"Database":{"acquireCount":{"w":2}},"Collection":{"acquireCount":{"w":2}}},"flowControl":{"acquireCount":2},"storage":{"timeWaitingMicros":{"storageEngineMicros":45}},"cpuNanos":9201784,"remote":"127.0.0.1:55486","queues":{"ingress":{"admissions":1,"totalTimeQueuedMicros":0},"ingress_request":{},"execution":{"admissions":3,"totalTimeQueuedMicros":0},"writeThrottle":{}},"workingMillis":13,"durationMillis":13}}'
126
+
127
+
128
+ def test_as_explain_rebuilds_a_real_write_level_update(tmp_path):
129
+ p = tmp_path / "u.log"
130
+ p.write_text(UPDATE_908 + "\n")
131
+ rc, out, _ = run(["filter", str(p), "--as-explain"])
132
+ assert rc == 0
133
+ assert out.startswith('db.getSiblingDB("shop").getCollection("orders").find({ "customerId": "cust-14" })')
134
+ assert '.updateMany({ "customerId": "cust-14" }, { "$set": { "touched": ISODate(' in out
135
+
136
+
137
+ def test_as_explain_rebuilds_a_write_level_delete(tmp_path):
138
+ d = json.loads(UPDATE_908)
139
+ d["attr"]["type"] = "remove"
140
+ d["attr"]["command"] = {"q": {"customerId": "cust-1"}, "limit": 1}
141
+ p = tmp_path / "d.log"
142
+ p.write_text(json.dumps(d) + "\n")
143
+ rc, out, _ = run(["filter", str(p), "--as-explain"])
144
+ assert '.find({ "customerId": "cust-1" })' in out and '.deleteOne({ "customerId": "cust-1" })' in out
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes