Skip to content

v4: fix race condition when continuing run when blocked at the same time #2073

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

Merged
merged 3 commits into from
May 19, 2025

Conversation

ericallam
Copy link
Member

@ericallam ericallam commented May 19, 2025

This fixes an issue where a run could get stuck when two things happened with the following exact timing:

  • Run A would be unblocked by a waitpoint, and have continueRunIfUnblocked called and get passed the "are there any blocking waitpoints" guard
  • Before Run A cleared the blocking waitpoints at the end of the continueRunIfUnblocked function, Run A would be blocked by a new waitpoint with blockRunWithWaitpoint, creating a new TaskRunWaitpoint
  • continueRunIfUnblocked would finish running, clearing ALL blocking waitpoints (including the new one just created in the step above)

The fix for this was simply to only delete blocking TaskRunWaitpoint records that participated in the blocking waitpoint guard at the beginning of continueRunIfUnblocked

Summary by CodeRabbit

  • New Features

    • Introduced race simulation functionality for runs, allowing asynchronous coordination and improved handling of race conditions during waitpoints.
  • Bug Fixes

    • Enhanced waitpoint processing to better manage race conditions, ensuring more accurate synchronization and deletion of waitpoints.
  • Tests

    • Added a new test suite to verify correct behavior of waitpoints under race conditions.
  • Chores

    • Updated test fixtures to reflect a shorter expected duration for the "hello-world" test case.

Copy link

changeset-bot bot commented May 19, 2025

⚠️ No Changeset found

Latest commit: 1a9233e

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.

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 May 19, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

A new RaceSimulationSystem was introduced and integrated into the RunEngine to manage asynchronous racepoints for runs. The waitpoint system was updated to coordinate with this new system by adding synchronization points and requiring an explicit organizationId. Additionally, a new test suite was added to simulate and verify waitpoint behavior under race conditions.

Changes

File(s) Change Summary
src/engine/index.ts Integrated RaceSimulationSystem into RunEngine, added a raceSimulationSystem property, updated blockRunWithWaitpoint to require organizationId, and added a new public method registerRacepointForRun.
src/engine/systems/raceSimulationSystem.ts Added new RaceSimulationSystem class to manage asynchronous racepoints keyed by run ID, with methods to wait for and register racepoints that resolve after a specified wait interval.
src/engine/systems/systems.ts Imported RaceSimulationSystem and extended the SystemResources type to include a raceSimulationSystem property.
src/engine/systems/waitpointSystem.ts Updated blockRunWithWaitpoint and continueRunIfUnblocked to require organizationId, added calls to raceSimulationSystem.waitForRacepoint for synchronization, and refined blocking waitpoint deletion logic to delete only specific waitpoints by ID.
src/engine/tests/waitpointRace.test.ts Added a new test suite simulating a race condition scenario in the waitpoint system, verifying that join rows are not prematurely deleted during rapid waitpoint changes.
packages/cli-v3/e2e/fixtures.ts Reduced the expected duration of the "hello-world" test run result from 1000ms to 500ms in the fixtures configuration.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RunEngine
    participant RaceSimulationSystem
    participant WaitpointSystem

    Client->>RunEngine: trigger(runId, organizationId)
    RunEngine->>WaitpointSystem: blockRunWithWaitpoint({runId, ..., organizationId})
    WaitpointSystem->>RaceSimulationSystem: waitForRacepoint({runId})
    RaceSimulationSystem-->>WaitpointSystem: (waits or resolves)
    WaitpointSystem->>WaitpointSystem: process waitpoints, update state

    Client->>RunEngine: registerRacepointForRun({runId, waitInterval})
    RunEngine->>RaceSimulationSystem: registerRacepointForRun({runId, waitInterval})
    RaceSimulationSystem->>RaceSimulationSystem: create and resolve racepoint after interval
Loading

Poem

In the warren of code, a new race is begun,
With waitpoints and racepoints, the systems now run.
Synchrony’s magic, with promises tight,
Ensures that our runs don’t hop out of sight.
The rabbits all cheer, for the test is in place—
No more lost join rows in this speedy race! 🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ 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.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 7e69661 and 1a9233e.

📒 Files selected for processing (1)
  • internal-packages/run-engine/src/engine/tests/waitpointRace.test.ts (1 hunks)
✨ 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.

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

🔭 Outside diff range comments (2)
internal-packages/run-engine/src/engine/systems/waitpointSystem.ts (2)

498-513: ⚠️ Potential issue

Racepoint sync must precede waitpoint query to avoid lost blockers

continueRunIfUnblocked fetches the list of waitpoints before calling waitForRacepoint.
If another thread inserts a new blocking waitpoint between the SELECT and the wait, the current thread will:

  1. Miss the newly-inserted waitpoint.
  2. Conclude the run is unblocked.
  3. Wrongly resume the run, re-introducing the very race we are trying to solve.

Move the race-point wait above the query so that the read view includes all inserts made prior to the sync.

-    // 1. Get the any blocking waitpoints
-    const blockingWaitpoints = await this.$.prisma.taskRunWaitpoint.findMany({
-      where: { taskRunId: runId },
-      select: {
-        id: true,
-        batchId: true,
-        batchIndex: true,
-        waitpoint: {
-          select: { id: true, status: true },
-        },
-      },
-    });
-
-    await this.$.raceSimulationSystem.waitForRacepoint({ runId });
+    // Synchronise first to guarantee a consistent view
+    await this.$.raceSimulationSystem.waitForRacepoint({ runId });
+
+    // 1. Get any blocking waitpoints
+    const blockingWaitpoints = await this.$.prisma.taskRunWaitpoint.findMany({
+      where: { taskRunId: runId },
+      select: {
+        id: true,
+        batchId: true,
+        batchIndex: true,
+        waitpoint: {
+          select: { id: true, status: true },
+        },
+      },
+    });

352-369: 💡 Verification agent

🧩 Analysis chain

Add-on parameter requires call-site audit

blockRunWithWaitpoint now mandates organizationId.
Please verify every invocation of this method across the code-base (tests, helpers, scheduled jobs, etc.) has been updated; otherwise the compiler/TS-server will complain, but dynamic any usage might silently pass undefined.


🏁 Script executed:

#!/bin/bash
# Finds all call-sites still passing 6 args (old signature) instead of ≥7.
rg -n $'blockRunWithWaitpoint\\(' | awk -F':' '{print $1":"$2}'

Length of output: 2690


🏁 Script executed:

#!/bin/bash
set -eu

echo "Call-sites missing 'organizationId' in the argument object:"
for file in $(rg -l "blockRunWithWaitpoint\("); do
  if ! rg -q "blockRunWithWaitpoint\(\{[^}]*organizationId" "$file"; then
    rg -n "blockRunWithWaitpoint\(" "$file"
  fi
done

Length of output: 5375


Audit and update all blockRunWithWaitpoint call-sites to include organizationId

blockRunWithWaitpoint now requires an organizationId field in its argument object. The following call-sites are still missing it; please update each to pass the correct organizationId from scope:

• internal-packages/run-engine/src/engine/index.ts
– lines 524, 909, 994
• internal-packages/run-engine/src/engine/tests/releaseConcurrency.test.ts
– lines 108, 159, 308, 360, 496, 548, 683, 845, 1027, 1191, 1345
• internal-packages/run-engine/src/engine/tests/triggerAndWait.test.ts (line 368)
• internal-packages/run-engine/src/engine/tests/waitpoints.test.ts
– lines 98, 211, 352, 491, 617, 759, 909, 1069, 1224, 1423
• internal-packages/run-engine/src/engine/tests/waitpointRace.test.ts (lines 71, 90)
• internal-packages/run-engine/src/engine/tests/checkpoints.test.ts
– lines 98, 354, 404, 557, 851
• apps/webapp/app/routes/engine.v1.runs.$runFriendlyId.wait.duration.ts (line 48)
• apps/webapp/app/routes/engine.v1.runs.$runFriendlyId.waitpoints.tokens.$waitpointFriendlyId.wait.ts (line 40)
• apps/webapp/app/runEngine/concerns/idempotencyKeys.server.ts (line 71)

Each object literal passed into blockRunWithWaitpoint({ … }) must now include

  organizationId: /* your org ID variable */

before merging.

🧹 Nitpick comments (4)
internal-packages/run-engine/src/engine/systems/raceSimulationSystem.ts (2)

4-4: Prefer Map over plain object to avoid prototype-pollution pitfalls

Record<string, Promise<void>> will work for UUID-ish runIds, but using a Map avoids collisions with __proto__, hasOwnProperty, … and provides cleaner semantics.

- private racepoints: Record<string, Promise<void> | undefined> = {};
+ private racepoints = new Map<string, Promise<void>>();

6-7: Remove the empty constructor

The synthetic constructor adds byte-code without value and was flagged by Biome.

-  constructor() {}
🧰 Tools
🪛 Biome (1.9.4)

[error] 6-6: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

internal-packages/run-engine/src/engine/tests/waitpointRace.test.ts (1)

104-106: Avoid console noise in automated test runs

console.log("joinRow", joinRow); will pollute CI output and can mask real issues when the suite scales.

-        console.log("joinRow", joinRow);
internal-packages/run-engine/src/engine/systems/waitpointSystem.ts (1)

667-679: Optional: Delete waitpoint links inside the lock

The cleanup of TaskRunWaitpoint rows happens after the run-level lock is released.
Two concurrent continueRunIfUnblocked jobs could both pass the blockers-completed check, then attempt to delete the same rows, causing redundant work or lost updates.

Consider performing the deletion inside the runLock or, at minimum, guarding it with ON CONFLICT DO NOTHING / IF EXISTS semantics.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 8471169 and 2929ede.

📒 Files selected for processing (5)
  • internal-packages/run-engine/src/engine/index.ts (7 hunks)
  • internal-packages/run-engine/src/engine/systems/raceSimulationSystem.ts (1 hunks)
  • internal-packages/run-engine/src/engine/systems/systems.ts (2 hunks)
  • internal-packages/run-engine/src/engine/systems/waitpointSystem.ts (7 hunks)
  • internal-packages/run-engine/src/engine/tests/waitpointRace.test.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
internal-packages/run-engine/src/engine/systems/raceSimulationSystem.ts

[error] 6-6: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
internal-packages/run-engine/src/engine/systems/systems.ts (1)

8-19: ✅ Resource wiring looks correct

RaceSimulationSystem is imported and exposed through SystemResources.
All downstream systems that require the new dependency can now pick it up via DI, so there is no immediate concern in this slice.

internal-packages/run-engine/src/engine/systems/waitpointSystem.ts (1)

379-381: Race-simulation hook added in the right place

Synchronising on this.$.raceSimulationSystem.waitForRacepoint before acquiring the run lock looks correct and should eliminate the original race condition.

@ericallam ericallam merged commit c63559f into main May 19, 2025
4 of 5 checks passed
@ericallam ericallam deleted the ea-branch-62 branch May 19, 2025 15:50
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