Skip to content

Commit 20fd3aa

Browse files
authored
Merge pull request DeusData#2511 from DeusData/fix/issue-1364-distinct-before-cap
fix(cypher): count DISTINCT rows against the row cap
2 parents 873a966 + 1b5ba09 commit 20fd3aa

2 files changed

Lines changed: 226 additions & 18 deletions

File tree

‎src/cypher/cypher.c‎

Lines changed: 132 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
#include "foundation/platform.h"
1313
#include "foundation/limits.h"
1414
#include "foundation/log.h"
15+
#include "foundation/hash_table.h"
16+
#include "foundation/mem_core.h"
1517

1618
enum {
1719
CYP_BUF_16 = 16,
@@ -2837,6 +2839,104 @@ static void rb_add_row(result_builder_t *rb, const char **values) {
28372839
rb->rows[rb->row_count++] = row;
28382840
}
28392841

2842+
/* ── DISTINCT while projecting (#1364) ─────────────────────────────
2843+
*
2844+
* RETURN DISTINCT used to project up to the engine row cap and only then drop
2845+
* duplicates, so a value first seen past the cap never reached the result: on
2846+
* a 150k-edge index `RETURN DISTINCT type(r)` lost its one HAS_BRANCH edge.
2847+
* The projection loops now de-duplicate as they go, so the cap counts DISTINCT
2848+
* rows. Memory stays bounded by the cap: only admitted rows are remembered;
2849+
* rows past the cap are probed (no insert) solely to decide `truncated`. */
2850+
typedef struct {
2851+
CBMHashTable *seen; /* row key -> the same heap key; NULL = not DISTINCT */
2852+
} rb_distinct_t;
2853+
2854+
static void rb_distinct_init(rb_distinct_t *d, bool distinct) {
2855+
d->seen = distinct ? cbm_ht_create(CBM_SZ_64) : NULL;
2856+
}
2857+
2858+
static void rb_distinct_free_key(const char *key, void *value, void *userdata) {
2859+
(void)key;
2860+
(void)userdata;
2861+
cbm_free(CBM_MEM_CLASS_OTHER, value);
2862+
}
2863+
2864+
static void rb_distinct_free(rb_distinct_t *d) {
2865+
if (d->seen) {
2866+
cbm_ht_foreach(d->seen, rb_distinct_free_key, NULL);
2867+
cbm_ht_free(d->seen);
2868+
d->seen = NULL;
2869+
}
2870+
}
2871+
2872+
/* Length-prefixed row key ("<len>:<value>" per column), so no value content
2873+
* can make two different rows collide. NULL projects as "" (as rb_add_row). */
2874+
static char *rb_distinct_row_key(const char **vals, int n) {
2875+
size_t total = SKIP_ONE;
2876+
for (int i = 0; i < n; i++) {
2877+
total += (vals[i] ? strlen(vals[i]) : 0) + CBM_SZ_32;
2878+
}
2879+
char *key = cbm_alloc(CBM_MEM_CLASS_OTHER, total);
2880+
if (!key) {
2881+
return NULL;
2882+
}
2883+
size_t pos = 0;
2884+
key[0] = '\0';
2885+
for (int i = 0; i < n; i++) {
2886+
const char *v = vals[i] ? vals[i] : "";
2887+
int w = snprintf(key + pos, total - pos, "%zu:%s", strlen(v), v);
2888+
if (w > 0) {
2889+
pos += (size_t)w;
2890+
}
2891+
}
2892+
return key;
2893+
}
2894+
2895+
/* Admission for one projected row. Returns false for a row DISTINCT already
2896+
* holds. On true, *key_out is the key to hand to rb_distinct_keep (NULL when
2897+
* not DISTINCT, or when the key allocation failed — the row is then admitted
2898+
* without de-duplication rather than dropped). */
2899+
static bool rb_distinct_is_new(const rb_distinct_t *d, const char **vals, int n, char **key_out) {
2900+
*key_out = NULL;
2901+
if (!d->seen) {
2902+
return true;
2903+
}
2904+
char *key = rb_distinct_row_key(vals, n);
2905+
if (!key) {
2906+
return true;
2907+
}
2908+
if (cbm_ht_has(d->seen, key)) {
2909+
cbm_free(CBM_MEM_CLASS_OTHER, key);
2910+
return false;
2911+
}
2912+
*key_out = key;
2913+
return true;
2914+
}
2915+
2916+
static void rb_distinct_keep(rb_distinct_t *d, char *key) {
2917+
if (key) {
2918+
cbm_ht_set(d->seen, key, key);
2919+
}
2920+
}
2921+
2922+
/* Add one projected row under a row cap, de-duplicating when DISTINCT.
2923+
* Returns false once a NEW row arrives with the cap already full: the caller
2924+
* stops there, and flags truncation when the cap is the engine budget. A
2925+
* duplicate past the cap is neither kept nor evidence of truncation. */
2926+
static bool rb_add_row_capped(result_builder_t *rb, rb_distinct_t *d, const char **vals, int cap) {
2927+
char *key = NULL;
2928+
if (!rb_distinct_is_new(d, vals, rb->col_count, &key)) {
2929+
return true;
2930+
}
2931+
if (rb->row_count >= cap) {
2932+
cbm_free(CBM_MEM_CLASS_OTHER, key);
2933+
return false;
2934+
}
2935+
rb_distinct_keep(d, key);
2936+
rb_add_row(rb, vals);
2937+
return true;
2938+
}
2939+
28402940
/* ── Main execution ─────────────────────────────────────────────── */
28412941

28422942
/* Hard ceiling: queries returning more than this trigger an error instead of data.
@@ -4359,14 +4459,20 @@ static void execute_return_star_after_with(cbm_query_t *q, binding_t *bindings,
43594459
cols[i] = resolve_item_alias(&wc->items[i], name_bufs[i], sizeof(name_bufs[i]));
43604460
}
43614461
rb_set_columns(rb, cols, col_n);
4362-
for (int bi = 0; bi < bind_count && rb->row_count < max_rows; bi++) {
4462+
rb_distinct_t seen;
4463+
rb_distinct_init(&seen, q->ret && q->ret->distinct);
4464+
for (int bi = 0; bi < bind_count; bi++) {
43634465
const char *vals[CYP_MAX_VARS];
43644466
for (int i = 0; i < col_n; i++) {
43654467
cbm_node_t *vn = binding_get(&bindings[bi], cols[i]);
43664468
vals[i] = vn && vn->name ? vn->name : "";
43674469
}
4368-
rb_add_row(rb, vals);
4470+
if (!rb_add_row_capped(rb, &seen, vals, max_rows)) {
4471+
g_cypher_truncated = true;
4472+
break;
4473+
}
43694474
}
4475+
rb_distinct_free(&seen);
43704476
}
43714477

43724478
static void execute_return_star(cbm_query_t *q, binding_t *bindings, int bind_count, int max_rows,
@@ -4381,19 +4487,22 @@ static void execute_return_star(cbm_query_t *q, binding_t *bindings, int bind_co
43814487
int projection_cap = max_rows;
43824488
bool cap_is_engine_budget = true;
43834489
cbm_return_clause_t *ret = q->ret;
4384-
if (ret && ret->limit >= 0 && ret->limit <= max_rows && !ret->distinct &&
4385-
ret->order_key_count == 0 && ret->skip <= 0) {
4386-
projection_cap = ret->limit;
4490+
if (ret && ret->limit >= 0 && ret->limit <= max_rows && ret->order_key_count == 0 &&
4491+
ret->skip <= 0) {
4492+
projection_cap = ret->limit; /* DISTINCT: the cap counts distinct rows (#1364) */
43874493
cap_is_engine_budget = false;
43884494
}
4389-
for (int bi = 0; bi < bind_count && rb->row_count < projection_cap; bi++) {
4495+
rb_distinct_t seen;
4496+
rb_distinct_init(&seen, ret && ret->distinct);
4497+
for (int bi = 0; bi < bind_count; bi++) {
43904498
const char *vals[CBM_SZ_128];
43914499
project_star_row(&bindings[bi], vars, vc, vals);
4392-
rb_add_row(rb, vals);
4393-
}
4394-
if (cap_is_engine_budget && bind_count > projection_cap) {
4395-
g_cypher_truncated = true;
4500+
if (!rb_add_row_capped(rb, &seen, vals, projection_cap)) {
4501+
g_cypher_truncated = g_cypher_truncated || cap_is_engine_budget;
4502+
break;
4503+
}
43964504
}
4505+
rb_distinct_free(&seen);
43974506
}
43984507

43994508
/* Format an aggregate value into buf based on function name */
@@ -4662,22 +4771,25 @@ static void execute_return_simple(cbm_return_clause_t *ret, binding_t *bindings,
46624771
int max_rows, result_builder_t *rb) {
46634772
int proj_cap = max_rows;
46644773
bool cap_is_engine_budget = true;
4665-
if (ret->limit >= 0 && !ret->distinct && ret->order_key_count == 0 && ret->skip <= 0) {
4666-
proj_cap = ret->limit;
4774+
if (ret->limit >= 0 && ret->order_key_count == 0 && ret->skip <= 0) {
4775+
proj_cap = ret->limit; /* DISTINCT: the cap counts distinct rows (#1364) */
46674776
cap_is_engine_budget = false;
46684777
}
4669-
for (int bi = 0; bi < bind_count && rb->row_count < proj_cap; bi++) {
4778+
rb_distinct_t seen;
4779+
rb_distinct_init(&seen, ret->distinct);
4780+
for (int bi = 0; bi < bind_count; bi++) {
46704781
const char *vals[CBM_SZ_32];
46714782
char func_bufs[CBM_SZ_32][CBM_SZ_512];
46724783
for (int ci = 0; ci < ret->count; ci++) {
46734784
vals[ci] =
46744785
project_item(&bindings[bi], &ret->items[ci], func_bufs[ci], sizeof(func_bufs[ci]));
46754786
}
4676-
rb_add_row(rb, vals);
4677-
}
4678-
if (cap_is_engine_budget && bind_count > proj_cap) {
4679-
g_cypher_truncated = true;
4787+
if (!rb_add_row_capped(rb, &seen, vals, proj_cap)) {
4788+
g_cypher_truncated = g_cypher_truncated || cap_is_engine_budget;
4789+
break;
4790+
}
46804791
}
4792+
rb_distinct_free(&seen);
46814793
}
46824794

46834795
/* Build default 3-column headers (name, qualified_name, label) per variable */
@@ -5019,7 +5131,9 @@ static void execute_return_clause(cbm_query_t *q, cbm_return_clause_t *ret, bind
50195131
}
50205132
}
50215133

5022-
if (ret->distinct) {
5134+
/* The simple and star projections de-duplicate while projecting (#1364);
5135+
* only aggregate rows still need the post-pass. */
5136+
if (ret->distinct && has_agg && !ret->star) {
50235137
rb_apply_distinct(rb);
50245138
}
50255139
rb_apply_order_by(rb, ret);

‎tests/test_cypher.c‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1269,6 +1269,99 @@ TEST(cypher_exec_aggregate_sees_all_edges_beyond_expansion_cap_issue1196) {
12691269
PASS();
12701270
}
12711271

1272+
/* #1364: RETURN DISTINCT de-duplicated only AFTER the engine row cap, so a
1273+
* value that first appears past the cap was never seen: on a 150k-edge index
1274+
* `RETURN DISTINCT type(r)` returned 21 of 22 types (HAS_BRANCH, one edge,
1275+
* missing). The cap must count DISTINCT rows. Fixture: 20 CALLS edges, then
1276+
* one HAS_BRANCH edge from the last-inserted node; max_rows=5 puts the rare
1277+
* type far past the raw-row cap. */
1278+
TEST(cypher_return_distinct_counts_distinct_rows_against_cap_issue1364) {
1279+
cbm_store_t *s = cbm_store_open_memory();
1280+
ASSERT_NOT_NULL(s);
1281+
ASSERT_EQ(cbm_store_upsert_project(s, "test", "/tmp/test"), CBM_STORE_OK);
1282+
1283+
int64_t ids[22];
1284+
for (int i = 0; i < 22; i++) {
1285+
char name[32];
1286+
char qn[64];
1287+
snprintf(name, sizeof(name), "fn_%02d", i);
1288+
snprintf(qn, sizeof(qn), "test.%s", name);
1289+
cbm_node_t n = {.project = "test",
1290+
.label = "Function",
1291+
.name = name,
1292+
.qualified_name = qn,
1293+
.file_path = "a.py"};
1294+
ids[i] = cbm_store_upsert_node(s, &n);
1295+
ASSERT_GT(ids[i], 0);
1296+
}
1297+
for (int i = 0; i < 20; i++) {
1298+
cbm_edge_t e = {
1299+
.project = "test", .source_id = ids[i], .target_id = ids[i + 1], .type = "CALLS"};
1300+
cbm_store_insert_edge(s, &e);
1301+
}
1302+
cbm_edge_t rare = {
1303+
.project = "test", .source_id = ids[21], .target_id = ids[0], .type = "HAS_BRANCH"};
1304+
cbm_store_insert_edge(s, &rare);
1305+
1306+
/* Plain DISTINCT: both types, complete (2 distinct rows << cap of 5). */
1307+
cbm_cypher_result_t r = {0};
1308+
int rc = cbm_cypher_execute(s, "MATCH ()-[r]->() RETURN DISTINCT type(r) AS t", "test", 5, &r);
1309+
ASSERT_EQ(rc, 0);
1310+
ASSERT_EQ(r.row_count, 2);
1311+
bool saw_calls = false;
1312+
bool saw_branch = false;
1313+
for (int i = 0; i < r.row_count; i++) {
1314+
saw_calls = saw_calls || strcmp(r.rows[i][0], "CALLS") == 0;
1315+
saw_branch = saw_branch || strcmp(r.rows[i][0], "HAS_BRANCH") == 0;
1316+
}
1317+
ASSERT_TRUE(saw_calls);
1318+
ASSERT_TRUE(saw_branch);
1319+
ASSERT_FALSE(r.truncated);
1320+
cbm_cypher_result_free(&r);
1321+
1322+
/* DISTINCT + ORDER BY shares the cap. */
1323+
memset(&r, 0, sizeof(r));
1324+
rc = cbm_cypher_execute(s, "MATCH ()-[r]->() RETURN DISTINCT type(r) AS t ORDER BY t DESC",
1325+
"test", 5, &r);
1326+
ASSERT_EQ(rc, 0);
1327+
ASSERT_EQ(r.row_count, 2);
1328+
ASSERT_STR_EQ(r.rows[0][0], "HAS_BRANCH");
1329+
ASSERT_STR_EQ(r.rows[1][0], "CALLS");
1330+
ASSERT_FALSE(r.truncated);
1331+
cbm_cypher_result_free(&r);
1332+
1333+
/* DISTINCT + ORDER BY + SKIP/LIMIT: SKIP counts distinct rows. */
1334+
memset(&r, 0, sizeof(r));
1335+
rc = cbm_cypher_execute(
1336+
s, "MATCH ()-[r]->() RETURN DISTINCT type(r) AS t ORDER BY t SKIP 1 LIMIT 1", "test", 5,
1337+
&r);
1338+
ASSERT_EQ(rc, 0);
1339+
ASSERT_EQ(r.row_count, 1);
1340+
ASSERT_STR_EQ(r.rows[0][0], "HAS_BRANCH");
1341+
ASSERT_FALSE(r.truncated);
1342+
cbm_cypher_result_free(&r);
1343+
1344+
/* An explicit LIMIT on DISTINCT counts distinct rows too. */
1345+
memset(&r, 0, sizeof(r));
1346+
rc = cbm_cypher_execute(s, "MATCH ()-[r]->() RETURN DISTINCT type(r) AS t LIMIT 2", "test", 5,
1347+
&r);
1348+
ASSERT_EQ(rc, 0);
1349+
ASSERT_EQ(r.row_count, 2);
1350+
ASSERT_FALSE(r.truncated);
1351+
cbm_cypher_result_free(&r);
1352+
1353+
/* More distinct rows than the cap: still bounded and reported truncated. */
1354+
memset(&r, 0, sizeof(r));
1355+
rc = cbm_cypher_execute(s, "MATCH (a)-[r]->(b) RETURN DISTINCT b.name", "test", 5, &r);
1356+
ASSERT_EQ(rc, 0);
1357+
ASSERT_EQ(r.row_count, 5);
1358+
ASSERT_TRUE(r.truncated);
1359+
cbm_cypher_result_free(&r);
1360+
1361+
cbm_store_close(s);
1362+
PASS();
1363+
}
1364+
12721365
/* #874: coalesce(var.prop, literal) in WHERE — null-safe numeric filters
12731366
* for audit queries over OPTIONAL graph properties. The parser rejected the
12741367
* call outright ("unexpected operator"); RETURN-side coalesce already
@@ -4925,6 +5018,7 @@ SUITE(cypher) {
49255018
RUN_TEST(cypher_exec_where_eq);
49265019
RUN_TEST(cypher_exec_unlabeled_where_beyond_result_limit_issue1196);
49275020
RUN_TEST(cypher_exec_aggregate_sees_all_edges_beyond_expansion_cap_issue1196);
5021+
RUN_TEST(cypher_return_distinct_counts_distinct_rows_against_cap_issue1364);
49285022
RUN_TEST(cypher_exec_varlength_path_semantics_issue797);
49295023
RUN_TEST(cypher_exec_where_coalesce_issue874);
49305024
RUN_TEST(cypher_exec_where_regex);

0 commit comments

Comments
 (0)