Skip to content

feat: ivm cache - #4675

Merged
lvrach merged 45 commits into
developfrom
feat.ivmCache2
Oct 3, 2025
Merged

lvrach merged 45 commits into
developfrom
feat.ivmCache2

Conversation

@cisse21

@cisse21 cisse21 commented Sep 24, 2025 •

Copy link
Copy Markdown
Member

What are the changes introduced in this PR?

This PR implements a caching system for ivm instances to improve performance of user transformations. The current implementation creates and destroys IVM instances for every transformation call, which is a costly operation. This optimisation introduces configurable caching strategies to reuse IVM instances.

We introduce IvmCacheManager as a singleton instance which can be used by the client. Also the IvmCacheManager provides all the get and set methods to retrieve cache for a given key, if it returns null it is the responsibility of client to create the ivm and then set it in the cache

What is the related Linear task?

Fixes PIPE-2297

Please explain the objectives of your changes below

Put down any required details on the broader aspect of your changes. If there are any dependent changes, mandatorily mention them here

Any changes to existing capabilities/behaviour, mention the reason & what are the changes ?

N/A

Any new dependencies introduced with this change?

N/A

Any new generic utility introduced or modified. Please explain the changes.

N/A

Any technical or performance related pointers to consider with the change?

N/A

@coderabbitai review


Developer checklist

  • My code follows the style guidelines of this project

  • No breaking changes are being introduced.

  • All related docs linked with the PR?

  • All changes manually tested?

  • Any documentation changes needed with this change?

  • Is the PR limited to 10 file changes?

  • Is the PR limited to one linear task?

  • Are relevant unit and component test-cases added in new readability format?

Reviewer checklist

  • Is the type of change in the PR title appropriate as per the changes?

  • Verified that there are no credentials or confidential data exposed with the changes.

ktgowtham
ktgowtham previously approved these changes Oct 1, 2025

@ktgowtham ktgowtham left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. unfortunately didn't review tests in detail, but will. but from my side, it's not a blocker to try the branch out in a mirroring environment.

Comment thread src/util/ivmFactory.js Resolved
fracasula
fracasula previously approved these changes Oct 1, 2025

@fracasula fracasula left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM, left a few comments mostly optional 👍

Comment thread src/util/ivmCache/strategies/isolate.js Resolved
Comment thread src/util/ivmCache/strategies/isolate.js Resolved
Comment thread src/util/ivmCache/cacheKey.js Resolved
Comment thread src/util/ivmCache/index.js Resolved
@cisse21
cisse21 dismissed stale reviews from fracasula and ktgowtham via d7049cd October 3, 2025 08:20
@cisse21
cisse21 requested review from fracasula and ktgowtham October 3, 2025 08:23
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

1 similar comment
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@sonarqubecloud

sonarqubecloud Bot commented Oct 3, 2025 •

Copy link
Copy Markdown

@cisse21
cisse21 marked this pull request as ready for review October 3, 2025 12:30
@cisse21
cisse21 requested review from a team as code owners October 3, 2025 12:30

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (1)
src/util/prometheus.js (1)

170-178: Populate all declared labels when observing ivm_cache_set_duration.

The histogram is registered with labelNames: ['strategy', 'result'], but the success path only supplies { strategy: 'isolate' }. prom-client treats that as a label mismatch and logs an error on every observe call, so the metric never records data. Please add the missing result label (e.g., 'success') before merging.

-      stats.timing('ivm_cache_set_duration', startTime, {
-        strategy: 'isolate',
-      });
+      stats.timing('ivm_cache_set_duration', startTime, {
+        strategy: 'isolate',
+        result: 'success',
+      });
🧹 Nitpick comments (3)
src/util/ivmCache/manager.js (1)

113-122: Consider conditional success logging.

The success log at line 121 is emitted even when strategy.clear() fails. Consider moving the success log inside the try block or making it conditional on successful completion.

Apply this diff to ensure accurate logging:

   async clear() {
     try {
       await this.strategy.clear();
+      logger.info('IVM cache cleared');
     } catch (error) {
       logger.error('Error clearing cache', {
         error: error.message,
       });
     }
-    logger.info('IVM cache cleared');
   }
src/util/ivmCache/index.js (2)

10-37: Well-configured LRU cache with comprehensive stats.

The constructor properly initializes the LRU cache with sensible defaults and configuration. The use of Number.parseInt aligns with modern JavaScript practices.

The ttlExpiries stat (line 29) is initialized but never incremented in the codebase. Consider removing it if TTL expiry tracking is not currently feasible with the LRU library version, or add a comment explaining its future purpose.


45-69: Robust disposal handling with comprehensive error handling.

The function properly handles cache item disposal with appropriate error handling for both synchronous and asynchronous cleanup failures.

