hawdb 0.11.0

An embedded Rust graph database for local data-plane workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::*;

#[test]
fn scoped_community_aggregate_accepts_case_membership() {
    let mut db = Database::new();
    for query in [
        "CREATE (:Memory {id: 'm1'})-[:MENTIONS]->(:Entity {community_id: 'alpha'})",
        "CREATE (:Memory {id: 'm2', space_id: ''})-[:MENTIONS]->(:Entity {community_id: 'alpha'})",
        "CREATE (:Memory {id: 'm3', space_id: 'team'})-[:MENTIONS]->(:Entity {community_id: 'beta'})",
        "CREATE (:Community {community_id: 'alpha', name: 'Alpha'})",
        "CREATE (:Community {community_id: 'beta', name: 'Beta'})",
    ] {
        db.query(query).unwrap();
    }
    let query = "MATCH (m:Memory)-[:MENTIONS]->(e:Entity) WHERE (CASE WHEN m.space_id IS NULL OR m.space_id = '' THEN $default_space ELSE m.space_id END) IN $space_ids AND e.community_id IS NOT NULL WITH e.community_id AS community_id, COUNT(DISTINCT m) AS members OPTIONAL MATCH (c:Community) WHERE c.community_id = community_id RETURN c.name AS name, members ORDER BY members DESC, community_id ASC LIMIT $limit";
    let params = BTreeMap::from([
        ("default_space".into(), Value::String("default".into())),
        (
            "space_ids".into(),
            Value::List(vec![Value::String("default".into())]),
        ),
        ("limit".into(), Value::Int(5)),
    ]);
    let result = db.query_with_params(query, &params).unwrap();
    assert_eq!(result.rows.len(), 1);
    assert_eq!(
        result.rows[0].get("name"),
        Some(&Value::String("Alpha".into()))
    );
    assert_eq!(result.rows[0].get("members"), Some(&Value::Int(2)));
}

#[test]
fn with_window_precedes_count_of_groups() {
    let mut db = Database::new();
    db.query("CREATE (:Entity {kind: 'a'})").unwrap();
    db.query("CREATE (:Entity {kind: 'b'})").unwrap();
    for offset in 0..=3 {
        for limit in 0..=3 {
            let output = db.query_with_params(
                "MATCH (e:Entity) WITH e.kind AS kind, COUNT(*) AS n SKIP $offset LIMIT $limit RETURN COUNT(*) AS groups",
                &BTreeMap::from([
                    ("offset".into(), Value::Int(offset)),
                    ("limit".into(), Value::Int(limit)),
                ]),
            ).unwrap();
            assert_eq!(output.rows.len(), 1, "offset={offset}, limit={limit}");
            assert_eq!(
                output.rows[0].get("groups"),
                Some(&Value::Int((2_i64 - offset).max(0).min(limit)))
            );
            let after_count = db.query_with_params(
                "MATCH (e:Entity) WITH e.kind AS kind, COUNT(*) AS n RETURN COUNT(*) AS groups SKIP $offset LIMIT $limit",
                &BTreeMap::from([
                    ("offset".into(), Value::Int(offset)),
                    ("limit".into(), Value::Int(limit)),
                ]),
            ).unwrap();
            assert_eq!(
                after_count.rows.len(),
                usize::from(offset == 0 && limit > 0)
            );
            if let Some(row) = after_count.rows.first() {
                assert_eq!(row.get("groups"), Some(&Value::Int(2)));
            }
        }
    }
}

#[test]
fn with_collect_preserves_distinct_nodes_with_the_same_projected_property() {
    let mut db = Database::new();
    db.query("CREATE (:Memory {id: 'same'})-[:SYNTHESIZED_FROM]->(:Memory {id: 'left'})")
        .unwrap();
    db.query("CREATE (:Memory {id: 'same'})-[:SYNTHESIZED_FROM]->(:Memory {id: 'right'})")
        .unwrap();
    let query = "MATCH (c:Memory)-[:SYNTHESIZED_FROM]->(s:Memory) WHERE c.id IN $ids WITH c, COLLECT(DISTINCT s.id) AS source_ids RETURN c.id, source_ids";
    // A second identity WITH exercises the production clause-pipeline path.
    for query in [
        query.to_string(),
        query.replace(" RETURN ", " WITH c, source_ids RETURN "),
    ] {
        let output = db
            .query_with_params(
                &query,
                &BTreeMap::from([(
                    "ids".to_string(),
                    Value::List(vec![Value::String("same".to_string())]),
                )]),
            )
            .unwrap();
        assert_eq!(output.rows.len(), 2);
        let mut sources = output
            .rows
            .iter()
            .map(|row| {
                assert_eq!(row.get("c.id"), Some(&Value::String("same".into())));
                let Some(Value::List(values)) = row.get("source_ids") else {
                    panic!("missing collected sources")
                };
                assert_eq!(values.len(), 1);
                let Value::String(source) = &values[0] else {
                    panic!("invalid source id")
                };
                source.clone()
            })
            .collect::<Vec<_>>();
        sources.sort();
        assert_eq!(sources, ["left", "right"]);
    }
}

#[test]
fn post_aggregate_lookup_applies_pagination_to_expanded_rows() {
    let mut db = Database::new();
    db.query(
        "CREATE (:Memory {id: 'm', space_id: 's'})-[:MENTIONS]->(:Entity {community_id: 'g'})",
    )
    .unwrap();
    db.query("CREATE (:Community {community_id: 'g', name: 'a', description: 'a'})")
        .unwrap();
    db.query("CREATE (:Community {community_id: 'g', name: 'b', description: 'b'})")
        .unwrap();
    for indexed in [false, true] {
        if indexed {
            db.query("CREATE INDEX ON :Community(community_id)")
                .unwrap();
        }
        // A window written on WITH intentionally limits groups before the
        // lookup. It must remain distinct from the RETURN window below.
        let before_lookup = db.query_with_params(
            "MATCH (m:Memory)-[:MENTIONS]->(e:Entity) WHERE m.space_id IN $space_ids AND e.community_id IS NOT NULL WITH e.community_id AS community_id, COUNT(DISTINCT m) AS memory_count ORDER BY memory_count DESC LIMIT $limit OPTIONAL MATCH (c:Community) WHERE c.community_id = community_id RETURN c.name, memory_count, c.description",
            &BTreeMap::from([
                ("space_ids".into(), Value::List(vec![Value::String("s".into())])),
                ("limit".into(), Value::Int(1)),
            ]),
        ).unwrap();
        assert_eq!(before_lookup.rows.len(), 2, "indexed={indexed}");
        for offset in 0..=3 {
            for limit in 0..=3 {
                let output = db.query_with_params(
            "MATCH (m:Memory)-[:MENTIONS]->(e:Entity) WHERE m.space_id IN $space_ids AND e.community_id IS NOT NULL WITH e.community_id AS community_id, COUNT(DISTINCT m) AS memory_count OPTIONAL MATCH (c:Community) WHERE c.community_id = community_id RETURN c.name, memory_count, c.description ORDER BY memory_count DESC SKIP $offset LIMIT $limit",
            &BTreeMap::from([
                ("space_ids".into(), Value::List(vec![Value::String("s".into())])),
                ("offset".into(), Value::Int(offset)),
                ("limit".into(), Value::Int(limit)),
            ]),
        ).unwrap();
                assert_eq!(
                    output.rows.len(),
                    (2_i64 - offset).max(0).min(limit) as usize,
                    "indexed={indexed}, offset={offset}, limit={limit}"
                );
                for row in &output.rows {
                    assert_eq!(row.get("memory_count"), Some(&Value::Int(1)));
                }
            }
        }
    }
}

#[test]
fn with_collect_preserves_null_property_groups_and_return_aliases() {
    let mut db = Database::new();
    db.query(
        "CREATE (:Memory {id: 'one', title: null})-[:SYNTHESIZED_FROM]->(:Memory {id: 'left'})",
    )
    .unwrap();
    db.query("CREATE (:Memory {id: 'two'})-[:SYNTHESIZED_FROM]->(:Memory {id: 'right'})")
        .unwrap();
    let output = db.query("MATCH (c:Memory)-[:SYNTHESIZED_FROM]->(s:Memory) WITH c, COLLECT(DISTINCT s.id) AS source_ids RETURN c.title AS title, source_ids AS sources").unwrap();
    assert_eq!(output.rows.len(), 2);
    for row in &output.rows {
        assert_eq!(row.get("title"), Some(&Value::Null));
        assert!(row.get("source_ids").is_none());
        let Some(Value::List(values)) = row.get("sources") else {
            panic!("missing aliased sources")
        };
        assert_eq!(values.len(), 1);
    }
}

