Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore/first eval optimisation remove trigger based context #38077

Conversation

dvj1988
Copy link
Contributor

@dvj1988 dvj1988 commented Dec 10, 2024

Description

Tip

Add a TL;DR when the description is longer than 500 words or extremely technical (helps the content, marketing, and DevRel team).

Please also include relevant motivation and context. List any dependencies that are required for this change. Add links to Notion, Figma or any other documents that might be relevant to the PR.

Fixes #Issue Number
or
Fixes Issue URL

Warning

If no issue exists, please create an issue first, and check with the maintainers if the issue is valid.

Automation

/ok-to-test tags="@tag.All"

🔍 Cypress test results

Tip

🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/12257427772
Commit: d08593b
Cypress dashboard.
Tags: @tag.All
Spec:


Tue, 10 Dec 2024 15:04:31 UTC

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced actionNames property in various configurations to enhance action handling.
    • Added new feature flag release_evaluation_scope_cache for improved cache management.
    • Implemented isPropertyAnEntityAction function to check property paths against action names.
  • Bug Fixes

    • Enhanced error handling and logging across multiple sagas and evaluation functions.
  • Documentation

    • Updated test cases to reflect changes in evaluation functions and context management.
  • Refactor

    • Renamed addDataTreeToContext to getDataTreeContext for clarity.
    • Streamlined imports and organization of worker instances for better maintainability.
  • Tests

    • Expanded test coverage for action bindings and widget configurations to ensure robustness.

Copy link
Contributor

coderabbitai bot commented Dec 10, 2024

Walkthrough

The pull request introduces several modifications across multiple files, primarily focusing on enhancing the functionality and testing of the generateDataTreeJSAction function. Key changes include the addition of an actionNames property to various configurations and updates to the evaluation context management. The introduction of new functions and adjustments to existing ones improve error handling and logging. Additionally, several import paths have been updated to streamline the codebase, particularly regarding the evalWorker. Overall, these changes aim to refine the handling of JavaScript actions and improve the evaluation process within the application.

Changes

File Change Summary
app/client/src/ce/entities/DataTree/dataTreeJSAction.test.ts Added actionNames property to expectedConfig in two test cases for generateDataTreeJSAction.
app/client/src/ce/entities/DataTree/dataTreeJSAction.ts Introduced actionNames property in the returned configEntity object of generateDataTreeJSAction.
app/client/src/ce/entities/DataTree/types.ts Added actionNames: string[] to JSActionEntityConfig interface.
app/client/src/ce/entities/FeatureFlag.ts Added new feature flag release_evaluation_scope_cache initialized to false.
app/client/src/ce/workers/Evaluation/Actions.ts Renamed addDataTreeToContext to getDataTreeContext and modified parameter handling and control flow.
app/client/src/ce/workers/Evaluation/evaluationUtils.ts Added isPropertyAnEntityAction function to check if a property path corresponds to an action.
app/client/src/entities/Engine/AppViewerEngine.ts Removed call to waitForFetchEnvironments in loadAppEntities and added action for fetching JavaScript libraries.
app/client/src/index.tsx Added import for initializing worker instance from utils/workerInstances.
app/client/src/sagas/ActionExecution/PluginActionSaga.ts Updated import for evalWorker, refined blob URL handling, and enhanced error handling in action execution logic.
app/client/src/sagas/ActionExecution/geolocationSaga.ts Updated import for evalWorker, introduced sanitizeGeolocationError function, and maintained existing functionality.
app/client/src/sagas/EvalWorkerActionSagas.ts Updated import for evalWorker, added handling for MAIN_THREAD_ACTION.UPDATE_DATATREE in message processing.
app/client/src/sagas/EvaluationsSaga.test.ts Updated import for evalWorker, modified tests to include shouldRespondWithLogs property.
app/client/src/sagas/EvaluationsSaga.ts Replaced GracefulWorkerService with direct reference to evalWorker, updated evaluation request handling.
app/client/src/sagas/JSLibrarySaga.ts Updated import for EvalWorker, enhanced error handling in library installation and uninstallation.
app/client/src/utils/workerInstances.ts Introduced evalWorker instance of GracefulWorkerService.
app/client/src/workers/Evaluation/JSObject/index.ts Changed import for evaluateSync from default to named import.
app/client/src/workers/Evaluation/JSObject/test.ts Updated tests for getUpdatedLocalUnEvalTreeAfterJSUpdates and saveResolvedFunctionsAndJSUpdates to include actionNames.
app/client/src/workers/Evaluation/__tests__/Actions.test.ts Replaced addDataTreeToContext with getDataTreeContext in tests.
app/client/src/workers/Evaluation/__tests__/evaluate.test.ts Replaced evaluate with evaluateSync in tests, adjusted error handling.
app/client/src/workers/Evaluation/__tests__/evaluation.test.ts Expanded WIDGET_CONFIG_MAP and added tests for widget evaluation logic.
app/client/src/workers/Evaluation/evaluate.ts Updated function signatures for evaluateSync and resetWorkerGlobalScope, refined evaluation context handling.
app/client/src/workers/Evaluation/fns/resetWidget.ts Changed import for evaluateSync from default to named import.
app/client/src/workers/Evaluation/handlers/jsLibrary.ts Simplified error messages in ImportError and TernDefinitionError classes.
app/client/src/workers/Evaluation/handlers/workerEnv.ts Updated flags property in WorkerEnv class for type safety.
app/client/src/workers/common/DataTreeEvaluator/index.ts Enhanced evaluation logic with scopeCache parameter and updated method signatures.
app/client/src/workers/common/DataTreeEvaluator/test.ts Added tests for evaluateActionBindings and dependency handling.

Possibly related PRs

Suggested labels

Task, Bug, JS Objects, Javascript Product, Query & JS Pod, High, ok-to-test

Suggested reviewers

  • rishabhrathod01
  • ApekshaBhosale

"In the land of code where functions play,
New properties added, brightening the way.
Tests now embrace the actions anew,
With evalWorker in tow, they pursue.
Errors handled with care, like a gentle breeze,
In this realm of JavaScript, we code with ease!" 🎉


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@dvj1988 dvj1988 marked this pull request as draft December 10, 2024 13:43
@dvj1988 dvj1988 added the ok-to-test Required label for CI label Dec 10, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (5)
app/client/src/ce/workers/Evaluation/Actions.ts (1)

107-109: Correct the comment to reflect the logic

The comment after the if (!isTriggerBased) condition is misleading. Since we're returning EVAL_CONTEXT when isTriggerBased is false, we are skipping the addition of entity functions in sync evaluations. Please update the comment for accuracy.

Apply this diff to fix the comment:

-  // if eval is not trigger based i.e., sync eval then we skip adding entity function to evalContext
+  // Since eval is not trigger-based (sync eval), we return EVAL_CONTEXT without adding entity functions
app/client/src/sagas/EvaluationsSaga.ts (1)

28-28: Importing evalWorker enhances clarity

Replacing GracefulWorkerService with direct evalWorker import simplifies worker usage.

app/client/src/workers/common/DataTreeEvaluator/index.ts (2)

Line range hint 1237-1367: Consider Refactoring Repetitive Scope Cache Code

The code block for setting values into nonTriggerBasedDataTreeContext under the release_evaluation_scope_cache flag is repeated multiple times. Refactoring this into a helper function could improve maintainability.


1479-1479: Update Function Documentation for 'getDynamicValue'

The getDynamicValue function signature now includes the scopeCache parameter. Update the function's JSDoc comments to reflect this change and explain the parameter's purpose.

app/client/src/sagas/EvalWorkerActionSagas.ts (1)

Line range hint 140-160: Consider optimizing the telemetry span usage.

The span creation and ending could be moved into the updateDataTreeHandler to ensure accurate timing of the data tree update operation itself.

-      const rootSpan = startRootSpan("DataTreeFactory.create");
-
       const unEvalAndConfigTree: ReturnType<typeof getUnevaluatedDataTree> =
         yield select(getUnevaluatedDataTree);
-
-      endSpan(rootSpan);

       yield call(updateDataTreeHandler, {
+        rootSpan: startRootSpan("DataTreeFactory.create"),
         evalTreeResponse: workerResponse as EvalTreeResponseData,
         unevalTree: unEvalAndConfigTree.unEvalTree || {},
         requiresLogging: false,
         configTree: unEvalAndConfigTree.configTree,
       });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6e2195c and d08593b.

📒 Files selected for processing (26)
  • app/client/src/ce/entities/DataTree/dataTreeJSAction.test.ts (2 hunks)
  • app/client/src/ce/entities/DataTree/dataTreeJSAction.ts (1 hunks)
  • app/client/src/ce/entities/DataTree/types.ts (1 hunks)
  • app/client/src/ce/entities/FeatureFlag.ts (2 hunks)
  • app/client/src/ce/workers/Evaluation/Actions.ts (3 hunks)
  • app/client/src/ce/workers/Evaluation/evaluationUtils.ts (1 hunks)
  • app/client/src/entities/Engine/AppViewerEngine.ts (0 hunks)
  • app/client/src/index.tsx (1 hunks)
  • app/client/src/sagas/ActionExecution/PluginActionSaga.ts (1 hunks)
  • app/client/src/sagas/ActionExecution/geolocationSaga.ts (1 hunks)
  • app/client/src/sagas/EvalWorkerActionSagas.ts (1 hunks)
  • app/client/src/sagas/EvaluationsSaga.test.ts (1 hunks)
  • app/client/src/sagas/EvaluationsSaga.ts (3 hunks)
  • app/client/src/sagas/JSLibrarySaga.ts (1 hunks)
  • app/client/src/utils/workerInstances.ts (1 hunks)
  • app/client/src/workers/Evaluation/JSObject/index.ts (1 hunks)
  • app/client/src/workers/Evaluation/JSObject/test.ts (1 hunks)
  • app/client/src/workers/Evaluation/__tests__/Actions.test.ts (2 hunks)
  • app/client/src/workers/Evaluation/__tests__/evaluate.test.ts (6 hunks)
  • app/client/src/workers/Evaluation/__tests__/evaluation.test.ts (0 hunks)
  • app/client/src/workers/Evaluation/evaluate.ts (5 hunks)
  • app/client/src/workers/Evaluation/fns/resetWidget.ts (1 hunks)
  • app/client/src/workers/Evaluation/handlers/jsLibrary.ts (1 hunks)
  • app/client/src/workers/Evaluation/handlers/workerEnv.ts (1 hunks)
  • app/client/src/workers/common/DataTreeEvaluator/index.ts (16 hunks)
  • app/client/src/workers/common/DataTreeEvaluator/test.ts (2 hunks)
💤 Files with no reviewable changes (2)
  • app/client/src/entities/Engine/AppViewerEngine.ts
  • app/client/src/workers/Evaluation/tests/evaluation.test.ts
✅ Files skipped from review due to trivial changes (1)
  • app/client/src/workers/Evaluation/JSObject/index.ts
🔇 Additional comments (28)
app/client/src/ce/workers/Evaluation/Actions.ts (1)

Line range hint 43-54: Function renaming and parameter adjustments look good

The renaming of addDataTreeToContext to getDataTreeContext and the updated parameters enhance clarity.

🧰 Tools
🪛 Biome (1.9.4)

[error] 58-58: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)

app/client/src/workers/Evaluation/evaluate.ts (3)

Line range hint 106-119: Exporting resetWorkerGlobalScope improves modularity

Making resetWorkerGlobalScope an exported function enhances its reusability across modules.


276-284: Refactored context creation is appropriate

The introduction of getDataTreeContext for creating the evaluation context simplifies the code and promotes consistency.


Line range hint 369-426: Ensure EVAL_CONTEXT is correctly populated in evaluateSync

The restructuring of evaluateSync to initialize and populate EVAL_CONTEXT may affect existing functionality. Verify that all necessary data is included and that there are no side effects.

app/client/src/sagas/EvaluationsSaga.ts (1)

297-298: Assess the impact of waitForFetchEnvironments on evaluation timing

Introducing waitForFetchEnvironments may affect the evaluation flow. Ensure it does not introduce unwanted delays.

app/client/src/sagas/ActionExecution/PluginActionSaga.ts (2)

105-106: Updated imports align with worker instances

Importing evalWorker from utils/workerInstances standardizes worker references.


Line range hint 397-398: Review new file upload functions for correctness

The addition of triggerFileUploadInstrumentation, clearTriggerActionResponse, and softRefreshActionsSaga functions should be thoroughly tested to ensure correct integration.

app/client/src/workers/common/DataTreeEvaluator/index.ts (1)

1068-1069: Verify 'resetWorkerGlobalScope()' Usage

Ensure that invoking resetWorkerGlobalScope() here does not unintentionally affect the evaluation context, especially in concurrent scenarios.

app/client/src/utils/workerInstances.ts (1)

1-13: Initialization of 'evalWorker' Instance

The creation of the evalWorker instance using GracefulWorkerService is correct. Ensure that the worker script at the specified path is accessible and the worker functions as intended.

app/client/src/workers/Evaluation/handlers/workerEnv.ts (1)

4-4: Enhance Type Safety for 'flags' Property

Defining flags with the FeatureFlags type adds type safety to the WorkerEnv class. This change improves code reliability and maintainability.

app/client/src/ce/entities/DataTree/dataTreeJSAction.ts (1)

92-92: Include 'actionNames' in JSActionEntity Config

Adding actionNames to the JSActionEntityConfig provides direct access to the names of actions, which can enhance code clarity and usability.

app/client/src/ce/entities/FeatureFlag.ts (1)

46-46: LGTM! Verify feature flag usage.

The feature flag follows the naming convention and is properly configured.

Also applies to: 85-85

✅ Verification successful

Feature flag is properly implemented and used

The feature flag is correctly used in DataTreeEvaluator for controlling scope cache functionality:

  • Defined in FeatureFlag.ts with proper typing and default value (false)
  • Consistently used in DataTreeEvaluator for conditional cache operations
  • Implementation follows the gradual rollout pattern with feature flag checks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the usage of the new feature flag across the codebase
rg "release_evaluation_scope_cache" --type ts --type tsx

Length of output: 84


Script:

#!/bin/bash
# Search for the feature flag usage with ripgrep, without file type filtering
rg "release_evaluation_scope_cache"

# Also search with ast-grep to find any TypeScript/JavaScript usage
ast-grep --pattern 'release_evaluation_scope_cache'

Length of output: 895


Script:

#!/bin/bash
# Let's check the context of usage in DataTreeEvaluator
rg "release_evaluation_scope_cache" app/client/src/workers/common/DataTreeEvaluator/index.ts -B 2 -A 2

Length of output: 1088

app/client/src/index.tsx (1)

3-4: LGTM! Worker initialization properly placed.

Early initialization of worker instances ensures they're available throughout the application lifecycle.

app/client/src/sagas/ActionExecution/geolocationSaga.ts (2)

8-8: LGTM! Import path updated for consistency.

The evalWorker import now comes from the centralized worker instances.


Line range hint 73-78: LGTM! Error handling improved for worker thread compatibility.

The sanitizeGeolocationError function properly handles GeolocationPositionError serialization for worker thread communication.

app/client/src/sagas/EvalWorkerActionSagas.ts (1)

18-18: LGTM!

The import path standardization improves code organization.

app/client/src/ce/entities/DataTree/types.ts (1)

99-99: LGTM!

The addition of actionNames array provides type safety for tracking JS action names.

app/client/src/workers/Evaluation/JSObject/test.ts (1)

216-216: LGTM!

The test data update properly validates the handling of action names, including the duplicate action scenario.

app/client/src/workers/Evaluation/fns/resetWidget.ts (1)

18-18: Verify import usage across the codebase

The change from default to named imports could affect other modules importing from "../evaluate".

✅ Verification successful

Let me search with a broader pattern to check both named imports and their usage. The first command will find any named imports of these functions, and the second will find their actual usage in the code.


Import change is consistent with codebase usage

All imports of evaluateSync and setEvalContext are using named imports from the evaluate module. The change aligns with the existing usage pattern across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining default imports of evaluate
rg "import\s+evaluateSync\s+from\s+['\"].*evaluate['\"]"

Length of output: 62


Script:

#!/bin/bash
# Search for imports of evaluateSync and setEvalContext with broader pattern
rg "import.*\{.*(?:evaluateSync|setEvalContext).*\}.*from.*evaluate"

# Search for usage of these functions
rg "(?:evaluateSync|setEvalContext)\("

Length of output: 3433

app/client/src/sagas/EvaluationsSaga.test.ts (1)

6-6: LGTM: Centralized worker instance import

The change aligns with the centralization of worker instances, improving maintainability.

app/client/src/ce/entities/DataTree/dataTreeJSAction.test.ts (1)

194-194: LGTM: Test coverage for actionNames property

The test cases correctly validate the new actionNames configuration property.

Also applies to: 393-393

app/client/src/sagas/JSLibrarySaga.ts (1)

24-24: LGTM: Import path change looks good.

The centralization of worker instances improves maintainability.

✅ Verification successful

Import change is correctly implemented and safe

The import change is part of a proper refactoring where:

  • The evalWorker is now centralized in utils/workerInstances
  • All relevant files (5 files found) are consistently using the new import path
  • The EvaluationsSaga file still exists and is used for other purposes, but worker initialization has been correctly moved
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify no broken imports exist for evalWorker
rg -g '!*.test.*' -g '!*.d.ts' "import.*evalWorker.*from.*EvaluationsSaga"

Length of output: 76


Script:

#!/bin/bash
# Let's verify the new import path exists and is being used correctly
rg -g '!*.test.*' -g '!*.d.ts' "import.*evalWorker.*from.*['\"]utils/workerInstances['\"]"

# Check if there are any remaining references to EvaluationsSaga
rg -g '!*.test.*' -g '!*.d.ts' "EvaluationsSaga"

# Verify the structure of the worker instances file
fd -g 'workerInstances.{ts,js}' -x cat {}

Length of output: 3017

app/client/src/workers/Evaluation/__tests__/Actions.test.ts (2)

9-9: LGTM: New import aligns with the optimization goals.


551-557: Great improvement: Moving to immutable context creation.

The change from mutation-based to functional approach reduces side effects and improves code predictability.

app/client/src/workers/Evaluation/handlers/jsLibrary.ts (2)

36-36: LGTM: Simplified error message.

Direct template literal improves maintainability by removing message constant dependency.


44-44: LGTM: Consistent error message simplification.

Follows the same pattern of using template literals for error messages.

app/client/src/workers/common/DataTreeEvaluator/test.ts (1)

771-771: LGTM: Test configuration updated correctly

The actionNames arrays are properly added to both JSObject configs to support testing the new isPropertyAnEntityAction function.

Also applies to: 825-825

app/client/src/workers/Evaluation/__tests__/evaluate.test.ts (1)

1-1: No changes to review in this file

Comment on lines +1108 to +1118
export const isPropertyAnEntityAction = (
entity: DataTreeEntity,
propertyPath: string,
entityConfig: DataTreeEntityConfig,
) => {
if (!isJSAction(entity)) return false;

const { actionNames } = entityConfig as JSActionEntityConfig;

return actionNames.includes(propertyPath);
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add type safety checks for actionNames access

The function should verify that entityConfig is a JSActionEntityConfig before accessing actionNames to prevent runtime errors.

 export const isPropertyAnEntityAction = (
   entity: DataTreeEntity,
   propertyPath: string,
   entityConfig: DataTreeEntityConfig,
 ) => {
   if (!isJSAction(entity)) return false;
 
+  if (!isJSActionConfig(entityConfig)) return false;
+
   const { actionNames } = entityConfig as JSActionEntityConfig;
 
   return actionNames.includes(propertyPath);
 };

Committable suggestion skipped: line range outside the PR's diff.

@dvj1988 dvj1988 closed this Dec 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ok-to-test Required label for CI
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant