Skip to content

Comments

Fix bug: learned patterns matching when no other conditions exist#867

Merged
elie222 merged 1 commit intomainfrom
fix/multiple-learnings-matching
Oct 23, 2025
Merged

Fix bug: learned patterns matching when no other conditions exist#867
elie222 merged 1 commit intomainfrom
fix/multiple-learnings-matching

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Oct 23, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Corrected rule matching logic to properly validate group conditions before applying rules
    • Improved accuracy of group pattern resolution in rule selection
  • Tests

    • Added regression tests to ensure rules only match when group patterns are properly validated

@vercel
Copy link

vercel bot commented Oct 23, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Oct 23, 2025 11:33am

@elie222 elie222 changed the title Fix bug learned patterns matching when no other conditions exist Fix bug: learned patterns matching when no other conditions exist Oct 23, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 23, 2025

Walkthrough

Bug fixes for rule matching logic: group lookups now correctly use groupId instead of rule.id, and condition evaluation no longer matches when no conditions exist. Regression tests verify that rules only match when their associated group pattern is found.

Changes

Cohort / File(s) Summary
Rule matching logic fixes
apps/web/utils/ai/choose-rule/match-rules.ts
Updated matchesGroupRule to lookup groups by rule.groupId instead of rule.id; modified evaluateRuleConditions to return no match for both OR and AND branches when no conditions exist, instead of defaulting to true
Regression tests
apps/web/utils/ai/choose-rule/match-rules.test.ts
Added regression tests verifying rules only match when group patterns are correctly associated; adjusted existing test expectations to reflect stricter group-condition matching behavior
Version update
version.txt
Bumped version from v2.17.9 to v2.17.10

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

The changes are localized to a single utility file with focused logic corrections (group ID resolution and condition evaluation logic). Multiple regression tests follow a consistent pattern and are straightforward to verify.

Possibly related PRs

Poem

🐰 The groups were lost, conditions too loose,
Now groupId finds the right roost,
No empty matches shall escape our view,
Each rule aligned—bug-free and true! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "Fix bug: learned patterns matching when no other conditions exist" directly corresponds to the main changes in the changeset. The modifications across match-rules.ts and match-rules.test.ts are specifically designed to fix a bug where rules were incorrectly matching when their group didn't match and no other conditions existed. The title is concise, clear, and specific enough that a reviewer scanning the repository history would immediately understand the primary purpose of this fix without needing to review the full changeset details.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/multiple-learnings-matching

📜 Recent 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 47dee1c and 2f2cfe4.

📒 Files selected for processing (3)
  • apps/web/utils/ai/choose-rule/match-rules.test.ts (5 hunks)
  • apps/web/utils/ai/choose-rule/match-rules.ts (3 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
  • apps/web/utils/ai/choose-rule/match-rules.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
  • apps/web/utils/ai/choose-rule/match-rules.ts
  • version.txt
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
  • apps/web/utils/ai/choose-rule/match-rules.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
  • apps/web/utils/ai/choose-rule/match-rules.ts
**/*.test.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

Include security tests in your test suites to verify authentication, authorization, and error handling.

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
apps/web/utils/**

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
  • apps/web/utils/ai/choose-rule/match-rules.ts
apps/web/utils/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
  • apps/web/utils/ai/choose-rule/match-rules.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
  • apps/web/utils/ai/choose-rule/match-rules.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
  • apps/web/utils/ai/choose-rule/match-rules.ts
  • version.txt
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Don't use export or module.exports in test files.
Don't use focused tests.
Don't use disabled tests.
Make sure the assertion function, like expect, is placed inside an it() function call.
Don't nest describe() blocks too deeply in test files.
Don't use focused tests.
Don't use disabled tests.
Don't use export or module.exports in test files.

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
apps/web/utils/ai/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)

apps/web/utils/ai/**/*.{ts,tsx}: Place main LLM feature implementations under apps/web/utils/ai/
LLM feature functions should follow the provided TypeScript pattern (separate system/user prompts, use createGenerateObject, Zod schema validation, early validation, return result.object)
Keep system prompts and user prompts separate
System prompt should define the LLM's role and task specifications
User prompt should contain the actual data and context
Always define a Zod schema for response validation
Make Zod schemas as specific as possible to guide LLM output
Use descriptive scoped loggers for each feature
Log inputs and outputs with appropriate log levels and include relevant context
Implement early returns for invalid inputs
Use proper error types and logging for failures
Implement fallbacks for AI failures
Add retry logic for transient failures using withRetry
Use XML-like tags to structure data in prompts
Remove excessive whitespace and truncate long inputs in prompts
Format prompt data consistently across similar functions
Use TypeScript types for all parameters and return values in LLM features
Define clear interfaces for complex input/output structures in LLM features

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
  • apps/web/utils/ai/choose-rule/match-rules.ts
apps/web/utils/{ai,llms}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)

Keep related AI functions co-located and extract common patterns into utilities; document complex AI logic with clear comments

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
  • apps/web/utils/ai/choose-rule/match-rules.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)

**/*.test.{ts,tsx}: Use Vitest (vitest) as the testing framework
Colocate tests next to the file under test (e.g., dir/format.ts with dir/format.test.ts)
In tests, mock the server-only module with vi.mock("server-only", () => ({}));
When testing code that uses Prisma, mock it with vi.mock("@/utils/prisma") and use the mock from @/utils/__mocks__/prisma
Use provided helpers for mocks: import { getEmail, getEmailAccount, getRule } from @/__tests__/helpers
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Clean up mocks between tests (e.g., vi.clearAllMocks() in beforeEach)
Avoid testing implementation details; focus on observable behavior
Do not mock the Logger

Files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
🧠 Learnings (1)
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Test both AI and non-AI paths, including cases where no AI processing is required

Applied to files:

  • apps/web/utils/ai/choose-rule/match-rules.test.ts
🧬 Code graph analysis (1)
apps/web/utils/ai/choose-rule/match-rules.test.ts (2)
apps/web/__tests__/helpers.ts (2)
  • getRule (44-66)
  • getEmailAccount (6-23)
apps/web/utils/ai/choose-rule/match-rules.ts (1)
  • findMatchingRules (47-98)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: test
🔇 Additional comments (6)
apps/web/utils/ai/choose-rule/match-rules.ts (3)

502-502: Critical bug fix: Group lookup now correctly uses groupId.

The previous implementation incorrectly looked up groups using rule.id instead of rule.groupId, which would cause rules to fail to find their associated learned pattern groups. This fix ensures rules correctly locate their group by matching group.id with rule.groupId.


279-280: Correct behavior: Rules with no conditions now return no match.

The OR-branch logic now correctly returns no match when a rule has neither static nor AI conditions. This prevents empty rules from inadvertently matching all messages.


291-293: Improved clarity: AND-branch explicitly handles no-condition case.

The logic now explicitly returns matched: false when a rule has no conditions at all (neither static nor AI), rather than relying on the implicit false value of staticMatch. This makes the intent clearer and aligns with the OR-branch behavior.

apps/web/utils/ai/choose-rule/match-rules.test.ts (3)

867-913: Good test coverage for group mismatch scenario.

This test validates that a rule with a groupId only matches when its specific group contains the matching pattern, not when other groups match. The test correctly verifies that when the rule's group doesn't match and no other conditions exist, the rule should not match.


1009-1107: Excellent regression test with comprehensive coverage.

This test provides thorough coverage for the group matching bug by creating multiple rules with distinct groups and verifying that only the rule whose group actually contains the matching pattern is selected. The explicit assertions that other rules are excluded (lines 1103-1106) ensure the fix prevents cross-contamination between groups.


2511-2526: Test updated to match correct no-condition behavior.

The expectation has been correctly updated to reflect that rules with no conditions should not match. The previous expectation of matched: true for a rule with no conditions was illogical; the new behavior properly returns matched: false.


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.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 3 files

@elie222 elie222 merged commit 760cbdc into main Oct 23, 2025
14 checks passed
@elie222 elie222 deleted the fix/multiple-learnings-matching branch October 23, 2025 11:43
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.

1 participant