mdbkit 0.8.0__tar.gz → 0.8.2__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 (52) hide show
  1. {mdbkit-0.8.0 → mdbkit-0.8.2}/PKG-INFO +67 -15
  2. {mdbkit-0.8.0 → mdbkit-0.8.2}/README.md +66 -14
  3. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/__init__.py +1 -1
  4. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/advisor.py +4 -2
  5. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/analysis.py +25 -0
  6. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/cli.py +66 -27
  7. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/filtering.py +27 -0
  8. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/indexusage.py +5 -3
  9. mdbkit-0.8.2/mdbkit/quoting.py +86 -0
  10. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/rebuild.py +82 -34
  11. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/render.py +50 -15
  12. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/sharding.py +16 -3
  13. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/triage.py +4 -2
  14. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit.egg-info/PKG-INFO +67 -15
  15. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit.egg-info/SOURCES.txt +3 -0
  16. {mdbkit-0.8.0 → mdbkit-0.8.2}/pyproject.toml +1 -1
  17. mdbkit-0.8.2/tests/test_printed_commands.py +246 -0
  18. mdbkit-0.8.2/tests/test_query_hash.py +144 -0
  19. {mdbkit-0.8.0 → mdbkit-0.8.2}/LICENSE +0 -0
  20. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/audit.py +0 -0
  21. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/compare.py +0 -0
  22. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/demo.py +0 -0
  23. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/explain.py +0 -0
  24. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/ftdc.py +0 -0
  25. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/host.py +0 -0
  26. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/lab.py +0 -0
  27. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/oslog.py +0 -0
  28. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/parser.py +0 -0
  29. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/report.py +0 -0
  30. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/scripts.py +0 -0
  31. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/serverstatus.py +0 -0
  32. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit/shelljson.py +0 -0
  33. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit.egg-info/dependency_links.txt +0 -0
  34. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit.egg-info/entry_points.txt +0 -0
  35. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit.egg-info/requires.txt +0 -0
  36. {mdbkit-0.8.0 → mdbkit-0.8.2}/mdbkit.egg-info/top_level.txt +0 -0
  37. {mdbkit-0.8.0 → mdbkit-0.8.2}/setup.cfg +0 -0
  38. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_demo_lab.py +0 -0
  39. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_explain.py +0 -0
  40. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_ftdc.py +0 -0
  41. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_host.py +0 -0
  42. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_indexes.py +0 -0
  43. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_mdbkit.py +0 -0
  44. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_oslog_serverstatus.py +0 -0
  45. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_real_failures.py +0 -0
  46. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_real_servers.py +0 -0
  47. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_rebuild_report.py +0 -0
  48. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_render_e2e.py +0 -0
  49. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_sharded.py +0 -0
  50. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_triage.py +0 -0
  51. {mdbkit-0.8.0 → mdbkit-0.8.2}/tests/test_v060_hardening.py +0 -0
  52. {mdbkit-0.8.0 → mdbkit-0.8.2}/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.2
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,22 @@ 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
+ **v0.8.2 is a security fix: upgrade.** The commands mdbkit prints for you
1599
+ to paste (`--as-explain`, the plan cache lookup, `hideIndex`, the `--ns`
1600
+ hints) put names from the log or export in as they were. A crafted
1601
+ collection name, or a regex built from an application user's search text,
1602
+ could turn the printed line into one that runs something else when pasted.
1603
+ Every such value is now quoted. It also fixes `--explain-script` for updates
1604
+ and deletes, which wrote a script mongosh could not run. Details:
1605
+ [SECURITY.md](SECURITY.md#security-fixes).
1606
+
1607
+ **Shipped in v0.8.1:** the `queryHash` of each shape in the `queries`
1608
+ table, `queries --shape <hash>` and `filter --query-hash`, to go from a
1609
+ shape back to its full log lines
1610
+ ([#1](https://github.com/saqibameen86/mdbkit/issues/1)). Checked against
1611
+ MongoDB 9.0.8, 8.3.17, 8.0.38 and 7.0.48, the newest patches in December
1612
+ 2026.
1613
+
1565
1614
  **Shipped in v0.8:**
1566
1615
 
1567
1616
  * **Sharded clusters.** mongos logs show how many shards each query shape
@@ -1603,10 +1652,13 @@ the most valuable bug reports of all (redact literals first!).
1603
1652
 
1604
1653
  ## Security
1605
1654
 
1606
- mdbkit is offline by design: the codebase contains no network code, never
1607
- executes or evaluates input, and treats every log line as untrusted data
1608
- (strict JSON parsing only — shell constructors are never evaluated). See
1609
- [SECURITY.md](SECURITY.md) for the reporting process.
1655
+ mdbkit is offline by design: no analysis command contains network code
1656
+ (`lab` is the documented exception), nothing it reads is ever executed or
1657
+ evaluated, and every log line is treated as untrusted data (strict JSON
1658
+ parsing only — shell constructors are never evaluated). Commands it prints
1659
+ for you to paste quote every name taken from a log or export, so a crafted
1660
+ name cannot become code (fixed in 0.8.2). See [SECURITY.md](SECURITY.md)
1661
+ for what every release is checked for and the reporting process.
1610
1662
 
1611
1663
  ## Non-affiliation
1612
1664
 
@@ -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,22 @@ 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
+ **v0.8.2 is a security fix: upgrade.** The commands mdbkit prints for you
1563
+ to paste (`--as-explain`, the plan cache lookup, `hideIndex`, the `--ns`
1564
+ hints) put names from the log or export in as they were. A crafted
1565
+ collection name, or a regex built from an application user's search text,
1566
+ could turn the printed line into one that runs something else when pasted.
1567
+ Every such value is now quoted. It also fixes `--explain-script` for updates
1568
+ and deletes, which wrote a script mongosh could not run. Details:
1569
+ [SECURITY.md](SECURITY.md#security-fixes).
1570
+
1571
+ **Shipped in v0.8.1:** the `queryHash` of each shape in the `queries`
1572
+ table, `queries --shape <hash>` and `filter --query-hash`, to go from a
1573
+ shape back to its full log lines
1574
+ ([#1](https://github.com/saqibameen86/mdbkit/issues/1)). Checked against
1575
+ MongoDB 9.0.8, 8.3.17, 8.0.38 and 7.0.48, the newest patches in December
1576
+ 2026.
1577
+
1529
1578
  **Shipped in v0.8:**
1530
1579
 
1531
1580
  * **Sharded clusters.** mongos logs show how many shards each query shape
@@ -1567,10 +1616,13 @@ the most valuable bug reports of all (redact literals first!).
1567
1616
 
1568
1617
  ## Security
1569
1618
 
1570
- mdbkit is offline by design: the codebase contains no network code, never
1571
- executes or evaluates input, and treats every log line as untrusted data
1572
- (strict JSON parsing only — shell constructors are never evaluated). See
1573
- [SECURITY.md](SECURITY.md) for the reporting process.
1619
+ mdbkit is offline by design: no analysis command contains network code
1620
+ (`lab` is the documented exception), nothing it reads is ever executed or
1621
+ evaluated, and every log line is treated as untrusted data (strict JSON
1622
+ parsing only — shell constructors are never evaluated). Commands it prints
1623
+ for you to paste quote every name taken from a log or export, so a crafted
1624
+ name cannot become code (fixed in 0.8.2). See [SECURITY.md](SECURITY.md)
1625
+ for what every release is checked for and the reporting process.
1574
1626
 
1575
1627
  ## Non-affiliation
1576
1628
 
@@ -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.2"
@@ -25,6 +25,7 @@ from .analysis import (
25
25
  RANGE_OPS,
26
26
  ShapeStats,
27
27
  )
28
+ from .quoting import js_key, js_str, sh_arg
28
29
 
29
30
  Confidence = str # "high" | "medium" | "low"
30
31
 
@@ -46,7 +47,8 @@ class Recommendation:
46
47
  )
47
48
 
48
49
  def candidate_str(self) -> str:
49
- return "{ " + ", ".join(f"{f}: {d}" for f, d in self.candidate) + " }"
50
+ return "{ " + ", ".join("%s: %s" % (js_key(f), d if isinstance(d, int) else js_str(d))
51
+ for f, d in self.candidate) + " }"
50
52
 
51
53
  def to_dict(self) -> dict:
52
54
  return {
@@ -234,7 +236,7 @@ def advise(
234
236
  caveats.append(
235
237
  "Based on a single explain document — confirm this query shape "
236
238
  "is frequent enough to justify an index "
237
- "(mdbkit queries <log> --ns %s)." % shape.ns
239
+ "(mdbkit queries <log> --ns %s)." % sh_arg(shape.ns)
238
240
  )
239
241
 
240
242
  # Flags from the shape.
@@ -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,
@@ -24,6 +24,7 @@ from .render import (
24
24
  render_summary,
25
25
  )
26
26
  from .scripts import INDEXES_SCRIPT, SCHEMA_SCRIPT
27
+ from .quoting import sh_arg
27
28
 
28
29
 
29
30
  def _warn_if_pre44(stats: ParseStats) -> None:
@@ -68,15 +69,32 @@ def cmd_queries(args) -> int:
68
69
  file=sys.stderr)
69
70
  if getattr(args, "shape", None):
70
71
  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
72
+ if isinstance(args.shape, str):
73
+ # by hash: look through every shape, not only the --limit shown
74
+ every = agg.results(sort_by=args.sort, limit=0)
75
+ found = [r for r in every if r.has_hash(args.shape)]
76
+ if not found:
77
+ print("error: no slow operation in this log has %s as its "
78
+ "queryHash, planCacheShapeHash, planCacheKey or "
79
+ "queryShapeHash" % args.shape, file=sys.stderr)
80
+ return 2
81
+ if len(found) > 1 and not args.json:
82
+ print("note: %d rows of the table carry %s (a query and the "
83
+ "getMores reading its cursor, or shapes mdbkit splits where "
84
+ "mongod does not); showing each" % (len(found), args.shape),
85
+ file=sys.stderr)
86
+ else:
87
+ idx = args.shape - 1
88
+ if idx < 0 or idx >= len(results):
89
+ print("error: --shape %d is out of range (1..%d)"
90
+ % (args.shape, len(results)), file=sys.stderr)
91
+ return 2
92
+ found = [results[idx]]
76
93
  if args.json:
77
- print(dump_json(results[idx].to_dict()))
94
+ data = [r.to_dict() for r in found]
95
+ print(dump_json(data[0] if len(data) == 1 else data))
78
96
  else:
79
- print(render_shape_detail(results[idx], stats))
97
+ print("\n\n".join(render_shape_detail(r, stats) for r in found))
80
98
  return 0
81
99
  if args.report:
82
100
  from .report import Report, stamp
@@ -89,18 +107,18 @@ def cmd_queries(args) -> int:
89
107
  round(s.mean_ms), s.max_ms, _shards_label(s),
90
108
  ("%d/%d" % (s.all_shard_runs(total), s.count))
91
109
  if total >= 2 and s.routed else "-",
92
- s.shape.pretty()[:80]] for s in results]
110
+ s.query_hash, s.shape.pretty()[:80]] for s in results]
93
111
  rep.table("Slow query shapes (mongos)",
94
112
  ["namespace", "op", "count", "cumMs", "mean", "max",
95
- "shards", "to all %d" % total, "shape"], rows)
113
+ "shards", "to all %d" % total, "queryHash", "shape"], rows)
96
114
  else:
97
115
  rows = [[s.shape.ns, s.shape.operation, s.count, s.total_ms,
98
116
  round(s.mean_ms), s.max_ms, s.docs_examined,
99
117
  ("%.0f:1" % s.scan_ratio) if s.n_returned else "-",
100
- s.shape.pretty()[:80]] for s in results]
118
+ s.query_hash, s.shape.pretty()[:80]] for s in results]
101
119
  rep.table("Slow query shapes",
102
120
  ["namespace", "op", "count", "cumMs", "mean", "max",
103
- "docsEx", "scan", "shape"], rows)
121
+ "docsEx", "scan", "queryHash", "shape"], rows)
104
122
  rep.text("Note",
105
123
  "cumMs is time summed across all occurrences of a shape, not "
106
124
  "a single query. Literal values are never included: these are "
@@ -132,14 +150,14 @@ def _emit(entry, as_explain: bool, wrap: bool):
132
150
  not abort a filter run over a million-line file."""
133
151
  if not as_explain:
134
152
  return entry.raw
135
- from .rebuild import to_mongosh, wrap_for_export
153
+ from .rebuild import rebuild_parts, to_mongosh, wrap_for_export
136
154
  try:
137
- cmd = to_mongosh(entry)
155
+ if wrap:
156
+ parts = rebuild_parts(entry)
157
+ return wrap_for_export(*parts) if parts else None
158
+ return to_mongosh(entry)
138
159
  except Exception:
139
160
  return None
140
- if cmd is None:
141
- return None
142
- return wrap_for_export(cmd) if wrap else cmd
143
161
 
144
162
 
145
163
  def cmd_filter(args) -> int:
@@ -154,6 +172,7 @@ def cmd_filter(args) -> int:
154
172
  ts_to=parse_when(args.ts_to) if args.ts_to else None,
155
173
  msg_contains=args.msg,
156
174
  failed=args.failed,
175
+ query_hash=args.query_hash,
157
176
  )
158
177
  except ValueError as exc:
159
178
  print(f"error: {exc}", file=sys.stderr)
@@ -330,6 +349,20 @@ NON_NEG = _int_range(0)
330
349
  POSITIVE = _int_range(1)
331
350
 
332
351
 
352
+ def _shape_ref(value: str):
353
+ """--shape takes a row number or one of mongod's hashes for the shape."""
354
+ value = value.strip()
355
+ # 8+ hex characters is a hash, even all digits ("08260234"): no table
356
+ # has ten million rows
357
+ if len(value) >= 8 and all(c in "0123456789abcdefABCDEF" for c in value):
358
+ return value.upper()
359
+ if value.isdigit():
360
+ return POSITIVE(value)
361
+ raise argparse.ArgumentTypeError(
362
+ "expected a row number from the table, or a queryHash / queryShapeHash "
363
+ "(hex, at least 8 characters), got %r" % value[:80])
364
+
365
+
333
366
  # ------------------------------------------------------- safe terminal ----
334
367
 
335
368
  class _SafeStream:
@@ -634,12 +667,13 @@ def cmd_demo(args) -> int:
634
667
  msg.append("wrote %s" % path)
635
668
  msg.append("")
636
669
  msg.append("Try:")
637
- msg.append(" mdbkit loginfo %s" % args.out)
638
- msg.append(" mdbkit queries %s" % args.out)
639
- msg.append(" mdbkit triage %s --window 0 --no-sysprobe" % args.out)
670
+ out = sh_arg(args.out)
671
+ msg.append(" mdbkit loginfo %s" % out)
672
+ msg.append(" mdbkit queries %s" % out)
673
+ msg.append(" mdbkit triage %s --window 0 --no-sysprobe" % out)
640
674
  if args.with_extras:
641
675
  msg.append(" mdbkit advise %s --indexes indexes.json "
642
- "--schema schema.json" % args.out)
676
+ "--schema schema.json" % out)
643
677
  msg.append(" mdbkit explain explain.json")
644
678
  print("\n".join(msg), file=sys.stderr)
645
679
  else:
@@ -683,7 +717,7 @@ def cmd_lab(args) -> int:
683
717
  print("")
684
718
  print("Next:")
685
719
  print(" mdbkit lab seed # sample data + workload")
686
- print(" mdbkit queries %s" % lab.log_paths(state)[0])
720
+ print(" mdbkit queries %s" % sh_arg(lab.log_paths(state)[0]))
687
721
  print(" mdbkit lab destroy --yes # remove it all")
688
722
  elif args.lab_action == "status":
689
723
  state = lab.status(args.dir)
@@ -705,12 +739,12 @@ def cmd_lab(args) -> int:
705
739
  print("")
706
740
  print("Now analyse what it produced:")
707
741
  first = lab.log_paths(state)[0]
708
- print(" mdbkit queries %s" % first)
709
- print(" mdbkit advise %s" % first)
742
+ print(" mdbkit queries %s" % sh_arg(first))
743
+ print(" mdbkit advise %s" % sh_arg(first))
710
744
  if state.get("sharded"):
711
745
  from .lab import DEFAULT_DIR
712
746
  print(" mdbkit triage $(mdbkit lab logs%s | head -1) --window 0"
713
- % ("" if args.dir == DEFAULT_DIR else " --dir %s" % args.dir))
747
+ % ("" if args.dir == DEFAULT_DIR else " --dir %s" % sh_arg(args.dir)))
714
748
  elif args.lab_action == "stop":
