Skip to content

Push count(*) below the joins for paths of three or more hops #135

Closed

Description

@prrao87

Problem

The two-hop count rewrite counts MATCH (a)-[:R]->(b)-[:S]->(c) RETURN count(*) as Σ_b n1(b) × n2(b), the product of each middle node's neighbours on either side, without building any path. A longer pattern, such as (a)-[:R]->(b)-[:S]->(c)-[:T]->(d) RETURN count(*), keeps the join plan and builds every path before counting it.

The first-hop count from #113 collapses only the first hop of a longer pattern; the hops after it still emit one row per match. Variable-length hops (-[:R*2..3]->) are never counted from degrees.

Idea

Count each end hop per node in place and sum their products over the middle hop's edges: Σ_(b,c) in(b) × out(c) for three hops, which follows the edges rather than the paths. Longer fixed-length patterns chain the same per-node sums.

Two things limit it:

  • Same-type hops. Cypher's rule that a path uses each edge once can exclude pairs of hops that aren't adjacent, such as r1 = r3 on a two-cycle, so the correction goes beyond the self-loop and shared-end cases the two-hop count handles. A first version could apply only when no two hops share a type.
  • Variable-length hops. The rule applies across the whole path, so degree products overcount any path that would revisit an edge. Short bounded lengths may be countable with corrections; otherwise they keep the current plan.

What to test on

Query 8 of graph-benchmark is the canonical example of this pattern. It is also the place to compare lance-csr with an engine that factorizes its intermediate results. Use LadybugDB for that comparison:

MATCH (a:Person)-[r1:Follows]->(b:Person)-[r2:Follows]->(c:Person)
RETURN count(*) AS numPaths

The benchmark generates a social network of 100,000 persons and 2,417,738 Follows edges, and has runners for Neo4j, Kuzu, LadybugDB, lance-csr, lance-graph and DuckPGQ over the same data. Its README reports q8 at 11.5 ms on Ladybug 0.21.2, which answers it without enumerating paths, against 14.5 ms on lance-csr 0.9.1, which already counts two hops from degrees, and 3.4 s on Neo4j, which builds every path (Apple M5, 24 GB).

q8 has two hops, so lance-csr already covers it. For this issue, add a hop at a time on the same data and runners:

MATCH (a:Person)-[:Follows]->(b:Person)-[:Follows]->(c:Person)-[:Follows]->(d:Person)
RETURN count(*) AS numPaths
  • What to report. The time on lance-csr and LadybugDB for two, three and four hops. A factorized engine's work follows the edges, so its time should grow slowly with each hop. lance-csr on main builds every path from the third hop on, and the dataset has 500 super nodes with hundreds to thousands of followers each, so the number of paths grows quickly. That gap is what this issue closes.
  • It is the same-type case. Every hop is Follows, so this query needs the corrections described under "Same-type hops". A first version limited to hops of different types won't apply to it. To test that version on this dataset, use a chain over different types, such as (i:Interest)<-[:HasInterest]-(a:Person)-[:Follows]->(b:Person)-[:LivesIn]->(c:City), and compare it with LadybugDB too.
  • Check the counts before the times. On two hops, Cypher's rule that a path uses each edge once only excludes pairs that reuse a self-loop, and the generator removes self-loops from its base edges. On three hops it also excludes paths whose first and third edge are the same, which happens wherever two persons follow each other. An engine that doesn't apply the rule returns a larger count, so confirm that lance-csr and LadybugDB agree, or say which rule each applies.

Experiments to run next

These upcoming experiments are ordered so that the first two, which need no engine change, decide whether the others are worth doing.

  1. Baseline against LadybugDB. Run q8 at two, three and four hops on lance-csr main and LadybugDB, and record counts and times. This gives the size of the gap, shows whether lance-csr finishes at four hops, and shows from the counts which edge-uniqueness rule LadybugDB applies. Every later experiment is measured against it.

  2. Write the pushdown by hand in Cypher. The idea can be tried without changing the planner:

    MATCH (a)-[:R]->(b) WITH b, count(*) AS n
    MATCH (b)-[:S]->(c) WITH c, sum(n) AS w
    MATCH (c)-[:T]->(d) RETURN sum(w)

    Time it against the plain three-hop query on main. If it lands near LadybugDB, the planner rewrite only automates it. If the grouped sum over the middle hop is slow, the fix is an operator that carries per-node weights along the CSR in place, as the degree count does for the end hops, and that is a larger change. Whether this Cypher plans as intended on lance-csr is itself unchecked.

  3. Derive the same-type correction for three hops, then check it by brute force. This addresses the first limitation. With three hops of one type, the excluded paths are those that reuse a self-loop and those whose first and third edge coincide, which needs two nodes joined in both directions. That should be a closed form over degrees, self-loop counts and mutual-edge counts. Validate it against the join path on small random graphs with self-loops, parallel edges and mutual edges, then measure how large the correction is on the benchmark data. The expected limit is four hops: the first and fourth edge coinciding closes a triangle, and triangle counts can't be read from degrees.

  4. Treat a bounded variable-length hop as a sum of fixed lengths. This addresses the second limitation. count(*) over -[:R*1..3]-> is the one-hop, two-hop and three-hop counts added together, each with its own correction, so experiment 3 answers it up to three hops. Longer bounds meet the same limit.

Separately, q8 itself takes 14.5 ms on lance-csr against 11.5 ms on LadybugDB, although neither enumerates paths. A profile would show where lance-csr's time goes. One candidate is the hash join of the two per-node counts: each direction's CSR numbers its nodes separately, so the counts can't simply be multiplied position by position. If the join dominates, q8 can get faster without any of the experiments above.

Split from #78.

Activity

  1. added
    enhancement
    on Nov 7, 2026
  2. changed the title [-]Count paths of three or more hops from node degrees[/-] [+]Push count(*) below the joins for paths of three or more hops[/+] on Nov 14, 2026
  3. prrao87 commented on Nov 14, 2026

    @prrao87
    MemberAuthor

    Experiment results (2026-11-14)

    Experiments 1 to 3 were run on main at 1cdd1b5 with the graph-benchmark data (100,000 persons, 2,417,738 Follows edges), release builds, Apple M5, 24 GB. A planner rewrite was built to test the idea. It is not being merged; the reasons are at the end.

    Baseline (experiments 1 and 2)

    count(*) over lance-csr main Pushdown written by hand in Cypher LadybugDB 0.22.3
    Two Follows hops 13.0 ms 12.5 ms 9.0 ms
    Three Follows hops 3,075 ms 23.5 ms 15.0 ms
    Four Follows hops 80.7 s 36.4 ms 23.0 ms
    Interest <- Person -> Person -> City 23.9 ms 15.2 ms 8.0 ms
    • The hand-written pushdown already plans from the edges on main, so a planner rewrite mostly automates it.
    • The engines count different things. LadybugDB and the hand-written Cypher return walks: 1,410,871,756 at three hops and 34,071,122,911 at four. lance-csr applies the rule that a path uses each edge once: 1,410,871,162 and 34,069,925,071. LadybugDB's times are for the easier question.

    Same-type correction for three hops (experiment 3)

    For (a)-->(b)-->(c)-->(d) of one type, the excluded walks are those with a = b = c or b = c = d (two self-loops at one node) and those with a = c and b = d (the first and third edge join the same nodes). With s(x) the self-loops at x, in and out its degrees, and m(x, y) the edges from x to y, they number

    Σ s(x)² × (in(x) + out(x)) - 2 × s(x)³ + Σ m(x, y)² × m(y, x)

    This matched path enumeration on random graphs with self-loops, parallel edges and pairs joined both ways. On the benchmark data it is 594, the number of pairs who follow each other. Four hops of one type were not attempted, as expected: they need triangle counts.

    The rewrite that was tried

    It handled an unfiltered count(*) over a directed chain of three or more hops, either all of different types, or three of one type pointing the same way. The end hops were counted per node in place and summed over the edges of the hops between them.

    count(*) over main Rewrite
    Three Follows hops 3,332 ms 64.6 ms
    Three hops of three types 24.4 ms 18.6 ms
    Four hops of four types 34.1 ms 21.0 ms
    Five hops of five types 47.6 ms 21.7 ms
    • Answers: identical to main on every query, including a synthetic graph with skewed degrees, self-loops and parallel edges.
    • Cost of the correction: about 40 of the 64.6 ms, because the last sum has to hash every edge. Grouping the edges instead of joining them with themselves did not help on this graph (80 against 83 ms in a busier run), and helped by 28% only where every edge has one back. Removing the cost would take a new CSR operator mode that intersects each node's out- and in-neighbours.
    • Suites: all 53 queries of graph-benchmark-ldbc, graph-benchmark-ldbc-complex and graph-benchmark kept exactly the same plan, so none of them gains.
    • Planning time: 0.5 to 2.8 ms more on rewritten queries.

    Why it is not being merged

    • It adds about 300 lines of planner logic for a query shape that no benchmark suite and no known workload contains: an unfiltered count over three or more hops.
    • Any filter, grouping, undirected hop or variable-length hop falls back to the current plan, and real queries usually have a filter.
    • The large gain is on a query used to compare engines, and the engine it is compared with answers an easier question.

    The findings suggest this is better served by the general mechanism in #134 than by another special case in the count planner. Experiment 4 (variable-length hops) and the q8 profile were not done.

  4. prrao87 commented on Nov 14, 2026

    @prrao87
    MemberAuthor

    Closing this issue now until we see a wider variety of patterns and have a real use case to test this on. We should focus on improving the use cases that exist!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions