Skip to content

[v4] Complete a waitpoint and then get affected runs #2034

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 2 commits into from
May 9, 2025

Conversation

matt-aitken
Copy link
Member

@matt-aitken matt-aitken commented May 9, 2025

When we block a run with a waitpoint we only block the run if the waitpoint is PENDING. If it's already completed then we don't do anything.

Before this PR, when we completed a waitpoint we were getting the blocked runs before marking the waitpoint as COMPLETED. This meant it was possible to get an outdated list of blocked runs if the timing was slightly wrong.

This change makes it so we only get the blocked runs after the Waitpoint is COMPLETED (at the point where it's not possible to block a run with it anymore).

Also added more logging so we can find what's happening more easily.

Summary by CodeRabbit

  • Refactor
    • Improved the process for completing waitpoints and resuming blocked runs, ensuring more reliable status updates.
  • Style
    • Enhanced and standardized debug and error logging for better visibility and traceability of waitpoint and run continuation actions.

Copy link

changeset-bot bot commented May 9, 2025

⚠️ No Changeset found

Latest commit: 32c6087

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 9, 2025

Walkthrough

The completeWaitpoint and continueRunIfUnblocked methods in the waitpoint system were refactored to change the order of operations, add explicit status validation, and introduce extensive debug logging. The core logic remains unchanged, but the flow and observability of waitpoint completion and run continuation were improved.

Changes

File(s) Change Summary
internal-packages/run-engine/src/engine/systems/waitpointSystem.ts Refactored completeWaitpoint to complete waitpoint before fetching blocked TaskRuns, added status validation, and enhanced debug logging in both completeWaitpoint and continueRunIfUnblocked. No changes to method signatures.

Poem

A waitpoint’s tale, now clearer to see,
With logs that dance in verbosity.
First complete, then check who’s blocked,
Each run’s fate carefully clocked.
Debugging trails, a bunny’s delight—
Hopping through code, making things right! 🐇✨

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.

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 (5)
internal-packages/run-engine/src/engine/systems/waitpointSystem.ts (5)

69-82: Consider wrapping the update + query in a single transaction for true atomicity

completeWaitpoint first marks the waitpoint as COMPLETED and then performs a separate query to collect affected TaskRunWaitpoint rows.
In the (admittedly tiny) time-window between these two statements a concurrent blockRunWithWaitpoint call could still insert additional TaskRunWaitpoint rows that would be missed by the follow-up query, leaving a run blocked without a scheduled continueRunIfUnblocked job.

Moving both statements into one $.prisma.$transaction() (or using a CTE) guarantees a consistent snapshot and eliminates the race completely.

-// 1. Complete the Waitpoint …
-let [waitpointError, waitpoint] = await tryCatch(this.$.prisma.waitpoint.update(…));
-
-// 2. Find the TaskRuns blocked by this waitpoint
-const affectedTaskRuns = await this.$.prisma.taskRunWaitpoint.findMany(…);
+const [waitpointResult, affectedTaskRuns] = await this.$.prisma.$transaction([
+  this.$.prisma.waitpoint.update({ … }),
+  this.$.prisma.taskRunWaitpoint.findMany({ … }),
+]);

This keeps the public behaviour unchanged while removing the edge-case window.


101-106: Include the actual status in the thrown error for easier debugging

Right now the error says “Waitpoint X is not completed” but omits the current status, forcing operators to re-query the DB.
A tiny tweak makes incidents faster to diagnose:

-throw new Error(`Waitpoint ${id} is not completed`);
+throw new Error(
+  `Waitpoint ${id} is not completed (current status: ${waitpoint.status})`
+);

120-133: Enqueue calls can be batched to reduce I/O latency

Inside the loop we await each worker.enqueue, turning the process into N sequential round-trips.
If hundreds of runs are affected this can add noticeable latency. The worker already de-duplicates by id, so we can safely fire them in parallel:

-for (const run of affectedTaskRuns) {
-
-  await this.$.worker.enqueue({ … });
-}
+await Promise.all(
+  affectedTaskRuns.map((run) =>
+    this.$.worker.enqueue({
+      id: `continueRunIfUnblocked:${run.taskRunId}`,
+      job: "continueRunIfUnblocked",
+      payload: { runId: run.taskRunId },
+      availableAt: new Date(Date.now() + 50),
+    })
+  )
+);

Throughput improves and overall wall-clock time drops, especially under load.


587-595: Logging full snapshot objects may bloat logs and expose PII

this.$.logger.debug serialises potentially large snapshot / newSnapshot objects.
Consider logging only stable identifiers (id, executionStatus, etc.) or using a structured logger that redacts bulky/PII fields. This keeps log volume manageable and avoids accidental leakage.


629-634: TODO: provide a concrete fallback when checkpoint is missing

The TODO notes “We're screwed” and throws an error, which will bubble up and retry the job indefinitely unless caught elsewhere. If this situation is expected to be unrecoverable, consider:

  1. Explicitly failing the run in the DB with an explanatory status.
  2. Surfacing a clear alert/metric so the condition doesn’t go unnoticed.
  3. Adding unit / integration tests to cover this edge case.

Happy to help draft the failure-handling code if useful.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1b1ad16 and 32c6087.

📒 Files selected for processing (1)
  • internal-packages/run-engine/src/engine/systems/waitpointSystem.ts (10 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: Analyze (javascript-typescript)

@matt-aitken matt-aitken merged commit 584722d into main May 9, 2025
12 checks passed
@matt-aitken matt-aitken deleted the fix-waitpoint-completing branch May 9, 2025 14:46
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