mnemo-engine 0.8.1__tar.gz → 0.9.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/PKG-INFO +2 -1
  2. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/README.md +1 -0
  3. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/Cargo.lock +43 -2
  4. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/Cargo.toml +18 -1
  5. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/README.md +9 -1
  6. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/benches/corpus.rs +6 -0
  7. mnemo_engine-0.9.1/mnemo/benches/thread.rs +162 -0
  8. mnemo_engine-0.9.1/mnemo/examples/open_rss.rs +254 -0
  9. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/bin/mnemo.rs +472 -0
  10. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/lib.rs +13 -3
  11. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/mcp.rs +585 -2
  12. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/memory.rs +524 -0
  13. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/store.rs +1735 -136
  14. mnemo_engine-0.9.1/mnemo/src/transcript.rs +324 -0
  15. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/tests/cli_smoke.rs +216 -0
  16. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/tests/integration.rs +1120 -3
  17. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/tests/proptest_store.rs +235 -0
  18. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo-python/Cargo.lock +2 -2
  19. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo-python/Cargo.toml +1 -1
  20. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo-python/README.md +1 -0
  21. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo-python/src/lib.rs +490 -26
  22. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo-python/test_mnemo.py +192 -0
  23. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/pyproject.toml +1 -1
  24. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/.gitignore +0 -0
  25. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/benches/cache.rs +0 -0
  26. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/benches/embed_overhead.rs +0 -0
  27. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/benches/open.rs +0 -0
  28. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/benches/recall.rs +0 -0
  29. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/benches/write.rs +0 -0
  30. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/deny.toml +0 -0
  31. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/examples/ann_defaults_v0_6_0.rs +0 -0
  32. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/examples/ann_diagnose.rs +0 -0
  33. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/examples/ann_recall_grid.rs +0 -0
  34. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/examples/ann_recall_grid_v2.rs +0 -0
  35. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/examples/embedder_server.py +0 -0
  36. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/examples/file_size_breakdown.rs +0 -0
  37. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/examples/quickstart.rs +0 -0
  38. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/examples/ranking_v2.rs +0 -0
  39. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/examples/session.rs +0 -0
  40. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/cache.rs +0 -0
  41. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/crypto.rs +0 -0
  42. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/embed.rs +0 -0
  43. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/embed_cmd.rs +0 -0
  44. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/error.rs +0 -0
  45. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/format.rs +0 -0
  46. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/index.rs +0 -0
  47. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/pager.rs +0 -0
  48. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/result_cache.rs +0 -0
  49. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/session.rs +0 -0
  50. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/src/wal.rs +0 -0
  51. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/tests/dur1_torn_header.rs +0 -0
  52. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/tests/fix1_correctness_sweep.rs +0 -0
  53. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/tests/proptest_store.proptest-regressions +0 -0
  54. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo/tests/sec1_nonce_uniqueness.rs +0 -0
  55. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/mnemo-python/.gitignore +0 -0
  56. {mnemo_engine-0.8.1 → mnemo_engine-0.9.1}/python/mnemo_engine/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mnemo-engine
3
- Version: 0.8.1
3
+ Version: 0.9.1
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: 3
6
6
  Classifier: License :: OSI Approved :: Apache Software License
@@ -167,6 +167,7 @@ its own agent.
167
167
  | `search(query, top_k=10)` | Exact nearest-neighbour search |
168
168
  | `get(id)` / `delete(id)` | Fetch / soft-delete by id |
169
169
  | `about()` | Self-describing onboarding briefing — memories tagged `metadata.area="onboarding"`, manifest first |
170
+ | `about_essence()` | The project essence render for the briefing (markdown), or `None` when the file has none |
170
171
  | `insert_default_manifest()` | Insert the canonical scaffold manifest (same one `mnemo init` adds); returns its id |
171
172
  | `session(agent_id)` | Begin a conversation `Session` |
172
173
  | `flush()` / `close()` | Persist pending changes |
@@ -153,6 +153,7 @@ its own agent.
153
153
  | `search(query, top_k=10)` | Exact nearest-neighbour search |
154
154
  | `get(id)` / `delete(id)` | Fetch / soft-delete by id |
155
155
  | `about()` | Self-describing onboarding briefing — memories tagged `metadata.area="onboarding"`, manifest first |
