Skip to content

perf(engine): parallel union-find (Afforest) for algo.wcc (#9133) - #9135

Merged
lvca merged 8 commits into
mainfrom
perf/9133-wcc-union-find
Oct 4, 2026
Merged

lvca merged 8 commits into
mainfrom
perf/9133-wcc-union-find

Conversation

@lvca

@lvca lvca commented Oct 3, 2026 •

Copy link
Copy Markdown
Member

Fixes #9133

Replaces the synchronous min-label propagation in GraphAlgorithms.connectedComponents with a lock-free parallel union-find with neighbour sampling (Afforest): sample 2 forward neighbours per node and type, pick the dominant root from 1024 sampled nodes, then finish only the nodes outside it using the remaining forward edges plus backward edges. Larger roots are always CAS-hooked under smaller ones, so the component id stays the min node id and callers are unchanged. Memory: one int[n]. The kernel now also exists as a package-private overload over raw CSR arrays so tests control node ids exactly.

The backward direction in the finish phase is required for correctness on directed CSRs: a node reachable from the giant component only by an incoming edge would otherwise be skipped. The giant root is re-resolved per node because phase 3 can re-hook it under a smaller id.

Tests (GraphAlgorithmsTest, 29 green, AlgoWCCTest green): randomized parallel-sized graphs checked against a sequential reference (end-to-end through a GAV with two edge types, and at CSR level for: giant with incoming-only satellites, lowest-id satellite re-hooking the giant root, many small components above the parallel threshold), plus self-loops, parallel edges, single node, and an edge type subset.

Local measurement (300k nodes, 3M skewed edges, warm): about 7.5 ms before, about 2.5 ms after. LDBC graph500-22 and datagen-7_5-fb numbers still to be measured with the Graphalytics harness.

Summary by CodeRabbit

  • Improvements
    • Connected-component analysis now uses a parallel approach designed to handle large and sparse graphs more efficiently.
    • Component IDs remain consistent, including for graphs with isolated nodes, self-loops, parallel edges, and selected edge types.

@lvca lvca added this to the 26.10.1 milestone Oct 3, 2026
@lvca lvca self-assigned this Oct 3, 2026
@coderabbitai

coderabbitai Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f4ed133f-96b8-4294-83eb-d9fbd8f640d3
📥 Commits

Reviewing files that changed from the base of the PR and between 33605b7 and c57c8ee.

📒 Files selected for processing (2)
  • engine/src/main/java/com/arcadedb/graph/olap/GraphAlgorithms.java
  • engine/src/test/java/com/arcadedb/graph/olap/GraphAlgorithmsTest.java

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.


📝 Walkthrough

Walkthrough

connectedComponents replaces synchronous min-label propagation with a sampled parallel union-find kernel. The kernel returns minimum-node component IDs. New regression tests compare its results with sequential references across CSR and database-backed graphs.

Changes

Connected Components

Layer / File(s) Summary
Kernel setup
engine/src/main/java/com/arcadedb/graph/olap/GraphAlgorithms.java
The public method passes prepared CSR arrays to a package-private union-find kernel. The kernel initializes parent IDs and adds limits for neighbor and dominant-root sampling.
Sampled union-find
engine/src/main/java/com/arcadedb/graph/olap/GraphAlgorithms.java
The kernel samples forward neighbors, selects a dominant root, and processes remaining edges for nodes outside that component. CAS links larger roots beneath smaller roots, and a final pass flattens the parent array.
Connected-components regression tests
engine/src/test/java/com/arcadedb/graph/olap/GraphAlgorithmsTest.java
Tests compare exact component IDs with sequential references across edge cases, edge-type selection, seeded sparse graphs, and database-backed graphs. The CSR kernel comparison runs five times.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to c57c8

Connected components now uses a faster parallel union-find while keeping the minimum-node-ID component results. Broad regression tests check its results against reference implementations. The review found no concrete defect. The benchmark measurements against the LDBC Graphalytics reference graphs are still pending.

Security Architecture Review

Security architecture risk: 🔵 Low · up to c57c8

The new computation preserves the existing inputs, outputs, and access path. No privilege expansion or broader data exposure was identified. Failure cleanup and execution against concurrently changing graph views remain incompletely validated.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Caller-selected relationship types and graph structure influence computation over the selected analytical view. The replacement does not introduce record lookups, credential use, or cross-database access. Computation still uses the shared query executor, so resource pressure can extend beyond one invocation; that dependency predates this change.

Trust Boundaries and Controls

  • inferred — The new raw-CSR overload remains package-private, and the public wrapper obtains arrays through the same graph-view and edge-type path as before. Backward-edge processing does not expand traversal authority: the previous implementation already traversed both directions.

Resilience and Maintainability Implications

  • observed — The await helper handles interruption, cancellation, and worker failures without returning successful partial results. An exception in the caller-executed chunk can bypass that helper and leave submitted workers running. This cleanup limitation exists in the pre-union-find implementation and is not established as a new or worsened security condition.

Hardening Proposals

  • proposed — As separate failure-containment hardening, ensure caller-chunk exceptions trigger worker cleanup and validate that path with fault injection. This addresses an inherited helper limitation, not a verified regression in this PR.
🚥 Pre-merge checks | ✅ 3 | ❌ 1 | ❓ 1

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.95% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 19 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check ❓ Inconclusive Issue #9133 asks to replace min-label propagation while preserving minimum-node component IDs and small-graph behavior. The PR implements parallel union-find with larger roots hooked under smaller roo… Provide evidence that the results match the LDBC Graphalytics WCC references for graph500-22 and datagen-7_5-fb.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the performance change and the Afforest-based union-find implementation for the WCC algorithm.
Description check ✅ Passed The description explains the change, its performance motivation, the related issue, implementation details, tests, and benchmark status. It does not confirm the required mvn clean package checklist …
Out of Scope Changes check ✅ Passed The changes are limited to the connectedComponents kernel, its package-private CSR overload, and tests for that kernel. These changes support issue #9133. No unrelated changes are present in the rev…
Full details: Linked Issues check

Explanation

Issue #9133 asks to replace min-label propagation while preserving minimum-node component IDs and small-graph behavior. The PR implements parallel union-find with larger roots hooked under smaller roots. It retains the parallel threshold through parallelForRange, and adds tests against a sequential reference for randomized and targeted CSR cases. The reviewed evidence does not establish matching output against the LDBC Graphalytics WCC references for graph500-22 and datagen-7_5-fb. The requested timing measurements and prior-pass count are measurement tasks, not coding requirements, so they do not affect this assessment.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mergify

mergify Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@codacy-production

codacy-production Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 16 complexity

Metric Results
Complexity 16

View in Codacy

🟢 Coverage 100.00% diff coverage · -5.68% coverage variation

Metric Results
Coverage variation ✅ -5.68% coverage variation
Diff coverage ✅ 100.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (33605b7) 210213 178315 84.83%
Head commit (c57c8ee) 243402 (+33189) 192652 (+14337) 79.15% (-5.68%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#9135) 73 73 100.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@claude

claude Bot commented Oct 3, 2026

Copy link
Copy Markdown

Review: parallel union-find (Afforest) for algo.wcc

Overall this is a solid change. I traced the algorithm and found no correctness bug, and I have one performance concern about the finish phase.

Correctness (verified by reading)

  • wccFind (path halving with opaque reads and writes) and wccUnion (CAS hi -> lo only while hi is still a root, then re-resolve and retry) are the standard lock-free pattern. A parent pointer only ever moves to an ancestor, and a root is only ever hooked under a smaller root. By induction the final root is the component minimum, so the "component id = min node id" contract holds.
  • Skipping giant-component nodes in phase 3 is safe. Any skipped edge u -> v either has both ends in the giant component, or v is outside it and picks up u through its backward row. The incoming-only satellite test targets exactly this case. The sampled edges (offsets[u] + r) and the phase-3 start (offsets[u] + WCC_SAMPLE_ROUNDS) line up, so no forward edge is dropped or double-counted.
  • parallelForRange joins its futures between phases, so phases 1 to 4 are ordered. Phase 4 only runs after all roots are final.
  • Small n is handled (samples = min(1024, n)), and (seed >>> 33) % n is non-negative.

Performance concern: giant is a fixed root id

Phase 3 skips a node when wccFind(parent, u) == giant, where giant is the root id captured in phase 2. Phase 3 itself can hook the giant's root under a smaller root. That happens whenever a lower-id node joins the giant through an edge that sampling skipped. Examples are a node with only incoming edges, which phase 1 never touches, or one reached only through a 3rd or later forward edge.

From then on no node in the giant matches giant any more, so every remaining node runs the full forward and backward scan. The result stays correct but the speedup is lost for the rest of the pass.

Low-id sink nodes are common in real data. In citation-style graphs the oldest nodes are cited but cite nothing, so they have a low id and no forward edges. Comparing against the giant's current root would avoid this:

if (wccFind(parent, u) == wccFind(parent, giant))
    continue;

giant stays hot in cache, so the extra find is cheap. Alternatively, re-resolve giant once per chunk. It would be worth adding a graph to the benchmark where vertex 0 is an incoming-only satellite of the giant, to confirm the speedup holds.

Tests

  • The two new tests compare against a sequential reference over a multi-type graph and cover the incoming-only satellite case. Both are above PARALLEL_THRESHOLD (8192). That is good.
  • PARALLELISM is availableProcessors(). On a 1-core CI runner the "parallel" tests run effectively sequentially, so they would not exercise the CAS races. That is not a blocker, but it is a limit on what they show.
  • Nothing yet covers the case from the concern above, a giant whose root gets re-hooked in phase 3. A small variant of the satellite test with the lowest id as an incoming-only node would at least pin the correctness side.
  • The reference union-find in the test walks roots without compression. That is fine at 44k edges.

Style and nits

  • The code matches the repo style (final locals, single-statement if without braces, no new dependencies, int[n] footprint). AtomicBoolean is still used elsewhere in the file, so the import stays.
  • The PR description says the LDBC graph500-22 and datagen-7_5-fb numbers are still to come. Those are the graphs that decide whether the sampling constants (2 rounds, 1024 samples) are right, so I would wait for them before merging. The local 7.5 ms to 2.5 ms on 300k nodes is encouraging but small.

Nothing blocking except the open benchmark numbers. I recommend the giant re-resolve fix.

@codecov

codecov Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 76.74%. Comparing base (33605b7) to head (c57c8ee).
⚠️ Report is 80 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #9135      +/-   ##
============================================
+ Coverage     76.57%   76.74%   +0.16%     
- Complexity     3906     3914       +8     
============================================
  Files          2117     2118       +1     
  Lines        210213   210802     +589     
  Branches      44483    44645     +162     
============================================
+ Hits         160981   161771     +790     
+ Misses        31938    31683     -255     
- Partials      17294    17348      +54     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review: parallel union-find (Afforest) for algo.wcc

Overall this is a clean, well-reasoned change. I traced the concurrency and correctness arguments and found no blocking issues.

Correctness (verified by reading)

  • Min-id invariant holds. wccUnion only CAS-hooks hi under lo (lo < hi), and wccFind halving only re-points a node to one of its own ancestors, so parent[x] <= x always. Each root is the minimum of its set, so the "component id = min node id" contract is preserved.
  • Path halving race is benign. The racy setOpaque only targets a node that was already a non-root when read, and non-roots never become roots again. A stale gp is still a valid ancestor, so at worst a shortcut is lost. CAS is only used on roots.
  • Phase 3 skip is sound. Skipping u because it is in the giant's component is safe: for an edge u->v with v outside, v unions via its backward row; for v->u, v handles it via its forward edges (phase 1 already did the first two). Re-resolving wccFind(parent, giant) per node is right since the giant's root can be re-hooked under a smaller id, and the third test covers exactly that.
  • Correctness does not depend on the sampled root being the largest component, only on it being a single component, so a poor sample costs performance, not results.

Suggestions (non-blocking)

  1. Giant-root lookup in phase 3. wccFind(parent, giant) runs for every node and all threads read the same cache lines. It is cheap once compressed, and caching it is not safe because the root can move, so I would leave it unless the graph500-22 numbers show it matters.
  2. Javadoc wording. "Each edge is visited about once" holds for edges touching the giant, but an edge between two non-giant nodes is visited in both the forward and backward direction. Consider "at most about twice".
  3. Test gaps (cheap to add, they exercise the new paths):
    • n == 1 and a graph with no edges (empty rows, wccDominantRoot with n < 1024),
    • self-loops and parallel edges between the same pair,
    • an edge type where one direction's CSR is null (all phases guard for it, a test would lock that in).
  4. Test runtime / tags. Each new test builds 20k-30k vertices through the full database path. If they take more than a couple of seconds in CI, consider @Tag("slow") per CLAUDE.md. Also assertMatchesReference creates the schema types inside the helper, so it can be called only once per test; fine today, maybe worth a one-line comment.
  5. Measurement. The description says the LDBC graph500-22 / datagen-7_5-fb numbers are still pending. Since the motivation is performance, please add them before merge, plus a high-diameter graph (where the old algorithm was worst) and a graph with many similar-sized components (where the dominant-root heuristic gives no benefit) to confirm no regression.

Style / conventions

  • Matches existing style (no braces on single statements, final params, imports). No new dependencies, no debug output, memory stays at a single int[n]. The AtomicBoolean import is still used elsewhere in the file.
  • getOpaque/setOpaque is appropriate here; plain reads could let the JIT hoist loads in the wccFind loop.

Nice work, especially the randomized comparison against a sequential reference and the dedicated regressions for the incoming-only and re-hook cases.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review: parallel union-find (Afforest) for algo.wcc

Overall this is a solid change. I traced the algorithm and the concurrency and found no correctness bugs.

Correctness (checked)

  • Hooking: the CAS in wccUnion only ever hooks a root (parent[hi] == hi) under a smaller id. Non-root entries are therefore always strictly smaller than their index, so no cycles are possible and the final root is the min node id. The "component id = min node id" contract holds.
  • Path halving under races: a racy setOpaque can only overwrite an entry with an ancestor of the same node. The worst case is lost compression, never a wrong root.
  • Phase 3 skip: skipping u when find(u) == find(giant) is safe. Component membership is monotone, so once u is in the giant component it stays there. Any edge u -> v with v outside the giant component is picked up by the backward row of v. Comparing against the current root of giant (not the id captured in phase 2) is the right call, and the re-hook test covers it.
  • Backward CSR: it is always built (double-indexed), so the incoming-only satellite handling is sound.
  • Edge cases: rows shorter than WCC_SAMPLE_ROUNDS, self-loops, parallel edges and n < 1024 all behave correctly. (seed >>> 33) % n is non-negative.

Tests
The tests are good. Comparing against a sequential reference, plus the incoming-only satellite case and the "lowest-id satellite re-hooks the giant root" case, targets exactly the subtle parts of the algorithm. Minor points:

  • assertMatchesReference builds the reference chain without compression or ranking. This is fine at these sizes, but worth a one-line note if someone scales the tests up.
  • The 20-30k vertex tests commit in batches, so they should be quick. If they take more than a couple of seconds in CI, consider @Tag("slow") per CLAUDE.md.
  • There is no test that restricts edgeTypes to a subset while other edge types exist in the view. The multi-type test always passes both types. A small one would guard the resolveEdgeTypes path.

Performance / nits

  • In phase 3, wccFind(parent, giant) runs for every node. It is cheap thanks to halving, but the giant root only changes if some lower-id node hooks it. Optionally cache the last observed root per chunk and re-resolve only when find(u) disagrees. Likely a micro-gain.
  • The 2.5 ms vs 7.5 ms number is on a 300k-node graph. The description says the LDBC runs (graph500-22, datagen-7_5-fb) are still to be measured. It would be good to see them before merge, especially on a high-diameter graph, where the old algorithm should do worst.
  • The Javadoc sentence "Each edge is visited at most about twice ... against once per pass ..." is a bit awkward. Consider tightening it.
  • There is no cancellation or checkpoint in the new loops. This matches the old implementation, which also used plain parallelForRange, so it is not a regression.

No security concerns. The change adds no dependencies and keeps memory at one int[n]. LGTM, pending the benchmark numbers.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review: parallel union-find (Afforest) for algo.wcc

I read the full diff and traced the algorithm. I did not run the tests. Overall this looks correct and well scoped. Nothing here blocks the merge.

Correctness (traced, no bugs found)

  • Min-id contract holds. wccUnion always CAS-hooks the larger root under the smaller one, so the final root is the component's minimum dense id. Path halving in wccFind only re-points a node to one of its own ancestors, which are always smaller ids, so concurrent halving is safe.
  • Skipping nodes in phase 3 is sound. For an edge u->v where u is already in the giant component and is skipped, either v is in the giant too (nothing to do) or v is processed and sees u through its backward row. Giant membership only grows, so the unsynchronised "already in giant" check cannot produce a false skip. The backward pass is what makes this work on directed CSRs, and a null bwdOffsets per type is handled the same way as elsewhere in GraphAlgorithms.
  • Re-hooked giant root. Re-resolving wccFind(parent, giant) per node instead of capturing the id is the right call, and the comment explains why.
  • Edge cases. Rows shorter than WCC_SAMPLE_ROUNDS, n < 1024, self-loops and parallel edges all behave. (seed >>> 33) % n is non-negative. The phase 4 flatten runs after all unions complete, so the opaque writes are safe.

Suggestions (non-blocking)

  1. Hot read in phase 3. wccFind(parent, giant) runs once per node, so every thread repeatedly reads the same few cache lines. It is cheap after compression. You could cache the giant root locally and re-resolve only when parent[cached] != cached. Please measure before changing it, since your 2.5 ms number may already make this irrelevant.
  2. Test gap: many small components above the parallel threshold. The new randomized tests all have a clear giant component. No test has n >= 8192 (PARALLEL_THRESHOLD) with no dominant component, for example 20k disjoint pairs and chains. That exercises the wccDominantRoot fallback, where the "giant" is just an arbitrary small component, on the multi-threaded path.
  3. Test coupling to dense-id order. connectedComponentsGiantRootRehookedByLowestIdSatellite relies on vertex 0 getting the lowest dense id, which depends on the view's build scan order. If that changes, the test would silently stop exercising the re-hook path. An assertion that gav.getNodeId(vertices[0].getIdentity()) is the minimum would keep it honest.
  4. PR description is stale. It says two new tests, but the diff adds six. Please update it.
  5. Javadoc wording. "Each edge is visited at most about twice ... against once per pass" is hard to parse. Something like "each edge is visited at most twice (once per direction), versus once per pass for label propagation" reads better.

Style and project rules

  • Follows CLAUDE.md: final usage, one-statement if without braces, assertj assertThat(...) style, no System.out, no new dependencies, and primitive int[] only (GC-friendly).
  • Test sizes (up to about 25k vertices) are modest. No @Tag("slow") seems needed, but keep an eye on engine test time.

Before merge

  • The LDBC graph500-22 and datagen-7_5-fb numbers are still pending per the description. The claimed gain (7.5 ms to 2.5 ms) comes from a synthetic skewed graph, so those runs would confirm the speedup on high-diameter and non-skewed graphs, where sampling helps less.

🤖 Generated with Claude Code

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review: parallel union-find (Afforest) for algo.wcc

Overall this is a solid change. I traced the algorithm and found no correctness bugs. A few minor remarks below.

Correctness (traced, looks right)

  • Min-id contract: wccUnion always CAS-hooks the larger root under the smaller one, and the CAS only succeeds while hi is still a root. After a lost race both roots are re-resolved, so the loop is sound. Roots only decrease, so the final root is the component's min node id and callers are unaffected.
  • Phase 3 skip: membership in the giant component only grows, so skipping a node that was in it at check time is safe. Any edge u->v with u skipped is still covered, either by v processing its backward row, or because both are already in the same component. Re-resolving wccFind(parent, giant) per node handles the re-hook case, and connectedComponentsGiantRootRehookedByLowestIdSatellite covers it.
  • Path halving with setOpaque: only non-root nodes are rewritten, and CAS only targets roots, so the plain write cannot clobber a concurrent hook. The target is always an ancestor. Phase 4 runs after the phase 3 join, so the forest is static there. The parallelForRange join provides the happens-before for the returned array.
  • (int) ((seed >>> 33) % n) is always in range, and the sample is deterministic, so runs are reproducible.
  • Edge cases (null CSR per type, rows shorter than WCC_SAMPLE_ROUNDS, n < 1024, self-loops, parallel edges) are handled.

Performance

  • 7.5 ms to 2.5 ms and one int[n] instead of two is a nice win. Please post the LDBC graph500-22 and datagen-7_5-fb numbers before merge, as noted in the description. Skewed-degree graphs are where Afforest's phase 3 behavior matters most.
  • Minor: phase 3 calls wccFind(parent, giant) for every node, so all threads read the same hot parent[giant] slot. It is read-mostly so probably fine, but you could cache the giant's root in a local per range and only re-resolve when wccFind(u) differs from the cached value. Optional.

Code quality / style

  • The Javadoc on connectedComponents has awkward wrapping ("Memory is a" followed by "single {@code int[n]}") and some overlong lines. Worth re-flowing.
  • The kernel assumes all four CSR arrays have the same length (one entry per edge type). Worth stating in its Javadoc.
  • The AtomicBoolean import is still needed (used elsewhere, line ~1544), so no leftover import.

Tests

  • Good coverage: randomized comparison against a sequential reference through the GAV (two edge types) and at CSR level, giant with incoming-only satellites, giant root re-hook, many small components above PARALLEL_THRESHOLD (8192), self-loops, parallel edges, single node, edge type subset. The hand-built CSR overload is a nice way to control ids exactly.
  • Suggestion: the re-hook and incoming-only tests rely on the 1024-node deterministic sample picking the intended giant. Nothing asserts that the re-hook path was actually hit, so if the sampling constants or hash change, the test could silently stop exercising it. A comment noting the dependency (or a precondition check) would help.
  • Nit: connectedComponentsMatchesReferenceOnLargeSparseGraph creates 30k vertices and 44k edges in a DB. If it is noticeably slow in CI, consider @Tag("slow"); otherwise fine.

Security

No concerns. Pure in-memory computation on engine-owned arrays, no new dependencies.

I did not run the test suite myself, only traced the code. No blockers from my side.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review: parallel union-find (Afforest) for algo.wcc

I read the full diff and traced the algorithm by hand. I did not build the project or run the tests, so the test-coverage notes below come from reading the test code only.

Verdict: no blocking issues. The algorithm looks correct.

Correctness (traced)

  • Union-find: wccUnion always hooks the larger root under the smaller one, using a CAS on a node that is still a root. Non-root entries are only ever re-pointed to ancestors by path halving. So parent[x] <= x always holds, and the final root is the minimum node id of the component. That keeps the "component id = min node id" contract for callers.
  • Halving races: setOpaque in wccFind is safe against a concurrent CAS. It only writes to a node it just observed as a non-root, and non-roots never become roots again. A stale write can only leave a less-compressed pointer, never a wrong one.
  • Phase 3 skip: A node is skipped only if it is already in the giant component, and components only merge, so that membership is permanent. An edge u->v with u in the giant is covered from v, through its backward row or its forward row. Edges between two giant nodes need no work. Re-resolving wccFind(parent, giant) per node is the right call, since phase 3 can re-hook the giant root.
  • Boundaries:
    • The fwdOffsets[u] + r and + WCC_SAMPLE_ROUNDS bounds are fine for short rows.
    • Self-loops and parallel edges are fine.
    • The sampling index (seed >>> 33) % n is non-negative.
    • Phase 4 flattening only runs after phase 3 completes. awaitFutures provides the happens-before edge.
  • Cancellation: There is no checkpoint, as before (the old code used plain parallelForRange too), so this is not a regression.

Test suggestions (non-blocking)

  1. connectedComponentsGiantRootRehookedByLowestIdSatellite never asserts that the re-hook happens. The Javadoc admits it depends on the sampling constants and hash. If the dominant-root pick changes, the test passes while no longer covering the scenario it is named for. A cheap fix would be a package-private way to observe it, such as returning or recording the giant root. Another would be a variant that fixes the dominant root by construction.
  2. The "remaining forward edges" loop (j = fwdOffsets[u] + WCC_SAMPLE_ROUNDS) is only lightly covered. Most test nodes have out-degree of about 1 or 2 per type, so almost all forward edges are consumed in phase 1. A node outside the giant with more than 2 forward edges per type would catch an off-by-one in the loop start. A hub or star outside the dominant component, with out-degree well above 2 per type, would do it. The random sparse test hits this only incidentally.
  3. Runtime of the DB-backed test: connectedComponentsMatchesReferenceOnLargeSparseGraph creates 30k vertices and 44k edges through the full engine. If it takes more than a couple of seconds, consider @Tag("slow") per CLAUDE.md. The kernel-level tests are cheap.

Minor / optional

  • Per-node wccFind(parent, giant) in phase 3: Every worker reads the same hot path on each node. It is read-mostly and should be cheap after halving. If the LDBC runs show contention, you could re-resolve the giant root only every N nodes, or when the value changes. I would not do it without data.
  • Sampling bias: The first 2 forward neighbours per type are not random, and if CSR rows are sorted they are the lowest ids. This only affects how much work phase 3 has to do, not correctness. It is worth knowing if the graph500 numbers look odd.
  • Kernel contract: If a type has a forward CSR but a null backward CSR, incoming-only nodes can no longer be reached. The old code had the same limitation, but the new package-private overload's Javadoc could say that both directions are required for weak connectivity.
  • Benchmarks: The PR notes the LDBC graph500-22 and datagen-7_5-fb numbers are still to be measured. Please post them before merge, since the claimed speedup (7.5 ms to 2.5 ms) comes from a single local run on 300k nodes.

Style and conventions look fine: final is used, there are no stray System.out calls, and the tests use the assertThat(...) form. No new dependencies.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review: parallel union-find (Afforest) for algo.wcc

Overall this is a solid change. I walked through the algorithm and found no correctness bugs.

Correctness (verified by reading)

  • Min-id contract holds. Hooking is always hi under lo by CAS on a root, and halving only re-points a node to one of its own ancestors. So parent ids only decrease, a non-root never becomes a root again, and the component minimum can never be hooked. The final root is therefore the min node id, and phase 4 flattening is safe.
  • Phase 3 skip is sound. Components only ever merge, so find(u) == find(giant) stays true once observed. For an edge u->v with u skipped, either v is also in the giant component, or v processes the edge as a backward edge. Re-resolving the giant root per node correctly handles the re-hook case.
  • Concurrency is fine. Stale halving writes only lose compression, never correctness. parallelForRange joins on futures, so there is a happens-before edge between phases and before the plain reads by the caller.
  • Edge cases are fine. Rows shorter than WCC_SAMPLE_ROUNDS, null CSR entries for a type, n < 1024 samples, and a "giant" picked arbitrarily when there is none (still correct, just no speedup).

Suggestions (non-blocking)

  1. Per-node wccFind(parent, giant) in phase 3. Every node re-resolves the giant root. After compression this is cheap, but it is a read-hot cache line shared by all threads. Re-resolving only when find(u) differs from the cached root, or caching the root and refreshing it on a mismatch, would likely be cheaper. Please measure it on the LDBC graphs you mention.
  2. Tests cannot assert the interesting interleavings. connectedComponentsGiantRootRehookedByLowestIdSatellite relies on the fixed sample/hash to make the giant the dominant root, and nothing asserts that the re-hook path actually ran. The javadoc already says so, which is good. If you want it robust against constant changes, you could expose wccDominantRoot package-private and assert it equals the expected root in that test.
  3. Missing kernel-level test with a null CSR entry (a type with no CSR, in either the fwd or bwd arrays). assertKernelMatchesReference always builds non-null arrays for both types. The edge-type-subset GAV test only covers resolveEdgeTypes. A cheap addition: pass null for one type's four arrays.
  4. Race-sensitive code, single-shot randomized tests. The tests use fixed seeds, so they exercise one schedule per run. Consider looping the kernel call a handful of times on the same CSR (results must be identical each time) to shake out nondeterminism.
  5. Benchmark numbers. The PR states LDBC graph500-22 and datagen-7_5-fb are still to be measured. Please add them before merge, especially for the many-small-components and high-diameter cases, where there is no giant and the gain should be smaller.

Style / conventions

  • Conforms to CLAUDE.md: final usage, single-statement ifs without braces, assertj style, JDK VarHandle (no new dependency).
  • The test helper assertMatchesReference and assertKernelMatchesReference duplicate the sequential reference union-find. A small shared helper would avoid the copy, but that is minor.
  • Nit: the AtomicBoolean import is still used elsewhere in the file (label propagation), so no cleanup is needed.

No blocking issues from me. Nice speedup and good test design for the incoming-only-edge hazard.

🤖 Generated with Claude Code

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review: parallel union-find (Afforest) for algo.wcc

I read the diff in full. I did not build it or run the tests. I am relying on the 29 green tests reported in the PR description.

Correctness

The algorithm is sound, and the points I checked all hold:

  • Skip in phase 3. Membership in the dominant component only grows during the phase. A skipped node u has an edge to some w. Either w is also in the giant component, or w is outside it and processes that edge itself, through its forward row or its backward row. So skipping is safe.
  • Re-resolving the giant root. wccFind(parent, giant) is evaluated per node, which is correct. The giant root can be re-hooked under a smaller id during phase 3.
  • Hooking. compareAndSet(hi, hi, lo) only succeeds while hi is still a root. On failure both roots are re-resolved, so the loop terminates. Hooking larger under smaller keeps "component id = min node id", so callers are unchanged.
  • Path halving. Only non-root nodes are written. They are re-pointed to one of their own ancestors, so this cannot race with the root CAS.
  • Phase 4. The final flatten runs after the phase 3 join, so no unions are in flight.
  • Sampling. (seed >>> 33) % n is non-negative and in range. n < 1024 is handled by Math.min. Rows shorter than WCC_SAMPLE_ROUNDS are guarded by j < fwdOffsets[u + 1]. Null CSR entries are skipped in every phase.
  • Sequential fallback. parallelForRange runs inline below PARALLEL_THRESHOLD, so the same code is correct single-threaded.

Tests

Coverage is good:

  • Randomized comparisons against a sequential reference, both through a GAV and at CSR level.
  • Incoming-only satellites, giant-root re-hooking, hubs with high out-degree, many small components, self-loops, parallel edges, a single node, and an edge-type subset.
  • A trailing null edge-type entry, plus five repeated runs to shake out schedule-dependent results.
  • The package-private overload over raw CSR arrays lets the tests control node ids exactly. That was a good call.

Suggestions (non-blocking)

  1. Fragile test. connectedComponentsGiantRootRehookedByLowestIdSatellite relies on the 20k-node giant being picked by the hard-coded sample constants and LCG. The comment says so, but nothing fails loudly if that stops being true. The test would still pass while no longer covering the re-hook path. Consider a cheap guard. For example, expose wccDominantRoot package-private, or build a small kernel-level case that forces giant to be re-hooked, and assert it directly.
  2. Phase 3 hot path. wccFind(parent, giant) runs for every node, so every worker thread reads the same hot cache lines. With path halving the chain is short, so this probably costs little. You could cache the giant root in a local and re-resolve it only when wccFind(parent, u) differs from the cached value. That saves one find per node, and the cached value stays valid because a stale root still resolves to the same component. Measure first, though. A micro-optimization is not needed if the numbers are already good.
  3. Benchmark numbers. The description says LDBC graph500-22 and datagen-7_5-fb are "still to be measured". The 7.5 ms to 2.5 ms local result is on a skewed synthetic graph with one giant component. The worst case for this design is a graph with no dominant component. Phase 3 then degenerates to a full two-direction pass, which should still be no worse than before, but a number for that would be useful.
  4. Reference union-find in tests. The test reference has no path compression, so each find walks a chain. At 30k nodes this is fine. If sizes grow, add path halving there.
  5. Minor. The Javadoc says "versus once per pass for label propagation". That is accurate, but a short note that results are deterministic regardless of thread schedule would help future readers, given the "racy by design" comment in the tests.

CLAUDE.md conformance

  • No new dependencies and no System.out.
  • Imports are used rather than FQNs.
  • Tests use assertThat(...).
  • Memory is a single int[n], with no per-node objects.
  • Check that AtomicBoolean is still used elsewhere in GraphAlgorithms.java. The old code used it only here. If nothing else uses it, remove the import.

Overall this looks good to merge once CI is green. The suggestions above are optional.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

algo.wcc: min-label propagation rescans every edge on each pass; a parallel union-find would need far fewer edge visits

1 participant