mirror of
https://github.com/bitbaum/openclaw.git
synced 2026-12-03 16:47:18 +01:00
fix(web-fetch): honor cancellation before caching or returning provider results (#131585)
* fix(web-fetch): honor cancellation in the provider fallback Pass the optional AbortSignal execution context through fetch providers and the Firecrawl adapter. Reject late provider results before wrapping or caching, recheck after asynchronous payload construction, and preserve cancellation through HTML fallback recovery. * fix(web-fetch): finalize cancellation before caching results Reject pre-aborted cache hits and preserve cancellation when a provider or guard cleanup fails after abort. Centralize direct and provider cache publication after the complete fetch lifecycle so cancellation during release cannot leave a successful entry. Extend all four fallback cancellation cases with late provider failures, cover direct/provider pre-aborted cache hits and guard-release races, and document the completed cancellation boundary. * fix(web-fetch): scope the post-cancellation guard to provider failures The cancellation guard sat in runWebFetch's catch, so a fetch that rejected *because of* the abort had its original error replaced by signal.reason. That discarded the transport's own failure detail and changed an existing contract: web-tools.fetch.test.ts asserts the tool surfaces the aborted fetch's error. fetchWebPayload already rethrows the original error when the signal aborted, so the outer guard only ever needed to cover the provider-fallback path, where a late failure should surface the caller's abort reason rather than an error from work the caller had already abandoned. Move it there and drop the outer catch. * docs(web-fetch): state cancellation forwarding and error preservation accurately Two wording corrections from deep review. The inline comment claimed an abort-caused fetch rejection "already carries the caller's reason", which the regression test deliberately shows is not always true; the code preserves the right object regardless. The docs implied cancellation stops provider work, when core only forwards the signal and rejects late results.
This commit is contained in:
1 parent
36b8127c54
commit
b6306da1a9
7 files changed
+271
-46
No files matched your search
@@ -1136,6 +1136,12 @@ catalog, API-key auth, and dynamic model resolution.
|
||||
original expiry. Reads return a payload marked `cached: true`, or
|
||||
`undefined` on a miss. The reader's `ttlMs` argument is optional:
|
||||
existing one-argument calls continue to use the stored expiry alone.
|
||||
|
||||
Both tool definitions accept `execute(args, context?)`, where the optional
|
||||
context carries `signal?: AbortSignal`. Forward that signal to network
|
||||
requests and check cancellation after asynchronous work. Existing
|
||||
one-argument implementations remain valid; OpenClaw rejects late fetch
|
||||
results after cancellation before publishing them to its fetch cache.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
|
||||
@@ -101,6 +101,13 @@ Fast cache hits and quick network responses finish before the timer fires, so
|
||||
they never show a progress line. Canceling the call clears the timer. The
|
||||
progress line is channel UI state only and never contains fetched page content.
|
||||
|
||||
OpenClaw passes cancellation to fallback providers. Providers that honor the
|
||||
signal can stop their requests; core rejects late results even when a provider
|
||||
ignores cancellation. Already-canceled calls reject even when a cached result
|
||||
exists. If cancellation occurs during fetching, fallback processing, or
|
||||
connection cleanup, OpenClaw rejects the call instead of returning success or
|
||||
adding a result to the fetch cache.
|
||||
|
||||
## Config
|
||||
|
||||
```json5
|
||||
|
||||
@@ -16,7 +16,8 @@ export function createFirecrawlWebFetchProvider(): WebFetchProviderPlugin {
|
||||
createTool: ({ config }) => ({
|
||||
description: "Fetch a page using Firecrawl.",
|
||||
parameters: {},
|
||||
execute: async (args) => {
|
||||
execute: async (args, executionContext) => {
|
||||
executionContext?.signal?.throwIfAborted();
|
||||
const url = typeof args.url === "string" ? args.url : "";
|
||||
const extractMode = args.extractMode === "text" ? "text" : "markdown";
|
||||
const maxChars = readPositiveIntegerParam(args, "maxChars");
|
||||
@@ -32,6 +33,7 @@ export function createFirecrawlWebFetchProvider(): WebFetchProviderPlugin {
|
||||
extractMode,
|
||||
access: "keyless",
|
||||
maxChars,
|
||||
...(executionContext?.signal ? { signal: executionContext.signal } : {}),
|
||||
...(proxy ? { proxy } : {}),
|
||||
...(storeInCache !== undefined ? { storeInCache } : {}),
|
||||
});
|
||||
|
||||
@@ -875,30 +875,33 @@ describe("firecrawl tools", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["paid", "free"] as const)(
|
||||
"forwards exact cancellation through the registered %s web-search provider",
|
||||
it.each(["paid", "free", "fetch"] as const)(
|
||||
"forwards exact cancellation through the registered %s web provider",
|
||||
async (kind) => {
|
||||
const provider =
|
||||
kind === "paid"
|
||||
? createFirecrawlWebSearchProvider()
|
||||
: createFirecrawlFreeWebSearchProvider();
|
||||
: kind === "free"
|
||||
? createFirecrawlFreeWebSearchProvider()
|
||||
: createFirecrawlWebFetchProvider();
|
||||
const tool = provider.createTool({ config: { test: true } } as never);
|
||||
expect(tool).not.toBeNull();
|
||||
const controller = new AbortController();
|
||||
const run = kind === "fetch" ? runFirecrawlScrape : runFirecrawlSearch;
|
||||
const args =
|
||||
kind === "fetch"
|
||||
? { url: "https://example.com/cancellation" }
|
||||
: { query: `${kind} cancellation` };
|
||||
|
||||
await tool!.execute({ query: `${kind} cancellation` }, { signal: controller.signal });
|
||||
await tool!.execute(args, { signal: controller.signal });
|
||||
|
||||
expect(runFirecrawlSearch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ signal: controller.signal }),
|
||||
);
|
||||
expect(run).toHaveBeenCalledWith(expect.objectContaining({ signal: controller.signal }));
|
||||
|
||||
const reason = new Error(`${kind} provider cancelled`);
|
||||
controller.abort(reason);
|
||||
runFirecrawlSearch.mockClear();
|
||||
await expect(
|
||||
tool!.execute({ query: `${kind} cancelled` }, { signal: controller.signal }),
|
||||
).rejects.toBe(reason);
|
||||
expect(runFirecrawlSearch).not.toHaveBeenCalled();
|
||||
run.mockClear();
|
||||
await expect(tool!.execute(args, { signal: controller.signal })).rejects.toBe(reason);
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { isRecord } from "@openclaw/normalization-core/record-coerce";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createDeferred } from "../../../test/helpers/promise.js";
|
||||
import type { WebFetchProviderToolDefinition } from "../../plugin-sdk/provider-web-fetch.js";
|
||||
import { withFetchPreconnect } from "../../test-utils/fetch-mock.js";
|
||||
import { createWebFetchTool } from "./web-fetch.js";
|
||||
import * as webGuardedFetch from "./web-guarded-fetch.js";
|
||||
|
||||
const { resolveWebFetchDefinition } = vi.hoisted(() => ({
|
||||
resolveWebFetchDefinition: vi.fn(),
|
||||
}));
|
||||
vi.mock("../../web-fetch/runtime.js", () => ({ resolveWebFetchDefinition }));
|
||||
vi.mock("../../web-fetch/content-extractors.runtime.js", () => ({
|
||||
extractReadableContent: vi.fn(async () => null),
|
||||
}));
|
||||
|
||||
describe("web_fetch provider cancellation", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
resolveWebFetchDefinition.mockReset();
|
||||
});
|
||||
|
||||
it.each(
|
||||
["network-error", "http-error", "empty-readability", "disabled-readability"].flatMap(
|
||||
(fallback) => ["success", "failure"].map((completion) => ({ fallback, completion })),
|
||||
),
|
||||
)(
|
||||
"rejects late provider $completion without caching after $fallback",
|
||||
async ({ fallback, completion }) => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
withFetchPreconnect(
|
||||
vi.fn(async () => {
|
||||
if (fallback === "network-error") {
|
||||
throw new Error("network failed");
|
||||
}
|
||||
return new Response("<html><body>Upstream content</body></html>", {
|
||||
status: fallback === "http-error" ? 503 : 200,
|
||||
headers: { "content-type": "text/html" },
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
const controller = new AbortController();
|
||||
const reason = new Error("parent run cancelled");
|
||||
const started = createDeferred();
|
||||
const pending = createDeferred<Record<string, unknown>>();
|
||||
const execute = vi
|
||||
.fn<WebFetchProviderToolDefinition["execute"]>()
|
||||
.mockImplementationOnce(async () => {
|
||||
started.resolve();
|
||||
return pending.promise;
|
||||
})
|
||||
.mockResolvedValue({ text: "fresh provider body" });
|
||||
resolveWebFetchDefinition.mockReturnValue({
|
||||
provider: { id: "test-fetch" },
|
||||
definition: { execute },
|
||||
});
|
||||
const tool = createWebFetchTool({
|
||||
config: {
|
||||
tools: {
|
||||
web: {
|
||||
fetch: { cacheTtlMinutes: 1, readability: fallback !== "disabled-readability" },
|
||||
},
|
||||
},
|
||||
},
|
||||
})!;
|
||||
const args = { url: `https://example.com/cancel-provider-${fallback}-${completion}` };
|
||||
const outcome = Promise.allSettled([tool.execute("cancelled", args, controller.signal)]);
|
||||
await started.promise;
|
||||
controller.abort(reason);
|
||||
if (completion === "success") {
|
||||
pending.resolve({ text: "stale provider body" });
|
||||
} else {
|
||||
pending.reject(new Error("provider cleanup failed"));
|
||||
}
|
||||
const [cancelled] = await outcome;
|
||||
const fresh = await tool.execute("fresh", args);
|
||||
const cached = await tool.execute("cached", args);
|
||||
|
||||
// Soft assertions retain both the late-success and cache-poisoning evidence.
|
||||
expect.soft(cancelled).toEqual({ status: "rejected", reason });
|
||||
expect.soft(fresh.details).not.toHaveProperty("cached");
|
||||
expect
|
||||
.soft(fresh.details)
|
||||
.toMatchObject({ text: expect.stringContaining("fresh provider body") });
|
||||
expect.soft(execute).toHaveBeenCalledTimes(2);
|
||||
expect
|
||||
.soft(execute.mock.calls[0])
|
||||
.toEqual([
|
||||
{ ...args, extractMode: "markdown", maxChars: 20_000 },
|
||||
{ signal: controller.signal },
|
||||
]);
|
||||
expect(cached.details).toMatchObject({
|
||||
cached: true,
|
||||
text: expect.stringContaining("fresh provider body"),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["direct", "provider"])(
|
||||
"rejects a pre-aborted %s cache hit without invalidating it",
|
||||
async (source) => {
|
||||
const fetch = vi.fn(async () => {
|
||||
if (source === "provider") {
|
||||
throw new Error("network failed");
|
||||
}
|
||||
return new Response("fresh direct body", { headers: { "content-type": "text/plain" } });
|
||||
});
|
||||
vi.stubGlobal("fetch", withFetchPreconnect(fetch));
|
||||
const execute = vi.fn(async () => ({ text: "fresh provider body" }));
|
||||
resolveWebFetchDefinition.mockReturnValue({
|
||||
provider: { id: "test-fetch" },
|
||||
definition: { execute },
|
||||
});
|
||||
const tool = createWebFetchTool({
|
||||
config: { tools: { web: { fetch: { cacheTtlMinutes: 1 } } } },
|
||||
})!;
|
||||
const args = { url: `https://example.com/pre-aborted-cache-${source}` };
|
||||
const fresh = await tool.execute("seed", args);
|
||||
const reason = new Error("parent already cancelled");
|
||||
const outcome = await Promise.allSettled([
|
||||
tool.execute("cancelled", args, AbortSignal.abort(reason)),
|
||||
]);
|
||||
const cached = await tool.execute("cached", args);
|
||||
|
||||
expect.soft(outcome).toEqual([{ status: "rejected", reason }]);
|
||||
assert(isRecord(fresh.details));
|
||||
expect(cached.details).toEqual({ ...fresh.details, cached: true });
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
expect(execute).toHaveBeenCalledTimes(source === "provider" ? 1 : 0);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["direct", "http-error", "empty-readability", "disabled-readability"])(
|
||||
"does not publish %s content if cancelled during guard release",
|
||||
async (source) => {
|
||||
const fetch = vi.fn(
|
||||
async () =>
|
||||
new Response("fresh direct body", {
|
||||
status: source === "http-error" ? 503 : 200,
|
||||
headers: { "content-type": source === "direct" ? "text/plain" : "text/html" },
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", withFetchPreconnect(fetch));
|
||||
const execute = vi.fn(async () => ({ text: "fresh provider body" }));
|
||||
resolveWebFetchDefinition.mockReturnValue({
|
||||
provider: { id: "test-fetch" },
|
||||
definition: { execute },
|
||||
});
|
||||
const started = createDeferred();
|
||||
const released = createDeferred();
|
||||
const realGuard = webGuardedFetch.fetchWithWebToolsNetworkGuard;
|
||||
vi.spyOn(webGuardedFetch, "fetchWithWebToolsNetworkGuard").mockImplementationOnce(
|
||||
async (params) => {
|
||||
const result = await realGuard(params);
|
||||
return {
|
||||
...result,
|
||||
release: async () => {
|
||||
await result.release();
|
||||
started.resolve();
|
||||
await released.promise;
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
const tool = createWebFetchTool({
|
||||
config: {
|
||||
tools: {
|
||||
web: {
|
||||
fetch: {
|
||||
cacheTtlMinutes: 1,
|
||||
readability: source !== "disabled-readability",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})!;
|
||||
const args = { url: `https://example.com/cancel-during-release-${source}` };
|
||||
const controller = new AbortController();
|
||||
const reason = new Error("cancelled during release");
|
||||
const outcome = Promise.allSettled([tool.execute("cancelled", args, controller.signal)]);
|
||||
await started.promise;
|
||||
controller.abort(reason);
|
||||
released.resolve();
|
||||
const [cancelled] = await outcome;
|
||||
const fresh = await tool.execute("fresh", args);
|
||||
const cached = await tool.execute("cached", args);
|
||||
|
||||
expect.soft(cancelled).toEqual({ status: "rejected", reason });
|
||||
expect.soft(fresh.details).not.toHaveProperty("cached");
|
||||
expect.soft(fetch).toHaveBeenCalledTimes(2);
|
||||
expect.soft(execute).toHaveBeenCalledTimes(source === "direct" ? 0 : 2);
|
||||
assert(isRecord(fresh.details));
|
||||
expect(cached.details).toEqual({ ...fresh.details, cached: true });
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -554,7 +554,7 @@ function throwIfFetchAborted(signal: AbortSignal | undefined): void {
|
||||
if (!signal?.aborted) {
|
||||
return;
|
||||
}
|
||||
// readResponseText may finish after an abort races with body reading. Recheck
|
||||
// Async fetch, provider, and payload work can finish after an abort. Recheck
|
||||
// before wrapping, caching, or returning content from a canceled tool call.
|
||||
throw signal.reason instanceof Error ? signal.reason : new Error("aborted");
|
||||
}
|
||||
@@ -697,20 +697,28 @@ async function buildWebFetchPayload(params: {
|
||||
async function maybeFetchProviderWebFetchPayload(
|
||||
params: WebFetchRuntimeParams & {
|
||||
urlToFetch: string;
|
||||
cacheKey: string;
|
||||
tookMs: number;
|
||||
},
|
||||
): Promise<Record<string, unknown> | null> {
|
||||
const providerFallback = await params.resolveProviderFallback();
|
||||
throwIfFetchAborted(params.signal);
|
||||
if (!providerFallback) {
|
||||
return null;
|
||||
}
|
||||
const rawPayload = await providerFallback.definition.execute({
|
||||
url: params.urlToFetch,
|
||||
extractMode: params.extractMode,
|
||||
maxChars: params.maxChars,
|
||||
});
|
||||
const payload = await buildWebFetchPayload({
|
||||
let rawPayload: unknown;
|
||||
try {
|
||||
rawPayload = await providerFallback.definition.execute(
|
||||
{ url: params.urlToFetch, extractMode: params.extractMode, maxChars: params.maxChars },
|
||||
{ signal: params.signal },
|
||||
);
|
||||
} catch (error) {
|
||||
// A provider failure landing after cancellation must surface the caller's abort
|
||||
// reason, not a late error from fallback work the caller already abandoned.
|
||||
throwIfFetchAborted(params.signal);
|
||||
throw error;
|
||||
}
|
||||
throwIfFetchAborted(params.signal);
|
||||
return await buildWebFetchPayload({
|
||||
providerId: providerFallback.provider.id,
|
||||
payload: rawPayload,
|
||||
requestedUrl: params.url,
|
||||
@@ -718,11 +726,10 @@ async function maybeFetchProviderWebFetchPayload(
|
||||
maxChars: params.maxChars,
|
||||
tookMs: params.tookMs,
|
||||
});
|
||||
writeCache(FETCH_CACHE, params.cacheKey, payload, params.cacheTtlMs);
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string, unknown>> {
|
||||
throwIfFetchAborted(params.signal);
|
||||
const ssrfPolicy = params.ssrfPolicy;
|
||||
const useTrustedEnvProxy = params.useTrustedEnvProxy;
|
||||
let parsedUrl: URL;
|
||||
@@ -755,9 +762,20 @@ async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string
|
||||
return { ...cached.value, cached: true };
|
||||
}
|
||||
|
||||
// Preserve the direct fetch's rejection; replacing it with signal.reason would
|
||||
// discard the transport's own error detail.
|
||||
const payload = await fetchWebPayload(params);
|
||||
// Publish only after guard release: cancellation or cleanup failure must not
|
||||
// leave a successful cache entry for a call that never returned its content.
|
||||
throwIfFetchAborted(params.signal);
|
||||
writeCache(FETCH_CACHE, cacheKey, payload, params.cacheTtlMs);
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function fetchWebPayload(params: WebFetchRuntimeParams): Promise<Record<string, unknown>> {
|
||||
const start = Date.now();
|
||||
let res: Response;
|
||||
let release: (() => Promise<void>) | null;
|
||||
let release: () => Promise<void>;
|
||||
let finalUrl = params.url;
|
||||
try {
|
||||
const fetchWithWebToolsNetworkGuard = await loadWebGuardedFetch();
|
||||
@@ -767,8 +785,8 @@ async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string
|
||||
timeoutSeconds: params.timeoutSeconds,
|
||||
signal: params.signal,
|
||||
lookupFn: params.lookupFn,
|
||||
useEnvProxy: useTrustedEnvProxy,
|
||||
policy: ssrfPolicy,
|
||||
useEnvProxy: params.useTrustedEnvProxy,
|
||||
policy: params.ssrfPolicy,
|
||||
capture: params.headers
|
||||
? { sensitiveRequestHeaderNames: Object.keys(params.headers) }
|
||||
: undefined,
|
||||
@@ -791,16 +809,12 @@ async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof SsrFBlockedError) {
|
||||
throw error;
|
||||
}
|
||||
if (params.signal?.aborted) {
|
||||
if (error instanceof SsrFBlockedError || params.signal?.aborted) {
|
||||
throw error;
|
||||
}
|
||||
const payload = await maybeFetchProviderWebFetchPayload({
|
||||
...params,
|
||||
urlToFetch: finalUrl,
|
||||
cacheKey,
|
||||
tookMs: Date.now() - start,
|
||||
});
|
||||
if (payload) {
|
||||
@@ -811,13 +825,10 @@ async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string
|
||||
|
||||
try {
|
||||
if (!res.ok) {
|
||||
if (params.signal?.aborted) {
|
||||
throw params.signal.reason instanceof Error ? params.signal.reason : new Error("aborted");
|
||||
}
|
||||
throwIfFetchAborted(params.signal);
|
||||
const payload = await maybeFetchProviderWebFetchPayload({
|
||||
...params,
|
||||
urlToFetch: params.url,
|
||||
cacheKey,
|
||||
tookMs: Date.now() - start,
|
||||
});
|
||||
if (payload) {
|
||||
@@ -871,11 +882,10 @@ async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string
|
||||
payload = await maybeFetchProviderWebFetchPayload({
|
||||
...params,
|
||||
urlToFetch: finalUrl,
|
||||
cacheKey,
|
||||
tookMs: Date.now() - start,
|
||||
});
|
||||
} catch {
|
||||
payload = null;
|
||||
throwIfFetchAborted(params.signal);
|
||||
}
|
||||
if (payload) {
|
||||
return payload;
|
||||
@@ -900,7 +910,6 @@ async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string
|
||||
const payload = await maybeFetchProviderWebFetchPayload({
|
||||
...params,
|
||||
urlToFetch: finalUrl,
|
||||
cacheKey,
|
||||
tookMs: Date.now() - start,
|
||||
});
|
||||
if (payload) {
|
||||
@@ -920,7 +929,7 @@ async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string
|
||||
}
|
||||
}
|
||||
|
||||
const payload = await buildWebFetchPayload({
|
||||
return await buildWebFetchPayload({
|
||||
payload: {
|
||||
finalUrl,
|
||||
status: res.status,
|
||||
@@ -936,18 +945,13 @@ async function runWebFetch(params: WebFetchRuntimeParams): Promise<Record<string
|
||||
maxChars: params.maxChars,
|
||||
tookMs: Date.now() - start,
|
||||
});
|
||||
throwIfFetchAborted(params.signal);
|
||||
writeCache(FETCH_CACHE, cacheKey, payload, params.cacheTtlMs);
|
||||
return payload;
|
||||
} finally {
|
||||
if (!res.bodyUsed) {
|
||||
// Fallbacks and provider failures can abandon the upstream stream. Cancel
|
||||
// without awaiting so a stalled cancellation cannot block guard release.
|
||||
void res.body?.cancel().catch(() => undefined);
|
||||
}
|
||||
if (release) {
|
||||
await release();
|
||||
}
|
||||
await release();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,10 @@ export type WebSearchProviderToolDefinition = {
|
||||
export type WebFetchProviderToolDefinition = {
|
||||
description: string;
|
||||
parameters: TSchema;
|
||||
execute: (args: Record<string, unknown>) => Promise<Record<string, unknown>>;
|
||||
execute: (
|
||||
args: Record<string, unknown>,
|
||||
context?: { signal?: AbortSignal },
|
||||
) => Promise<Record<string, unknown>>;
|
||||
};
|
||||
|
||||
type WebSearchProviderContext = {
|
||||
|
||||
Reference in new issue
Block a user