Skip to content

chore: add dedicated queue to compute workspace policy targets#591

Merged
adityachoudhari26 merged 1 commit intomainfrom
new-workspace-policy-queue
Jun 17, 2025
Merged

chore: add dedicated queue to compute workspace policy targets#591
adityachoudhari26 merged 1 commit intomainfrom
new-workspace-policy-queue

Conversation

@adityachoudhari26
Copy link
Copy Markdown
Member

@adityachoudhari26 adityachoudhari26 commented Jun 17, 2025

Summary by CodeRabbit

  • New Features

    • Introduced improved processing for workspace policy targets, enabling more efficient handling and evaluation of release targets within a workspace.
  • Improvements

    • Simplified and streamlined the release target computation process, reducing redundant processing and enhancing reliability.
    • Enhanced job dispatching for system and workspace policy targets, leading to better performance and clearer control flow.
  • Tests

    • Updated end-to-end tests to align with the new release target creation logic.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jun 17, 2025

Walkthrough

This change refactors the release target computation workflow by simplifying the computeSystemsReleaseTargetsWorker, removing incremental policy target processing, and introducing a new computeWorkspacePolicyTargetsWorker. It also updates job dispatching logic and types, and adjusts related tests and exports to align with the new control flow.

Changes

File(s) Change Summary
apps/event-worker/src/workers/compute-systems-release-targets.ts Simplified logic: removed incremental policy target processing and redeploy handling; streamlined transaction and job dispatch.
apps/event-worker/src/workers/compute-workspace-policy-targets.ts Added new worker to process workspace policy targets sequentially with row lock error handling and downstream job dispatch.
apps/event-worker/src/workers/index.ts Imported and registered the new computeWorkspacePolicyTargetsWorker.
packages/events/src/dispatch-jobs.ts Simplified system release targets job dispatch; added workspace policy targets job dispatch and updated factory methods.
packages/events/src/types.ts Added new channel/type for workspace policy targets; simplified system release targets channel payload.
e2e/tests/api/release.spec.ts Removed assertion on the release count after adding a deployment variable.

Sequence Diagram(s)

sequenceDiagram
    participant API/Trigger
    participant SystemReleaseWorker
    participant WorkspacePolicyWorker
    participant DB
    participant DownstreamJobs

    API/Trigger->>SystemReleaseWorker: Dispatch ComputeSystemsReleaseTargets (system id)
    SystemReleaseWorker->>DB: Lock and compute created/deleted release targets
    SystemReleaseWorker->>DownstreamJobs: Enqueue deletion events for deleted targets
    SystemReleaseWorker->>WorkspacePolicyWorker: Dispatch ComputeWorkspacePolicyTargets (workspace id, created targets)
    WorkspacePolicyWorker->>DB: Fetch unprocessed policy targets
    alt Policy targets exist
        WorkspacePolicyWorker->>DB: Compute each policy target (handle lock errors)
        WorkspacePolicyWorker->>DownstreamJobs: Optionally dispatch evaluation for created targets
    else No policy targets
        WorkspacePolicyWorker->>DownstreamJobs: Dispatch evaluation for created targets
    end
Loading

Possibly related PRs

Suggested reviewers

  • jsbroks

Poem

A rabbit hopped through lines anew,
Streamlined the jobs, made workers two.
No more redeploys to chase or track,
Policy targets in a tidy stack.
With queues and locks, the code’s in sync—
Release flows faster than you think!
🐇✨

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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
Copy Markdown
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: 2

🧹 Nitpick comments (7)
packages/events/src/types.ts (1)

81-86: Optional: default processedPolicyTargetIds to an empty array

Down-stream code always does processedPolicyTargetIds ?? [].
Consider making the property non-optional (default []) to remove repeated null-coalescing and avoid feeding undefined into SQL helpers.

apps/event-worker/src/workers/compute-workspace-policy-targets.ts (3)

37-44: Early-exit still calls downstream for empty list

If releaseTargetsToEvaluate is [], the worker still enqueues an evaluation job that performs no work.
A tiny guard can avoid superfluous queue traffic:

if (policyTargets.length === 0) {
  if (releaseTargetsToEvaluate?.length)
    await dispatchQueueJob().toEvaluate().releaseTargets(releaseTargetsToEvaluate);
  return;
}

47-66: Potential hot-loop on row-lock contention

On every 55P03 the job immediately re-queues itself without delay.
Consider adding back-off (e.g., BullMQ delay or retry strategy) to avoid thrashing when another long-running transaction is holding the locks.


69-73: Same superfluous-enqueue note applies here

Skip dispatch when releaseTargetsToEvaluate is an empty array.

apps/event-worker/src/workers/compute-systems-release-targets.ts (1)

188-195: Empty created array still spawns follow-up job

You always enqueue a workspace job even when created is empty, which leads to no-op processing.
Add a quick length check to avoid unnecessary queue churn.

packages/events/src/dispatch-jobs.ts (2)

88-91: Minor: provide deduplication opts instead of manual waiting scan

BullMQ supports opts.jobId or opts.deduplication to avoid duplicates without an explicit getWaiting scan.
The manual check works but costs an extra round-trip; using built-in deduping would simplify the code.


130-141: Fluent API: consider returning the inner helpers

toCompute().workspace(id).policyTargets() currently returns nothing, making it hard to await the enqueue in calling code.
Returning the underlying promise would let callers await/job-chain naturally.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between da9d6ac and eedd187.

📒 Files selected for processing (6)
  • apps/event-worker/src/workers/compute-systems-release-targets.ts (4 hunks)
  • apps/event-worker/src/workers/compute-workspace-policy-targets.ts (1 hunks)
  • apps/event-worker/src/workers/index.ts (2 hunks)
  • e2e/tests/api/release.spec.ts (0 hunks)
  • packages/events/src/dispatch-jobs.ts (2 hunks)
  • packages/events/src/types.ts (3 hunks)
💤 Files with no reviewable changes (1)
  • e2e/tests/api/release.spec.ts
🧰 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/index.ts
  • packages/events/src/types.ts
  • apps/event-worker/src/workers/compute-workspace-policy-targets.ts
  • apps/event-worker/src/workers/compute-systems-release-targets.ts
  • packages/events/src/dispatch-jobs.ts
🧬 Code Graph Analysis (3)
apps/event-worker/src/workers/index.ts (1)
apps/event-worker/src/workers/compute-workspace-policy-targets.ts (1)
  • computeWorkspacePolicyTargetsWorker (27-74)
packages/events/src/types.ts (1)
packages/rule-engine/src/types.ts (1)
  • ReleaseTargetIdentifier (76-80)
packages/events/src/dispatch-jobs.ts (2)
packages/rule-engine/src/types.ts (1)
  • ReleaseTargetIdentifier (76-80)
packages/events/src/index.ts (1)
  • getQueue (28-34)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: Lint
  • GitHub Check: Typecheck
  • GitHub Check: build (linux/amd64)
🔇 Additional comments (2)
apps/event-worker/src/workers/index.ts (1)

10-10: Worker correctly registered – no issues spotted

Import and registry entry look good; naming and channel match the new file.

Also applies to: 63-64

apps/event-worker/src/workers/compute-systems-release-targets.ts (1)

91-118: Lock acquisition order – confirm global consistency

The worker obtains locks on releaseTarget, computedEnvironmentResource, then computedDeploymentResource.
If any other code acquires the same tables in a different order, Postgres can deadlock.
Please verify that the chosen order is used everywhere or codify it in a shared helper.

