GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(#6060): add apoc.do.when, apoc.refactor.mergeNodes, apoc.refactor.cloneNodesWithRelationships by robfrank · Pull Request #6071 · ArcadeData/arcadedb

Conversation

@robfrank

@robfrank robfrank commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator

What does this PR do?

Adds the 3 remaining APOC-compatible refactor/control-flow procedures, following the existing merge.node/merge.relationship CypherProcedure pattern (com.arcadedb.query.opencypher.procedures.merge):

  • apoc.do.when(condition, ifQuery, elseQuery, params) YIELD value - runs ifQuery when condition is true, elseQuery otherwise (both Cypher query strings), with params bound as named parameters. Dispatches to database.query() or database.command() based on QueryEngine.analyze(query).isIdempotent(), so both read and write sub-queries work without the caller having to say which. Each result row of the sub-query is yielded as a map under value.
  • apoc.refactor.mergeNodes(nodes, config) YIELD node - merges a list of nodes into the first one (the survivor). config.properties controls how a property present on both the survivor and an absorbed node is resolved: "overwrite" (default, absorbed value wins), "discard" (survivor's value kept), or "combine" (both kept as a list). Every incoming/outgoing edge of the absorbed nodes is rewired onto the survivor via MutableEdge.set("@out"/"@in", ...) (which the engine's GraphEngine.moveEdge already handles correctly) - an edge that connected two nodes both being merged naturally becomes a self-relationship on the survivor. The absorbed nodes are then deleted.
  • apoc.refactor.cloneNodesWithRelationships(nodes, config) YIELD input, output, error - clones each given node (new vertex, same type/properties, minus an optional config.skipProperties list) together with every relationship touching it in either direction. A relationship whose other endpoint is also being cloned reconnects the two clones rather than the originals; a relationship to a node outside the given list reconnects the clone to that same original node. A per-node clone failure surfaces via the error yield field instead of aborting the whole call. The source nodes and their relationships are left untouched.

All three are registered under both their plain and apoc.-prefixed names in CypherProcedureRegistry.

Motivation

A customer migrating from Neo4j reported these among the APOC functions their query catalogue depends on (see #6059 for the full list; the other 7, simpler ones already shipped via #6058). These 3 were split out because they need deliberate semantics decisions matching real APOC config-flag behavior (property-conflict policy, self-relationship handling, clone-to-clone rewiring), plus dedicated regression tests per node/edge-count and property-conflict scenario, rather than being safe one-file/low-risk additions.

Related issues

Closes #6060. Related to #6059 (tracking issue) and #6058 (the 7 simpler APOC functions already shipped).

Additional Notes

Testing (TDD, tests written first): DoWhenTest, RefactorMergeNodesTest, RefactorCloneNodesWithRelationshipsTest - 19 tests total, all passing. Also re-ran the full com.arcadedb.query.opencypher.procedures package plus the registry/arity tests (CypherProcedureRegistryTest, CypherBuiltInFunctionsTest, ProcedureRegistryTest, ProcedureArityIssue5627Test) with no regressions.

One general-purpose finding surfaced while testing, worth flagging for reviewers: a write CypherProcedure (this includes the pre-existing merge.node/merge.relationship) is not auto-committed by the engine the way built-in write clauses like SET/CREATE/DELETE are - CallStep.executeProcedure runs lazily on the first ResultSet pull with no begin()/commit() wrapping, unlike those steps. A caller invoking a write procedure via CALL therefore needs its own explicit transaction around the call and its full consumption. Documented in RefactorMergeNodesTest's class Javadoc since it isn't obvious and affects every existing write procedure, not just the new ones.

Checklist

  • I have run the build using mvn clean package command (ran mvn -pl engine -am compile plus targeted test runs; full mvn verify not run for time)
  • My unit tests cover both failure and success scenarios

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@robfrank
feat(#6060): add apoc.do.when, apoc.refactor.mergeNodes, apoc.refacto…
ee4451e
…r.cloneNodesWithRelationships

Adds the 3 remaining APOC-compatible control-flow/refactor procedures split out
from #6059, following the existing merge.node/merge.relationship CypherProcedure
pattern.
@mergify

mergify Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@codacy-production

codacy-production Bot commented Aug 11, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 83 complexity

Metric Results
Complexity 83

View in Codacy

🟢 Coverage 92.82% diff coverage · -6.49% coverage variation

Metric Results
Coverage variation ✅ -6.49% coverage variation
Diff coverage ✅ 92.82% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (377035d) 154212 120461 78.11%
Head commit (6de3a2e) 187044 (+32832) 133974 (+13513) 71.63% (-6.49%)

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 (#6071) 195 181 92.82%

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.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review: apoc.do.when / apoc.refactor.mergeNodes / apoc.refactor.cloneNodesWithRelationships

Nice, well-scoped PR that follows the existing CypherProcedure pattern closely (merge.node/merge.relationship), and it's good to see the write-procedure auto-commit gotcha documented in the test Javadoc for future implementers. I verified that MutableEdge.set("@out"/"@in", ...) does correctly go through GraphEngine.moveEdge (it re-points the edge list on both endpoints, not just the edge record), so the core rewiring approach in RefactorMergeNodes is sound. A few things worth addressing before merge:

Potential bugs

  1. RefactorMergeNodes.execute doesn't guard against a duplicate non-survivor entry in nodes. The only duplicate check is absorbed.getIdentity().equals(survivorMutable.getIdentity()) (skips a duplicate of the first node). If the same non-survivor node appears twice, e.g. apoc.refactor.mergeNodes([a, b, b], {}), the second occurrence of b is processed after b has already been merged and deleted in the previous iteration. rewireEdges/absorbed.modify().delete() then operate on an already-deleted record, which will surface as a raw RecordNotFoundException (or similar) instead of a clean CommandSemanticException like the existing "fewer than two nodes" validation. Worth either de-duplicating nodes by identity up front, or explicitly validating for duplicates and raising the same kind of semantic error used elsewhere in this class.

  2. DoWhen.execute doesn't close the sub-query ResultSet on the error path. It's drained manually (while (resultSet.hasNext()) ... resultSet.close();) instead of the try-with-resources pattern already used one package over in MergeNode.findMatchingNode. If row.toMap() (or the iteration itself) throws partway through, resultSet is never closed. Since this procedure can dispatch to database.command(...) for write sub-queries, that's a resource leak on a path that's specifically about running writes.

  3. RefactorCloneNodesWithRelationships's per-item resilience only covers node cloning, not edge cloning. The class doc/PR description says "a per-node clone failure surfaces via the error yield field instead of aborting the whole call", but that try/catch only wraps the node-creation loop. The edge-rewiring loop (cloneEdge) has no try/catch, so a failure there (e.g. a unique-index conflict on the new edge, or a schema constraint) throws out of execute() uncaught, and the caller gets nothing at all, not even the yield rows for nodes that cloned successfully. Worth deciding whether edge failures should also be captured, or documenting explicitly that only the node-creation step is best-effort.

Code quality

  1. Import ordering regression in CypherProcedureRegistry.java. The new imports break the existing alphabetical ordering:

    import com.arcadedb.query.opencypher.procedures.path.PathExpand;
    import com.arcadedb.query.opencypher.procedures.path.PathExpandConfig;
    import com.arcadedb.query.opencypher.procedures.refactor.RefactorCloneNodesWithRelationships;
    import com.arcadedb.query.opencypher.procedures.refactor.RefactorMergeNodes;
    import com.arcadedb.query.opencypher.procedures.path.PathSpanningTree;
    ...

    refactor.* is sandwiched in the middle of the path.* block. No checkstyle enforcement in this repo so it won't break the build, but it's inconsistent with the rest of the (alphabetized) file.

  2. extractVertices(Object) is duplicated verbatim between RefactorMergeNodes and RefactorCloneNodesWithRelationships. Same for the general "extract a Map config, throw IllegalArgumentException otherwise" pattern. Given both live under the same refactor package, a small shared helper (or a common base in procedures) would avoid the copy-paste and keep the two in sync if the error wording changes.

  3. Inconsistent config-type validation between the two refactor procedures. RefactorMergeNodes.extractMap throws IllegalArgumentException if config is a non-null, non-Map value. RefactorCloneNodesWithRelationships.extractSkipProperties silently treats any non-Map config as "no skip properties" with no error. Minor, but worth aligning since they're siblings in the same PR.

Test coverage

All three procedures are tested for the happy path and basic error cases, and the transaction-boundary gotcha is called out clearly. A couple of gaps worth adding given the bug above:

  • A mergeNodes test with a duplicate node in the list (covers finding build support #1), and one with 3+ nodes to exercise the multi-way merge/edge-rewiring path (existing tests only cover exactly 2 nodes).
  • A cloneNodesWithRelationships test where the config argument isn't a map ({} is tested, but not e.g. null or a non-map value), to confirm the intended behavior for finding Bump slf4j-simple.version from 1.7.31 to 1.7.32 #3/Bump metrics.version from 4.2.2 to 4.2.3 #6.

Performance / Security

  • No concerns on performance; the merge/clone loops are O(V+E) and reuse existing engine primitives (moveEdge via MutableEdge.set) rather than reimplementing edge bookkeeping.
  • apoc.do.when executes caller-supplied Cypher text via database.query/database.command, which is inherent to what the procedure needs to do (mirrors real APOC apoc.do.when), not a defect introduced here. Just flagging for reviewers so it's a conscious call that this dynamic-query surface is now reachable from Cypher CALL the same way it would be for merge.node/merge.relationship today.

Overall this is solid, well-tested work; the main thing I'd want resolved before merge is #1 (duplicate-node crash) since it's a real, easily-triggered edge case, and #3 since it contradicts the documented resilience guarantee.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@robfrank
fix(#6060): address code review - duplicate-node crash, resource leak…
d65efe4
…, edge-clone resilience

- RefactorMergeNodes: deduplicate nodes by identity before merging, fixing an
  uncaught RecordNotFoundException when the same non-survivor node appears
  twice in the list (e.g. mergeNodes([a, b, b], {}))
- DoWhen: run the sub-query ResultSet through try-with-resources so it's
  closed on the exception path, not just after a clean drain
- RefactorCloneNodesWithRelationships: make edge cloning best-effort like
  node cloning already was, so one bad edge no longer discards the yield
  rows already produced for successfully cloned nodes; align its config
  validation with RefactorMergeNodes (throw on a non-map config instead of
  silently ignoring it)
- Extract the nodes/config argument parsing shared by both refactor
  procedures into RefactorProcedureArgs
- Fix CypherProcedureRegistry import ordering (refactor.* was sandwiched
  inside the path.* block)
- Add regression tests for the duplicate-node case, a 3-way merge exercising
  multi-node edge rewiring, and a non-map config argument
@robfrank

robfrank commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in d65efe4:

  1. Duplicate-node crash - confirmed: mergeNodes([a, b, b], {}) re-processed the second b after it was already deleted. Fixed by deduplicating nodes by identity up front (RefactorMergeNodes.deduplicateByIdentity) instead of the narrower survivor-only check. [a, a] now collapses to one node and hits the existing "at least two nodes" validation.
  2. DoWhen resource leak - confirmed, no try-with-resources on the exception path. Switched to try-with-resources around the sub-query ResultSet, matching MergeNode.findMatchingNode.
  3. Edge-clone failures uncaught in cloneNodesWithRelationships - confirmed, cloneEdge wasn't wrapped. Now catches per-edge and logs a warning instead of losing every already-produced node row; class Javadoc now states the best-effort scope covers both phases.
  4. Fixed the import ordering regression.
  5. Extracted the identical extractVertices/config-map parsing into RefactorProcedureArgs, shared by both refactor procedures.
  6. Aligned cloneNodesWithRelationships's config validation with mergeNodes - a non-map, non-null config now throws in both instead of being silently ignored in one.

Added regression tests for the duplicate-node case, a 3-way merge (exercises multi-node edge rewiring, not just the 2-node path), and a non-map config argument. Full com.arcadedb.query.opencypher.procedures package plus the registry/arity tests still green.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review

Reviewed the diff (CypherProcedureRegistry, DoWhen, RefactorMergeNodes, RefactorCloneNodesWithRelationships, RefactorProcedureArgs, plus the three test classes). Overall this is a clean, well-scoped addition that follows the existing CypherProcedure/merge.node pattern closely, and the second commit already addressed real issues found in self-review (duplicate-node crash, ResultSet leak, edge-clone resilience). A few notes for further consideration:

Correctness

  • RefactorMergeNodes.rewireEdges/RefactorCloneNodesWithRelationships.cloneEdge rely on MutableEdge.set("@out"/"@in", ...) triggering GraphEngine.moveEdge immediately (confirmed in MutableEdge.java), so the lack of an explicit .save() on the edge after rewiring is correct, not an oversight.
  • deduplicateByIdentity in RefactorMergeNodes is a good fix — nice inline Javadoc explaining the RecordNotFoundException it prevents.
  • DoWhen.extractBoolean throws if condition isn't a literal Boolean (e.g. rejects a truthy non-boolean value). That's a reasonable, explicit design choice given Cypher boolean expressions evaluate to Boolean, but it does diverge slightly from APOC's more permissive coercion — worth a one-line note in the class Javadoc if that's intentional/final, since a caller migrating literal APOC queries could hit this.

Test coverage gaps

  • RefactorCloneNodesWithRelationshipsTest has no test for config.skipProperties, even though it's documented behavior and has its own extraction helper (extractSkipProperties). Worth a small test asserting an excluded property is absent from the clone.
  • The second commit's message says edge cloning was made "best-effort ... so one bad edge no longer discards the yield rows already produced," but there's no regression test exercising that path (e.g. forcing a unique-index conflict on the cloned edge and asserting the node yield rows still come back). Same for the per-node clone failure path — only the success case (error == null) is tested, not a case producing a populated error field.
  • nonMapConfigThrows (clone test) asserts hasCauseInstanceOf(IllegalArgumentException.class), consistent with how CypherProcedure exceptions propagate — fine, just noting the pattern differs from RefactorMergeNodesTest's CommandSemanticException assertions, since these come from different validation layers (arg-shape checks vs. semantic checks). Not a bug, just worth being consistent about which exception type new argument-validation helpers throw across the three procedures for a more predictable API surface.

Minor

  • DoWhen.extractString/elseQuery handling calls .toString() on non-null, non-String args without validating type, unlike extractMap's explicit instanceof check. Minor inconsistency — low risk since these normally come from string literals in the CALL, but a stray non-string argument silently gets stringified rather than raising the same clear IllegalArgumentException the other extractors give.
  • Good catch already documented in the PR description: CypherProcedure writes aren't auto-committed by the engine, and the tests correctly wrap every mutating CALL in an explicit begin()/commit(). Worth eventually filing/linking a follow-up issue for making write procedures auto-commit like SET/CREATE/DELETE, since it's an easy footgun for future callers of any write procedure (not just these three).

Style/consistency

  • All three procedures and RefactorProcedureArgs follow existing conventions well (no fully-qualified names, final on locals/params, single-statement if without braces, Apache 2.0 header, no new dependencies).

Nice test-first coverage overall (dedup, 3-way merge with multi-node edge rewiring, self-relationship formation, property policies, non-map config) — the gaps above are additive polish, not blockers.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@robfrank
fix(#6060): address second review pass - strict string args, resilien…
00c8d45
…ce test coverage

- DoWhen: extractString now validates the argument is actually a String
  (ifQuery/elseQuery) instead of silently stringifying anything non-null;
  documented why the condition arg is strictly Boolean (diverges from real
  APOC's coercion, deliberately, so a wrong-typed caller mistake surfaces
  instead of silently picking a branch)
- RefactorCloneNodesWithRelationships: corrected the best-effort resilience
  doc/comments - a UNIQUE index violation is NOT something the per-item
  try/catch can protect against, since ArcadeDB defers uniqueness checking
  to commit time; a mandatory-property violation is the actual synchronous
  failure mode this catches (validated at save() time)
- Added regression tests: config.skipProperties excludes a property from
  the clone; a node-clone failure (mandatory-property violation) produces
  a populated error field without losing the other node's row; an
  edge-clone failure is skipped without losing the node's own yield row

Filed #6073 for the pre-existing gap this surfaced: write CypherProcedures
(this includes merge.node/merge.relationship, not just the new ones) aren't
auto-committed by the engine the way SET/CREATE/DELETE are.
@robfrank

robfrank commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in 00c8d45:

  • DoWhen.extractString - confirmed, ifQuery/elseQuery now require an actual String, matching extractMap's rigor instead of silently .toString()-ing anything non-null.

  • extractBoolean strictness - documented in the class Javadoc: intentional, diverges from real APOC's coercion so a wrong-typed caller mistake surfaces rather than silently picking a branch.

  • Test coverage gaps - added skipPropertiesExcludesGivenPropertyFromTheClone, plus two regression tests forcing an actual synchronous failure inside the try/catch blocks: nodeCloneFailureProducesPopulatedErrorFieldWithoutLosingOtherRows and edgeCloneFailureIsSkippedWithoutLosingTheNodeYieldRow.

    Writing those surfaced a real problem with my own commit message and Javadoc from the first round: I'd described the resilience as protecting against "a unique-index conflict on the new edge," and it doesn't. ArcadeDB defers UNIQUE index checking to commit time (TransactionIndexContext.checkUniqueIndexKeys runs in commit1stPhase), so a duplicate-key violation escapes the procedure's own try/catch entirely and fails the whole transaction - confirmed by writing that exact test first and watching it fail at database.commit(), not inside execute(). A MANDATORY property constraint, by contrast, is validated synchronously in LocalDatabase.createRecordNoLock before the record is ever written, so that's what the tests actually use, and I corrected the Javadoc/inline comments in RefactorCloneNodesWithRelationships to say so.

  • Exception-type consistency (CommandSemanticException vs IllegalArgumentException) - checked against MergeNode/MergeRelationship: type/shape validation (is this arg a List/Map/Vertex) is already fully consistent everywhere, old and new code, using IllegalArgumentException. The apparent inconsistency is that MergeNode's own "at least one label required" business-rule check also uses IllegalArgumentException rather than CommandSemanticException, while mine uses CommandSemanticException for the analogous "at least two nodes" check. That's MergeNode predating and not matching Procedure.checkArity's own documented rationale (a caller mistake should be HTTP 400 via CommandSemanticException, not an internal-looking 500) - not something this PR should quietly regress to match. Leaving as-is; retrofitting MergeNode/MergeRelationship is a separate, pre-existing cleanup outside this PR's scope.

  • Filed Write CypherProcedures aren't auto-committed like SET/CREATE/DELETE #6073 for the auto-commit gap, since it's real and affects every existing write procedure, not just these three.

Full com.arcadedb.query.opencypher.procedures package plus registry/arity/built-in-functions tests: 495 tests, all green.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review: apoc.do.when, apoc.refactor.mergeNodes, apoc.refactor.cloneNodesWithRelationships

Overall this is well-structured work: it follows the existing CypherProcedure / merge.node pattern, the javadoc is thorough about non-obvious semantics (self-relationships, best-effort cloning, the write-procedure transaction caveat), and the commit history shows two solid self-review passes already fixed a real crash (duplicate-node RecordNotFoundException), a resource leak, and tightened arg validation. A few things worth a look before merge.

Possible bug: duplicate nodes in cloneNodesWithRelationships silently orphan a clone

RefactorMergeNodes explicitly deduplicates its nodes list by identity (with a good comment explaining why: a repeated node would otherwise crash on absorbed.modify()). RefactorCloneNodesWithRelationships does not apply the same treatment, and it has its own failure mode for the same input shape.

In RefactorCloneNodesWithRelationships.execute(), cloneOf is a Map<RID, Vertex> keyed by the original node's identity. If nodes contains the same vertex twice (e.g. apoc.refactor.cloneNodesWithRelationships([a, a], {}), plausible if a caller builds the list from collect() over an overlapping match), the node-cloning loop creates two separate clones but cloneOf.put(original.getIdentity(), clone) overwrites the first mapping with the second. Both clones are reported as successful rows (error == null), but the edge-cloning phase only ever looks up cloneOf.get(a.getIdentity()), which now resolves to the second clone. Because processedEdges dedupes by the original edge's identity (not per output clone), the first clone never receives any of its relationships, while still being yielded with error = null as if it succeeded. That silently produces a node with no edges, which is worse than a visible error since nothing in the yield tells the caller which output is the "real" one.

Suggest either deduplicating nodes up front the same way RefactorMergeNodes does (probably belongs in the shared RefactorProcedureArgs, since both refactor procedures take a nodes list), or explicitly documenting/handling the duplicate case if it should be allowed to produce multiple independent clones (in which case cloneOf would need to key by list index/clone rather than by original RID, and the edge phase would need to run per node-clone pair rather than per distinct original identity).

Test coverage gaps

A few negative-path branches that exist in the code aren't exercised by the new tests:

  • RefactorMergeNodes: an unknown config.properties value (e.g. {properties: 'bogus'}) should throw CommandSemanticException per extractPropertiesPolicy, but there's no test for it. (Also note the same check is duplicated as a default case inside mergeProperties's switch; that branch is unreachable since extractPropertiesPolicy already validates before mergeProperties is ever called, worth removing as dead code or leaving a short comment noting it's a defensive fallback.)
  • RefactorProcedureArgs.extractVertices/extractConfig: no test drives a non-list nodes argument or a list containing a non-vertex element, for either refactor procedure.
  • DoWhen: only the arity-mismatch negative path is tested. extractBoolean/extractString/extractMap's IllegalArgumentException paths (non-boolean condition, non-string ifQuery, non-map params) aren't covered, even though the class javadoc calls out the strict-boolean behavior as a deliberate design decision worth pinning down with a test.
  • combine policy is only tested for a 2-node merge; the 3-way merge test uses discard, so the list-accumulation-across-multiple-absorbed-nodes path in mergeProperties's combine branch (combined.addAll(list) on an already-combined survivor value) isn't directly exercised, even though it looks correct on inspection.

Minor / design notes

  • DoWhen.extractString(args[2], "elseQuery") is only called when args[2] != null (null maps to ""), but ifQuery (args[1]) is validated unconditionally even on the branch where it won't run (i.e. condition == false still requires ifQuery to be a well-typed String). That's a minor asymmetry versus real APOC and against your own leniency for elseQuery; probably fine as "fail fast on a malformed call regardless of which branch is taken," but worth a one-line javadoc note since it's not obvious from the code alone.
  • DoWhen (and by extension any caller of apoc.do.when) executes caller-provided Cypher strings via database.query/database.command. That mirrors real APOC's apoc.do.when/apoc.cypher.doIt behavior so it's not a new class of risk, but since it's a new "run arbitrary dynamic Cypher" surface in ArcadeDB, it's worth a docs callout that ifQuery/elseQuery must never be built by string-concatenating untrusted input (the usual dynamic-query injection risk), the same caveat that applies to raw SQL dynamic-command features elsewhere in the engine.
  • Good call documenting that write CypherProcedures aren't auto-committed (and filing Write CypherProcedures aren't auto-committed like SET/CREATE/DELETE #6073 for the underlying gap) rather than working around it locally in this PR, that keeps the fix scoped.

Nit

RefactorMergeNodes.mergeProperties calls survivor.getPropertyNames().contains(propertyName) inside the loop; since getPropertyNames() returns the live map.keySet() (not a fresh copy) this is cheap, just flagging in case a future edit changes that to something more expensive.

Nothing above blocks merging as-is if the duplicate-clone case is deemed out of scope for this PR (it's a pre-existing class of gap, similar in spirit to the one already fixed in RefactorMergeNodes), but I'd lean toward fixing or at least tracking it alongside #6073 given the sibling procedure already had to handle the identical input shape.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@robfrank
fix(#6060): address third review pass - shared dedup fixes an orphane…
6de3a2e
…d-clone bug

- Move node-list deduplication from RefactorMergeNodes into
  RefactorProcedureArgs.extractVertices, so both refactor procedures get it
  automatically. This fixes a real bug in RefactorCloneNodesWithRelationships:
  cloneNodesWithRelationships([a, a], {}) created two clones of 'a' but
  cloneOf (keyed by the original's identity) only kept the second mapping,
  so the edge phase wired every one of 'a's edges onto that second clone
  while the first - still yielded with error=null - silently got none
- Documented the unreachable default branch in mergeProperties's policy
  switch as a defensive fallback (extractPropertiesPolicy already validates
  before mergeProperties runs)
- DoWhen: documented that ifQuery is type-checked unconditionally regardless
  of which branch condition selects, and added a caveat that ifQuery/
  elseQuery run as Cypher with the caller's own privileges - same as real
  APOC's do.when/cypher.doIt, not a new risk, but worth calling out
- Added regression tests: the duplicate-node orphaned-clone case, an
  unknown properties policy, combine policy accumulating across a 3-way
  merge, DoWhen's non-boolean/non-string/non-map argument validation, and
  a new RefactorProcedureArgsTest unit-testing the shared arg parsing
  directly (non-list/non-vertex/non-map inputs, dedup order)
@robfrank

robfrank commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed in 6de3a2e:

  • Duplicate-node orphaned-clone bug - confirmed by tracing it exactly as described: cloneNodesWithRelationships([a, a], {}) produces two clones, the second cloneOf.put(a.getIdentity(), clone2) overwrites the first mapping, and processedEdges dedupes by the original edge's identity, so all of a's edges land on clone2 while clone1 - still yielded with error = null - gets none. Fixed by moving dedup from RefactorMergeNodes into RefactorProcedureArgs.extractVertices itself, so both refactor procedures get it automatically and can't drift apart on this again. Added duplicateNodeInTheListProducesOneCloneWithAllItsEdges reproducing the exact scenario from the review.
  • Test coverage gaps - added all four: unknown properties policy throws, combine policy accumulating across a 3-way merge (traced through the code by hand first to confirm ["x","y","z"] is actually correct, then the test locks it in), DoWhen's non-boolean/non-string/non-map argument paths, and a new RefactorProcedureArgsTest unit-testing the shared helper directly (non-list, non-vertex element, non-map, dedup order) rather than only through a full CALL.
  • Dead-code default branch - left in place per your suggested alternative, with a comment noting it's an unreachable defensive fallback rather than removing it, since extractPropertiesPolicy and mergeProperties are two separate methods that could drift apart under a future edit.
  • ifQuery validated even on the untaken branch - documented in the class Javadoc as intentional (fail the same way regardless of which branch runs).
  • Dynamic-Cypher-injection callout - added to the class Javadoc: same caveat as any other caller-supplied-command surface in the engine, not a new risk class, but worth stating explicitly since it's new to Cypher CALL.

Full com.arcadedb.query.opencypher.procedures package plus registry/arity/built-in-functions tests: 509 tests, all green.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review

Went through the diff (CypherProcedureRegistry, DoWhen, RefactorMergeNodes, RefactorCloneNodesWithRelationships, RefactorProcedureArgs, plus all 4 test files). Overall this is solid work — it clearly already went through several review/fix cycles (dedup crash, resource leak, best-effort resilience, orphaned-clone bug), and it shows: the edge cases I went looking for (self-loop absorbed nodes, multi-hop edge rewiring across a 3-way merge, duplicate nodes in the list, edge-to-external-node reconnection) are already handled correctly and covered by tests. I traced MutableEdge.set("@out"/"@in", ...) down into GraphEngine.moveEdge to confirm the "no explicit .save() needed after rewiring" claim in the PR description — checks out, moveEdge does a full disconnect/reconnect, not just a field mutation.

A few smaller points, none blocking:

1. RefactorCloneNodesWithRelationships.java:353 — results.add(row(original, null, e.getMessage())) uses e.getMessage(), which is null for exceptions raised without one (e.g. some NullPointerExceptions). That yields a row with both output and error as null, which looks like neither a clean success nor a diagnosable failure. Might be worth falling back to e.toString() when getMessage() is null, so the error field is always populated on a failure row.

2. RefactorCloneNodesWithRelationships.extractSkipProperties (line ~406) — silently coerces non-String items via item.toString() instead of rejecting them, which is a slightly different posture than the rest of this PR (DoWhen.extractString/extractBoolean and RefactorProcedureArgs.extractVertices all deliberately reject a wrong-typed argument rather than coerce it, per the class Javadoc rationale in DoWhen). Not a bug, just a minor inconsistency in strictness across the new code — a caller passing skipProperties: [123] gets {"123"} silently instead of an error surfacing the mistake.

3. Mixed-type merges in RefactorMergeNodes — nothing stops apoc.refactor.mergeNodes from merging nodes of different vertex types; the survivor's type is kept and absorbed properties are copied onto it regardless of the absorbed node's type. That's a reasonable default (and arguably matches real APOC's permissiveness), but it isn't mentioned in the class Javadoc and isn't covered by a test. Worth a one-line doc mention if the behavior is intentional, since it's the kind of thing a caller might reasonably expect to be rejected instead.

4. Auto-commit footgun, already flagged by the author — the PR description calls out that write CypherProcedures aren't auto-committed the way SET/CREATE/DELETE are, and that #6073 was filed to track it. Worth a distinct comment: this PR triples the number of write procedures affected by that gap (from 2 to 5). Given it's a real correctness trap (CALL apoc.refactor.mergeNodes(...) outside an explicit transaction silently no-ops instead of erroring), it might be worth linking #6073 directly in each new class's Javadoc (only RefactorMergeNodesTest's Javadoc mentions it today, and only in the test, not the production class), so anyone grepping the procedure source for how to call it safely sees the warning without having to find the test file.

Test coverage: good breadth — property-conflict policies (overwrite/discard/combine, including accumulation across a 3-way merge), self-relationship formation, duplicate-node handling, config.skipProperties, mandatory-property clone failures for both nodes and edges, and argument-type validation are all exercised. RefactorProcedureArgsTest unit-testing the shared helper directly (rather than only through a Cypher CALL) is a nice touch for isolating that logic.

Style/conventions: consistent with the existing merge.node/merge.relationship pattern, imports are used (no FQNs), final is used consistently, no stray System.out, license headers present, no new dependencies. Import ordering in CypherProcedureRegistry is correct per the commit history (this PR's own second commit fixed an ordering slip from the first).

No security or performance concerns beyond what's already flagged in the PR description (caller-supplied Cypher strings in do.when, documented as no more of a risk than any other command-string entry point).

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@codecov

codecov Bot commented Aug 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.66667% with 26 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.44%. Comparing base (377035d) to head (6de3a2e).
⚠️ Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
...cypher/procedures/refactor/RefactorMergeNodes.java 84.61% 7 Missing and 3 partials ⚠️
...db/query/opencypher/procedures/control/DoWhen.java 78.57% 4 Missing and 5 partials ⚠️
.../refactor/RefactorCloneNodesWithRelationships.java 90.76% 3 Missing and 3 partials ⚠️
...her/procedures/refactor/RefactorProcedureArgs.java 93.75% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6071      +/-   ##
==========================================
+ Coverage   69.33%   69.44%   +0.10%     
==========================================
  Files        1799     1811      +12     
  Lines      154212   154701     +489     
  Branches    32616    32720     +104     
==========================================
+ Hits       106930   107438     +508     
+ Misses      33790    33725      -65     
- Partials    13492    13538      +46     

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

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@robfrank
robfrank merged commit db55f94 into main Aug 12, 2026
32 of 33 checks passed

Uh oh!

There was an error while loading. Please reload this page.

@robfrank
robfrank deleted the feat/6060-add-apoc-compatible-refactor-control branch August 26, 2026 09:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Add APOC-compatible refactor/control-flow procedures: apoc.do.when, apoc.refactor.mergeNodes, apoc.refactor.cloneNodesWithRelationships

Uh oh!

There was an error while loading. Please reload this page.

1 participant

@robfrank
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.