#[test]
fn post_aggregate_lookup_filters_or_extends_missing_groups_before_limit() {
    let mut db = Database::new();
    for id in ["missing-1", "missing-2"] {
        db.query_with_params("CREATE (:Memory {id: $id, space_id: 's'})-[:MENTIONS]->(:Entity {community_id: 'missing'})", &BTreeMap::from([("id".into(), Value::String(id.into()))])).unwrap();
    }
    db.query("CREATE (:Memory {id: 'found', space_id: 's'})-[:MENTIONS]->(:Entity {community_id: 'found'})").unwrap();
    db.query("CREATE (:Community {community_id: 'found', name: 'found', description: 'present'})")
        .unwrap();
    for optional in [false, true] {
        let lookup = if optional { "OPTIONAL MATCH" } else { "MATCH" };
        let query = format!("MATCH (m:Memory)-[:MENTIONS]->(e:Entity) WHERE m.space_id IN $space_ids AND e.community_id IS NOT NULL WITH e.community_id AS community_id, COUNT(DISTINCT m) AS memory_count {lookup} (c:Community) WHERE c.community_id = community_id RETURN c.name, memory_count, c.description ORDER BY memory_count DESC LIMIT $limit");
        let output = db
            .query_with_params(
                &query,
                &BTreeMap::from([
                    (
                        "space_ids".into(),
                        Value::List(vec![Value::String("s".into())]),
                    ),
                    ("limit".into(), Value::Int(1)),
                ]),
            )
            .unwrap();
        assert_eq!(output.rows.len(), 1, "optional={optional}");
        assert_eq!(
            output.rows[0].get("memory_count"),
            Some(&Value::Int(if optional { 2 } else { 1 }))
        );
        assert_eq!(
            output.rows[0].get("c.name"),
            Some(&if optional {
                Value::Null
            } else {
                Value::String("found".into())
            })
        );
    }
}

#[test]
fn count_property_ignores_missing_and_null_values() {
    let mut db = Database::new();
    db.query("CREATE (:Memory {id: 1, title: 'One', deleted_at: null})")
        .unwrap();
    db.query("CREATE (:Memory {id: 2, title: 'Two'})").unwrap();
    db.query("CREATE (:Memory {id: 3, title: 'Three', deleted_at: 'now'})")
        .unwrap();

    let output = db
        .query("MATCH (m:Memory) RETURN count(m.deleted_at) AS deleted")
        .unwrap();
    assert_eq!(output.rows[0].get("deleted"), Some(&Value::Int(1)));
}

#[test]
fn count_distinct_property_ignores_duplicate_missing_and_null_values() {
    let mut db = Database::new();
    db.query("CREATE (:Memory {id: 1, kind: 'note', status: null})")
        .unwrap();
    db.query("CREATE (:Memory {id: 2, kind: 'note'})").unwrap();
    db.query("CREATE (:Memory {id: 3, kind: 'task', status: 'open'})")
        .unwrap();
    db.query("CREATE (:Memory {id: 4, kind: 'task', status: 'open'})")
        .unwrap();

    let output = db
        .query(
            "MATCH (m:Memory) RETURN count(DISTINCT m.kind) AS kinds, count(DISTINCT m.status) AS statuses",
        )
        .unwrap();
    assert_eq!(output.rows[0].get("kinds"), Some(&Value::Int(2)));
    assert_eq!(output.rows[0].get("statuses"), Some(&Value::Int(1)));
}

#[test]
fn avg_property_ignores_missing_null_and_non_numeric_values() {
    let mut db = Database::new();
    db.query("CREATE (:Memory {id: 1, is_crystal: false, decay_score_cached: 0.2})")
        .unwrap();
    db.query("CREATE (:Memory {id: 2, is_crystal: false, decay_score_cached: 1})")
        .unwrap();
    db.query("CREATE (:Memory {id: 3, is_crystal: false, decay_score_cached: null})")
        .unwrap();
    db.query("CREATE (:Memory {id: 4, is_crystal: false, decay_score_cached: 'skip'})")
        .unwrap();
    db.query("CREATE (:Memory {id: 5, is_crystal: true, decay_score_cached: 10.0})")
        .unwrap();

    let output = db
        .query(
            "MATCH (m:Memory) WHERE m.is_crystal = false RETURN count(m) AS total, avg(m.decay_score_cached) AS avg_decay",
        )
        .unwrap();
    assert_eq!(output.rows[0].get("total"), Some(&Value::Int(4)));
    let Some(Value::Float(avg_decay)) = output.rows[0].get("avg_decay") else {
        panic!("expected floating point average");
    };
    assert!((avg_decay - 0.6).abs() < f64::EPSILON);

    let output = db
        .query("MATCH (m:Memory) WHERE m.is_crystal = true RETURN avg(m.missing) AS avg_decay")
        .unwrap();
    assert_eq!(output.rows[0].get("avg_decay"), Some(&Value::Null));
}

