Skip to content

Conversation

@adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented May 9, 2025

Summary by CodeRabbit

  • New Features

    • Added an end-to-end test to verify that a release is created when a new resource does not match any existing policy target.
  • Refactor

    • Simplified and improved the computation and updating of policy target release targets with enhanced transactional consistency.
    • Updated the release target evaluation process to handle all relevant targets more efficiently.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 9, 2025

Walkthrough

This update refactors the event worker's computation of policy target release targets by replacing custom inline transactional logic with a new computePolicyTargets function that handles deletion and insertion atomically. It also modifies job dispatching to evaluate all release targets in a workspace. Additionally, an end-to-end test is added to verify release creation when a new resource does not match any policy target.

Changes

File(s) Change Summary
apps/event-worker/src/workers/compute-policy-target-release-target-selector.ts Replaced inline transaction logic with a call to computePolicyTargets; removed diffing; now dispatches evaluation jobs for all release targets in the workspace; updated imports and eager loading of policy relation.
apps/event-worker/src/workers/compute-systems-release-targets.ts Removed dispatch of compute jobs; replaced with concurrent calls to computePolicyTargets for each policy target; removed unused imports; changed control flow to continue dispatching evaluation jobs.
packages/db/src/queries/compute-policy-targets.ts Added new module implementing computePolicyTargets function that atomically deletes old computed entries and inserts new matching release targets for a policy target using transactions and row locking.
packages/db/src/queries/index.ts Exported the new compute-policy-targets module in the queries package index.
e2e/tests/api/release.spec.ts Added an end-to-end test verifying release creation when a new resource is created that does not match any existing policy target.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant API
    participant DB
    participant EventWorker

    User->>API: Create new resource (no matching policy target)
    API->>DB: Insert resource
    API->>EventWorker: Trigger compute-policy-target-release-target-selector
    EventWorker->>DB: Call computePolicyTargets (transactionally delete old and insert new computed release targets)
    EventWorker->>DB: Query all release targets in workspace
    EventWorker->>API: Dispatch evaluation jobs for all release targets
Loading

Possibly related PRs

  • ctrlplanedev/ctrlplane#559: Refines existing inline logic for computing and updating policy target release targets and dispatching evaluation jobs for affected release targets; closely related to this PR which replaces that logic entirely.
  • ctrlplanedev/ctrlplane#524: Modifies transaction and job dispatch logic for release targets in the same event worker file.
  • ctrlplanedev/ctrlplane#518: Involves event-worker logic for release target computation and release creation, including related end-to-end tests.

Suggested reviewers

  • jsbroks

Poem

A rabbit hopped into the code,
Sweeping old targets off the road.
No more diffing, just delete and write,
Then test to see releases light.
With every hop, the logic’s clean—
Hooray for code that’s lean and keen! 🐇✨

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

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)
e2e/tests/api/release.spec.ts (1)

453-454: Remove console.log statements from test.

Debug console.log statements should be removed from production test code.

-    for (const release of releases) {
-      console.log(release);
-    }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5947306 and 2694e3f.

📒 Files selected for processing (2)
  • apps/event-worker/src/workers/compute-policy-target-release-target-selector.ts (3 hunks)
  • e2e/tests/api/release.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{ts,tsx}`: **Note on Error Handling:** Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error...

**/*.{ts,tsx}: Note on Error Handling:
Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error handling. These are acceptable as long as they maintain clarity and predictability.

  • apps/event-worker/src/workers/compute-policy-target-release-target-selector.ts
  • e2e/tests/api/release.spec.ts
🧬 Code Graph Analysis (2)
apps/event-worker/src/workers/compute-policy-target-release-target-selector.ts (3)
packages/db/src/schema/policy.ts (2)
  • policyTarget (64-78)
  • policy (42-62)
packages/db/src/client.ts (1)
  • db (15-15)
apps/event-worker/src/utils/dispatch-evaluate-jobs.ts (1)
  • dispatchEvaluateJobs (5-20)
e2e/tests/api/release.spec.ts (3)
e2e/tests/fixtures.ts (1)
  • test (11-26)
packages/db/src/schema/workspace.ts (1)
  • workspace (18-27)
packages/db/src/schema/release.ts (2)
  • releaseTarget (20-42)
  • release (113-124)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
🔇 Additional comments (6)
apps/event-worker/src/workers/compute-policy-target-release-target-selector.ts (5)

3-3: Import update properly reflects code changes.

The inArray import was removed as it's no longer used after the logic simplification.


69-69: Good optimization with eager loading.

Eager loading the policy relation is an appropriate optimization that avoids an additional query later.


73-74: Direct property access improves code clarity.

Destructuring the policy and workspaceId makes the code more readable and works well with the eager loading added above.


77-94: Simplified transaction logic for better reliability.

The transaction now simply deletes all existing computed entries for the policy target without trying to compute differences. This approach is more robust and less error-prone.


108-123: Verify performance implications of processing all release targets.

The code now queries and dispatches evaluation jobs for all release targets in the workspace rather than just those affected by changes. While this is simpler and more reliable, it could potentially lead to more processing than necessary in large workspaces.

Consider monitoring the performance of this change in production, especially for workspaces with many release targets. You might want to add metrics to track:

  1. Number of release targets being evaluated per policy target change
  2. Processing time for the evaluation queue
e2e/tests/api/release.spec.ts (1)

335-464: Good test coverage for the reverted optimization.

This test properly verifies that releases are created when a new resource is added that doesn't match any policy target. It ensures the simplified computation logic correctly handles this case.

The test is comprehensive, covering:

  1. Policy creation with a specific target selector
  2. Deployment and version creation
  3. Resource creation with a non-matching identifier
  4. Verification of release target and release creation

This aligns perfectly with the changes in the compute-policy-target-release-target-selector worker.

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)
apps/event-worker/src/workers/compute-policy-target-release-target-selector.ts (2)

27-27: Fix typo in variable name

There's a typo in the variable name: changedReleaseTaretIds should be changedReleaseTargetIds (missing 'g').

-      const changedReleaseTaretIds = await computePolicyTargets(
+      const changedReleaseTargetIds = await computePolicyTargets(

41-41: Fix typo in variable reference

The same typo exists when using the variable in the query condition.

-            inArray(schema.releaseTarget.id, changedReleaseTaretIds),
+            inArray(schema.releaseTarget.id, changedReleaseTargetIds),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 72ca219 and 263cb62.

📒 Files selected for processing (2)
  • apps/event-worker/src/workers/compute-policy-target-release-target-selector.ts (2 hunks)
  • packages/db/src/queries/compute-policy-targets.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{ts,tsx}`: **Note on Error Handling:** Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error...

**/*.{ts,tsx}: Note on Error Handling:
Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error handling. These are acceptable as long as they maintain clarity and predictability.

  • apps/event-worker/src/workers/compute-policy-target-release-target-selector.ts
  • packages/db/src/queries/compute-policy-targets.ts
🧬 Code Graph Analysis (1)
apps/event-worker/src/workers/compute-policy-target-release-target-selector.ts (4)
packages/db/src/queries/compute-policy-targets.ts (1)
  • computePolicyTargets (53-94)
packages/db/src/client.ts (1)
  • db (15-15)
packages/db/src/schema/policy.ts (1)
  • policyTarget (64-78)
apps/event-worker/src/utils/dispatch-evaluate-jobs.ts (1)
  • dispatchEvaluateJobs (5-20)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/amd64)
🔇 Additional comments (6)
apps/event-worker/src/workers/compute-policy-target-release-target-selector.ts (1)

27-47: Good refactoring to use centralized computation function

The implementation now uses the centralized computePolicyTargets function, which improves code organization and maintenance. The refactoring correctly:

  1. Retrieves changed release target IDs
  2. Queries only the relevant release targets
  3. Filters out deleted resources
  4. Dispatches evaluation jobs appropriately

Overall, this is a good improvement to the codebase structure.

packages/db/src/queries/compute-policy-targets.ts (5)

7-51: Well-structured query with proper joins and selectors

The findMatchingReleaseTargets helper function efficiently queries for release targets using appropriate joins across resource, deployment, and environment tables. The selector pattern provides a clean way to apply complex filtering conditions based on policy target selectors.


58-65: Good use of FOR UPDATE NOWAIT to prevent deadlocks

The implementation correctly uses FOR UPDATE NOWAIT to lock rows and fail immediately if they're already locked, which is a good practice to prevent deadlocks. This works well with the error handling in the caller code.


79-92: Efficient change detection using Sets

The code efficiently calculates created and deleted associations using Sets for fast lookups. The approach is clear and well-structured, with descriptive variable names that explain the intent of each step in the process.


86-90: Good optimization with conditional insert

The code correctly avoids unnecessary database operations by only performing the insert when there are matching release targets. The use of onConflictDoNothing() ensures idempotence, which is important for robustness.


53-57:

✅ Verification successful

Verify nested transaction behavior

The function receives a transaction object db but then creates a new transaction with it. Nested transactions might not behave as expected across all database systems and ORMs.

Consider either:

  1. Removing the inner transaction if the function is always called within a transaction
  2. Adding a parameter to control whether to use a transaction

🏁 Script executed:

#!/bin/bash
# Check if this pattern is used elsewhere in the codebase
rg -A 3 "transaction\(async \(" --type ts

Length of output: 15034


Nested transactions are supported and consistently used; no changes needed

  • A code search shows the same db.transaction(async (tx) => …) pattern in 40+ places (API routers, workers, migrations, etc.).
  • With Postgres and Kysely, nested transactions become savepoints and behave predictably on rollback/commit.

No actionable fixes are required here.

@adityachoudhari26 adityachoudhari26 merged commit d560e8f into main May 9, 2025
9 of 10 checks passed
@adityachoudhari26 adityachoudhari26 deleted the revert-compute-policy-optimization branch May 9, 2025 05:26
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.

3 participants