156
+ | `about_essence()` | The project essence render for the briefing (markdown), or `None` when the file has none |
156
157
  | `insert_default_manifest()` | Insert the canonical scaffold manifest (same one `mnemo init` adds); returns its id |
157
158
  | `session(agent_id)` | Begin a conversation `Session` |
158
159
  | `flush()` / `close()` | Persist pending changes |
@@ -183,6 +183,16 @@ version = "0.3.0"
183
183
  source = "registry+https://github.com/rust-lang/crates.io-index"
184
184
  checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
185
185
 
186
+ [[package]]
187
+ name = "cc"
188
+ version = "1.11.1"
189
+ source = "registry+https://github.com/rust-lang/crates.io-index"
190
+ checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155"
191
+ dependencies = [
192
+ "find-msvc-tools",
193
+ "shlex",
194
+ ]
195
+
186
196
  [[package]]
187
197
  name = "cfg-if"
188
198
  version = "1.0.5"
@@ -420,6 +430,12 @@ version = "2.5.0"
420
430
  source = "registry+https://github.com/rust-lang/crates.io-index"
421
431
  checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
422
432
 
433
+ [[package]]
434
+ name = "find-msvc-tools"
435
+ version = "0.1.15"
436
+ source = "registry+https://github.com/rust-lang/crates.io-index"
437
+ checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
438
+
423
439
  [[package]]
424
440
  name = "fnv"
425
441
  version = "1.0.7"
@@ -596,6 +612,15 @@ version = "0.2.16"
596
612
  source = "registry+https://github.com/rust-lang/crates.io-index"
597
613
  checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
598
614
 
615
+ [[package]]
616
+ name = "libmimalloc-sys"
617
+ version = "0.1.49"
618
+ source = "registry+https://github.com/rust-lang/crates.io-index"
619
+ checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9"
620
+ dependencies = [
621
+ "cc",
622
+ ]
623
+
599
624
  [[package]]
600
625
  name = "linux-raw-sys"
601
626
  version = "0.4.15"
@@ -608,9 +633,18 @@ version = "2.8.3"
608
633
  source = "registry+https://github.com/rust-lang/crates.io-index"
609
634
  checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
610
635
 
636
+ [[package]]
637
+ name = "mimalloc"
638
+ version = "0.1.43"
639
+ source = "registry+https://github.com/rust-lang/crates.io-index"
640
+ checksum = "68914350ae34959d83f732418d51e2427a794055d0b9529f48259ac07af65633"
641
+ dependencies = [
642
+ "libmimalloc-sys",
643
+ ]
644
+
611
645
  [[package]]
612
646
  name = "mnemo-engine"