Comment on lines +7 to +25
const getPolicyTargets = async (
workspaceId: string,
processedPolicyTargetIds: string[],
) =>
db
.select()
.from(schema.policyTarget)
.innerJoin(
schema.policy,
eq(schema.policyTarget.policyId, schema.policy.id),
)
.where(
and(
eq(schema.policy.workspaceId, workspaceId),
processedPolicyTargetIds.length > 0
? notInArray(schema.policyTarget.id, processedPolicyTargetIds)
: undefined,
),
);
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.

🛠️ Refactor suggestion

Guard against undefined in SQL and()

and(cond1, undefined) relies on the query builder silently discarding undefined; should that behaviour ever change, the query will break.
Prefer building the condition list explicitly:

-    .where(
-      and(
-        eq(schema.policy.workspaceId, workspaceId),
-        processedPolicyTargetIds.length > 0
-          ? notInArray(schema.policyTarget.id, processedPolicyTargetIds)
-          : undefined,
-      ),
-    );
+    .where(
+      and(
+        eq(schema.policy.workspaceId, workspaceId),
+        ...(processedPolicyTargetIds.length
+          ? [notInArray(schema.policyTarget.id, processedPolicyTargetIds)]
+          : []),
+      ),
+    );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const getPolicyTargets = async (
workspaceId: string,
processedPolicyTargetIds: string[],
) =>
db
.select()
.from(schema.policyTarget)
.innerJoin(
schema.policy,
eq(schema.policyTarget.policyId, schema.policy.id),
)
.where(
and(
eq(schema.policy.workspaceId, workspaceId),
processedPolicyTargetIds.length > 0
? notInArray(schema.policyTarget.id, processedPolicyTargetIds)
: undefined,
),
);
const getPolicyTargets = async (
workspaceId: string,
processedPolicyTargetIds: string[],
) =>
db
.select()
.from(schema.policyTarget)
.innerJoin(
schema.policy,
eq(schema.policyTarget.policyId, schema.policy.id),
)
.where(
and(
eq(schema.policy.workspaceId, workspaceId),
...(processedPolicyTargetIds.length
? [notInArray(schema.policyTarget.id, processedPolicyTargetIds)]
: []),
),
);
🤖 Prompt for AI Agents
In apps/event-worker/src/workers/compute-workspace-policy-targets.ts around
lines 7 to 25, the SQL query uses and() with a condition that can be undefined,
relying on the query builder to ignore undefined values. To fix this, explicitly
build an array of conditions, adding the notInArray condition only if
processedPolicyTargetIds is non-empty, then pass this array to and() to avoid
any undefined arguments.

Comment on lines +93 to 104
const dispatchComputeWorkspacePolicyTargetsJobs = async (
workspaceId: string,
processedPolicyTargetIds?: string[],
releaseTargetsToEvaluate?: ReleaseTargetIdentifier[],
) => {
const q = getQueue(Channel.ComputeWorkspacePolicyTargets);
await q.add(workspaceId, {
workspaceId,
processedPolicyTargetIds,
releaseTargetsToEvaluate,
});
};
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.

⚠️ Potential issue

Duplicate-job check missing

Unlike the system-level helper above, workspace dispatch does not guard against the same workspace being queued multiple times.
Consider mirroring the waiting-queue check or use BullMQ job deduplication to prevent redundant jobs.

🤖 Prompt for AI Agents
In packages/events/src/dispatch-jobs.ts around lines 93 to 104, the
dispatchComputeWorkspacePolicyTargetsJobs function lacks a check to prevent
queuing duplicate jobs for the same workspace. To fix this, implement a check
before adding a new job to the queue that verifies if a job with the same
workspaceId is already waiting or active in the queue. You can achieve this by
querying the queue for existing jobs with the same identifier or by using
BullMQ's built-in job deduplication features to avoid redundant job entries.

@adityachoudhari26 adityachoudhari26 merged commit e18b3a0 into main Jun 17, 2025
7 checks passed
@adityachoudhari26 adityachoudhari26 deleted the new-workspace-policy-queue branch June 17, 2025 06:24
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