Skip to content

[NAE-2449] ActionDelegate memory leak causes OOM - #452

Merged
machacjozef merged 6 commits into
release/7.0.0-rev10from
NAE-2449
Jun 16, 2026
Merged

machacjozef merged 6 commits into
release/7.0.0-rev10from
NAE-2449

Conversation

@renczesstefan

@renczesstefan renczesstefan commented Jun 11, 2026 •

Copy link
Copy Markdown
Member

Description

Refactor action handling logic and improve memory management in FieldActionsRunner and related classes.

Fixes NAE-2449

Dependencies

No new dependencies were introduced

Third party dependencies

No new dependencies were introduced

Blocking Pull requests

There are no dependencies on other PR

How Has Been This Tested?

This was tested manually and with unit tests.

Test Configuration

Name Tested on
OS macOS Tahoe 26.3
Runtime Java 21
Dependency Manager Maven 3.9.9n
Framework version Spring Boot 3.4.4
Run parameters
Other configuration

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • My changes have been checked, personally or remotely, with @machacjozef
  • I have commented my code, particularly in hard-to-understand areas
  • I have resolved all conflicts with the target branch of the PR
  • I have updated and synced my code with the target branch
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing tests pass locally with my changes:
    • Lint test
    • Unit tests
    • Integration tests
  • I have checked my contribution with code analysis tools:
  • I have made corresponding changes to the documentation:
    • Developer documentation
    • User Guides
    • Migration Guides

Summary by CodeRabbit

  • Bug Fixes
    • Corrected a method name typo in action execution logic.
  • Refactor
    • Improved memory management by clearing action-related state after execution and cleaning up temporary Groovy closure metadata.
    • Enhanced performance by caching the Groovy shell instance for reuse.
    • Restructured action execution to support dynamic method invocation with overload resolution and safer closure preparation/cleanup.
  • New Features
    • Added function/namespace support for process-scoped calls using dynamic expando behavior, including overload-aware dispatch.

Refactor action handling logic and improve memory management in FieldActionsRunner and related classes.
@renczesstefan renczesstefan self-assigned this Jun 11, 2026
@coderabbitai

coderabbitai Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@renczesstefan, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 31 minutes and 37 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: ddff0e33-6ba4-4ea6-9b05-7fae65a26667

📥 Commits

Reviewing files that changed from the base of the PR and between 56ec1f7 and 004e9fb.

📒 Files selected for processing (1)
  • application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/FieldActionsRunner.groovy

Walkthrough

Introduces DelegateExpando and FunctionExpando as a new overload-capable dynamic dispatch layer for Groovy action closures, backed by a new ClosureSignatureMatcher reflection utility. ActionDelegate is updated to extend DelegateExpando and gains a post-execution cleanup method. FieldActionsRunner is refactored to use the expando system with a finally-based cleanup flow and direct property assignment instead of metaClass mutations. GroovyShellFactory gains lazy singleton shell caching.

Changes

Expando-Based Action Dispatch and Cleanup

Layer / File(s) Summary
ClosureSignatureMatcher reflection utility
application-engine/src/main/java/com/netgrif/application/engine/utils/ClosureSignatureMatcher.java
New utility with a static matches() method that reflects over a Closure's doCall overloads, checking argument count and non-null type assignability. Includes wrapPrimitive() helper to convert primitive parameter types to boxed equivalents.
DelegateExpando dynamic dispatch
application-engine/src/main/groovy/.../expando/DelegateExpando.groovy
Extends Expando with an ordered functionMap that accumulates closure overloads per method name. Overrides setProperty to append rather than replace closures, and methodMissing to normalize arguments, select the first ClosureSignatureMatcher-matched closure, and execute it with cloned DELEGATE_FIRST resolution.
FunctionExpando namespace delegation
application-engine/src/main/groovy/.../expando/FunctionExpando.groovy
Extends DelegateExpando with an ActionDelegate parentDelegate field for execution context. Overrides getDelegate() to return parentDelegate, and methodMissing to resolve function closures first via super, then fall back to parentDelegate.invokeMethod when no match is found.
ActionDelegate extends DelegateExpando with cleanup
application-engine/src/main/groovy/.../action/ActionDelegate.groovy
Updates ActionDelegate to extend DelegateExpando. Adds clearAfterExecution() method that nulls all internal references (action, useCase, task, actionsRunner, Frontend, NaeModule, Plugin) and clears map and outcomes collections.
FieldActionsRunner refactoring, cleanup helpers, and GroovyShell caching
application-engine/src/main/groovy/.../action/FieldActionsRunner.groovy, application-engine/src/main/java/.../event/GroovyShellFactory.java
FieldActionsRunner imports FunctionExpando and fixes the getActionDelegate() typo. The run method adds outcomes capture and a finally block that invokes cleanUp. getActionCode replaces metaClass mutations with direct property assignment for cached functions and FunctionExpando wrapping for global functions. New private helpers: clearGroovyMetaClass removes metaClass entries, prepareCode rehydrates closures with DELEGATE_FIRST, and cleanUp clears action-delegate and metaClass state. GroovyShellFactory implements lazy initialization with double-checked locking and caches a single GroovyShell instance.

Sequence Diagram(s)

sequenceDiagram
  participant Script as Action Script
  participant FAR as FieldActionsRunner
  participant AD as ActionDelegate
  participant FE as FunctionExpando
  participant CSM as ClosureSignatureMatcher

  Script->>FAR: run(action, useCase, task)
  FAR->>FAR: getActionCode() — assign functions as properties, wrap globals in FunctionExpando
  FAR->>AD: setProperty(name, closure) [accumulate overloads]
  FAR->>AD: prepareCode(closure, delegate)
  FAR->>AD: closure.call()
  
  rect rgba(200, 150, 100, 0.5)
  Note over FAR: Action invokes function
  Script->>FE: functionName(args)
  FE->>AD: super.methodMissing
  AD->>CSM: matches(closure, args)
  CSM-->>AD: true/false
  alt match found
    AD-->>Script: execute matched closure
  else no match
    FE->>AD: invokeMethod fallback
    AD-->>Script: result
  end
  end

  Note over FAR: finally block
  FAR->>AD: clearAfterExecution()
  FAR->>FAR: clearGroovyMetaClass(delegate, functionExpando)
  FAR-->>Script: outcomes returned
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: fixing an ActionDelegate memory leak causing OOM errors, which is the primary objective of this PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Introduce FunctionExpando as a lightweight proxy for scoped global functions,
delegating property and method access to the parent ActionDelegate while
rehydrating cached function closures only when invoked.

