You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@age.apache.org by "sandy-bes (via GitHub)" <gi...@apache.org> on 2026/03/03 07:14:52 UTC

[PR] Add index scan [age]

sandy-bes opened a new pull request, #2351:
URL: https://github.com/apache/age/pull/2351

   Motivation / Problem: 
   As a result of load testing, a significant performance degradation was found in insertion scenarios. The scenarios used were taken from an open-source benchmark and rewritten in pure SQL. Examples of the queries can be found here:
   1) https://github.com/ldbc/ldbc_snb_interactive_v1_impls/blob/main/cypher/queries/interactive-update-1.cypher
   2) https://github.com/ldbc/ldbc_snb_interactive_v1_impls/blob/main/cypher/queries/interactive-update-6.cypher
   3) https://github.com/ldbc/ldbc_snb_interactive_v1_impls/blob/main/cypher/queries/interactive-update-7.cypher
   
   Analysis showed that the main bottleneck is the entity_exists function. The root cause lies in the use of a Sequential Scan (SeqScan) to check for the existence of an entity prior to insertion. The time complexity of a `SeqScan` is O(N), meaning the search time grows linearly as the number of rows in the table increases. The larger the graph became, the longer each individual insertion took. This led to a drop in TPS regardless of the concurrency level (the issue was consistently reproduced with both 1 and 30 threads).
   
   Changes Made:
   - Added Index Scan (IndexScan / time complexity O(log N)) inside the entity_exists function.
   - Refactored other functions utilizing SeqScan — they were also migrated to use IndexScan wherever applicable.
   
   Performance Impact: 
   Benchmarks were conducted on a server with 30 CPU cores and 32 GB of RAM, using a graph ranging from 20,000 to 200,000 objects over a 2-minute duration. The transition to index access completely eliminated the performance degradation associated with data volume growth:
   - Before: ~1,500 TPS (at peak, with subsequent degradation as the table grew).
   - After: Stable ~15,000 TPS (a 10x speedup).
   
   Acknowledgments:
   - Huge thanks to Daria Barsukova for conducting the load testing and isolating the issue.
   - Implementation of index scanning: Alexandra Bondar.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r3013694013


##########
src/backend/utils/adt/agtype.c:
##########
@@ -5646,19 +5649,74 @@ static Datum get_vertex(const char *graph, const char *vertex_label,
         aclcheck_error(aclresult, OBJECT_TABLE, vertex_label);
     }
 
-    /* initialize the scan key */
-    ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
-                Int64GetDatum(graphid));
-
-    /* open the relation (table), begin the scan, and get the tuple  */
+    /* open the relation (table) */
     graph_vertex_label = table_open(vertex_label_table_oid, ShareLock);
-    scan_desc = table_beginscan(graph_vertex_label, snapshot, 1, scan_keys);
-    tuple = heap_getnext(scan_desc, ForwardScanDirection);
+
+    index_oid = RelationGetPrimaryKeyIndex(graph_vertex_label, false);
+
+    if (!OidIsValid(index_oid))
+    {
+        List *idx_list = RelationGetIndexList(graph_vertex_label);
+        ListCell *lc;
+        foreach(lc, idx_list)
+        {
+            Oid curr = lfirst_oid(lc);
+            Relation idx_rel = index_open(curr, ShareLock);
+
+            if (idx_rel->rd_index->indisvalid &&
+                idx_rel->rd_index->indnatts >= 1 &&
+                idx_rel->rd_index->indkey.values[0] == 1)
+            {
+                index_oid = curr;
+                index_close(idx_rel, ShareLock);
+                break;
+            }
+            index_close(idx_rel, ShareLock);
+        }
+        list_free(idx_list);
+    }
+
+    if (OidIsValid(index_oid))
+    {
+        IndexScanDesc index_scan_desc;
+        Relation index_rel;
+
+        index_rel = index_open(index_oid, ShareLock);
+        slot = table_slot_create(graph_vertex_label, NULL);
+
+        /* initialize the scan key using GRAPHIDEQ for index */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber,
+                    F_GRAPHIDEQ, Int64GetDatum(graphid));
+
+        index_scan_desc = index_beginscan(graph_vertex_label, index_rel, 
+                                          snapshot, NULL, 1, 0);
+        index_rescan(index_scan_desc, scan_keys, 1, NULL, 0);
+
+        if (index_getnext_slot(index_scan_desc, ForwardScanDirection, slot))
+        {
+            tuple = ExecCopySlotHeapTuple(slot);
+            should_free_tuple = true;
+        }
+
+        index_endscan(index_scan_desc);
+        index_close(index_rel, ShareLock);
+        ExecDropSingleTupleTableSlot(slot);
+    }
+    else
+    {
+        /* fallback to sequential scan */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
+                    Int64GetDatum(graphid));

Review Comment:
   Done! I've refactored this as requested. I also left a note about fixing this on a similar comment during the second review iteration.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r3013703301


##########
src/backend/utils/adt/age_global_graph.c:
##########
@@ -204,43 +204,117 @@ static List *get_ag_labels_names(Snapshot snapshot, Oid graph_oid,
     TableScanDesc scan_desc;
     HeapTuple tuple;
     TupleDesc tupdesc;
+    Oid index_oid = InvalidOid;
 
     /* we need a valid snapshot */
     Assert(snapshot != NULL);
 
-    /* setup scan keys to get all edges for the given graph oid */
-    ScanKeyInit(&scan_keys[1], Anum_ag_label_graph, BTEqualStrategyNumber,
-                F_OIDEQ, ObjectIdGetDatum(graph_oid));
-    ScanKeyInit(&scan_keys[0], Anum_ag_label_kind, BTEqualStrategyNumber,
-                F_CHAREQ, CharGetDatum(label_type));
-
     /* setup the table to be scanned, ag_label in this case */
     ag_label = table_open(ag_label_relation_id(), AccessShareLock);
-    scan_desc = table_beginscan(ag_label, snapshot, 2, scan_keys);
 
     /* get the tupdesc - we don't need to release this one */
     tupdesc = RelationGetDescr(ag_label);
     /* bail if the number of columns differs - this table has 5 */
     Assert(tupdesc->natts == Natts_ag_label);
 
-    /* get all of the label names */
-    while((tuple = heap_getnext(scan_desc, ForwardScanDirection)) != NULL)
+    /* We look for 'ag_label_graph_oid_index' or any index starting with 'graph' */

Review Comment:
   Done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r2989807659


##########
src/backend/utils/adt/agtype.c:
##########
@@ -5646,19 +5649,74 @@ static Datum get_vertex(const char *graph, const char *vertex_label,
         aclcheck_error(aclresult, OBJECT_TABLE, vertex_label);
     }
 
-    /* initialize the scan key */
-    ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
-                Int64GetDatum(graphid));
-
-    /* open the relation (table), begin the scan, and get the tuple  */
+    /* open the relation (table) */
     graph_vertex_label = table_open(vertex_label_table_oid, ShareLock);
-    scan_desc = table_beginscan(graph_vertex_label, snapshot, 1, scan_keys);
-    tuple = heap_getnext(scan_desc, ForwardScanDirection);
+
+    index_oid = RelationGetPrimaryKeyIndex(graph_vertex_label, false);
+
+    if (!OidIsValid(index_oid))
+    {
+        List *idx_list = RelationGetIndexList(graph_vertex_label);
+        ListCell *lc;
+        foreach(lc, idx_list)
+        {
+            Oid curr = lfirst_oid(lc);
+            Relation idx_rel = index_open(curr, ShareLock);
+
+            if (idx_rel->rd_index->indisvalid &&
+                idx_rel->rd_index->indnatts >= 1 &&
+                idx_rel->rd_index->indkey.values[0] == 1)
+            {
+                index_oid = curr;
+                index_close(idx_rel, ShareLock);
+                break;
+            }
+            index_close(idx_rel, ShareLock);
+        }
+        list_free(idx_list);
+    }
+
+    if (OidIsValid(index_oid))
+    {
+        IndexScanDesc index_scan_desc;
+        Relation index_rel;
+
+        index_rel = index_open(index_oid, ShareLock);
+        slot = table_slot_create(graph_vertex_label, NULL);
+
+        /* initialize the scan key using GRAPHIDEQ for index */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber,
+                    F_GRAPHIDEQ, Int64GetDatum(graphid));
+
+        index_scan_desc = index_beginscan(graph_vertex_label, index_rel, 
+                                          snapshot, NULL, 1, 0);
+        index_rescan(index_scan_desc, scan_keys, 1, NULL, 0);
+
+        if (index_getnext_slot(index_scan_desc, ForwardScanDirection, slot))
+        {
+            tuple = ExecCopySlotHeapTuple(slot);
+            should_free_tuple = true;
+        }
+
+        index_endscan(index_scan_desc);
+        index_close(index_rel, ShareLock);
+        ExecDropSingleTupleTableSlot(slot);
+    }
+    else
+    {
+        /* fallback to sequential scan */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
+                    Int64GetDatum(graphid));

Review Comment:
   Let me think about that.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r3013702547


##########
src/backend/catalog/ag_label.c:
##########
@@ -297,49 +298,111 @@ List *get_all_edge_labels_per_graph(EState *estate, Oid graph_oid)
     HeapTuple tuple;
     TupleTableSlot *slot;
     ResultRelInfo *resultRelInfo;
-
-    /* setup scan keys to get all edges for the given graph oid */
-    ScanKeyInit(&scan_keys[1], Anum_ag_label_graph, BTEqualStrategyNumber,
-                F_OIDEQ, ObjectIdGetDatum(graph_oid));
-    ScanKeyInit(&scan_keys[0], Anum_ag_label_kind, BTEqualStrategyNumber,
-                F_CHAREQ, CharGetDatum(LABEL_TYPE_EDGE));
+    Oid index_oid;
 
     /* setup the table to be scanned */
-    ag_label = table_open(ag_label_relation_id(), RowExclusiveLock);
-    scan_desc = table_beginscan(ag_label, estate->es_snapshot, 2, scan_keys);
+    ag_label = table_open(ag_label_relation_id(), AccessShareLock);
+
+    index_oid = find_usable_index_for_attr(ag_label, Anum_ag_label_graph);
 
     resultRelInfo = create_entity_result_rel_info(estate, "ag_catalog",
                                                   "ag_label");
 

Review Comment:
   I see exactly what you mean now: the code explicitly does table_open with AccessShareLock, and then create_entity_result_rel_info opens the exact same relation again via parserOpenTable with RowExclusiveLock.
   
   This is actually existing code that I didn't write. To keep the PR focused and avoid breaking existing logic, I didn't change its internal mechanics. Let me know if you'd still prefer me to fix it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-4225765911

   @sandy-bes Okay, one small-ish ask. We used to not have this coding rule, so code exists that doesn't follow it. However, we try to enforce that all new code always uses braces {} even for one line of code. If you could make that change in your code, please :)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r2930489790


