Skip to content

fix(#4287): split comma/pipe-separated relTypes string in extractRelTypes - #4360

Merged
robfrank merged 4 commits into
mainfrom
fix/4287-leiden-reltypes-singleton
May 27, 2026
Merged

robfrank merged 4 commits into
mainfrom
fix/4287-leiden-reltypes-singleton

Conversation

@robfrank

Copy link
Copy Markdown
Collaborator

Closes #4287

Summary

algo.leiden("TYPE_A,TYPE_B") and all other algo.* procedures returned singleton
communities for every node when a comma- or pipe-separated relTypes string was passed.
The root cause was in AbstractAlgoProcedure.extractRelTypes(), which wrapped the entire
string as a single array element instead of splitting it:

// before — wraps the whole string as one non-existent type name
case String s -> new String[]{s};

Because no edge type named "TYPE_A,TYPE_B" exists, the graph appeared to have no edges,
so each node was placed in its own community.

The fix adds a splitRelTypeString() helper that splits on , or |, trims whitespace
from each token, and drops empty tokens. A second fix extends
AbstractPathProcedure.extractRelTypes() to also handle comma separators (it previously
handled only |).

Both changes are single-method fixes in the two base classes; all derived procedures
(AlgoLouvain, AlgoSCC, AlgoWCC, PathExpand, PathSubgraphAll, etc.) inherit the
corrected behaviour automatically.

Test plan

  • AlgoLeidenTest.leidenWithCommaRelTypesYieldsMultiNodeCommunities — calls
    algo.leiden('KNOWS,NONEXISTENT') on the standard 6-node / 2-community test graph and
    asserts that at least two nodes share a community (proving KNOWS edges were matched after
    the split).
  • AlgoLeidenTest.leidenWithPipeRelTypesYieldsMultiNodeCommunities — same with
    'KNOWS|NONEXISTENT'.
  • All 8 AlgoLeidenTest tests pass.
  • All 270 Algo*Test tests pass.
  • All 110 path-related tests pass.

🤖 Generated with Claude Code

@codacy-production

codacy-production Bot commented May 27, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Coverage 45.83% diff coverage · -7.84% coverage variation

Metric Results
Coverage variation ✅ -7.84% coverage variation
Diff coverage ✅ 45.83% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (f2a41f8) 127753 94277 73.80%
Head commit (1bfcf30) 159446 (+31693) 105165 (+10888) 65.96% (-7.84%)

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 (#4360) 24 11 45.83%

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request addresses an issue where passing comma- or pipe-separated relationship types to algorithm and path procedures (such as algo.leiden()) incorrectly treated the entire string as a single type, resulting in singleton communities. The changes split the input string on commas and pipes and trim the individual tokens. The review feedback points out an inconsistency where single relationship types are not trimmed, whereas split types are. It also highlights that if the input string contains only delimiters or spaces, the methods might return empty arrays instead of null consistently.

Comment on lines +131 to +143
private static String[] splitRelTypeString(final String s) {
if (s.isEmpty())
return null;
if (!s.contains(",") && !s.contains("|"))
return new String[]{s};
final List<String> types = new ArrayList<>();
for (final String part : s.split("[,|]")) {
final String trimmed = part.trim();
if (!trimmed.isEmpty())
types.add(trimmed);
}
return types.isEmpty() ? null : types.toArray(new String[0]);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There is an inconsistency in how single vs. multiple relationship types are handled regarding whitespace. If a single relationship type with leading/trailing spaces is passed (e.g., " TYPE_A "), it is returned untrimmed because it doesn't contain , or |. However, if multiple types are passed (e.g., "TYPE_A, TYPE_B"), they are trimmed. To ensure consistent behavior and prevent potential matching issues due to accidental whitespace, we should trim the input string first.

Suggested change
private static String[] splitRelTypeString(final String s) {
if (s.isEmpty())
return null;
if (!s.contains(",") && !s.contains("|"))
return new String[]{s};
final List<String> types = new ArrayList<>();
for (final String part : s.split("[,|]")) {
final String trimmed = part.trim();
if (!trimmed.isEmpty())
types.add(trimmed);
}
return types.isEmpty() ? null : types.toArray(new String[0]);
}
private static String[] splitRelTypeString(final String s) {
final String trimmedSource = s.trim();
if (trimmedSource.isEmpty())
return null;
if (!trimmedSource.contains(",") && !trimmedSource.contains("|"))
return new String[]{trimmedSource};
final List<String> types = new ArrayList<>();
for (final String part : trimmedSource.split("[,|]")) {
final String trimmed = part.trim();
if (!trimmed.isEmpty())
types.add(trimmed);
}
return types.isEmpty() ? null : types.toArray(new String[0]);
}

Comment on lines 55 to 63
if (s.isEmpty())
return null;

// Handle pipe-separated format "REL1|REL2|REL3"
if (s.contains("|"))
return s.split("\\|");
// Handle pipe- or comma-separated format "REL1|REL2" or "REL1,REL2"
if (s.contains("|") || s.contains(","))
return Arrays.stream(s.split("[,|]")).map(String::trim).filter(t -> !t.isEmpty()).toArray(String[]::new);

return new String[]{s};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similar to AbstractAlgoProcedure, there is an inconsistency where single relationship types are not trimmed, while split types are. Additionally, if the input string contains only delimiters/spaces (e.g., ","), this method returns an empty array String[0] instead of null, which is inconsistent with how empty strings are handled. Trimming the source string first and returning null if no valid types are found resolves both issues.

      final String trimmedSource = s.trim();
      if (trimmedSource.isEmpty())
        return null;

      // Handle pipe- or comma-separated format "REL1|REL2" or "REL1,REL2"
      if (trimmedSource.contains("|") || trimmedSource.contains(",")) {
        final String[] types = Arrays.stream(trimmedSource.split("[,|]")).map(String::trim).filter(t -> !t.isEmpty()).toArray(String[]::new);
        return types.length == 0 ? null : types;
      }

      return new String[]{trimmedSource};

@claude

claude Bot commented May 27, 2026

Copy link
Copy Markdown

Code Review

Overview

This PR fixes a real bug: algo.* procedures and path procedures silently treated a comma- or pipe-separated relTypes string (e.g. "KNOWS,FRIENDS") as a single non-existent edge type, resulting in every node being placed in its own singleton community. The root cause and fix are correctly identified. The logic is sound and all derived procedures inherit the fix automatically.


Issues

1. Spurious documentation file (docs/4287-leiden-reltypes-singleton.md)

This file is an implementation planning/debugging document and should not be committed to the repository. It duplicates information already in the PR description and git history, and will rot quickly as the codebase evolves. Please drop it from the PR.

2. Code duplication between the two base classes

AbstractAlgoProcedure.splitRelTypeString() (loop-based) and the updated AbstractPathProcedure.extractRelTypes() (streams-based) implement the same logic in two different styles. These classes are not in the same hierarchy, so the natural fix would be a small package-private utility - or at least using the same implementation style. As-is, the next person who needs to adjust the splitting behaviour has to remember to update two places.

3. Inconsistent trimming in splitRelTypeString()

When the string contains no delimiter, the fast-path returns the original string verbatim:

if (!s.contains(",") && !s.contains("|"))
    return new String[]{s};   // no trim here

But when a delimiter is present, each token is trimmed. So " KNOWS " (leading/trailing spaces, no delimiter) is not trimmed while " KNOWS , FRIENDS " is. A quick s.trim() on the fast-path would make the two branches consistent.

4. Test method comments reference the fix

Per project conventions, comments should not reference the current task or pre-fix behaviour. Lines like:

// Without the fix, the whole string is treated as one non-existent type so
// every node appears isolated (all singleton communities).

describe what used to happen rather than a non-obvious invariant. Please remove them.

5. Duplicated test methods - consider @ParameterizedTest

leidenWithCommaRelTypesYieldsMultiNodeCommunities and leidenWithPipeRelTypesYieldsMultiNodeCommunities are identical except for the separator character. A parameterized test avoids the duplication and makes it easier to add more separators later using @ParameterizedTest with @ValueSource.


Minor Nit

In AbstractPathProcedure.extractRelTypes() the old single-type path returned the raw string without trimming; the new multi-type path trims each token. It would be worth trimming the single-type return too for the same consistency reason as point 3 above.


Summary

The bug fix itself is correct and the approach is clean. The main things to address before merging: drop the documentation file, fix the no-delimiter trim inconsistency, and clean up the test comments.

@claude

claude Bot commented May 27, 2026

Copy link
Copy Markdown

Code Review

Overview

This PR fixes a real bug (#4287): algo.* procedures treated a comma- or pipe-separated relTypes string as a single non-existent edge type, causing every node to land in its own community. The root cause analysis is correct and the fix is minimal and focused.


Issues

Critical

1. docs/4287-leiden-reltypes-singleton.md should not be committed

This file is Claude Code's internal working notes (review cycles, commit SHAs, gemini reviewer status). It is not project documentation and should be removed from the PR before merging. Per CLAUDE.md: "do not create planning, decision, or analysis documents unless the user asks for them."


Medium

2. extractLabels() in AbstractPathProcedure is now inconsistent

extractRelTypes() was updated to handle both , and |, but the sibling method extractLabels() (lines 74-92) still only splits on |. If a user passes "Label1,Label2" as node labels to a path procedure it will be treated as a single non-existent label - the same bug pattern this PR is fixing. Recommend updating extractLabels() at the same time, or at minimum opening a follow-up issue.

3. No regression tests for AbstractPathProcedure

The path procedures (PathExpand, PathSubgraphAll, etc.) also inherit the old broken extractRelTypes(), but this PR only adds tests for AlgoLeiden. A test against apoc.path.expandConfig or apoc.path.subgraphAll with a comma-separated relFilter would close the coverage gap and confirm the AbstractPathProcedure fix actually works end-to-end.


Minor / Style

4. Duplicated split logic in two base classes

AbstractAlgoProcedure.splitRelTypeString() and the inline logic added to AbstractPathProcedure.extractRelTypes() do the same thing but are written differently (for-loop vs streams). If these classes share a common ancestor or a utility class already exists in the package, the logic should live once. If not, at least keep the style consistent between the two.

5. Style inconsistency between the two implementations

splitRelTypeString() uses a for loop + ArrayList:

for (final String part : trimmedSource.split("[,|]")) {
    final String trimmed = part.trim();
    if (!trimmed.isEmpty())
        types.add(trimmed);
}
return types.isEmpty() ? null : types.toArray(new String[0]);

While AbstractPathProcedure uses streams:

final String[] types = Arrays.stream(trimmedSource.split("[,|]"))
    .map(String::trim).filter(t -> !t.isEmpty()).toArray(String[]::new);
return types.length == 0 ? null : types;

The stream form in AbstractPathProcedure also produces a result with a known size directly as String[], avoiding the intermediate List. Pick one style and apply it consistently. The loop variant in AbstractAlgoProcedure is also heavier on GC (creates an ArrayList even for the common single-type case where no splitting happens).

6. Line length in AbstractPathProcedure.java:61 exceeds 160 chars

The project's Prettier config uses printWidth: 160. That line should be broken across two lines.

7. Test method comments reference the bug fix context

Per CLAUDE.md: "Don't reference the current task, fix, or callers - those belong in the PR description and rot as the codebase evolves."

The block comments // "KNOWS,NONEXISTENT" must be split into... Without the fix, the whole string is treated as... describe why the test exists, not a non-obvious invariant. They should be removed; the test name and the PR description already carry that context.

8. Near-duplicate test methods are candidates for @ParameterizedTest

leidenWithCommaRelTypesYieldsMultiNodeCommunities and leidenWithPipeRelTypesYieldsMultiNodeCommunities differ only in the separator character. A @ParameterizedTest + @ValueSource(strings = {"KNOWS,NONEXISTENT", "KNOWS|NONEXISTENT"}) would keep the test logic in one place and make adding a third separator trivial.


Summary

The fix itself is correct. The two blocking items before merge are: (1) remove the docs file, and (2) either fix extractLabels() or file a tracked follow-up. The style points are clean-up that would help maintainability but are not blockers.

@claude

claude Bot commented May 27, 2026

Copy link
Copy Markdown

test

@claude

claude Bot commented May 27, 2026

Copy link
Copy Markdown

Code Review

Summary: This PR correctly identifies and fixes a real bug - extractRelTypes() in both base classes was treating a comma- or pipe-separated string as a single opaque type name, causing every node to appear isolated and producing all-singleton communities. The fix is well-targeted and the regression tests are solid.


What works well

  • The root cause analysis is accurate and the fix is minimal and correct.
  • Both base classes are fixed, so all derived procedures inherit the behavior automatically.
  • The two regression tests verify the actual observable symptom (multi-node communities vs. singletons), not just the internal split, which makes them more meaningful.
  • Null/empty/no-delimiter paths are all handled consistently between the two implementations.
  • Imports were already in place (ArrayList, List, Arrays) so no compilation surprises.

Issues and suggestions

1. Redundant delimiter pre-check in splitRelTypeString() (minor)

The guard below is unnecessary:

if (!trimmedSource.contains(",") && !trimmedSource.contains("|"))
    return new String[]{trimmedSource};

trimmedSource.split("[,|]") on a string with no delimiters already returns new String[]{trimmedSource}, so the pre-check duplicates the split's own behavior. Removing it simplifies the method without changing semantics.

2. Inconsistent style between the two fixed methods (minor)

AbstractAlgoProcedure.splitRelTypeString() uses a for-each loop, while AbstractPathProcedure.extractRelTypes() uses Arrays.stream().map().filter().toArray() inline. Both are correct, but given that the two methods solve the exact same sub-problem, consistency (either both loop or both stream) would make future maintenance easier.

3. Duplicated split logic across two base classes (suggestion)

Both classes now independently implement the same comma/pipe-split-and-trim pattern. This is acceptable for a targeted bug fix, but if a third caller ever needs it a shared utility (e.g., a package-private ProcedureUtils.splitRelTypes()) would be the natural home. Not required now - just worth noting so it stays on the radar.

4. Overly verbose test comments (style, per CLAUDE.md)

The comment blocks inside the two new test methods explain what happens "without the fix." CLAUDE.md asks for comments only when the WHY is non-obvious. The test names already communicate intent (leidenWithCommaRelTypesYieldsMultiNodeCommunities), and the assertions are self-explanatory. The multi-line explanatory comments can be trimmed.


Overall assessment

The fix is correct, the tests cover both separator styles, and there are no security or performance regressions introduced. The items above are all minor style and simplification points - none of them block merging. The most actionable one is removing the redundant delimiter pre-check in splitRelTypeString().

@claude

claude Bot commented May 27, 2026

Copy link
Copy Markdown

Code Review

Overview

This PR correctly identifies and fixes a real bug: extractRelTypes() in AbstractAlgoProcedure was wrapping the entire input string as a single array element instead of splitting it on , or |. The root cause explanation is clear, the fix is minimal, and the regression tests are well-structured. Good use of @ParameterizedTest + @ValueSource to cover both separators with a single test method.


Correctness

The core fix is correct. The regex [,|] is valid - | inside a character class is treated as a literal, not alternation, so this splits on both characters as intended.

Consistency gap - AbstractPathProcedure.extractLabels(): The same comma-split fix was applied to extractLabels() which is good for consistency. However, there are no new tests covering extractLabels() with comma-separated input. If a caller passes "Label1,Label2", the fix silently lands untested.

Trim behavior on old pipe split: The pre-existing code in AbstractPathProcedure used s.split("\\|") which did not trim whitespace from tokens (e.g. "REL1 | REL2" would yield "REL1 " and " REL2"). The new code correctly adds .map(String::trim) - this is a latent bug fix bundled in, worth calling out in the PR description.


Code Quality

Style inconsistency between the two classes: AbstractAlgoProcedure.splitRelTypeString() uses a manual ArrayList + loop while AbstractPathProcedure uses Arrays.stream(...).filter(...).toArray(...). Both approaches are fine, but they diverge in style for essentially identical logic. Prefer one approach - the stream form in AbstractPathProcedure is more idiomatic and concise.

Duplicated splitting logic: splitRelTypeString() is private static in AbstractAlgoProcedure, making it unreachable from AbstractPathProcedure. If these two classes share a common base or utility, extracting this logic into a shared protected static helper (or a package-level utility) would eliminate the duplication and ensure both classes stay in sync if the splitting rules ever change.

Minor - new String[0] vs String[]::new: types.toArray(new String[0]) (in AbstractAlgoProcedure) and .toArray(String[]::new) (in AbstractPathProcedure) are semantically equivalent, but mixing them in the same PR adds unnecessary visual noise. Pick one - String[]::new is the modern idiomatic form.


Test Coverage

Good:

  • Parameterized test covers comma and pipe separators in one test method - avoids duplication.
  • Assert logic (unique.size() < communities.size()) is robust against algorithm non-determinism.

Gaps to consider:

  1. Whitespace handling - A test like " KNOWS , NONEXISTENT " (padded separators) would confirm the trim logic works end-to-end, since that was a latent defect in the old AbstractPathProcedure code.

  2. Other algo procedures - The fix is inherited by AlgoLouvain, AlgoSCC, AlgoWCC, etc. Even a single smoke test for one other algorithm (e.g. algo.wcc('KNOWS,NONEXISTENT')) with comma-separated types would prevent regression if the inheritance chain changes.

  3. Path procedures - AbstractPathProcedure.extractRelTypes() was also fixed but no new path-procedure tests cover comma-separated input.

  4. extractLabels() fix - No test exercises comma-separated node labels.


Summary

Area Assessment
Bug fix correctness Correct
Regression test Present and well-structured
Style consistency Minor inconsistencies between the two classes
Code duplication splitRelTypeString logic is duplicated across the two files
Test coverage gaps extractLabels, path procedures, whitespace edge cases untested

The fix itself is solid and the main regression test covers the reported issue well. The suggestions above are mostly polish - the duplication point is the most worth addressing before merge to avoid the two implementations drifting apart in the future.

@codecov

codecov Bot commented May 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 33.33333% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.27%. Comparing base (f2a41f8) to head (1bfcf30).

Files with missing lines Patch % Lines
...ncypher/procedures/path/AbstractPathProcedure.java 0.00% 12 Missing ⚠️
...ncypher/procedures/algo/AbstractAlgoProcedure.java 66.66% 1 Missing and 3 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #4360      +/-   ##
============================================
- Coverage     64.65%   64.27%   -0.39%     
- Complexity      423      424       +1     
============================================
  Files          1647     1647              
  Lines        127753   127768      +15     
  Branches      27382    27389       +7     
============================================
- Hits          82599    82120     -479     
- Misses        33507    34103     +596     
+ Partials      11647    11545     -102     

☔ View full report in Codecov by Sentry.
📢 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.

@robfrank
robfrank merged commit 2a3810f into main May 27, 2026
26 of 30 checks passed
@robfrank
robfrank deleted the fix/4287-leiden-reltypes-singleton branch May 27, 2026 09:46
@robfrank robfrank added this to the 26.6.1 milestone May 27, 2026
@robfrank robfrank self-assigned this May 27, 2026
tae898 pushed a commit to humemai/arcadedb-embedded-python that referenced this pull request Jun 28, 2026
robfrank added a commit that referenced this pull request Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

algo.leiden() relTypes parameter produces singleton communities regardless of separator format

1 participant