Skip to content

[opencypher] count push-down counts an undirected self-loop twice: MATCH (a)-[:K]-(b) RETURN count(*) differs from the same query behind WITH #8750

Closed

Description

@lvca

Found while fixing #8426.

The CSR count push-down (`COUNT CHAIN PATHS (CSR count-push-down)`, with or without a Graph Analytical View) answers an undirected hop from the union of a vertex's forward and backward adjacency, so an edge from a vertex to itself sits in both lists and is counted twice. The record path matches an undirected self-loop once, as Neo4j does.

Repro (30 `P` vertices, every one with a `K` self-loop plus a few ordinary `K` edges):

  • `MATCH (a:P)-[:K]-(b:P) RETURN count(*)` answers 232
  • `MATCH (a:P)-[:K]-(b:P) WITH a, b RETURN count(*)` answers 198 (the push-down does not claim a `WITH`)

The gap is exactly the self-loop count. It carries into longer chains, with and without an inequality (`(a)-[:K]-(b)-[:L]-(c)`: 195 vs 165).

Direction: count a self-loop once when a hop walks BOTH, in the dense propagation, the per-source inequality expansion and the self-loop subtraction alike (the provider already skips the backward side for a self-loop in `countEdgesBetween`). Needs a per-vertex self-loop count per edge type, or a provider primitive that reports it.

