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

BAL-3498: enhance rule-engine evaluation logic with path comparison #3069

Merged
merged 7 commits into from
Feb 20, 2025

Conversation

shanegrouber
Copy link
Collaborator

@shanegrouber shanegrouber commented Feb 19, 2025

Summary by CodeRabbit

  • New Features
    • Improved rule processing to deliver more robust value extraction and advanced comparison handling.
    • Added a new property for indicating path-based comparisons in specific rule operators.
    • Enhanced rule engine tests with support for path comparisons.
  • Refactor
    • Enhanced internal rule validation logic for clearer, more consistent evaluation.
  • Chores
    • Updated internal migration settings to support ongoing system maintenance.

- Introduce isPathComparison flag in Rule schema for clearer distinction
- Update extractValue method to handle operators with and without path comparison
- Adjust validation logic to accommodate new extracted value structure
- Ensure 'isPathComparison' is only true when present in the rule
- Update condition to prevent false positives in comparison checks
Copy link

changeset-bot bot commented Feb 19, 2025

⚠️ No Changeset found

Latest commit: f90ab06

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

Walkthrough

This pull request updates the rule engine by modifying how values are extracted and compared. The extractValue method now distinguishes between path comparisons and regular operations by using a new constant and returns an object with both the original value and a comparison value. Schemas are enhanced with an isPathComparison flag, and variable names in the validation flow have been updated for clarity. Additionally, an import statement and a subproject commit identifier have been revised.

Changes

File(s) Change Summary
packages/common/src/rule-engine/operators/helpers.ts Updated extractValue method: adds constant OPERATORS_WITHOUT_PATH_COMPARISON to distinguish path comparisons, throws errors if values are missing, returns an object with value and comparisonValue, and updates import to include OPERATION.
packages/common/src/rule-engine/rules/schemas.ts Added isPathComparison boolean (default false) to schemas for operators: EQUALS, NOT_EQUALS, GT, LT, GTE, LTE, IN, IN_CASE_INSENSITIVE, and NOT_IN.
services/workflows-service/src/rule-engine/core/rule-engine.ts Renamed variable to extractedValue, introduced boolean isPathComparison to manage value extraction, and updated operator.execute to use comparisonValue.
services/workflows-service/prisma/data-migrations Updated subproject commit identifier from af8373720458da7f4dbd65cd95e31540c583d854 to 576e5e4e8a3e6f28b299c41d609fa8de934f1259.
packages/common/src/rule-engine/operators/constants.ts Added new constant OPERATORS_WITHOUT_PATH_COMPARISON containing specific operation values.
services/workflows-service/src/rule-engine/core/test/rule-engine.unit.test.ts Added isPathComparison property to rule definitions and introduced new test cases for path comparisons.
services/workflows-service/src/rule-engine/rule-engine.service.intg.test.ts Added isPathComparison: false to rule definitions for IN_CASE_INSENSITIVE operator in tests.

Possibly related PRs

  • Notion schema fix and Cron schedule change #2793: The changes in the main PR are related to the addition of the isPathComparison property in the RuleSchema, which is also referenced in the retrieved PR's modifications to the schemas.ts file, specifically regarding the IN_CASE_INSENSITIVE operator.
  • In case insensitive risk rule engine operator  #2790: The changes in the main PR, which involve modifications to the extractValue method and the introduction of the isPathComparison property, are related to the changes in the retrieved PR that introduces the IN_CASE_INSENSITIVE operator, as both involve enhancements to the rule engine's handling of comparisons.

Suggested reviewers

  • tomer-shvadron
  • MatanYadaev
  • alonp99

Poem

Hopping through lines of code so neat,
I tweak comparisons with nimble feet.
Values and paths now dance in rhyme,
With errors caught in proper time.
A bunny’s cheer in every commit — oh, what a treat!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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. (Beta)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

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: 0

🧹 Nitpick comments (2)
packages/common/src/rule-engine/rules/schemas.ts (1)

42-42: Consider adding JSDoc documentation for the isPathComparison property.

While the implementation is correct, adding documentation would help other developers understand when and why to use path comparison in rules.

Add documentation like this:

 z.object({
   key: z.string(),
   operator: z.literal(OPERATION.EQUALS),
   value: PrimitiveSchema,
+  /** When true, treats the value as a path to compare against instead of a literal value */
   isPathComparison: z.boolean().default(false),
 }),

Also applies to: 48-48, 59-59, 65-65, 71-71, 77-77, 88-88, 94-94, 100-100

packages/common/src/rule-engine/operators/helpers.ts (1)

42-46: Consider moving OPERATORS_WITHOUT_PATH_COMPARISON to a constants file.

The constant would be better placed in a dedicated constants file since it defines operator behavior.

Consider moving it to the existing constants file:

// In ./constants.ts
+export const OPERATORS_WITHOUT_PATH_COMPARISON = [
+  OPERATION.AML_CHECK,
+  OPERATION.BETWEEN,
+  OPERATION.LAST_YEAR,
+] as const;

// In this file
-const OPERATORS_WITHOUT_PATH_COMPARISON = [...]
+import { OPERATORS_WITHOUT_PATH_COMPARISON } from './constants';
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3a693f9 and 06c82d9.

📒 Files selected for processing (4)
  • packages/common/src/rule-engine/operators/helpers.ts (2 hunks)
  • packages/common/src/rule-engine/rules/schemas.ts (3 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
  • services/workflows-service/src/rule-engine/core/rule-engine.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • services/workflows-service/prisma/data-migrations
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
services/workflows-service/src/rule-engine/core/rule-engine.ts (1)

26-35: LGTM! Clear and robust value extraction logic.

The new implementation properly handles both path comparison and regular value comparison cases with clear variable naming and type checking.

packages/common/src/rule-engine/operators/helpers.ts (1)

48-71: LGTM! Robust path comparison implementation.

The implementation:

  • Properly checks for path comparison eligibility
  • Includes appropriate null/undefined checks
  • Provides clear error messages

…s usage

- Move OPERATORS_WITHOUT_PATH_COMPARISON to constants for better reusability
- Refactor extraction logic to use isObject utility for clarity
- Update imports to reflect the new constants structure
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

🧹 Nitpick comments (1)
packages/common/src/rule-engine/operators/helpers.ts (1)

43-49: Consider extracting the path comparison check into a helper method.

The path comparison check logic could be more readable if extracted into a separate method like isPathComparisonOperation.

+  private isPathComparisonOperation(rule: Rule): boolean {
+    return (
+      !OPERATORS_WITHOUT_PATH_COMPARISON.includes(
+        rule.operator as (typeof OPERATORS_WITHOUT_PATH_COMPARISON)[number],
+      ) &&
+      'isPathComparison' in rule &&
+      rule.isPathComparison
+    );
+  }
+
   extractValue(data: unknown, rule: Rule) {
     const value = get(data, rule.key);
-    const isPathComparison =
-      !OPERATORS_WITHOUT_PATH_COMPARISON.includes(
-        rule.operator as (typeof OPERATORS_WITHOUT_PATH_COMPARISON)[number],
-      ) &&
-      'isPathComparison' in rule &&
-      rule.isPathComparison;
+    const isPathComparison = this.isPathComparisonOperation(rule);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06c82d9 and f90ab06.

📒 Files selected for processing (4)
  • packages/common/src/rule-engine/operators/constants.ts (1 hunks)
  • packages/common/src/rule-engine/operators/helpers.ts (2 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
  • services/workflows-service/src/rule-engine/core/rule-engine.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • services/workflows-service/src/rule-engine/core/rule-engine.ts
  • services/workflows-service/prisma/data-migrations
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test_windows
  • GitHub Check: test_linux
  • GitHub Check: build (windows-latest)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: lint
🔇 Additional comments (2)
packages/common/src/rule-engine/operators/constants.ts (1)

35-39: LGTM! Well-defined constant for operators without path comparison support.

The constant correctly identifies operators that have special value handling and therefore don't support path comparison.

packages/common/src/rule-engine/operators/helpers.ts (1)

62-64: LGTM! Proper null check for comparison value.

The code correctly validates the comparison value and throws a descriptive error when the path is invalid.

- Refactor validation logic for extracted values
- Utilize 'in' operator for better readability and accuracy
…lity

- Add isPathComparison flag to various rule definitions
- Implement new unit tests for path comparison scenarios
- Update integration tests to include path comparison in validation
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: 0

🧹 Nitpick comments (1)
services/workflows-service/src/rule-engine/core/test/rule-engine.unit.test.ts (1)

1062-1125: LGTM! The new test suite thoroughly validates path comparison functionality.

The test suite covers:

  1. Successful path comparison between different paths.
  2. Error handling for invalid paths.

The test cases are well-structured and provide good coverage of the new feature.

However, consider adding more test cases to cover:

  1. Path comparison with arrays
  2. Path comparison with nested objects
  3. Path comparison with different data types
  4. Edge cases like empty objects or null values

Here's an example test case for array comparison:

+    it('should compare array values from two different paths', () => {
+      const ruleSetExample: RuleSet = {
+        operator: OPERATOR.AND,
+        rules: [
+          {
+            key: 'pluginsOutput.businessInformation.data',
+            operator: OPERATION.EQUALS,
+            value: 'entity.data.businesses',
+            isPathComparison: true,
+          },
+        ],
+      };
+
+      const testContext = {
+        pluginsOutput: {
+          businessInformation: {
+            data: ['Business1', 'Business2'],
+          },
+        },
+        entity: {
+          data: {
+            businesses: ['Business1', 'Business2'],
+          },
+        },
+      };
+
+      const engine = RuleEngine(ruleSetExample);
+      const result = engine.run(testContext);
+      expect(result).toBeDefined();
+      expect(result).toHaveLength(1);
+      expect(result[0]?.status).toBe('PASSED');
+    });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f90ab06 and fd0c4ab.

📒 Files selected for processing (3)
  • services/workflows-service/src/rule-engine/core/rule-engine.ts (2 hunks)
  • services/workflows-service/src/rule-engine/core/test/rule-engine.unit.test.ts (20 hunks)
  • services/workflows-service/src/rule-engine/rule-engine.service.intg.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • services/workflows-service/src/rule-engine/core/rule-engine.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test_windows
  • GitHub Check: test_linux
  • GitHub Check: build (windows-latest)
  • GitHub Check: lint
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
services/workflows-service/src/rule-engine/rule-engine.service.intg.test.ts (1)

24-24: LGTM! The changes correctly specify that these rules don't use path comparison.

The addition of isPathComparison: false to the rule definitions is consistent with the PR's objective of enhancing the rule engine with path comparison functionality.

Also applies to: 30-30

services/workflows-service/src/rule-engine/core/test/rule-engine.unit.test.ts (1)

29-29: LGTM! The changes consistently specify that these rules don't use path comparison.

The addition of isPathComparison: false to all existing rule definitions is thorough and consistent with the PR's objective.

Also applies to: 47-47, 53-53, 80-80, 103-103, 505-505, 560-560, 625-625, 652-652, 681-681

@shanegrouber shanegrouber merged commit f319d83 into dev Feb 20, 2025
18 checks passed
@shanegrouber shanegrouber deleted the BAL-3498 branch February 20, 2025 13:55
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.

2 participants