Skip to content

Add NonRetryableError type - #197

Merged
ianmacartney merged 9 commits into
convex:mainfrom
danthegoodman1:main
May 20, 2026
Merged

ianmacartney merged 9 commits into
convex:mainfrom
danthegoodman1:main

Conversation

@danthegoodman1

@danthegoodman1 danthegoodman1 commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes #196

Adds a non-retryable error type to workpools that will immediately fail the action or mutation rather than attempting to retry.

This is important for known-permanent failures, especially in workflows, where you don't want things to retry (e.g. date range validation).

Using this wasn't an ideal solution, but it seems to be the best considering that errors have to be serialized with Convex https://github.com/get-convex/workpool/pull/197/changes#diff-039becadccd934ea0ec18f1aaea16e0f7725553d5314b5d3876cebb97b0a060aR3-R7


By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

@coderabbitai

coderabbitai Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds a non-retryable error mechanism to Workpool: a new NonRetryableError class and helpers (isNonRetryableError, getNonRetryableErrorMessage), re-exports these from the client entrypoint, updates worker wrappers to detect and propagate a nonRetryable flag, and updates completion logic to skip retries when that flag is set. It includes unit and integration tests, example flows demonstrating terminal action/mutation behavior, and README documentation describing the terminal-failure semantics.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant WorkerWrapper
    participant UserCode
    participant ErrorDetector
    participant CompletionJob
    participant WorkpoolStore

    Client->>WorkerWrapper: enqueue action/mutation (with retry config)
    WorkerWrapper->>UserCode: execute handler
    UserCode-->>WorkerWrapper: throws NonRetryableError
    WorkerWrapper->>ErrorDetector: isNonRetryableError(error)
    ErrorDetector-->>WorkerWrapper: true
    WorkerWrapper->>CompletionJob: schedule complete(workId, runResult: failed, attempt, nonRetryable: true)
    CompletionJob->>WorkpoolStore: load work entry by workId
    WorkpoolStore-->>CompletionJob: work found
    CompletionJob->>WorkpoolStore: mark failed, remove work, create pendingCompletion (retry: false)
    CompletionJob-->>Client: invoke onComplete with { kind: "failed", error }
Loading

Suggested reviewers

  • ianmacartney
  • reeceyang
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add NonRetryableError type' directly and clearly describes the main change—introduction of a new error type for marking errors as non-retryable.
Description check ✅ Passed The description is related to the changeset, explaining the purpose of NonRetryableError, use cases, and implementation constraints with Convex error serialization.
Linked Issues check ✅ Passed The changeset fully implements issue #196 by introducing NonRetryableError type with detection logic, integrating it into the worker and complete mutation, and providing comprehensive tests and documentation.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing NonRetryableError functionality; the only tangential change (backoff timing in stateMachine.test.ts) is a necessary test fix for flakiness, not out-of-scope.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@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

