mongory 2.1.1 → 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 (52) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +22 -0
  3. data/README.md +45 -74
  4. data/docs/clang_bridge.md +2 -2
  5. data/docs/performance.md +28 -1
  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 +67 -118
  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/coverage.rb +84 -0
  50. metadata +7 -7
  51. data/ext/mongory_ext/mongory-core/src/matchers/matcher_explainable.c +0 -117
  52. 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: f41aa0bea7de774e96bbc53a478fd90b5cf12d72fa2684d360424e3ac745677f
4
- data.tar.gz: 372350cf13aa2735959b627fd60fc20d6e72dd729cb6b2d1cc288620b1e8d59a
3
+ metadata.gz: 8d49ac9069e9ac8dbf8c6541f16f3643fd00b792bf3294767f7157bf3a926338
4
+ data.tar.gz: 4bd8cfd6d58e5ea66ee647ddbe4fd248101532ba85836b120aa4278c75cc9a49
5
5
  SHA512:
6
- metadata.gz: d09473d0e1dd40090ca9e65a0598b8f75e117e265415aaba2c4ea74f8c2c013a9710faed1e698e7dfdb70c9d3ece87e1a3e21100628f3c0815b7cc9bafbf339e
7
- data.tar.gz: c06699ee0bae9d81395e5a684d5261fe95aac83378cf739db4eed0a327391071d92d6bf5a98d58541a9f0bae1b189935cf5f09a0e29cb67ba3370169ea5db273
6
+ metadata.gz: 23ae867269c6306befa5ebff3ce5ff31047ac80b70861dbfdc98816fd5c42857b320caecffddf00fb82e72cef63d1441d2b0d4e1a742f05ebeedd397013ed521
7
+ data.tar.gz: c9b3fa0f98cfbc66aba4b3da02cf068622592d0232a2c61702c8c086aa4adce4e580f5846b0342c3c67af0f382b6fb4cfc960de71edc67a2f6b3079cea014438
data/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
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
+
3
25
  ## [2.1.1] - 2026-11-25
4
26
 
5
27
  ### Performance
data/README.md CHANGED
@@ -1,27 +1,19 @@
1
1
  # Mongory (Ruby)
2
2
 
3
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/)
4
5
  [![CI](https://github.com/mongoryhq/mongory-rb/actions/workflows/main.yml/badge.svg)](https://github.com/mongoryhq/mongory-rb/actions/workflows/main.yml)
5
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)
6
7
  ![Ruby](https://img.shields.io/badge/Ruby-2.6%2B-CC342D)
7
8
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
8
9
 
9
- **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).
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).
10
11
 
11
- **[Try the Interactive Playground & Visual Explain/Trace Debugger ↗](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)**
12
13
 
13
- [![Mongory Playground & Visual Trace](https://mongoryhq.github.io/mongory-central/playground-trace.png)](https://mongoryhq.github.io/mongory-central/)
14
+ [![Mongory Playground & Visual Trace](https://mongoryhq.github.io/mongory-central/playground-trace.png)](https://mongoryhq.github.io/mongory-central/?ref=mongory-rb-readme)
14
15
 
15
- > **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.
16
- > **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)
17
-
18
- ## Features
19
-
20
- - **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.
21
- - **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`).
22
- - **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`.
23
- - **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`.
24
- - **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)
25
17
 
26
18
  ## Installation
27
19
 
@@ -31,13 +23,14 @@ gem install mongory
31
23
  gem 'mongory'
32
24
  ```
33
25
 
34
- 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`.
35
27
 
36
- ```bash
37
- rails g mongory:install
38
- ```
28
+ <details>
29
+ <summary>Platform note (Apple Silicon system Ruby / source builds)</summary>
30
+
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.
39
32
 
40
- > **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.
33
+ </details>
41
34
 
42
35
  ## Quick Start
43
36
 
@@ -49,19 +42,19 @@ Mongory.register(Array)
49
42
  Mongory.enable_symbol_snippets!
50
43
 
51
44
  records = [
52
- { 'name' => 'Jack', 'age' => 18, 'tags' => %w[ruby go], 'active' => true },
53
- { 'name' => 'Jill', 'age' => 15, 'tags' => %w[js], 'active' => true },
54
- { '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 }
55
48
  ]
56
49
 
57
50
  # 1. Chainable DSL with symbol operator snippets
58
- matched = records.mongory
51
+ records.mongory
59
52
  .where(:age.gte => 18, :active => true)
60
53
  .any_of({ :tags => 'ruby' }, { :name => /^J/ })
61
54
  .to_a
62
55
  # => [{ "name" => "Jack", ... }]
63
56
 
64
- # 2. Direct JSON condition (e.g. rule payload from API / front-end)
57
+ # 2. Direct JSON condition (e.g. rule payload from API / database)
65
58
  rule = JSON.parse('{"age": {"$gte": 18}, "$or": [{"name": {"$regex": "^J"}}, {"name": "Bob"}]}')
66
59
  records.mongory.where(rule).pluck('name')
67
60
  # => ["Jack", "Bob"]
@@ -72,35 +65,37 @@ ADULT_RULE.match?(records.first)
72
65
  # => true
73
66
  ```
74
67
 
75
- ### Query Builder Methods
68
+ ## Why Mongory? (and When Not to Use It)
76
69
 
77
- | Method | Description | Example |
78
- |--------|-------------|---------|
79
- | `where` | Adds an `$and` filter condition | `where(:age.gte => 18, status: 'active')` |
80
- | `any_of` | Adds an `$or` branch inside the current `$and` | `any_of({ role: 'admin' }, { :score.gte => 90 })` |
81
- | `or` | Combines the current query with `$or` conditions | `or({ age: 18 }, { name: 'Bob' })` |
82
- | `and` | Combines conditions with `$and` | `and({ :age.gte => 18 }, { active: true })` |
83
- | `not` | Negates a condition (`$not`) | `not(:status => 'banned')` |
84
- | `in` / `nin` | Matches values in / not in a list | `in(role: %w[admin editor])` |
85
- | `limit` | Limits processed records (executes at its position in the chain) | `limit(10)` |
86
- | `pluck` | Extracts one or more fields from matching records | `pluck(:name)` |
87
- | `with_context` | Passes shared context/options to matchers | `with_context(tenant: current_tenant)` |
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.
73
+
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** |
88
84
 
89
85
  ## Debugging: `explain`, `trace`, `explain_tree` & `trace_tree`
90
86
 
91
- 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:
92
88
 
93
89
  ```ruby
94
90
  query = records.mongory
95
91
  .where(:age.gte => 18)
96
92
  .any_of({ status: 'active' }, { :name.regex => /^J/ })
97
93
 
98
- # Structured explain tree (Hash)
99
- plan = query.explain_tree
100
- # => { 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)
101
96
 
102
- # Prints the explain tree to STDOUT
103
- 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
104
99
  ```
105
100
 
106
101
  ```text
@@ -114,44 +109,24 @@ And: {"age"=>{"$gte"=>18}, "$or"=>[{"status"=>"active"}, {"name"=>{"$regex"=>/^J
114
109
  └─ Regex: /^J/
115
110
  ```
116
111
 
117
- ```ruby
118
- # Structured trace trees across all records (Array<Hash>);
119
- # short-circuited branches are recursively expanded with result: :skip.
120
- trees = query.trace_tree
121
- # => [
122
- # {
123
- # name: "Query",
124
- # condition: ...,
125
- # record: { "name" => "Bob", "age" => 15, "status" => "inactive" },
126
- # result: :fail, # :pass | :fail | :skip
127
- # priority: ...,
128
- # children: [...]
129
- # },
130
- # ...
131
- # ]
132
-
133
- # Prints each record's trace tree to STDOUT and yields matching records
134
- query.trace { |record| puts record['name'] }
135
- ```
136
-
137
- 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)`.
138
113
 
139
- ## Supported Operators
114
+ ## Operators & Query Builder
140
115
 
141
116
  | Category | Operators | Notes |
142
- |----------|-----------|-------|
117
+ |---|---|---|
143
118
  | Comparison | `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte` | Cross-type `Integer`/`Float` equality; implicit `$elemMatch` on arrays |
144
- | Inclusion | `$in`, `$nin` | Scalar membership or array intersection |
119
+ | Inclusion | `$in`, `$nin` | Scalar membership or array intersection; O(1) hash lookup for `>= 16` items |
145
120
  | Logical | `$and`, `$or`, `$not` | Priority-sorted sibling evaluation with dynamic re-sorting |
146
- | 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 |
147
122
  | Existence | `$exists`, `$present` | `$present` checks non-nil and non-empty (`String`, `Array`, `Hash`) |
148
123
  | Regex | `$regex` (`$options`: `i`, `m`, `s`) | Accepts `Regexp` or pattern string with optional `$options` |
149
124
 
150
- > **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`.
151
126
 
152
- ## 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`.
153
128
 
154
- Configure registered collection classes and converters in `Mongory.configure`:
129
+ ## Custom Matchers & Configuration
155
130
 
156
131
  ```ruby
157
132
  Mongory.configure do |mc|
@@ -159,11 +134,7 @@ Mongory.configure do |mc|
159
134
  mc.register(Array)
160
135
  mc.register(ActiveRecord::Relation)
161
136
  end
162
- ```
163
137
 
164
- Define a custom operator with `Mongory::Matchers::AbstractMatcher` (or run `rails g mongory:matcher class_in`):
165
-
166
- ```ruby
167
138
  class ClassInMatcher < Mongory::Matchers::AbstractMatcher
168
139
  def match(subject)
169
140
  @condition.any? { |klass| subject.is_a?(klass) }
@@ -180,10 +151,10 @@ Mongory::Matchers.register(:class_in, '$classIn', ClassInMatcher)
180
151
 
181
152
  ## Guides & Further Reading
182
153
 
154
+ - [Performance & Benchmarks](docs/performance.md)
183
155
  - [Handling Dots in Field Names](docs/field_names.md)
184
156
  - [Advanced Usage & Converters](docs/advanced_usage.md)
185
157
  - [Clang Bridge (C Extension Internals)](docs/clang_bridge.md)
186
- - [Performance & Benchmarks](docs/performance.md)
187
158
  - [Migration Guide](docs/migration.md)
188
159
 
189
160
  ## Security & Untrusted Input
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
@@ -24,7 +24,34 @@ GEM_PATH=/tmp/rb-bench-gems ruby script/bench.rb
24
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
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
26
 
27
- > For cross-language benchmarks (`mongory-go`, `mongory-js`, `mongory-py`), see [Mongory Central](https://mongoryhq.github.io/mongory-central/#benchmarks).
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 |
53
+
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).
28
55
 
29
56
  ## Optimization Tips
30
57
 
@@ -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
  }