Skip to content

fix(#6216): a graph-algorithm knob is bounded by the resource it spends, not by a guessed cap - #6222

Merged
lvca merged 8 commits into
mainfrom
issue-6216
Aug 16, 2026
Merged

lvca merged 8 commits into
mainfrom
issue-6216

Conversation

@lvca

@lvca lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member

Closes #6216

Summary

Follow-up to #6065 (PR #6214), which bounded the allocation-shaped numeric knobs of the OpenCypher algo.* package. This closes the second family that PR deliberately left alone: knobs that are unbounded ints and multiply CPU work rather than one allocation - algo.node2vec's walksPerNode, walkLength, windowSize, negSamples; algo.maxKCut's restarts, maxIterations; algo.influenceMaximization's simulations.

Why not the issue's options as written

The issue offers three: (1) a generous hard cap per knob, (2) cooperative cancellation, (3) bound only the derived allocations. It also says why it stopped short of choosing: there is no obvious ceiling, because "what is a sane maximum iteration count?" depends on the graph, the hardware and how long the caller is willing to wait.

That is an argument against option 1 as a general policy, not against bounding anything. The seven knobs are not one family - they spend three different resources - so the fix applies one principle: a knob is bounded by the resource it actually spends, not by a guess at what a user wants. That subsumes option 3, does option 2 properly, and replaces option 1 with a heap-derived budget only where the resource really is memory.

The parameter's own domain

Below its minimum a walk/restart/simulation count is not "a smaller run", it is an answer the algorithm cannot produce - and every one of those values was absorbed in silence or died in the allocator:

input before
algo.maxKCut(2, {restarts: 0}) never entered the restart loop: every node in community 0, cutWeight -1.0, reported as success
algo.maxKCut(2, {maxIterations: 0}) skipped the local search: the "maximum" cut was the random initialisation
algo.node2vec({iterations: 0}) returned the untrained Xavier init as an embedding
algo.influenceMaximization(2, 'X', 0) divided the spread by zero: every candidate NaN, no comparison ever won, empty result set as if no node were influential
algo.node2vec({walksPerNode: -1}) new int[-4][...], a bare NegativeArraySizeException naming nothing
algo.node2vec({walkLength: 0}) zero-width rows, then walk[0] = v: ArrayIndexOutOfBoundsException

A new AbstractAlgoProcedure.extractInt(value, name, minimum) overload rejects all of them where the extraction already happens, naming the parameter, its minimum and the value. negSamples keeps a minimum of 0 - plain Skip-gram without negative sampling is a legitimate configuration; the rest take 1.

Heap - the clear-cut bug, and its one-dimensional twin

algo.node2vec computed final int totalWalks = n * walksPerNode and then new int[totalWalks][walkLen]. That product wraps. 4 nodes at walksPerNode: 1073741824 is exactly 2^32, so totalWalks came out as 0: the matrix was allocated with no rows and the generator died on walks[wi++]. Other magnitudes wrap negative instead. Even without the wrap the matrix is sized by two knobs with no graph-derived ceiling - the allocation-DoS shape #6065 closed for the embedding dimensions, in two dimensions.

algo.randomWalk has the one-dimensional version, not mentioned in the issue but the same defect in the same walk-buffer family: new int[steps + 1] wraps to Integer.MIN_VALUE at steps = 2147483647.

Both are estimated in saturating long arithmetic and checked before anything is allocated against a new arcadedb.cypher.algoMaxWalkMemory, which auto-scales with the JVM max heap (one eighth, floor 64MB) and is tunable (negative = no limit). This is the house pattern of arcadedb.queryMaxHeapElementsAllowedPerOp / arcadedb.queryMaxRangeSize, not a new invention, and it is strictly better than a per-knob constant here: the ceiling is the machine's, the error names the knobs that produced the estimate and the setting to raise, and since it is a client parameter out of range it is an IllegalArgumentException - HTTP 400, not 500. A second guard, independent of the budget, refuses a walk count past Integer.MAX_VALUE: no heap setting makes 2^32 array entries legal.

Time - option 2, using the setting that already exists

For the rest there is no honest ceiling, so a large value is not forbidden, it is made abortable. The hot loops of all three procedures call a shared WorkGuard that aborts on thread interruption - matching what ShortestPathStep and SQLFunctionShortestPath already do on the query path - and on the arcadedb.command.timeout deadline, which until now only the SQL SELECT planner honoured. No new setting for this: arcadedb.command.timeout is documented, DATABASE-scoped and defaults to 0, so behaviour is unchanged unless an operator has already asked for a command deadline.

The guard reads the clock only when a deadline is configured, so the default costs one flag test per iteration and no syscall. The interrupt flag is consumed, not restored: the exception aborts the whole call, and leaving it set would poison the next task on a pooled query thread.

Two correctness bugs found on the way

  • windowSize silently disabled training. Math.min(walkLen - 1, pos + window) wraps int for a large windowSize and comes back negative, so winEnd < winStart and the Skip-gram loop ran at position 0 and nowhere else. A window wider than the walk already spans the whole walk, so it is now clamped to walkLength - a clamp with a genuinely correct fallback, unlike an embedding dimension. The regression test asserts a huge window now yields exactly the embeddings of windowSize = walkLength, same seed, same RNG consumption.
  • algo.influenceMaximization's negative k. k saturates upwards on purpose and is clamped by Math.min(k, n), but a negative k passes that clamp untouched and reaches new int[seedCount] as another nameless NegativeArraySizeException. Message wording matches PR fix(#6065): an embedding dimension is bounded, and a negative k is named instead of reaching the allocator #6214's extractCount() so the two converge trivially once it lands.

Verification

New Issue6216AlgoWorkKnobBoundsTest, 23 tests. Confirmed sensitive: with the four procedure sources restored to HEAD (helpers and setting kept, so it still compiles), 17 of the 21 then-existing tests go red. The four that stay green are the deliberate over-reach guards - a matrix inside the budget, negSamples: 0 - and the two WorkGuard unit tests, which only exercise code the revert left in place. The two tests added afterwards (...MoreWalksThanAJavaArrayCanHold..., ...MoreStepsThanAJavaArrayCanHold...) hit the same pre-fix ArrayIndexOutOfBoundsException / NegativeArraySizeException.

Full com.arcadedb.query.opencypher.** unit suite: 4397 tests, 0 failures, 0 errors, 13 skipped.

Test plan

  • mvn -o -pl engine -am -Dtest='Issue6216AlgoWorkKnobBoundsTest' test - 23 green
  • mvn -o -pl engine -am -Dtest='AlgoNode2VecTest,AlgoMaxKCutTest,AlgoInfluenceMaximizationTest,AlgoRandomWalkTest' test - no regression on the four touched procedures
  • mvn -o -pl engine -am -Dtest='com.arcadedb.query.opencypher.**.*Test' -DexcludedGroups=benchmark,vector,slow test - no regression across the package
  • Manual: CALL algo.node2vec({walksPerNode: 1073741824}) is refused promptly by name instead of throwing ArrayIndexOutOfBoundsException
  • Manual: CALL algo.maxKCut(2, {restarts: 0}) returns algo.maxKCut(): restarts must be at least 1, got 0 instead of a cut weight of -1.0

Notes for review

…ds, and a walk count no longer wraps int

Follow-up to #6065. The CPU-shaped config knobs of the OpenCypher algo.* package accepted any in-range int
and drove a loop count directly. Rather than one guessed cap per knob, each is now bounded by the resource
it actually spends.

Domain: extractInt(value, name, minimum) rejects by name a restart, iteration, walk or simulation count
below its minimum. Those values were absorbed in silence (restarts 0 returned community 0 with cutWeight
-1.0, iterations 0 returned untrained embeddings, simulations 0 divided by zero and returned nothing) or
died in the allocator without naming the parameter.

Heap: node2vec's `n * walksPerNode` wrapped int (4 nodes at walksPerNode 2^30 gave totalWalks 0 and an
ArrayIndexOutOfBoundsException), and randomWalk's `steps + 1` wrapped at Integer.MAX_VALUE. Both walk
buffers are now estimated in saturating long arithmetic and checked before allocating against the new
arcadedb.cypher.algoMaxWalkMemory budget, which auto-scales with the JVM heap; a walk count past
Integer.MAX_VALUE is refused independently of it.

Time: no honest ceiling exists, so a long run is made abortable instead of forbidden. The hot loops of
node2vec, maxKCut and influenceMaximization call a shared WorkGuard that aborts on thread interruption and
on the arcadedb.command.timeout deadline, which until now only the SQL SELECT planner honoured.

Also: node2vec's `pos + window` wrapped int for a large windowSize, leaving the context window empty and
training a no-op past position 0 - windowSize is clamped to walkLength; and influenceMaximization's
negative k reached new int[seedCount] unnamed.
@lvca lvca self-assigned this Aug 16, 2026
@mergify

mergify Bot commented Aug 16, 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 16, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 18 complexity

Metric Results
Complexity 18

View in Codacy

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 16, 2026

Copy link
Copy Markdown

Review

