@@ -715,6 +715,45 @@ TEST(cypher_exec_optional_empty_label_no_overflow) {
715715 PASS ();
716716}
717717
718+ /* Regression: the relationship variant of the test above. An OPTIONAL MATCH
719+ * with a relationship whose start AND terminal are both unbound, and whose
720+ * start matches zero nodes, drove cross_join_with_rels with extra_count == 0.
721+ * That sized its output for a single binding, and the OPTIONAL fallback then
722+ * wrote one row per existing binding without growing the buffer: a heap
723+ * buffer overflow once the first MATCH bound more than one node (ASan:
724+ * heap-buffer-overflow). The query text reaches this from the MCP query tool. */
725+ TEST (cypher_exec_optional_empty_label_rel_no_overflow ) {
726+ cbm_store_t * s = setup_cypher_store (); /* 4 Function nodes */
727+ cbm_cypher_result_t r = {0 };
728+
729+ int rc = cbm_cypher_execute (s ,
730+ "MATCH (a:Function) OPTIONAL MATCH (x:NoSuchLabel)-[:CALLS]->(y) "
731+ "RETURN a.name, x.name, y.name" ,
732+ "test" , 0 , & r );
733+ ASSERT_EQ (rc , 0 );
734+ ASSERT_EQ (r .col_count , 3 );
735+ /* One row per Function, each with x and y left unbound (""). */
736+ ASSERT_EQ (r .row_count , 4 );
737+ const char * want [] = {"HandleOrder" , "ValidateOrder" , "SubmitOrder" , "LogError" };
738+ for (int w = 0 ; w < 4 ; w ++ ) {
739+ int seen = 0 ;
740+ for (int i = 0 ; i < r .row_count ; i ++ ) {
741+ if (strcmp (r .rows [i ][0 ], want [w ]) == 0 ) {
742+ seen ++ ;
743+ }
744+ }
745+ ASSERT_EQ (seen , 1 );
746+ }
747+ for (int i = 0 ; i < r .row_count ; i ++ ) {
748+ ASSERT_STR_EQ (r .rows [i ][1 ], "" );
749+ ASSERT_STR_EQ (r .rows [i ][2 ], "" );
750+ }
751+
752+ cbm_cypher_result_free (& r );
753+ cbm_store_close (s );
754+ PASS ();
755+ }
756+
718757/* Regression: expand_pattern_rels sized its OPTIONAL-expansion output buffer as
719758 * bind_cap*10 + 1 — room for the bounded expansion (max_new = bind_cap*10) plus
720759 * a SINGLE OPTIONAL fallback row. When one source saturated the expansion to
@@ -4869,6 +4908,7 @@ SUITE(cypher) {
48694908 RUN_TEST (cypher_deep_nesting_rejected_not_crash );
48704909 RUN_TEST (cypher_exec_match_all_functions );
48714910 RUN_TEST (cypher_exec_optional_empty_label_no_overflow );
4911+ RUN_TEST (cypher_exec_optional_empty_label_rel_no_overflow );
48724912 RUN_TEST (cypher_cross_join_alloc_rejects_overflow );
48734913 RUN_TEST (cypher_exec_optional_rel_saturated_no_overflow );
48744914 RUN_TEST (cypher_exec_optional_saturated_does_not_fabricate_no_match );
0 commit comments