Skip to content

Add user stack track to error reporting - #218

Merged
ianmacartney merged 4 commits into
mainfrom
ian/error-line-numbers
Mar 18, 2026
Merged

ianmacartney merged 4 commits into
mainfrom
ian/error-line-numbers

Conversation

@ianmacartney

@ianmacartney ianmacartney commented Mar 10, 2026 •

Copy link
Copy Markdown
Member

pass through RunResult to improve error line tracking

add example of catching an error

Fixes #167

Summary by CodeRabbit

Release Notes

  • New Features

    • Added example workflow demonstrating error catching and automatic retry mechanisms for failed operations.
  • Improvements

    • Enhanced workflow step execution with improved error handling and explicit result state interpretation.
  • Tests

    • Added comprehensive test coverage for workflow step execution, error propagation, and cancellation scenarios.

Copy link
Copy Markdown
Member Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

@coderabbitai

coderabbitai Bot commented Mar 10, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

Adds an example Convex workflow demonstrating error-catching and retries, refactors client-side step result handling to use explicit RunResult interpretation, and adds comprehensive step/workflow executor tests.

Changes

Cohort / File(s) Summary
Example: new workflow example
example/convex/catchError.ts
Adds three exports: alwaysFails (action that throws), catchErrorWorkflow (workflow with manual retry loop), and start (mutation to start the workflow).
Step result handling
src/client/step.ts
Narrows StepRequest.resolve to accept RunResult; replaces per-case resolution with direct resolution of the RunResult object in completeMessage. Risk: changes how callers interpret results.
Workflow context run logic
src/client/workflowContext.ts
Removes reject callback from run request; awaits a RunResult promise and switches on result.kind to return values or throw mapped errors. Attention: control flow and error mapping changed.
Tests: step/workflow executor
src/client/stepContext.test.ts
Adds extensive tests and helpers to simulate journal replay and validate success/failure/cancel, sequencing, parallel behavior, and error propagation. Review needed for test assumptions and mocks.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Mutation as start (Mutation)
    participant Workflow as catchErrorWorkflow
    participant Step as Step Runner
    participant Action as alwaysFails (Action)

    Client->>Mutation: start(manualRetries?)
    Mutation->>Workflow: spawn workflow(manualRetries)
    Workflow->>Step: runAction(alwaysFails)
    Step->>Action: invoke handler
    Action-->>Step: throws Error
    Step->>Step: catch error, log, increment attempt
    alt attempts left
        Step->>Step: retry runAction(alwaysFails)
    else exhausted
        Step-->>Workflow: return attempt count (or final failure)
    end
    Workflow-->>Mutation: workflow result
    Mutation-->>Client: WorkflowId / result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰✨ I hopped through logs and retries bright,
Counting failures by soft moonlight,
Catching errors, one, two, three—then cheer!
A workflow mended, bound to persevere,
🥕🐇 humming back to life without fear.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The PR title 'Add user stack track to error reporting' is vague and does not clearly convey the main change; it uses non-descriptive phrasing that doesn't indicate the specific implementation. Consider a more specific title like 'Pass RunResult through workflow error handling to include user stack traces' or 'Improve error source tracking in workflow steps'.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed The PR addresses issue #167 by modifying error handling to pass RunResult objects through the workflow context, enabling proper stack trace attribution to user code rather than internal library code.
Out of Scope Changes check ✅ Passed All changes align with the goal of improving error reporting: step.ts and workflowContext.ts refactor error handling, stepContext.test.ts validates the changes, and catchError.ts provides a working example.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ian/error-line-numbers
📝 Coding Plan
  • Generate coding plan for human review comments

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.

Tip

CodeRabbit can approve the review once all CodeRabbit's comments are resolved.

Enable the reviews.request_changes_workflow setting to automatically approve the review once all CodeRabbit's comments are resolved.

@pkg-pr-new

pkg-pr-new Bot commented Mar 10, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@convex-dev/workflow@218

commit: 6d42252

@ianmacartney ianmacartney changed the title pass through RunResult to improve error line tracking Add user stack track to error reporting Mar 10, 2026
@ianmacartney
ianmacartney marked this pull request as ready for review March 10, 2026 06:59

Copy link
Copy Markdown
Member Author

cc @sujayakar finally getting around to some of these tasks

@ianmacartney
ianmacartney requested a review from mikecann March 10, 2026 07:02

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 (1)
example/convex/catchError.ts (1)

24-29: Avoid logging from replayed workflow code.

This handler can rerun from the top on every resume, so these console.error calls will repeat earlier failures. If you want one log per attempt, emit it inside the action or after the workflow finishes.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@example/convex/catchError.ts` around lines 24 - 29, The catch block in the
workflow handler currently logs errors via the console.error calls (the two
branches handling e instanceof Error and the else branch); remove those
console.error calls from the workflow code so logs are not emitted on every
replay, and instead either rethrow the error or record the error in workflow
state and invoke a side-effect/action (or emit the log) from the corresponding
action or after the workflow finishes so the log is produced exactly once per
attempt.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@example/convex/catchError.ts`:
- Around line 16-20: Validate and normalize args.manualRetries before using it
as the loop bound in the handler function: ensure args.manualRetries is a finite
integer >= 0 (e.g., check Number.isFinite and Number.isInteger or coerce with
Math.max(0, Math.floor(...))) and use that sanitized value instead of raw
args.manualRetries in the for loop and final return so the loop runs as intended
and the handler always returns a number; update references to args.manualRetries
in the handler to use the sanitized variable.

In `@src/client/workflowContext.ts`:
- Around line 196-202: The switch currently throws plain Error for both "failed"
and "canceled" cases, which makes cancellations indistinguishable from failures;
create and throw a specific cancellation error class (e.g., CancelledError or
StepCanceledError) in the "canceled" branch instead of new Error("Canceled"),
keep the "failed" branch throwing the existing Error(result.error), and ensure
the new class has an identifiable name/property so callers or retry logic can
detect cancellations (reference the switch on result.kind in
workflowContext.ts).

---

Nitpick comments:
In `@example/convex/catchError.ts`:
- Around line 24-29: The catch block in the workflow handler currently logs
errors via the console.error calls (the two branches handling e instanceof Error
and the else branch); remove those console.error calls from the workflow code so
logs are not emitted on every replay, and instead either rethrow the error or
record the error in workflow state and invoke a side-effect/action (or emit the
log) from the corresponding action or after the workflow finishes so the log is
produced exactly once per attempt.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ef403d86-2b07-4a81-8a51-05b29b4656a5

📥 Commits

Reviewing files that changed from the base of the PR and between 6782ac7 and 31e1251.

⛔ Files ignored due to path filters (1)
  • example/convex/_generated/api.d.ts is excluded by !**/_generated/**
📒 Files selected for processing (3)
  • example/convex/catchError.ts
  • src/client/step.ts
  • src/client/workflowContext.ts

Comment on lines +16 to +20
args: { manualRetries: v.number() },
returns: v.number(),
handler: async (step, args): Promise<number> => {
let i;
for (i = 0; i < args.manualRetries + 1; i++) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# First, find and read the example file
find . -name "catchError.ts" -type f

Repository: get-convex/workflow

Length of output: 93


🏁 Script executed:

# Also search for any Convex validator documentation or type definitions
fd -e ts -e tsx | head -20

Repository: get-convex/workflow

Length of output: 657


🌐 Web query:

Convex v.number() validator accepts negative values non-integer

💡 Result:

v.number() in Convex validates the type “Float64”, i.e. any JavaScript number, not a “positive integer” or “non-negative” constraint. That means it will accept:

  • negative numbers (e.g. -3)
  • non-integers/decimals (e.g. 2.5)
  • generally any IEEE-754 double value (Convex even notes it supports NaNs, etc.) [1]

If you need an integer:

  • Use v.int64() only if you can represent the value as a JS bigint (e.g. 3n) and you truly want an Int64 value. [1]

If you need a non-negative integer in a number:

  • Keep v.number() and add a manual check in your function handler, e.g. Number.isInteger(n) && n >= 0, and throw an error if it fails (because Convex’s built-in validators are primarily about types/shape, not numeric ranges). [1]

Sources: [1] Convex docs: Argument and Return Value Validation (Float64 = v.number(), Int64 = v.int64(), notes on Float64 values).


🏁 Script executed:

cat -n example/convex/catchError.ts

Repository: get-convex/workflow

Length of output: 1723


Validate manualRetries before using it as a loop bound.

v.number() accepts negative and non-integer values. With manualRetries = -1, the loop condition 0 < 0 is false, the loop never executes, and Line 32 returns undefined, violating the declared v.number() return contract.

Possible fix
   handler: async (step, args): Promise<number> => {
+    if (!Number.isInteger(args.manualRetries) || args.manualRetries < 0) {
+      throw new Error("manualRetries must be a non-negative integer");
+    }
     let i;
     for (i = 0; i < args.manualRetries + 1; i++) {
📝 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
args: { manualRetries: v.number() },
returns: v.number(),
handler: async (step, args): Promise<number> => {
let i;
for (i = 0; i < args.manualRetries + 1; i++) {
args: { manualRetries: v.number() },
returns: v.number(),
handler: async (step, args): Promise<number> => {
if (!Number.isInteger(args.manualRetries) || args.manualRetries < 0) {
throw new Error("manualRetries must be a non-negative integer");
}
let i;
for (i = 0; i < args.manualRetries + 1; i++) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@example/convex/catchError.ts` around lines 16 - 20, Validate and normalize
args.manualRetries before using it as the loop bound in the handler function:
ensure args.manualRetries is a finite integer >= 0 (e.g., check Number.isFinite
and Number.isInteger or coerce with Math.max(0, Math.floor(...))) and use that
sanitized value instead of raw args.manualRetries in the for loop and final
return so the loop runs as intended and the handler always returns a number;
update references to args.manualRetries in the handler to use the sanitized
variable.

Comment on lines +196 to +202
switch (result.kind) {
case "success":
return result.returnValue;
case "failed":
throw new Error(result.error);
case "canceled":
throw new Error("Canceled");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Keep cancellations distinguishable from ordinary failures.

Both branches now throw plain Error, so callers that intentionally catch step failures can't reliably stop on cancellation. The new retry example will also retry canceled steps because the only signal left is the message string.

Possible fix
     case "success":
       return result.returnValue;
     case "failed":
-      throw new Error(result.error);
+      throw Object.assign(new Error(result.error), { kind: "failed" as const });
     case "canceled":
-      throw new Error("Canceled");
+      throw Object.assign(new Error("Canceled"), { kind: "canceled" as const });
     default:
       throw new Error("Unknown result kind: " + (result as any).kind);
📝 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
switch (result.kind) {
case "success":
return result.returnValue;
case "failed":
throw new Error(result.error);
case "canceled":
throw new Error("Canceled");
switch (result.kind) {
case "success":
return result.returnValue;
case "failed":
throw Object.assign(new Error(result.error), { kind: "failed" as const });
case "canceled":
throw Object.assign(new Error("Canceled"), { kind: "canceled" as const });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/workflowContext.ts` around lines 196 - 202, The switch currently
throws plain Error for both "failed" and "canceled" cases, which makes
cancellations indistinguishable from failures; create and throw a specific
cancellation error class (e.g., CancelledError or StepCanceledError) in the
"canceled" branch instead of new Error("Canceled"), keep the "failed" branch
throwing the existing Error(result.error), and ensure the new class has an
identifiable name/property so callers or retry logic can detect cancellations
(reference the switch on result.kind in workflowContext.ts).

@mikecann

Copy link
Copy Markdown
Member

Look good Ian tho I have to admit I don't fully understand it.

Do you think this could benefit from a unit test or two?

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.

Validator error should specify source (line no. or calling function)

2 participants