Consider adding a defensive check for the destroy method existence before calling it (line 51):

-      value.destroy().catch((error) => {
+      if (typeof value.destroy === 'function') {
+        value.destroy().catch((error) => {
+          logger.error('Error in async destroy during disposal', {
+            key,
+            reason,
+            error: error.message,
+          });
+        });
+      }
-        logger.error('Error in async destroy during disposal', {
-          key,
-          reason,
-          error: error.message,
-        });
-      });

This provides an additional safety layer if a non-disposable value is accidentally cached.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 24ab4a8 and e8f1e54.

⛔ Files ignored due to path filters (13)
  • package-lock.json is excluded by !**/package-lock.json, !**/*.json
  • package.json is excluded by !**/*.json
  • test/__tests__/data/user_transformation_cache_input.json is excluded by !**/test/**, !**/*.json
  • test/__tests__/data/user_transformation_cache_output.json is excluded by !**/test/**, !**/*.json
  • test/__tests__/ivmCache/cacheKey.test.js is excluded by !**/test/**
  • test/__tests__/ivmCache/contextReset.test.js is excluded by !**/test/**
  • test/__tests__/ivmCache/index.test.js is excluded by !**/test/**
  • test/__tests__/ivmCache/manager.test.js is excluded by !**/test/**
  • test/__tests__/ivmCache/strategies/isolate.test.js is excluded by !**/test/**
  • test/__tests__/user_transformation.test.js is excluded by !**/test/**
  • test/__tests__/user_transformation_cache.test.js is excluded by !**/test/**
  • test/__tests__/user_transformation_errors.test.js is excluded by !**/test/**
  • test/__tests__/user_transformation_fetch.test.js is excluded by !**/test/**
📒 Files selected for processing (9)
  • src/util/customTransformer-v1.js (4 hunks)
  • src/util/customTransformer.js (5 hunks)
  • src/util/ivmCache/cacheKey.js (1 hunks)
  • src/util/ivmCache/contextReset.js (1 hunks)
  • src/util/ivmCache/index.js (1 hunks)
  • src/util/ivmCache/manager.js (1 hunks)
  • src/util/ivmCache/strategies/isolate.js (1 hunks)
  • src/util/ivmFactory.js (10 hunks)
  • src/util/prometheus.js (5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit configuration file

Focus on ESLint errors (max 3) and warnings (max 5).

Files:

  • src/util/customTransformer.js
  • src/util/ivmCache/contextReset.js
  • src/util/ivmCache/strategies/isolate.js
  • src/util/ivmCache/manager.js
  • src/util/prometheus.js
  • src/util/ivmFactory.js
  • src/util/ivmCache/cacheKey.js
  • src/util/ivmCache/index.js
  • src/util/customTransformer-v1.js
🧬 Code graph analysis (8)
src/util/customTransformer.js (2)
src/util/ivmFactory.js (10)
  • ISOLATE_VM_MEMORY (11-11)
  • GEOLOCATION_TIMEOUT_IN_MS (13-16)
  • logString (320-320)
  • fnRef (454-456)
  • logger (7-7)
  • bootstrapScriptResult (415-415)
  • context (196-196)
  • context (486-486)
  • isolate (195-195)
  • isolate (485-485)
src/util/ivmCache/contextReset.js (3)
  • GEOLOCATION_TIMEOUT_IN_MS (42-45)
  • fnRef (212-214)
  • logger (4-4)
src/util/ivmCache/contextReset.js (1)
src/util/utils.js (2)
  • fetchWithDnsWrapper (105-121)
  • extractStackTraceUptoLastSubstringMatch (207-219)
src/util/ivmCache/strategies/isolate.js (2)
src/util/ivmCache/contextReset.js (6)
  • require (1-1)
  • require (6-6)
  • logger (4-4)
  • stats (5-5)
  • cachedIsolateWithResetContext (217-231)
  • module (22-24)
src/util/ivmCache/index.js (3)
  • require (1-1)
  • logger (2-2)
  • stats (3-3)
src/util/ivmCache/manager.js (2)
src/util/ivmFactory.js (8)
  • require (3-3)
  • require (5-5)
  • require (6-6)
  • require (9-9)
  • logger (7-7)
  • cacheKey (562-562)
  • stats (8-8)
  • ivmCacheManager (559-559)
src/util/ivmCache/strategies/isolate.js (3)
  • require (2-2)
  • logger (3-3)
  • stats (4-4)
src/util/prometheus.js (4)
src/util/customTransformer-v1.js (1)
  • tags (116-121)
src/util/customTransformer.js (1)
  • tags (312-316)
src/util/openfaas/index.js (2)
  • tags (111-114)
  • tags (429-436)
src/util/customTransformer-faas.js (1)
  • tags (96-100)
src/util/ivmFactory.js (2)
src/util/customTransformer-v1.js (5)
  • logger (6-6)
  • stats (7-7)
  • require (3-3)
  • require (4-4)
  • require (5-5)
src/util/ivmCache/manager.js (2)
  • logger (3-3)
  • ivmCacheManager (149-149)
src/util/ivmCache/cacheKey.js (2)
src/util/ivmCache/contextReset.js (1)
  • module (22-24)
src/util/ivmFactory.js (2)
  • module (22-22)
  • module (29-31)
src/util/ivmCache/index.js (2)
src/util/ivmCache/strategies/isolate.js (4)
  • require (2-2)
  • logger (3-3)
  • stats (4-4)
  • DisposableCache (1-1)
test/__tests__/ivmCache/index.test.js (1)
  • DisposableCache (125-125)
🔇 Additional comments (25)
src/util/ivmCache/contextReset.js (2)

21-27: LGTM - Clean module loading implementation.

The function correctly compiles and instantiates modules with appropriate filename metadata for debugging.


35-151: Well-structured API injection with comprehensive error handling.

The function properly injects fresh APIs for each execution with appropriate timing metrics, error handling, and validation. The use of Number.parseInt and for...of loops aligns with modern JavaScript practices.

src/util/ivmCache/manager.js (7)

10-40: Clean initialization with appropriate error handling.

The manager correctly initializes the cache strategy and handles cleanup of any existing strategy. The environment-based configuration provides good flexibility.


48-58: LGTM - Proper error handling and logging.

The method correctly wraps the cache key generation with error handling and propagates errors to the caller.


66-77: Appropriate error handling for cache retrieval.

The method correctly delegates to the strategy and returns null on errors, allowing callers to fall back to non-cached creation.


84-93: LGTM - Fire-and-forget caching pattern.

The method correctly implements a fire-and-forget pattern for cache storage, ensuring cache failures don't block the main flow.


99-108: Consistent error handling pattern.

The method follows the same fire-and-forget pattern as set, which is appropriate for cache operations.


128-145: LGTM - Appropriate stats retrieval with error handling.

The method correctly retrieves and augments cache statistics, returning an error object on failure which is suitable for observability endpoints.


148-151: LGTM - Correct singleton pattern.

The singleton instance is properly created and exported for use across the codebase.

src/util/ivmCache/index.js (8)

76-90: LGTM - Clean cache retrieval with proper stats tracking.

The method correctly handles cache hits and misses with appropriate statistics and logging.


97-115: LGTM - Proper handling of cache disabled scenario.

The method correctly handles the case where caching is disabled (maxSize === 0) while still maintaining stats for observability.


121-128: LGTM - Standard delete implementation.

The method correctly removes items from the cache with appropriate stats tracking.


135-137: LGTM - Simple key existence check.

The method correctly delegates to the underlying cache without side effects (TTL not refreshed due to updateAgeOnHas: false).


142-154: LGTM - Complete cache and stats reset.

The method correctly clears the cache and resets all statistics to provide a clean slate.


160-172: LGTM - Comprehensive stats with computed hit rate.

The method correctly calculates cache hit rate with proper zero-division handling and returns all relevant metrics.


178-196: LGTM - Standard accessor methods.

The methods correctly expose cache keys, values, and entries by converting the underlying iterators to arrays.


202-229: LGTM - Comprehensive metrics emission.

The method correctly emits operation-specific counters and a cache size gauge with consistent tagging for observability.

src/util/ivmFactory.js (8)

11-16: LGTM - Consistent use of modern parsing.

The changes to use Number.parseInt with explicit radix align with the codebase modernization across the PR.


65-81: LGTM - Modern iteration patterns.

The use of for...of loops improves readability and aligns with modern JavaScript practices across the codebase.


247-249: LGTM - Proper Headers iteration.

The for...of loop correctly iterates over response headers.


321-323: LGTM - Clean log argument iteration.

The for...of loop improves the log function's readability.


514-532: Enhanced error handling in resource cleanup.

The updated destroy method properly handles resource release with optional chaining and error logging. The approach of releasing resources individually with error containment prevents cascade failures.


459-481: Essential support for context reset functionality.

The addition of moduleSource to the returned isolate object enables the context reset mechanism to recompile modules with fresh contexts. This is a key component of the caching strategy.


679-684: LGTM - Public API expanded appropriately.

The module exports now include getCachedFactory while maintaining backward compatibility with the existing getFactory export.


534-677: Cached factory implementation approved

Confirmed that the cache strategy’s get method resets isolate contexts via createNewContext on cache hits. No further action required.

Comment thread src/util/ivmCache/cacheKey.js Resolved
Comment thread src/util/ivmCache/contextReset.js Resolved
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.

7 participants