mongory 2.1.0 → 2.2.0

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 (53) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +30 -0
  3. data/README.md +55 -73
  4. data/docs/clang_bridge.md +2 -2
  5. data/docs/performance.md +43 -7
  6. data/ext/mongory_ext/extconf.rb +15 -0
  7. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/config.h +28 -43
  8. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/memory_pool.h +0 -1
  9. data/ext/mongory_ext/mongory-core/include/mongory-core/matchers/matcher.h +3 -4
  10. data/ext/mongory_ext/mongory-core/src/foundations/array.c +28 -5
  11. data/ext/mongory_ext/mongory-core/src/foundations/config.c +24 -22
  12. data/ext/mongory_ext/mongory-core/src/foundations/config_private.h +3 -3
  13. data/ext/mongory_ext/mongory-core/src/foundations/memory_pool.c +22 -13
  14. data/ext/mongory_ext/mongory-core/src/foundations/string_buffer.c +4 -3
  15. data/ext/mongory_ext/mongory-core/src/foundations/table.c +60 -224
  16. data/ext/mongory_ext/mongory-core/src/foundations/table_private.h +36 -0
  17. data/ext/mongory_ext/mongory-core/src/foundations/utils.c +30 -47
  18. data/ext/mongory_ext/mongory-core/src/foundations/utils.h +2 -5
  19. data/ext/mongory_ext/mongory-core/src/foundations/value.c +18 -32
  20. data/ext/mongory_ext/mongory-core/src/matchers/base_matcher.c +89 -104
  21. data/ext/mongory_ext/mongory-core/src/matchers/base_matcher.h +18 -11
  22. data/ext/mongory_ext/mongory-core/src/matchers/compare_matcher.c +35 -150
  23. data/ext/mongory_ext/mongory-core/src/matchers/composite_matcher.c +244 -418
  24. data/ext/mongory_ext/mongory-core/src/matchers/composite_matcher.h +30 -0
  25. data/ext/mongory_ext/mongory-core/src/matchers/existence_matcher.c +15 -56
  26. data/ext/mongory_ext/mongory-core/src/matchers/external_matcher.c +18 -39
  27. data/ext/mongory_ext/mongory-core/src/matchers/implicit_array_matcher.c +14 -15
  28. data/ext/mongory_ext/mongory-core/src/matchers/inclusion_matcher.c +382 -74
  29. data/ext/mongory_ext/mongory-core/src/matchers/matcher.c +373 -123
  30. data/ext/mongory_ext/mongory-core/src/matchers/matcher_traversable.c +20 -12
  31. data/ext/mongory_ext/mongory-core/src/matchers/matcher_traversable.h +1 -4
  32. data/ext/mongory_ext/mongory-core/src/matchers/value_matcher.c +214 -171
  33. data/ext/mongory_ext/mongory-core/src/matchers/value_matcher.h +8 -16
  34. data/ext/mongory_ext/mongory_ext.c +26 -4
  35. data/ext/mongory_ext/mongory_ext_internal.h +15 -3
  36. data/ext/mongory_ext/rb_mongory_adapters.c +52 -19
  37. data/ext/mongory_ext/rb_mongory_matcher.c +115 -36
  38. data/ext/mongory_ext/rb_mongory_value.c +124 -51
  39. data/lib/mongory/converters/abstract_converter.rb +5 -5
  40. data/lib/mongory/converters/converted.rb +0 -4
  41. data/lib/mongory/converters/key_converter.rb +13 -36
  42. data/lib/mongory/converters/value_converter.rb +4 -4
  43. data/lib/mongory/matchers.rb +8 -7
  44. data/lib/mongory/query_builder.rb +9 -0
  45. data/lib/mongory/utils/context.rb +0 -6
  46. data/lib/mongory/utils/singleton_builder.rb +1 -4
  47. data/lib/mongory/version.rb +1 -1
  48. data/lib/mongory.rb +0 -1
  49. data/script/bench.rb +77 -4
  50. data/script/coverage.rb +84 -0
  51. metadata +7 -7
  52. data/ext/mongory_ext/mongory-core/src/matchers/matcher_explainable.c +0 -117
  53. data/ext/mongory_ext/mongory-core/src/matchers/matcher_explainable.h +0 -29
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 16eec5033c412a221a105ef1153ca8637e37f854a09398950357dda4d2be5ff7
4
- data.tar.gz: d7558b69669515a52d8d7247b6b1589748fe58391d8df32552de99720a7b4651
3
+ metadata.gz: 8d49ac9069e9ac8dbf8c6541f16f3643fd00b792bf3294767f7157bf3a926338
4
+ data.tar.gz: 4bd8cfd6d58e5ea66ee647ddbe4fd248101532ba85836b120aa4278c75cc9a49
5
5
  SHA512:
6
- metadata.gz: ca6094143a3e56a757c635a73d4cd65175ccc2b6c921970ca098791a391b62803717e8a4d00abdf5ede87b5876d2e6763c184e583a552a5e198c905570360598
7
- data.tar.gz: 5590c5f152d142b862a463019bed349b44b6aec999d5218c7a67ec7dd3562ef77c4edcd8bc9c32f381d86c84120172ec71ed0f0e0bf31e3c41914b6f2ed5b07e
6
+ metadata.gz: 23ae867269c6306befa5ebff3ce5ff31047ac80b70861dbfdc98816fd5c42857b320caecffddf00fb82e72cef63d1441d2b0d4e1a742f05ebeedd397013ed521
7
+ data.tar.gz: c9b3fa0f98cfbc66aba4b3da02cf068622592d0232a2c61702c8c086aa4adce4e580f5846b0342c3c67af0f382b6fb4cfc960de71edc67a2f6b3079cea014438
data/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.2.0] - 2026-12-04
4
+
5
+ ### Added
6
+ - **`$nor` operator**: `$nor` via `mongory-core`, plus `QueryBuilder#nor`.
7
+ - **Memory accounting**: native matchers report their pool memory to the Ruby GC (`TypedData` `dsize`).
8
+
9
+ ### Changed
10
+ - **`null` means explicit `nil` or a missing key (`mongory-spec v0.5.0`)**: `{ a: { '$eq' => nil } }` and `{ a: { '$in' => [nil] } }` now match a missing key, like `{ a: nil }`. `{ a: { '$ne' => nil } }` and `$nin` with `nil` no longer match a missing key, and on a path through an array they fail when any element lacks the key.
11
+ - **Missing parents**: a nested field whose parent is missing or not a Hash or Array now counts as missing for every operator (for example `{ 'profile.address' => { '$present' => false } }` matches `{}`).
12
+ - Bumped the `ext/mongory_ext/mongory-core` submodule to `v0.4.0`.
13
+ - Dotted-key expansion is delegated to `mongory-core`.
14
+
15
+ ### Fixed
16
+ - An explicit empty `$elemMatch` on an array field no longer matches an empty array.
17
+ - Hardened GC/trace safety, custom matcher `NULL` values, and converter edge cases.
18
+
19
+ ### Packaging
20
+ - Release builds true per-arch native gems and smoke-tests a clean-room install on all 8 platforms.
21
+
22
+ ### Docs
23
+ - README links the full [Differences from MongoDB](https://github.com/mongoryhq/mongory-spec/blob/main/docs/mongodb-differences.md) page.
24
+
25
+ ## [2.1.1] - 2026-11-25
26
+
27
+ ### Performance
28
+ - **O(1) `$in` / `$nin` Hash Lookup (`mongory-core v0.3.1`)**: Bumped `mongory-core` submodule to `v0.3.1`, adding an immutable, arena-allocated, type-bucketed O(1) hash set for `$in` / `$nin` arrays with 16+ items (~15x speedup on 500-item `$in`, ~840x faster than `Mongoid::Matcher` in local benchmarks).
29
+
30
+ ### Docs & Benchmarks
31
+ - Added optional `Mongoid::Matcher` comparison to `script/bench.rb` and updated `docs/performance.md`.
32
+
3
33
  ## [2.1.0] - 2026-11-23
4
34
 
5
35
  ### Added
data/README.md CHANGED
@@ -1,21 +1,19 @@
1
1
  # Mongory (Ruby)
2
2
 
3
- **Cross-language, in-memory Mongo-style rule engine & query matcher with built-in Explain & Trace debugging** — powered by the C99 [`mongory-core`](https://github.com/mongoryhq/mongory-core) native extension with cross-language parity via [`mongory-spec`](https://github.com/mongoryhq/mongory-spec).
3
+ [![Gem Version](https://img.shields.io/gem/v/mongory)](https://rubygems.org/gems/mongory)
4
+ [![API Docs](https://img.shields.io/badge/API%20Docs-YARD-CC342D)](https://mongoryhq.github.io/mongory-rb/)
5
+ [![CI](https://github.com/mongoryhq/mongory-rb/actions/workflows/main.yml/badge.svg)](https://github.com/mongoryhq/mongory-rb/actions/workflows/main.yml)
6
+ [![mongory-spec](https://github.com/mongoryhq/mongory-rb/actions/workflows/spec-conformance.yml/badge.svg)](https://github.com/mongoryhq/mongory-rb/actions/workflows/spec-conformance.yml)
7
+ ![Ruby](https://img.shields.io/badge/Ruby-2.6%2B-CC342D)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
4
9
 
5
- **[Try the Interactive Playground & Visual Explain/Trace Debugger ↗](https://mongoryhq.github.io/mongory-central/)**
10
+ **Zero-dependency, C99-backed in-memory MongoDB-style query and rule engine for Ruby**, with built-in `explain` / `trace` debugging and cross-language parity via [`mongory-spec`](https://github.com/mongoryhq/mongory-spec).
6
11
 
7
- [![Mongory Playground & Visual Trace](https://mongoryhq.github.io/mongory-central/playground-trace.png)](https://mongoryhq.github.io/mongory-central/)
12
+ **[Try the Interactive Playground & Visual Explain/Trace Debugger ↗](https://mongoryhq.github.io/mongory-central/?ref=mongory-rb-readme)**
8
13
 
9
- > **Zero database required:** Evaluate MongoDB-style conditions (`$gte`, `$elemMatch`, `$every`, `$present`, `$regex`, etc.) directly against in-memory Ruby Arrays, Hashes, custom objects, and ActiveRecord/Mongoid relations.
10
- > **Ecosystem:** [Interactive Playground](https://mongoryhq.github.io/mongory-central/) · [`mongory-go` (Go)](https://github.com/mongoryhq/mongory-go) · [`mongory-js` (TypeScript/JS)](https://github.com/mongoryhq/mongory-js) · [`mongory-core` (C99)](https://github.com/mongoryhq/mongory-core) · [`mongory-spec`](https://github.com/mongoryhq/mongory-spec)
14
+ [![Mongory Playground & Visual Trace](https://mongoryhq.github.io/mongory-central/playground-trace.png)](https://mongoryhq.github.io/mongory-central/?ref=mongory-rb-readme)
11
15
 
12
- ## Features
13
-
14
- - **Chainable Ruby DSL & Raw JSON Support**: Compose queries with `.where`, `.any_of`, `.or`, `.not`, and optional Symbol snippets (`:age.gte => 18`), or pass parsed JSON conditions directly from front-end rules.
15
- - **All 17 Mongory Operators**: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`, `$exists`, `$present`, `$and`, `$or`, `$not`, `$elemMatch`, `$every`, `$size`, `$regex` (with `$options`: `i`, `m`, `s`).
16
- - **Priority-Ordered Execution & Visual Debugging**: Automatically sorts sibling conditions so cheaper checks short-circuit before expensive regex or array scans; inspect compiled trees with `.explain` and per-record evaluation with `.trace`.
17
- - **Native C99 Engine (`Mongory::Matcher`)**: Powered directly by `mongory-core` with zero Pure-Ruby engine overhead, while still supporting custom Ruby matchers via `Mongory::Matchers::AbstractMatcher`.
18
- - **Precompiled Native Gems (Ruby 2.6–4.0)**: Ships prebuilt binaries for Linux (`x86_64`/`aarch64`, glibc & musl), macOS (`x86_64`/`arm64`), and Windows (`x64-mingw32`/`ucrt`).
16
+ > **Ecosystem:** [Playground](https://mongoryhq.github.io/mongory-central/?ref=mongory-rb-readme) · [`mongory-go` (Go)](https://github.com/mongoryhq/mongory-go) · [`mongory-js` (TypeScript/JS)](https://github.com/mongoryhq/mongory-js) · [`mongory-py` (Python)](https://github.com/mongoryhq/mongory-py) · [`mongory-core` (C99)](https://github.com/mongoryhq/mongory-core) · [`mongory-spec`](https://github.com/mongoryhq/mongory-spec)
19
17
 
20
18
  ## Installation
21
19
 
@@ -25,13 +23,14 @@ gem install mongory
25
23
  gem 'mongory'
26
24
  ```
27
25
 
28
- In a Rails project, generate the initializer (`config/initializers/mongory.rb`):
26
+ The gem ships precompiled native binaries (Ruby `2.6-4.0`) for Linux (`x86_64`/`aarch64`, glibc and musl), macOS (`x86_64`/`arm64`), and Windows (`x64-mingw32`/`ucrt`). In a Rails project, generate the initializer with `rails g mongory:install`.
29
27
 
30
- ```bash
31
- rails g mongory:install
32
- ```
28
+ <details>
29
+ <summary>Platform note (Apple Silicon system Ruby / source builds)</summary>
33
30
 
34
- > **Note:** Precompiled native gems are installed automatically on supported Linux, macOS, and Windows platforms (Ruby 2.6–4.0). On older Apple Silicon macOS system Ruby (`universal-darwin`), run `gem install mongory --platform arm64-darwin` or `bundle lock --add-platform arm64-darwin`. When compiling from source on other platforms, ensure `gcc`/`clang` and `make` are installed.
31
+ On older Apple Silicon macOS system Ruby (`universal-darwin`), run `gem install mongory --platform arm64-darwin` or `bundle lock --add-platform arm64-darwin`. When compiling from source on other platforms, ensure `gcc`/`clang` and `make` are installed.
32
+
33
+ </details>
35
34
 
36
35
  ## Quick Start
37
36
 
@@ -43,19 +42,19 @@ Mongory.register(Array)
43
42
  Mongory.enable_symbol_snippets!
44
43
 
45
44
  records = [
46
- { 'name' => 'Jack', 'age' => 18, 'tags' => %w[ruby go], 'active' => true },
47
- { 'name' => 'Jill', 'age' => 15, 'tags' => %w[js], 'active' => true },
48
- { 'name' => 'Bob', 'age' => 21, 'tags' => %w[ruby], 'active' => false }
45
+ { 'name' => 'Jack', 'age' => 18, 'tags' => %w(ruby go), 'active' => true },
46
+ { 'name' => 'Jill', 'age' => 15, 'tags' => %w(js), 'active' => true },
47
+ { 'name' => 'Bob', 'age' => 21, 'tags' => %w(ruby), 'active' => false }
49
48
  ]
50
49
 
51
50
  # 1. Chainable DSL with symbol operator snippets
52
- matched = records.mongory
51
+ records.mongory
53
52
  .where(:age.gte => 18, :active => true)
54
53
  .any_of({ :tags => 'ruby' }, { :name => /^J/ })
55
54
  .to_a
56
55
  # => [{ "name" => "Jack", ... }]
57
56
 
58
- # 2. Direct JSON condition (e.g. rule payload from API / front-end)
57
+ # 2. Direct JSON condition (e.g. rule payload from API / database)
59
58
  rule = JSON.parse('{"age": {"$gte": 18}, "$or": [{"name": {"$regex": "^J"}}, {"name": "Bob"}]}')
60
59
  records.mongory.where(rule).pluck('name')
61
60
  # => ["Jack", "Bob"]
@@ -66,35 +65,37 @@ ADULT_RULE.match?(records.first)
66
65
  # => true
67
66
  ```
68
67
 
69
- ### Query Builder Methods
68
+ ## Why Mongory? (and When Not to Use It)
69
+
70
+ - **Use Mongory when**: rules are stored as data (DB/config/API/feature flags), shared between frontend TS and Ruby/Go/Python services, or complex enough that nested `select` blocks become unreadable and hard to debug without `trace`.
71
+ - **Don't use Mongory when**: your filter is a simple static `records.select { |r| r['age'] >= 18 }` hardcoded in Ruby, or when you need full SQL/MongoDB aggregation pipelines (`$group`, `$lookup`, `$project`).
72
+ - **vs `Mongoid::Matcher`**: `mongory` has zero external gem dependencies (no `mongoid`, `mongo`, or `activesupport` required), works on plain `Hash`/PORO/ActiveRecord objects, compiles queries once into C99 (`mongory-core`), and adds `explain`/`trace` trees.
70
73
 
71
- | Method | Description | Example |
72
- |--------|-------------|---------|
73
- | `where` | Adds an `$and` filter condition | `where(:age.gte => 18, status: 'active')` |
74
- | `any_of` | Adds an `$or` branch inside the current `$and` | `any_of({ role: 'admin' }, { :score.gte => 90 })` |
75
- | `or` | Combines the current query with `$or` conditions | `or({ age: 18 }, { name: 'Bob' })` |
76
- | `and` | Combines conditions with `$and` | `and({ :age.gte => 18 }, { active: true })` |
77
- | `not` | Negates a condition (`$not`) | `not(:status => 'banned')` |
78
- | `in` / `nin` | Matches values in / not in a list | `in(role: %w[admin editor])` |
79
- | `limit` | Limits processed records (executes at its position in the chain) | `limit(10)` |
80
- | `pluck` | Extracts one or more fields from matching records | `pluck(:name)` |
81
- | `with_context` | Passes shared context/options to matchers | `with_context(tenant: current_tenant)` |
74
+ ## Benchmark Snapshot
75
+
76
+ Measured on Apple M3 (macOS arm64, Ruby `4.0.5`, `100,000` records x 5 rounds; full details & script in [docs/performance.md](docs/performance.md)):
77
+
78
+ | Case | Plain Ruby `Array#count` | `Mongory::Matcher` (C99) | `Mongoid::Matcher` (`9.1.2`) | `Mongory` vs `Mongoid` |
79
+ |---|---:|---:|---:|---:|
80
+ | `simple` (`age >= 18`) | `63.1 ns/rec` | `77.9 ns/rec` | `3,224.5 ns/rec` | **41.4x faster** |
81
+ | `$or` (`age >= 18` or `status == "active"`) | `71.8 ns/rec` | `127.4 ns/rec` | `3,967.9 ns/rec` | **31.1x faster** |
82
+ | `in_array_field` (`tags $in ["ruby", "rust"]`) | `85.3 ns/rec` | `136.4 ns/rec` | `4,302.1 ns/rec` | **31.5x faster** |
83
+ | `large_in_500` (`name $in [500 items]`) | `62.9 ns/rec` | `115.8 ns/rec` | `97,351.9 ns/rec` | **840.7x faster** |
82
84
 
83
85
  ## Debugging: `explain`, `trace`, `explain_tree` & `trace_tree`
84
86
 
85
- Use `explain_tree` and `trace_tree` to inspect structured Ruby Hashes (for logging, JSON APIs, or UIs), or `explain` and `trace` to print those trees directly to STDOUT:
87
+ Mongory automatically sorts sibling conditions by cost (cheap `$eq`/`$exists` short-circuit before `$regex` or array scans). Inspect compiled plans or per-record `PASS`/`FAIL`/`SKIP` traces in CLI output or structured Ruby Hashes:
86
88
 
87
89
  ```ruby
88
90
  query = records.mongory
89
91
  .where(:age.gte => 18)
90
92
  .any_of({ status: 'active' }, { :name.regex => /^J/ })
91
93
 
92
- # Structured explain tree (Hash)
93
- plan = query.explain_tree
94
- # => { name: "Query", condition: ..., priority: ..., children: [...] }
94
+ query.explain # prints priority-sorted plan tree to STDOUT
95
+ plan = query.explain_tree # structured Hash (for logging / APIs / UIs)
95
96
 
96
- # Prints the explain tree to STDOUT
97
- query.explain
97
+ query.trace { |r| puts r['name'] } # prints per-record PASS/FAIL/SKIP trace
98
+ trees = query.trace_tree # Array<Hash> with :pass | :fail | :skip nodes
98
99
  ```
99
100
 
100
101
  ```text
@@ -108,44 +109,24 @@ And: {"age"=>{"$gte"=>18}, "$or"=>[{"status"=>"active"}, {"name"=>{"$regex"=>/^J
108
109
  └─ Regex: /^J/
109
110
  ```
110
111
 
111
- ```ruby
112
- # Structured trace trees across all records (Array<Hash>);
113
- # short-circuited branches are recursively expanded with result: :skip.
114
- trees = query.trace_tree
115
- # => [
116
- # {
117
- # name: "Query",
118
- # condition: ...,
119
- # record: { "name" => "Bob", "age" => 15, "status" => "inactive" },
120
- # result: :fail, # :pass | :fail | :skip
121
- # priority: ...,
122
- # children: [...]
123
- # },
124
- # ...
125
- # ]
126
-
127
- # Prints each record's trace tree to STDOUT and yields matching records
128
- query.trace { |record| puts record['name'] }
129
- ```
130
-
131
- Single-record structured tracing is also available on matchers directly via `matcher.explain_tree` and `matcher.trace_tree(record)` on `Mongory::Matcher`.
112
+ Single-record tracing is also available directly on matchers via `matcher.explain_tree` and `matcher.trace_tree(record)`.
132
113
 
133
- ## Supported Operators
114
+ ## Operators & Query Builder
134
115
 
135
116
  | Category | Operators | Notes |
136
- |----------|-----------|-------|
117
+ |---|---|---|
137
118
  | Comparison | `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte` | Cross-type `Integer`/`Float` equality; implicit `$elemMatch` on arrays |
138
- | Inclusion | `$in`, `$nin` | Scalar membership or array intersection |
119
+ | Inclusion | `$in`, `$nin` | Scalar membership or array intersection; O(1) hash lookup for `>= 16` items |
139
120
  | Logical | `$and`, `$or`, `$not` | Priority-sorted sibling evaluation with dynamic re-sorting |
140
- | Array | `$elemMatch`, `$every`, `$size` | `$every` requires a non-empty array where all elements match; `$size` accepts an integer or range object |
121
+ | Array | `$elemMatch`, `$every`, `$size` | `$every` requires non-empty array; `$size` accepts integer or nested matcher |
141
122
  | Existence | `$exists`, `$present` | `$present` checks non-nil and non-empty (`String`, `Array`, `Hash`) |
142
123
  | Regex | `$regex` (`$options`: `i`, `m`, `s`) | Accepts `Regexp` or pattern string with optional `$options` |
143
124
 
144
- > **Differences from MongoDB:** `$every` (returns `false` on `[]`) and `$present` are Mongory extensions; `$options` only permits `i`/`m`/`s`; unknown `$` operators raise `Mongory::TypeError`. See [`mongory-spec`](https://github.com/mongoryhq/mongory-spec#37-differences-from-mongodb-query-syntax).
125
+ Query builder methods: `where`, `any_of`, `or`, `and`, `not`, `in` / `nin`, `limit`, `pluck`, `with_context`.
145
126
 
146
- ## Custom Matchers & Configuration
127
+ > **Differences from MongoDB:** Mongory is MongoDB-style, not MongoDB-compatible. A nested object condition matches a subset of fields (use `$eq` for an exact document), several comparisons on one array field must hold for the same element, and negative indexes count from the end of an array. `$every`, `$present`, field-level `$and`/`$or`/`$nor`, and `$size` with operators are Mongory extensions. Full list with examples: [Differences from MongoDB](https://github.com/mongoryhq/mongory-spec/blob/main/docs/mongodb-differences.md). Unknown `$` operators raise `Mongory::TypeError`.
147
128
 
148
- Configure registered collection classes and converters in `Mongory.configure`:
129
+ ## Custom Matchers & Configuration
149
130
 
150
131
  ```ruby
151
132
  Mongory.configure do |mc|
@@ -153,11 +134,7 @@ Mongory.configure do |mc|
153
134
  mc.register(Array)
154
135
  mc.register(ActiveRecord::Relation)
155
136
  end
156
- ```
157
137
 
158
- Define a custom operator with `Mongory::Matchers::AbstractMatcher` (or run `rails g mongory:matcher class_in`):
159
-
160
- ```ruby
161
138
  class ClassInMatcher < Mongory::Matchers::AbstractMatcher
162
139
  def match(subject)
163
140
  @condition.any? { |klass| subject.is_a?(klass) }
@@ -174,12 +151,17 @@ Mongory::Matchers.register(:class_in, '$classIn', ClassInMatcher)
174
151
 
175
152
  ## Guides & Further Reading
176
153
 
154
+ - [Performance & Benchmarks](docs/performance.md)
177
155
  - [Handling Dots in Field Names](docs/field_names.md)
178
156
  - [Advanced Usage & Converters](docs/advanced_usage.md)
179
157
  - [Clang Bridge (C Extension Internals)](docs/clang_bridge.md)
180
- - [Performance & Benchmarks](docs/performance.md)
181
158
  - [Migration Guide](docs/migration.md)
182
159
 
160
+ ## Security & Untrusted Input
161
+
162
+ - **Engine protections**: Pure in-memory C99 evaluation (no SQL, no `$where`/`eval`), arena memory pool chunk limits, and compile-time depth/node budgets (`MaxDepth = 64`, `MaxNodes = 4096`).
163
+ - **Application responsibility**: When accepting query conditions from untrusted users, validate expected scalar types (to prevent operator injection such as `{"$ne" => nil}`), allowlist queryable fields, and configure `Regexp.timeout` (Ruby 3.2+) or restrict untrusted `$regex` patterns.
164
+
183
165
  ## Contributing & License
184
166
 
185
167
  Bug reports and pull requests are welcome on [GitHub](https://github.com/mongoryhq/mongory-rb). Everyone interacting in the project is expected to follow the [Code of Conduct](CODE_OF_CONDUCT.md).
data/docs/clang_bridge.md CHANGED
@@ -6,11 +6,11 @@ As of `mongory-rb v2.0.0`, Mongory uses the C99 [`mongory-core`](https://github.
6
6
  - C99-compatible compiler (`gcc` / `clang`)
7
7
  - CMake >= 3.12 (optional; only needed if you want to build `mongory-core` standalone or run its native tests)
8
8
 
9
- > Note: Precompiled native gems are distributed for Linux, macOS (`arm64` & `x86_64`), and Windows (Ruby 2.6–4.0). When compiling from source, Ruby's `mkmf` (`ext/mongory_ext/extconf.rb`) compiles `mongory-core` sources directly — CMake is not required for gem installation.
9
+ > Note: Precompiled native gems are distributed for Linux, macOS (`arm64` and `x86_64`), and Windows (Ruby 2.6-4.0). When compiling from source, Ruby's `mkmf` (`ext/mongory_ext/extconf.rb`) compiles `mongory-core` sources directly; CMake is not required for gem installation.
10
10
 
11
11
  ## Architecture
12
12
 
13
- The Clang bridge connects the Ruby DSL to `mongory-core` via a compact C layer exposing two key entry points:
13
+ The Clang bridge connects the Ruby DSL to `mongory-core` via a compact C layer exposing two entry points:
14
14
 
15
15
  - `Mongory::Matcher`: the compiled matcher class backed by `mongory-core`.
16
16
  - `Mongory::QueryBuilder`: the chainable Ruby DSL (`records.mongory.where(...)`) backed by `Mongory::Matcher`.
data/docs/performance.md CHANGED
@@ -8,17 +8,53 @@ Run the included benchmark script in `mongory-rb` to measure `Mongory::Matcher`
8
8
  ruby script/bench.rb
9
9
  ```
10
10
 
11
- ### Measured Results (Apple M3, macOS arm64, Ruby `4.0.5`, 100,000 records)
11
+ To include the `Mongoid::Matcher` comparison (optional, keeps `mongory` zero-dependency), install `mongoid` in a separate `GEM_PATH`:
12
12
 
13
- | Engine / Case | Simple (`age >= 18`) | `$or` (`age >= 18` or `status == "active"`) |
14
- |---|---|---|
15
- | Plain Ruby `Array#count` | `7.26 ms` (`72.6 ns/rec`) | `6.85 ms` (`68.5 ns/rec`) |
16
- | `Mongory::Matcher` (`mongory-core` C99) | `7.67 ms` (`76.7 ns/rec`) | `12.92 ms` (`129.2 ns/rec`) |
13
+ ```bash
14
+ gem install --install-dir /tmp/rb-bench-gems --no-document mongoid
15
+ GEM_PATH=/tmp/rb-bench-gems ruby script/bench.rb
16
+ ```
17
+
18
+ ### Measured Results (Apple M3, macOS arm64, Ruby `4.0.5`, 100,000 records x 5 rounds)
19
+
20
+ | Case | Plain Ruby `Array#count` | `Mongory::Matcher` (`mongory-core` C99) | `Mongoid::Matcher` (`mongoid 9.1.2`) | `Mongory` vs `Mongoid` |
21
+ |---|---:|---:|---:|---:|
22
+ | `simple` (`age >= 18`) | `6.31 ms` (`63.1 ns/rec`) | `7.79 ms` (`77.9 ns/rec`) | `322.45 ms` (`3,224.5 ns/rec`) | **41.4x faster** |
23
+ | `$or` (`age >= 18` or `status == "active"`) | `7.18 ms` (`71.8 ns/rec`) | `12.74 ms` (`127.4 ns/rec`) | `396.79 ms` (`3,967.9 ns/rec`) | **31.1x faster** |
24
+ | `in_array_field` (`tags $in ["ruby", "rust"]`) | `8.53 ms` (`85.3 ns/rec`) | `13.64 ms` (`136.4 ns/rec`) | `430.21 ms` (`4,302.1 ns/rec`) | **31.5x faster** |
25
+ | `large_in_500` (`name $in [500 items]`, O(1) hash) | `6.29 ms` (`62.9 ns/rec`) | `11.58 ms` (`115.8 ns/rec`) | `9,735.19 ms` (`97,351.9 ns/rec`) | **840.7x faster** |
26
+
27
+ ## Code Footprint & Runtime Memory
28
+
29
+ Measured on Apple M3 (`macOS arm64`, Ruby `4.0.5`) using `GC.stat` alongside macOS `malloc_zone_statistics` and `ru_maxrss` so native C heap allocations in `mongory-core` are captured alongside Ruby object allocations:
30
+
31
+ ### 1. Code Size & `require` Overhead (Median of 3 Subprocesses)
32
+
33
+ | Library | Production Source | Native Binary / Deps | `require` RSS Delta | `malloc` / Ruby Live Slots |
34
+ |---|---|---|---:|---:|
35
+ | **`mongory`** (`2.1.1`) | `2,392` LOC binding (26 files) + `7,277` LOC embedded `mongory-core` C99 | `mongory_ext.bundle` **`141.7 KB`**, **0 runtime deps** | **`+0.8 MiB`** | `+277.3 KiB` / **`+1,403` slots** |
36
+ | `mongoid` (`9.1.3`) | `1,743` matcher / `40,890` gem / **`244,692` LOC** across 19 gems | Pure Ruby + `bson`/`json`/`bigdecimal` (**19 gems**) | `+47.3 MiB` | `+23.3 MiB` / `+91,286` slots |
37
+
38
+ ### 2. Dataset & Compiled Matcher Retained Memory
39
+
40
+ - **Dataset Wrapper Overhead (`10,000` records)**: `Mongory::Matcher` evaluates plain Ruby `Hash`es directly (`40,007` live slots for 10k records). `Mongoid::Matcher` requires wrapping records in `Mongoid::Document` instances, adding **`+120,338` Ruby slots** and **`+2,361.6 KiB` malloc (`+241.8 B/rec`)**.
41
+ - **Compiled Matcher Retained Memory (`1,000` retained)**: Each `Mongory::Matcher` keeps a C99 arena + scratch pool (`4,687 B` + 5 slots for `simple`, `8,811 B` + 5 slots for `nested_and`, `137,372 B` + 6 slots for `large_in_500` O(1) hash table). `Mongoid::Matcher` interprets the query `Hash` on every call (`0 B` compiled AST).
42
+
43
+ ### 3. Match-Time Allocations (`10,000` records, GC disabled during single pass)
44
+
45
+ | Case | `Mongory::Matcher` | `Mongoid::Matcher` (`mongoid 9.1.3`) |
46
+ |---|---:|---:|
47
+ | `simple` (`age >= 18`) | **`7` Ruby objs** (`0.00/rec`), C `0.1 KiB` | `113,202` Ruby objs (`11.32/rec`) |
48
+ | `or` | **`2` Ruby objs** (`0.00/rec`), C `0.0 KiB` | `166,534` Ruby objs (`16.65/rec`) |
49
+ | `nested_and` | **`2` Ruby objs** (`0.00/rec`), C `0.0 KiB` | `179,672` Ruby objs (`17.97/rec`) |
50
+ | `in_array_field` | **`2` Ruby objs** (`0.00/rec`), C `0.0 KiB` | `172,502` Ruby objs (`17.25/rec`) |
51
+ | `large_in_500` | **`2` Ruby objs** (`0.00/rec`), C `0.0 KiB` | **`4,796,168` Ruby objs** (`479.62/rec`), `+5.6 MiB` malloc |
52
+ | `regex` | **`2` Ruby objs** (`0.00/rec`), C `0.0 KiB` | `310,002` Ruby objs (`31.00/rec`), `+10.2 MiB` malloc |
17
53
 
18
- > For cross-language benchmarks (`mongory-js`, `mongory-go`), see [Mongory Central](https://mongoryhq.github.io/mongory-central/#benchmarks).
54
+ > For cross-language benchmarks (`mongory-go`, `mongory-js`, `mongory-py`), see [Mongory Central](https://mongoryhq.github.io/mongory-central/?ref=mongory-rb-perf#benchmarks).
19
55
 
20
56
  ## Optimization Tips
21
57
 
22
- - **Reuse `Mongory::Matcher` Instances**: Compile once with `Mongory::Matcher.new(condition)` and call `#match?` across records to avoid recompiling the condition tree.
58
+ - **Reuse `Mongory::Matcher` Instances**: Compile once with `Mongory::Matcher.new(condition)` (or `Mongory.compile(condition)`) and call `#match?` across records to avoid recompiling the condition tree.
23
59
  - **Priority Ordering & Dynamic Re-Sorting**: Mongory automatically orders cheaper equality/existence checks before regex or array scans, and re-sorts siblings if a lazy array matcher is constructed.
24
60
  - **Inspect Plans**: Use `.explain` / `.trace` to verify cheap fields short-circuit early.
@@ -66,6 +66,13 @@ elsif RbConfig::CONFIG['host_os'] !~ /mswin|mingw|android|haiku/
66
66
  $LOCAL_LIBS << ' -lpthread' unless $LIBS.include?('-lpthread') || $LOCAL_LIBS.include?('-lpthread')
67
67
  end
68
68
 
69
+ portable_linux_link = ENV['MONGORY_PORTABLE_LINK'] == '1' && RbConfig::CONFIG['host_os'] =~ /linux/
70
+ if portable_linux_link
71
+ # Precompiled Linux binaries resolve Ruby C-API symbols against whichever interpreter dlopens them,
72
+ # supporting both `--enable-shared` and `--disable-shared` host Rubies without `DT_NEEDED: libruby.so`.
73
+ scrub_flags_from_config!(%w(DLDFLAGS LDFLAGS LIBS), %w(-Wl,--no-undefined --no-undefined -Wl,-z,defs))
74
+ end
75
+
69
76
  # Let mkmf generate rules by listing all sources and corresponding objects
70
77
  $INCFLAGS << ' -I.'
71
78
  $INCFLAGS << " -I#{File.join(core_src_dir, 'foundations')}"
@@ -96,6 +103,14 @@ if RbConfig::CONFIG['host_os'] =~ /darwin/
96
103
  LIBRUBY =
97
104
  LIBS =
98
105
  MAKE
106
+ elsif portable_linux_link
107
+ mk << <<~'MAKE'
108
+ # --- portable linux: resolve Ruby symbols from the host process at dlopen time ---
109
+ LIBRUBYARG =
110
+ LIBRUBYARG_SHARED =
111
+ LIBRUBYARG_STATIC =
112
+ LIBRUBY =
113
+ MAKE
99
114
  end
100
115
 
101
116
  # rubocop:disable Layout/HeredocIndentation
@@ -65,21 +65,6 @@ typedef bool (*mongory_regex_options_func)(mongory_memory_pool *pool, mongory_va
65
65
  */
66
66
  typedef char* (*mongory_regex_stringify_func)(mongory_memory_pool *pool, mongory_value *pattern);
67
67
 
68
- /**
69
- * @brief Function pointer type for deep conversion of an external value to a
70
- * mongory_value.
71
- *
72
- * "Deep" implies that if the external value is a complex type (e.g., a struct
73
- * representing a document or array), its contents should also be converted.
74
- *
75
- * @param pool The memory pool to use for allocating the new mongory_value and
76
- * its data.
77
- * @param value A pointer to the external value to convert.
78
- * @return mongory_value* A new mongory_value representing the converted data,
79
- * or NULL on failure.
80
- */
81
- typedef mongory_value *(*mongory_deep_convert_func)(mongory_memory_pool *pool, void *value);
82
-
83
68
  /**
84
69
  * @brief Function pointer type for shallow conversion of an external value to a
85
70
  * mongory_value.
@@ -94,21 +79,6 @@ typedef mongory_value *(*mongory_deep_convert_func)(mongory_memory_pool *pool, v
94
79
  */
95
80
  typedef mongory_value *(*mongory_shallow_convert_func)(mongory_memory_pool *pool, void *value);
96
81
 
97
- /**
98
- * @brief Function pointer type for recovering an external value from a
99
- * mongory_value.
100
- *
101
- * This is the reverse of a conversion, intended to get back the original
102
- * external data representation if it was stored or wrapped.
103
- *
104
- * @param pool The memory pool (can be used if recovery involves allocation,
105
- * though often it might just retrieve a stored pointer).
106
- * @param value The mongory_value from which to recover the external data.
107
- * @return void* A pointer to the recovered external value, or NULL if not
108
- * possible.
109
- */
110
- typedef void *(*mongory_recover_func)(mongory_memory_pool *pool, mongory_value *value);
111
-
112
82
  /**
113
83
  * @brief Initializes the Mongory library.
114
84
  *
@@ -154,24 +124,12 @@ void mongory_regex_options_func_set(mongory_regex_options_func func);
154
124
  */
155
125
  void mongory_regex_stringify_func_set(mongory_regex_stringify_func func);
156
126
 
157
- /**
158
- * @brief Sets the custom deep value conversion function.
159
- * @param deep_convert The function to use for deep conversions.
160
- */
161
- void mongory_value_converter_deep_convert_set(mongory_deep_convert_func deep_convert);
162
-
163
127
  /**
164
128
  * @brief Sets the custom shallow value conversion function.
165
129
  * @param shallow_convert The function to use for shallow conversions.
166
130
  */
167
131
  void mongory_value_converter_shallow_convert_set(mongory_shallow_convert_func shallow_convert);
168
132
 
169
- /**
170
- * @brief Sets the custom value recovery function.
171
- * @param recover The function to use for recovering external values.
172
- */
173
- void mongory_value_converter_recover_set(mongory_recover_func recover);
174
-
175
133
  /**
176
134
  * @brief Function pointer type for matching a value against an external matcher.
177
135
  * @param external_matcher The external reference to the matcher.
@@ -185,7 +143,7 @@ typedef struct mongory_matcher_custom_context {
185
143
 
186
144
  void mongory_custom_matcher_match_func_set(bool (*match)(void *external_matcher, mongory_value *value));
187
145
  void mongory_custom_matcher_build_func_set(mongory_matcher_custom_context *(*build)(char *key, mongory_value *condition, void *extern_ctx));
188
- void mongory_custom_matcher_lookup_func_set(bool (*lookup)(char *key));
146
+ void mongory_custom_matcher_lookup_func_set(bool (*lookup)(char *key, void *extern_ctx));
189
147
 
190
148
  void mongory_matcher_trace_result_colorful_set(bool colorful);
191
149
 
@@ -214,4 +172,31 @@ void mongory_max_nodes_set(size_t max_nodes);
214
172
  */
215
173
  size_t mongory_max_nodes_get(void);
216
174
 
175
+ /**
176
+ * @brief Function pointer type for global heap allocations outside memory pools
177
+ * (e.g., memory pool internals, chunk buffers, adapter contexts).
178
+ * @param size Number of bytes to allocate.
179
+ * @return Pointer to allocated memory, or NULL on failure.
180
+ */
181
+ typedef void *(*mongory_global_malloc_func)(size_t size);
182
+
183
+ /**
184
+ * @brief Function pointer type for freeing memory allocated via mongory_global_malloc_func.
185
+ * @param ptr Pointer to free (may be NULL).
186
+ */
187
+ typedef void (*mongory_global_free_func)(void *ptr);
188
+
189
+ /**
190
+ * @brief Sets the global allocator used for internal non-pool allocations.
191
+ * Pass NULL to restore the default allocator (`malloc`).
192
+ * Must be configured while no pools allocated with a different allocator are live.
193
+ */
194
+ void mongory_global_malloc_set(mongory_global_malloc_func func);
195
+
196
+ /**
197
+ * @brief Sets the global deallocator paired with `mongory_global_malloc_set`.
198
+ * Pass NULL to restore the default deallocator (`free`).
199
+ */
200
+ void mongory_global_free_set(mongory_global_free_func func);
201
+
217
202
  #endif /* MONGORY_FOUNDATIONS_CONFIG_H */
@@ -21,7 +21,6 @@ typedef struct mongory_memory_pool mongory_memory_pool;
21
21
 
22
22
  #define MG_ALLOC(p, n) (p->alloc(p, n))
23
23
  #define MG_ALLOC_PTR(p, t) ((t*)MG_ALLOC(p, sizeof(t)))
24
- #define MG_ALLOC_OBJ(p, t) ((t)MG_ALLOC(p, sizeof(t)))
25
24
  #define MG_ALLOC_ARY(p, t, n) ((t*)MG_ALLOC(p, sizeof(t) * (n)))
26
25
  /**
27
26
  * @struct mongory_memory_pool
@@ -19,10 +19,9 @@ typedef struct mongory_matcher mongory_matcher;
19
19
  /**
20
20
  * @brief Creates a new generic matcher instance.
21
21
  *
22
- * This function typically serves as a high-level entry point for creating
23
- * matchers. In the current implementation, it delegates to
24
- * `mongory_matcher_condition_new`, implying that conditions are often
25
- * table-based (similar to query documents).
22
+ * Expands unescaped dotted field paths (e.g. `"a.b.c": 1` -> `{"a": {"b": {"c": 1}}}`),
23
+ * unescapes `\.` into literal `.`, and preserves leaf collisions via `$and` before
24
+ * building the matcher tree.
26
25
  *
27
26
  * @param pool The memory pool to use for the matcher's allocations.
28
27
  * @param condition A `mongory_value` representing the condition for this
@@ -15,6 +15,7 @@
15
15
  #include <mongory-core/foundations/memory_pool.h>
16
16
  #include <stdarg.h>
17
17
  #include <mongory-core/foundations/value.h>
18
+ #include "utils.h"
18
19
 
19
20
  /**
20
21
  * @def MONGORY_ARRAY_INIT_SIZE
@@ -36,6 +37,9 @@
36
37
  * allocation failure).
37
38
  */
38
39
  bool mongory_array_resize(mongory_array *self, size_t size) {
40
+ if (!self || !mongory_validate_pool(self->pool)) {
41
+ return false;
42
+ }
39
43
  mongory_array_private *internal = (mongory_array_private *)self;
40
44
  if (size > SIZE_MAX / sizeof(mongory_value *)) {
41
45
  self->pool->error = &MONGORY_ALLOC_ERROR;
@@ -104,6 +108,9 @@ static inline bool mongory_array_grow_if_needed(mongory_array *self, size_t size
104
108
  * @return true if iteration completed, false if callback stopped it.
105
109
  */
106
110
  static inline bool mongory_array_each(mongory_array *self, void *acc, mongory_array_callback_func func) {
111
+ if (!self || !func) {
112
+ return false;
113
+ }
107
114
  mongory_array_private *internal = (mongory_array_private *)self;
108
115
  for (size_t i = 0; i < self->count; i++) {
109
116
  mongory_value *item = internal->items[i];
@@ -122,6 +129,9 @@ static inline bool mongory_array_each(mongory_array *self, void *acc, mongory_ar
122
129
  * @return true if successful, false on failure (e.g., memory allocation).
123
130
  */
124
131
  static inline bool mongory_array_push(mongory_array *self, mongory_value *value) {
132
+ if (!self || !self->pool) {
133
+ return false;
134
+ }
125
135
  mongory_array_private *internal = (mongory_array_private *)self;
126
136
  // Ensure there's space for one more element (current count).
127
137
  if (!mongory_array_grow_if_needed(self, self->count)) {
@@ -139,10 +149,10 @@ static inline bool mongory_array_push(mongory_array *self, mongory_value *value)
139
149
  * @return Pointer to the mongory_value, or NULL if index is out of bounds.
140
150
  */
141
151
  static inline mongory_value *mongory_array_get(mongory_array *self, size_t index) {
142
- mongory_array_private *internal = (mongory_array_private *)self;
143
- if (index >= self->count) {
144
- return NULL; // Index out of bounds.
152
+ if (!self || index >= self->count) {
153
+ return NULL; // Invalid array or index out of bounds.
145
154
  }
155
+ mongory_array_private *internal = (mongory_array_private *)self;
146
156
  return internal->items[index];
147
157
  }
148
158
 
@@ -158,6 +168,9 @@ static inline mongory_value *mongory_array_get(mongory_array *self, size_t index
158
168
  * @return true if successful, false on failure (e.g., memory allocation).
159
169
  */
160
170
  static inline bool mongory_array_set(mongory_array *self, size_t index, mongory_value *value) {
171
+ if (!self || !self->pool) {
172
+ return false;
173
+ }
161
174
  mongory_array_private *internal = (mongory_array_private *)self;
162
175
  // Ensure capacity for the given 0-based index.
163
176
  if (!mongory_array_grow_if_needed(self, index)) {
@@ -177,9 +190,16 @@ static inline bool mongory_array_set(mongory_array *self, size_t index, mongory_
177
190
  }
178
191
 
179
192
  mongory_array *mongory_array_new_with_capacity(mongory_memory_pool *pool, size_t capacity) {
193
+ if (!mongory_validate_pool(pool)) {
194
+ return NULL;
195
+ }
180
196
  if (capacity == 0) {
181
197
  capacity = MONGORY_ARRAY_INIT_SIZE;
182
198
  }
199
+ if (capacity > SIZE_MAX / sizeof(mongory_value *)) {
200
+ pool->error = &MONGORY_ALLOC_ERROR;
201
+ return NULL;
202
+ }
183
203
  // First, allocate the private structure that holds all array metadata.
184
204
  mongory_array_private *internal = MG_ALLOC_PTR(pool, mongory_array_private);
185
205
  if (!internal) {
@@ -248,7 +268,7 @@ mongory_array *mongory_array_nested_wrap(mongory_memory_pool *pool, int argc, ..
248
268
  bool ok = true;
249
269
  for (int i = 0; i < argc; i++) {
250
270
  mongory_value *value = va_arg(args, mongory_value *);
251
- if (ok && (!value || !array->push(array, value))) {
271
+ if (ok && (!MONGORY_VALIDATE_PTR(pool, value) || !array->push(array, value))) {
252
272
  ok = false;
253
273
  }
254
274
  }
@@ -326,9 +346,12 @@ mongory_array *mongory_array_sort_by(mongory_array *self, mongory_memory_pool *t
326
346
  }
327
347
 
328
348
  bool mongory_array_includes(mongory_array *self, mongory_value *value) {
349
+ if (!self || !value) {
350
+ return false;
351
+ }
329
352
  for (size_t i = 0; i < self->count; i++) {
330
353
  mongory_value *item = self->get(self, i);
331
- if (item->comp(item, value) == 0) {
354
+ if (item && item->comp && item->comp(item, value) == 0) {
332
355
  return true;
333
356
  }
334
357
  }