nedb-engine 0.1.0__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Interchained
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.4
2
+ Name: nedb-engine
3
+ Version: 0.1.0
4
+ Summary: NEDB — a versioned, self-compressing, time-traveling embedded database (replay-protected, idempotent, relational, searchable).
5
+ Author: Interchained
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/interchained/nedb
8
+ Project-URL: Repository, https://github.com/interchained/nedb
9
+ Keywords: database,embedded,mvcc,time-travel,versioning,compression,dedup,graph,search,redis,git
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Rust
15
+ Classifier: Topic :: Database :: Database Engines/Servers
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
21
+ <div align="center">
22
+
23
+ # NEDB
24
+
25
+ **A versioned, self-compressing, time-traveling embedded database.**
26
+
27
+ Replay-protected · idempotent · relational · filterable · sortable · searchable · provable.
28
+ One Rust core → ships to **PyPI** and **npm** from a single source.
29
+
30
+ </div>
31
+
32
+ ---
33
+
34
+ ## Why NEDB
35
+
36
+ Redis is fast because it's in-memory and simple — but relations are hand-rolled, history is gone the moment you overwrite, and every call pays a network hop. NEDB keeps the speed and adds the things real systems actually need:
37
+
38
+ - **Faster-than-Redis latency where it's honest to claim it** — NEDB runs **embedded, in-process**, so point reads pay *no socket hop*. The networked server (`nedbd`, RESP-compatible) competes on the Rust core's merits.
39
+ - **Replay protection + idempotency in the core, not the app.** Every write carries a strictly-monotonic per-client nonce and an optional idempotency key. Retries are no-ops; stale/out-of-order ops are rejected. This is built into one **hash-chained, append-only log**.
40
+ - **Time-travel.** Read the database *exactly as it existed* at any past sequence — `AS OF seq`. Debugging, audit, MVCC snapshots, and deterministic replay all fall out of the same log.
41
+ - **First-class relations.** Adjacency-list graph edges with O(1) traversal — *and the graph time-travels too*.
42
+ - **Filter / sort / search.** Equality, ordered, and full-text inverted indexes, maintained incrementally.
43
+ - **git-style files with maximum compression.** Content-defined chunking + content-addressed dedup + temperature tiers (fast warm codec, max-ratio cold archival). Every file version has a Merkle root you can **anchor on-chain**.
44
+
45
+ > **The keystone:** one nonce-enforced append-only log is the substrate for idempotency, replay protection, crash recovery, MVCC, *and* time-travel — simultaneously.
46
+
47
+ ---
48
+
49
+ ## Quickstart (Python reference engine — runs today, zero build)
50
+
51
+ ```bash
52
+ git clone https://github.com/interchained/nedb && cd nedb
53
+ pip install -e . # pure-Python reference; no toolchain needed
54
+ python3 examples/demo.py # see every feature
55
+ python3 tests/test_nedb.py # 10/10 invariants
56
+ ```
57
+
58
+ ```python
59
+ from nedb import NEDB
60
+
61
+ db = NEDB()
62
+ db.create_index("users", "status", "eq")
63
+ db.create_index("users", "age", "ordered")
64
+ db.create_index("users", "bio", "search")
65
+
66
+ db.put("users", "alice", {"name": "Alice", "age": 31, "status": "active",
67
+ "city": "Austin", "bio": "rust systems hacker"})
68
+
69
+ # Idempotent, replay-protected write (safe to retry forever):
70
+ db.put("orders", "o1", {"total": 42}, client="checkout", nonce=7, idem="charge-o1")
71
+
72
+ # NQL — filter + sort
73
+ db.query('FROM users WHERE age >= 25 AND status = "active" ORDER BY age DESC')
74
+
75
+ # Full-text search
76
+ db.query('FROM users SEARCH "rust"')
77
+
78
+ # Relations + graph traversal
79
+ db.link("users:alice", "follows", "users:bob")
80
+ db.q("users").where("_id", "=", "alice").traverse("follows").run()
81
+
82
+ # Time-travel
83
+ s = db.seq
84
+ db.put("users", "alice", {"name": "Alice", "city": "Lisbon", "age": 31, "status": "active"})
85
+ db.get("users", "alice", as_of=s)["city"] # -> "Austin"
86
+
87
+ # git-style files with Cascade compression + provable history
88
+ v1 = db.put_file("notes.txt", open("notes.txt","rb").read())
89
+ db.file_root("notes.txt", v1) # Merkle root — anchorable on ITC
90
+ ```
91
+
92
+ ---
93
+
94
+ ## NQL — the NEDB Query Language
95
+
96
+ One small grammar; the Rust parser is the single source of truth so Python and Node share identical semantics. A fluent builder compiles to the same plan.
97
+
98
+ ```
99
+ FROM <collection>
100
+ [ AS OF <seq> ]
101
+ [ WHERE <field> <op> <value> (AND ...)* ] op ∈ = != < <= > >=
102
+ [ SEARCH "<text>" ]
103
+ [ ORDER BY <field> [ASC|DESC] ]
104
+ [ TRAVERSE <relation> ]
105
+ [ LIMIT <n> ]
106
+ ```
107
+
108
+ ---
109
+
110
+ ## What's measured (reference engine, pure Python, 2 vCPU)
111
+
112
+ | Operation | Result |
113
+ |---|---|
114
+ | GET (embedded, in-process) | **~1.2M ops/s** (~800 ns/op) |
115
+ | SET (logged + indexed) | ~77K ops/s |
116
+ | Indexed query latency | ~75 µs |
117
+ | File compression — warm (zlib stand-in) | **39.9×** |
118
+ | File compression — cold (LZMA archival) | **88.9×** |
119
+ | Cross-version dedup | 20 of 22 chunks reused on edit |
120
+
121
+ The reference engine proves the **architecture**. The Rust core (`rust/`) is the speed target — see `bench/bench_redis.py` for the embedded-vs-Redis harness.
122
+
123
+ ---
124
+
125
+ ## Architecture
126
+
127
+ ```
128
+ ┌──────────────────────────────────────────────┐
129
+ put/del → │ OpLog (append-only · BLAKE3 hash chain · │ ← single source of truth
130
+ link │ per-client nonce · idempotency keys) │
131
+ └───────────────┬──────────────────────────────┘
132
+ deterministic fold │ (state = pure function of the log)
133
+ ┌──────────────┬───────┴────────┬───────────────────┐
134
+ ▼ ▼ ▼ ▼
135
+ MVCC store Relations Indexes BlobStore (Cascade)
136
+ (time-travel) (graph, AS OF) eq/ordered/search CDC+dedup+tiers, Merkle roots
137
+ ```
138
+
139
+ One Rust core (`nedb-core`) → **PyO3** wheels (PyPI) and **napi-rs** binaries (npm), plus a future `nedbd` server (RESP-compatible) and a WASM build for browser/edge.
140
+
141
+ Full design: [`docs/SPEC.md`](docs/SPEC.md).
142
+
143
+ ---
144
+
145
+ ## Repo layout
146
+
147
+ ```
148
+ nedb/ pure-Python reference engine (this is what `pip install` ships today)
149
+ rust/ production core — nedb-core + nedb-py (PyO3) + nedb-node (napi-rs)
150
+ examples/demo.py end-to-end walkthrough
151
+ tests/ invariant tests
152
+ bench/ embedded micro-bench + Redis head-to-head harness
153
+ docs/SPEC.md architecture specification
154
+ .github/ release CI → PyPI + npm on tag
155
+ ```
156
+
157
+ ## Roadmap
158
+
159
+ - [x] Reference engine: log, MVCC, relations, indexes, NQL, Cascade, Merkle
160
+ - [ ] Rust core parity + criterion benches + `cargo test`
161
+ - [ ] PyO3 wheels + napi-rs binaries published on tag
162
+ - [ ] `nedbd` server: RESP-compatible + native protocol
163
+ - [ ] Similarity-picked deltas + schema-aware columnar transforms
164
+ - [ ] On-chain (ITC) root anchoring; WASM build
165
+
166
+ ## License
167
+
168
+ Apache-2.0. Part of the [Interchained](https://github.com/interchained) ecosystem.
@@ -0,0 +1,148 @@
1
+ <div align="center">
2
+
3
+ # NEDB
4
+
5
+ **A versioned, self-compressing, time-traveling embedded database.**
6
+
7
+ Replay-protected · idempotent · relational · filterable · sortable · searchable · provable.
8
+ One Rust core → ships to **PyPI** and **npm** from a single source.
9
+
10
+ </div>
11
+
12
+ ---
13
+
14
+ ## Why NEDB
15
+
16
+ Redis is fast because it's in-memory and simple — but relations are hand-rolled, history is gone the moment you overwrite, and every call pays a network hop. NEDB keeps the speed and adds the things real systems actually need:
17
+
18
+ - **Faster-than-Redis latency where it's honest to claim it** — NEDB runs **embedded, in-process**, so point reads pay *no socket hop*. The networked server (`nedbd`, RESP-compatible) competes on the Rust core's merits.
19
+ - **Replay protection + idempotency in the core, not the app.** Every write carries a strictly-monotonic per-client nonce and an optional idempotency key. Retries are no-ops; stale/out-of-order ops are rejected. This is built into one **hash-chained, append-only log**.
20
+ - **Time-travel.** Read the database *exactly as it existed* at any past sequence — `AS OF seq`. Debugging, audit, MVCC snapshots, and deterministic replay all fall out of the same log.
21
+ - **First-class relations.** Adjacency-list graph edges with O(1) traversal — *and the graph time-travels too*.
22
+ - **Filter / sort / search.** Equality, ordered, and full-text inverted indexes, maintained incrementally.
23
+ - **git-style files with maximum compression.** Content-defined chunking + content-addressed dedup + temperature tiers (fast warm codec, max-ratio cold archival). Every file version has a Merkle root you can **anchor on-chain**.
24
+
25
+ > **The keystone:** one nonce-enforced append-only log is the substrate for idempotency, replay protection, crash recovery, MVCC, *and* time-travel — simultaneously.
26
+
27
+ ---
28
+
29
+ ## Quickstart (Python reference engine — runs today, zero build)
30
+
31
+ ```bash
32
+ git clone https://github.com/interchained/nedb && cd nedb
33
+ pip install -e . # pure-Python reference; no toolchain needed
34
+ python3 examples/demo.py # see every feature
35
+ python3 tests/test_nedb.py # 10/10 invariants
36
+ ```
37
+
38
+ ```python
39
+ from nedb import NEDB
40
+
41
+ db = NEDB()
42
+ db.create_index("users", "status", "eq")
43
+ db.create_index("users", "age", "ordered")
44
+ db.create_index("users", "bio", "search")
45
+
46
+ db.put("users", "alice", {"name": "Alice", "age": 31, "status": "active",
47
+ "city": "Austin", "bio": "rust systems hacker"})
48
+
49
+ # Idempotent, replay-protected write (safe to retry forever):
50
+ db.put("orders", "o1", {"total": 42}, client="checkout", nonce=7, idem="charge-o1")
51
+
52
+ # NQL — filter + sort
53
+ db.query('FROM users WHERE age >= 25 AND status = "active" ORDER BY age DESC')
54
+
55
+ # Full-text search
56
+ db.query('FROM users SEARCH "rust"')
57
+
58
+ # Relations + graph traversal
59
+ db.link("users:alice", "follows", "users:bob")
60
+ db.q("users").where("_id", "=", "alice").traverse("follows").run()
61
+
62
+ # Time-travel
63
+ s = db.seq
64
+ db.put("users", "alice", {"name": "Alice", "city": "Lisbon", "age": 31, "status": "active"})
65
+ db.get("users", "alice", as_of=s)["city"] # -> "Austin"
66
+
67
+ # git-style files with Cascade compression + provable history
68
+ v1 = db.put_file("notes.txt", open("notes.txt","rb").read())
69
+ db.file_root("notes.txt", v1) # Merkle root — anchorable on ITC
70
+ ```
71
+
72
+ ---
73
+
74
+ ## NQL — the NEDB Query Language
75
+
76
+ One small grammar; the Rust parser is the single source of truth so Python and Node share identical semantics. A fluent builder compiles to the same plan.
77
+
78
+ ```
79
+ FROM <collection>
80
+ [ AS OF <seq> ]
81
+ [ WHERE <field> <op> <value> (AND ...)* ] op ∈ = != < <= > >=
82
+ [ SEARCH "<text>" ]
83
+ [ ORDER BY <field> [ASC|DESC] ]
84
+ [ TRAVERSE <relation> ]
85
+ [ LIMIT <n> ]
86
+ ```
87
+
88
+ ---
89
+
90
+ ## What's measured (reference engine, pure Python, 2 vCPU)
91
+
92
+ | Operation | Result |
93
+ |---|---|
94
+ | GET (embedded, in-process) | **~1.2M ops/s** (~800 ns/op) |
95
+ | SET (logged + indexed) | ~77K ops/s |
96
+ | Indexed query latency | ~75 µs |
97
+ | File compression — warm (zlib stand-in) | **39.9×** |
98
+ | File compression — cold (LZMA archival) | **88.9×** |
99
+ | Cross-version dedup | 20 of 22 chunks reused on edit |
100
+
101
+ The reference engine proves the **architecture**. The Rust core (`rust/`) is the speed target — see `bench/bench_redis.py` for the embedded-vs-Redis harness.
102
+
103
+ ---
104
+
105
+ ## Architecture
106
+
107
+ ```
108
+ ┌──────────────────────────────────────────────┐
109
+ put/del → │ OpLog (append-only · BLAKE3 hash chain · │ ← single source of truth
110
+ link │ per-client nonce · idempotency keys) │
111
+ └───────────────┬──────────────────────────────┘
112
+ deterministic fold │ (state = pure function of the log)
113
+ ┌──────────────┬───────┴────────┬───────────────────┐
114
+ ▼ ▼ ▼ ▼
115
+ MVCC store Relations Indexes BlobStore (Cascade)
116
+ (time-travel) (graph, AS OF) eq/ordered/search CDC+dedup+tiers, Merkle roots
117
+ ```
118
+
119
+ One Rust core (`nedb-core`) → **PyO3** wheels (PyPI) and **napi-rs** binaries (npm), plus a future `nedbd` server (RESP-compatible) and a WASM build for browser/edge.
120
+
121
+ Full design: [`docs/SPEC.md`](docs/SPEC.md).
122
+
123
+ ---
124
+
125
+ ## Repo layout
126
+
127
+ ```
128
+ nedb/ pure-Python reference engine (this is what `pip install` ships today)
129
+ rust/ production core — nedb-core + nedb-py (PyO3) + nedb-node (napi-rs)
130
+ examples/demo.py end-to-end walkthrough
131
+ tests/ invariant tests
132
+ bench/ embedded micro-bench + Redis head-to-head harness
133
+ docs/SPEC.md architecture specification
134
+ .github/ release CI → PyPI + npm on tag
135
+ ```
136
+
137
+ ## Roadmap
138
+
139
+ - [x] Reference engine: log, MVCC, relations, indexes, NQL, Cascade, Merkle
140
+ - [ ] Rust core parity + criterion benches + `cargo test`
141
+ - [ ] PyO3 wheels + napi-rs binaries published on tag
142
+ - [ ] `nedbd` server: RESP-compatible + native protocol
143
+ - [ ] Similarity-picked deltas + schema-aware columnar transforms
144
+ - [ ] On-chain (ITC) root anchoring; WASM build
145
+
146
+ ## License
147
+
148
+ Apache-2.0. Part of the [Interchained](https://github.com/interchained) ecosystem.
@@ -0,0 +1,23 @@
1
+ """
2
+ NEDB — a versioned, self-compressing, time-traveling embedded database.
3
+
4
+ * Replay-protected & idempotent: every write carries a monotonic nonce and an
5
+ optional idempotency key, enforced by a hash-chained append-only log.
6
+ * Time-travel: read the database AS OF any past sequence number.
7
+ * Relational: first-class, time-travel-aware relations with O(1) traversal.
8
+ * Filterable / sortable / searchable: equality, ordered, and full-text indexes.
9
+ * Queryable: NQL text queries and a fluent builder that share one plan.
10
+ * git-style files with Cascade compression: content-defined chunking + dedup +
11
+ temperature tiers, with a Merkle root per version anchorable on-chain.
12
+
13
+ This pure-Python package is the reference implementation. The production speed core
14
+ is Rust (see ../rust), exposed to PyPI via PyO3 and to npm via napi-rs.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ from .engine import NEDB
19
+ from .log import Op, OpLog, ReplayError
20
+ from .query import Query, parse_nql
21
+
22
+ __all__ = ["NEDB", "OpLog", "Op", "ReplayError", "Query", "parse_nql"]
23
+ __version__ = "0.1.0"
@@ -0,0 +1,130 @@
1
+ """
2
+ nedb.cascade — the Cascade compression pipeline + content-addressed blob store.
3
+
4
+ This is what makes NEDB double as a git-style file manager with maximum compression
5
+ WITHOUT inventing a new entropy coder. The novelty is the pipeline composition:
6
+
7
+ 1. Content-defined chunking (Gear rolling hash) — boundaries follow content, so a
8
+ one-byte insert only changes the chunk(s) around it, not everything after it.
9
+ 2. Content-addressed dedup (BLAKE) — identical chunks across all files and all
10
+ versions are stored exactly once.
11
+ 3. Temperature tiers — warm data uses a fast codec (zstd in prod; zlib in this
12
+ reference), cold/archival history uses a maximum-ratio codec (LZMA).
13
+
14
+ The production pipeline adds similarity-picked binary deltas (zstd --patch-from) and
15
+ schema-aware columnar transforms before the entropy stage; both are documented in
16
+ docs/SPEC.md and stubbed for the reference engine.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import lzma
22
+ import random
23
+ import zlib
24
+ from typing import Dict, List
25
+
26
+ from .merkle import merkle_root
27
+
28
+ # --- Gear-hash content-defined chunking -------------------------------------
29
+ _MASK = (1 << 13) - 1 # ~8 KiB average chunk
30
+ _MIN = 2 * 1024
31
+ _MAX = 64 * 1024
32
+ _M64 = 0xFFFFFFFFFFFFFFFF
33
+ _GEAR = [random.Random(0x12345678 + i).getrandbits(64) for i in range(256)]
34
+
35
+
36
+ def chunk(data: bytes) -> List[bytes]:
37
+ chunks: List[bytes] = []
38
+ n = len(data)
39
+ i = 0
40
+ while i < n:
41
+ limit = min(i + _MAX, n)
42
+ h = 0
43
+ pos = i
44
+ cut = limit
45
+ while pos < limit:
46
+ h = ((h << 1) + _GEAR[data[pos]]) & _M64
47
+ pos += 1
48
+ if (pos - i) >= _MIN and (h & _MASK) == 0:
49
+ cut = pos
50
+ break
51
+ chunks.append(data[i:cut])
52
+ i = cut
53
+ return chunks
54
+
55
+
56
+ def _blake(b: bytes) -> str:
57
+ return hashlib.blake2b(b, digest_size=32).hexdigest()
58
+
59
+
60
+ # --- temperature tiers ------------------------------------------------------
61
+ def warm_compress(b: bytes) -> bytes: # zstd stand-in in the reference
62
+ return zlib.compress(b, 6)
63
+
64
+
65
+ def warm_decompress(b: bytes) -> bytes:
66
+ return zlib.decompress(b)
67
+
68
+
69
+ def cold_compress(b: bytes) -> bytes: # real LZMA — the maximum-ratio archival tier
70
+ return lzma.compress(b, preset=9 | lzma.PRESET_EXTREME)
71
+
72
+
73
+ def cold_decompress(b: bytes) -> bytes:
74
+ return lzma.decompress(b)
75
+
76
+
77
+ class BlobStore:
78
+ """Content-addressed, deduplicated, tiered blob store with versioned files."""
79
+
80
+ def __init__(self, tier: str = "warm") -> None:
81
+ self.tier = tier
82
+ self.chunks: Dict[str, bytes] = {} # hash -> compressed bytes
83
+ self.files: Dict[str, Dict[str, list]] = {} # name -> {versions, roots}
84
+ self.logical_bytes = 0
85
+ self.dedup_hits = 0
86
+
87
+ def _compress(self, b: bytes) -> bytes:
88
+ return cold_compress(b) if self.tier == "cold" else warm_compress(b)
89
+
90
+ def _decompress(self, b: bytes) -> bytes:
91
+ return cold_decompress(b) if self.tier == "cold" else warm_decompress(b)
92
+
93
+ def put_file(self, name: str, data: bytes) -> int:
94
+ recipe: List[str] = []
95
+ for c in chunk(data):
96
+ hh = _blake(c)
97
+ recipe.append(hh)
98
+ if hh in self.chunks:
99
+ self.dedup_hits += 1
100
+ else:
101
+ self.chunks[hh] = self._compress(c)
102
+ self.logical_bytes += len(data)
103
+ f = self.files.setdefault(name, {"versions": [], "roots": []})
104
+ f["versions"].append(recipe)
105
+ f["roots"].append(merkle_root(recipe))
106
+ return len(f["versions"]) - 1
107
+
108
+ def get_file(self, name: str, version: int = -1) -> bytes:
109
+ recipe = self.files[name]["versions"][version]
110
+ out = bytearray()
111
+ for hh in recipe:
112
+ out += self._decompress(self.chunks[hh])
113
+ return bytes(out)
114
+
115
+ def root(self, name: str, version: int = -1) -> str:
116
+ return self.files[name]["roots"][version]
117
+
118
+ def stored_bytes(self) -> int:
119
+ return sum(len(v) for v in self.chunks.values())
120
+
121
+ def stats(self) -> dict:
122
+ stored = self.stored_bytes()
123
+ return {
124
+ "tier": self.tier,
125
+ "unique_chunks": len(self.chunks),
126
+ "dedup_hits": self.dedup_hits,
127
+ "logical_bytes": self.logical_bytes,
128
+ "stored_bytes": stored,
129
+ "ratio": round(self.logical_bytes / stored, 2) if stored else 0.0,
130
+ }