🤖 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/example.ts`:
- Line 41: The module-scoped variable terminalMutationAttempts is unsafe in
Convex; replace it with durable state stored in the database and update the
three places that reference it (resetTerminalMutationAttempts,
terminalMutationAttemptCount, and terminalMutation) to read/write that DB-backed
counter instead of the module variable; implement atomic operations (e.g.,
Convex document get/update or an incrementing transaction) for incrementing
attempts in terminalMutation and for resetting in resetTerminalMutationAttempts,
and have terminalMutationAttemptCount read the latest persisted value so
concurrent invocations see a consistent count.

In `@src/component/errors.ts`:
- Around line 39-61: getNonRetryableErrorMessage currently handles
NonRetryableError and ConvexError but ignores plain marker-shaped objects that
isNonRetryableError accepts; update getNonRetryableErrorMessage to mirror
isNonRetryableError by checking for a marker-shaped object (inspect (error as
Partial<NonRetryableErrorMarker>)[NON_RETRYABLE_ERROR_MARKER] === true) and,
when present, return the embedded message (e.g., (error as
Partial<NonRetryableErrorMarker>).message) so that marker-based non-retryable
errors preserve their original message; keep existing branches using
getNonRetryableErrorData and ConvexError unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: get-convex/coderabbit/.coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 65f0617f-15cf-468f-8280-3148fb5e69e6

📥 Commits

Reviewing files that changed from the base of the PR and between 7da34f4 and 938674a.

📒 Files selected for processing (9)
  • README.md
  • example/convex/example.test.ts
  • example/convex/example.ts
  • src/client/index.ts
  • src/component/complete.test.ts
  • src/component/complete.ts
  • src/component/errors.test.ts
  • src/component/errors.ts
  • src/component/worker.ts

Comment thread example/convex/example.ts Outdated
logLevel: "INFO",
});
const console = createLogger("DEBUG");
let terminalMutationAttempts = 0;

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

🧩 Analysis chain

🌐 Web query:

In Convex, are module-level variables guaranteed to be durable/consistent across invocations and isolates, or should counters for correctness be stored in the database?

💡 Result:

No, module-level variables in Convex are not guaranteed to be durable or consistent across invocations and isolates. Convex runs functions in an isolated, serverless environment where each function invocation executes in a fresh isolate. Module state, such as variables declared with let or const at the module top-level, is loaded per invocation and does not persist across different function calls or concurrent executions. Even within the same deployment, modules are not reevaluated on every run, but changes to mutable module-level state (e.g., if assigned to) would not survive across separate invocations due to the stateless nature of the serverless runtime. For counters requiring correctness, especially under high contention or concurrency, they must be stored in the database. Official best practices and components like the Sharded Counter emphasize database storage to ensure atomicity, consistency, reactivity, and scalability. Using module variables for counters would lead to lost updates, race conditions, or optimistic concurrency control (OCC) conflicts, as seen in scaling guides that recommend sharded database documents instead.

Citations:


🏁 Script executed:

# First, let's find and verify the file exists
find . -type f -name "example.ts" | head -20

Repository: get-convex/workpool

Length of output: 91


🏁 Script executed:

# Get file info and read the relevant sections
wc -l ./example/convex/example.ts
echo "---"
# Read around line 41
sed -n '35,50p' ./example/convex/example.ts
echo "---"
# Read around lines 107-117
sed -n '100,125p' ./example/convex/example.ts

Repository: get-convex/workpool

Length of output: 1298


Use durable state instead of a module-scoped retry counter.

Line 41 introduces process-local mutable state. In Convex execution environments, each invocation executes in a fresh isolate where module-level state is not persisted, causing the counter operations in resetTerminalMutationAttempts, terminalMutationAttemptCount, and terminalMutation to become flaky and unreliable. For correctness under concurrency, counters must be stored in the database.

💡 Proposed durable-state fix
-let terminalMutationAttempts = 0;
+const TERMINAL_MUTATION_MARKER = "terminal-mutation-attempt";

 export const resetTerminalMutationAttempts = mutation({
   args: {},
-  handler: async () => {
-    terminalMutationAttempts = 0;
+  handler: async (ctx) => {
+    const attempts = await ctx.db
+      .query("data")
+      .filter((q) => q.eq(q.field("misc"), TERMINAL_MUTATION_MARKER))
+      .collect();
+    await Promise.all(attempts.map((doc) => ctx.db.delete(doc._id)));
   },
 });

 export const terminalMutationAttemptCount = query({
   args: {},
-  handler: async () => terminalMutationAttempts,
+  handler: async (ctx) => {
+    const attempts = await ctx.db
+      .query("data")
+      .filter((q) => q.eq(q.field("misc"), TERMINAL_MUTATION_MARKER))
+      .collect();
+    return attempts.length;
+  },
 });

 export const terminalMutation = internalMutation({
   args: {},
-  handler: async () => {
-    terminalMutationAttempts++;
+  handler: async (ctx) => {
+    await ctx.db.insert("data", { data: 0, misc: TERMINAL_MUTATION_MARKER });
     throw new NonRetryableError("terminal mutation failure");
   },
 });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@example/convex/example.ts` at line 41, The module-scoped variable
terminalMutationAttempts is unsafe in Convex; replace it with durable state
stored in the database and update the three places that reference it
(resetTerminalMutationAttempts, terminalMutationAttemptCount, and
terminalMutation) to read/write that DB-backed counter instead of the module
variable; implement atomic operations (e.g., Convex document get/update or an
incrementing transaction) for incrementing attempts in terminalMutation and for
resetting in resetTerminalMutationAttempts, and have
terminalMutationAttemptCount read the latest persisted value so concurrent
invocations see a consistent count.

Comment thread src/component/errors.ts Resolved
@pkg-pr-new

pkg-pr-new Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/get-convex/workpool/@convex-dev/workpool@197

commit: 3eb640f

@danthegoodman1

Copy link
Copy Markdown
Contributor Author

From the failing test:

 FAIL  src/component/stateMachine.test.ts > state machine > multi-step / interleaved transitions > two jobs complete(retry) before main -> main retries both
AssertionError: expected false to be true // Object.is equality

- Expected
+ Received

- true
+ false

 ❯ src/component/stateMachine.test.ts:917:31
    915|       // With small backoff (100ms), retry pendingStarts are immediate…

    916|       // by handleStart in the same main pass, so both jobs are runnin…
 Test Files  1 failed | 12 passed (13)
    917|       expect(s1After.running).toBe(true);
      Tests  1 failed | 131 passed (132)
       |                               ^
Type Errors  no errors
   Start at  23:10:59
   Duration  2.20s (transform 670ms, setup 0ms, import 1.41s, tests 1.58s, environment 1.11s)

    918|       expect(s2After.running).toBe(true);
    919|       expect(s1After.pendingStart).toBe(false);

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯


Error: AssertionError: expected false to be true // Object.is equality

- Expected
+ Received

- true
+ false

 ❯ src/component/stateMachine.test.ts:917:31


Error: Process completed with exit code 1.

This looks like a flaky assumption in the test (passes on my machine, GitHub actions runners are super slow): it expects a retry with 100ms backoff plus jitter to be picked up in the same main pass. Since jitter can push the retry into the next segment, that assertion can flip. I made the test deterministic instead Math.random().

@ianmacartney

Copy link
Copy Markdown
Member

Thanks Dan! I've wanted something like this for a while - I'll give it a deeper look soon to make sure it's aligned with future plans before upstreaming

@danthegoodman1

Copy link
Copy Markdown
Contributor Author

Of course. Feel free to make any changes you think are needed.

@ianmacartney

ianmacartney commented May 15, 2026 via email

Copy link
Copy Markdown
Member

@danthegoodman1

Copy link
Copy Markdown
Contributor Author

Yeah I was just about to check in on this, we definitely need it in mainline release now

@danthegoodman1

Copy link
Copy Markdown
Contributor Author

@ianmacartney just bumping this, will we be able to get this in soon?

@ianmacartney ianmacartney left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

can you rebase this on main and move the example / test usage out of example.ts please?

The carrying of extra typed data seems like overkill given that it's only ever observable by clients in RunResult, which only carries a message?

@ianmacartney

Copy link
Copy Markdown
Member

I guess it's a clean merge now, so rebasing isn't strictly necessary. I kicked off the workflow so you can use the pkg-pr-new build to verify

@ianmacartney

Copy link
Copy Markdown
Member

As much as it can be simplified would be appreciated - but overall lgmt

@danthegoodman1

Copy link
Copy Markdown
Contributor Author

yep, doing it now

@ianmacartney ianmacartney left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm on board - some small cleanup / clarification, then I'd happily release it in a main version

Comment thread example/convex/test/nonRetryable.ts Resolved
Comment thread example/convex/test/nonRetryable.ts Resolved
Comment thread example/convex/test/nonRetryable.ts Resolved
Comment thread example/convex/example.test.ts Resolved
Comment thread example/convex/test/nonRetryable.ts Resolved
Comment thread src/component/errors.ts Resolved
Comment thread src/component/errors.ts Resolved
Comment thread src/component/errors.ts Resolved
Comment thread src/component/stateMachine.test.ts Resolved
fix hacky error check with clear object

use public api

dont fall back to global
@ianmacartney
ianmacartney merged commit 2a0f010 into convex:main May 20, 2026
3 checks passed
@ianmacartney

Copy link
Copy Markdown
Member

published in @convex-dev/workpool@0.4.7-alpha.1

@ianmacartney

Copy link
Copy Markdown
Member

Thanks Dan, really nice work!

@danthegoodman1

Copy link
Copy Markdown
Contributor Author

Thanks Dan, really nice work!

o7

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.

Non-retryable errors

2 participants