##########
src/backend/executor/cypher_set.c:
##########
@@ -628,60 +656,100 @@ static void process_update_list(CustomScanState *node)
 
         if (luindex[update_item->entity_position - 1] == lidx)
         {
-            /*
-             * Setup the scan key to require the id field on-disc to match the
-             * entity's graphid.
-             */
-            ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
-                        GRAPHID_GET_DATUM(id->val.int_value));
-            /*
-             * Setup the scan description, with the correct snapshot and scan
-             * keys.
-             */
-            scan_desc = table_beginscan(resultRelInfo->ri_RelationDesc,
-                                        estate->es_snapshot, 1, scan_keys);
-            /* Retrieve the tuple. */
-            heap_tuple = heap_getnext(scan_desc, ForwardScanDirection);
-
-            /*
-             * If the heap tuple still exists (It wasn't deleted between the
-             * match and this SET/REMOVE) update the heap_tuple.
-             */
-            if (HeapTupleIsValid(heap_tuple))
-            {
-                bool should_update = true;
-                Oid relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
-
-                /* Check RLS security quals (USING policy) before update */
-                if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
+            if (OidIsValid(index_oid))
+             {
+                Relation index_rel;
+                IndexScanDesc scan_desc;
+                TupleTableSlot *index_slot;
+
+                index_rel = index_open(index_oid, RowExclusiveLock);
+                
+                /*
+                 * Setup the scan key to require the id field on-disc to match the
+                 * entity's graphid.
+                 */
+                ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
+                            GRAPHID_GET_DATUM(id->val.int_value));
+
+                index_slot = table_slot_create(rel, NULL);
+                scan_desc = index_beginscan(rel, index_rel, estate->es_snapshot, NULL, 1, 0);
+                index_rescan(scan_desc, scan_keys, 1, NULL, 0);
+
+                if (index_getnext_slot(scan_desc, ForwardScanDirection, index_slot))
                 {
-                    RLSCacheEntry *entry;
+                    bool shouldFree;
+                    
+                    /* Retrieve the tuple from the slot */
+                    heap_tuple = ExecFetchSlotHeapTuple(index_slot, true, &shouldFree);
 
-                    /* Entry was already created earlier when setting up WCOs */
-                    entry = hash_search(qual_cache, &relid, HASH_FIND, NULL);
-                    if (!entry)
+                    if (HeapTupleIsValid(heap_tuple))
                     {
-                        ereport(ERROR,
-                                (errcode(ERRCODE_INTERNAL_ERROR),
-                                 errmsg("missing RLS cache entry for relation %u",
-                                        relid)));
+                        heap_tuple = update_entity_tuple(resultRelInfo, slot, estate, heap_tuple);
                     }
 
-                    ExecStoreHeapTuple(heap_tuple, entry->slot, false);
-                    should_update = check_security_quals(entry->qualExprs,
-                                                         entry->slot,
-                                                         econtext);
+                    if (shouldFree)
+                        heap_freetuple(heap_tuple);

Review Comment:
   I modified the call to update_entity_tuple() so that it no longer overwrites the heap_tuple variable. This ensures that when shouldFree is true, heap_freetuple(heap_tuple) safely frees the original fetched tuple without causing memory corruption or double-free issues.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r3013697757


##########
src/backend/utils/adt/agtype.c:
##########
@@ -12020,6 +12065,38 @@ static int64 get_int64_from_int_datums(Datum d, Oid type, char *funcname,
     return result;
 }
 
+/*
+ * Helper function to find a valid index for a specific attribute.
+ * Returns the OID of the index, or InvalidOid if none is found.
+ */
+Oid find_usable_index_for_attr(Relation rel, AttrNumber attnum)
+{
+List *index_list = RelationGetIndexList(rel);
+    ListCell *ilc;
+    Oid index_oid = InvalidOid;
+
+    foreach(ilc, index_list)
+    {
+        Oid curr_idx_oid = lfirst_oid(ilc);
+        Relation curr_idx_rel = index_open(curr_idx_oid, AccessShareLock);
+
+        if (curr_idx_rel->rd_index->indisvalid &&
+            curr_idx_rel->rd_index->indnatts >= 1 &&
+            curr_idx_rel->rd_index->indkey.values[0] == attnum) 

Review Comment:
   I've updated the helper function to strictly filter for B-Tree indexes (relam == BTREE_AM_OID) and to skip partial indexes. To make this specific behavior explicit and prevent any future misuse, I also took the liberty of renaming the function to find_usable_btree_index_for_attr.



##########
src/backend/utils/adt/agtype.c:
##########
@@ -5646,19 +5649,52 @@ static Datum get_vertex(const char *graph, const char *vertex_label,
         aclcheck_error(aclresult, OBJECT_TABLE, vertex_label);
     }
 
-    /* initialize the scan key */
-    ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
-                Int64GetDatum(graphid));
-
-    /* open the relation (table), begin the scan, and get the tuple  */
+    /* open the relation (table) */
     graph_vertex_label = table_open(vertex_label_table_oid, ShareLock);
-    scan_desc = table_beginscan(graph_vertex_label, snapshot, 1, scan_keys);
-    tuple = heap_getnext(scan_desc, ForwardScanDirection);
+
+    index_oid = find_usable_index_for_attr(graph_vertex_label, 1);
+
+    if (OidIsValid(index_oid))
+    {
+        IndexScanDesc index_scan_desc;
+        Relation index_rel;
+
+        index_rel = index_open(index_oid, ShareLock);
+        slot = table_slot_create(graph_vertex_label, NULL);
+
+        /* initialize the scan key using GRAPHIDEQ for index */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber,
+                    F_GRAPHIDEQ, Int64GetDatum(graphid));
+
+        index_scan_desc = index_beginscan(graph_vertex_label, index_rel, 
+                                          snapshot, NULL, 1, 0);
+        index_rescan(index_scan_desc, scan_keys, 1, NULL, 0);
+
+        if (index_getnext_slot(index_scan_desc, ForwardScanDirection, slot))
+        {
+            tuple = ExecCopySlotHeapTuple(slot);
+            should_free_tuple = true;
+        }
+
+        index_endscan(index_scan_desc);
+        index_close(index_rel, ShareLock);
+        ExecDropSingleTupleTableSlot(slot);
+    }
+    else
+    {
+        /* fallback to sequential scan */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
+                    Int64GetDatum(graphid));
+
+        scan_desc = table_beginscan(graph_vertex_label, snapshot, 1, scan_keys);
+        tuple = heap_getnext(scan_desc, ForwardScanDirection);

Review Comment:
   As I mentioned in a similar comment, this was existing code that I simply moved into the else branch, which is why I didn't touch its internal mechanics initially. I'll update the fallback path to use F_GRAPHIDEQ with the correct datum conversion right away.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r3013700953


##########
src/backend/executor/cypher_utils.c:
##########
@@ -238,20 +240,47 @@ bool entity_exists(EState *estate, Oid graph_oid, graphid id)
                                       GetCurrentCommandId(false));
 
     rel = table_open(label->relation, RowExclusiveLock);
-    scan_desc = table_beginscan(rel, estate->es_snapshot, 1, scan_keys);
 
-    tuple = heap_getnext(scan_desc, ForwardScanDirection);
+    index_oid = find_usable_index_for_attr(rel, 1);
 
-    /*
-     * If a single tuple was returned, the tuple is still valid, otherwise'
-     * set to false.
-     */
-    if (!HeapTupleIsValid(tuple))
+    if (OidIsValid(index_oid))
     {
-        result = false;
+        IndexScanDesc index_scan_desc;
+        Relation index_rel;
+
+        slot = table_slot_create(rel, NULL);
+
+        index_rel = index_open(index_oid, RowExclusiveLock);

Review Comment:
   I originally matched the table's lock level due to the upstream modification paths (create_vertex, etc.), but I see now why AccessShareLock is the correct (and much more concurrent) choice for the index scan itself. Fixed in the latest commit.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-4128453464

   @sandy-bes Sorry, you know the drill by now, more Copilot,... I keep hoping it stops complaining :( But, I think we're close.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-3992543259

   @sandy-bes Please address the above Copilot suggestions


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r2879242495


##########
src/backend/executor/cypher_set.c:
##########
@@ -628,60 +656,100 @@ static void process_update_list(CustomScanState *node)
 
         if (luindex[update_item->entity_position - 1] == lidx)
         {
-            /*
-             * Setup the scan key to require the id field on-disc to match the
-             * entity's graphid.
-             */
-            ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
-                        GRAPHID_GET_DATUM(id->val.int_value));
-            /*
-             * Setup the scan description, with the correct snapshot and scan
-             * keys.
-             */
-            scan_desc = table_beginscan(resultRelInfo->ri_RelationDesc,
-                                        estate->es_snapshot, 1, scan_keys);
-            /* Retrieve the tuple. */
-            heap_tuple = heap_getnext(scan_desc, ForwardScanDirection);
-
-            /*
-             * If the heap tuple still exists (It wasn't deleted between the
-             * match and this SET/REMOVE) update the heap_tuple.
-             */
-            if (HeapTupleIsValid(heap_tuple))
-            {
-                bool should_update = true;
-                Oid relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
-
-                /* Check RLS security quals (USING policy) before update */
-                if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
+            if (OidIsValid(index_oid))
+             {
+                Relation index_rel;
+                IndexScanDesc scan_desc;
+                TupleTableSlot *index_slot;
+
+                index_rel = index_open(index_oid, RowExclusiveLock);
+                
+                /*
+                 * Setup the scan key to require the id field on-disc to match the
+                 * entity's graphid.
+                 */
+                ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
+                            GRAPHID_GET_DATUM(id->val.int_value));
+
+                index_slot = table_slot_create(rel, NULL);
+                scan_desc = index_beginscan(rel, index_rel, estate->es_snapshot, NULL, 1, 0);
+                index_rescan(scan_desc, scan_keys, 1, NULL, 0);
+
+                if (index_getnext_slot(scan_desc, ForwardScanDirection, index_slot))
                 {
-                    RLSCacheEntry *entry;
+                    bool shouldFree;
+                    
+                    /* Retrieve the tuple from the slot */
+                    heap_tuple = ExecFetchSlotHeapTuple(index_slot, true, &shouldFree);
 
-                    /* Entry was already created earlier when setting up WCOs */
-                    entry = hash_search(qual_cache, &relid, HASH_FIND, NULL);
-                    if (!entry)
+                    if (HeapTupleIsValid(heap_tuple))
                     {
-                        ereport(ERROR,
-                                (errcode(ERRCODE_INTERNAL_ERROR),
-                                 errmsg("missing RLS cache entry for relation %u",
-                                        relid)));
+                        heap_tuple = update_entity_tuple(resultRelInfo, slot, estate, heap_tuple);

Review Comment:
   The index-scan update path skips the RLS USING-policy check (check_security_quals) that the sequential-scan path performs. This can allow SET/REMOVE to update rows that should be filtered by RLS, and also changes behavior (it should silently skip when filtered). Apply the same RLS gating logic in the index-scan branch before calling update_entity_tuple().
   ```suggestion
                           /*
                            * Apply the same RLS USING-policy gating as in the
                            * sequential-scan path: if the tuple is filtered by
                            * RLS, silently skip the update.
                            */
                           if (check_security_quals(estate, resultRelInfo, heap_tuple))
                               heap_tuple = update_entity_tuple(resultRelInfo, slot, estate, heap_tuple);
   ```



##########
src/backend/executor/cypher_set.c:
##########
@@ -628,60 +656,100 @@ static void process_update_list(CustomScanState *node)
 
         if (luindex[update_item->entity_position - 1] == lidx)
         {
-            /*
-             * Setup the scan key to require the id field on-disc to match the
-             * entity's graphid.
-             */
-            ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
-                        GRAPHID_GET_DATUM(id->val.int_value));
-            /*
-             * Setup the scan description, with the correct snapshot and scan
-             * keys.
-             */
-            scan_desc = table_beginscan(resultRelInfo->ri_RelationDesc,
-                                        estate->es_snapshot, 1, scan_keys);
-            /* Retrieve the tuple. */
-            heap_tuple = heap_getnext(scan_desc, ForwardScanDirection);
-
-            /*
-             * If the heap tuple still exists (It wasn't deleted between the
-             * match and this SET/REMOVE) update the heap_tuple.
-             */
-            if (HeapTupleIsValid(heap_tuple))
-            {
-                bool should_update = true;
-                Oid relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
-
-                /* Check RLS security quals (USING policy) before update */
-                if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
+            if (OidIsValid(index_oid))
+             {
+                Relation index_rel;
+                IndexScanDesc scan_desc;
+                TupleTableSlot *index_slot;
+
+                index_rel = index_open(index_oid, RowExclusiveLock);
+                
+                /*
+                 * Setup the scan key to require the id field on-disc to match the
+                 * entity's graphid.
+                 */
+                ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
+                            GRAPHID_GET_DATUM(id->val.int_value));
+
+                index_slot = table_slot_create(rel, NULL);
+                scan_desc = index_beginscan(rel, index_rel, estate->es_snapshot, NULL, 1, 0);
+                index_rescan(scan_desc, scan_keys, 1, NULL, 0);
+
+                if (index_getnext_slot(scan_desc, ForwardScanDirection, index_slot))
                 {
-                    RLSCacheEntry *entry;
+                    bool shouldFree;
+                    
+                    /* Retrieve the tuple from the slot */
+                    heap_tuple = ExecFetchSlotHeapTuple(index_slot, true, &shouldFree);
 
-                    /* Entry was already created earlier when setting up WCOs */
-                    entry = hash_search(qual_cache, &relid, HASH_FIND, NULL);
-                    if (!entry)
+                    if (HeapTupleIsValid(heap_tuple))
                     {
-                        ereport(ERROR,
-                                (errcode(ERRCODE_INTERNAL_ERROR),
-                                 errmsg("missing RLS cache entry for relation %u",
-                                        relid)));
+                        heap_tuple = update_entity_tuple(resultRelInfo, slot, estate, heap_tuple);
                     }
 
-                    ExecStoreHeapTuple(heap_tuple, entry->slot, false);
-                    should_update = check_security_quals(entry->qualExprs,
-                                                         entry->slot,
-                                                         econtext);
+                    if (shouldFree)
+                        heap_freetuple(heap_tuple);

Review Comment:
   In the index-scan branch, heap_tuple is overwritten with the HeapTuple returned by update_entity_tuple(), but the code then calls heap_freetuple(heap_tuple) based on shouldFree from ExecFetchSlotHeapTuple(index_slot,...). This can free the wrong tuple (and potentially double-free or corrupt memory). Keep the fetched tuple in a separate variable and only free that one when shouldFree is true.



##########
src/backend/catalog/ag_label.c:
##########
@@ -297,46 +298,104 @@ List *get_all_edge_labels_per_graph(EState *estate, Oid graph_oid)
     HeapTuple tuple;
     TupleTableSlot *slot;
     ResultRelInfo *resultRelInfo;
+    Oid index_oid;
 
-    /* setup scan keys to get all edges for the given graph oid */
-    ScanKeyInit(&scan_keys[1], Anum_ag_label_graph, BTEqualStrategyNumber,
-                F_OIDEQ, ObjectIdGetDatum(graph_oid));
-    ScanKeyInit(&scan_keys[0], Anum_ag_label_kind, BTEqualStrategyNumber,
-                F_CHAREQ, CharGetDatum(LABEL_TYPE_EDGE));
+    index_oid = get_relname_relid("ag_label_graph_oid_index", 
+                                  get_namespace_oid("ag_catalog", false));
 
     /* setup the table to be scanned */
     ag_label = table_open(ag_label_relation_id(), RowExclusiveLock);
-    scan_desc = table_beginscan(ag_label, estate->es_snapshot, 2, scan_keys);
 
     resultRelInfo = create_entity_result_rel_info(estate, "ag_catalog",
                                                   "ag_label");
 
-    slot = ExecInitExtraTupleSlot(
-        estate, RelationGetDescr(resultRelInfo->ri_RelationDesc),
-        &TTSOpsHeapTuple);
-
-    /* scan through the results and get all the label names. */
-    while(true)
+    if (OidIsValid(index_oid))
+    {
+        Relation index_rel;
+        IndexScanDesc index_scan_desc;
+
+        slot = ExecInitExtraTupleSlot(
+            estate, RelationGetDescr(resultRelInfo->ri_RelationDesc),
+            &TTSOpsBufferHeapTuple);
+
+        index_rel = index_open(index_oid, RowExclusiveLock);
+
+        ScanKeyInit(&scan_keys[0], Anum_ag_label_name, BTEqualStrategyNumber,
+                    F_OIDEQ, ObjectIdGetDatum(graph_oid));
+
+        index_scan_desc = index_beginscan(ag_label, index_rel, estate->es_snapshot, NULL, 1, 0);
+        index_rescan(index_scan_desc, scan_keys, 1, NULL, 0);
+
+        while (index_getnext_slot(index_scan_desc, ForwardScanDirection, slot))
+        {
+            Name label;
+            Name lval;
+            bool isNull;
+            Datum datum;
+            char kind;
+
+            /*There isn't field kind in index. So we should check it by hands*/
+            datum = slot_getattr(slot, Anum_ag_label_kind, &isNull);
+            if (isNull)
+                continue;
+
+            kind = DatumGetChar(datum);
+            
+            if (kind != LABEL_TYPE_EDGE)
+                continue;
+
+            datum = slot_getattr(slot, Anum_ag_label_name, &isNull);
+            if (!isNull)
+            {
+                label = DatumGetName(datum);
+                lval = (Name) palloc(NAMEDATALEN);
+                namestrcpy(lval, NameStr(*label));
+                labels = lappend(labels, lval);
+            }
+        }
+
+        index_endscan(index_scan_desc);
+        index_close(index_rel, RowExclusiveLock);
+    } else
     {
-        Name label;
-        bool isNull;
-        Datum datum;
+        slot = ExecInitExtraTupleSlot(
+            estate, RelationGetDescr(resultRelInfo->ri_RelationDesc),
+            &TTSOpsHeapTuple);
 
-        tuple = heap_getnext(scan_desc, ForwardScanDirection);
+        // setup scan keys to get all edges for the given graph oid
+        ScanKeyInit(&scan_keys[1], Anum_ag_label_graph, BTEqualStrategyNumber,
+                  F_OIDEQ, ObjectIdGetDatum(graph_oid));
+        ScanKeyInit(&scan_keys[0], Anum_ag_label_kind, BTEqualStrategyNumber,
+                  F_CHAREQ, CharGetDatum(LABEL_TYPE_EDGE));

Review Comment:
   This file uses C++-style '//' comments in newly added code. The rest of the backend C codebase follows C90/C-style block comments, and using '//' can break builds under stricter C90 settings. Please convert these to /* ... */ comments for consistency and portability.



##########
src/backend/utils/adt/agtype.c:
##########
@@ -5646,19 +5649,74 @@ static Datum get_vertex(const char *graph, const char *vertex_label,
         aclcheck_error(aclresult, OBJECT_TABLE, vertex_label);
     }
 
-    /* initialize the scan key */
-    ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
-                Int64GetDatum(graphid));
-
-    /* open the relation (table), begin the scan, and get the tuple  */
+    /* open the relation (table) */
     graph_vertex_label = table_open(vertex_label_table_oid, ShareLock);
-    scan_desc = table_beginscan(graph_vertex_label, snapshot, 1, scan_keys);
-    tuple = heap_getnext(scan_desc, ForwardScanDirection);
+
+    index_oid = RelationGetPrimaryKeyIndex(graph_vertex_label, false);
+
+    if (!OidIsValid(index_oid))
+    {
+        List *idx_list = RelationGetIndexList(graph_vertex_label);
+        ListCell *lc;
+        foreach(lc, idx_list)
+        {
+            Oid curr = lfirst_oid(lc);
+            Relation idx_rel = index_open(curr, ShareLock);
+
+            if (idx_rel->rd_index->indisvalid &&
+                idx_rel->rd_index->indnatts >= 1 &&
+                idx_rel->rd_index->indkey.values[0] == 1)
+            {
+                index_oid = curr;
+                index_close(idx_rel, ShareLock);
+                break;
+            }
+            index_close(idx_rel, ShareLock);
+        }
+        list_free(idx_list);
+    }
+
+    if (OidIsValid(index_oid))
+    {
+        IndexScanDesc index_scan_desc;
+        Relation index_rel;
+
+        index_rel = index_open(index_oid, ShareLock);
+        slot = table_slot_create(graph_vertex_label, NULL);
+
+        /* initialize the scan key using GRAPHIDEQ for index */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber,
+                    F_GRAPHIDEQ, Int64GetDatum(graphid));
+
+        index_scan_desc = index_beginscan(graph_vertex_label, index_rel, 
+                                          snapshot, NULL, 1, 0);
+        index_rescan(index_scan_desc, scan_keys, 1, NULL, 0);
+
+        if (index_getnext_slot(index_scan_desc, ForwardScanDirection, slot))
+        {
+            tuple = ExecCopySlotHeapTuple(slot);
+            should_free_tuple = true;
+        }
+
+        index_endscan(index_scan_desc);
+        index_close(index_rel, ShareLock);
+        ExecDropSingleTupleTableSlot(slot);
+    }
+    else
+    {
+        /* fallback to sequential scan */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
+                    Int64GetDatum(graphid));

Review Comment:
   The sequential-scan fallback still uses F_OIDEQ to compare the graphid column. Since the index path uses F_GRAPHIDEQ (and the column type is GRAPHIDOID), the fallback should also use F_GRAPHIDEQ/GRAPHID_GET_DATUM to avoid incorrect comparisons when no suitable index is found.
   ```suggestion
           ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
                       GRAPHID_GET_DATUM(graphid));
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-4160168744

   @jrgemignani No worries at all, I completely understand! As much as it complains, I have to admit Copilot actually gives some really good hints and catches subtle things. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-3995924097

   @sandy-bes 
   
   > I've updated the PR description with the steps to reproduce the tests locally.
   
   I was able to validate the perf claims with Opus earlier. 
   
   But, more importantly, I can't do anything with this PR until **all of the above issues (Copilot & Opus)** have been addressed. Including noting any use of AI. Btw, using AI is fine, it just needs to be noted.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r2879242631


##########
src/backend/catalog/ag_label.c:
##########
@@ -297,46 +298,104 @@ List *get_all_edge_labels_per_graph(EState *estate, Oid graph_oid)
     HeapTuple tuple;
     TupleTableSlot *slot;
     ResultRelInfo *resultRelInfo;
+    Oid index_oid;
 
-    /* setup scan keys to get all edges for the given graph oid */
-    ScanKeyInit(&scan_keys[1], Anum_ag_label_graph, BTEqualStrategyNumber,
-                F_OIDEQ, ObjectIdGetDatum(graph_oid));
-    ScanKeyInit(&scan_keys[0], Anum_ag_label_kind, BTEqualStrategyNumber,
-                F_CHAREQ, CharGetDatum(LABEL_TYPE_EDGE));
+    index_oid = get_relname_relid("ag_label_graph_oid_index", 
+                                  get_namespace_oid("ag_catalog", false));
 
     /* setup the table to be scanned */
     ag_label = table_open(ag_label_relation_id(), RowExclusiveLock);
-    scan_desc = table_beginscan(ag_label, estate->es_snapshot, 2, scan_keys);
 
     resultRelInfo = create_entity_result_rel_info(estate, "ag_catalog",
                                                   "ag_label");
 
-    slot = ExecInitExtraTupleSlot(
-        estate, RelationGetDescr(resultRelInfo->ri_RelationDesc),
-        &TTSOpsHeapTuple);
-
-    /* scan through the results and get all the label names. */
-    while(true)
+    if (OidIsValid(index_oid))
+    {
+        Relation index_rel;
+        IndexScanDesc index_scan_desc;
+
+        slot = ExecInitExtraTupleSlot(
+            estate, RelationGetDescr(resultRelInfo->ri_RelationDesc),
+            &TTSOpsBufferHeapTuple);
+
+        index_rel = index_open(index_oid, RowExclusiveLock);
+
+        ScanKeyInit(&scan_keys[0], Anum_ag_label_name, BTEqualStrategyNumber,
+                    F_OIDEQ, ObjectIdGetDatum(graph_oid));
+

Review Comment:
   In the index-scan setup, ScanKeyInit() uses Anum_ag_label_name as the scan-key attno. For index scans the attno should be the index column number (typically 1 for the first index key), not a heap attribute-number macro (even if it currently happens to be 1). Using the heap Anum macro here is misleading and easy to break if catalog columns are ever reordered—use an explicit index-key attno instead (and consider using ag_label_graph_oid_index_id() rather than name-based lookup).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r2989842420


##########
src/backend/utils/adt/agtype.c:
##########
@@ -12020,6 +12065,38 @@ static int64 get_int64_from_int_datums(Datum d, Oid type, char *funcname,
     return result;
 }
 
+/*
+ * Helper function to find a valid index for a specific attribute.
+ * Returns the OID of the index, or InvalidOid if none is found.
+ */
+Oid find_usable_index_for_attr(Relation rel, AttrNumber attnum)
+{
+List *index_list = RelationGetIndexList(rel);
+    ListCell *ilc;
+    Oid index_oid = InvalidOid;
+
+    foreach(ilc, index_list)
+    {
+        Oid curr_idx_oid = lfirst_oid(ilc);
+        Relation curr_idx_rel = index_open(curr_idx_oid, AccessShareLock);
+
+        if (curr_idx_rel->rd_index->indisvalid &&
+            curr_idx_rel->rd_index->indnatts >= 1 &&
+            curr_idx_rel->rd_index->indkey.values[0] == attnum) 

Review Comment:
   `find_usable_index_for_attr()` can select any valid index whose first key matches `attnum`, but all call sites build scan keys with `BTEqualStrategyNumber` (btree strategy numbering). If a non-btree index exists on that column (or an index AM with different strategy semantics), the scan can behave incorrectly or fail. Restrict the helper to only return btree indexes (and optionally skip partial/expression indexes), or change the scan-key construction to be compatible with the selected index AM/opclass.



##########
src/backend/utils/adt/agtype.c:
##########
@@ -5646,19 +5649,52 @@ static Datum get_vertex(const char *graph, const char *vertex_label,
         aclcheck_error(aclresult, OBJECT_TABLE, vertex_label);
     }
 
-    /* initialize the scan key */
-    ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
-                Int64GetDatum(graphid));
-
-    /* open the relation (table), begin the scan, and get the tuple  */
+    /* open the relation (table) */
     graph_vertex_label = table_open(vertex_label_table_oid, ShareLock);
-    scan_desc = table_beginscan(graph_vertex_label, snapshot, 1, scan_keys);
-    tuple = heap_getnext(scan_desc, ForwardScanDirection);
+
+    index_oid = find_usable_index_for_attr(graph_vertex_label, 1);
+
+    if (OidIsValid(index_oid))
+    {
+        IndexScanDesc index_scan_desc;
+        Relation index_rel;
+
+        index_rel = index_open(index_oid, ShareLock);
+        slot = table_slot_create(graph_vertex_label, NULL);
+
+        /* initialize the scan key using GRAPHIDEQ for index */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber,
+                    F_GRAPHIDEQ, Int64GetDatum(graphid));
+
+        index_scan_desc = index_beginscan(graph_vertex_label, index_rel, 
+                                          snapshot, NULL, 1, 0);
+        index_rescan(index_scan_desc, scan_keys, 1, NULL, 0);
+
+        if (index_getnext_slot(index_scan_desc, ForwardScanDirection, slot))
+        {
+            tuple = ExecCopySlotHeapTuple(slot);
+            should_free_tuple = true;
+        }
+
+        index_endscan(index_scan_desc);
+        index_close(index_rel, ShareLock);
+        ExecDropSingleTupleTableSlot(slot);
+    }
+    else
+    {
+        /* fallback to sequential scan */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
+                    Int64GetDatum(graphid));
+
+        scan_desc = table_beginscan(graph_vertex_label, snapshot, 1, scan_keys);
+        tuple = heap_getnext(scan_desc, ForwardScanDirection);

Review Comment:
   The index path uses `F_GRAPHIDEQ` for the same attribute, but the seq-scan fallback still uses `F_OIDEQ`. That makes correctness depend on whether an index exists (and may be wrong if the column type/operator is `graphid`). Use the same operator/function for both paths (e.g., `F_GRAPHIDEQ` with the appropriate datum conversion) so results are consistent regardless of index availability.



##########
src/backend/executor/cypher_set.c:
##########
@@ -628,60 +652,129 @@ static void process_update_list(CustomScanState *node)
 
         if (luindex[update_item->entity_position - 1] == lidx)
         {
-            /*
-             * Setup the scan key to require the id field on-disc to match the
-             * entity's graphid.
-             */
-            ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
-                        GRAPHID_GET_DATUM(id->val.int_value));
-            /*
-             * Setup the scan description, with the correct snapshot and scan
-             * keys.
-             */
-            scan_desc = table_beginscan(resultRelInfo->ri_RelationDesc,
-                                        estate->es_snapshot, 1, scan_keys);
-            /* Retrieve the tuple. */
-            heap_tuple = heap_getnext(scan_desc, ForwardScanDirection);
-
-            /*
-             * If the heap tuple still exists (It wasn't deleted between the
-             * match and this SET/REMOVE) update the heap_tuple.
-             */
-            if (HeapTupleIsValid(heap_tuple))
-            {
-                bool should_update = true;
-                Oid relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
-
-                /* Check RLS security quals (USING policy) before update */
-                if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
+            if (OidIsValid(index_oid))
+             {
+                Relation index_rel;
+                IndexScanDesc idx_scan_desc;
+                TupleTableSlot *index_slot;
+
+                index_rel = index_open(index_oid, RowExclusiveLock);
+                
+                /*
+                 * Setup the scan key to require the id field on-disc to match the
+                 * entity's graphid.
+                 */
+                ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
+                            GRAPHID_GET_DATUM(id->val.int_value));
+
+                index_slot = table_slot_create(rel, NULL);
+                idx_scan_desc = index_beginscan(rel, index_rel, estate->es_snapshot, NULL, 1, 0);
+                index_rescan(idx_scan_desc, scan_keys, 1, NULL, 0);
+
+                if (index_getnext_slot(idx_scan_desc, ForwardScanDirection, index_slot))
                 {
-                    RLSCacheEntry *entry;
+                    bool shouldFree;
+                    
+                    /* Retrieve the tuple from the slot */
+                    heap_tuple = ExecFetchSlotHeapTuple(index_slot, true, &shouldFree);
 
-                    /* Entry was already created earlier when setting up WCOs */
-                    entry = hash_search(qual_cache, &relid, HASH_FIND, NULL);
-                    if (!entry)
+                    if (HeapTupleIsValid(heap_tuple))
                     {
-                        ereport(ERROR,
-                                (errcode(ERRCODE_INTERNAL_ERROR),
-                                 errmsg("missing RLS cache entry for relation %u",
-                                        relid)));
+                        bool should_update = true;
+                        
+                        /* Check RLS security quals (USING policy) before update */
+                        if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
+                        {
+                            RLSCacheEntry *entry;
+
+                            /* Entry was already created earlier when setting up WCOs */
+                            entry = hash_search(qual_cache, &relid, HASH_FIND, NULL);
+                            if (!entry)
+                            {
+                                ereport(ERROR,
+                                        (errcode(ERRCODE_INTERNAL_ERROR),
+                                        errmsg("missing RLS cache entry for relation %u",
+                                                relid)));
+                            }
+
+                            ExecStoreHeapTuple(heap_tuple, entry->slot, false);
+                            should_update = check_security_quals(entry->qualExprs,
+                                                                entry->slot,
+                                                                econtext);
+                        }
+
+                        /* Silently skip if USING policy filters out this row */
+                        if (should_update)
+                        {
+                            update_entity_tuple(resultRelInfo, slot, estate,
+                                                            heap_tuple);

Review Comment:
   In the seq-scan path, the return value of `update_entity_tuple(...)` is assigned back to `heap_tuple`, but in the index-scan path it is ignored. If `update_entity_tuple` can return a different `HeapTuple` (or if callers rely on the returned value for ownership/lifetime), this inconsistency can cause incorrect behavior or memory/tuple lifecycle issues. Make the index-scan path match the existing pattern (assign the return value and handle any required freeing/ownership consistently).
   ```suggestion
                               heap_tuple = update_entity_tuple(resultRelInfo, slot,
                                                                estate, heap_tuple);
   ```



##########
src/backend/executor/cypher_utils.c:
##########
@@ -238,20 +240,47 @@ bool entity_exists(EState *estate, Oid graph_oid, graphid id)
                                       GetCurrentCommandId(false));
 
     rel = table_open(label->relation, RowExclusiveLock);
-    scan_desc = table_beginscan(rel, estate->es_snapshot, 1, scan_keys);
 
-    tuple = heap_getnext(scan_desc, ForwardScanDirection);
+    index_oid = find_usable_index_for_attr(rel, 1);
 
-    /*
-     * If a single tuple was returned, the tuple is still valid, otherwise'
-     * set to false.
-     */
-    if (!HeapTupleIsValid(tuple))
+    if (OidIsValid(index_oid))
     {
-        result = false;
+        IndexScanDesc index_scan_desc;
+        Relation index_rel;
+
+        slot = table_slot_create(rel, NULL);
+
+        index_rel = index_open(index_oid, RowExclusiveLock);

Review Comment:
   `entity_exists()` is a read-only existence check, but it opens the index with `RowExclusiveLock`. This lock mode is stronger than necessary for scanning and can increase lock contention under concurrent workloads (especially since `entity_exists` is in the hot insertion path). Prefer `AccessShareLock` for `index_open` (while keeping the table lock as required by the surrounding logic).



##########
src/backend/catalog/ag_label.c:
##########
@@ -297,49 +298,111 @@ List *get_all_edge_labels_per_graph(EState *estate, Oid graph_oid)
     HeapTuple tuple;
     TupleTableSlot *slot;
     ResultRelInfo *resultRelInfo;
-
-    /* setup scan keys to get all edges for the given graph oid */
-    ScanKeyInit(&scan_keys[1], Anum_ag_label_graph, BTEqualStrategyNumber,
-                F_OIDEQ, ObjectIdGetDatum(graph_oid));
-    ScanKeyInit(&scan_keys[0], Anum_ag_label_kind, BTEqualStrategyNumber,
-                F_CHAREQ, CharGetDatum(LABEL_TYPE_EDGE));
+    Oid index_oid;
 
     /* setup the table to be scanned */
-    ag_label = table_open(ag_label_relation_id(), RowExclusiveLock);
-    scan_desc = table_beginscan(ag_label, estate->es_snapshot, 2, scan_keys);
+    ag_label = table_open(ag_label_relation_id(), AccessShareLock);
+
+    index_oid = find_usable_index_for_attr(ag_label, Anum_ag_label_graph);
 
     resultRelInfo = create_entity_result_rel_info(estate, "ag_catalog",
                                                   "ag_label");
 

Review Comment:
   This function opens `ag_label` via `table_open(...)` but later closes `resultRelInfo->ri_RelationDesc` instead of the `ag_label` relation it opened. This double-open pattern is easy to get wrong and risks leaking a relation reference/lock if the descriptors are not the same instance. Prefer using a single relation handle throughout (e.g., use `resultRelInfo->ri_RelationDesc` for scanning and close that, or explicitly close `ag_label` if it remains separately opened).
   ```suggestion
       resultRelInfo = create_entity_result_rel_info(estate, "ag_catalog",
                                                     "ag_label");
       ag_label = resultRelInfo->ri_RelationDesc;
   
       index_oid = find_usable_index_for_attr(ag_label, Anum_ag_label_graph);
   ```



##########
src/backend/utils/adt/age_global_graph.c:
##########
@@ -204,43 +204,117 @@ static List *get_ag_labels_names(Snapshot snapshot, Oid graph_oid,
     TableScanDesc scan_desc;
     HeapTuple tuple;
     TupleDesc tupdesc;
+    Oid index_oid = InvalidOid;
 
     /* we need a valid snapshot */
     Assert(snapshot != NULL);
 
-    /* setup scan keys to get all edges for the given graph oid */
-    ScanKeyInit(&scan_keys[1], Anum_ag_label_graph, BTEqualStrategyNumber,
-                F_OIDEQ, ObjectIdGetDatum(graph_oid));
-    ScanKeyInit(&scan_keys[0], Anum_ag_label_kind, BTEqualStrategyNumber,
-                F_CHAREQ, CharGetDatum(label_type));
-
     /* setup the table to be scanned, ag_label in this case */
     ag_label = table_open(ag_label_relation_id(), AccessShareLock);
-    scan_desc = table_beginscan(ag_label, snapshot, 2, scan_keys);
 
     /* get the tupdesc - we don't need to release this one */
     tupdesc = RelationGetDescr(ag_label);
     /* bail if the number of columns differs - this table has 5 */
     Assert(tupdesc->natts == Natts_ag_label);
 
-    /* get all of the label names */
-    while((tuple = heap_getnext(scan_desc, ForwardScanDirection)) != NULL)
+    /* We look for 'ag_label_graph_oid_index' or any index starting with 'graph' */

Review Comment:
   The comment is inaccurate: the code does not look for an index by name/prefix; it selects the first “usable” index whose first key matches the attribute number. Update the comment to reflect the actual selection logic to avoid misleading future maintainers.
   ```suggestion
       /* Find a usable index whose first key column is ag_label.graph (Anum_ag_label_graph) */
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r2989868681


##########
src/backend/utils/adt/agtype.c:
##########
@@ -5646,19 +5649,74 @@ static Datum get_vertex(const char *graph, const char *vertex_label,
         aclcheck_error(aclresult, OBJECT_TABLE, vertex_label);
     }
 
-    /* initialize the scan key */
-    ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
-                Int64GetDatum(graphid));
-
-    /* open the relation (table), begin the scan, and get the tuple  */
+    /* open the relation (table) */
     graph_vertex_label = table_open(vertex_label_table_oid, ShareLock);
-    scan_desc = table_beginscan(graph_vertex_label, snapshot, 1, scan_keys);
-    tuple = heap_getnext(scan_desc, ForwardScanDirection);
+
+    index_oid = RelationGetPrimaryKeyIndex(graph_vertex_label, false);
+
+    if (!OidIsValid(index_oid))
+    {
+        List *idx_list = RelationGetIndexList(graph_vertex_label);
+        ListCell *lc;
+        foreach(lc, idx_list)
+        {
+            Oid curr = lfirst_oid(lc);
+            Relation idx_rel = index_open(curr, ShareLock);
+
+            if (idx_rel->rd_index->indisvalid &&
+                idx_rel->rd_index->indnatts >= 1 &&
+                idx_rel->rd_index->indkey.values[0] == 1)
+            {
+                index_oid = curr;
+                index_close(idx_rel, ShareLock);
+                break;
+            }
+            index_close(idx_rel, ShareLock);
+        }
+        list_free(idx_list);
+    }
+
+    if (OidIsValid(index_oid))
+    {
+        IndexScanDesc index_scan_desc;
+        Relation index_rel;
+
+        index_rel = index_open(index_oid, ShareLock);
+        slot = table_slot_create(graph_vertex_label, NULL);
+
+        /* initialize the scan key using GRAPHIDEQ for index */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber,
+                    F_GRAPHIDEQ, Int64GetDatum(graphid));
+
+        index_scan_desc = index_beginscan(graph_vertex_label, index_rel, 
+                                          snapshot, NULL, 1, 0);
+        index_rescan(index_scan_desc, scan_keys, 1, NULL, 0);
+
+        if (index_getnext_slot(index_scan_desc, ForwardScanDirection, slot))
+        {
+            tuple = ExecCopySlotHeapTuple(slot);
+            should_free_tuple = true;
+        }
+
+        index_endscan(index_scan_desc);
+        index_close(index_rel, ShareLock);
+        ExecDropSingleTupleTableSlot(slot);
+    }
+    else
+    {
+        /* fallback to sequential scan */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
+                    Int64GetDatum(graphid));

Review Comment:
   If you could fix it, that would be great. Otherwise, it will just keep reminding us and it will still need to be fixed in a diff. pr. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-3995429738

   I've updated the PR description with the steps to reproduce the tests locally.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-4054319807

   All review comments and suggestions provided by GitHub Copilot and Opus 4.6 have been addressed and integrated into this patch.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r2930488901


##########
src/backend/executor/cypher_set.c:
##########
@@ -628,60 +656,100 @@ static void process_update_list(CustomScanState *node)
 
         if (luindex[update_item->entity_position - 1] == lidx)
         {
-            /*
-             * Setup the scan key to require the id field on-disc to match the
-             * entity's graphid.
-             */
-            ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
-                        GRAPHID_GET_DATUM(id->val.int_value));
-            /*
-             * Setup the scan description, with the correct snapshot and scan
-             * keys.
-             */
-            scan_desc = table_beginscan(resultRelInfo->ri_RelationDesc,
-                                        estate->es_snapshot, 1, scan_keys);
-            /* Retrieve the tuple. */
-            heap_tuple = heap_getnext(scan_desc, ForwardScanDirection);
-
-            /*
-             * If the heap tuple still exists (It wasn't deleted between the
-             * match and this SET/REMOVE) update the heap_tuple.
-             */
-            if (HeapTupleIsValid(heap_tuple))
-            {
-                bool should_update = true;
-                Oid relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
-
-                /* Check RLS security quals (USING policy) before update */
-                if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
+            if (OidIsValid(index_oid))
+             {
+                Relation index_rel;
+                IndexScanDesc scan_desc;
+                TupleTableSlot *index_slot;
+
+                index_rel = index_open(index_oid, RowExclusiveLock);
+                
+                /*
+                 * Setup the scan key to require the id field on-disc to match the
+                 * entity's graphid.
+                 */
+                ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
+                            GRAPHID_GET_DATUM(id->val.int_value));
+
+                index_slot = table_slot_create(rel, NULL);
+                scan_desc = index_beginscan(rel, index_rel, estate->es_snapshot, NULL, 1, 0);
+                index_rescan(scan_desc, scan_keys, 1, NULL, 0);
+
+                if (index_getnext_slot(scan_desc, ForwardScanDirection, index_slot))
                 {
-                    RLSCacheEntry *entry;
+                    bool shouldFree;
+                    
+                    /* Retrieve the tuple from the slot */
+                    heap_tuple = ExecFetchSlotHeapTuple(index_slot, true, &shouldFree);
 
-                    /* Entry was already created earlier when setting up WCOs */
-                    entry = hash_search(qual_cache, &relid, HASH_FIND, NULL);
-                    if (!entry)
+                    if (HeapTupleIsValid(heap_tuple))
                     {
-                        ereport(ERROR,
-                                (errcode(ERRCODE_INTERNAL_ERROR),
-                                 errmsg("missing RLS cache entry for relation %u",
-                                        relid)));
+                        heap_tuple = update_entity_tuple(resultRelInfo, slot, estate, heap_tuple);

Review Comment:
   I have added the same RLS USING-policy check right before calling update_entity_tuple().



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r2930499585


##########
src/backend/catalog/ag_label.c:
##########
@@ -297,46 +298,104 @@ List *get_all_edge_labels_per_graph(EState *estate, Oid graph_oid)
     HeapTuple tuple;
     TupleTableSlot *slot;
     ResultRelInfo *resultRelInfo;
+    Oid index_oid;
 
-    /* setup scan keys to get all edges for the given graph oid */
-    ScanKeyInit(&scan_keys[1], Anum_ag_label_graph, BTEqualStrategyNumber,
-                F_OIDEQ, ObjectIdGetDatum(graph_oid));
-    ScanKeyInit(&scan_keys[0], Anum_ag_label_kind, BTEqualStrategyNumber,
-                F_CHAREQ, CharGetDatum(LABEL_TYPE_EDGE));
+    index_oid = get_relname_relid("ag_label_graph_oid_index", 
+                                  get_namespace_oid("ag_catalog", false));
 
     /* setup the table to be scanned */
     ag_label = table_open(ag_label_relation_id(), RowExclusiveLock);
-    scan_desc = table_beginscan(ag_label, estate->es_snapshot, 2, scan_keys);
 
     resultRelInfo = create_entity_result_rel_info(estate, "ag_catalog",
                                                   "ag_label");
 
-    slot = ExecInitExtraTupleSlot(
-        estate, RelationGetDescr(resultRelInfo->ri_RelationDesc),
-        &TTSOpsHeapTuple);
-
-    /* scan through the results and get all the label names. */
-    while(true)
+    if (OidIsValid(index_oid))
+    {
+        Relation index_rel;
+        IndexScanDesc index_scan_desc;
+
+        slot = ExecInitExtraTupleSlot(
+            estate, RelationGetDescr(resultRelInfo->ri_RelationDesc),
+            &TTSOpsBufferHeapTuple);
+
+        index_rel = index_open(index_oid, RowExclusiveLock);
+
+        ScanKeyInit(&scan_keys[0], Anum_ag_label_name, BTEqualStrategyNumber,
+                    F_OIDEQ, ObjectIdGetDatum(graph_oid));
+

Review Comment:
   I updated ScanKeyInit() for the index scan to use an explicit index column number (1) instead of the heap attribute macro (Anum_ag_label_name), as recommended.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-4057273580

   @sandy-bes A lot of regression tests failed. Are you running the installcheck locally to verify the build?
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r2930495761


##########
src/backend/utils/adt/agtype.c:
##########
@@ -5646,19 +5649,74 @@ static Datum get_vertex(const char *graph, const char *vertex_label,
         aclcheck_error(aclresult, OBJECT_TABLE, vertex_label);
     }
 
-    /* initialize the scan key */
-    ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
-                Int64GetDatum(graphid));
-
-    /* open the relation (table), begin the scan, and get the tuple  */
+    /* open the relation (table) */
     graph_vertex_label = table_open(vertex_label_table_oid, ShareLock);
-    scan_desc = table_beginscan(graph_vertex_label, snapshot, 1, scan_keys);
-    tuple = heap_getnext(scan_desc, ForwardScanDirection);
+
+    index_oid = RelationGetPrimaryKeyIndex(graph_vertex_label, false);
+
+    if (!OidIsValid(index_oid))
+    {
+        List *idx_list = RelationGetIndexList(graph_vertex_label);
+        ListCell *lc;
+        foreach(lc, idx_list)
+        {
+            Oid curr = lfirst_oid(lc);
+            Relation idx_rel = index_open(curr, ShareLock);
+
+            if (idx_rel->rd_index->indisvalid &&
+                idx_rel->rd_index->indnatts >= 1 &&
+                idx_rel->rd_index->indkey.values[0] == 1)
+            {
+                index_oid = curr;
+                index_close(idx_rel, ShareLock);
+                break;
+            }
+            index_close(idx_rel, ShareLock);
+        }
+        list_free(idx_list);
+    }
+
+    if (OidIsValid(index_oid))
+    {
+        IndexScanDesc index_scan_desc;
+        Relation index_rel;
+
+        index_rel = index_open(index_oid, ShareLock);
+        slot = table_slot_create(graph_vertex_label, NULL);
+
+        /* initialize the scan key using GRAPHIDEQ for index */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber,
+                    F_GRAPHIDEQ, Int64GetDatum(graphid));
+
+        index_scan_desc = index_beginscan(graph_vertex_label, index_rel, 
+                                          snapshot, NULL, 1, 0);
+        index_rescan(index_scan_desc, scan_keys, 1, NULL, 0);
+
+        if (index_getnext_slot(index_scan_desc, ForwardScanDirection, slot))
+        {
+            tuple = ExecCopySlotHeapTuple(slot);
+            should_free_tuple = true;
+        }
+
+        index_endscan(index_scan_desc);
+        index_close(index_rel, ShareLock);
+        ExecDropSingleTupleTableSlot(slot);
+    }
+    else
+    {
+        /* fallback to sequential scan */
+        ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_OIDEQ,
+                    Int64GetDatum(graphid));

Review Comment:
   This is actually existing code that I didn't write. To keep the PR focused and avoid breaking existing logic, I didn't change its internal mechanics and simply moved it under the else branch. Let me know if you'd still prefer me to fix the F_OIDEQ to F_GRAPHIDEQ comparison.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-4062187562

   I forgot to run installcheck for the latest change in the commit, my bad! It turned out there was a lock mismatch. I just fixed it, the tests are passing now, and I force-pushed the update.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-3993202685

   @sandy-bes Please see this as well (Opus 4.6 review). All of these items need to be address.
   
   ## Review of PR #2351 — Add index scan
   
   The core idea — replacing O(N) sequential scans with O(log N) index scans in `entity_exists` and related hot paths — is excellent, and the performance numbers are compelling. However, there are several correctness, security, and code quality issues that need to be addressed before this can be merged.
   
   ### Critical Issues
   
   **1. RLS bypass in `cypher_set.c` index-scan path (security bug)**
   
   The index-scan branch in `process_update_list()` calls `update_entity_tuple()` directly without checking `check_security_quals`. The seq-scan fallback correctly gates the update on RLS USING-policy evaluation. This means SET/REMOVE will bypass row-level security when an index is present. The same RLS gating logic must be applied in the index-scan branch.
   
   **2. `heap_freetuple` on wrong tuple in `cypher_set.c` (memory corruption)**
   
   ```c
   heap_tuple = ExecFetchSlotHeapTuple(index_slot, true, &shouldFree);
   // ...
   heap_tuple = update_entity_tuple(resultRelInfo, slot, estate, heap_tuple);
   // ...
   if (shouldFree)
       heap_freetuple(heap_tuple);  // <-- frees the UPDATE result, not the fetched tuple
   ```
   
   After `update_entity_tuple()`, `heap_tuple` points to the new tuple, but `shouldFree` applies to the originally fetched tuple. This can free the wrong memory. Keep the fetched tuple in a separate variable and only free that one.
   
   ### Correctness Issues
   
   **3. `F_OIDEQ` vs `F_GRAPHIDEQ` mismatch in `agtype.c` fallback path**
   
   The index path correctly uses `F_GRAPHIDEQ`, but the seq-scan fallback at line ~5709 still uses `F_OIDEQ`. The column type is `graphid`, so both paths should use `F_GRAPHIDEQ` / `GRAPHID_GET_DATUM`.
   
   **4. Index attno vs heap attno confusion in `ag_label.c`**
   
   `ScanKeyInit` for the index scan uses `Anum_ag_label_name` as the attribute number. For index scans, the attno should be the index column number (typically 1), not a heap attribute-number macro. Additionally, the index is on `graph_oid`, so referencing `Anum_ag_label_name` is semantically incorrect — it only works by coincidence if the value happens to equal 1. Consider using `ag_label_graph_oid_index_id()` instead of `get_relname_relid()` string lookup as well.
   
   ### Performance Issue
   
   **5. Index discovery runs per-tuple in hot paths**
   
   In `process_delete_list()` and `process_update_list()`, the index discovery block (`RelationGetIndexList` + open/close each index) runs inside the per-entity loop. For a DELETE or SET touching N entities of the same label, this runs N times. The index OID should be cached per-label or discovered once outside the inner loop.
   
   ### Code Quality Issues
   
   **6. Massive code duplication**
   
   The index discovery pattern (iterate `RelationGetIndexList`, open each, check `indisvalid`/`indnatts`/`indkey.values[0]`) is copy-pasted 6+ times across the changed files. This should be factored into a shared utility function, e.g.:
   
   ```c
   Oid find_usable_index_for_attr(Relation rel, AttrNumber attnum);
   ```
   
   **7. DETACH DELETE duplication in `cypher_delete.c`**
   
   The two-pass connected-edge check (START_ID pass + END_ID pass) duplicates ~120 lines of nearly identical ACL check + RLS check + delete + error logic. A helper function would reduce this significantly.
   
   **8. C++ style comments**
   
   New code uses `//` comments in `ag_label.c` and elsewhere. The AGE/PostgreSQL codebase uses `/* ... */` exclusively. Please convert for consistency and C90 portability.
   
   **9. Brace style inconsistency**
   
   The PR mixes `} else {` with the existing codebase convention of:
   
   ```c
   }
   else
   {
   ```
   
   Please follow the existing style.
   
   **10. Inconsistent lock levels**
   
   Index open calls use `RowExclusiveLock` in some read-only scan paths (`ag_label.c` label enumeration, `age_global_graph.c`) where `AccessShareLock` would be more appropriate. The lock levels for index access during reads vs writes should be reviewed for consistency.
   
   ### Summary
   
   | # | Issue | Severity |
   |---|---|---|
   | 1 | RLS bypass in SET index path | **Critical** |
   | 2 | `heap_freetuple` on wrong tuple | **High** |
   | 3 | `F_OIDEQ` vs `F_GRAPHIDEQ` mismatch | **Medium** |
   | 4 | Index attno vs heap attno confusion | **Medium** |
   | 5 | Index discovery per-tuple in loops | **Medium** |
   | 6 | Index discovery code duplication (6x) | **High** |
   | 7 | DETACH DELETE logic duplication | **Medium** |
   | 8 | C++ style comments | **Low** |
   | 9 | Brace style inconsistency | **Low** |
   | 10 | Inconsistent lock levels | **Medium** |
   
   The performance improvement is real and valuable. With the security fix (#1), memory safety fix (#2), correctness fixes (#3-4), and a refactoring pass to deduplicate the index discovery logic (#5-7), this will be in good shape.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-4241686455

   @jrgemignani I've added the missing braces {}.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-3996495927

   Yes, absolutely, I understand that the review process needs to be finalized first. I will do my best to address all the feedback over the next few days.
   
   Regarding the use of AI agents: I did not use any AI agents while writing this code.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r2930500905


##########
src/backend/catalog/ag_label.c:
##########
@@ -297,46 +298,104 @@ List *get_all_edge_labels_per_graph(EState *estate, Oid graph_oid)
     HeapTuple tuple;
     TupleTableSlot *slot;
     ResultRelInfo *resultRelInfo;
+    Oid index_oid;
 
-    /* setup scan keys to get all edges for the given graph oid */
-    ScanKeyInit(&scan_keys[1], Anum_ag_label_graph, BTEqualStrategyNumber,
-                F_OIDEQ, ObjectIdGetDatum(graph_oid));
-    ScanKeyInit(&scan_keys[0], Anum_ag_label_kind, BTEqualStrategyNumber,
-                F_CHAREQ, CharGetDatum(LABEL_TYPE_EDGE));
+    index_oid = get_relname_relid("ag_label_graph_oid_index", 
+                                  get_namespace_oid("ag_catalog", false));
 
     /* setup the table to be scanned */
     ag_label = table_open(ag_label_relation_id(), RowExclusiveLock);
-    scan_desc = table_beginscan(ag_label, estate->es_snapshot, 2, scan_keys);
 
     resultRelInfo = create_entity_result_rel_info(estate, "ag_catalog",
                                                   "ag_label");
 
-    slot = ExecInitExtraTupleSlot(
-        estate, RelationGetDescr(resultRelInfo->ri_RelationDesc),
-        &TTSOpsHeapTuple);
-
-    /* scan through the results and get all the label names. */
-    while(true)
+    if (OidIsValid(index_oid))
+    {
+        Relation index_rel;
+        IndexScanDesc index_scan_desc;
+
+        slot = ExecInitExtraTupleSlot(
+            estate, RelationGetDescr(resultRelInfo->ri_RelationDesc),
+            &TTSOpsBufferHeapTuple);
+
+        index_rel = index_open(index_oid, RowExclusiveLock);
+
+        ScanKeyInit(&scan_keys[0], Anum_ag_label_name, BTEqualStrategyNumber,
+                    F_OIDEQ, ObjectIdGetDatum(graph_oid));
+
+        index_scan_desc = index_beginscan(ag_label, index_rel, estate->es_snapshot, NULL, 1, 0);
+        index_rescan(index_scan_desc, scan_keys, 1, NULL, 0);
+
+        while (index_getnext_slot(index_scan_desc, ForwardScanDirection, slot))
+        {
+            Name label;
+            Name lval;
+            bool isNull;
+            Datum datum;
+            char kind;
+
+            /*There isn't field kind in index. So we should check it by hands*/
+            datum = slot_getattr(slot, Anum_ag_label_kind, &isNull);
+            if (isNull)
+                continue;
+
+            kind = DatumGetChar(datum);
+            
+            if (kind != LABEL_TYPE_EDGE)
+                continue;
+
+            datum = slot_getattr(slot, Anum_ag_label_name, &isNull);
+            if (!isNull)
+            {
+                label = DatumGetName(datum);
+                lval = (Name) palloc(NAMEDATALEN);
+                namestrcpy(lval, NameStr(*label));
+                labels = lappend(labels, lval);
+            }
+        }
+
+        index_endscan(index_scan_desc);
+        index_close(index_rel, RowExclusiveLock);
+    } else
     {
-        Name label;
-        bool isNull;
-        Datum datum;
+        slot = ExecInitExtraTupleSlot(
+            estate, RelationGetDescr(resultRelInfo->ri_RelationDesc),
+            &TTSOpsHeapTuple);
 
-        tuple = heap_getnext(scan_desc, ForwardScanDirection);
+        // setup scan keys to get all edges for the given graph oid
+        ScanKeyInit(&scan_keys[1], Anum_ag_label_graph, BTEqualStrategyNumber,
+                  F_OIDEQ, ObjectIdGetDatum(graph_oid));
+        ScanKeyInit(&scan_keys[0], Anum_ag_label_kind, BTEqualStrategyNumber,
+                  F_CHAREQ, CharGetDatum(LABEL_TYPE_EDGE));

Review Comment:
   I've replaced all C++-style // comments.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on PR #2351:
URL: https://github.com/apache/age/pull/2351#issuecomment-4225368101

   @sandy-bes I think if I keep having Copilot review it, it will never stop finding "something" to complain about. So, I think I'm done with it for this PR. Now I'll review the changes manually and go from there.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani merged PR #2351:
URL: https://github.com/apache/age/pull/2351


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add index scan [age]

Posted by "sandy-bes (via GitHub)" <gi...@apache.org>.
sandy-bes commented on code in PR #2351:
URL: https://github.com/apache/age/pull/2351#discussion_r3013699818


##########
src/backend/executor/cypher_set.c:
##########
@@ -628,60 +652,129 @@ static void process_update_list(CustomScanState *node)
 
         if (luindex[update_item->entity_position - 1] == lidx)
         {
-            /*
-             * Setup the scan key to require the id field on-disc to match the
-             * entity's graphid.
-             */
-            ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
-                        GRAPHID_GET_DATUM(id->val.int_value));
-            /*
-             * Setup the scan description, with the correct snapshot and scan
-             * keys.
-             */
-            scan_desc = table_beginscan(resultRelInfo->ri_RelationDesc,
-                                        estate->es_snapshot, 1, scan_keys);
-            /* Retrieve the tuple. */
-            heap_tuple = heap_getnext(scan_desc, ForwardScanDirection);
-
-            /*
-             * If the heap tuple still exists (It wasn't deleted between the
-             * match and this SET/REMOVE) update the heap_tuple.
-             */
-            if (HeapTupleIsValid(heap_tuple))
-            {
-                bool should_update = true;
-                Oid relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
-
-                /* Check RLS security quals (USING policy) before update */
-                if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
+            if (OidIsValid(index_oid))
+             {
+                Relation index_rel;
+                IndexScanDesc idx_scan_desc;
+                TupleTableSlot *index_slot;
+
+                index_rel = index_open(index_oid, RowExclusiveLock);
+                
+                /*
+                 * Setup the scan key to require the id field on-disc to match the
+                 * entity's graphid.
+                 */
+                ScanKeyInit(&scan_keys[0], 1, BTEqualStrategyNumber, F_GRAPHIDEQ,
+                            GRAPHID_GET_DATUM(id->val.int_value));
+
+                index_slot = table_slot_create(rel, NULL);
+                idx_scan_desc = index_beginscan(rel, index_rel, estate->es_snapshot, NULL, 1, 0);
+                index_rescan(idx_scan_desc, scan_keys, 1, NULL, 0);
+
+                if (index_getnext_slot(idx_scan_desc, ForwardScanDirection, index_slot))
                 {
-                    RLSCacheEntry *entry;
+                    bool shouldFree;
+                    
+                    /* Retrieve the tuple from the slot */
+                    heap_tuple = ExecFetchSlotHeapTuple(index_slot, true, &shouldFree);
 
-                    /* Entry was already created earlier when setting up WCOs */
-                    entry = hash_search(qual_cache, &relid, HASH_FIND, NULL);
-                    if (!entry)
+                    if (HeapTupleIsValid(heap_tuple))
                     {
-                        ereport(ERROR,
-                                (errcode(ERRCODE_INTERNAL_ERROR),
-                                 errmsg("missing RLS cache entry for relation %u",
-                                        relid)));
+                        bool should_update = true;
+                        
+                        /* Check RLS security quals (USING policy) before update */
+                        if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
+                        {
+                            RLSCacheEntry *entry;
+
+                            /* Entry was already created earlier when setting up WCOs */
+                            entry = hash_search(qual_cache, &relid, HASH_FIND, NULL);
+                            if (!entry)
+                            {
+                                ereport(ERROR,
+                                        (errcode(ERRCODE_INTERNAL_ERROR),
+                                        errmsg("missing RLS cache entry for relation %u",
+                                                relid)));
+                            }
+
+                            ExecStoreHeapTuple(heap_tuple, entry->slot, false);
+                            should_update = check_security_quals(entry->qualExprs,
+                                                                entry->slot,
+                                                                econtext);
+                        }
+
+                        /* Silently skip if USING policy filters out this row */
+                        if (should_update)
+                        {
+                            update_entity_tuple(resultRelInfo, slot, estate,
+                                                            heap_tuple);

Review Comment:
   I had actually removed that assignment in a previous PR iteration to fix a memory bug (calling heap_freetuple on the updated tuple instead of the fetched one caused issues).
   
   But I completely agree that leaving the return value unassigned is bad practice and breaks consistency. I've refactored this block: we now store the fetched tuple in a dedicated original_tuple variable for safe memory freeing at the end, which allows us to correctly assign the update_entity_tuple result back to heap_tuple. Fixed it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@age.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org