Solid, well-motivated fix, closes real bugs (int-wrap on n * walksPerNode, steps + 1, the windowSize context-window wrap, the negative-k NegativeArraySizeException), and the memory-budget/extractInt(min)/WorkGuard design mirrors existing house patterns (queryMaxHeapElementsAllowedPerOp, ShortestPathStep's interrupt handling) rather than inventing new mechanisms. Test coverage for the domain/heap/interrupt/timeout axes is thorough.

Main concern: WorkGuard granularity in AlgoNode2Vec's training loop doesn't actually bound wall-clock time for large walkLength + windowSize

In AlgoNode2Vec.java, guard.check() in the Skip-gram training loop is called once per walk (line ~206), not per position:

for (final int walkIdx : walkOrder) {
  guard.check();                                   // checked here
  final int[] walk = walks[walkIdx];
  for (int pos = 0; pos < walkLen; pos++) {         // NOT checked per position
    ...
    final int winStart = Math.max(0, pos - window);
    final int winEnd = Math.min(walkLen - 1, pos + window);
    for (int ctx = winStart; ctx <= winEnd; ctx++) { // NOT checked per context
      ...
    }
  }
}

window is now Math.min(rawWindow, walkLen) (the fix for the int-wrap/silent-no-op bug), so a caller can set windowSize >= walkLength, making every position scan the entire walk as context. That makes a single walk's training cost O(walkLength²), and the whole loop only re-checks the guard between walks.

walkLength has no upper bound of its own — it's only bounded by arcadedb.cypher.algoMaxWalkMemory, which is a memory budget, not a work budget. A small walksPerNode/node count keeps total walks low while still allowing a large walkLength within the memory budget, e.g.:

CALL algo.node2vec({walksPerNode: 1, walkLength: 5000000, windowSize: 5000000})

On a modest graph (few nodes → few total walks) this comfortably fits the default heap-scaled budget (which grows with -Xmx), but each walk then does on the order of walkLength² ≈ 2.5×10^13 inner-loop iterations before the next walk's guard.check() is even reached. With only a handful of walks total, that's effectively one interrupt/timeout check every many hours — arcadedb.command.timeout and thread interruption are exactly the two things this PR introduces WorkGuard to guarantee, and for this parameter combination neither actually fires in a useful time frame. node2VecHonoursTheCommandTimeout in the new test uses walkLength: 60, so it doesn't exercise this path and wouldn't catch a regression here.

Suggest calling guard.check() inside the pos loop (e.g., every N positions if per-position is too hot) so the abort latency stays proportional to a bounded amount of work rather than to walkLength². The walk-generation phase (phase 1, guard.check() at line ~156) has the same coarser-than-ideal granularity, but it's only O(walkLength) per check there, not O(walkLength²), so it's much less urgent.

Minor

  • Residual int overflow in pos + window: clamping window to walkLen (AlgoNode2Vec.java) prevents the wrap for realistic walk lengths, but if an operator raises arcadedb.cypher.algoMaxWalkMemory enough to let walkLength approach ~1.1B+ (needs several GB of budget), pos + window can still overflow int in Math.min(walkLen - 1, pos + window). Given the PR's own stated philosophy ("bounded by the resource it spends, not by a guess"), this is a narrow edge case gated behind an explicit admin override, but worth a one-line note or a long-arithmetic version of that line if you want to close the class of bug completely rather than just the practical instance of it.
  • Coupling with fix(#6065): an embedding dimension is bounded, and a negative k is named instead of reaching the allocator #6214: checkWalkBudget's estimate only covers the walk matrix, not the W/WCtx embedding matrices (n × embeddingDimension × 8 bytes × 2), which is fine since embeddingDimension bounding is explicitly deferred to fix(#6065): an embedding dimension is bounded, and a negative k is named instead of reaching the allocator #6214 — just flagging so the two PRs' budgets get reconciled/considered together once both land, since a large embeddingDimension is currently still an unbounded allocation on the same code path.

Nits (no action needed, just noting they read correctly)

  • checkWalkBudget's inclusive estimatedBytes <= budget boundary matches the test expectations.
  • saturatingProduct callers are all non-negative inputs, consistent with its documented precondition.
  • GlobalConfiguration.CYPHER_ALGO_MAX_WALK_MEMORY's auto-scaling-default-via-callbackIfNoSet pattern is copied correctly from QUERY_MAX_HEAP_ELEMENTS_ALLOWED_PER_OP/QUERY_MAX_RANGE_SIZE.
  • AlgoRandomWalk's early steps <= 0 return happens before the new budget/overflow checks, so a negative steps never reaches walkCapacity sizing — no bug there.

Overall: good direction and mostly well-executed; the training-loop guard granularity in node2vec is the one issue I'd want addressed before merge since it undercuts the PR's central time-boundedness claim for exactly the knobs it targets.

…long, not between them

Review cycle 1. The WorkGuard was checked once per walk in node2vec's training loop, which bounds nothing
when a single walk is the unbounded thing: windowSize is clamped to walkLength, so every position scans the
whole walk as context and one walk is O(walkLength^2), while walkLength is bounded only by the walk-MEMORY
budget. walksPerNode 1 with walkLength 5000000 and windowSize 5000000 fits the default budget on a small
graph and then runs for hours between two checkpoints, so neither the deadline nor an interrupt fires in any
useful time.

WorkGuard.checkPeriodically(counter) tests every 1024 iterations - one AND and one branch per iteration -
and is called from the loops whose length a knob controls: the Skip-gram context loop, the walk-generation
step loop, and maxKCut's per-node scan inside a local-search pass. The per-walk and per-pass checks stay.

Also: `pos + window` is computed in long. The clamp to walkLength covers the practical instance, but
walkLength is bounded by a budget an operator can raise, so past ~1.1B the clamped window reaches the same
wrap; long arithmetic closes the class.

node2VecHonoursTheCommandTimeoutInsideOneLongWalk covers the case the existing timeout test could not: one
node, one walk, a window as wide as the walk. Confirmed sensitive - with the context-loop checkpoint removed
it runs to completion in 2.4s and never times out.
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Review cycle 1 - the checkpoint was in the wrong loop

Main concern: actioned, and it was right. A checkpoint between walks bounds nothing when a single walk is the unbounded thing. windowSize is clamped to walkLength, so every position can scan the whole walk as context and one walk is O(walkLength²); walkLength is bounded only by arcadedb.cypher.algoMaxWalkMemory, which is a memory budget, not a work budget. The review's own example is exact: walksPerNode: 1, walkLength: 5000000, windowSize: 5000000 on a small graph fits the default budget and then runs for hours between two checkpoints, so neither the deadline nor an interrupt fires in any useful time. That undercuts the PR's central claim, which is the right reason to block on it.

Fixed with WorkGuard.checkPeriodically(counter): tests every 1024 iterations, so the per-iteration cost is one AND and one branch and abort latency is bounded by a fixed amount of work rather than by the loop's length. Per-position was considered and rejected - it is not enough. With window = walkLen a single position is O(walkLength × negSamples × dim), still seconds at the magnitudes above; the context loop is the innermost loop a knob makes long, so that is where the checkpoint belongs.

Applied to every loop whose length a knob controls, not just the one flagged:

  • the Skip-gram context loop (the reported case);
  • the walk-generation step loop (the review's "less urgent" note - O(walkLength) per check, still knob-driven);
  • algo.maxKCut's per-node scan inside a local-search pass, which is graph-driven rather than knob-driven but is seconds on a large graph.

The per-walk and per-pass checks stay: they cost nothing and fire first on short-walk configurations.

New regression test. node2VecHonoursTheCommandTimeoutInsideOneLongWalk covers exactly what the existing timeout test could not, and the review was right that it could not - walkLength: 60 over 160 walks reaches a per-walk checkpoint constantly. The new one uses its own single-node database so there is exactly one walk and therefore exactly one per-walk checkpoint, reached before any work has happened, with a window as wide as the walk. Confirmed sensitive: with the context-loop checkpoint removed it runs to completion in 2.4 s and never times out; with it, it aborts in milliseconds.

Minor 1 - residual pos + window overflow: actioned rather than noted. The review's own framing settles it - "bounded by the resource it spends, not by a guess" is not consistent with leaving a wrap reachable through a documented admin override. Math.min(walkLen - 1L, pos + (long) window) closes the class instead of the instance, at the cost of one long add on a path that already does a double dot product per iteration.

Minor 2 - coupling with #6214: agreed, no action here. checkWalkBudget deliberately prices only the walk buffers. W/WCtx are n × embeddingDimension × 8 × 2 and embeddingDimension is #6214's to bound; pricing an allocation whose knob this branch does not validate would half-fix it and make the merge worse. Flagging it on both PRs is the right call - once #6214 lands, the two budgets should be looked at together.

Nits: all four read correctly, no action taken, and the AlgoRandomWalk steps <= 0 ordering observation is right - the early return is what keeps a negative steps away from walkCapacity.

Verification after the fix

  • Issue6216AlgoWorkKnobBoundsTest - 24 green (23 + the new one)
  • AlgoNode2VecTest, AlgoMaxKCutTest, AlgoInfluenceMaximizationTest, AlgoRandomWalkTest - 17 green, no regression on the touched procedures
  • Full com.arcadedb.query.opencypher.** unit suite - 4400 tests, 0 failures, 0 errors, 13 skipped

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

I read through the diff in detail (AbstractAlgoProcedure, AlgoNode2Vec, AlgoMaxKCut, AlgoInfluenceMaximization, AlgoRandomWalk, the new GlobalConfiguration entry, and the new test class) and traced the arithmetic by hand rather than just skimming. Overall this is a well-scoped, well-tested fix with a clear, consistently-applied design principle. A few notes, nothing blocking:

Correctness

  • The int-overflow fixes check out. 4 * 1_073_741_824 == 2^32, which wraps a signed 32-bit int product to exactly 0 - confirms the walksPerNode matrix-sizing bug as described. The fix (saturatingProduct via Math.multiplyExact, checked in long before the int cast/allocation) is correct and ordered properly: budget check, then Integer.MAX_VALUE overflow check, then cast, then allocate.
  • checkWalkBudget/saturatingProduct are only ever called with non-negative operands in all three call sites (n, a min-1-bounded walksPerNode, bytesPerWalk, steps), so the "non-negative longs" precondition documented on saturatingProduct actually holds everywhere it's used.
  • The windowSize clamp-to-walkLength plus the switch to long arithmetic for pos + window correctly closes both the practical case and the residual wrap past ~1.1B once walkLength is raised (walkLength itself is only bounded by the heap budget, not a constant, so doing this in long rather than relying on the clamp alone is the right call).
  • GlobalConfiguration.CYPHER_ALGO_MAX_WALK_MEMORY's constructor call (Long.class, default, null, callbackIfNoSet) matches the exact pattern of QUERY_MAX_HEAP_ELEMENTS_ALLOWED_PER_OP/QUERY_MAX_RANGE_SIZE, including the maxMemory() == Long.MAX_VALUE (no -Xmx) guard. Consistent with house style.
  • WorkGuard's Thread.interrupted() plus consume-not-restore pattern matches the existing precedent in ShortestPathStep/SQLFunctionShortestPath/SQLFunctionDuanSSSP, as claimed in the PR description.
  • Checkpoint placement is genuinely the hard part of this PR and it looks right: guard.check() at the coarse per-walk/per-pass/per-restart granularity, guard.checkPeriodically() inside the loops a knob can blow up on its own (Skip-gram context loop, walk-step loop, maxKCut's per-node scan). I traced through the windowSize: 8000, walkLength: 8000 single-walk timeout test by hand: since window clamps to walkLength, winStart is 0 for every pos, so the context loop is O(walkLength^2) and resets to ctx=0 every position - the periodic check fires roughly every 1024 counts within each position's inner loop, so abort latency stays small even though the two enclosing "outer" checkpoints (per-walk, per-epoch) would otherwise be hours apart. That matches the second commit's stated motivation.

Minor / non-blocking

  • AlgoInfluenceMaximization's simulation loop uses unconditional guard.check() rather than checkPeriodically():

    for (int sim = 0; sim < simulations; sim++) {
      guard.check();
      totalSpread += simulateIC(adj, seeds, round, candidate, n, propagationProbability, rng);
    }

    This is the innermost loop of a triple nest (round x candidate x sim), so with a large simulations value and arcadedb.command.timeout configured, this calls System.currentTimeMillis() on every single Monte-Carlo simulation rather than throttled to every 1024 like the analogous hot loops in AlgoNode2Vec/AlgoMaxKCut. Given simulateIC does real per-call work (a cascade simulation over the graph, not O(1)), this is probably fine in practice and arguably intentional (mirrors the per-walk guard.check() in node2vec's walk-generation loop, which is also non-trivial per iteration) - but it's worth double-checking whether simulateIC can be cheap enough on sparse graphs/low propagation probability for this to matter, since it's the one hot loop in this PR that didn't get the checkPeriodically treatment its siblings did.

  • Nit: docs/release-26.9.1.md and the Javadoc/comments are extensive and clearly written, but there's a lot of near-duplication between the PR description, the release note, and the class-level Javadocs added to all four procedure classes. Not a problem, just flagging in case future edits need to keep three-plus copies of the same explanation in sync.

Test coverage

The new Issue6216AlgoWorkKnobBoundsTest (23 tests) is thorough: it covers the domain-minimum rejection for every knob, the int-overflow case independent of the budget, the budget-in-effect and budget-disabled paths, the windowSize clamp equivalence (asserting identical embeddings between a huge window and one equal to walkLength, same seed - a good regression shape that verifies behavior rather than just "doesn't throw"), and both interrupt and command-timeout abort paths including the single-long-walk case that specifically exercises the periodic-vs-per-walk checkpoint placement. The PR description's claim of "17 of 21 existing tests go red on revert" is a good sensitivity signal, though I wasn't able to independently execute mvn in this sandboxed review environment to confirm the build/tests pass - worth confirming CI is green before merge.

Style/process

No System.out/fully-qualified names in new code, final used consistently, no new dependencies, and the PR correctly calls out the mechanical merge conflict expected with #6214 in AbstractAlgoProcedure.

Nice work overall - the "bound by the resource it actually spends" framing is applied consistently across all seven knobs rather than mixing ad-hoc caps.

@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Review cycle 2 - the influenceMaximization checkpoint, checked and left alone

Thanks for tracing the arithmetic by hand - the 4 * 1_073_741_824 == 2^32 -> 0 confirmation and the walk-through of the single-walk timeout test are exactly the parts worth an independent check.

The simulateIC loop: checked, deliberately not converged on checkPeriodically. The review asks the right question - is simulateIC ever cheap enough for an unthrottled clock read to matter - so here is the answer rather than an assertion.

It is not. simulateIC opens with:

final boolean[] activated = new boolean[n];
final int[] queue = new int[n];

Two allocations of size n, both zero-filled by the JVM, on every call. So a simulation is Ω(n) before the cascade does anything, even on an edgeless graph with propagationProbability 0 - there is no sparse-graph or low-p shape that makes it O(1). At n = 1 the clock read is comparable to the call; at any n worth running influence maximization on, the two array fills dominate it by orders of magnitude. And check() only reads the clock when a deadline is configured - the default is one flag test, which is not measurable against two array allocations.

Converging it on checkPeriodically would also make it worse where the deadline matters most: abort latency would become 1024 x O(n + m) cascades, seconds on a large graph. The asymmetry with node2vec's context loop is the point rather than an oversight - that loop's body is O(dim) of flat arithmetic with no allocation and can be a handful of flops, which is what earns it a throttle. The rule the PR applies is "throttle where an iteration can be cheaper than the check", and this loop cannot be.

Worth recording for whoever reads this later: the per-simulation allocation is itself a real cost (simulations x candidates x rounds arrays of size n) and hoisting the two buffers out of the loop with an explicit clear would be a straightforward win. It is pre-existing, unrelated to the knob-bounding this PR is about, and belongs in its own change rather than smuggled into a validation fix.

Doc duplication nit: agreed and noted. The three copies do serve different readers - the release note is the operator's account of what changed and why, the class Javadoc is what an API user sees at the call site, the PR description is the reviewer's. The one that must not drift is the Javadoc, since it states the parameter minimums a caller has to satisfy.

On CI: you flagged not being able to run mvn in the review sandbox. As of now build-and-package, CodeQL, Codacy and the analysis lanes are green; the test lanes (unit-tests, opencypher-tck-tests, slow-unit-tests, integration-tests and the e2e set) are still running and I am watching them. Locally: Issue6216AlgoWorkKnobBoundsTest 24 green, the four touched procedures' own suites 17 green, and the full com.arcadedb.query.opencypher.** unit suite 4400 tests / 0 failures / 0 errors / 13 skipped.

No code changes in this cycle.

@codecov

codecov Bot commented Aug 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.59701% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.07%. Comparing base (d75174c) to head (c2a62bc).

Files with missing lines Patch % Lines
...query/opencypher/procedures/algo/AlgoNode2Vec.java 72.22% 0 Missing and 5 partials ⚠️
...ncypher/procedures/algo/AbstractAlgoProcedure.java 88.88% 2 Missing and 1 partial ⚠️
...rc/main/java/com/arcadedb/GlobalConfiguration.java 66.66% 1 Missing and 1 partial ⚠️
.../query/opencypher/procedures/algo/AlgoMaxKCut.java 60.00% 0 Missing and 2 partials ⚠️
...her/procedures/algo/AlgoInfluenceMaximization.java 83.33% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6222      +/-   ##
==========================================
- Coverage   70.08%   70.07%   -0.01%     
==========================================
  Files        1836     1836              
  Lines      158245   158300      +55     
  Branches    33396    33407      +11     
==========================================
+ Hits       110904   110928      +24     
- Misses      33483    33509      +26     
- Partials    13858    13863       +5     

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

@lvca lvca added this to the 26.9.1 milestone Aug 16, 2026
#6214 landed the embedding-dimension bound for #6065, which is the collision this branch was cut expecting.
Three files conflicted, all of them because both changes are additive in the same place:

- AbstractAlgoProcedure: both added extractors after extractInt(). Kept both, ordered so the three argument
  extractors sit together under the "Argument extractors" header - extractInt(min), then
  extractEmbeddingDimension, then extractCount - with the "Work bounds" section after them.
- AlgoNode2Vec: both rewrote the config-extraction block and the javadoc parameter list. embeddingDimension
  now goes through extractEmbeddingDimension (theirs), the four work knobs through extractInt(min) (ours);
  the javadoc list carries both the 4096 cap and the per-knob minimums.
- docs/release-26.9.1.md: both appended a section. Ordered by merge date, so #6216's goes last.

Also converged AlgoInfluenceMaximization's k on the extractCount() helper #6065 introduced: it is exactly
the saturate-then-reject-negative pair that was written inline here, so the inline form and its now-unused
NumberUtils import are gone. The error message is unchanged, so the regression test binds to the shared
helper without edit.

Verified: Issue6216AlgoWorkKnobBoundsTest 24, Issue6065NumericParameterBoundsTest 12,
CypherCallVectorNeighborsTest 10 and the eight touched procedures' own suites all green together (80 tests),
and the full com.arcadedb.query.opencypher.** unit suite at 4415 tests, 0 failures.
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Conflict with main resolved (#6214 landed)

main merged #6214 (#6065) at 09:05, which is the collision this branch was cut expecting. Merged main in; three files conflicted, all because both changes are additive in the same place.

AbstractAlgoProcedure - both sides added extractors immediately after extractInt, so the conflict was over a shared closing brace, not over behaviour. Kept both, and ordered them so the three argument extractors sit together under the existing // ── Argument extractors ── header: extractInt(value, name, minimum), then extractEmbeddingDimension, then extractCount, with the // ── Work bounds ── section after them. Taking the merge as git left it would have interleaved the extractor group with the work-bound helpers.

AlgoNode2Vec - both sides rewrote the config-extraction block and the javadoc parameter list. Resolved to the union: embeddingDimension goes through extractEmbeddingDimension (#6065's cap), the four work knobs through extractInt(..., minimum) (this PR), and the javadoc list carries both the 4096 cap and the per-knob minimums. Ordering is unchanged, so algo.node2vec({embeddingDimension: 1000000000}) is still rejected by the dimension cap before the walk-memory budget is consulted - #6065's test binds to that message and stays green.

docs/release-26.9.1.md - both appended a section at the end. Ordered by merge date, so #6216's goes last.

One convergence taken while here

AlgoInfluenceMaximization's k now goes through extractCount(). The PR description promised this: the inline saturateToInt + reject-negative pair written here is extractCount, and its message was deliberately worded to match so the two could converge without touching the test. The inline form and its now-unused NumberUtils import are gone; the regression test binds to the shared helper unedited.

AlgoMaxKCut needed no hand-resolution - #6065's rawK/Math.max(2, Math.min(rawK, n)) clamp and this PR's restarts/maxIterations minimums plus checkpoints auto-merged, and both sets of tests pass over the result.

Verification on the merged tree

The PR diff is still the same 8 files; the merge leaked nothing.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

Went through the full diff (GlobalConfiguration, AbstractAlgoProcedure, the four procedures, and the new Issue6216AlgoWorkKnobBoundsTest). This is a careful, well-scoped piece of work overall - focusing on what stood out rather than restating the PR description.

Code quality / design

  • WorkGuard cleanly separates the two abort mechanisms (interrupt + arcadedb.command.timeout) and the two call sites (check() for coarse loops, checkPeriodically() for hot inner loops with a power-of-two mask so the throttle is a single AND). The placement decisions are well-reasoned and specifically justified in comments (e.g. why the node2vec context loop needs its own checkpoint rather than relying on the per-walk one - a window clamped to walkLength makes a single walk O(walkLength^2)).
  • CYPHER_ALGO_MAX_WALK_MEMORY's auto-scaling default follows the exact house pattern already used by QUERY_MAX_HEAP_ELEMENTS_ALLOWED_PER_OP / QUERY_MAX_RANGE_SIZE (same constructor shape, same maxMemory() == Long.MAX_VALUE guard for -Xmx-less JVMs). Good consistency with existing conventions rather than inventing a new mechanism.
  • Using saturating long arithmetic (Math.multiplyExact + catch) to check the walk-buffer estimate before allocating, plus an independent > Integer.MAX_VALUE guard even when the budget is disabled, correctly separates "too much heap" from "physically doesn't fit in a Java array" - these are different failure classes and deserve different messages, which they get.
  • extractInt(value, name, minimum) is a small, well-placed addition next to the existing extractInt/extractCount/extractEmbeddingDimension family, and the choice of negSamples minimum 0 vs. everything else minimum 1 is explained inline.
  • The windowSize clamp-to-walkLength fix is correct and is exactly the kind of clamp that's safe (unlike an embedding dimension, a window wider than the walk is provably equivalent to one equal to the walk) - and it's backed by a same-seed equivalence test rather than just a "doesn't throw" test, which is the right way to validate a clamp.

Potential bugs / correctness

  • AlgoRandomWalk's step loop intentionally has no WorkGuard check (called out explicitly in the PR description: bounded by the walk-memory budget, O(1) per iteration). That's a reasonable tradeoff as stated, but it does mean that if an operator raises arcadedb.cypher.algoMaxWalkMemory substantially (the setting explicitly supports "negative = no limit") and sets arcadedb.command.timeout, a huge steps value is memory-bounded but not time-bounded until the walk completes. Might be worth a one-line callout in the CYPHER_ALGO_MAX_WALK_MEMORY javadoc noting that raising it also raises the worst-case latency of algo.randomWalk, which isn't covered by arcadedb.command.timeout.
  • AlgoInfluenceMaximization calls guard.check() unthrottled inside the simulations loop (not checkPeriodically), while AlgoMaxKCut/AlgoNode2Vec use checkPeriodically for their tightest loops. That's consistent with the reasoning elsewhere in the PR (simulateIC is presumably not O(1), so an unthrottled check is appropriate), but worth double-checking that simulateIC's cost per call can't degenerate to near-O(1) on a sparse/disconnected graph, in which case the same "checkpoint too coarse" argument made for node2vec's context loop could apply here too at large n * simulations.

Test coverage

  • The new test class is thorough: it separately exercises the domain-minimum rejections, the int-overflow-vs-heap-budget distinction (including the "budget disabled but array-size guard still fires" case, which is an easy thing to accidentally couple), the windowSize clamp equivalence, and both abort mechanisms (interrupt-flag-cleared and deadline-exceeded) including the one case a between-walk checkpoint can't catch (node2VecHonoursTheCommandTimeoutInsideOneLongWalk). The PR description's claim of having verified test sensitivity by reverting the four procedure files is exactly the right way to validate a regression suite like this and is good practice worth calling out positively.
  • One gap: there's no test that a simulations/restarts/walksPerNode value that's merely large-but-not-timeout-worthy still completes and produces a sane result under a raised algoMaxWalkMemory budget at meaningful scale. Not blocking since node2VecRunsWhenTheWalkMatrixFitsTheBudget covers the shape of this, just at small scale.

Performance / security

  • No concerns. The design principle (bound by the resource actually spent: domain minimum, heap budget, or cooperative time abort) is sound and matches the project's existing guidance on avoiding a single guessed cap. The default-disabled arcadedb.command.timeout behavior is preserved (guard reads the clock only when a deadline is configured), so there's no behavior change for operators who haven't opted in.
  • Correctly surfaces all new rejections as IllegalArgumentException (client error / HTTP 400) rather than letting them fall through to a 500, consistent with the rest of the allocation-bound work in the two prior issues.

Merge note

  • The PR body flags the expected textual conflict with the related PR in AbstractAlgoProcedure/AlgoNode2Vec/AlgoMaxKCut, and the third commit here already merges main and resolves it (including converging AlgoInfluenceMaximization's k onto the shared extractCount() helper). That merge commit looks clean from the diff.

Nice work overall - the resource-based framing (domain / heap / time) is a clear, defensible policy and the test suite backs it up well.

Codecov flagged the saturation path as uncovered, and it was: saturatingProduct's overflow branch and the
"over Long.MAX_VALUE" arm of the budget message were both written and never exercised. It is reachable
end to end - walksPerNode and walkLength both at Integer.MAX_VALUE over 4 nodes estimate ~7.4e19 bytes
against a long ceiling of 9.2e18.

Worth a test rather than a coverage number: a wrapping multiply can land on a SMALL positive value, which
passes the budget check outright, so this is the one arm where getting the arithmetic wrong defeats the
check instead of merely misreporting it. Confirmed sensitive by replacing multiplyExact with a plain
product, which turns the run red.
@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

Overall this is a well-reasoned, well-tested PR. The "bound each knob by the resource it actually spends" framing is applied consistently in most places, the saturating-long-arithmetic pattern for the walk-matrix estimate is correct and has a dedicated regression test for the saturate-vs-wrap distinction, and the new CYPHER_ALGO_MAX_WALK_MEMORY setting follows the existing queryMaxHeapElementsAllowedPerOp/queryMaxRangeSize auto-scaling pattern exactly. The WorkGuard design (interrupt + arcadedb.command.timeout, throttled via a power-of-two mask, flag cleared not restored) is sound and matches ShortestPathStep's existing convention.

Two things worth a look before merge:

1. negSamples has no WorkGuard check at all (likely bug)

In AlgoNode2Vec.java, the negative-sampling loop is left unguarded:

for (int ctx = winStart; ctx <= winEnd; ctx++) {
  guard.checkPeriodically(ctx);
  ...
  for (int ns = 0; ns < negSamples; ns++) {   // <-- no guard.check()/checkPeriodically() here
    ...
  }
}

negSamples is one of the seven knobs the PR explicitly sets out to bound ("algo.node2vec's walksPerNode, walkLength, windowSize, negSamples" - PR description), and unlike the other three it gets no upper protection whatsoever:

  • No heap ceiling - checkWalkBudget only sizes the walk matrix, not the negative-sample loop.
  • No domain cap - extractInt(n, "negSamples", 0) only enforces a minimum, there's no maximum.
  • No WorkGuard inside the ns loop - the nearest checkpoint is guard.checkPeriodically(ctx), which runs before entering the ns loop, not during it.

With embeddingDimension capped at 4096 but negSamples uncapped at up to Integer.MAX_VALUE, a single (pos, ctx) pair can require on the order of negSamples * dim operations with zero opportunity to observe a thread interrupt or arcadedb.command.timeout for the whole duration - exactly the "checkpoint sits between the unbounded thing, not inside it" bug that commit c2a62bc (second commit in this PR) fixed for windowSize/walkLength. This one seems to have been missed for negSamples. Suggest adding guard.checkPeriodically(ns) inside the loop, and a regression test analogous to node2VecHonoursTheCommandTimeoutInsideOneLongWalk but driven by a large negSamples on a tiny walk/window.

2. AlgoRandomWalk's step loop relies on the memory budget to bound time, but the budget can legitimately be unbounded

The PR notes justify skipping a WorkGuard here: "steps is already bounded by the walk-memory budget and each iteration is O(1)." That holds only while arcadedb.cypher.algoMaxWalkMemory stays near its conservative default. But:

  • The setting is documented as tunable, and "negative = no limit" is a first-class supported value (there's even a test, randomWalkRejectsMoreStepsThanAJavaArrayCanHoldEvenWithTheBudgetDisabled, that disables it) - in that mode steps is bounded only by Integer.MAX_VALUE.
  • Even with the budget left at its default, it auto-scales to maxHeap / 8 with no upper cap, so on a large-heap deployment (tens of GB) the effective steps ceiling approaches Integer.MAX_VALUE anyway.

In either case, a steps value in the high hundreds-of-millions to low billions with O(1)-but-not-free per-step work (array bounds check, Random.nextInt, adjacency lookup) can plausibly run for seconds, ignoring a configured arcadedb.command.timeout entirely - which is inconsistent with the "time is made abortable everywhere" principle this PR establishes for the other three procedures. Given AlgoRandomWalk already has all the pieces (WorkGuard, newWorkGuard) wired up in the sibling procedures, adding guard.checkPeriodically(step) to the step loop looks like a small, consistent fix.

Minor / nits

  • WALK_ROW_OVERHEAD_BYTES = 32 is a reasonable JVM-layout estimate but is inherently approximate (compressed-oops header size varies by JVM flags); worth a one-line acknowledgment in the javadoc that it's a heuristic, not a guarantee, in case someone later "fixes" it to a different number.
  • Test coverage is strong for everything that is guarded (23 focused tests, including the saturation-arithmetic edge case and the "checkpoint inside vs. between loops" case for windowSize) - the gaps above are exactly the two cases that don't have a corresponding timeout test, which is a useful signal pointing at the same gap independently.

No issues with the license/dependency footprint (no new dependencies), the new GlobalConfiguration entry follows house conventions, and I didn't spot any security concerns beyond the availability/DoS-shaped gaps noted above (both are pre-existing-class-of-bug, not newly introduced by this PR - this PR just doesn't fully close them for these two spots).

…a raised budget is not an unabortable one

Review cycle 3. The walk step loop was left unguarded on the argument that the walk-memory budget already
bounds `steps`. It does not bound it as a matter of time, and the setting explicitly accepts "negative = no
limit": with the budget raised or disabled and arcadedb.command.timeout set, a huge steps value was
memory-free and abort-free. The review suggested documenting that caveat in the setting's javadoc; closing
it is the better answer, and it costs one AND and one branch per step.

Measured rather than assumed: algo.randomWalk(a, 500000000) with the budget disabled and a 1ms deadline runs
39.4 SECONDS to completion without the checkpoint and aborts in milliseconds with it. The regression test
asserts exactly that.

Also adds node2VecStillCompletesAndTrainsWithLargeButLegitimateKnobs for the gap the review named: every
other test here proves something is REFUSED, and nothing proved a merely-big run still succeeds at a scale
the small-graph guards do not reach. 200 walks x 50 steps x 20 epochs, asserting the output - one embedding
per node, of the requested width, finite and L2 normalised - rather than the absence of an exception, since
only a training loop that ran to completion produces that.
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Review cycle 3 - two actioned, one answered

algo.randomWalk's unguarded step loop: actioned, and it was worse than the review's framing. The suggestion was a one-line caveat in the CYPHER_ALGO_MAX_WALK_MEMORY javadoc noting that raising the budget also raises an untimeoutable worst case. Documenting a gap is worse than closing it, especially when the gap is "this one setting has a side effect the other three procedures don't", so the step loop now carries guard.checkPeriodically(step) like its siblings. One AND and one branch per step.

The reasoning I had written for leaving it out ("O(1) per iteration, bounded by the budget") was wrong in the way the review identified: a memory bound is not a time bound, and the setting accepts negative = no limit by design. Measured rather than argued - algo.randomWalk(a, 500000000) with the budget disabled and a 1 ms deadline:

wall clock outcome
without the checkpoint 39.4 s runs to completion, deadline never observed
with the checkpoint milliseconds TimeoutException naming arcadedb.command.timeout

randomWalkHonoursTheCommandTimeoutEvenWithTheWalkMemoryBudgetDisabled asserts that, and the 39.4 s figure is what it produces when the checkpoint is removed. The class javadoc now states the guarantee instead of the caveat.

The "large but legitimate at scale" test gap: actioned. Correctly identified - every other test in the class proves something is refused, and node2VecRunsWhenTheWalkMatrixFitsTheBudget only shows the shape at 2 walks of 5 steps. That is the wrong side of the risk this PR carries: it adds rejections and checkpoints to a hot path, so the failure mode worth guarding is refusing or aborting a run that is merely big.

node2VecStillCompletesAndTrainsWithLargeButLegitimateKnobs runs 200 walks x 50 steps x 20 epochs - two orders of magnitude past the defaults used elsewhere in the class - and asserts the output: one embedding per node, of the requested width, every component finite, and L2 norm 1.0 to 1e-9. Only a training loop that ran to completion produces that, so it cannot pass by not throwing.

simulateIC degenerating to near-O(1): answered, no change. Raised in cycle 2 as well, and I checked it against the source rather than assuming. simulateIC opens with new boolean[n] and new int[n], both zero-filled, on every call - so it is Ω(n) before the cascade starts, on any graph shape including empty and disconnected ones at propagationProbability 0. There is no sparse-graph case that makes it O(1).

The two regimes both come out fine, which is why the asymmetry with node2vec is deliberate rather than an oversight:

  • large n - each simulation is Ω(n), so an unthrottled check is free by comparison;
  • small n, large simulations - each simulation is cheap, but then the check happens every simulation, so abort latency is one cheap simulation.

Throttling it to 1024 would degrade the first regime to 1024 x O(n + m) of abort latency, which is where the deadline matters most. The rule the PR applies is "throttle only where an iteration can be cheaper than the check", and this iteration cannot be. (The per-simulation allocation is itself a real cost worth hoisting, but it is pre-existing and belongs in its own change, not smuggled into a validation fix.)

Verification

  • Issue6216AlgoWorkKnobBoundsTest - 27 green (25 + the two above)
  • Full com.arcadedb.query.opencypher.** unit suite - 4418 tests, 0 failures, 0 errors, 13 skipped

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

This has already been through several careful review cycles (int-overflow fixes, the windowSize/O(walkLength²) checkpoint-placement fix, the algo.randomWalk step-loop guard, the merge with #6214) and the design is sound: bounding each knob by the resource it actually spends (domain minimum / heap budget / cooperative time abort) rather than a guessed cap, reusing house patterns (queryMaxHeapElementsAllowedPerOp-style auto-scaling default, ShortestPathStep's interrupt handling). I re-read the current HEAD (612427b) against the diff rather than re-litigating what's already been discussed, and one thing from that discussion is still open in the code as it stands.

negSamples is still unguarded - the earlier review flagged this and it wasn't actioned

A previous review comment on this PR ("### 1. negSamples has no WorkGuard check at all (likely bug)") already identified this, but I don't see it addressed in the "Review cycle 3" response (which covers the algo.randomWalk step loop and the large-scale legitimacy test - both fixed - and simulateIC, answered) or in any commit after that comment landed. Checking the current source confirms the gap is still there, in AlgoNode2Vec.java:

for (int ctx = winStart; ctx <= winEnd; ctx++) {
  guard.checkPeriodically(ctx);
  if (ctx == pos)
    continue;
  final int ctxNode = walk[ctx];
  ...
  for (int ns = 0; ns < negSamples; ns++) {   // no guard.check()/checkPeriodically() here
    ...
  }
}

negSamples is one of the four node2vec knobs named in the PR's own opening line ("algo.node2vec's walksPerNode, walkLength, windowSize, negSamples"), but unlike the other three it only got the domain-minimum treatment (extractInt(n, "negSamples", 0)) - no heap ceiling (fair, it isn't allocation-shaped) and, unlike walksPerNode/walkLength/windowSize, no WorkGuard inside its own loop.

guard.checkPeriodically(ctx) runs before the ns loop for that ctx, not during it, so it doesn't bound the ns loop's own trip count. With negSamples up to Integer.MAX_VALUE, a single (pos, ctx) pair can spin for as long as negSamples dictates with zero opportunity to observe a thread interrupt or arcadedb.command.timeout - this is exactly the "checkpoint sits between the unbounded thing, not inside it" class of bug that the second commit (c2a62bc) fixed for windowSize/walkLength, and that the fifth commit fixed again for algo.randomWalk's step loop. It reads like this one instance was simply missed when those were closed out, not a deliberate exception (nothing in the docs/comments calls out negSamples as an intentional exception the way AlgoInfluenceMaximization's per-simulation guard.check() or algo.maxKCut's per-restart check are explained).

Concretely reachable and untested: CALL algo.node2vec({negSamples: 2000000000}) (defaults otherwise) would hang for a very long time regardless of arcadedb.command.timeout or an interrupt, on a trivially small graph. None of the existing Issue6216AlgoWorkKnobBoundsTest cases exercise negSamples as a work multiplier - the only two tests touching it check the domain minimum and that 0 is accepted.

Suggested fix, consistent with the loop's siblings: guard.checkPeriodically(ns) inside the ns loop, plus a regression test analogous to node2VecHonoursTheCommandTimeoutInsideOneLongWalk but driven by a large negSamples on a small walk/window (so it isolates this loop rather than the already-covered context loop).

Everything else

No new issues beyond what the earlier cycles already surfaced and resolved. Design, docs, and the rest of the test suite (domain minimums, heap-budget saturation arithmetic, the windowSize clamp equivalence test, interrupt/timeout coverage for the other six knobs) look solid. No new dependencies, no System.out, final used consistently, errors correctly surfaced as IllegalArgumentException/TimeoutException (client-error shaped, not a 500). Once the negSamples gap above is closed, this looks ready.

…knob that had no bound of any kind

Review cycle 4. negSamples was named in this PR's own list of seven knobs and then left with no protection
at all: no heap ceiling (the walk budget prices the walk matrix, not the sampling), no maximum (its
extractInt only sets a minimum of 0), and no checkpoint. One (position, context) pair costs
negSamples x embeddingDimension, and the nearest checkpoint sits in the enclosing context loop, which runs
BEFORE the sampling starts - the same "checkpoint outside the unbounded loop" shape already closed here for
windowSize and walkLength. Missed when that fix went in.

The regression test has to assert LATENCY, not just the exception: unlike the walk case the unguarded
version does eventually throw, at the next context checkpoint, once the whole sampling loop has run. Bound
set from measurement - the test method runs in 0.33s with the checkpoint and 24.0s without it, so 5s sits
~16x above the passing case and ~5x below the failing one.

Also documents WALK_ROW_OVERHEAD_BYTES as a heuristic rather than a guarantee: the true per-row cost moves
with the JVM object layout, and the estimate only has to stay in the right order of magnitude, so there is
nothing to "correct" there short of measuring a specific JVM.
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Review cycle 4 - negSamples was genuinely unguarded

This review landed against 00c4a64f6 and crossed with the cycle-3 push, so its point 2 (AlgoRandomWalk's step loop) was already fixed in 612427b36 - independently reaching the same conclusion, including the "negative = no limit is a first-class value, so the budget is not a time bound" argument. Nothing further needed there.

Point 1 is a real miss and is now fixed. negSamples is in this PR's own list of seven knobs and had, as the review says, no protection of any kind:

walkLength / walksPerNode windowSize embeddingDimension negSamples
heap ceiling walk budget - 4096 cap (#6065) none
maximum - clamped to walkLength 4096 none
checkpoint step loop context loop - none

One (position, context) pair costs negSamples x dim with the nearest checkpoint in the enclosing context loop, which runs before the sampling starts. That is precisely the "checkpoint outside the unbounded loop" shape c2a62bc closed for windowSize/walkLength, and I missed this loop when making that fix. guard.checkPeriodically(ns) now sits inside it.

The test needed a different shape, which is worth flagging. For the walk case, "it throws" was a sufficient assertion because the unguarded version ran to completion and never threw. Here it is not: the unguarded version does throw, at the next context checkpoint, once the entire sampling loop has already run. So node2VecHonoursTheCommandTimeoutInsideOneNegativeSamplingLoop asserts latency.

The bound is set from measurement rather than taste. My first attempt used negSamples: 20000000 with a 3 s bound and passed with the checkpoint removed - the loop was faster than I estimated, so the test proved nothing. Re-measured at 200000000:

test method wall clock verdict
with the checkpoint 0.33 s green
without it 24.0 s red, fails the bound

5 s sits ~16x above the passing case and ~5x below the failing one - wide enough not to be a stopwatch on a slow machine, tight enough that it cannot pass while the loop is unabortable.

Nit actioned: WALK_ROW_OVERHEAD_BYTES now says in its javadoc that it is a heuristic, not a guarantee - the true per-row cost moves with the JVM object layout (compressed oops, alignment), the estimate only has to stay in the right order of magnitude, and there is nothing to "correct" there short of measuring a specific JVM. Exactly the drive-by "fix" the review was guarding against.

Verification

  • Issue6216AlgoWorkKnobBoundsTest - 28 green
  • Full com.arcadedb.query.opencypher.** unit suite - 4419 tests, 0 failures, 0 errors, 13 skipped

Every knob in the PR's list now has a checkpoint inside the loop it drives: walk generation (step), Skip-gram context (ctx), negative sampling (ns), maxKCut's per-node scan (i), randomWalk's step loop (step), plus the coarse per-walk / per-pass / per-simulation checks.

@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 18 complexity

Metric Results
Complexity 18

View in Codacy

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.

@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Note on ordering: the negSamples review crossed with its fix

The review above ran against 612427b and re-flagged negSamples. It is already closed in 47dddb557, pushed a couple of minutes later, and the comment immediately preceding this one is the response to it - the reviews and the fixes have been leapfrogging each other for a few cycles now.

Worth recording that the two arrived at the same fix independently: guard.checkPeriodically(ns) inside the sampling loop, plus "a regression test analogous to node2VecHonoursTheCommandTimeoutInsideOneLongWalk but driven by a large negSamples on a small walk/window (so it isolates this loop rather than the already-covered context loop)" - which is exactly the shape of node2VecHonoursTheCommandTimeoutInsideOneNegativeSamplingLoop (walkLength: 2, windowSize: 1, negSamples: 200000000).

The one thing the suggestion does not mention, and which the first attempt at the test got wrong: that analogous test cannot assert only "it throws". The long-walk case is red because the unguarded version completes; the sampling case is not, because the unguarded version does throw at the next context checkpoint, just 24 s late. The assertion has to be on latency, and my first version at negSamples: 20000000 passed with the checkpoint removed before I re-measured and raised it.

HEAD is 47dddb557 and the review of it is in flight. No open points that I am aware of.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

Went through the full diff (GlobalConfiguration, AbstractAlgoProcedure, the three touched procedures, and the new Issue6216AlgoWorkKnobBoundsTest) plus the merged working tree. This is a thorough, well-scoped fix - each of the seven knobs is bounded by the resource it actually spends (domain / heap / time), matching the analysis in the PR description. I did not find any correctness bugs; notes below are mostly confirmations and minor nits.

Correctness

  • The int-overflow fixes are solid: saturatingProduct correctly uses Math.multiplyExact with a saturating catch, totalWalksAsLong/walkCapacity are computed in long before any cast to int, and the pos + window fix in AlgoNode2Vec is also done in long (not just relying on the windowSize clamp), which correctly closes the class of bug rather than just the instance the clamp happens to cover.
  • checkWalkBudget is called before the Integer.MAX_VALUE array-size guard in both AlgoNode2Vec and AlgoRandomWalk. That ordering is fine since the two checks are independent (the budget check catches the common case, the array-size check is a backstop when the budget is disabled with -1), and the new tests exercise both orders explicitly.
  • WorkGuard.checkPeriodically's placement is careful throughout - in particular the negative-sampling loop and the Skip-gram context loop both get their own checkpoint, not just the enclosing walk/epoch loop, which is exactly what's needed since windowSize is clamped to walkLength and can make one walk O(walkLength^2). The regression tests for these two specific gaps (node2VecHonoursTheCommandTimeoutInsideOneLongWalk, ...InsideOneNegativeSamplingLoop) are a nice touch since they assert latency bounds rather than just "eventually throws."
  • GlobalConfiguration.CYPHER_ALGO_MAX_WALK_MEMORY's auto-scaling default follows the exact same pattern as QUERY_MAX_HEAP_ELEMENTS_ALLOWED_PER_OP/QUERY_MAX_RANGE_SIZE (callback-if-not-set, Runtime.getRuntime().maxMemory(), Long.MAX_VALUE guard for unbounded heap). Consistent with house style.
  • Thread.interrupted() (clearing, not isInterrupted()) matches ShortestPathStep's existing convention, as claimed in the docstring.

Minor / non-blocking

  • In AlgoNode2Vec, the Fisher-Yates shuffle of walkOrder at the top of each epoch has no WorkGuard checkpoint of its own. In practice this isn't a real gap since its cost is O(totalWalks), and totalWalks is already bounded by CYPHER_ALGO_MAX_WALK_MEMORY - so it can't grow unboundedly the way the pre-fix windowSize/negSamples loops could. Just flagging for awareness in case a future change decouples totalWalks from that budget.
  • window = Math.min(rawWindow, walkLen) clamps to walkLength rather than walkLength - 1. Harmless since winStart/winEnd are separately clamped to [0, walkLen - 1] right after, but walkLength - 1 would be the "exact" cap if it's ever worth tightening.
  • AlgoInfluenceMaximization's simulation loop calls guard.check() unthrottled (every simulation) rather than checkPeriodically, while the other two procedures throttle to every 1024 iterations. Not a bug (simulations are already non-trivial BFS passes and check() is cheap when no timeout is configured), just a small stylistic inconsistency worth a one-line comment if it was deliberate.

Performance

  • The checkPeriodically throttle (mask on 1023, single AND + branch) is a good choice for the hot inner loops, and the default-disabled-timeout path avoids any System.currentTimeMillis() call, as documented.
  • Saturating-long arithmetic and the up-front budget check mean the common "in-range but abusive" case is rejected before any allocation, rather than after partial work - good for both correctness and avoiding wasted CPU/heap churn.

Security

  • Well-motivated fix for what's effectively an allocation-DoS / unbounded-CPU-DoS surface exposed to any Cypher caller with algo.* access. The heap budget rejection as IllegalArgumentException (client error, HTTP 400) rather than letting it surface as an OutOfMemoryError or crash is the right call.
  • No new dependencies introduced, so no ATTRIBUTIONS.md/license concerns.

Test coverage

  • 23 new tests in Issue6216AlgoWorkKnobBoundsTest covering the domain checks, the heap budget (including the saturation-not-wrap edge case, which is a good catch - a wrapped estimate could pass the budget check outright), the int-overflow backstop with the budget disabled, the windowSize clamp equivalence, and command-timeout/interrupt behavior for all three procedures. The PR description's methodology (reverting to HEAD and confirming 17/21 existing tests go red) is good evidence the tests are actually sensitive to the fix rather than vacuous.
  • One thing worth double-checking in CI: node2VecHonoursTheCommandTimeoutInsideOneNegativeSamplingLoop's 5s latency assertion is derived from measurement on the author's machine (0.33s passing / 24s failing). That's a wide margin, but latency-bound assertions like this are the most likely source of any CI flakiness on a slower/contended runner - worth keeping an eye on if it ever goes red intermittently.

Overall: solid fix, no blocking issues found.

… and the deliberate exceptions say so

Review cycle 5, which found no blocking issues. Two of its three minor notes are actioned; the third is
answered in the code rather than only in a PR comment.

The shuffle note was under-rated. It was called "not a real gap since totalWalks is already bounded by
CYPHER_ALGO_MAX_WALK_MEMORY" - which is the same argument cycle 3 rejected for algo.randomWalk's step loop,
and for the same reason: the budget is tunable and a negative value means no limit, leaving totalWalks capped
only by Integer.MAX_VALUE. Per-epoch that is an unabortable loop. The Fisher-Yates shuffle, the walkOrder
initialisation and the Xavier initialisation now all carry checkpoints, so every O(nodeCount)/O(totalWalks)
loop in the procedure has one and the rule holds without exceptions to remember.

AlgoInfluenceMaximization's unthrottled check() is deliberate and now says so at the call site instead of
only in review replies: simulateIC allocates and zero-fills two arrays of size n before the cascade starts,
so it is never O(1), and throttling would make abort latency 1024 x O(n + m) - worst on the large graphs
where the deadline matters most.

Also records why the window ceiling is walkLen rather than walkLen - 1 (winStart/winEnd are clamped to
[0, walkLen - 1] regardless, and the tighter bound would send windowSize to 0 at walkLength 1, under the
minimum of 1 the extraction enforces), and why the latency assertion's margins are what they are, with the
instruction to raise the bound rather than weaken it to "it throws" - the form that silently passed before.
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Review cycle 5 - no blocking issues; two notes actioned, one answered in the code

The shuffle note was under-rated, and I acted on it as a gap rather than an FYI. It was flagged as "not a real gap since its cost is O(totalWalks), and totalWalks is already bounded by CYPHER_ALGO_MAX_WALK_MEMORY". That is the same argument cycle 3 rejected for algo.randomWalk's step loop, and it fails here for the same reason: the budget is tunable and a negative value means no limit, which leaves totalWalks capped only by Integer.MAX_VALUE. A per-epoch Fisher-Yates over 2^31 entries is an unabortable loop, not a rounding error.

Rather than fix only the loop named, I swept the rest of the procedure by the same rule. The Fisher-Yates shuffle, the walkOrder initialisation and the Xavier initialisation now all carry guard.checkPeriodically(i). Every O(nodeCount) / O(totalWalks) loop in AlgoNode2Vec has a checkpoint now, so the rule holds with no exceptions anyone has to remember - which is the actual fix for "in case a future change decouples totalWalks from that budget".

AlgoInfluenceMaximization's unthrottled check(): deliberate, and now says so at the call site. A fair catch that the reasoning existed only in review replies, where nobody will find it in a year. The comment now states it: simulateIC allocates and zero-fills two arrays of size n before the cascade starts, so it is never O(1) on any graph shape; throttling to 1024 would make abort latency 1024 x O(n + m), worst on exactly the large graphs where the deadline matters most.

window = Math.min(rawWindow, walkLen) vs walkLen - 1: left as is, with the reason recorded. winStart/winEnd are clamped to [0, walkLen - 1] regardless, so the tighter bound is unobservable - and at walkLength: 1 it would drive windowSize to 0, under the minimum of 1 the extraction enforces. Documented so it does not get "tightened" later.

On the latency assertion and CI flakiness. Worth flagging, and the margins are the answer: both figures scale together on a slower runner, so it takes a machine ~15x slower than the reference to push the passing case to 5 s (where the failing case would sit at ~360 s), or ~5x faster to bring the failing case under it. The comment now carries the instruction that matters if it ever does flake: raise the bound, do not weaken it to "it throws" - that form passes with the checkpoint removed, which is exactly how the first version of this test was wrong.

Verification

Full com.arcadedb.query.opencypher.** unit suite - 4419 tests, 0 failures, 0 errors, 13 skipped.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

Went through the full diff (GlobalConfiguration, AbstractAlgoProcedure, the four procedures, and the new Issue6216AlgoWorkKnobBoundsTest). This is a well-scoped, carefully-argued fix, and the PR description's own reasoning (parameter domain / heap / time, one mechanism per resource) checks out against the code. A few notes:

Correctness — looks solid

  • saturatingProduct/checkWalkBudget are only ever called with non-negative operands, and the two-step check (budget, then > Integer.MAX_VALUE) correctly orders "reject as a memory-budget violation" before "reject as exceeding a Java array's capacity," with the array-capacity check still firing independently when the budget is disabled (-1). Traced through the arithmetic for the walksPerNode=Integer.MAX_VALUE, walkLength=Integer.MAX_VALUE case — bytesPerWalk and totalWalksAsLong * bytesPerWalk genuinely need saturation, and Math.multiplyExact + catch is the right tool here (not naive overflow-prone multiplication).
  • WorkGuard: confirmed Thread.interrupted() clears the flag (matches ShortestPathStep/SQLFunctionShortestPath), and that CommandExecutionException/TimeoutException both extend ArcadeDBException rather than NeedRetryException — so an aborted algo call won't get silently retried by the server's auto-retry path and re-burn the same CPU budget.
  • Checked the "small window" case that isn't explicitly covered by a test (negSamples: 0, small windowSize, huge walkLength): since ctx in the Skip-gram inner loop is pos ± window and slides by 1 per pos, the union of per-position [winStart, winEnd] ranges covers [0, walkLen-1] with no gaps whenever window ≥ 1, so checkPeriodically(ctx)'s % 1024 check still fires roughly every 1024 positions even though the ctx loop body itself never runs anywhere near 1024 iterations. Good — that's not an accidental gap.
  • CYPHER_ALGO_MAX_WALK_MEMORY's constructor call (Long.class, default, null, value -> {...}) matches the exact callback/callbackIfNoSet pattern used by QUERY_MAX_HEAP_ELEMENTS_ALLOWED_PER_OP and QUERY_MAX_RANGE_SIZE — same auto-scale-unless-explicitly-set semantics, same heap-unbounded fallback. Good consistency with the house pattern the PR description claims to follow.

Minor / non-blocking

  • AlgoNode2Vec's negative-sampling loop: guard.checkPeriodically(ns) is throttled to "every 1024 iterations," but since ns restarts at 0 on every (pos, ctx) pair, it actually fires unconditionally on the first iteration of every such pair (0 & 1023 == 0). For the default negSamples: 5 that means check() (and, when a command timeout is configured, a System.currentTimeMillis() call) effectively runs once per context pair rather than once per 1024 — redundant with the ctx-level checkpoint immediately above it. Harmless correctness-wise (it only makes aborts more responsive, and Thread.interrupted()/the deadline compare are cheap), and it does matter for the large-negSamples case the regression test targets, so not asking for a change — just flagging that the "every 1024" framing in the comment slightly overstates the throttle for small negSamples.
  • The Javadoc note in CYPHER_ALGO_MAX_WALK_MEMORY and the various procedure-level docs are thorough to the point of being closer to design-doc prose than typical Javadoc; not a problem, just worth knowing that's now the bar for this package if others touch it later.

Test coverage

The new Issue6216AlgoWorkKnobBoundsTest is unusually rigorous for this kind of change — it separately proves the overflow-vs-wrap distinction (saturatingProduct test using multiplyExact rather than assuming coverage is enough), proves the checkpoint placement matters via measured latency (not just "it eventually throws"), and includes over-reach guards (negSamples: 0, in-budget matrix, large-but-legitimate run) so the new checks can't silently start rejecting valid input. The PR description's claim that reverting the four procedure files turns 17/21 pre-existing tests red is a good sanity check on test sensitivity that I'd take at face value given how the rest of the diff reads.

Security/perf

No dependency changes, no System.out debug leftovers spotted, nothing that weakens an existing guarantee. The IllegalArgumentException-vs-500 distinction for the budget check (client error → HTTP 400) is the right call and consistent with how out-of-range params are already handled elsewhere.

Nice piece of work — didn't find anything blocking.

…unter restarts

Review cycle 6, which found nothing blocking. Its one substantive note is that "every 1024 iterations"
overstates the throttle for the negative-sampling loop: ns restarts at 0 for every (position, context) pair,
so the check also fires on the first iteration of each pair.

The behaviour is right and stays - one flag test per pair is what keeps the default negSamples of 5
responsive, because the enclosing ctx checkpoint fires only about once every 1024 POSITIONS when the window
is narrow, not once per pair. What was wrong is the comment, which described a monotonically climbing
counter as though it were the only case. A reader who trusted it would see the ns check as redundant with
the ctx one and delete it, which is the regression this PR just spent a cycle fixing.

Comments only, no functional change.
@lvca

lvca commented Aug 16, 2026

Copy link
Copy Markdown
Member Author

Review cycle 6 - nothing blocking; the throttle comment corrected

Thanks for tracing the walksPerNode=Integer.MAX_VALUE, walkLength=Integer.MAX_VALUE arithmetic and the narrow-window ctx coverage by hand - the second one in particular is the question I would have wanted checked, since checkPeriodically(ctx) looks like it could leave gaps when the ctx loop body is only a few iterations wide, and the sliding-window argument for why it does not is not obvious from the code.

The ns throttle note is right, and the comment was the thing at fault. ns restarts at 0 for every (position, context) pair, so the check fires once per pair rather than once per 1024 samples. The behaviour is correct and stays - one flag test per pair is exactly what keeps the default negSamples: 5 responsive, because as your own analysis shows the enclosing ctx checkpoint fires only about once every 1024 positions when the window is narrow, not once per pair. So the two are not redundant: the ns one is strictly the more frequent, and it is carrying the common case.

What was wrong is that the javadoc described a monotonically climbing counter as though that were the only shape. A reader who trusted it would conclude the ns check is redundant with the ctx one and delete it - which is precisely the regression cycle 4 fixed. checkPeriodically's javadoc and the call site now state the restart case and why it is deliberate. Comments only, no functional change (69ba8ae).

Javadoc verbosity: taken as read. It is heavier than typical because most of it is recording why a bound is where it is - the alternative that was rejected, the measurement behind a constant, the reason a clamp is safe here and would not be elsewhere. That is the part that decays fastest into folklore otherwise, and this PR is on its second round of someone (me included) proposing to "simplify" something that was load-bearing.

Status

Six review cycles: four found something real (checkpoint placement in the Skip-gram context loop, algo.randomWalk's step loop, the negSamples loop, the shuffle/init loops), two found nothing blocking. Every point raised has been either actioned or answered with the reasoning in the code rather than only here.

Full com.arcadedb.query.opencypher.** unit suite at the last functional change: 4419 tests, 0 failures, 0 errors, 13 skipped. Ready for a maintainer's call.

@claude

claude Bot commented Aug 16, 2026

Copy link
Copy Markdown

Review

Reviewed the full diff (7 commits) plus the current state of the touched files. This is a well-scoped, well-tested change: bound each CPU-shaped algo.* knob by the resource it actually spends (domain minimum, heap budget, or cooperative-abort time budget), following the existing house pattern (arcadedb.queryMaxHeapElementsAllowedPerOp, arcadedb.queryMaxRangeSize) for CYPHER_ALGO_MAX_WALK_MEMORY. I didn't find any correctness bugs in the final state — the commit history shows the PR already went through several self-review cycles that closed the gaps I'd normally flag (checkpoint-inside-vs-between-loop, negSamples's missing guard, long arithmetic for the pos + window wrap, saturating-vs-wrapping product, randomWalk's step loop when the budget is disabled).

A few smaller points, none blocking:

1. docs/release-26.9.1.md claims "23 tests"; the file now has 28.
The doc text (added in commit 1) says "New Issue6216AlgoWorkKnobBoundsTest, 23 tests" but grep -c "@Test" on the current file returns 28 (tests were added in review cycles 3–6 without updating the earlier doc/PR-description count). Cosmetic only, but worth a quick pass before merge so the release notes don't undercount.

2. checkWalkBudget vs. the Integer.MAX_VALUE guard fire in a fixed order regardless of which is the "real" reason.
In both AlgoNode2Vec and AlgoRandomWalk, checkWalkBudget(...) runs before the > Integer.MAX_VALUE check. With the default (finite) budget this is unobservable — the budget almost always trips first — but if an operator sets a very large or negative (disabled) budget and a walk count just over Integer.MAX_VALUE with a tiny bytesPerWalk, the message the caller sees is determined by whichever check happens to run first rather than by which limit is "more informative." Not a bug, just a minor ordering note — the tests already pin the behavior for the disabled-budget case, so this is really just a documentation/readability observation, not something to change.

3. WorkGuard.checkPeriodically's throttle is a shared, currently-undocumented contract across call sites.
Each call site passes a different loop-local counter (step, ctx, ns, i), and correctness relies on each such counter's range being large enough to cross a multiple of 1024 within the loop it guards (this is proven true for every current call site, and the comments explain the individual reasoning well). If a future call site reuses checkPeriodically with a counter that stays within a narrow band far from a 1024 boundary for a very long time (e.g., a counter that increments by large strides, or resets to a mid-range value), it could silently defeat the throttle's latency bound. Worth a one-line note on checkPeriodically's javadoc making that precondition explicit (something like "the counter must range over enough contiguous values to guarantee crossing a multiple of 1024") so a future caller doesn't reintroduce the exact "checkpoint outside the unbounded loop" bug this PR spent several cycles closing.

4. Test coverage is thorough and appropriately tagged.
Good use of measured, not guessed, latency bounds (e.g., the negative-sampling timeout test's comment explaining the 5s threshold derivation), and a real "large-but-legitimate-knobs still completes and produces valid output" test alongside all the rejection tests — that's the right shape for a PR that adds this many new rejection paths, since it's easy to over-restrict while fixing a DoS-shaped bug. No @Tag("slow")/@Tag("benchmark") annotations on the class, which seems right since (per the commit messages) these run in well under a second each; only node2VecHonoursTheCommandTimeoutInsideOneNegativeSamplingLoop deliberately measures wall-clock latency, which is a candidate for @Tag("slow") if it turns out flaky on a slow CI runner, but the documented margin (16x/5x) seems to already account for that.

5. AlgoInfluenceMaximization's k message reuse is correct but worth double-checking against #6214 on merge.
The PR notes this converges on extractCount() from #6214/#6065 and that the message text is unchanged so the regression test binds without edits — confirmed, extractCount's message format ("... must not be negative, got " + count) matches the test's expectation. Since both PRs touch AbstractAlgoProcedure and AlgoNode2Vec, it's worth re-running the full algo.* suite once more after whichever of #6214/#6222 lands second, even though the PR states this was already done as of the merge commit.

Overall: solid engineering, clear reasoning trail in the commit history, good test discipline (assertions on latency are justified with measurements rather than arbitrary guesses), and no outstanding correctness or security concerns found.

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.

Unbounded CPU-shaped config knobs in the OpenCypher algo procedures (follow-up to #6065)

1 participant