Replace eager global function rehydration in FieldActionsRunner with lazy
FunctionExpando-based binding to reduce heap usage during action preparation.
…cher to support dynamic method invocation and improve closure signature matching.
@renczesstefan
renczesstefan marked this pull request as ready for review June 15, 2026 07:14
@coderabbitai coderabbitai Bot added bugfix A change that fixes a bug Large labels Jun 15, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/expando/FunctionExpando.groovy`:
- Around line 117-122: The methodMissing function in FunctionExpando catches all
MissingMethodException instances from super.methodMissing(), but this
incorrectly catches exceptions thrown from inside the closure body when it calls
undefined methods on parentDelegate. The catch block should only handle the case
where the method itself is not found in the parent, not exceptions occurring
during closure execution. Restructure the exception handling to distinguish
between "method not found" failures versus "method found but raised exception
during execution" scenarios, so that MissingMethodExceptions originating from
within the executed closure are allowed to propagate rather than being caught
and rerouted to parentDelegate.invokeMethod().

In
`@application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/FieldActionsRunner.groovy`:
- Around line 68-70: In the FieldActionsRunner.groovy finally block where
outcomes are captured at line 69, add a null check before dereferencing
code.delegate.outcomes to guard against NPE. Check that both code.delegate
exists and that outcomes have been allocated before assigning them to the
ArrayList, ensuring that if code.init(...) fails before outcomes are
initialized, the finally block safely handles this case without throwing a
NullPointerException that would mask the original exception. This protects the
exception handling flow in the overall try-finally structure.

In
`@application-engine/src/main/java/com/netgrif/application/engine/event/GroovyShellFactory.java`:
- Around line 26-35: The lazy initialization of the shell field in
GroovyShellFactory lacks thread-safety guarantees. To fix this, declare the
shell field as volatile to ensure proper memory visibility across threads, and
wrap the entire null-check and initialization block (lines 26-35) in a
synchronized block using a lock object (typically synchronized on this or a
dedicated lock). This prevents multiple threads from simultaneously entering the
initialization block, which would otherwise cause duplicate ImportCustomizer
additions to configuration and non-deterministic shell publication across memory
barriers.

In
`@application-engine/src/main/java/com/netgrif/application/engine/utils/ClosureSignatureMatcher.java`:
- Around line 49-51: In the ClosureSignatureMatcher class, the loop iterating
through params needs to handle the case where params[i] is a primitive type.
Before calling isAssignableFrom on params[i], add logic to check if the
parameter is a primitive type, and if so, wrap it with its boxed equivalent
(e.g., int becomes Integer, long becomes Long). Additionally, when a parameter
is primitive and the corresponding args[i] is null, mark the match as false
immediately since primitives cannot accept null values. This ensures that when a
Groovy closure expects primitive parameters but receives boxed arguments at
runtime, the assignability check correctly evaluates to true, allowing valid
closure overloads to be properly matched.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3285a8ed-1bf2-4b9a-8ebd-742995b92594

📥 Commits

Reviewing files that changed from the base of the PR and between 39e1172 and fc5e125.

📒 Files selected for processing (6)
  • application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/ActionDelegate.groovy
  • application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/FieldActionsRunner.groovy
  • application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/expando/DelegateExpando.groovy
  • application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/expando/FunctionExpando.groovy
  • application-engine/src/main/java/com/netgrif/application/engine/event/GroovyShellFactory.java
  • application-engine/src/main/java/com/netgrif/application/engine/utils/ClosureSignatureMatcher.java

@machacjozef
machacjozef requested a review from mazarijuraj June 15, 2026 10:45
mazarijuraj
mazarijuraj previously approved these changes Jun 15, 2026
…fety; improve error handling in FunctionExpando; enhance memory management in FieldActionsRunner; and add primitive type wrapping to ClosureSignatureMatcher.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
application-engine/src/main/java/com/netgrif/application/engine/utils/ClosureSignatureMatcher.java (2)

39-39: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Update @param javadoc to reflect null rejection for primitive parameters.

The @param documentation states "null values in the array are considered compatible with any parameter type", but the implementation correctly rejects null when the corresponding parameter is primitive.

📝 Proposed javadoc fix
  * `@param` args the array of arguments to match against the closure's signature;
- *             null values in the array are considered compatible with any parameter type
+ *             null values are compatible with reference parameter types but not with primitive parameter types
  * `@return` {`@code` true} if at least one {`@code` doCall} method in the closure matches the provided arguments;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@application-engine/src/main/java/com/netgrif/application/engine/utils/ClosureSignatureMatcher.java`
at line 39, Update the `@param` javadoc documentation in the
ClosureSignatureMatcher class to accurately reflect the null handling behavior.
The current documentation incorrectly states that null values are compatible
with any parameter type, but the implementation actually rejects null values
when the corresponding parameter is primitive. Revise the javadoc to clarify
that null values are only compatible with non-primitive (object) parameter
types, and that null is rejected for primitive parameters.

33-33: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Update javadoc to reflect null rejection for primitive parameters.

The documentation states "Null arguments are allowed for any parameter type", but the implementation (lines 52-54) correctly rejects null arguments when the corresponding parameter is primitive. Primitive types cannot accept null values in Java.

📝 Proposed javadoc fix
  *   <li>The parameter count matches the argument count</li>
  *   <li>Each argument's type is assignable to the corresponding parameter type</li>