Activity

  1. added this to the 26.10.1 milestone on Sep 30, 2026
  2. self-assigned this
    on Sep 30, 2026
  3. added
    severity:minor
    on Sep 30, 2026
  4. tae898 commented on Oct 3, 2026

    @tae898
    Contributor

    The same double count of an undirected self-loop also happens in three places that do not go through COUNT CHAIN PATHS, with no Graph Analytical View: a count(*) grouped by the start node (COUNT EDGES RETURN in the plan), count(m) after OPTIONAL MATCH with WITH n, count(m) (COUNT EDGES OPTIMIZATION), and the COUNT { } subquery, in RETURN and in WHERE. The rows of the pattern are right (one row per self-loop), and so are WITH n, m before the count and a pattern comprehension.

    In case one fix can cover them all: the edge-count steps ask for the count in direction BOTH (for example in CountEdgesStep), which adds the outgoing and the incoming edge lists, and a self-loop is in both. LabelReplacements.countEdgesToMigrate already notes this and skips the second copy.

    Neo4j 2026.08.1 returns, for the eight queries in order: the same four rows, 2, 1, 1, 2, 2, 2, 2, 1, 1, 2, 1, 1, [1], 2, 1, 1, and 2, 1, 1.

    Repro

    javac -cp 'lib/*' -d cls SelfLoopDegree.java
    java -Xmx8g -XX:+UseCompactObjectHeaders --add-modules=jdk.incubator.vector --enable-native-access=ALL-UNNAMED -cp 'lib/*:cls' SelfLoopDegree /tmp/SelfLoopDegree-db

    lib/ holds the engine jar and its dependencies. On Temurin 21, use the same command without -XX:+UseCompactObjectHeaders.

    import com.arcadedb.database.Database;
    import com.arcadedb.database.DatabaseFactory;
    import com.arcadedb.query.sql.executor.ResultSet;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class SelfLoopDegree {
      public static void main(String[] args) {
        Database db = fresh(args[0]);
        System.out.println("ArcadeDB " + com.arcadedb.Constants.getRawVersion() + " (" + com.arcadedb.Constants.getBuildNumber() + "), Java "
            + System.getProperty("java.version"));
        // node 1: an R self-loop and an R edge to node 2; node 3: an R self-loop and an S edge to node 2
        db.transaction(() -> db.command("opencypher", """
            CREATE (a:N {id: 1}), (b:N {id: 2}), (c:N {id: 3}),
                   (a)-[:R]->(a), (a)-[:R]->(b), (c)-[:R]->(c), (c)-[:S]->(b)"""));
    
        String[] queries = {
            "MATCH (n:N)-[:R]-(m) RETURN n.id AS id, m.id AS m ORDER BY id, m",
            "MATCH (n:N)-[:R]-(m) RETURN n.id AS id, count(*) AS c ORDER BY id",
            "MATCH (n:N)-[r]-(m) RETURN n.id AS id, count(*) AS c ORDER BY id",
            "MATCH (n:N) OPTIONAL MATCH (n)-[:R]-(m) WITH n, count(m) AS c RETURN n.id AS id, c ORDER BY id",
            "MATCH (n:N) RETURN n.id AS id, COUNT { (n)-[:R]-() } AS c ORDER BY id",
            "MATCH (n:N) WHERE COUNT { (n)-[:R]-() } = 2 RETURN n.id AS id ORDER BY id",
            "MATCH (n:N)-[:R]-(m) WITH n, m RETURN n.id AS id, count(*) AS c ORDER BY id",
            "MATCH (n:N) RETURN n.id AS id, size([(n)-[:R]-() | 1]) AS c ORDER BY id" };
        for (String q : queries)
          System.out.println(q + "  ->  " + rows(db, q));
        db.close();
      }
    
      static List<String> rows(Database db, String q) {
        List<String> out = new ArrayList<>();
        try (ResultSet rs = db.query("opencypher", q)) {
          rs.stream().forEach(r -> out.add(r.toJSON().toString()));
        }
        return out;
      }
    
      static Database fresh(String path) {
        DatabaseFactory factory = new DatabaseFactory(path);
        if (factory.exists())
          factory.open().drop();
        return factory.create();
      }
    }

    Output on main at cecb369df9 (2026-10-03), embedded, on Temurin 25 with compact object headers (the engine jar's build stamp names 04bb03ebec, the newest commit in cecb369df9 that is not a merge). Temurin 21 prints the same lines apart from the Java version on the first line.

    ArcadeDB 26.10.1-SNAPSHOT (04bb03ebec07fce19101595d65ca1e3bdf516755), Java 25.0.4
    MATCH (n:N)-[:R]-(m) RETURN n.id AS id, m.id AS m ORDER BY id, m  ->  [{"id":1,"m":1}, {"id":1,"m":2}, {"id":2,"m":1}, {"id":3,"m":3}]
    MATCH (n:N)-[:R]-(m) RETURN n.id AS id, count(*) AS c ORDER BY id  ->  [{"id":1,"c":3}, {"id":2,"c":1}, {"id":3,"c":2}]
    MATCH (n:N)-[r]-(m) RETURN n.id AS id, count(*) AS c ORDER BY id  ->  [{"id":1,"c":3}, {"id":2,"c":2}, {"id":3,"c":3}]
    MATCH (n:N) OPTIONAL MATCH (n)-[:R]-(m) WITH n, count(m) AS c RETURN n.id AS id, c ORDER BY id  ->  [{"id":1,"c":3}, {"id":2,"c":1}, {"id":3,"c":2}]
    MATCH (n:N) RETURN n.id AS id, COUNT { (n)-[:R]-() } AS c ORDER BY id  ->  [{"id":1,"c":3}, {"id":2,"c":1}, {"id":3,"c":2}]
    MATCH (n:N) WHERE COUNT { (n)-[:R]-() } = 2 RETURN n.id AS id ORDER BY id  ->  [{"id":3}]
    MATCH (n:N)-[:R]-(m) WITH n, m RETURN n.id AS id, count(*) AS c ORDER BY id  ->  [{"id":1,"c":2}, {"id":2,"c":1}, {"id":3,"c":1}]
    MATCH (n:N) RETURN n.id AS id, size([(n)-[:R]-() | 1]) AS c ORDER BY id  ->  [{"id":1,"c":2}, {"id":2,"c":1}, {"id":3,"c":1}]
    

    Versions affected: main cecb369df9, main 66541f57d9 (2026-10-02), main 417314c18 (2026-09-17), and 26.9.1 print the same lines, on Temurin 25 and Temurin 21.

    Expected: a self-loop counts once in an undirected pattern: [{"id":1,"c":2}, {"id":2,"c":1}, {"id":3,"c":1}] for the :R counts, [{"id":1,"c":2}, {"id":2,"c":2}, {"id":3,"c":2}] for the untyped count, and [{"id":1}] for the WHERE query.

  5. modified the milestones: 26.10.1, 26.11.1 on Oct 5, 2026
  6. added
    in progress
    on Oct 9, 2026
  7. added 2 commits that reference this issue on Oct 9, 2026
  8. lvca commented on Oct 9, 2026

    @lvca
    MemberAuthor

    Fixed by #9571 (release 26.11.1).

    An undirected pattern such as MATCH (a)-[:K]-(b) RETURN count(*) now counts a self loop once, as Neo4j and the openCypher spec do, so the result no longer changes when the same query is written behind a WITH. The fix covers every count shortcut, including COUNT { } subqueries and chain counts.

    While testing it we also fixed chain counts with an a <> c condition, which could be wrong when the first or last part of the chain carried a label or spanned several hops.

    Note: a query that relied on the old, doubled count now returns a smaller number.


    ❤️ Thanks for helping make ArcadeDB better! ArcadeDB is free and open source, sustained by its community. If it's useful to you or your company, please consider becoming a sponsor to keep development going.

  9. removed
    in progress
    on Oct 9, 2026
  10. added 2 commits that reference this issue on Oct 11, 2026
  11. added 3 commits that reference this issue on Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugopencypherseverity:minor

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions