Skip to content

fix(#6295, #6300, #6301, #6302): a weight belongs to its own edge, and the phase a call spends its time in is the one that has to be abortable - #6306

Merged
lvca merged 4 commits into
mainfrom
issue-6295-6300-6301-6302
Aug 17, 2026
Merged

lvca merged 4 commits into
mainfrom
issue-6295-6300-6301-6302

Conversation

@lvca

@lvca lvca commented Aug 17, 2026

Copy link
Copy Markdown
Member

Fixes #6295, #6300, #6301, #6302.

#6301 - an edge weight was attached to whatever neighbour sat at that index

AlgoSteinerTree.buildWeightedAdj paired weights with neighbours by iteration position. adj[i] was built
with the relTypes filter applied and in the backing store's order; tmpW was filled positionally from an
unfiltered getEdges(BOTH) walk in OLTP order. nbIdx was computed and then used only as a skip test, never as
the index to write at. That array is what Dijkstra runs on in step 1, so the tree itself changed, not only the
weight column.

Both reproductions from the issue are pinned as tests and both were verified red before the fix:

  • an excluded NOISE edge of weight 999 landed on an included ROAD edge → weight: 999.0, totalWeight: 1000.0
    for a tree that costs 2.0;
  • with a Graph Analytical View present the same query returned a 51.0 tree where OLTP returned 2.0. A view is meant
    to be a transparent accelerator, so this is the worst failure mode it has.

The fix removes the second traversal rather than repairing it. GraphData.weightedAdjacency(direction, weightProperty, relTypes) produces the neighbour list and its weights from one walk of the same edges - from
the view's columnar edge properties when it has them, from the edge records otherwise - so the pairing is correct
by construction and the two backings return the same multiset of (neighbour, weight) pairs. buildWeightedAdj is
deleted, and so is the old GraphData.edgeWeights.

The issue suggested reusing edgeWeights(...). That could not be taken as-is, and the reason is the interesting
part: getEdgeProperty returns null for DIRECTION.BOTH, which is the direction algo.steinerTree needs, and
getNeighborIds(i, BOTH, type) is a sorted merge of the OUT and IN slices, so no positional mapping to the
column store exists for it at all. weightedAdjacencyFromColumns walks one slice per (type, direction) instead,
each of which is positional, and concatenates them.

The same helper was broken for its two existing callers, and both are fixed with it:

  • algo.apsp with no relTypes filter on a view with edge properties produced an empty weight row against a
    non-empty neighbour row: an ArrayIndexOutOfBoundsException for a query that worked without the view. With
    several edge types it mismatched silently, because the adjacency is sorted across types while the weights were
    concatenated per type.
  • algo.bellmanford fell back to a unit weight for every edge whenever the graph was CSR-backed and the
    view had no column for the property - ignoring weightProperty entirely, and only when a view existed. Its edge
    list is now parallel primitive arrays rather than List<int[]> + List<Double>, which the O(V x E) relaxation
    reads up to V - 1 times.

One provider-contract change. GraphTraversalProvider.hasEdgeProperties() now means "the columns are
materialised and the positional mapping getEdgeProperty relies on is exact", and GraphAnalyticalView answers
false while a delta overlay is active: the columns are aligned with the base CSR's forward slots while
getNeighborIds serves the overlay's view of the node (deletions dropped, additions merged, list re-sorted), so
the n-th neighbour is not the n-th edge of the column store. SQLFunctionAstar, SQLFunctionBellmanFord and
algo.dijkstra.singleSource pair positionally too and gain the same protection: in that state they read the edge
records, which is slower and exact. Same "say unknown rather than guess" convention as countEdgesBetween and
getMeanEdgesPerConnectedPair.

#6295 - the phase a call spends its time in was outside every checkpoint

algo.hashgnn's MinHash reduction runs after the loop iterations drives, and costs
4 x embeddingDimension² operations per node - a bounded per-node figure multiplied by an unbounded node count.
Reproduced as the issue measured it: the deadline overshot by two orders of magnitude and the call returned.

The generalisable lesson, and the one applied here: #6216 and #6264 hunted knobs with no ceiling;
embeddingDimension HAS one (#6065), which is exactly why the lens walked past it. Ask "which loop over the node
count has no checkpoint", not "which knob has no cap".
That sweep also found the pre-loop initialisation of
algo.hashgnn, algo.fastrp and algo.graphsage, and algo.slpa's post-processing and its O(degree²)
mostFrequent. All now carry a checkpoint; the two-phase ones use a counter spanning both loops, because a
per-node check is too coarse on a wide embedding and a per-dimension clock read is too expensive on a narrow one.

#6302 - a guard belongs wherever the work is unbounded, not only where a knob multiplies it

algo.apsp makes the case alone: the #6263 budget's 64 MB floor admits n ≈ 2890, and 2890³ is ~2.4e10
Floyd-Warshall iterations during which Thread.interrupt(), arcadedb.command.timeout and client cancellation all
did nothing. The memory half of the guarantee was waving through a run the time half could not stop.

Taking the issue's "better framing" rather than its four-procedure list, all 68 procedures were swept with the
question "can one call of this run for minutes on an accepted input?". 22 are now abortable: apsp,
kShortestPaths, steinerTree, mst, bellmanford, betweenness, closeness, harmonic, eccentricity,
maxFlow, msa, knn, hierarchicalClustering, clique, allSimplePaths, kTruss, triangleCount,
localClusteringCoefficient, densestSubgraph, bipartiteMatching, voteRank, richClub.

Procedures making a single O(V + E) pass are deliberately left alone: one pass costs what loading the graph and
emitting the rows already cost, so a checkpoint there bounds nothing the surrounding pipeline does not. One gap is
named rather than hidden: algo.localClusteringCoefficient's CSR path delegates to a GraphAlgorithms kernel that
counts triangles across a thread pool, and WorkCheckpoint is specified to be called between iterations on the
calling thread - covering it is a change to how that kernel partitions its work.

#6300 - algo.mst's edge arrays are the one dense path #6263 did not price

24 bytes per edge across eu/ev/ew and the index sort, unreserved. #6263's criterion was "knob-sized or
quadratic in the node count", and edge-linear reads like the graph paying for itself - but the edge count is the
largest linear dimension a graph has, and 100M edges is ~2.4 GB with nothing between it and the allocator.

The issue asked for the reservation to be made before the pass-1 count loop, which cannot be done as stated:
nothing knows the edge count before the walk, and every cheap upper bound (countType over the edge types) is
itself a scan. What it wants is achievable another way, and that is what is implemented: the new
MemoryBudget.capacityFor(bytesPerItem) turns the budget into a bound the walk carries, so the count stops the
moment it passes what the budget allows. The refusal still goes through reserve(), so the message names the same
component and the same setting either way. The issue's Borůvka-over-CSR alternative is not taken here - it would
remove the allocation rather than bound it, but it changes tie-breaking and result ordering, which is a different
change from closing a hole in the budget.

algo.mst's List<Vertex> + Map<RID, Integer> are noted in the issue and left alone on purpose: that is the
shared OLTP loading path every procedure uses, so pricing it in one procedure would be inconsistent. It belongs in
loadGraph, as one change, if it is wanted.

Verification

  • Issue6301AlgoSteinerTreeWeightAlignmentTest (6) - both reproductions, the analytical-view comparison with an
    explicit CSR_ACCELERATED_VAR assertion so it cannot silently pin the OLTP path twice, parallel edges, the
    bellmanford unit-weight fallback, the apsp all-types crash. 4 of 6 verified red on the pre-fix code.
  • Issue6302AlgoGraphDrivenWorkGuardTest (42) - every one of the 22 procedures aborts on a pending thread
    interrupt and still returns its result without one, plus a @Tag("slow") deadline test on algo.apsp at 1500
    nodes. Verified: with the Floyd-Warshall checkpoint removed the same test runs the loop to completion and
    returns.
  • Issue6295AlgoUnguardedPhaseTest (2) - the MinHash reduction aborts on a deadline that the single message-passing
    round comfortably survives. Verified red (no exception, ran to completion) with the checkpoint removed.
  • Issue6300AlgoMSTEdgeBudgetTest (5) - refusal, the message naming the count the walk stopped at, a budget that
    fits, a disabled budget, and the MST itself unchanged. 2 of 5 verified red on the pre-fix code.

Only algo.hashgnn's reduction is pinned as a binary abort, and the test javadoc records why the others are not:
SLPA's propagation and its post-processing are both O(nodeCount x iterations) and measured at the same order, so
any threshold between them would be measuring the fixture rather than the checkpoint. They are covered by the
no-regression test instead.

Full runs: 2541 tests across Algo*/Issue62*/Issue63*/Cypher*/GraphAnalyticalView*/SQLFunction*, 1639
across com.arcadedb.graph.** and com.arcadedb.function.**, plus the slow lane for the touched classes. All
green.

Follow-up worth filing

GraphAnalyticalView.getEdgeProperty's positional contract is broken by an active overlay for any caller, not
only these. This PR makes the four known callers fall back safely via hasEdgeProperties(), but the SPI method
itself still returns a value addressed against the base CSR while getNeighborIds returns the overlay's list. A
provider-side fix (an overlay-aware property lookup, or an explicit "unknown" return) would close the shape rather
than the instances.

🤖 Generated with Claude Code

https://claude.ai/code/session_016yjKJXMNMQeLPKdCno7cFX

…d the phase a call spends its time in is the one that has to be abortable

#6301 - algo.steinerTree paired edge weights with neighbours BY ITERATION POSITION. The adjacency was built with
the relTypes filter applied and in the backing store's order; the weights were filled positionally from an
unfiltered getEdges(BOTH) walk in OLTP order. Nothing reconciled the two, and that array feeds Dijkstra, so the
TREE moved, not only the reported weight. An excluded edge type lent its 999.0 to an included edge (totalWeight
1000.0 for a tree costing 2.0), and the mere presence of a Graph Analytical View made the procedure return a
51.0 tree where it had returned 2.0. Replaced by GraphData.weightedAdjacency(), which produces the neighbour
list and its weights from ONE walk of the same edges - columnar when the view has them, edge records otherwise -
so the pairing is correct by construction and both backings return the same answer. The same broken helper also
made algo.apsp throw ArrayIndexOutOfBounds on a view with no relTypes filter, and made algo.bellmanford silently
use a unit weight for EVERY edge whenever the view had no column for the requested property.
GraphTraversalProvider.hasEdgeProperties() now also asserts that getEdgeProperty's positional mapping is exact,
and GraphAnalyticalView answers false while a delta overlay is active.

#6295 - algo.hashgnn's MinHash reduction runs AFTER the loop `iterations` drives and costs 4 x
embeddingDimension^2 per node, so a bounded per-node figure times an unbounded node count. Measured: 112,988 ms
against a 1000 ms arcadedb.command.timeout, and the call returned rather than aborting. The question that finds
this is "which loop over the node count has no checkpoint", not "which knob has no cap" - which also turned up
the pre-loop initialisation of hashgnn, fastrp and graphsage, and slpa's post-processing and mostFrequent.

#6302 - the four densest procedures had no WorkGuard at all. The #6263 budget's 64 MB floor admits n ~ 2890 for
algo.apsp, and 2890^3 is ~2.4e10 Floyd-Warshall iterations that ignored Thread.interrupt(), command.timeout and
client cancellation. Swept all 68 procedures: every one whose dominant loop is superlinear in the graph is now
abortable, 22 in total. Single O(V + E) passes are deliberately left alone.

#6300 - algo.mst builds three edge-sized arrays plus the index sort, 24 bytes per edge, unpriced: the one dense
path #6263 missed, because its criterion was knob-sized or node-quadratic and this one is edge-linear. Reserved
through the new MemoryBudget.capacityFor(), consulted AS the counting pass runs, so a graph too large to serve
stops being walked rather than being refused after a full traversal.
@lvca lvca self-assigned this Aug 17, 2026
@mergify

mergify Bot commented Aug 17, 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

@codacy-production

codacy-production Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🟢 Coverage 95.38% diff coverage

Metric Results
Coverage variation Report missing for d71b26a1
Diff coverage ✅ 95.38% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (d71b26a) Report Missing Report Missing Report Missing
Head commit (0dc5467) 192250 139566 72.60%

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 (#6306) 260 248 95.38%

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%

1 Codacy didn't receive coverage data for the commit, or there was an error processing the received data. Check your integration for errors and validate that your coverage setup is correct.

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 Aug 17, 2026

Copy link
Copy Markdown

Review of #6306

Reviewed via multi-angle analysis of git diff 11763ff..70f2236 (excluding docs/). This PR fixes a real weight/neighbor misalignment bug in AlgoSteinerTree (#6301), adds cooperative-abort WorkGuard checkpoints to 22 graph procedures (#6302), fixes an unguarded post-loop phase in algo.hashgnn (#6295), and adds an edge-array memory budget to algo.mst (#6300). The core rewrite (GraphData.weightedAdjacency replacing the buggy two-pass edgeWeights) is well-reasoned and the four new test classes do pin the described regressions red-before-fix.

Overall this is a careful, well-documented PR with strong test coverage for its primary claims. The items below are gaps found on top of that.

Correctness

  1. GraphAnalyticalView.hasEdgeProperties()/getEdgeProperty() are keyed by "some property materialized," not by the specific weightProperty requested (GraphAnalyticalView.java ~L1204-1236). If a view is built with .withEdgeProperties("distance") only, and an algo is called with weightProperty="cost", hasEdgeProperties() still returns true (a column store exists), so weightedAdjacency takes the columnar path; getEdgeProperty(..., "cost") then returns null for the missing column and every edge silently defaults to weight 1.0. This is the exact "unit-weight-for-every-edge" failure class algo.steinerTree attaches edge weights by iteration position, so a relTypes filter and the analytical view each silently change the tree it returns #6301 was written to fix, just triggered by a property-name mismatch instead of a missing view. It's a pre-existing gap (the old edgeWeights() had the same hasEdgeProperties()-only gate), not a new regression, but the new abstraction would be a natural place to close it, e.g. checking edgeColStore.hasColumn(propertyName) instead of just non-null. Issue6301AlgoSteinerTreeWeightAlignmentTest covers "view materializes nothing → falls back to records" but not "view materializes a different property than requested." Worth a follow-up issue if not fixed here.

  2. The new GraphData.weightedAdjacency* methods in AbstractAlgoProcedure.java (~L693-750) have no WorkGuard checkpoints, despite weightedAdjacencyFromRecords walking every edge of a vertex via real record access (including RecordNotFoundException/ghost-edge handling) in the OLTP fallback. Since ArcadeDB graphs are multigraphs, a vertex with a very large number of parallel/duplicate edges and no materialized CSR properties would have this walk run unguarded through algo.apsp, algo.bellmanford and algo.steinerTree alike, the same bug class The four densest algo.* procedures have no WorkGuard, so an O(V³) run the memory budget explicitly admits cannot be interrupted or timed out #6302 fixes everywhere else in the algo package, reintroduced in the one shared helper all these callers now funnel through. Notably inconsistent with AlgoMST's own near-identical edge-collection passes in this same PR, which do get guard.checkPeriodically(i).

  3. AlgoMST's edge-collecting passes throttle the checkpoint by vertex count (checkPeriodically(i)), not edge count (AlgoMST.java ~L143, L174). A near-star graph (a few vertices each with millions of edges) with arcadedb.cypher.algoMaxWorkingMemory=-1 (a supported, tested configuration) means the memory-budget throw never fires, and the inner per-edge loop for one such vertex runs to completion with no interior checkpoint. AlgoAPSP's analogous loop uses the same pattern, so this may be an intentional PR-wide granularity choice rather than MST-specific, worth confirming either way.

  4. AlgoKTruss.computeFullTrussDecomposition's setup phase (neighbor-set rebuild and the O(E×V) initial per-edge support computation) runs before the loop's first guard.check() (~L213 vs. the first check at ~L239), even though the method now takes a WorkGuard specifically for this kind of graph-driven cost. On a large graph this unguarded setup (BitSet clone+and per edge) can itself run long before any checkpoint is reached.

  5. AlgoBellmanFord's negative-cycle-detection pass (after relaxation) has no checkpoint, unlike the structurally identical relaxation loop directly above it in the same method (~L180). Lower confidence, since it's a single O(E) pass which the PR's own convention (single-pass loops deliberately left unguarded) may cover intentionally, but the relaxation loop right above it is also an O(E) pass per iteration and does get guard.check(), so it's worth a second look for consistency.

Test coverage

  1. AlgoMinSpanningArborescence's new WorkGuard threading through edmonds()'s recursive cycle-contraction has no regression test, confirmed via grep -rn "Arborescence|edmonds" over all 4 new Issue*Test.java files returning nothing, while its siblings (clique, kTruss, bipartiteMatching, etc.) are covered in Issue6302AlgoGraphDrivenWorkGuardTest. A slip in the guard's placement across recursion levels, or in threading the new leading WorkGuard parameter through the recursive self-call, would ship silently.

  2. hasEdgeProperties()'s new overlay-active narrowing has no test for its three non-algo-package callers: AlgoDijkstraSingleSource.java:116, SQLFunctionBellmanFord.java:112, SQLFunctionAstar.java:258. They correctly degrade to the OLTP fallback by inspection, but unlike the algo-package trio covered by Issue6301AlgoSteinerTreeWeightAlignmentTest, no test exercises "view has edge-property columns AND a delta overlay is active" for these three.

  3. AlgoKShortestPaths and AlgoMinSpanningArborescence hand-roll the same RID-resolution/weight-extraction/ghost-edge-skip pattern that GraphData.weightedAdjacency was introduced in this very PR to consolidate. Not incorrect, but a future fix to the neighbor/weight alignment bug class in the shared method won't propagate to these two files' independent copies.

Minor / cleanup

  1. AbstractAlgoProcedure.weightedAdjacencyFromColumns (~L706-738) does two passes over types x directions (one to sum degree into a cached slices[], one to refill from it) where the sibling weightedAdjacencyFromRecords a few lines below already demonstrates a single growable-buffer pass. Not a correctness issue, just avoidable duplication.

  2. WorkGuard placement across the ~25 touched files is ad hoc: some loops use unthrottled guard.check() per outer round, others use throttled checkPeriodically(counter) on inner loops, each with its own bespoke justification rather than a shared "checked graph-walk" primitive. Reasonable for this PR's scope, but nothing structural stops the next new/refactored algorithm from reintroducing the algo.hashgnn's MinHash phase is O(nodeCount × embeddingDimension²) and sits outside every checkpoint (follow-up to #6264) #6295/The four densest algo.* procedures have no WorkGuard, so an O(V³) run the memory budget explicitly admits cannot be interrupted or timed out #6302 bug class, the way a checked iterator baked into GraphData.adjacency/weightedAdjacency would.

  3. GraphAnalyticalView.snapshot (volatile) is read three separate times in sequence within weightedAdjacency (getMaterializedEdgeTypes(), hasEdgeProperties(), then per-node CSR calls in weightedAdjacencyFromColumns), with no atomicity guarantee across the reads. This is a pre-existing risk in the lock-free-read design, marginally widened by the extra read this diff adds ahead of the loop, flagging for awareness, not as a proven bug.

None of the above should block merging on their own given the strength of the existing tests and the PR's explicit self-documentation of scope (the "Follow-up worth filing" section already flags a related instance of item 1's root cause). Items 1, 2, 6, and 7 seem the most worth a quick follow-up.

…and guard the walk that reads it

Review round 1 on PR #6306.

1. hasEdgeProperties() answers "are there edge property columns at all", so a view built over `distance` said yes
   to a call asking for `cost`; every getEdgeProperty then returned null and the whole graph was silently
   unweighted - the same wrong answer #6301 is about, reached from the other direction. New
   GraphTraversalProvider.servesEdgeProperty(propertyName, edgeTypes...) resolves "all types" against what the
   provider holds and checks each one, and is now the gate for algo.apsp, algo.bellmanford, algo.steinerTree,
   algo.dijkstra.singleSource, SQLFunctionAstar and SQLFunctionBellmanFord. The last of those also passed a null
   edge type to getEdgeProperty, which can never resolve a column store, so its CSR path had been unit-weighting
   every edge unconditionally.

2. GraphData.weightedAdjacency now takes the WorkGuard: it walks every edge of the graph, including the record
   path with its ghost-edge handling, so it is one of the graph-driven loops that has to be abortable - and it is
   the one helper algo.apsp, algo.bellmanford and algo.steinerTree all funnel through. The record path throttles
   by EDGE, not by vertex, since one supernode can hold millions.

3. algo.mst's two edge-collecting passes throttle by edge rather than by vertex for the same reason: with
   algoMaxWorkingMemory disabled the budget never fires, and a near-star graph left one vertex's whole edge list
   unabortable.

4. algo.kTruss's setup phases - the neighbour bit matrix and the O(E) initial support computation, in both
   execute() and computeFullTrussDecomposition() - run before the peeling loop that carried the only checkpoint.

5. algo.bellmanford's negative-cycle pass is guarded like the relaxation passes above it, rather than being the
   one unabortable loop left in the method.

Tests: a view materialising a different property than the one requested (verified red on the coarse gate: 1.0
instead of 2.0), an active delta overlay asserted to flip hasEdgeProperties() from true to false with
algo.bellmanford still reading the right weights, and algo.msa over a graph whose cheapest-incoming selection
forms a cycle, so the guard is exercised through the contraction recursion rather than only at level 1.

Declined, with reasons in the PR thread: consolidating algo.kShortestPaths and algo.msa onto weightedAdjacency
(they resolve neighbours by index already, so they carry no alignment bug - it is a CSR-acceleration change, not a
fix), a checked-iterator primitive baked into GraphData (placement genuinely differs per loop complexity), and the
non-atomic repeated snapshot reads (pre-existing lock-free design, unchanged in kind by this diff).
@lvca

lvca commented Aug 17, 2026

Copy link
Copy Markdown
Member Author

Thanks - actioned 8 of the 11 points in dfb2d8b. Three declined, with reasons.

1. hasEdgeProperties() is keyed by "some property", not the requested one — actioned, and it was worse than the review found.

You are right that this is the same failure class as #6301 arrived at from the other direction, and the new abstraction is the place to close it. New GraphTraversalProvider.servesEdgeProperty(propertyName, edgeTypes...) resolves "all types" against getMaterializedEdgeTypes() and checks hasEdgeProperty(type, property) for each. It is now the gate in GraphData.weightedAdjacency, and also in the three non-algo callers from point 7 — algo.dijkstra.singleSource, SQLFunctionAstar, SQLFunctionBellmanFord — so the check lives in one place rather than being open-coded four times.

Chasing it into those callers turned up a live instance: SQLFunctionBellmanFord passed null as the edge type to getEdgeProperty, which can never resolve a column store, so on any CSR-backed graph its weighted path had been using a unit weight for every edge unconditionally — weightProperty ignored outright. Fixed by resolving a single materialized type and gating on it.

aViewThatMaterialisedADifferentPropertyDoesNotMakeTheGraphUnweighted pins it and was verified red on the coarse gate: returns 1.0 (the direct hop at unit weight) instead of 2.0.

2. weightedAdjacency* has no checkpoint — actioned. Correct, and the inconsistency with AlgoMST in the same PR is the tell. weightedAdjacency now takes the WorkGuard. The record path throttles by edge, not by vertex, for the multigraph reason you give.

3. AlgoMST throttles by vertex — actioned, and it is a real hole, not a granularity choice. With algoMaxWorkingMemory=-1 the budget never fires, so nothing bounds it; both passes now use a running edge counter. AlgoAPSP's analogous loop is a different case — it reads an already-materialised int[], so the per-vertex throttle there costs at most one array scan, and the expensive part of that phase moved into weightedAdjacency, which is now guarded per edge.

4. AlgoKTruss setup runs before the first check — actioned, in both computeFullTrussDecomposition and execute() (the same two phases exist in each): the neighbour bit matrix and the O(E) initial support computation.

5. AlgoBellmanFord's negative-cycle pass — actioned. You are right that the consistency argument wins: the relaxation pass right above it is also a single O(E) pass and does get a check.

6. No test for edmonds()'s recursion — actioned. algo.msa is in Issue6302AlgoGraphDrivenWorkGuardTest's interrupt table (the grep missed it because the procedure is named algo.msa, not "arborescence"), but you are right about what that fixture does not reach: on a directed cycle each non-root vertex's cheapest incoming edge already forms a path from the root, so nothing contracts and the recursion never runs. Added msaStaysAbortableThroughItsCycleContractionRecursion over a graph where R reaches A and B at 10 while A and B reach each other at 1 — the cheapest-incoming selection is then a 2-cycle that must be contracted. The 11.0 total is itself the proof the contraction happened; without it the answer is 20.0.

7. No test for the overlay narrowing — actioned. anActiveOverlayDoesNotLendItsWeightsToTheWrongEdges builds a SYNCHRONOUS view, asserts hasEdgeProperties() is true, commits a change the view absorbs into its delta overlay, asserts it flips to false, and checks algo.bellmanford still returns the record weights. The two assertions around the commit are what make it non-vacuous — a test that never actually produced an overlay would fail the first one.


8. AlgoKShortestPaths/AlgoMinSpanningArborescence hand-roll the pattern — declined, with a correction. Worth separating two things: neither carries the alignment bug. Both resolve the neighbour by index (ridToIdx.get(e.getIn())) rather than by iteration position, and neither touches the CSR at all — they load vertices manually. So moving them onto weightedAdjacency would not fix anything; it would newly route them through a Graph Analytical View, which changes neighbour ordering and result ordering for two procedures this PR has no other reason to touch. That is a CSR-acceleration change and belongs in its own PR with its own regression evidence. The consolidation argument is real, though — noted as a follow-up alongside the one already in the description.

10. No structural "checked iterator" primitive — declined. A shared primitive would have to pick one throttling policy, and the placement genuinely differs per loop: unthrottled check() where one iteration is already O(V) (algo.apsp's matrix row, a Floyd-Warshall i step, a whole BFS), checkPeriodically on a running counter where one iteration is O(1) and the product of two loops is what is unbounded (algo.hashgnn's reduction, algo.mst's edge walk). Baking one into GraphData.adjacency would explain the mechanism but not the varying part, which is the part that is easy to get wrong. Same conclusion #6264 reached over three review rounds. The general form worth building is a lint, not an API.

11. Repeated non-atomic snapshot reads — declined as flagged. Agreed it is pre-existing and unchanged in kind: each read already returns a self-consistent snapshot, and no invariant here spans two of them (a torn read across servesEdgeProperty and the per-node calls yields the columnar path over a newer snapshot, which is exactly what a concurrent rebuild produces anyway). Widening it to a single captured read would mean pinning a snapshot across a whole graph walk, which is a different lifetime contract than the lock-free design currently offers.

Re-ran after the changes: 1631 tests across Algo*/Issue62*/Issue63*/GraphAnalyticalView*/SQLFunction*/com.arcadedb.function.**, 1966 across com.arcadedb.graph.**/Cypher*, plus the slow lane. All green.

@claude

claude Bot commented Aug 17, 2026

Copy link
Copy Markdown

Reviewed this PR (the SteinerTree weight-alignment fix, hashgnn/apsp/mst checkpointing, and the MST edge-array budget). The core diagnosis and fixes for #6301/#6295/#6302/#6300 are solid: GraphData.weightedAdjacency/weightedAdjacencyFromColumns correctly builds neighbours and weights from one walk (splitting BOTH into OUT+IN slices per type, keeping each slice positional against getEdgeProperty), the WorkGuard checkpoint placement across the 22 procedures looks right on the loops I traced (recursion in AlgoMinSpanningArborescence.edmonds, the two-pass edge counting in AlgoMST, AlgoKTruss's pre-peeling setup), and the four deleted OLTP/CSR builders are faithfully subsumed with no loss of the "min over parallel edges" invariant in AlgoAPSP. Test coverage for the pinned regressions is thorough (red-before-fix verified per the PR description).

Two issues found in the two SQLFunction* call sites this same PR touched, in the same #6301 bug class the rest of the PR fixes - both silent-wrong-answer, no exception, so they won't surface as a crash in testing:

1. SQLFunctionAstar.getNeighborWeightsCSR (engine/src/main/java/com/arcadedb/function/sql/graph/SQLFunctionAstar.java:256-274) reproduces the exact positional-misalignment bug #6301 fixes elsewhere, for two independent reasons:

  • Line 258 takes only paramEdgeTypeNames[0] as edgeType, and line 262 gates the CSR path with servesEdgeProperty(paramWeightFieldName, edgeType) (single type). But line 265 calls getNeighborIds(nodeId, paramDirection, paramEdgeTypeNames) with the full type array, and GraphAnalyticalView.getVertices merges all requested types into one sorted list. Line 271 then reads getEdgeProperty(nodeId, i, paramDirection, edgeType, ...) against only the first type's per-type CSR column, indexed by i's position in the merged list. With astar(a, b, 'distance', {edgeTypeNames: ['KNOWS','LIKES']}) over a view where only KNOWS materializes distance, every LIKES-reached neighbour (and any KNOWS neighbour whose merged-list position differs from its per-type offset) gets null (silently defaults to weight MIN/0, i.e. free) or another edge's unrelated weight.
  • Independently, line 271 passes paramDirection straight through even when it's BOTH. GraphAnalyticalView.getEdgeProperty only resolves OUT/IN and hits else { return null; } for anything else (confirmed by reading the method, lines ~1219-1245), so a direction: 'BOTH' call zeroes every CSR-backed weight regardless of type count. This is the same pattern weightedAdjacencyFromColumns in AbstractAlgoProcedure.java (lines 738-742) explicitly guards against by splitting BOTH into {OUT, IN} slices before calling getEdgeProperty - that fix wasn't carried over here.

2. SQLFunctionBellmanFord.execute (engine/src/main/java/com/arcadedb/function/sql/graph/SQLFunctionBellmanFord.java:118-146) has the same BOTH-direction gap, and it's reachable by default: parseDirectionParam (line 266) defaults to "BOTH" when no 4th argument is given, so the plain, minimal 3-arg call bellmanFord(src, dst, 'weight') sets dir = BOTH. If the graph has a Graph Analytical View materializing exactly one edge type with that property, useCSR is true (line 118-120), and line 146's provider.getEdgeProperty(nodeId, ni, dir, csrEdgeType, weightProperty) hits the same BOTH -> null branch, so w stays at its default 1.0 for every edge - the CSR path silently unit-weights the whole graph for the common, undecorated call shape, which is precisely the failure #6301's fix set out to eliminate.

Neither SQLFunctionAstarTest nor SQLFunctionBellmanFordTest has a Graph-Analytical-View-backed case, so the useCSR/CSR-accelerated branch of both functions is untested and this is invisible to CI today.

Minor style nit: Issue6301AlgoSteinerTreeWeightAlignmentTest.java uses fully-qualified com.arcadedb.graph.Vertex inline at lines 375, 376, 406, 407 with no colliding import to justify it - CLAUDE.md asks for an import instead.

One maintainability note, not a defect: the WorkGuard checkpoint convention (newWorkGuard(context) + guard.check()/checkPeriodically()) is opt-in by hand-copied convention across the 22 algo.* classes, with Issue6302AlgoGraphDrivenWorkGuardTest's parametrized list as the only backstop. A future algo.* procedure with an unbounded graph-driven loop can ship without a guard unless someone remembers to add it to that list. Not blocking for this PR, but worth a lint/base-class check if more procedures get added later.

Suggest fixing the two SQLFunctionAstar/SQLFunctionBellmanFord BOTH-direction and multi-type cases before merge, ideally by routing both through the same weightedAdjacency-style one-walk builder AbstractAlgoProcedure already has, since that's what closed this exact bug class everywhere else in the PR.

…not four hand-rolled copies

Review round 2 on PR #6306, which found the same bug class still live in the two SQL functions this PR had
touched - and reachable by DEFAULT in one of them.

getEdgeProperty() is addressed by (type, direction, position), and pairing it with getNeighborIds() by hand is
wrong in two independent ways, both silent:

  - a multi-type neighbour list is MERGED AND SORTED across types while the property columns are per type, so
    position j in the list is not position j in any one column;
  - DIRECTION.BOTH has no column at all. A provider resolves OUT and IN, so a BOTH lookup returns null for every
    edge and the caller reads the whole neighbourhood at its default weight.

SQLFunctionBellmanFord's direction argument defaults to BOTH, so the plain three-argument call
bellmanFord(src, dst, 'weight') had been unit-weighting the entire graph the moment a view existed - on the
fixture here that returns the two-hop A-C-D instead of the weighted A-B-C-D. SQLFunctionAstar hit the same branch
with direction 'BOTH' and priced every edge at MIN (0.0), so every path tied, and separately read a merged
multi-type list against only paramEdgeTypeNames[0]'s column.

New GraphTraversalProvider.edgeWeightsOf(nodeId, direction, property, defaultWeight, types...) returns one node's
neighbours and weights together, splitting BOTH into OUT+IN and taking one slice per (type, direction) - each of
which IS positional. It is the single place that knows how to pair a CSR edge with its own weight, and all three
CSR readers now go through it: GraphData.weightedAdjacencyFromColumns (whose duplicate of the logic is deleted),
SQLFunctionAstar and SQLFunctionBellmanFord. New record NodeEdgeWeights carries the pair.

algo.dijkstra.singleSource needs no change beyond round 1's gate: GraphAlgorithms.dijkstraSingleSource walks the
forward and backward CSR arrays itself with the column index rather than through getEdgeProperty, so it has no
BOTH hazard.

Issue6301CsrEdgeWeightAlignmentTest is the coverage the review noted was missing entirely - neither SQL function
had a Graph-Analytical-View-backed case, so the whole CSR branch of both was untested. The fixture is the
discriminator: A-B-C-D at 1.0 per hop against a direct A-C at 100.0, so wrong weights return a different PATH,
not merely a different number. Verified red on the round-1 code for both functions.

Also actioned: the fully-qualified com.arcadedb.graph.Vertex references in the test are imports now.
@lvca

lvca commented Aug 17, 2026

Copy link
Copy Markdown
Member Author

Both findings confirmed and fixed in 26f7516. You were right that the two SQLFunction* call sites still carried the bug class the rest of the PR closes, and the BOTH case is worse than "reachable" — it is the default.

Verified both, red-before-fix, on the round-1 code:

  • bellmanFord(src, dst, 'weight') — three arguments, so parseDirectionParam gives BOTH — returned the two-hop A-C-D instead of the weighted A-B-C-D the moment a view existed. Every edge at 1.0, weightProperty ignored.
  • astar(..., {direction: 'BOTH'}) did the same at MIN (0.0), i.e. every edge free, so all paths tied and whichever was found first won.

The fix takes your suggestion of routing through the one-walk builder, but pushes it one level lower. GraphData.weightedAdjacency lives in the OpenCypher procedures package and is shaped for a whole-graph build, which is the wrong shape for astar — it expands one node at a time and must not build the graph per expansion. So the pairing logic moved onto the SPI instead, where getEdgeProperty's positional contract already lives:

NodeEdgeWeights edgeWeightsOf(int nodeId, Vertex.DIRECTION direction, String propertyName,
                              double defaultWeight, String... edgeTypes)

It splits BOTH into {OUT, IN} and takes one slice per (type, direction) — each of which is positional — and returns null unless the provider can serve that property for every type in play. weightedAdjacencyFromColumns's copy of the logic is deleted and now calls it; so do both SQL functions. That is one method that knows how to pair a CSR edge with its weight, rather than the four hand-rolled copies that existed when this PR opened, which is what stops the three from drifting apart again. defaultWeight is a parameter because the callers genuinely disagree: astar defaults a missing weight to MIN (0.0), the others to 1.0.

algo.dijkstra.singleSource needed nothing beyond round 1's gate — worth stating since it looks like a fourth instance. GraphAlgorithms.dijkstraSingleSource walks the forward and backward CSR arrays itself using the column index, never through getEdgeProperty, so it has no BOTH hazard; the only thing it was missing was the per-property check, which it got in dfb2d8b.

On the missing coverage: you are right that the CSR branch of both functions was untested outright. Issue6301CsrEdgeWeightAlignmentTest covers it, and the fixture is chosen so the test cannot pass by accident — A-B-C-D at 1.0 per hop against a direct A-C at 100.0 means the weighted answer is the four-vertex path and the unit-weighted answer is the three-vertex one. Getting the weights wrong changes the path, not just a number. It also pins the "view materialises a different property" case for bellmanFord, and asserts the OLTP result first in every test so a view that silently stopped being used could not make it pass.

Style nit — fixed, com.arcadedb.graph.Vertex is imported in both test classes.

Maintainability note — agreed, and worth being precise about why it is not addressed here. The gap is not that a checkpoint is easy to forget; it is that the right placement is a per-loop judgement (unthrottled where one iteration is already O(V), throttled on a running counter where the unbounded thing is the product of two loops), so a base-class hook would standardise the part that is already easy and leave the part that is hard. The enforceable version is a lint over the package — "a loop over nodeCount or edgeCount inside execute() with no guard reference in its body" — which is a build-tooling change rather than an API one. Noted as a follow-up alongside the two already in the description.

Re-ran: 1634 tests across Algo*/Issue62*/Issue63*/SQLFunction*/GraphAnalyticalView*/com.arcadedb.function.**, 1969 across com.arcadedb.graph.**/Cypher*, plus the slow lane. All green.

@codecov

codecov Bot commented Aug 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.38462% with 38 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.38%. Comparing base (11763ff) to head (26f7516).

Files with missing lines Patch % Lines
...ncypher/procedures/algo/AbstractAlgoProcedure.java 76.27% 6 Missing and 8 partials ⚠️
...ava/com/arcadedb/graph/GraphTraversalProvider.java 83.33% 3 Missing and 3 partials ⚠️
.../arcadedb/function/sql/graph/SQLFunctionAstar.java 50.00% 2 Missing and 3 partials ⚠️
...a/com/arcadedb/graph/olap/GraphAnalyticalView.java 50.00% 0 Missing and 4 partials ⚠️
...edb/function/sql/graph/SQLFunctionBellmanFord.java 62.50% 0 Missing and 3 partials ⚠️
...dedb/query/opencypher/procedures/algo/AlgoMST.java 83.33% 1 Missing and 1 partial ⚠️
...edb/query/opencypher/procedures/algo/AlgoAPSP.java 91.66% 0 Missing and 1 partial ⚠️
...ry/opencypher/procedures/algo/AlgoBellmanFord.java 96.42% 0 Missing and 1 partial ⚠️
...pher/procedures/algo/AlgoDijkstraSingleSource.java 0.00% 0 Missing and 1 partial ⚠️
...opencypher/procedures/algo/AlgoKShortestPaths.java 85.71% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6306      +/-   ##
==========================================
+ Coverage   70.29%   70.38%   +0.08%     
==========================================
  Files        1842     1843       +1     
  Lines      159382   159470      +88     
  Branches    33574    33561      -13     
==========================================
+ Hits       112042   112243     +201     
+ Misses      33459    33360      -99     
+ Partials    13881    13867      -14     

☔ 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 Aug 17, 2026

Copy link
Copy Markdown

Review

This is an exceptionally well-engineered PR: each fix comes with a "verified red before fix" regression test, the reasoning for scope decisions (what's included vs. explicitly declined) is spelled out, and the iterative self-review rounds (visible in the commit history) already caught and fixed several real bugs - the hasEdgeProperties() vs servesEdgeProperty() distinction, the BOTH-direction column gap in SQLFunctionBellmanFord/SQLFunctionAstar, and the multi-type merge/sort mismatch. I reviewed the final state after all three rounds. A few smaller points below, nothing blocking.

Possible gap: no per-edge checkpoint in the columnar weight-reading path

GraphTraversalProvider.edgeWeightsOf() (engine/src/main/java/com/arcadedb/graph/GraphTraversalProvider.java) and its caller GraphData.weightedAdjacencyFromColumns() (AbstractAlgoProcedure.java) only call guard.checkPeriodically(i) once per node, before filling that node's whole neighbour/weight slice. The PR is explicit elsewhere that a near-star graph (one supernode holding a huge share of the edges) makes per-vertex throttling unsafe - that's exactly why weightedAdjacencyFromRecords() and AlgoMST's edge-collection passes were changed to throttle by edge instead (see the round-1 commit message, points 2 and 3). The same supernode shape can exist in a CSR/Graph-Analytical-View-backed graph, but edgeWeightsOf's inner per-edge loop (the getEdgeProperty calls building neighbors/weights) has no checkpoint at all, and the method doesn't even take a WorkGuard parameter.

This is very likely fine in practice - CSR reads are array indexing rather than record deserialization, so the per-edge cost is much lower than the OLTP path this reasoning was applied to. But given how carefully this PR documents why a gap is acceptable elsewhere (e.g. the algo.localClusteringCoefficient CSR-kernel gap called out explicitly in both the Javadoc and the release notes), it would be worth a one-line comment here confirming the columnar path is exempt for that reason, so a future reader doesn't have to re-derive it - or a checkPeriodically call on the inner loop if a single supernode's CSR degree can in fact get large enough to matter.

Minor: edgeWeightsOf re-validates servesEdgeProperty on every call

weightedAdjacencyFromColumns calls provider.edgeWeightsOf(i, ...) once per node, and edgeWeightsOf itself starts with if (!servesEdgeProperty(propertyName, edgeTypes)) return null; - but the caller (GraphData.weightedAdjacency) already checked servesEdgeProperty once before entering the columnar path at all, so this re-checks the same (constant-for-the-call) answer on every node/vertex. Same pattern in SQLFunctionAstar/SQLFunctionBellmanFord, which call edgeWeightsOf once per expanded/visited vertex. ColumnStore.getColumn's single-slot memoization keeps the per-call cost low, but it's still an avoidable hash lookup per type per node. Not worth a structural change given how much clearer edgeWeightsOf is as the single source of truth, but a "pre-validated" fast path (or hoisting the check) would be a straightforward win on large graphs - worth doing only if it shows up in profiling.

Test coverage: Issue6302AlgoGraphDrivenWorkGuardTest happy-path list is missing two procedures

aGraphDrivenProcedureStopsOnAThreadInterrupt (interrupt case) covers all 22 procedures, including algo.clique and algo.kTruss. anUninterruptedCallStillReturnsItsResult (the counterweight "still produces a result" test) covers only 20 - algo.clique and algo.kTruss are absent from that second @CsvSource. For algo.kTruss this is probably intentional (the 4-node directed-cycle fixture has no triangles, so a 3-truss is legitimately empty and isNotEmpty() would fail), but algo.clique with minSize=2 should return the four edges as maximal 2-cliques on that same fixture, so its absence looks like it could be an oversight rather than a deliberate exclusion. Given how deliberately this PR calls out every other intentional gap, a short comment (or adding the two rows with a fixture that fits) would keep the test file's own bar.

Everything else

The core fix (GraphData.weightedAdjacency / GraphTraversalProvider.edgeWeightsOf producing neighbours and weights from one walk instead of two independently-ordered ones) is the right shape for #6301 - removing the second traversal instead of trying to reconcile it. The WorkGuard placement reasoning (per-node vs. per-edge throttling, check() vs checkPeriodically()) is consistently applied and matches WorkGuard's own documented cost model (cheap when no deadline is configured, since the clock is only read when a deadline exists). MemoryBudget.capacityFor() for algo.mst's edge arrays is a clean way to bound the walk itself rather than refusing after paying for a full traversal, and the budget-disabled / budget-fits / budget-refuses test triad for it is thorough.

No security concerns - this is internal graph-algorithm bookkeeping with no new external input surface.

tae898 pushed a commit to humemai/arcadedb-embedded-python that referenced this pull request Aug 28, 2026
…om the traversal SPI, resolve the overlay instead

GraphTraversalProvider.getEdgeProperty addressed an edge by its position in the node's neighbour list. That
position identified the same edge getNeighborIds reported only while nothing else was in play: an active
DeltaOverlay drops deleted edges, merges added ones in and re-sorts the list, while the property columns stay
aligned with the base CSR's forward slots. Delete the first of three outgoing edges and every remaining
neighbour shifts down a slot, so position 1 came back with the deleted edge's weight - a wrong shortest path,
a wrong MST, a wrong Steiner tree, and never an exception. PR ArcadeData#6306 closed that for the callers that existed
by narrowing hasEdgeProperties() to false whenever an overlay was active, leaving the accessor itself for the
next caller to find and the rule for it to remember.

The accessor is gone. In its place edgeWeightsForSlice() returns one (type, direction) slice's neighbours and
their weights together, produced by the walk that decided which edges the slice holds, so no index crosses the
SPI boundary and there is nothing left to re-derive wrongly. edgeWeightsOf() composes the slices, which is
where the multi-type merge and the BOTH split already lived, and a slice the provider cannot answer for makes
the whole node unanswerable rather than a neighbourhood with edges silently missing from it.

Resolving the overlay rather than refusing it also keeps the columnar path alive while a view is being
updated, which is the state UpdateMode.SYNCHRONOUS leaves it in after every commit:

  - a base edge the overlay has not deleted takes its own forward column slot, tracked through the merge by
    packing each entry's provenance into the low half of the sort key;
  - an edge the overlay added takes the value DeltaCollector captured for it at commit time - it has no column
    slot, the columns having been built with the base CSR;
  - a run of parallel edges between one pair, partially deleted, is refused: deletions are counted per pair,
    which is all the neighbour list needs, but not enough to say which of the run died, and parallel edges need
    not weigh the same;
  - an edge whose properties were updated marks the columns out of date until the rebuild that repairs them
    lands, so no stale weight is served. An update to an edge the overlay itself holds is applied there and
    dirties nothing, which is what keeps the ordinary newEdge(...).save() - one create and one update of the
    same edge - from forcing a rebuild per insert.

Two consequences follow from the view now serving edge properties through an overlay. GraphAlgorithms's
Dijkstra kernel reads the CSR arrays directly and was kept off them only as a side effect of that narrowing;
it refuses for itself now. And AbstractAlgoProcedure's columnar build reads the records for a node the
provider cannot answer for, through the same row reader its whole-graph record build uses, so the fallback
cannot answer differently from the path it stands in for.
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.hashgnn's MinHash phase is O(nodeCount × embeddingDimension²) and sits outside every checkpoint (follow-up to #6264)

1 participant