Repository navigation
Add NonRetryableError type - #197
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis 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 }
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (9)
README.mdexample/convex/example.test.tsexample/convex/example.tssrc/client/index.tssrc/component/complete.test.tssrc/component/complete.tssrc/component/errors.test.tssrc/component/errors.tssrc/component/worker.ts
| logLevel: "INFO", | ||
| }); | ||
| const console = createLogger("DEBUG"); | ||
| let terminalMutationAttempts = 0; |
There was a problem hiding this comment.
🧩 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:
- 1: https://docs.convex.dev/llms-full.txt
- 2: https://docs.convex.dev/components/understanding
- 3: https://docs.convex.dev/understanding/best-practices/
- 4: https://github.com/get-convex/sharded-counter/blob/main/README.md
- 5: https://docs.convex.dev/functions/bundling.md
- 6: https://docs.convex.dev/tutorial/scale.md
- 7: https://github.com/get-convex/convex-backend/blob/feffea82/crates/function_runner/src/server.rs
🏁 Script executed:
# First, let's find and verify the file exists
find . -type f -name "example.ts" | head -20Repository: 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.tsRepository: 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.
commit: |
|
From the failing test: 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 |
|
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 |
|
Of course. Feel free to make any changes you think are needed. |
|
sorry for the delay here - I'm still tracking it but have had other high
priority things in flight. I agree with this directionally, but want to dig
in before merging
…On Mon, May 4, 2026 at 1:33 PM Dan Goodman ***@***.***> wrote:
*danthegoodman1* left a comment (convex/workpool#197)
<#197 (comment)>
Of course. Feel free to make any changes you think are needed.
—
Reply to this email directly, view it on GitHub
<#197 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AACZQW3FQXP5DKTTIIGSNPT4ZD5CVAVCNFSM6AAAAACYJUSY72VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHM2DGNZUGI3TSOBXGQ>
.
You are receiving this because you commented.Message ID:
***@***.***>
|
|
Yeah I was just about to check in on this, we definitely need it in mainline release now |
|
@ianmacartney just bumping this, will we be able to get this in soon? |
ianmacartney
left a comment
There was a problem hiding this comment.
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?
|
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 |
|
As much as it can be simplified would be appreciated - but overall lgmt |
|
yep, doing it now |
ianmacartney
left a comment
There was a problem hiding this comment.
I'm on board - some small cleanup / clarification, then I'd happily release it in a main version
fix hacky error check with clear object use public api dont fall back to global
|
published in |
|
Thanks Dan, really nice work! |
o7 |
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.