715
749
  n = lab.stop(args.dir, echo=_lab_echo)
716
750
  print("stopped %d node(s)" % n)
@@ -782,9 +816,10 @@ def build_parser() -> argparse.ArgumentParser:
782
816
  "not your workload)")
783
817
  sp.add_argument("--report", metavar="FILE",
784
818
  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)")
819
+ sp.add_argument("--shape", type=_shape_ref, metavar="N|HASH",
820
+ help="show full detail for shape N from the table, or for "
821
+ "the shape with this queryHash / planCacheShapeHash / "
822
+ "planCacheKey / queryShapeHash")
788
823
  sp.set_defaults(func=cmd_queries)
789
824
 
790
825
  sp = sub.add_parser("connections", help="connection churn by source IP and app")
@@ -801,6 +836,10 @@ def build_parser() -> argparse.ArgumentParser:
801
836
  sp.add_argument("--from", dest="ts_from", help="ISO timestamp lower bound")
802
837
  sp.add_argument("--to", dest="ts_to", help="ISO timestamp upper bound")
803
838
  sp.add_argument("--msg", help="substring match on the msg field")
839
+ sp.add_argument("--query-hash", metavar="HASH",
840
+ help="only operations with this queryHash, "
841
+ "planCacheShapeHash, planCacheKey or queryShapeHash "
842
+ "(as `queries` shows it)")
804
843
  sp.add_argument("--failed", action="store_true",
805
844
  help="only operations that failed (logged with an errName)")
806
845
  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