#[test]
fn max_property_ignores_missing_and_null_values() {
    let mut db = Database::new();
    db.query("CREATE (:Memory {id: 1, updated_at: 5})").unwrap();
    db.query("CREATE (:Memory {id: 2, updated_at: null})")
        .unwrap();
    db.query("CREATE (:Memory {id: 3, updated_at: 9})").unwrap();
    db.query("CREATE (:Memory {id: 4})").unwrap();

    let output = db
        .query("MATCH (m:Memory) RETURN count(m), max(m.updated_at)")
        .unwrap();
    assert_eq!(output.rows[0].get("count(m)"), Some(&Value::Int(4)));
    assert_eq!(
        output.rows[0].get("max(m.updated_at)"),
        Some(&Value::Int(9))
    );

    let output = db
        .query("MATCH (m:Missing) RETURN max(m.updated_at)")
        .unwrap();
    assert_eq!(output.rows[0].get("max(m.updated_at)"), Some(&Value::Null));
}

#[test]
fn aggregate_order_by_alias_and_limit() {
    let mut db = Database::new();
    db.query("CREATE (:Memory {id: 1, title: 'One'})").unwrap();
    db.query("CREATE (:Memory {id: 2, title: 'Two'})").unwrap();

    let output = db
        .query("MATCH (m:Memory) RETURN count(*) AS total ORDER BY total DESC LIMIT 1")
        .unwrap();
    assert_eq!(output.rows.len(), 1);
    assert_eq!(output.rows[0].get("total"), Some(&Value::Int(2)));
}

#[test]
fn grouped_count_aggregates_by_projected_property() {
    let mut db = Database::new();
    db.query("CREATE (:Memory {id: 1, kind: 'note'})").unwrap();
    db.query("CREATE (:Memory {id: 2, kind: 'note'})").unwrap();
    db.query("CREATE (:Memory {id: 3, kind: 'task'})").unwrap();

    let output = db
        .query("MATCH (m:Memory) RETURN m.kind AS kind, count(*) AS total ORDER BY total DESC, kind ASC")
        .unwrap();
    assert_eq!(output.rows.len(), 2);
    assert_eq!(
        output.rows[0].get("kind"),
        Some(&Value::String("note".to_string()))
    );
    assert_eq!(output.rows[0].get("total"), Some(&Value::Int(2)));
    assert_eq!(
        output.rows[1].get("kind"),
        Some(&Value::String("task".to_string()))
    );
    assert_eq!(output.rows[1].get("total"), Some(&Value::Int(1)));
}

#[test]
fn aggregate_with_can_count_its_grouped_rows() {
    let mut db = Database::new();
    db.query("CREATE (:Thread {id: 'one', thread_id: 'shared', space_id: ''})")
        .unwrap();
    db.query("CREATE (:Thread {id: 'two', thread_id: 'shared', space_id: ''})")
        .unwrap();
    db.query("CREATE (:Thread {id: 'three', thread_id: 'other', space_id: ''})")
        .unwrap();

    let output = db
        .query(
            "MATCH (t:Thread) WITH CASE WHEN t.space_id IS NULL OR t.space_id = '' THEN 'default' ELSE t.space_id END AS space_id, t.thread_id AS thread_id, MAX(t.id) AS representative_id RETURN COUNT(*) AS total",
        )
        .unwrap();

    assert_eq!(output.rows.len(), 1);
    assert_eq!(output.rows[0].get("total"), Some(&Value::Int(2)));
}

#[test]
fn grouped_count_aggregates_relationship_matches() {
    let mut db = Database::new();
    db.query(
            "CREATE (:Memory {id: 1, kind: 'note'})-[:MENTIONS {weight: 3}]->(:Entity {id: 10, name: 'Rust'})",
        )
        .unwrap();
    db.query(
            "CREATE (:Memory {id: 2, kind: 'note'})-[:MENTIONS {weight: 1}]->(:Entity {id: 11, name: 'Kuzu'})",
        )
        .unwrap();
    db.query(
            "CREATE (:Memory {id: 3, kind: 'task'})-[:MENTIONS {weight: 5}]->(:Entity {id: 12, name: 'Neo4j'})",
        )
        .unwrap();

    let output = db
            .query(
                "MATCH (m:Memory)-[:MENTIONS]->(e:Entity) RETURN m.kind AS kind, count(e) AS total ORDER BY kind ASC",
            )
            .unwrap();
    assert_eq!(output.rows.len(), 2);
    assert_eq!(
        output.rows[0].get("kind"),
        Some(&Value::String("note".to_string()))
    );
    assert_eq!(output.rows[0].get("total"), Some(&Value::Int(2)));
    assert_eq!(
        output.rows[1].get("kind"),
        Some(&Value::String("task".to_string()))
    );
    assert_eq!(output.rows[1].get("total"), Some(&Value::Int(1)));

    let output = db
        .query("MATCH (:Memory)-[r:MENTIONS]->(:Entity) RETURN count(*), min(r.weight)")
        .unwrap();
    assert_eq!(output.rows[0].get("count(*)"), Some(&Value::Int(3)));
    assert_eq!(output.rows[0].get("min(r.weight)"), Some(&Value::Int(1)));
}

#[test]
fn with_collect_distinct_property_returns_source_ids() {
    let mut db = Database::new();
    db.query(
        "CREATE (:Memory {id: 'crystal-1', is_crystal: true})-[:SYNTHESIZED_FROM]->(:Memory {id: 'source-2'})",
    )
    .unwrap();
    db.query("CREATE (:Memory {id: 'source-1'})").unwrap();
    db.query("MATCH (c:Memory {id: 'crystal-1'}), (s:Memory {id: 'source-1'}) CREATE (c)-[:SYNTHESIZED_FROM]->(s)")
        .unwrap();
    db.query("MATCH (c:Memory {id: 'crystal-1'}), (s:Memory {id: 'source-1'}) CREATE (c)-[:SYNTHESIZED_FROM]->(s)")
        .unwrap();
    db.query(
        "CREATE (:Memory {id: 'crystal-2', is_crystal: true})-[:SYNTHESIZED_FROM]->(:Memory {id: 'source-3'})",
    )
    .unwrap();

    let output = db
        .query_with_params(
            "MATCH (c:Memory)-[:SYNTHESIZED_FROM]->(s:Memory) WHERE c.id IN $ids WITH c, COLLECT(DISTINCT s.id) AS source_ids RETURN c.id, source_ids",
            &BTreeMap::from([(
                "ids".to_string(),
                Value::List(vec![Value::String("crystal-1".to_string())]),
            )]),
        )
        .unwrap();

    assert_eq!(output.rows.len(), 1);
    assert_eq!(
        output.rows[0].get("c.id"),
        Some(&Value::String("crystal-1".to_string()))
    );
    assert_eq!(
        output.rows[0].get("source_ids"),
        Some(&Value::List(vec![
            Value::String("source-1".to_string()),
            Value::String("source-2".to_string()),
        ]))
    );
}

#[test]
fn with_count_and_collect_preserves_group_node_for_ordering() {
    let mut db = Database::new();
    db.query("CREATE (:Entity {id: 'entity-1', community_id: 42})")
        .unwrap();
    db.query("CREATE (:Entity {id: 'entity-2', community_id: 42})")
        .unwrap();
    db.query("CREATE (:Memory {id: 'memory-1', title: 'First', importance: 0.8})")
        .unwrap();
    db.query("CREATE (:Memory {id: 'memory-2', title: 'Second', importance: 0.9})")
        .unwrap();
    db.query("MATCH (m:Memory {id: 'memory-1'}), (e:Entity {id: 'entity-1'}) CREATE (m)-[:MENTIONS]->(e)")
        .unwrap();
    db.query("MATCH (m:Memory {id: 'memory-1'}), (e:Entity {id: 'entity-2'}) CREATE (m)-[:MENTIONS]->(e)")
        .unwrap();
    db.query("MATCH (m:Memory {id: 'memory-1'}), (e:Entity {id: 'entity-2'}) CREATE (m)-[:MENTIONS]->(e)")
        .unwrap();
    db.query("MATCH (m:Memory {id: 'memory-2'}), (e:Entity {id: 'entity-1'}) CREATE (m)-[:MENTIONS]->(e)")
        .unwrap();

    let output = db
        .query_with_params(
            "MATCH (e:Entity {community_id: $community_id})<-[:MENTIONS]-(m:Memory) WITH m, COUNT(e) AS entity_count, COLLECT(DISTINCT e.id) AS entity_ids RETURN m, entity_count, entity_ids ORDER BY entity_count DESC, m.importance DESC LIMIT 1",
            &BTreeMap::from([("community_id".to_string(), Value::Int(42))]),
        )
        .unwrap();

    assert_eq!(output.rows.len(), 1);
    let Some(Value::Map(memory)) = output.rows[0].get("m") else {
        panic!("expected grouped memory node map");
    };
    assert_eq!(
        memory.get("id"),
        Some(&Value::String("memory-1".to_string()))
    );
    assert_eq!(output.rows[0].get("entity_count"), Some(&Value::Int(3)));
    assert_eq!(
        output.rows[0].get("entity_ids"),
        Some(&Value::List(vec![
            Value::String("entity-1".to_string()),
            Value::String("entity-2".to_string()),
        ]))
    );
}

#[test]
fn counts_single_node_matches() {
    let mut db = Database::new();
    db.query("CREATE (:Memory {id: 1, title: 'One'})").unwrap();
    db.query("CREATE (:Memory {id: 2, title: 'Two'})").unwrap();
    db.query("CREATE (:Entity {id: 10, name: 'Rust'})").unwrap();

    let output = db
        .query("MATCH (m:Memory) RETURN count(*) AS total")
        .unwrap();
    assert_eq!(output.rows.len(), 1);
    assert_eq!(output.rows[0].get("total"), Some(&Value::Int(2)));

    let explain = db
        .explain_query("MATCH (m:Memory) RETURN count(*) AS total")
        .unwrap();
    assert!(explain.trace.selected_plan.contains("NodeCountExec"));
    assert!(!explain.trace.selected_plan.contains("AggregateExec"));
}

#[test]
fn counts_relationship_expansion_matches() {
    let mut db = Database::new();
    db.query(
        "CREATE (:Memory {id: 1, title: 'One'})-[:MENTIONS]->(:Entity {id: 10, name: 'Rust'})",
    )
    .unwrap();
    db.query(
        "CREATE (:Memory {id: 2, title: 'Two'})-[:MENTIONS]->(:Entity {id: 11, name: 'Kuzu'})",
    )
    .unwrap();

    let output = db
        .query("MATCH (m:Memory)-[:MENTIONS]->(e:Entity) RETURN count(e) AS total")
        .unwrap();
    assert_eq!(output.rows[0].get("total"), Some(&Value::Int(2)));
}

#[test]
fn counts_unfiltered_relationship_types_from_the_exact_count_store() {
    let mut db = Database::new();
    db.query("CREATE (:Memory {id: 1})-[:MENTIONS]->(:Entity {id: 10})")
        .unwrap();
    db.query("CREATE (:Memory {id: 2})-[:MENTIONS]->(:Entity {id: 11})")
        .unwrap();
    db.query("CREATE (:Entity {id: 10})-[:RELATES_TO]->(:Entity {id: 11})")
        .unwrap();

    let output = db
        .query("MATCH ()-[r:MENTIONS]->() RETURN count(r) AS total")
        .unwrap();
    assert_eq!(output.rows[0].get("total"), Some(&Value::Int(2)));

    let explain = db
        .explain_query("MATCH ()-[r:MENTIONS]->() RETURN count(r) AS total")
        .unwrap();
    assert!(explain
        .trace
        .selected_plan
        .contains("RelationshipCountExec"));
    assert!(!explain.trace.selected_plan.contains("AdjacencyExpandExec"));
    assert!(!explain.trace.selected_plan.contains("AggregateExec"));
}

#[test]
fn filtered_node_count_does_not_hydrate_unreferenced_payloads() {
    let execution_memory = crate::executor::ExecutionMemoryConfig {
        batch_payload_bytes: NonZeroUsize::new(512).unwrap(),
        ..crate::executor::ExecutionMemoryConfig::default()
    };
    let mut db = Database::new_with_config(DatabaseConfig {
        execution_memory,
        ..DatabaseConfig::default()
    });
    db.query(&format!(
        "CREATE (:Memory {{id: 'memory-1', content: '{}'}})",
        "x".repeat(64 * 1024)
    ))
    .unwrap();
    db.query("CREATE INDEX ON :Memory(id)").unwrap();
    let cypher = "MATCH (m:Memory {id: $id}) RETURN count(m) AS total";
    let parameters = BTreeMap::from([("id".to_string(), Value::String("memory-1".to_string()))]);

    let explain = db.explain_query_with_params(cypher, &parameters).unwrap();
    let physical_plan = explain.physical_plan.explain(0);
    assert!(physical_plan.contains("AggregateExec"));
    assert!(physical_plan.contains("NodeProjectionScanExec"));
    assert!(physical_plan.contains("output=node_binding"));
    assert!(physical_plan.contains("properties=[\"id\"]"));
    assert!(!physical_plan.contains("content"));

    let output = db.query_with_params(cypher, &parameters).unwrap();
    assert_eq!(output.rows[0].get("total"), Some(&Value::Int(1)));
}

#[test]
fn node_detail_neighbor_counts_use_distinct_neighbors_and_edges() {
    let mut db = Database::new();
    db.query("CREATE (:Entity {id: 'n1', name: 'One'})")
        .unwrap();
    db.query("CREATE (:Entity {id: 'n2', name: 'Two'})")
        .unwrap();
    db.query("MATCH (a:Entity {id: 'n1'}), (b:Entity {id: 'n2'}) CREATE (a)-[:RELATES_TO]->(b)")
        .unwrap();
    db.query("MATCH (a:Entity {id: 'n2'}), (b:Entity {id: 'n1'}) CREATE (a)-[:MENTIONS]->(b)")
        .unwrap();
    db.query("MATCH (a:Entity {id: 'n1'}), (b:Entity {id: 'n1'}) CREATE (a)-[:SELF]->(b)")
        .unwrap();

    let output = db
        .query_with_params(
            "MATCH (n)-[r]-(neighbor)
                 WHERE n.id = $node_id
                 RETURN COUNT(DISTINCT neighbor), COUNT(r)",
            &BTreeMap::from([("node_id".to_string(), Value::String("n1".into()))]),
        )
        .unwrap();

    assert_eq!(
        output.rows[0].get("count(DISTINCT neighbor)"),
        Some(&Value::Int(2))
    );
    assert_eq!(output.rows[0].get("count(r)"), Some(&Value::Int(3)));
}

#[test]
fn converging_relationship_pattern_counts_distinct_source_nodes() {
    let mut db = Database::new();
    db.query("CREATE (:Memory {id: 'target'})").unwrap();
    db.query("CREATE (:Memory {id: 'other-1'})").unwrap();
    db.query("CREATE (:Memory {id: 'other-2'})").unwrap();
    db.query("CREATE (:Entity {id: 'shared'})").unwrap();
    db.query(
        "MATCH (m:Memory {id: 'target'}), (e:Entity {id: 'shared'}) CREATE (m)-[:MENTIONS]->(e)",
    )
    .unwrap();
    db.query(
        "MATCH (m:Memory {id: 'other-1'}), (e:Entity {id: 'shared'}) CREATE (m)-[:MENTIONS]->(e)",
    )
    .unwrap();
    db.query(
        "MATCH (m:Memory {id: 'other-2'}), (e:Entity {id: 'shared'}) CREATE (m)-[:MENTIONS]->(e)",
    )
    .unwrap();

    let output = db
        .query(
            "MATCH (other:Memory)-[:MENTIONS]->(:Entity)<-[:MENTIONS]-(m:Memory {id: 'target'})
                 WHERE other.id <> 'target'
                 RETURN other.id AS id
                 ORDER BY id ASC",
        )
        .unwrap();

    assert_eq!(
        output.rows,
        vec![
            BTreeMap::from([("id".to_string(), Value::String("other-1".to_string()))]),
            BTreeMap::from([("id".to_string(), Value::String("other-2".to_string()))]),
        ]
    );

    let output = db
        .query(
            "MATCH (other:Memory)-[:MENTIONS]->(:Entity)<-[:MENTIONS]-(m:Memory {id: 'target'})
                 WHERE other.id <> 'target'
                 RETURN COUNT(DISTINCT other)",
        )
        .unwrap();

    assert_eq!(
        output.rows[0].get("count(DISTINCT other)"),
        Some(&Value::Int(2))
    );
}