Skip to content

#4210 fix: [cypher] MERGE+UNWIND crash on single-quote property value - #4237

Merged
robfrank merged 2 commits into
mainfrom
fix/4210-merge-unwind-single-quote-crash
May 14, 2026
Merged

robfrank merged 2 commits into
mainfrom
fix/4210-merge-unwind-single-quote-crash

Conversation

@robfrank

Copy link
Copy Markdown
Collaborator

Summary

  • Fixes [CYPHER] Weird -> Range [1, 0) out of bounds for length 1 error #4210. MergeStep.matchesProperties and setProperties stripped surrounding quotes from string property values with substring(1, len-1) and no length guard, so a value equal to a single ' (or ") crashed with StringIndexOutOfBoundsException: Range [1, 0) out of bounds for length 1.
  • The stripping is also dead: literals are already unquoted by LiteralExpression.getValue() (parsed via CypherExpressionBuilder.tryParseLiteral, which has its own length >= 2 guard), and evaluateProperties resolves expressions/parameters to plain Java values before either method runs. The block additionally would silently corrupt genuine values that happen to start and end with a quote (e.g. 'wrapped' stored as wrapped).
  • Removed the stripping blocks from both methods.

Test plan

  • New Issue4210MergeUnwindSingleQuoteTest reproduces the original UNWIND $batch ... MERGE (n:NER {...}) crash with a single-quote property value, plus value-fidelity for quote-wrapped strings; both pass.
  • All 54 MERGE-related Cypher tests pass.
  • Full Cypher/Issue test suite (6112 tests) passes with no new failures.

MergeStep.matchesProperties() and setProperties() stripped surrounding
quotes from string property values via substring(1, len-1), with no
length guard. A property value equal to the single character ' (or ")
satisfied both startsWith and endsWith and triggered substring(1, 0),
throwing StringIndexOutOfBoundsException ("Range [1, 0) out of bounds
for length 1").

The stripping was also dead: by the time these methods run,
evaluateProperties has already resolved literals (LiteralExpression
returns unquoted values, CypherExpressionBuilder.tryParseLiteral has a
length >= 2 guard) and expressions/parameters to plain Java objects.
Beyond the crash, the code would silently corrupt any genuine value
that happened to start and end with a quote (e.g. "'wrapped'" stored
as "wrapped").

Removed the stripping blocks from both methods. Added
Issue4210MergeUnwindSingleQuoteTest covering the crash case, repeated
ON MATCH execution, and value-fidelity for quote-wrapped strings.
@claude

claude Bot commented May 14, 2026

Copy link
Copy Markdown

Code Review

Overview

This PR fixes a StringIndexOutOfBoundsException in MergeStep when a Cypher property value is a single ' (or ") character. The root cause was dead stripping code in matchesProperties and setProperties that tried to unquote string values that were already unquoted by the time they arrived. The fix is a clean deletion of that dead code.


Correctness - Looks Good

The root cause analysis is accurate:

  • evaluateProperties resolves all expressions and parameters to plain Java values before either method is called.
  • LiteralExpression.getValue() (via CypherExpressionBuilder.tryParseLiteral) already strips quotes with its own length >= 2 guard.
  • The removed code was therefore double-unquoting (which never triggered on inline literals because they arrive unquoted) and crashing on single-char quote values (substring(1, 0) is out of bounds).
  • The stripping also silently corrupted legitimate values like 'wrapped' - storing wrapped instead.

Removing both blocks is the correct fix.


Code Quality

  • matchesProperties correctly promotes expectedValue to final now - good alignment with project style.
  • setProperties drops the curly braces on the single-statement for-loop, matching the CLAUDE.md guideline ("if statements with only one child sub-statement don't require a curly brace open/close").
  • No stray System.out calls introduced.

Test Coverage

The regression test covers the important cases:

  • Single ' as a property value (the original crash)
  • UNWIND $batch ... MERGE pattern (the exact scenario from the issue)
  • ON CREATE vs ON MATCH paths both exercised
  • Quote-wrapped strings ('wrapped') to verify value fidelity
  • Partial-quote strings (it's) to verify those pass through untouched

Two minor issues in the test file:

1. Unclosed ResultSet in mergeWithQuotePropertyPreservesExactValue

final ResultSet rs = database.query("opencypher", "MATCH (n:Token) RETURN n.value AS val");
assertThat(rs.hasNext()).isTrue();
assertThat(rs.next().<String>getProperty("val")).isEqualTo("'");
// rs is never closed - resource leak

rs.close() should be called after assertions, or the query wrapped in a try-with-resources. The first test correctly calls .close() on the inline command result.

2. Multi-line class Javadoc

The class-level /** ... */ comment spans multiple lines. CLAUDE.md says "Never write multi-paragraph docstrings or multi-line comment blocks - one short line max." A single-line // Regression test for issue #4210. would be more consistent with project guidelines.


Summary

Area Assessment
Fix correctness Correct - dead code removed, both crash and data-corruption paths addressed
Code style Consistent with project conventions
Test coverage Good - covers the crash case, ON CREATE/MATCH paths, and value fidelity
Resource management Minor: ResultSet not closed in one test method
Comments Minor: multi-line class Javadoc violates CLAUDE.md guideline

The core fix is solid. The two test-file issues above are minor but worth addressing before merge.

@codacy-production

codacy-production Bot commented May 14, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

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

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

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (8bacfb9) 127073 93641 73.69%
Head commit (a46ec56) 158736 (+31663) 105101 (+11460) 66.21% (-7.48%)

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 (#4237) 3 3 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.

@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 resolves GitHub issue #4210 by removing logic in MergeStep.java that incorrectly stripped quotes from string property values, which could lead to StringIndexOutOfBoundsException. A new regression test suite, Issue4210MergeUnwindSingleQuoteTest, was added to verify the fix. Review feedback suggests further improving Cypher compliance by allowing null property matches in matchesProperties and recommends using try-with-resources in the test code to ensure ResultSet resources are properly managed.

else if (strValue.startsWith("\"") && strValue.endsWith("\""))
expectedValue = strValue.substring(1, strValue.length() - 1);
}
final Object expectedValue = entry.getValue();

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

While cleaning up this method, it's worth noting that the actualValue == null check (on line 912 in the context) prevents MERGE from matching properties that are explicitly null or missing. In Cypher, MERGE should match when both the pattern and the document have a null value for a property. Since valuesEqual already handles null comparisons correctly, this check is likely incorrect and could be removed to improve Cypher compliance.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Out of scope for this PR. The reported issue is the substring crash; removing the early actualValue == null check changes MERGE's null-matching semantics (whether a missing/null property in the document satisfies a pattern that supplies a null/missing key), which is a separate behavioural concern and would need its own TCK-coverage analysis and tests. Leaving as-is for this fix.

Comment on lines +99 to +105
final ResultSet rs = database.command("opencypher", query, params);
int count = 0;
while (rs.hasNext()) {
rs.next();
count++;
}
assertThat(count).isEqualTo(4);

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

The ResultSet should be closed to ensure that database resources are released. Using try-with-resources is the recommended approach.

      try (ResultSet rs = database.command("opencypher", query, params)) {
        int count = 0;
        while (rs.hasNext()) {
          rs.next();
          count++;
        }
        assertThat(count).isEqualTo(4);
      }

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in a46ec56 - all three ResultSet sites wrapped in try-with-resources.

Comment on lines +110 to +117
final ResultSet rs = database.command("opencypher", query, params);
int count = 0;
while (rs.hasNext()) {
final var row = rs.next();
assertThat(row.<Boolean>getProperty("created")).isFalse();
count++;
}
assertThat(count).isEqualTo(4);

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

The ResultSet should be closed to ensure that database resources are released. Using try-with-resources is the recommended approach.

      try (ResultSet rs = database.command("opencypher", query, params)) {
        int count = 0;
        while (rs.hasNext()) {
          final var row = rs.next();
          assertThat(row.<Boolean>getProperty("created")).isFalse();
          count++;
        }
        assertThat(count).isEqualTo(4);
      }

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in a46ec56.

Comment on lines +138 to +140
final ResultSet rs = database.query("opencypher", "MATCH (n:Token) RETURN n.value AS val");
assertThat(rs.hasNext()).isTrue();
assertThat(rs.next().<String>getProperty("val")).isEqualTo("'");

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

The ResultSet should be closed to ensure that database resources are released. Using try-with-resources is the recommended approach.

    try (ResultSet rs = database.query("opencypher", "MATCH (n:Token) RETURN n.value AS val")) {
      assertThat(rs.hasNext()).isTrue();
      assertThat(rs.next().<String>getProperty("val")).isEqualTo("'");
    }

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in a46ec56.

@codecov

codecov Bot commented May 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 64.64%. Comparing base (8bacfb9) to head (a46ec56).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #4237   +/-   ##
=======================================
  Coverage   64.63%   64.64%           
=======================================
  Files        1644     1644           
  Lines      127073   127058   -15     
  Branches    27217    27211    -6     
=======================================
+ Hits        82136    82139    +3     
+ Misses      33460    33448   -12     
+ Partials    11477    11471    -6     

☔ 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.

ResultSet is AutoCloseable; wrap the three open() sites in
try-with-resources to release database resources deterministically.
@robfrank

Copy link
Copy Markdown
Collaborator Author

Addressing the two test-file points from the review:

  1. Unclosed ResultSet - fixed in a46ec56; all three ResultSet open sites in the test are now wrapped in try-with-resources.

  2. Multi-line class Javadoc - keeping as-is. The pattern (Regression test for GitHub issue #NNNN. line + <p> + behavioural description) is the established convention for issue-regression tests across the engine module (Issue4226MergeBoundAnchorTest, Issue4213OptionalMatchNullEndpointMergeTest, Issue4089MergeWithUniqueHashIndexTest, etc.). Shortening this single test would just create an outlier.

@claude

claude Bot commented May 14, 2026

Copy link
Copy Markdown

Code Review

Overview

This PR removes genuinely dead and crash-prone stripping code from MergeStep.matchesProperties and setProperties. The fix is correct and well-analyzed.


Correctness - Confirmed

The root cause analysis in the PR description is accurate:

  • Via the ANTLR path, inline string literals ('hello') become LiteralExpression objects; LiteralExpression.getValue() strips quotes via tryParseLiteral (with a length >= 2 guard at line 2624 of CypherExpressionBuilder). The parseMapProperties method then stores the already-unquoted Java value directly via ((LiteralExpression) expr).getValue() (line 2548-2549).
  • Via the parameter path (UNWIND $batch ... MERGE), values come from context.getInputParameters() as plain Java objects and are returned as-is from evaluateProperties.
  • In both cases, string values arriving at matchesProperties/setProperties are plain Java Strings with no surrounding quote characters - unless the Java String itself happens to start and end with a quote (e.g., "'" or "'hello'" passed as a parameter value). The old stripping code was incorrectly treating those as Cypher literals to unquote, causing:
    • Crash with StringIndexOutOfBoundsException for "'" (single-char quote: substring(1, 0) is out of bounds)
    • Silent data corruption for "'hello'" (stored as hello instead of 'hello')

Removing both blocks is the correct fix.


Code Style - Consistent

  • matchesProperties correctly promotes expectedValue to final - aligns with project style.
  • setProperties removes curly braces on the single-statement for-loop, matching the CLAUDE.md guideline.
  • No stray System.out calls.

Test Coverage

Correction to prior review: Both test methods correctly use try-with-resources for ResultSet. The mergeWithQuotePropertyPreservesExactValue method uses try (final ResultSet rs = database.query(...)), so there is no resource leak.

The test scenarios are well-chosen:

  • Single ' crash case (original bug)
  • ON CREATE vs ON MATCH paths exercised
  • 'wrapped' value-fidelity check (data corruption case)
  • Partial-quote string (it's)

One gap worth addressing: The removed code handled both single-quote and double-quote stripping symmetrically. A " (double-quote character) passed as a parameter value would have triggered the same StringIndexOutOfBoundsException as '. Adding a test entry with identity: "\"" (or "\"wrapped\"") would complete the coverage.


Minor Style Issue

The class-level /** ... */ Javadoc in Issue4210MergeUnwindSingleQuoteTest.java spans multiple lines with a paragraph. CLAUDE.md states "Never write multi-paragraph docstrings or multi-line comment blocks - one short line max." A single-line comment or no class-level comment at all would be more consistent.


Summary

Area Assessment
Fix correctness Correct - dead code removed, crash and data-corruption paths both addressed
Code style Consistent with project conventions
Test coverage Good; add a double-quote single-char case to complete symmetry
Resource management Correct - both ResultSets use try-with-resources
Comments Minor: multi-line class Javadoc violates CLAUDE.md guideline

The core fix is solid. The double-quote test gap and style nit are minor but worth addressing before merge.

@robfrank
robfrank merged commit 42bb25f into main May 14, 2026
34 of 37 checks passed
@robfrank
robfrank deleted the fix/4210-merge-unwind-single-quote-crash branch May 14, 2026 21:11
tae898 pushed a commit to humemai/arcadedb-embedded-python that referenced this pull request Jun 28, 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.

[CYPHER] Weird -> Range [1, 0) out of bounds for length 1 error

1 participant