Skip to content

fix: contain abort retries during gateway restart (#17589) - #17940

Closed
amabito wants to merge 4 commits into
openclaw:mainfrom
amabito:fix/17589-abort-classifier
Closed

amabito wants to merge 4 commits into
openclaw:mainfrom
amabito:fix/17589-abort-classifier

Conversation

@amabito

@amabito amabito commented Feb 16, 2026 •

Copy link
Copy Markdown

Summary

During a SIGUSR1 gateway restart, all in-flight fetch requests abort. Without classification, every AbortError is treated as a transient network failure and retried up to 5x with the full session context (100k+ tokens), causing $10+/day in wasted LLM spend.

This PR adds a lightweight abort classifier that distinguishes restart, user-cancel, timeout, and transient abort causes, and wires it into the two retry layers (delivery queue recovery and retryAsync) so that non-retryable aborts fail immediately.

Fixes #17589

Changes

File Change
src/infra/abort-classifier.ts New - classifyAbort(), isRestartAbort(), isNonRetryableAbort()
src/infra/abort-classifier.test.ts New - 13 Vitest test cases
src/infra/restart.ts Add gatewayRestarting flag with get/set
src/cli/gateway-cli/run-loop.ts Set flag before server?.close(), clear on new iteration
src/cli/gateway-cli/run-loop.test.ts Add setGatewayRestarting to restart.js mock
src/infra/retry.ts Break immediately on non-retryable aborts (both overloads)
src/infra/outbound/delivery-queue.ts Move non-retryable aborts straight to failed/
src/gateway/server-methods/chat.ts User-friendly error messages for restart/cancel aborts

Total: 8 files, ~280 LOC added, 4 LOC changed. No breaking changes. No new dependencies.

Abort Classification

Type Source Should Retry?
restart Gateway SIGUSR1 (isGatewayRestarting()) No
user UI abort (cause.source === "user") No
timeout Fetch timeout (TimeoutError cause) Yes
transient Network drop (default) Yes

How It Works

  1. classifyAbort() inspects AbortError properties to determine the abort type (restart, user, timeout, or transient).
  2. Restart- and user-induced aborts are treated as non-retryable across both retry layers (retryAsync() and recoverPendingDeliveries()).
  3. The gateway restart flag is set immediately before server?.close() inside request(), ensuring it only becomes true when active connections are actually being aborted. This avoids a race where the flag could be set too early during the drain phase.
  4. The flag is cleared at the start of the next run-loop iteration (setGatewayRestarting(false)) to avoid stale restart state after the gateway is back up.
  5. chat.ts error handler surfaces "Gateway restarting. Please retry your message." instead of the misleading raw error.

This preserves existing retry semantics for transient failures while preventing unintended full-run re-execution during restart windows.

Test Plan

  • 13 unit tests covering all classification paths (restart, user, timeout, transient, non-abort errors, undici message variant, nested AbortError, non-"user" source)
  • CI green (bun test, node test, Windows test, formal conformance, install smoke)
  • Manual: kill -USR1 $(pgrep -f "openclaw gateway") during active chat -- verify 0 retries in logs
  • Manual: Verify Anthropic Console shows no duplicate API calls after restart

Greptile Summary

Adds an abort classifier (classifyAbort) that distinguishes restart, user-cancel, timeout, and transient abort causes, and wires it into both retry layers (retryAsync and recoverPendingDeliveries) so that restart- and user-induced aborts fail immediately without costly retries. The gatewayRestarting flag is set just before server?.close() and cleared at the start of each run-loop iteration, avoiding both the early-flag race and stale-flag problems.

  • src/infra/abort-classifier.ts — New module with classifyAbort(), isRestartAbort(), and isNonRetryableAbort() plus internal helpers for undici message detection, user-cancel cause inspection, and timeout cause matching.
  • src/infra/restart.ts — Adds gatewayRestarting flag with isGatewayRestarting()/setGatewayRestarting() accessors; flag is included in __testing.resetSigusr1State().
  • src/cli/gateway-cli/run-loop.ts — Sets flag to true immediately before server?.close() (post-drain); clears to false at the top of each while-loop iteration.
  • src/infra/retry.ts — Both retryAsync overloads now break immediately on non-retryable aborts.
  • src/infra/outbound/delivery-queue.ts — recoverPendingDeliveries moves non-retryable aborts straight to failed/ instead of incrementing retry count.
  • src/gateway/server-methods/chat.ts — Surfaces user-friendly messages ("Gateway restarting" / "Request cancelled") for restart/user aborts instead of the generic error.
  • src/infra/abort-classifier.test.ts — 13 test cases covering all classification paths.

Confidence Score: 4/5

  • This PR is safe to merge — it adds a well-scoped abort classifier with no breaking changes to existing retry semantics for transient/timeout failures.
  • Score of 4 reflects: clean implementation, good test coverage of the classifier, correct flag lifecycle management, and no regressions to existing retry paths. Deducted one point because the classification priority (restart checked before user-cancel) means user cancellations during a restart window get a "Gateway restarting" message instead of "Request cancelled", and because the run-loop test doesn't assert on setGatewayRestarting call ordering — though neither issue affects correctness of the retry-prevention goal.
  • No files require special attention — the implementation is straightforward across all changed files.

Last reviewed commit: daed892

Add a lightweight AbortError classifier that distinguishes restart,
user-cancel, timeout and transient abort causes. During a SIGUSR1
restart cycle every in-flight fetch is aborted; without classification
these are retried up to 5x with the full session context, causing
$10+/day in wasted LLM spend.

Changes:
- New `abort-classifier.ts` with `classifyAbort()`, `isRestartAbort()`,
  `isNonRetryableAbort()` helpers
- `restart.ts`: add `gatewayRestarting` flag set/cleared by run loop
- `run-loop.ts`: set flag on SIGUSR1, clear on new iteration
- `retry.ts`: break immediately on non-retryable aborts (both overloads)
- `delivery-queue.ts`: move non-retryable aborts straight to failed/
- `chat.ts`: surface user-friendly messages for restart/cancel aborts
- 9 Vitest test cases covering all classification paths

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

7 files reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

Comment thread src/cli/gateway-cli/run-loop.ts Outdated
Comment on lines 132 to 134
setGatewayRestarting(true);
markGatewaySigusr1RestartHandled();
request("restart", "SIGUSR1");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Race condition: flag set too early, before server shutdown begins

setGatewayRestarting(true) is called here, but the actual server shutdown (which aborts fetch requests) happens later in the async request() function (line 77). Between lines 132-134 and line 77, there's a delay where:

  1. The flag is true
  2. But fetch requests haven't been aborted yet
  3. New requests could start and immediately see isGatewayRestarting() === true

This means new requests that start after line 132 but before line 77 will be classified as "restart" aborts even though they were never actually aborted by the restart process.

Move setGatewayRestarting(true) to just before server?.close() (around line 77) to ensure the flag is only set when fetch requests are actually being aborted.

Suggested change
setGatewayRestarting(true);
markGatewaySigusr1RestartHandled();
request("restart", "SIGUSR1");
const authorized = consumeGatewaySigusr1RestartAuthorization();
if (!authorized && !isGatewaySigusr1RestartExternallyAllowed()) {
gatewayLog.warn(
"SIGUSR1 restart ignored (not authorized; enable commands.restart or use gateway tool).",
);
return;
}
markGatewaySigusr1RestartHandled();
request("restart", "SIGUSR1");
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/cli/gateway-cli/run-loop.ts
Line: 132:134

Comment:
Race condition: flag set too early, before server shutdown begins

`setGatewayRestarting(true)` is called here, but the actual server shutdown (which aborts fetch requests) happens later in the async `request()` function (line 77). Between lines 132-134 and line 77, there's a delay where:
1. The flag is `true`
2. But fetch requests haven't been aborted yet
3. New requests could start and immediately see `isGatewayRestarting() === true`

This means new requests that start after line 132 but before line 77 will be classified as "restart" aborts even though they were never actually aborted by the restart process.

Move `setGatewayRestarting(true)` to just before `server?.close()` (around line 77) to ensure the flag is only set when fetch requests are actually being aborted.

```suggestion
    const authorized = consumeGatewaySigusr1RestartAuthorization();
    if (!authorized && !isGatewaySigusr1RestartExternallyAllowed()) {
      gatewayLog.warn(
        "SIGUSR1 restart ignored (not authorized; enable commands.restart or use gateway tool).",
      );
      return;
    }
    markGatewaySigusr1RestartHandled();
    request("restart", "SIGUSR1");
```

How can I resolve this? If you propose a fix, please make it concise.

@greptile-apps

greptile-apps Bot commented Feb 16, 2026

Copy link
Copy Markdown
Contributor
Additional Comments (1)

src/cli/gateway-cli/run-loop.ts
Missing setGatewayRestarting(true) call before aborting connections

To fix the race condition, add setGatewayRestarting(true) here, just before calling server?.close(). This ensures the flag is only set when the server is actually closing and aborting active fetch requests.

        if (isRestart) {
          setGatewayRestarting(true);
        }
        await server?.close({
          reason: isRestart ? "gateway restarting" : "gateway stopping",
          restartExpectedMs: isRestart ? 1500 : null,
        });
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/cli/gateway-cli/run-loop.ts
Line: 77:80

Comment:
Missing `setGatewayRestarting(true)` call before aborting connections

To fix the race condition, add `setGatewayRestarting(true)` here, just before calling `server?.close()`. This ensures the flag is only set when the server is actually closing and aborting active fetch requests.

```suggestion
        if (isRestart) {
          setGatewayRestarting(true);
        }
        await server?.close({
          reason: isRestart ? "gateway restarting" : "gateway stopping",
          restartExpectedMs: isRestart ? 1500 : null,
        });
```

How can I resolve this? If you propose a fix, please make it concise.

amabito and others added 3 commits February 16, 2026 18:55
Move setGatewayRestarting(true) from the SIGUSR1 handler into the
request() async function, right before server?.close(). This prevents
new requests arriving between flag-set and actual close from being
misclassified as restart aborts.
The vi.mock for restart.js was missing the setGatewayRestarting export
added in the previous commit, causing Vitest to throw at runtime.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@amabito

amabito commented Feb 16, 2026

Copy link
Copy Markdown
Author

Thanks for the review — agreed on the race condition.

I've moved setGatewayRestarting(true) so it is set immediately before server?.close() inside request(), and removed the early flag from the SIGUSR1 handler. This ensures the flag only becomes true when connections are actually being aborted.

Let me know if you'd like further tightening.

@amabito

amabito commented Feb 16, 2026

Copy link
Copy Markdown
Author

CI is now fully green (including node and Windows test suites).

To summarize the scope clearly:

  • Classifies AbortError (restart vs user vs transient/timeout)
  • Prevents run-level retries for restart/user-induced aborts
  • Applies consistently across both retry layers (delivery queue + retryAsync)
  • Fixes the restart flag race by setting it only at the actual shutdown boundary

No new dependencies, no behavior changes outside restart scenarios, and existing retry semantics for transient failures remain intact.

Happy to make any small naming or structural adjustments if preferred.

@amabito amabito mentioned this pull request Feb 16, 2026
3 tasks done
@amabito

amabito commented Feb 16, 2026

Copy link
Copy Markdown
Author

Heads up: this PR focuses specifically on the remaining scope called out in #17589 ("retry/error messaging behavior" after #15026).

It should be complementary to the ongoing SIGUSR1 drain/timeout work (e.g., #17445): even with drain hardening, preventing run-level retries on restart/user aborts is still needed to avoid the high-cost re-execution path.

CI is green; happy to rebase promptly if any overlap lands first.

@steipete steipete closed this Feb 16, 2026
@steipete steipete reopened this Feb 17, 2026
@amabito amabito closed this Feb 17, 2026
@amabito
amabito deleted the fix/17589-abort-classifier branch February 17, 2026 01:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui cli CLI command changes gateway Gateway runtime size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Gateway restart/AbortError triggers full LLM-run retries (Opus cost explosion) + misleading “API rate limit reached”

2 participants