613
- version = "0.8.1"
647
+ version = "0.9.1"
614
648
  dependencies = [
615
649
  "aes-gcm",
616
650
  "argon2",
@@ -618,6 +652,7 @@ dependencies = [
618
652
  "clap",
619
653
  "criterion",
620
654
  "fs4",
655
+ "mimalloc",
621
656
  "proptest",
622
657
  "rand",
623
658
  "rmp",
@@ -634,7 +669,7 @@ dependencies = [
634
669
 
635
670
  [[package]]
636
671
  name = "mnemo-node"
637
- version = "0.8.1"
672
+ version = "0.9.1"
638
673
  dependencies = [
639
674
  "mnemo-engine",
640
675
  "napi",
@@ -1075,6 +1110,12 @@ dependencies = [
1075
1110
  "digest",
1076
1111
  ]
1077
1112
 
1113
+ [[package]]
1114
+ name = "shlex"
1115
+ version = "2.0.1"
1116
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1117
+ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
1118
+
1078
1119
  [[package]]
1079
1120
  name = "slab"
1080
1121
  version = "0.4.12"
@@ -10,7 +10,7 @@
10
10
  # The CLI binary name stays `mnemo`, so users still invoke `mnemo` on
11
11
  # the command line after `cargo install mnemo-engine`.
12
12
  name = "mnemo-engine"
13
- version = "0.8.1"
13
+ version = "0.9.1"
14
14
  edition = "2021"
15
15
  rust-version = "1.75"
16
16
  # `benches/corpus.rs` is a shared helper module pulled into real benches
@@ -108,6 +108,13 @@ sha2 = "=0.10.8"
108
108
  # published crate carries criterion only as an optional feature,
109
109
  # never resolved by default consumers.
110
110
  criterion = { version = "=0.5.1", features = ["html_reports"], optional = true }
111
+ # Phase 12.1 MEM-1 open_rss example variant 4 (`#[global_allocator]`).
112
+ # Pure Rust microsoft/mimalloc binding; gated behind `mimalloc_bench`
113
+ # so default consumers of the crate don't carry the dep. Lives under
114
+ # `[dependencies]` for the same reason criterion does — `optional`
115
+ # fields are only honoured on top-level deps, and we need the example
116
+ # binary (built from this crate) to link against it when requested.
117
+ mimalloc = { version = "=0.1.43", default-features = false, optional = true }
111
118
 
112
119
  [dev-dependencies]
113
120
  tempfile = "=3.10.1"
@@ -141,6 +148,11 @@ name = "embed_overhead"
141
148
  harness = false
142
149
  required-features = ["benches"]
143
150
 
151
+ [[bench]]
152
+ name = "thread"
153
+ harness = false
154
+ required-features = ["benches"]
155
+
144
156
  [features]
145
157
  # When enabled, exposes crash-injection hooks used by the Phase 1.3
146
158
  # proptest under `mnemo_engine::__failpoints::*`. Always enabled during
@@ -156,6 +168,11 @@ failpoints = []
156
168
  # `--all-targets --features failpoints,benches`; the MSRV CI job
157
169
  # never sees them. Not for production use.
158
170
  benches = ["dep:criterion"]
171
+ # Phase 12.1 MEM-1 open_rss example variant 4: swap the global
172
+ # allocator for mimalloc inside the example binary only. Default
173
+ # consumers do not carry the dep. Combine with `--features benches`
174
+ # to actually build the example.
175
+ mimalloc_bench = ["dep:mimalloc"]
159
176
 
160
177
  [profile.release]
161
178
  lto = true
@@ -695,9 +695,17 @@ knowledge. The `about` command surfaces that introduction:
695
695
  cargo run --bin mnemo -- about agent.mnemo
696
696
  # Prints a one-line stats header, then every memory tagged
697
697
  # metadata.area = "onboarding" sorted with the canonical manifest first,
698
- # then by importance descending, ending with a quick-start footer.
698
+ # then by importance descending, then the project essence (if any),
699
+ # ending with a quick-start footer.
699
700
  ```
700
701
 
702
+ Since v0.9.1 the briefing also carries the file's **project essence**: the
703
+ render of its project-scope essence items (conventions, lasting decisions,
704
+ open items), at the default 6 KB budget, after the manifest and onboarding
705
+ memories. `Mnemo::about_essence()` returns it (`None` when there is none),
706
+ `mnemo about --format json` adds it as `"essence"`, and the MCP `about` tool
707
+ appends it as a final `{"kind": "essence", "render": …}` element.
708
+
701
709
  The convention is two metadata keys on ordinary memories — no new schema, no
702
710
  extra file:
703
711
 
@@ -71,6 +71,12 @@ pub fn secure_kdf_cfg(dimensions: usize) -> MnemoConfig {
71
71
  /// show that advantage.
72
72
  #[allow(dead_code)]
73
73
  pub fn gen_clustered_vectors(n: usize, dims: usize, k_clusters: usize, seed: u64) -> Vec<Vec<f32>> {
74
+ // MEM-1: a swapped (seed, k_clusters) pair once asked for
75
+ // 0xDEAD_BEEF ≈ 3.7 billion centres and read as a 13–43 GB "leak".
76
+ assert!(
77
+ (1..=n.max(1_000)).contains(&k_clusters),
78
+ "k_clusters looks like a swapped argument"
79
+ );
74
80
  // Hand-rolled splitmix64 → xoroshiro128+ because the `rand` crate's
75
81
  // RNG API moved between 0.8 and 0.9 and we're pinned to 0.8.6; a
76
82
  // tiny deterministic RNG here keeps the benches independent of
@@ -0,0 +1,162 @@
1
+ //! Phase 12.7d speed benches for the thread layers.
2
+ //!
3
+ //! Three entries, all with a trivial in-process embedder (a canned
4
+ //! 384-dim vector), so they measure the engine's cost rather than a
5
+ //! model's:
6
+ //!
7
+ //! 1. `thread/ingest_1000_turns`: `ingest_thread` of 1,000 ~200-byte
8
+ //! turns into an empty thread, plus the flush. Throughput is reported
9
+ //! in turns per second.
10
+ //! 2. `thread/essence_render_1000_items`: `essence(thread, 6144)` over a
11
+ //! thread holding 1,000 essence items (700 section items across the
12
+ //! seven sections, 300 timeline entries).
13
+ //! 3. `thread/about_with_essence_1000_items`: the full `about` briefing,
14
+ //! `about()` plus `about_essence()`, on a file with a manifest and
15
+ //! 1,000 project-scope essence items.
16
+
17
+ use std::hint::black_box;
18
+
19
+ use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughput};
20
+ use mnemo_engine::{
21
+ Embedder, EmbedderIdentity, EssenceScope, EssenceSection, Memory, Mnemo, Result, ThreadTurn,
22
+ };
23
+ use tempfile::TempDir;
24
+
25
+ #[path = "corpus.rs"]
26
+ mod corpus;
27
+ use corpus::{fast_kdf_cfg, gen_clustered_vectors, DIMENSIONS, PASSPHRASE};
28
+
29
+ const ITEMS: usize = 1_000;
30
+ const TURNS: usize = 1_000;
31
+
32
+ struct CannedEmbedder {
33
+ vector: Vec<f32>,
34
+ }
35
+
36
+ impl Embedder for CannedEmbedder {
37
+ fn identity(&self) -> EmbedderIdentity {
38
+ EmbedderIdentity {
39
+ name: "bench-canned-embedder".into(),
40
+ dimensions: self.vector.len(),
41
+ normalize: true,
42
+ }
43
+ }
44
+
45
+ fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
46
+ Ok(texts.iter().map(|_| self.vector.clone()).collect())
47
+ }
48
+ }
49
+
50
+ fn canned_vector() -> Vec<f32> {
51
+ gen_clustered_vectors(1, DIMENSIONS, 1, 0x7E8D_0001)
52
+ .into_iter()
53
+ .next()
54
+ .unwrap()
55
+ }
56
+
57
+ fn make_db(td: &TempDir) -> Mnemo {
58
+ let path = td.path().join("thread-bench.mnemo");
59
+ let mut db = Mnemo::create(&path, PASSPHRASE, fast_kdf_cfg(DIMENSIONS)).expect("create");
60
+ db.remember(Memory::scaffold_manifest(DIMENSIONS))
61
+ .expect("manifest");
62
+ db.set_embedder(CannedEmbedder {
63
+ vector: canned_vector(),
64
+ })
65
+ .expect("set_embedder");
66
+ db
67
+ }
68
+
69
+ const SECTIONS: [EssenceSection; 7] = [
70
+ EssenceSection::Intent,
71
+ EssenceSection::Conventions,
72
+ EssenceSection::Decisions,
73
+ EssenceSection::State,
74
+ EssenceSection::Open,
75
+ EssenceSection::Next,
76
+ EssenceSection::Lessons,
77
+ ];
78
+
79
+ /// Fill `scope` with `ITEMS` essence items: 70% section items spread
80
+ /// over the seven sections, 30% timeline entries.
81
+ fn fill_essence(db: &mut Mnemo, scope: &EssenceScope) {
82
+ for i in 0..ITEMS {
83
+ if i % 10 < 7 {
84
+ let section = SECTIONS[i % SECTIONS.len()];
85
+ let text =
86
+ format!("item {i:04}: a one-line essence entry of typical length for a bench");
87
+ db.essence_add(scope.clone(), section, &text, None)
88
+ .expect("essence_add");
89
+ } else {
90
+ let text =
91
+ format!("milestone {i:04}: shipped a thing, measured it, and wrote down why");
92
+ db.essence_append_timeline(scope.clone(), &text, None)
93
+ .expect("essence_append_timeline");
94
+ }
95
+ }
96
+ db.flush().expect("flush");
97
+ }
98
+
99
+ fn bench_ingest(c: &mut Criterion) {
100
+ let turns: Vec<ThreadTurn> = (0..TURNS)
101
+ .map(|i| ThreadTurn {
102
+ turn_id: format!("turn-{i:05}"),
103
+ role: if i % 2 == 0 { "user" } else { "assistant" }.into(),
104
+ content: format!("turn {i:05}: {}", "lorem ipsum dolor sit amet ".repeat(7)),
105
+ timestamp: Some(1_700_000_000 + i as i64),
106
+ })
107
+ .collect();
108
+
109
+ let mut group = c.benchmark_group("thread");
110
+ group.sample_size(10);
111
+ group.throughput(Throughput::Elements(TURNS as u64));
112
+ group.bench_function("ingest_1000_turns", |b| {
113
+ b.iter_batched(
114
+ || {
115
+ let td = TempDir::new().expect("tempdir");
116
+ let db = make_db(&td);
117
+ (td, db)
118
+ },
119
+ |(_td, mut db)| {
120
+ let report = db.ingest_thread("bench", &turns).expect("ingest");
121
+ db.flush().expect("flush");
122
+ black_box(report);
123
+ },
124
+ BatchSize::PerIteration,
125
+ );
126
+ });
127
+ group.finish();
128
+ }
129
+
130
+ fn bench_render(c: &mut Criterion) {
131
+ let td = TempDir::new().expect("tempdir");
132
+ let mut db = make_db(&td);
133
+ let scope = EssenceScope::Thread("bench".into());
134
+ fill_essence(&mut db, &scope);
135
+
136
+ let mut group = c.benchmark_group("thread");
137
+ group.sample_size(20);
138
+ group.bench_function("essence_render_1000_items", |b| {
139
+ b.iter(|| black_box(db.essence(scope.clone(), 6144).expect("render")));
140
+ });
141
+ group.finish();
142
+ }
143
+
144
+ fn bench_about(c: &mut Criterion) {
145
+ let td = TempDir::new().expect("tempdir");
146
+ let mut db = make_db(&td);
147
+ fill_essence(&mut db, &EssenceScope::Project);
148
+
149
+ let mut group = c.benchmark_group("thread");
150
+ group.sample_size(20);
151
+ group.bench_function("about_with_essence_1000_items", |b| {
152
+ b.iter(|| {
153
+ let records = db.about().expect("about");
154
+ let essence = db.about_essence().expect("about_essence");
155
+ black_box((records, essence))
156
+ });
157
+ });
158
+ group.finish();
159
+ }
160
+
161
+ criterion_group!(thread_benches, bench_ingest, bench_render, bench_about);
162
+ criterion_main!(thread_benches);
@@ -0,0 +1,254 @@
1
+ //! Fresh-handle loop harness (PR MEM-1; `fresh_handle_loop_n50`).
2
+ //!
3
+ //! Opens a cached corpus, measures the first recall on each fresh
4
+ //! handle, drops the handle, and prints the process's RSS after the
5
+ //! drop. Run it read-write, then read-only:
6
+ //!
7
+ //! ```text
8
+ //! cargo run --release --example open_rss --features benches -- --corpus 100000
9
+ //! cargo run --release --example open_rss --features benches -- --corpus 100000 --read-only
10
+ //! ```
11
+ //!
12
+ //! MEM-1 closed in v0.9.0: the 13–43 GB "growth" was this harness
13
+ //! (and the deleted `first_recall` bench) passing `0xDEAD_BEEF` as
14
+ //! `k_clusters` to `gen_clustered_vectors`, not an engine or allocator
15
+ //! leak. `corpus.rs` now asserts on implausible `k_clusters`.
16
+ //!
17
+ //! The macOS allocator switches from the diagnostic are kept as
18
+ //! optional knobs: `MallocSpaceEfficient=1 MallocAggressiveMadvise=1`
19
+ //! in the environment, `--pressure-relief` (calls
20
+ //! `malloc_zone_pressure_relief` after each drop), and
21
+ //! `--features benches,mimalloc_bench` (mimalloc as the global
22
+ //! allocator, in this example only).
23
+
24
+ #[cfg(feature = "mimalloc_bench")]
25
+ use mimalloc::MiMalloc;
26
+ #[cfg(feature = "mimalloc_bench")]
27
+ #[global_allocator]
28
+ static GLOBAL: MiMalloc = MiMalloc;
29
+
30
+ use std::hint::black_box;
31
+ use std::process::Command;
32
+ use std::time::Instant;
33
+
34
+ use mnemo_engine::{Mnemo, RecallRequest, ScoreWeights};
35
+
36
+ #[path = "../benches/corpus.rs"]
37
+ mod corpus;
38
+ use corpus::{gen_clustered_vectors, setup_cached_corpus, DIMENSIONS, PASSPHRASE};
39
+
40
+ const OPEN_LOOPS: usize = 50;
41
+
42
+ /// Macro picks the active-allocator banner so the CLI header leaves
43
+ /// no ambiguity about which variant produced the numbers.
44
+ const ALLOCATOR_BANNER: &str = if cfg!(feature = "mimalloc_bench") {
45
+ "mimalloc (variant 4)"
46
+ } else {
47
+ "system default (variant 1/2/3 depending on env + --pressure-relief)"
48
+ };
49
+
50
+ /// macOS `libSystem` purge hook. The planner-A DISPATCH wants variant
51
+ /// 3 to call this after every handle drop. Declared only on
52
+ /// `target_os = "macos"`; other platforms fall back to a no-op so the
53
+ /// example still builds.
54
+ #[cfg(target_os = "macos")]
55
+ mod purge {
56
+ #[link(name = "System", kind = "dylib")]
57
+ extern "C" {
58
+ fn malloc_zone_pressure_relief(zone: *mut std::ffi::c_void, goal: usize) -> usize;
59
+ }
60
+ pub fn pressure_relief() -> usize {
61
+ // SAFETY: libSystem's `malloc_zone_pressure_relief` accepts a
62
+ // null zone (meaning "all zones") and a goal of 0 (meaning
63
+ // "as much as you can give back"). Returns the number of
64
+ // bytes released.
65
+ unsafe { malloc_zone_pressure_relief(std::ptr::null_mut(), 0) }
66
+ }
67
+ }
68
+ #[cfg(not(target_os = "macos"))]
69
+ mod purge {
70
+ pub fn pressure_relief() -> usize {
71
+ 0
72
+ }
73
+ }
74
+
75
+ /// Snapshot the current process's resident set size (RSS) in kB via
76
+ /// `ps -o rss= -p <pid>`. Portable enough for macOS + Linux.
77
+ fn rss_kb() -> u64 {
78
+ let pid = std::process::id();
79
+ let out = Command::new("ps")
80
+ .args(["-o", "rss=", "-p", &pid.to_string()])
81
+ .output();
82
+ out.ok()
83
+ .and_then(|o| {
84
+ String::from_utf8(o.stdout)
85
+ .ok()
86
+ .and_then(|s| s.trim().parse::<u64>().ok())
87
+ })
88
+ .unwrap_or(0)
89
+ }
90
+
91
+ fn one_iteration(
92
+ path: &std::path::Path,
93
+ q: &[f32],
94
+ read_only: bool,
95
+ pressure_relief: bool,
96
+ ) -> (f64, u64, u64) {
97
+ let mut db = if read_only {
98
+ Mnemo::open_read_only(path, PASSPHRASE).expect("open_read_only")
99
+ } else {
100
+ Mnemo::open(path, PASSPHRASE).expect("open")
101
+ };
102
+ let req = RecallRequest::new(q.to_vec())
103
+ .top_k(10)
104
+ .track_access(false)
105
+ .weights(ScoreWeights::default());
106
+ let start = Instant::now();
107
+ let hits = db.recall(&req).expect("recall");
108
+ let elapsed = start.elapsed();
109
+ black_box(hits);
110
+ drop(db);
111
+ // Variant 3: ask libSystem to return free pages to the OS before
112
+ // we sample RSS.
113
+ let released = if pressure_relief {
114
+ purge::pressure_relief() as u64
115
+ } else {
116
+ 0
117
+ };
118
+ let rss = rss_kb();
119
+ (elapsed.as_secs_f64() * 1_000.0, rss, released)
120
+ }
121
+
122
+ fn percentile(sorted: &[f64], pct: f64) -> f64 {
123
+ if sorted.is_empty() {
124
+ return 0.0;
125
+ }
126
+ let idx = ((pct / 100.0) * (sorted.len() as f64 - 1.0)).round() as usize;
127
+ sorted[idx.min(sorted.len() - 1)]
128
+ }
129
+
130
+ fn median(sorted: &[f64]) -> f64 {
131
+ percentile(sorted, 50.0)
132
+ }
133
+
134
+ /// Parse the CLI args (hand-rolled to avoid pulling in clap for a
135
+ /// one-shot measurement example). Accepts `--corpus N`, `--loops N`,
136
+ /// `--pressure-relief`, `--read-only`.
137
+ struct Args {
138
+ corpus: usize,
139
+ loops: usize,
140
+ pressure_relief: bool,
141
+ read_only_phase: bool,
142
+ }
143
+
144
+ fn parse_args() -> Args {
145
+ let mut args = Args {
146
+ corpus: 100_000,
147
+ loops: OPEN_LOOPS,
148
+ pressure_relief: false,
149
+ read_only_phase: false,
150
+ };
151
+ let mut it = std::env::args().skip(1).peekable();
152
+ while let Some(a) = it.next() {
153
+ match a.as_str() {
154
+ "--corpus" => {
155
+ args.corpus = it
156
+ .next()
157
+ .and_then(|v| v.parse().ok())
158
+ .expect("--corpus needs a positive integer");
159
+ }
160
+ "--loops" => {
161
+ args.loops = it
162
+ .next()
163
+ .and_then(|v| v.parse().ok())
164
+ .expect("--loops needs a positive integer");
165
+ }
166
+ "--pressure-relief" => args.pressure_relief = true,
167
+ "--read-only" => args.read_only_phase = true,
168
+ other => panic!("unknown arg: {other}"),
169
+ }
170
+ }
171
+ args
172
+ }
173
+
174
+ fn main() {
175
+ let args = parse_args();
176
+ println!("mnemo PR MEM-1 open_rss harness");
177
+ println!(" pid : {}", std::process::id());
178
+ println!(
179
+ " corpus size : {} memories, {}-dim vectors",
180
+ args.corpus, DIMENSIONS
181
+ );
182
+ println!(" loops : {}", args.loops);
183
+ println!(
184
+ " phase : {}",
185
+ if args.read_only_phase {
186
+ "read-only"
187
+ } else {
188
+ "read-write"
189
+ }
190
+ );
191
+ println!(
192
+ " pressure_relief : {}",
193
+ if args.pressure_relief {
194
+ "on (variant 3)"
195
+ } else {
196
+ "off"
197
+ }
198
+ );
199
+ println!(" allocator : {ALLOCATOR_BANNER}");
200
+ println!(
201
+ " macOS env : MallocSpaceEfficient={} MallocAggressiveMadvise={}",
202
+ std::env::var("MallocSpaceEfficient").unwrap_or_else(|_| "unset".into()),
203
+ std::env::var("MallocAggressiveMadvise").unwrap_or_else(|_| "unset".into()),
204
+ );
205
+
206
+ let cached = setup_cached_corpus(args.corpus, DIMENSIONS);
207
+ let queries = gen_clustered_vectors(args.loops, DIMENSIONS, 100, 0xDEAD_BEEF);
208
+ println!("rss_kb at start: {}\n", rss_kb());
209
+
210
+ println!(
211
+ "{:>4} {:>14} {:>14} {:>14}",
212
+ "iter", "first_recall_ms", "rss_kb_after", "released_kb"
213
+ );
214
+ let mut ms_log = Vec::with_capacity(args.loops);
215
+ let mut rss_log = Vec::with_capacity(args.loops);
216
+ for i in 0..args.loops {
217
+ let q = &queries[i % queries.len()];
218
+ let (ms, rss, released) =
219
+ one_iteration(&cached, q, args.read_only_phase, args.pressure_relief);
220
+ println!("{i:>4} {ms:>14.3} {rss:>14} {:>14}", released / 1024);
221
+ ms_log.push(ms);
222
+ rss_log.push(rss);
223
+ }
224
+
225
+ let mut sorted = ms_log.clone();
226
+ sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
227
+ println!("\n== summary ==");
228
+ println!(
229
+ "first-recall ms: median {:.3}, p95 {:.3}",
230
+ median(&sorted),
231
+ percentile(&sorted, 95.0),
232
+ );
233
+ let start = *rss_log.first().unwrap_or(&0);
234
+ let end = *rss_log.last().unwrap_or(&0);
235
+ let peak = *rss_log.iter().max().unwrap_or(&0);
236
+ println!(
237
+ "rss_kb: start {start}, end {end}, peak {peak}, delta {}",
238
+ end as i64 - start as i64
239
+ );
240
+ // Slope over the second half: positive = climbing, near-zero =
241
+ // plateau.
242
+ let slope = {
243
+ if rss_log.len() < 4 {
244
+ 0.0
245
+ } else {
246
+ let half = rss_log.len() / 2;
247
+ let last_half = &rss_log[half..];
248
+ let first = *last_half.first().unwrap_or(&0) as f64;
249
+ let last = *last_half.last().unwrap_or(&0) as f64;
250
+ (last - first) / (last_half.len() as f64 - 1.0)
251
+ }
252
+ };
253
+ println!("rss_kb slope (second half): {:.2} kB/iter", slope);
254
+ }