- *   <li>Null arguments are allowed for any parameter type</li>
+ *   <li>Null arguments are allowed for reference parameter types but rejected for primitive parameter types</li>
  * </ul>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@application-engine/src/main/java/com/netgrif/application/engine/utils/ClosureSignatureMatcher.java`
at line 33, The javadoc comment in ClosureSignatureMatcher.java at line 33
incorrectly states that null arguments are allowed for any parameter type, but
the actual implementation in the validation logic (lines 52-54) correctly
rejects null arguments for primitive parameters since Java primitives cannot be
null. Update the javadoc comment to clarify that null arguments are allowed only
for non-primitive parameter types, while primitive parameter types do not accept
null values.
application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/FieldActionsRunner.groovy (1)

131-134: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add defensive guard consistent with finally block.

cleanUp unconditionally casts code.delegate to ActionDelegate (line 132), but the finally block at lines 69-70 defensively checks code?.delegate instanceof ActionDelegate before accessing it. If code.delegate is unexpectedly null or not an ActionDelegate, this throws an exception that masks the original error.

🛡️ Proposed fix for consistency
 private void cleanUp(Closure code) {
-    ((ActionDelegate) code.delegate).clearAfterExecution()
+    if (code?.delegate instanceof ActionDelegate) {
+        ((ActionDelegate) code.delegate).clearAfterExecution()
+    }
     clearGroovyMetaClass(code)
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/FieldActionsRunner.groovy`
around lines 131 - 134, The cleanUp method unconditionally casts code.delegate
to ActionDelegate without defensive checking, which is inconsistent with the
finally block that defensively checks code?.delegate instanceof ActionDelegate
before accessing it. Add a guard condition in the cleanUp method before calling
clearAfterExecution() on the cast delegate, checking if code and code.delegate
exist and that code.delegate is actually an instance of ActionDelegate, similar
to the pattern used in the finally block. Only execute the clearAfterExecution()
call when this condition is satisfied, ensuring defensive consistency and
preventing exceptions that could mask original errors.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In
`@application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/FieldActionsRunner.groovy`:
- Around line 131-134: The cleanUp method unconditionally casts code.delegate to
ActionDelegate without defensive checking, which is inconsistent with the
finally block that defensively checks code?.delegate instanceof ActionDelegate
before accessing it. Add a guard condition in the cleanUp method before calling
clearAfterExecution() on the cast delegate, checking if code and code.delegate
exist and that code.delegate is actually an instance of ActionDelegate, similar
to the pattern used in the finally block. Only execute the clearAfterExecution()
call when this condition is satisfied, ensuring defensive consistency and
preventing exceptions that could mask original errors.

In
`@application-engine/src/main/java/com/netgrif/application/engine/utils/ClosureSignatureMatcher.java`:
- Line 39: Update the `@param` javadoc documentation in the
ClosureSignatureMatcher class to accurately reflect the null handling behavior.
The current documentation incorrectly states that null values are compatible
with any parameter type, but the implementation actually rejects null values
when the corresponding parameter is primitive. Revise the javadoc to clarify
that null values are only compatible with non-primitive (object) parameter
types, and that null is rejected for primitive parameters.
- Line 33: The javadoc comment in ClosureSignatureMatcher.java at line 33
incorrectly states that null arguments are allowed for any parameter type, but
the actual implementation in the validation logic (lines 52-54) correctly
rejects null arguments for primitive parameters since Java primitives cannot be
null. Update the javadoc comment to clarify that null arguments are allowed only
for non-primitive parameter types, while primitive parameter types do not accept
null values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 904a3215-dce9-4a6b-9978-fbf0145a11b7

📥 Commits

Reviewing files that changed from the base of the PR and between fc5e125 and a42c5d7.

📒 Files selected for processing (4)
  • application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/FieldActionsRunner.groovy
  • application-engine/src/main/groovy/com/netgrif/application/engine/petrinet/domain/dataset/logic/action/expando/FunctionExpando.groovy
  • application-engine/src/main/java/com/netgrif/application/engine/event/GroovyShellFactory.java
  • application-engine/src/main/java/com/netgrif/application/engine/utils/ClosureSignatureMatcher.java

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 15, 2026
Retoocs
Retoocs previously approved these changes Jun 15, 2026
@renczesstefan
renczesstefan dismissed stale reviews from Retoocs and coderabbitai[bot] via 56ec1f7 June 16, 2026 09:51
@renczesstefan
renczesstefan requested a review from Retoocs June 16, 2026 09:54
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 16, 2026
Retoocs
Retoocs previously approved these changes Jun 16, 2026
machacjozef
machacjozef previously approved these changes Jun 16, 2026
@renczesstefan
renczesstefan dismissed stale reviews from machacjozef and Retoocs via 004e9fb June 16, 2026 10:20
@machacjozef
machacjozef merged commit 41e0442 into release/7.0.0-rev10 Jun 16, 2026
4 of 5 checks passed
@machacjozef
machacjozef deleted the NAE-2449 branch June 16, 2026 10:49
@coderabbitai coderabbitai Bot mentioned this pull request Jun 30, 2026
5 of 18 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Aug 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bugfix A change that fixes a bug Large

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants