From c02212f34a35f958c60e45658a8f71c20e653acc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:42:53 +0000 Subject: [PATCH 1/6] Nothing is resent after a timeout; explain tells an unanswered write from a failed read; 1.0.0-alpha.11 A timeout ends the client's wait and does not stop the work on the server, so a request that timed out (TIMEOUT, a 408, a 504) is no longer sent again, a read included: a slow query was being run twice. A lost connection, a 429 and other 5xx are resent once as before. Every ApiError the client lets out says what was asked (method, path, idempotent). explain uses it: a write that got no answer is 'the change may or may not have been made', never 'try again', and Explanation gains retrySafe. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 48 ++++++++++++++++++++++++++++ README.md | 3 +- package-lock.json | 4 +-- package.json | 2 +- specs/000-layers.md | 13 ++++++-- src/client.ts | 4 ++- src/core/clientConfig.ts | 19 ++++++----- src/core/errors.ts | 8 +++++ src/core/fetchTransport.ts | 15 ++++----- src/core/retry.ts | 49 ++++++++++++++++++++++++----- src/services/explain.ts | 52 ++++++++++++++++++++++++++----- test/unit/explain.test.ts | 5 +-- test/unit/retry.test.ts | 27 ++++++++++++++-- test/unit/timeout.test.ts | 64 ++++++++++++++++++++++++++++++++------ 14 files changed, 262 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d6042d..d7b7e9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,53 @@ # Changelog +## 1.0.0-alpha.11 + +### Breaking + +- **A request that timed out is no longer sent again, a read included.** + Since alpha.5 an idempotent request (a GET, a query.v1 read, a guarded + batch) that timed out was sent once more. A timeout ends the client's + wait; it does not stop the work on the server. A slow query was + therefore run twice while the first might still be running, and the + caller waited two timeouts. Now nothing is resent after a timeout, + whoever gave up: the client (`TIMEOUT`), the server (a 408) or a + gateway (a 504). A lost connection, a 429 and any other 5xx are resent + once as before. `client.pages` and `client.all` stop at the first + timeout. `TIMEOUT` is still `kind: "transient"` (the same request may + work later): the kind says what the failure is, and the resend rule is + narrower than the kind. Migration: nothing, unless you relied on the + second attempt; a caller that wants one resends in its own code, + knowing a costly request may then run twice. Applies to the built-in + transport and to a custom one alike. + +### Changed + +- **`client.explain` no longer tells a person to try again after a write + that got no answer.** For any `transient` error it said "Agility could + not be reached, or is busy. The same request may work in a moment.", + which for a write whose fate is unknown is how a duplicate gets made. + Now: a write with no answer, a timeout or a 5xx is "Agility did not + confirm the change. It may or may not have been made: check before + trying again."; a read or a guarded batch that timed out is "Agility + did not answer in time. The request may still be running: wait before + trying again."; a 429 is "Agility is busy. The same request may work in + a moment."; an error that does not say what was asked is "Agility could + not be reached, or is busy.". Migration: a test that asserts the old + sentence for a write; a consumer that offers a retry button should + decide on `retrySafe` (below). + +### Added + +- `Explanation.retrySafe`: `true` when sending the same request again is + safe (a read, a guarded batch, anything refused with a 429), `false` + for a write that got no answer or a server failure, `null` when the + server answered and said why, or when it cannot be told. +- `ApiError.request`: `{ method, path, idempotent }`, stamped by the + client on every error it lets out, with any transport. Never the body + or headers. Absent on an error from a `/wire` or `/services` function + used on a transport no client wrapped; such an error is explained with + the cautious sentence and `retrySafe: null`. + ## 1.0.0-alpha.10 ### Breaking (for a consumer with its own `Transport`) diff --git a/README.md b/README.md index 312ebae..d9a5292 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,8 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `TypeCache` - one instance's loaded type definitions, shared by many clients (`new AgilityApiClient(config, { types })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded - `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401 (resends idempotent requests once), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one - **Timeouts are the client's business with any transport**: each attempt has `timeoutMs` (default 60000; 0 for none), and at the deadline the request rejects with an `ApiError` coded `TIMEOUT`, whether or not a custom transport lets go of it (the transport is handed a `signal` that fires then; a late answer is discarded). A timed-out write may still have been applied. A custom transport that waits for a person inside `request` (a sign-in prompt before it replays the request) sets `timeoutMs: 0`: the deadline cannot tell a person from a slow network. The built-in transport's `onUnauthorized` hook runs outside the deadline -- Resends and failures are the client's business with any transport: an idempotent request (a GET, a read, a guarded batch with no creates) is sent once more after a network failure, a timeout, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403), and `onError(error, request)` in the config is told about each request that finally failed +- Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read or a guarded batch (which the guard makes safe to repeat) is `retrySafe: true`. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) +- Resends and failures are the client's business with any transport: an idempotent request (a GET, a read, a guarded batch with no creates) is sent once more after a network failure, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403, and **never after a timeout**: the client's `TIMEOUT`, a 408 or a 504. A timeout or an abort ends the client's wait and does not stop the work on the server, so a query that timed out may still be running; `pages` and `all` stop at the first one), and `onError(error, request)` in the config is told about each request that finally failed - A custom `Transport` (`new AgilityApiClient(config, { transport })`) decides by itself where requests go; `config.baseUrl` is then used only for the links the client builds (`urls.*`, `embeddedImages.normalize`). `apiErrorFromResponse(status, data)` is the error the fetch transport throws for a refused response, for a custom transport to throw the same - `@versionone/agility-sdk/services` - the services as free functions over a `Transport` (`guard`, `batch`, `resolve`, `schema`, `attachments`, `fields`), for a caller that composes one differently; the client's methods are the same things - `@versionone/agility-sdk/wire` - the wire modules (`assetApi`, `queryV1`, `rest1`, `meta`, `loc2`, `attachment`, `fields`, `select`), for passthroughs and transport authors; they speak the endpoints' own shapes. diff --git a/package-lock.json b/package-lock.json index bb6f975..adeb3cd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.10", + "version": "1.0.0-alpha.11", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.10", + "version": "1.0.0-alpha.11", "license": "MIT", "devDependencies": { "@types/node": "^22.13.10", diff --git a/package.json b/package.json index 85cbfc0..9d350d2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.10", + "version": "1.0.0-alpha.11", "description": "TypeScript SDK for the Digital.ai Agility (VersionOne) API: queries, batches, schema-translated rows, guarded writes, attachments", "keywords": [ "agility", diff --git a/specs/000-layers.md b/specs/000-layers.md index 872655d..67a7bc1 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -231,7 +231,7 @@ made), which api/asset's `execute` performs but does not report. The transport retries only idempotent requests (GET by default, and every query.v1 POST, since that endpoint cannot write), only on a network failure, a 5xx or a 429 (Retry-After honoured, up to 30 s), never -another 4xx, and once by default (`retries: 1`); a batch write is never retried unless the +another 4xx, never after a timeout (below), and once by default (`retries: 1`); a batch write is never retried unless the caller has made it idempotent with a guard and says so. That rule is the client's, not one transport's: the built-in fetch transport applies it itself (it can read Retry-After), and the client applies it around a @@ -248,7 +248,16 @@ abandoned request answers later is discarded. A transport therefore owes nothing about timing beyond honouring `signal`, which the conformance suite checks; one with a shorter timeout of its own simply rejects first. A timeout says the client stopped waiting, never that the server did not -act, which is one more reason a write is not resent. The deadline cannot +act, which is one more reason a write is not resent. + +**Nothing is resent after a timeout, a read included.** A timeout or an +abort ends the client's wait; it does not stop the work on the server. A +query that timed out may still be running, and a request that ran out of +time is likely one that costs a lot, so sending it again runs the cost +twice and makes the caller wait twice. That holds whoever gave up: the +client (`TIMEOUT`), the server (408) or a gateway in front of it (504). +`pages` and `all` stop at the first timeout rather than pressing on. A +caller that wants to try again does so itself, knowing the cost. The deadline cannot tell the network from a person: a custom transport that waits for someone inside `request` turns the client's timeout off (`timeoutMs: 0`), and the built-in transport's re-authentication hook runs outside the deadline. diff --git a/src/client.ts b/src/client.ts index eeea227..156a036 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,7 +1,7 @@ import type { ClientConfig } from "./core/clientConfig"; import { ApiError, UsageError } from "./core/errors"; import { createFetchTransport } from "./core/fetchTransport"; -import { withErrorHook, DEFAULT_TIMEOUT_MS, withRetry, withTimeout } from "./core/retry"; +import { DEFAULT_TIMEOUT_MS, withErrorHook, withRequestStamp, withRetry, withTimeout } from "./core/retry"; import type { Transport } from "./core/transport"; import * as attachments from "./services/attachments"; import * as batch from "./services/batch"; @@ -123,6 +123,8 @@ export class AgilityApiClient { if (!dressed.has(transport)) { // A custom transport: each attempt under the client's deadline, and the resend rule around that. if (opts.transport) transport = withRetry(withTimeout(transport, config.timeoutMs ?? DEFAULT_TIMEOUT_MS), config.retries ?? 1); + // Every error says what was asked (so an explanation can tell a failed read from a write whose fate is unknown). + transport = withRequestStamp(transport); if (config.onError) transport = withErrorHook(transport, config.onError); dressed.add(transport); } diff --git a/src/core/clientConfig.ts b/src/core/clientConfig.ts index 6334b6c..4d51222 100644 --- a/src/core/clientConfig.ts +++ b/src/core/clientConfig.ts @@ -20,8 +20,11 @@ export interface ClientConfig extends Pick; diff --git a/src/core/errors.ts b/src/core/errors.ts index 2d2544a..b8effb6 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -57,6 +57,14 @@ export class ApiError extends Error { * word it as a server error. */ readonly kind: ErrorKind; + /** + * What was asked when this error came back, stamped by the client: the + * method, the path, and whether the request was one that is safe to send + * twice (a GET, a read, a guarded batch with no creates). Never the body + * or the headers: errors get logged. Absent on an error from a function + * of `/wire` or `/services` used on a transport no client has wrapped. + */ + request?: { method: string; path: string; idempotent: boolean }; constructor(message: string, status: number, code?: string, details?: unknown, kind: ErrorKind = kindOf(status, code)) { const cause = causeOf(details); diff --git a/src/core/fetchTransport.ts b/src/core/fetchTransport.ts index e7cbf8d..fc7d6f0 100644 --- a/src/core/fetchTransport.ts +++ b/src/core/fetchTransport.ts @@ -1,5 +1,5 @@ import { ApiError, apiErrorFromResponse } from "./errors"; -import { DEFAULT_TIMEOUT_MS, deadline } from "./retry"; +import { DEFAULT_TIMEOUT_MS, deadline, resendable } from "./retry"; import type { RequestBody, RequestOptions, ResponseType, Transport } from "./transport"; /** @@ -160,9 +160,6 @@ function retryDelay(response: { status: number; headers: { get(name: string): st return 150 * (attempt + 1); } -/** A status the same request may succeed after: too many requests, or a server-side failure. */ -const retriable = (status: number): boolean => status === 429 || status >= 500; - export function createFetchTransport(config: FetchTransportConfig): Transport { const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS; const retries = Math.max(0, config.retries ?? 1); @@ -201,10 +198,10 @@ export function createFetchTransport(config: FetchTransportConfig): Transport { settle(); // The caller gave up: final, whatever attempt this was. if (callerSignal?.aborted) throw abortedError(callerSignal); - // Network failure or timeout: the only case a retry can help. - lastError = limit.expired() - ? new ApiError(`Timed out after ${timeoutMs} ms`, 0, "TIMEOUT", { cause: error }) - : new ApiError(error instanceof Error ? error.message : String(error), 0, "NETWORK_ERROR", { cause: error }); + // A timeout ends the wait, not the work: the request may still be running, so it is never sent again. + if (limit.expired()) throw new ApiError(`Timed out after ${timeoutMs} ms`, 0, "TIMEOUT", { cause: error }); + // No connection: the one failure here that a resend can help. + lastError = new ApiError(error instanceof Error ? error.message : String(error), 0, "NETWORK_ERROR", { cause: error }); if (attempt + 1 < attempts) await delay(150 * (attempt + 1)); continue; } @@ -245,7 +242,7 @@ export function createFetchTransport(config: FetchTransportConfig): Transport { } break; } - if (retriable(response.status) && attempt + 1 < attempts) { + if (resendable(lastError) && attempt + 1 < attempts) { const wait = retryDelay(response, attempt); if (wait === null) break; await delay(wait); diff --git a/src/core/retry.ts b/src/core/retry.ts index 7562cac..3b87f5a 100644 --- a/src/core/retry.ts +++ b/src/core/retry.ts @@ -75,15 +75,31 @@ export function withTimeout(transport: Transport, timeoutMs: number): Transport }; } +/** + * May a request that failed this way be sent again by the SDK? Only when + * the failure says the server never took the request up, or took it up and + * fell over: no connection (NETWORK_ERROR), a 429, a 5xx. + * + * Not after a timeout, of the client's (TIMEOUT) or of the server's or a + * gateway's (408, 504). A timeout ends the wait; it does not stop the + * work. The request may still be running on the server, and a request that + * ran out of time is likely one that costs a lot: sending it again runs + * the cost twice and keeps the caller waiting twice as long. + */ +export function resendable(error: unknown): boolean { + return error instanceof ApiError && error.kind === "transient" && error.code !== "TIMEOUT" && error.status !== 408 && error.status !== 504; +} + /** * The resend rule, for any Transport: an idempotent request (a GET, or one * the caller marked — a query.v1 read, a guarded batch with no creates) - * that fails with a transient error (no answer, a timeout, a 5xx, a 429) - * is sent again, `retries` times at most, a little later each time. - * Nothing else is: not a plain write, whatever happened to it; not a 401 - * or 403 (re-authentication is the unauthorized hook's business, and a - * resend would prompt twice); not any other 4xx, which is an answer; not a - * request its caller aborted. + * that fails because it never reached the server or the server fell over + * (no connection, a 5xx other than 504, a 429) is sent again, `retries` + * times at most, a little later each time. Nothing else is: not a plain + * write, whatever happened to it; not a request that timed out, here or on + * the server (see `resendable`); not a 401 or 403 (re-authentication is + * the unauthorized hook's business, and a resend would prompt twice); not + * any other 4xx, which is an answer; not a request its caller aborted. * * The client puts this around a custom Transport (outside the timeout * rule, so each attempt has its own deadline), so the rule is the client's @@ -102,7 +118,7 @@ export function withRetry(transport: Transport, retries: number): Transport { try { return await transport.request(options); } catch (error) { - const again = attempt + 1 < attempts && error instanceof ApiError && error.kind === "transient" && !options.signal?.aborted; + const again = attempt + 1 < attempts && resendable(error) && !options.signal?.aborted; if (!again) throw error; await delay(150 * (attempt + 1)); } @@ -111,6 +127,25 @@ export function withRetry(transport: Transport, retries: number): Transport { }; } +/** + * A Transport whose errors say what was asked: every ApiError that comes + * out carries `request` (method, path, whether it was safe to send twice). + * It is what lets an explanation tell a read that failed from a write + * whose fate is unknown. + */ +export function withRequestStamp(transport: Transport): Transport { + return { + async request(options: RequestOptions): Promise { + try { + return await transport.request(options); + } catch (error) { + if (error instanceof ApiError && !error.request) error.request = { method: options.method, path: options.path.split("?")[0]!, idempotent: options.idempotent ?? options.method === "GET" }; + throw error; + } + } + }; +} + /** * A Transport that tells `onError` about every request that finally * failed (after any resend), and then fails as before. Observation only: diff --git a/src/services/explain.ts b/src/services/explain.ts index 2908bf3..216f4df 100644 --- a/src/services/explain.ts +++ b/src/services/explain.ts @@ -54,6 +54,18 @@ export interface Explanation { audience: "user" | "developer"; /** True when `sentence` is nothing more than the message as the server (or the SDK) sent it: nothing was explained. */ echoed: boolean; + /** + * Is it safe to send the same request again? True: nothing was changed + * by the failed attempt, or sending it twice changes nothing more (a + * read, a guarded batch, anything the server turned away with a 429). + * False: a write that got no answer, or a server failure in answer to + * one; the change may or may not have been made, so look before trying + * again. Null when the question does not arise (the server answered and + * said why) or cannot be told (the error does not say what was asked, + * as one from a `/wire` function on a bare transport does not). Decide + * on this field, not on the wording of `sentence`. + */ + retrySafe: boolean | null; /** The failed command's index in the batch, when this explains one; null otherwise. */ index: number | null; /** What was violated: Required, Invalid, Unresolved, Ambiguous, AssetCannotDeleteClosed, …; null when the message is not such a token. */ @@ -90,8 +102,9 @@ const typeTag = (type: string): string => `AssetType'${type}`; /** A token that looks like one loc-2 would know: no spaces, apostrophe-delimited. A plain sentence is not asked about. */ const isTag = (message: string): boolean => /^[A-Za-z]\w*'[^\s]+$/.test(message.trim()); -type Said = Pick; -const forUser = (sentence: string): Said => ({ sentence, audience: "user", echoed: false }); +type Said = Pick; +const forUser = (sentence: string, retrySafe: boolean | null = null): Said => ({ sentence, audience: "user", echoed: false, retrySafe }); +const forDeveloper = (sentence: string, echoed: boolean): Said => ({ sentence, audience: "developer", echoed, retrySafe: null }); function sentenceOf(problem: Problem, label: string | null, related: string | null, localized: string | null, message: string): Said { if (label) { @@ -107,9 +120,9 @@ function sentenceOf(problem: Problem, label: string | null, related: string | nu // A rule the instance has no words for (seen live: Violation'AssetCannotInactivateClosed, Violation'MessageMustNotBeSent): // never the bare token, but the rule's name spelled out is still a token and not a sentence written for a person. It can // read as the opposite of what happened ("message must not be sent" is said of a message that was). So it is for a developer. - if (problem.rule) return { sentence: `${label ? `${label}: refused` : "Refused"} (${words(problem.rule)}).`, audience: "developer", echoed: false }; + if (problem.rule) return forDeveloper(`${label ? `${label}: refused` : "Refused"} (${words(problem.rule)}).`, false); // Anything else is the server's own text, as it came. - return { sentence: message, audience: "developer", echoed: true }; + return forDeveloper(message, true); } /** A rule's name as words: AssetCannotInactivateClosed → "asset cannot inactivate closed". */ const words = (rule: string): string => rule.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase(); @@ -121,17 +134,42 @@ function failuresOf(input: unknown): CommandFailureDetail[] | null { return null; } +/** + * A request that got no answer, or a failure for one. What to tell a + * person depends on what was asked, which the client stamps on the error + * (`error.request`): + * - a 429, whatever was asked: the server turned it away before doing + * anything, so it is safe to send again; + * - a write (not idempotent) with no answer, a timeout or a 5xx: nobody + * knows whether the change was made, and saying "try again" is how a + * duplicate happens; + * - a read, or a guarded batch (which the guard makes safe to repeat), + * that timed out: safe to repeat, but it may still be running, so not + * at once; + * - a read that never got through: safe, and may work in a moment; + * - no stamp: say only what is known. + */ +function unanswered(error: ApiError): Said { + if (error.status === 429) return forUser("Agility is busy. The same request may work in a moment.", true); + const asked = error.request; + if (!asked) return forUser("Agility could not be reached, or is busy."); + if (!asked.idempotent) return forUser("Agility did not confirm the change. It may or may not have been made: check before trying again.", false); + const timedOut = error.code === "TIMEOUT" || error.status === 408 || error.status === 504; + if (timedOut) return forUser("Agility did not answer in time. The request may still be running: wait before trying again.", true); + return forUser("Agility could not be reached, or is busy. The same request may work in a moment.", true); +} + /** A sentence for an error that is not a list of failed commands, by its kind, and who it is for. */ function sentenceForError(error: unknown): Said { - if (!(error instanceof ApiError)) return { sentence: error instanceof Error ? error.message : String(error), audience: "developer", echoed: true }; + if (!(error instanceof ApiError)) return forDeveloper(error instanceof Error ? error.message : String(error), true); switch (error.kind) { case "auth": return forUser("Agility did not accept the sign-in: the token is missing, wrong or no longer valid."); case "forbidden": return forUser("Agility refused: this member is not allowed to do that."); - case "transient": return forUser("Agility could not be reached, or is busy. The same request may work in a moment."); + case "transient": return unanswered(error); case "aborted": return forUser("The request was cancelled."); case "conflict": return forUser("Someone else changed this since it was read; nothing was applied. Look at it again and decide."); // notFound, invalid, usage, protocol and the rest: the message is the SDK's or the server's own, about the call. - default: return { sentence: error.message, audience: "developer", echoed: true }; + default: return forDeveloper(error.message, true); } } diff --git a/test/unit/explain.test.ts b/test/unit/explain.test.ts index ff76d80..53c8733 100644 --- a/test/unit/explain.test.ts +++ b/test/unit/explain.test.ts @@ -42,7 +42,7 @@ describe("explain", () => { "Agility Warning: Attempting to delete a closed item. This change was not saved." ]); expect(explained[0]).toEqual({ - sentence: "Project is required.", audience: "user", echoed: false, index: 0, rule: "Required", attribute: "Story.Scope", attributeLabel: "Project", typeLabel: "Backlog Item", relatedType: null, relatedTypeLabel: null, + sentence: "Project is required.", audience: "user", echoed: false, retrySafe: null, index: 0, rule: "Required", attribute: "Story.Scope", attributeLabel: "Project", typeLabel: "Backlog Item", relatedType: null, relatedTypeLabel: null, localized: LOC2["Violation'Required'AttributeDefinition'Scope'Story"], message: "Violation'Required'AttributeDefinition'Scope'Story" }); // A Resolution failure names the attribute as a token and then the related type; loc-2 has no label for these here, so their own names stand in. @@ -80,7 +80,8 @@ describe("explain", () => { const say = async (e: unknown) => (await explain(t, e))[0]!.sentence; expect(await say(new ApiError("Unauthorized", 401))).toBe("Agility did not accept the sign-in: the token is missing, wrong or no longer valid."); expect(await say(new ApiError("Forbidden", 403))).toBe("Agility refused: this member is not allowed to do that."); - expect(await say(new ApiError("fetch failed", 0, "NETWORK_ERROR"))).toBe("Agility could not be reached, or is busy. The same request may work in a moment."); + // An error that does not say what was asked (no client stamped it): only what is known, and no invitation to send it again. + expect(await say(new ApiError("fetch failed", 0, "NETWORK_ERROR"))).toBe("Agility could not be reached, or is busy."); expect(await say(new ApiError("Request aborted", 0, "ABORTED"))).toBe("The request was cancelled."); // The SDK's own sentences and the server's (a rejected query) are said as they are. expect(await say(new UsageError("query of Story without a page: every read must be bounded"))).toBe("query of Story without a page: every read must be bounded"); diff --git a/test/unit/retry.test.ts b/test/unit/retry.test.ts index c71f779..360de7e 100644 --- a/test/unit/retry.test.ts +++ b/test/unit/retry.test.ts @@ -20,8 +20,8 @@ const noTypes = (t: Transport): Transport => ({ request: (o) => (o.path.startsWi const q = { from: "Story", select: ["Name"], page: { size: 1, start: 0 } }; describe("the resend rule above a custom Transport", () => { - it("a read is sent once more after a 5xx, a lost connection or a timeout, by default", async () => { - for (const failure of [new ApiError("Bad Gateway", 502), new ApiError("fetch failed", 0, "NETWORK_ERROR"), new ApiError("Timed out", 0, "TIMEOUT"), new ApiError("Too Many Requests", 429)]) { + it("a read is sent once more after a 5xx, a lost connection or a 429, by default", async () => { + for (const failure of [new ApiError("Bad Gateway", 502), new ApiError("fetch failed", 0, "NETWORK_ERROR"), new ApiError("Too Many Requests", 429)]) { const t = custom(failure, [[{ _oid: "Story:1", Name: "n" }]]); const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: noTypes(t) }); expect(await client.query(q)).toEqual([{ _oid: "Story:1", Name: "n" }]); @@ -29,6 +29,29 @@ describe("the resend rule above a custom Transport", () => { } }); + it("a read that timed out is NOT sent again, whoever gave up: the transport, the server (408) or a gateway (504). The request may still be running", async () => { + for (const failure of [new ApiError("timeout of 30000ms exceeded", 0, "TIMEOUT"), new ApiError("Request Timeout", 408), new ApiError("Gateway Timeout", 504)]) { + const t = custom(failure, [[{ _oid: "Story:1", Name: "n" }]]); + const client = new AgilityApiClient({ baseUrl: "https://x", retries: 3 }, { transport: noTypes(t) }); + // Still a transient failure (the same request may work later), and it says what was asked. + await expect(client.query(q)).rejects.toMatchObject({ kind: "transient", status: failure.status, request: { method: "POST", path: "/query.v1", idempotent: true } }); + expect(t.calls).toHaveLength(1); + } + // The built-in transport alike: a 504 once, a 502 twice. + for (const [status, sends] of [[504, 1], [408, 1], [502, 2]] as const) { + const fetchImpl = vi.fn(async () => new Response("down", { status })); + await expect(createFetchTransport({ baseUrl: "https://x", fetchImpl: fetchImpl as unknown as typeof fetch }).request({ method: "GET", path: "/meta.v1/Story" })).rejects.toMatchObject({ status }); + expect(fetchImpl).toHaveBeenCalledTimes(sends); + } + }); + + it("pages and all stop at the first timeout rather than pressing on", async () => { + const t = custom([[{ _oid: "Story:1", Name: "a" }, { _oid: "Story:2", Name: "b" }]], new ApiError("Timed out after 60000 ms", 0, "TIMEOUT"), [[{ _oid: "Story:9", Name: "never read" }]]); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: noTypes(t) }); + await expect(client.all({ from: "Story", select: ["Name"], page: { size: 2, start: 0 } })).rejects.toMatchObject({ code: "TIMEOUT" }); + expect(t.calls).toHaveLength(2); + }); + it("once, not forever; `retries` says how many times, and 0 turns it off", async () => { const down = () => new ApiError("Service Unavailable", 503); const once = custom(down(), down(), [[]]); diff --git a/test/unit/timeout.test.ts b/test/unit/timeout.test.ts index 0008446..c1366f8 100644 --- a/test/unit/timeout.test.ts +++ b/test/unit/timeout.test.ts @@ -34,16 +34,17 @@ const read: RequestOptions = { method: "GET", path: "/loc-2.v1" }; const write: RequestOptions = { method: "POST", path: "/api/asset", body: [{ from: "Story:1", update: { Name: "x" } }] }; describe("the timeout rule above a custom Transport", () => { - it("an attempt that takes longer than timeoutMs is a TIMEOUT, and an idempotent request is then sent once more, with a deadline of its own", async () => { - const t = honouring((n) => (n === 1 ? never : later(5, { ok: true }))); - expect(await clientOn(t, { timeoutMs: 30 }).request(read)).toEqual({ ok: true }); - expect(t.calls).toHaveLength(2); - // The first attempt was told to stop; the second got a fresh signal. - expect([t.calls[0]!.signal!.aborted, t.calls[1]!.signal!.aborted]).toEqual([true, false]); - // Every attempt slow: the caller gets the TIMEOUT, a transient failure, after the one resend. - const slow = honouring(() => never); - await expect(clientOn(slow, { timeoutMs: 20 }).request(read)).rejects.toMatchObject({ code: "TIMEOUT", status: 0, kind: "transient", message: "Timed out after 20 ms" }); - expect(slow.calls).toHaveLength(2); + it("an attempt that takes longer than timeoutMs is a TIMEOUT, and it is not sent again, a read included: the first one may still be running", async () => { + const slow = honouring((n) => (n === 1 ? never : later(5, { ok: true }))); + await expect(clientOn(slow, { timeoutMs: 20, retries: 3 }).request(read)).rejects.toMatchObject({ code: "TIMEOUT", status: 0, kind: "transient", message: "Timed out after 20 ms", request: { method: "GET", path: "/loc-2.v1", idempotent: true } }); + expect(slow.calls).toHaveLength(1); + // The attempt was told to stop. + expect(slow.calls[0]!.signal!.aborted).toBe(true); + // A lost connection is another matter (the request never arrived): that read is sent once more, with a deadline of its own. + const dropped = honouring((n) => (n === 1 ? Promise.reject(new ApiError("fetch failed", 0, "NETWORK_ERROR")) : later(5, { ok: true }))); + expect(await clientOn(dropped, { timeoutMs: 50 }).request(read)).toEqual({ ok: true }); + expect(dropped.calls).toHaveLength(2); + expect(dropped.calls[1]!.signal!.aborted).toBe(false); }); it("a plain write that times out is not sent again: the client stopped waiting, which says nothing about whether the server acted", async () => { @@ -129,3 +130,46 @@ describe("the built-in transport under the same rule", () => { expect(await transport.request(read)).toEqual({ ok: true }); }); }); + +describe("what to tell a person when a request got no answer", () => { + const failing = (failure: ApiError): Transport => ({ request: (() => Promise.reject(failure)) as Transport["request"] }); + const say = async (failure: () => ApiError, request: RequestOptions) => { + const client = new AgilityApiClient({ baseUrl: "https://agility.example.com/I", retries: 0 }, { transport: failing(failure()) }); + const error = await client.transport.request(request).catch((e: unknown) => e); + const [said] = await client.explain(error); + return { stamp: (error as ApiError).request, sentence: said!.sentence, retrySafe: said!.retrySafe, audience: said!.audience }; + }; + const guarded: RequestOptions = { ...write, idempotent: true }; + const timeout = () => new ApiError("Timed out after 60000 ms", 0, "TIMEOUT"); + const dropped = () => new ApiError("fetch failed", 0, "NETWORK_ERROR"); + + it("a write that got no answer, or a server failure for one, is never 'try again': the change may or may not have been made, and retrySafe is false", async () => { + for (const failure of [timeout, dropped, () => new ApiError("Bad Gateway", 502), () => new ApiError("Internal Server Error", 500), () => new ApiError("Gateway Timeout", 504)]) { + expect(await say(failure, write)).toEqual({ stamp: { method: "POST", path: "/api/asset", idempotent: false }, audience: "user", retrySafe: false, sentence: "Agility did not confirm the change. It may or may not have been made: check before trying again." }); + } + }); + + it("a read, or a guarded batch, that timed out is safe to repeat but may still be running; one that never got through may work in a moment", async () => { + for (const request of [read, guarded]) { + for (const failure of [timeout, () => new ApiError("Gateway Timeout", 504), () => new ApiError("Request Timeout", 408)]) { + expect(await say(failure, request)).toMatchObject({ retrySafe: true, sentence: "Agility did not answer in time. The request may still be running: wait before trying again." }); + } + for (const failure of [dropped, () => new ApiError("Service Unavailable", 503)]) { + expect(await say(failure, request)).toMatchObject({ retrySafe: true, sentence: "Agility could not be reached, or is busy. The same request may work in a moment." }); + } + } + }); + + it("a 429 was turned away before any work, so even a write is safe to send again; an error that does not say what was asked gets only what is known", async () => { + expect(await say(() => new ApiError("Too Many Requests", 429), write)).toMatchObject({ retrySafe: true, sentence: "Agility is busy. The same request may work in a moment." }); + // An error from a function of /wire on a transport no client wrapped carries no stamp. + const client = new AgilityApiClient({ baseUrl: "https://agility.example.com/I" }, { transport: failing(timeout()) }); + const [bare] = await client.explain(timeout()); + expect(bare).toMatchObject({ retrySafe: null, audience: "user", sentence: "Agility could not be reached, or is busy." }); + // The stamp never carries the body or the headers. + const stamped = await client.transport.request({ ...write, headers: { authorization: "Bearer secret" } }).catch((e: unknown) => e) as ApiError; + expect(Object.keys(stamped.request!).sort()).toEqual(["idempotent", "method", "path"]); + // And the question does not arise for an answered refusal. + expect((await client.explain([{ index: 0, message: "Violation'Required'Story.Scope", command: {} } as never]))[0]!.retrySafe).toBeNull(); + }); +}); From 5ca8a5f75c20ac7b29d90de29751e864291f409d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:49:25 +0000 Subject: [PATCH 2/6] Recognise the server's SQL execution timeout: SERVER_TIMEOUT, never resent A server-side SQL execution timeout, as an instance answers it, arrives as an error document (a SqlException beginning "Execution Timeout Expired", a Win32Exception "The wait operation timed out"), not as a 408. It surfaced as a bare "Server Error" and a read was sent again. apiErrorFromResponse now codes it SERVER_TIMEOUT by the exception's type and the start of its message, whatever the status; the resend rule leaves it alone; explain says to ask for less, with retrySafe false; a 400 carrying it is not re-coded as a rejected query; the conformance suite checks a refusal's code. Unit-tested with the document as sent, through query.v1, api/asset and rest-1. Not provoked live. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 34 +++++++++++++++++++++--- README.md | 4 +-- specs/000-layers.md | 7 +++++ src/core/errors.ts | 32 ++++++++++++++++++++-- src/core/retry.ts | 5 ++-- src/services/explain.ts | 11 +++++++- src/testing/transportConformance.ts | 3 +++ src/wire/queryV1.ts | 3 ++- test/unit/retry.test.ts | 41 ++++++++++++++++++++++++++++- test/unit/timeout.test.ts | 13 ++++++++- 10 files changed, 140 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d7b7e9b..8f0215f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,8 @@ therefore run twice while the first might still be running, and the caller waited two timeouts. Now nothing is resent after a timeout, whoever gave up: the client (`TIMEOUT`), the server (a 408) or a - gateway (a 504). A lost connection, a 429 and any other 5xx are resent + gateway (a 504), or the server's own SQL execution timeout + (`SERVER_TIMEOUT`, under Added). A lost connection, a 429 and any other 5xx are resent once as before. `client.pages` and `client.all` stop at the first timeout. `TIMEOUT` is still `kind: "transient"` (the same request may work later): the kind says what the failure is, and the resend rule is @@ -32,15 +33,42 @@ did not answer in time. The request may still be running: wait before trying again."; a 429 is "Agility is busy. The same request may work in a moment."; an error that does not say what was asked is "Agility could - not be reached, or is busy.". Migration: a test that asserts the old + not be reached, or is busy."; a read the server itself gave up on + (`SERVER_TIMEOUT`) is "Agility gave up on this request: it takes more + work than the server allows. Sending it again will cost the same. Ask + for less: a smaller page, fewer selected paths, a tighter filter.". + Migration: a test that asserts the old sentence for a write; a consumer that offers a retry button should decide on `retrySafe` (below). ### Added +- **A server-side SQL execution timeout, as an instance answers it, has + its own code: `SERVER_TIMEOUT`.** The server gives up on a request + that takes longer than it allows and answers an error document whose + `exceptions` hold a `SqlException` beginning "Execution Timeout + Expired" and a `Win32Exception` "The wait operation timed out". It + used to surface as a bare "Server Error" and, being a 5xx, a read was + sent again: the same cost, twice. Now it is told by the exception's + type and the start of its message, whatever the status: `code: + "SERVER_TIMEOUT"`, `kind: "transient"`, the exception's words as the + message, the whole document in `details`, never resent, and explained + as above. Recognised in `apiErrorFromResponse`, so a custom transport + that builds its errors there has it too, and `transportConformance` + now checks that a refusal carries the code `apiErrorFromResponse` + gives it. Migration: nothing for the built-in transport; a custom + transport that builds refusals by hand calls `apiErrorFromResponse( + status, body)` instead. Proved by unit tests with the document as an + instance sent it, through query.v1, api/asset and rest-1; it has not + been provoked live (that would mean running a query that costly), the + status it arrives with is not known, and whether api/asset reports it + in this shape or in its own `Exceptions` list is not confirmed (both + are recognised). - `Explanation.retrySafe`: `true` when sending the same request again is safe (a read, a guarded batch, anything refused with a 429), `false` - for a write that got no answer or a server failure, `null` when the + for a write that got no answer or a server failure and for a read the + server gave up on (the same request would cost and fail the same), + `null` when the server answered and said why, or when it cannot be told. - `ApiError.request`: `{ method, path, idempotent }`, stamped by the client on every error it lets out, with any transport. Never the body diff --git a/README.md b/README.md index d9a5292..1bb7a9c 100644 --- a/README.md +++ b/README.md @@ -147,8 +147,8 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `TypeCache` - one instance's loaded type definitions, shared by many clients (`new AgilityApiClient(config, { types })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded - `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401 (resends idempotent requests once), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one - **Timeouts are the client's business with any transport**: each attempt has `timeoutMs` (default 60000; 0 for none), and at the deadline the request rejects with an `ApiError` coded `TIMEOUT`, whether or not a custom transport lets go of it (the transport is handed a `signal` that fires then; a late answer is discarded). A timed-out write may still have been applied. A custom transport that waits for a person inside `request` (a sign-in prompt before it replays the request) sets `timeoutMs: 0`: the deadline cannot tell a person from a slow network. The built-in transport's `onUnauthorized` hook runs outside the deadline -- Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read or a guarded batch (which the guard makes safe to repeat) is `retrySafe: true`. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) -- Resends and failures are the client's business with any transport: an idempotent request (a GET, a read, a guarded batch with no creates) is sent once more after a network failure, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403, and **never after a timeout**: the client's `TIMEOUT`, a 408 or a 504. A timeout or an abort ends the client's wait and does not stop the work on the server, so a query that timed out may still be running; `pages` and `all` stop at the first one), and `onError(error, request)` in the config is told about each request that finally failed +- Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read or a guarded batch (which the guard makes safe to repeat) is `retrySafe: true`, except a read the server itself gave up on (`SERVER_TIMEOUT`), which is `false`: the same request would cost and fail the same. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) +- Resends and failures are the client's business with any transport: an idempotent request (a GET, a read, a guarded batch with no creates) is sent once more after a network failure, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403, and **never after a timeout**: the client's `TIMEOUT`, a 408, a 504, or the server's own SQL execution timeout, which arrives as an error document and is coded `SERVER_TIMEOUT` (ask for less: a smaller page, fewer selected paths, a tighter filter). A timeout or an abort ends the client's wait and does not stop the work on the server, so a query that timed out may still be running; `pages` and `all` stop at the first one), and `onError(error, request)` in the config is told about each request that finally failed - A custom `Transport` (`new AgilityApiClient(config, { transport })`) decides by itself where requests go; `config.baseUrl` is then used only for the links the client builds (`urls.*`, `embeddedImages.normalize`). `apiErrorFromResponse(status, data)` is the error the fetch transport throws for a refused response, for a custom transport to throw the same - `@versionone/agility-sdk/services` - the services as free functions over a `Transport` (`guard`, `batch`, `resolve`, `schema`, `attachments`, `fields`), for a caller that composes one differently; the client's methods are the same things - `@versionone/agility-sdk/wire` - the wire modules (`assetApi`, `queryV1`, `rest1`, `meta`, `loc2`, `attachment`, `fields`, `select`), for passthroughs and transport authors; they speak the endpoints' own shapes. diff --git a/specs/000-layers.md b/specs/000-layers.md index 67a7bc1..227e490 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -256,6 +256,13 @@ query that timed out may still be running, and a request that ran out of time is likely one that costs a lot, so sending it again runs the cost twice and makes the caller wait twice. That holds whoever gave up: the client (`TIMEOUT`), the server (408) or a gateway in front of it (504). +The server also has a timeout of its own on the SQL a request runs, and +answers it as an error document, not a status: `exceptions` holding a +`SqlException` whose message begins "Execution Timeout Expired" (and a +`Win32Exception` "The wait operation timed out"). `apiErrorFromResponse` +codes that `SERVER_TIMEOUT`, whatever the status, and it is not resent +either: the same request would cost the same. The remedy is a smaller +request (page, selected paths, filter), which `explain` says. `pages` and `all` stop at the first timeout rather than pressing on. A caller that wants to try again does so itself, knowing the cost. The deadline cannot tell the network from a person: a custom transport that waits for someone diff --git a/src/core/errors.ts b/src/core/errors.ts index b8effb6..1203ff0 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -24,6 +24,7 @@ export function kindOf(status: number, code?: string): ErrorKind { switch (code) { case "ABORTED": return "aborted"; case "TIMEOUT": + case "SERVER_TIMEOUT": case "NETWORK_ERROR": return "transient"; case "BAD_JSON": case "BAD_RESPONSE": return "protocol"; @@ -105,10 +106,37 @@ function messageOf(data: unknown, status: number): string { * parsed JSON when the server sent JSON, else the text. The message comes * from the shapes the endpoints send (rest-1's `exceptions`, api/asset's * `Exceptions`, a bare `message`, or the text itself), `HTTP ` - * when the body says nothing; `details` is `data` unchanged. + * when the body says nothing; `details` is `data` unchanged. One body + * gets a code: a server-side SQL execution timeout, as an instance answers + * it, is `SERVER_TIMEOUT` (kind transient, never resent), worded by the + * exception that says so. */ export function apiErrorFromResponse(status: number, data?: unknown): ApiError { - return new ApiError(messageOf(data, status), status, undefined, data); + const gaveUp = serverTimeoutIn(data); + // "Server Error" says nothing; the exception's own words say what happened. + return gaveUp === null ? new ApiError(messageOf(data, status), status, undefined, data) : new ApiError(gaveUp, status, "SERVER_TIMEOUT", data); +} + +/** + * The message of the exception that says so, or null: is this error body a server-side SQL execution timeout, as an instance + * answers it? The server gave up on a request that took longer than it + * allows: `{ error: "Server Error", exceptions: [{ type: "SqlException", + * message: "Execution Timeout Expired. …" }, { type: "Win32Exception", + * message: "The wait operation timed out" }] }`. Told by the exception's + * type and the start of its message, whatever the status. The same test + * is made of the entries of api/asset's `Exceptions` (plain strings), in + * case that endpoint reports one so; that it does is not confirmed. + */ +function serverTimeoutIn(data: unknown): string | null { + if (!data || typeof data !== "object") return null; + const body = data as { exceptions?: unknown; Exceptions?: unknown }; + const entries = [...(Array.isArray(body.exceptions) ? body.exceptions : []), ...(Array.isArray(body.Exceptions) ? body.Exceptions : [])]; + for (const entry of entries) { + const type = entry && typeof entry === "object" ? String((entry as { type?: unknown }).type ?? "") : ""; + const message = (typeof entry === "string" ? entry : entry && typeof entry === "object" ? String((entry as { message?: unknown }).message ?? "") : "").trim(); + if ((message.startsWith("Execution Timeout Expired") && (type === "" || type === "SqlException")) || (type === "Win32Exception" && message.startsWith("The wait operation timed out"))) return message; + } + return null; } /** diff --git a/src/core/retry.ts b/src/core/retry.ts index 3b87f5a..26f433f 100644 --- a/src/core/retry.ts +++ b/src/core/retry.ts @@ -81,13 +81,14 @@ export function withTimeout(transport: Transport, timeoutMs: number): Transport * fell over: no connection (NETWORK_ERROR), a 429, a 5xx. * * Not after a timeout, of the client's (TIMEOUT) or of the server's or a - * gateway's (408, 504). A timeout ends the wait; it does not stop the + * gateway's (408, 504, or the server's own SQL execution timeout, which + * arrives as an error document and is coded SERVER_TIMEOUT). A timeout ends the wait; it does not stop the * work. The request may still be running on the server, and a request that * ran out of time is likely one that costs a lot: sending it again runs * the cost twice and keeps the caller waiting twice as long. */ export function resendable(error: unknown): boolean { - return error instanceof ApiError && error.kind === "transient" && error.code !== "TIMEOUT" && error.status !== 408 && error.status !== 504; + return error instanceof ApiError && error.kind === "transient" && error.code !== "TIMEOUT" && error.code !== "SERVER_TIMEOUT" && error.status !== 408 && error.status !== 504; } /** diff --git a/src/services/explain.ts b/src/services/explain.ts index 216f4df..c4c27e3 100644 --- a/src/services/explain.ts +++ b/src/services/explain.ts @@ -60,7 +60,9 @@ export interface Explanation { * read, a guarded batch, anything the server turned away with a 429). * False: a write that got no answer, or a server failure in answer to * one; the change may or may not have been made, so look before trying - * again. Null when the question does not arise (the server answered and + * again; or a read the server itself gave up on (SERVER_TIMEOUT), which + * would cost and fail the same, so the request is to be made smaller, + * not repeated. Null when the question does not arise (the server answered and * said why) or cannot be told (the error does not say what was asked, * as one from a `/wire` function on a bare transport does not). Decide * on this field, not on the wording of `sentence`. @@ -147,13 +149,20 @@ function failuresOf(input: unknown): CommandFailureDetail[] | null { * that timed out: safe to repeat, but it may still be running, so not * at once; * - a read that never got through: safe, and may work in a moment; + * - a read the server itself gave up on (its SQL execution timeout, + * code SERVER_TIMEOUT): harmless to the data and still not to be + * repeated (retrySafe false), since it will cost the server the same + * and fail the same; the thing to do is ask for less; * - no stamp: say only what is known. */ function unanswered(error: ApiError): Said { if (error.status === 429) return forUser("Agility is busy. The same request may work in a moment.", true); const asked = error.request; + if (error.code === "SERVER_TIMEOUT" && !asked) return forUser("Agility gave up on this request: it takes more work than the server allows."); if (!asked) return forUser("Agility could not be reached, or is busy."); if (!asked.idempotent) return forUser("Agility did not confirm the change. It may or may not have been made: check before trying again.", false); + // The server itself gave up: the request costs more than it allows, and will cost the same again. + if (error.code === "SERVER_TIMEOUT") return forUser("Agility gave up on this request: it takes more work than the server allows. Sending it again will cost the same. Ask for less: a smaller page, fewer selected paths, a tighter filter.", false); const timedOut = error.code === "TIMEOUT" || error.status === 408 || error.status === 504; if (timedOut) return forUser("Agility did not answer in time. The request may still be running: wait before trying again.", true); return forUser("Agility could not be reached, or is busy. The same request may work in a moment.", true); diff --git a/src/testing/transportConformance.ts b/src/testing/transportConformance.ts index cd61345..bcf6da3 100644 --- a/src/testing/transportConformance.ts +++ b/src/testing/transportConformance.ts @@ -155,6 +155,8 @@ export function transportConformance(make: (server: ConformanceServer) => Transp const bodies: [number, unknown][] = [ [400, { _type: "Error", error: "Invalid WHERE parameter", exceptions: [{ type: "FormatException", message: "Invalid QueryFilter2 token Nope=1" }] }], [400, { Exceptions: ["The request body is not valid JSON."] }], + // A server-side SQL execution timeout, as an instance answers it: told by its body, coded SERVER_TIMEOUT. + [500, { error: "Server Error", exceptions: [{ type: "SqlException", message: "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding." }, { type: "Win32Exception", message: "The wait operation timed out" }] }], [401, "Unauthorized"], [503, ""] ]; @@ -165,6 +167,7 @@ export function transportConformance(make: (server: ConformanceServer) => Transp expect(error instanceof ApiError, `a ${status} must reject with an ApiError`); expect(error.status === status && error.kind === expected.kind, `a ${status} must carry its status and the kind it implies (${expected.kind})`); expect(error.message === expected.message, `a ${status} must be worded as apiErrorFromResponse words it ("${expected.message}"), got "${error.message}"`); + expect(error.code === expected.code, `a ${status} with this body must carry the code apiErrorFromResponse gives it (${expected.code}), got ${error.code}`); if (typeof data === "object") expect(same(error.details, data), "the parsed error body must be the error's details"); } } }, diff --git a/src/wire/queryV1.ts b/src/wire/queryV1.ts index 3b83c44..cfc9718 100644 --- a/src/wire/queryV1.ts +++ b/src/wire/queryV1.ts @@ -40,7 +40,8 @@ export interface QueryRejection { type: string | null; message: string } export function rejected(error: ApiError): ApiError { const details = error.details as { error?: unknown; exceptions?: { type?: unknown; message?: unknown }[] } | undefined; const rejections: QueryRejection[] = (details?.exceptions ?? []).filter((e) => e && typeof e.message === "string" && e.message).map((e) => ({ type: typeof e.type === "string" ? e.type : null, message: e.message as string })); - if (!rejections.length) return error; + // The server's own timeout is not a refusal of the query, whatever status it came with. + if (!rejections.length || error.code === "SERVER_TIMEOUT") return error; // rest-1 names what it refused in `error` ("Invalid WHERE parameter"); query.v1 says only "Bad Request", which adds nothing. const lead = typeof details?.error === "string" && details.error && details.error !== "Bad Request" ? [details.error] : []; return new ApiError([...lead, ...rejections.map((r) => r.message)].join("; "), error.status, "QUERY_REJECTED", rejections); diff --git a/test/unit/retry.test.ts b/test/unit/retry.test.ts index 360de7e..8f4c08a 100644 --- a/test/unit/retry.test.ts +++ b/test/unit/retry.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import { AgilityApiClient } from "../../src/client"; -import { ApiError } from "../../src/core/errors"; +import { ApiError, apiErrorFromResponse } from "../../src/core/errors"; +import { resendable } from "../../src/core/retry"; import { createFetchTransport } from "../../src/core/fetchTransport"; import type { RequestOptions, Transport } from "../../src/core/transport"; import { FakeAgilityClient } from "../../src/testing"; @@ -45,6 +46,44 @@ describe("the resend rule above a custom Transport", () => { } }); + it("a server-side SQL execution timeout, as an instance answers it, is told by its body, coded SERVER_TIMEOUT and never sent again, whatever its status or the method", async () => { + const gaveUp = () => ({ error: "Server Error", exceptions: [{ type: "SqlException", message: "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding." }, { type: "Win32Exception", message: "The wait operation timed out" }] }); + const words = "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding."; + // The status it arrives with is not known (most likely 500), so the body decides. + for (const status of [500, 400, 503]) { + const error = apiErrorFromResponse(status, gaveUp()); + expect(error).toMatchObject({ code: "SERVER_TIMEOUT", kind: "transient", status, message: words, details: gaveUp() }); + expect(resendable(error)).toBe(false); + } + // Either exception alone is enough; the type and the start of the message are what is matched. + expect(apiErrorFromResponse(500, { error: "Server Error", exceptions: [{ type: "Win32Exception", message: "The wait operation timed out" }] }).code).toBe("SERVER_TIMEOUT"); + expect(apiErrorFromResponse(500, { error: "Server Error", exceptions: [{ type: "SqlException", message: "Execution Timeout Expired." }] }).code).toBe("SERVER_TIMEOUT"); + // api/asset lists its exceptions as plain strings; that it reports this one so is not confirmed, and it is recognised if it does. + expect(apiErrorFromResponse(500, { Exceptions: [words] }).code).toBe("SERVER_TIMEOUT"); + // Controls: another SQL failure, another server error, the words elsewhere in a message. + for (const body of [{ error: "Server Error", exceptions: [{ type: "SqlException", message: "Invalid column name 'x'." }] }, { error: "Server Error", exceptions: [{ type: "NullReferenceException", message: "Object reference not set" }] }, { error: "Bad Request", exceptions: [{ type: "FormatException", message: "no token 'Execution Timeout Expired'" }] }, "Execution Timeout Expired", null]) { + expect(apiErrorFromResponse(500, body).code).toBeUndefined(); + } + + // Through the client, by each read endpoint and a write, with the built-in transport: sent once. + for (const status of [500, 400]) { + const sends: string[] = []; + const fetchImpl = (async (url: string | URL, init?: RequestInit) => { + const path = new URL(String(url)).pathname; + if (path.startsWith("/meta.v1/")) return new Response("{}", { status: 404 }); + sends.push(`${init?.method ?? "GET"} ${path}`); + return new Response(JSON.stringify(gaveUp()), { status, headers: { "content-type": "application/json" } }); + }) as typeof fetch; + const client = new AgilityApiClient({ baseUrl: "https://x", retries: 3 }, { transport: createFetchTransport({ baseUrl: "https://x", fetchImpl }) }); + const asked = { code: "SERVER_TIMEOUT", kind: "transient", status, message: words }; + await expect(client.query(q)).rejects.toMatchObject({ ...asked, request: { method: "POST", path: "/query.v1", idempotent: true } }); + await expect(client.queryPage(q)).rejects.toMatchObject(asked); + await expect(client.deleted("Story", { select: ["Name"], page: { size: 1, start: 0 } })).rejects.toMatchObject(asked); + await expect(client.send([{ op: "update", oid: "Story:1", attributes: { Name: "n" } }])).rejects.toMatchObject({ status }); + expect(sends).toHaveLength(4); + } + }); + it("pages and all stop at the first timeout rather than pressing on", async () => { const t = custom([[{ _oid: "Story:1", Name: "a" }, { _oid: "Story:2", Name: "b" }]], new ApiError("Timed out after 60000 ms", 0, "TIMEOUT"), [[{ _oid: "Story:9", Name: "never read" }]]); const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: noTypes(t) }); diff --git a/test/unit/timeout.test.ts b/test/unit/timeout.test.ts index c1366f8..014c266 100644 --- a/test/unit/timeout.test.ts +++ b/test/unit/timeout.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { AgilityApiClient } from "../../src/client"; -import { ApiError } from "../../src/core/errors"; +import { ApiError, apiErrorFromResponse } from "../../src/core/errors"; import { createFetchTransport } from "../../src/core/fetchTransport"; import type { RequestOptions, Transport } from "../../src/core/transport"; @@ -132,6 +132,17 @@ describe("the built-in transport under the same rule", () => { }); describe("what to tell a person when a request got no answer", () => { + it("a read the server itself gave up on (its SQL execution timeout) is not 'wait and try again': the same request costs the same, so ask for less; a write keeps the sentence about the change", async () => { + const gaveUp = () => apiErrorFromResponse(500, { error: "Server Error", exceptions: [{ type: "SqlException", message: "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding." }, { type: "Win32Exception", message: "The wait operation timed out" }] }); + for (const request of [read, guarded]) { + expect(await say(gaveUp, request)).toMatchObject({ audience: "user", retrySafe: false, sentence: "Agility gave up on this request: it takes more work than the server allows. Sending it again will cost the same. Ask for less: a smaller page, fewer selected paths, a tighter filter." }); + } + expect(await say(gaveUp, write)).toMatchObject({ retrySafe: false, sentence: "Agility did not confirm the change. It may or may not have been made: check before trying again." }); + // With no stamp (a /wire function on a bare transport): what is known, and no advice about a query it may not have been. + const [bare] = await new AgilityApiClient({ baseUrl: "https://agility.example.com/I" }, { transport: failing(gaveUp()) }).explain(gaveUp()); + expect(bare).toMatchObject({ audience: "user", retrySafe: null, sentence: "Agility gave up on this request: it takes more work than the server allows." }); + }); + const failing = (failure: ApiError): Transport => ({ request: (() => Promise.reject(failure)) as Transport["request"] }); const say = async (failure: () => ApiError, request: RequestOptions) => { const client = new AgilityApiClient({ baseUrl: "https://agility.example.com/I", retries: 0 }, { transport: failing(failure()) }); From 51e59fc3be3d47e35afce2863fa2a2ac84fecc48 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:51:46 +0000 Subject: [PATCH 3/6] Say what retrySafe false means: do not resend as it is, not that the outcome is unknown Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 6 ++++-- README.md | 2 +- src/services/explain.ts | 7 ++++++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f0215f..1b11251 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,8 +68,10 @@ safe (a read, a guarded batch, anything refused with a 429), `false` for a write that got no answer or a server failure and for a read the server gave up on (the same request would cost and fail the same), - `null` when the - server answered and said why, or when it cannot be told. + `null` when the server answered and said why, or when it cannot be + told. `false` means "do not send it again as it is" and nothing more: + whether the outcome is unknown is `error.request.idempotent === false` + (a write), not `retrySafe`. - `ApiError.request`: `{ method, path, idempotent }`, stamped by the client on every error it lets out, with any transport. Never the body or headers. Absent on an error from a `/wire` or `/services` function diff --git a/README.md b/README.md index 1bb7a9c..6ab80c7 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `TypeCache` - one instance's loaded type definitions, shared by many clients (`new AgilityApiClient(config, { types })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded - `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401 (resends idempotent requests once), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one - **Timeouts are the client's business with any transport**: each attempt has `timeoutMs` (default 60000; 0 for none), and at the deadline the request rejects with an `ApiError` coded `TIMEOUT`, whether or not a custom transport lets go of it (the transport is handed a `signal` that fires then; a late answer is discarded). A timed-out write may still have been applied. A custom transport that waits for a person inside `request` (a sign-in prompt before it replays the request) sets `timeoutMs: 0`: the deadline cannot tell a person from a slow network. The built-in transport's `onUnauthorized` hook runs outside the deadline -- Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read or a guarded batch (which the guard makes safe to repeat) is `retrySafe: true`, except a read the server itself gave up on (`SERVER_TIMEOUT`), which is `false`: the same request would cost and fail the same. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) +- Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read or a guarded batch (which the guard makes safe to repeat) is `retrySafe: true`, except a read the server itself gave up on (`SERVER_TIMEOUT`), which is `false`: the same request would cost and fail the same. `retrySafe: false` means "do not send it again as it is" and nothing more; whether the outcome is unknown is `error.request.idempotent === false` (a write: look before acting), not `retrySafe`. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) - Resends and failures are the client's business with any transport: an idempotent request (a GET, a read, a guarded batch with no creates) is sent once more after a network failure, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403, and **never after a timeout**: the client's `TIMEOUT`, a 408, a 504, or the server's own SQL execution timeout, which arrives as an error document and is coded `SERVER_TIMEOUT` (ask for less: a smaller page, fewer selected paths, a tighter filter). A timeout or an abort ends the client's wait and does not stop the work on the server, so a query that timed out may still be running; `pages` and `all` stop at the first one), and `onError(error, request)` in the config is told about each request that finally failed - A custom `Transport` (`new AgilityApiClient(config, { transport })`) decides by itself where requests go; `config.baseUrl` is then used only for the links the client builds (`urls.*`, `embeddedImages.normalize`). `apiErrorFromResponse(status, data)` is the error the fetch transport throws for a refused response, for a custom transport to throw the same - `@versionone/agility-sdk/services` - the services as free functions over a `Transport` (`guard`, `batch`, `resolve`, `schema`, `attachments`, `fields`), for a caller that composes one differently; the client's methods are the same things diff --git a/src/services/explain.ts b/src/services/explain.ts index c4c27e3..33bfca5 100644 --- a/src/services/explain.ts +++ b/src/services/explain.ts @@ -65,7 +65,12 @@ export interface Explanation { * not repeated. Null when the question does not arise (the server answered and * said why) or cannot be told (the error does not say what was asked, * as one from a `/wire` function on a bare transport does not). Decide - * on this field, not on the wording of `sentence`. + * on this field, not on the wording of `sentence`. False means "do not + * send it again as it is" and nothing more: it does not say whether + * the outcome is unknown. For that, read the error's + * `request.idempotent`: false is a write whose outcome nobody knows + * (look before acting); true with `code: "SERVER_TIMEOUT"` is a read + * that failed and will fail the same way (re-reading is no remedy). */ retrySafe: boolean | null; /** The failed command's index in the batch, when this explains one; null otherwise. */ From b4423c1577aeb9278d5fa3dda889ef7a7720a960 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:54:56 +0000 Subject: [PATCH 4/6] Explanation.outcome: is it known whether the change was made retrySafe false covered a write whose fate is unknown and a read that will fail the same way, which call for opposite actions. The fact is now a field: unknown (a write with no confirmation), notApplied (the server refused before doing the work; one failed command of a batch), null (a read, or nothing known of the request). Replaces the previous commit's advice to derive it from request.idempotent, which was wrong for a write the server refused. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 19 ++++++++++++++--- README.md | 2 +- src/services/explain.ts | 45 ++++++++++++++++++++++++++++++++------- test/unit/explain.test.ts | 2 +- test/unit/timeout.test.ts | 32 ++++++++++++++++++++++++++-- 5 files changed, 85 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b11251..4afeff9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,9 +69,22 @@ for a write that got no answer or a server failure and for a read the server gave up on (the same request would cost and fail the same), `null` when the server answered and said why, or when it cannot be - told. `false` means "do not send it again as it is" and nothing more: - whether the outcome is unknown is `error.request.idempotent === false` - (a write), not `retrySafe`. + told. It answers "may the same request be sent again as it is?" and + nothing more. +- `Explanation.outcome`: is it known whether the change was made? + `"unknown"` for a write that got no confirmation (no answer, a + timeout of the client's or the server's, a cancelled wait, a 5xx, an + unreadable answer): look before acting. `"notApplied"` where the + server answered a refusal before doing the work: a 4xx (a 429 + included) in answer to a write, a guarded write that met a conflict, + and each failed command when a batch's failures are explained (that + command alone: the others are in the Outcome). `null` for a read, for + a guarded batch with no creates (safe to send again, and the guard + settles it) and for an error that does not say what was asked. With + `retrySafe` these are the two questions a consumer has after a + failure, as two fields: `retrySafe: false` covers both a write whose + fate is unknown (`outcome: "unknown"`) and a read that will fail the + same way again (`outcome: null`), which call for opposite actions. - `ApiError.request`: `{ method, path, idempotent }`, stamped by the client on every error it lets out, with any transport. Never the body or headers. Absent on an error from a `/wire` or `/services` function diff --git a/README.md b/README.md index 6ab80c7..27cbfcb 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `TypeCache` - one instance's loaded type definitions, shared by many clients (`new AgilityApiClient(config, { types })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded - `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401 (resends idempotent requests once), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one - **Timeouts are the client's business with any transport**: each attempt has `timeoutMs` (default 60000; 0 for none), and at the deadline the request rejects with an `ApiError` coded `TIMEOUT`, whether or not a custom transport lets go of it (the transport is handed a `signal` that fires then; a late answer is discarded). A timed-out write may still have been applied. A custom transport that waits for a person inside `request` (a sign-in prompt before it replays the request) sets `timeoutMs: 0`: the deadline cannot tell a person from a slow network. The built-in transport's `onUnauthorized` hook runs outside the deadline -- Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read or a guarded batch (which the guard makes safe to repeat) is `retrySafe: true`, except a read the server itself gave up on (`SERVER_TIMEOUT`), which is `false`: the same request would cost and fail the same. `retrySafe: false` means "do not send it again as it is" and nothing more; whether the outcome is unknown is `error.request.idempotent === false` (a write: look before acting), not `retrySafe`. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) +- Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read or a guarded batch (which the guard makes safe to repeat) is `retrySafe: true`, except a read the server itself gave up on (`SERVER_TIMEOUT`), which is `false`: the same request would cost and fail the same. The two questions after a failure are two fields: `retrySafe` (may the same request be sent again as it is?) and `outcome` (is it known whether the change was made?). `outcome` is `"unknown"` for a write that got no confirmation (no answer, a timeout, a 5xx: look before acting), `"notApplied"` where the server answered a refusal before doing the work (a 4xx or a 429 in answer to a write, a conflict, and each failed command in the explanation of a batch, which says nothing of the batch's other commands: those are in the Outcome), and `null` for a read or when the error does not say what was asked. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) - Resends and failures are the client's business with any transport: an idempotent request (a GET, a read, a guarded batch with no creates) is sent once more after a network failure, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403, and **never after a timeout**: the client's `TIMEOUT`, a 408, a 504, or the server's own SQL execution timeout, which arrives as an error document and is coded `SERVER_TIMEOUT` (ask for less: a smaller page, fewer selected paths, a tighter filter). A timeout or an abort ends the client's wait and does not stop the work on the server, so a query that timed out may still be running; `pages` and `all` stop at the first one), and `onError(error, request)` in the config is told about each request that finally failed - A custom `Transport` (`new AgilityApiClient(config, { transport })`) decides by itself where requests go; `config.baseUrl` is then used only for the links the client builds (`urls.*`, `embeddedImages.normalize`). `apiErrorFromResponse(status, data)` is the error the fetch transport throws for a refused response, for a custom transport to throw the same - `@versionone/agility-sdk/services` - the services as free functions over a `Transport` (`guard`, `batch`, `resolve`, `schema`, `attachments`, `fields`), for a caller that composes one differently; the client's methods are the same things diff --git a/src/services/explain.ts b/src/services/explain.ts index 33bfca5..cdd6f6d 100644 --- a/src/services/explain.ts +++ b/src/services/explain.ts @@ -65,14 +65,32 @@ export interface Explanation { * not repeated. Null when the question does not arise (the server answered and * said why) or cannot be told (the error does not say what was asked, * as one from a `/wire` function on a bare transport does not). Decide - * on this field, not on the wording of `sentence`. False means "do not - * send it again as it is" and nothing more: it does not say whether - * the outcome is unknown. For that, read the error's - * `request.idempotent`: false is a write whose outcome nobody knows - * (look before acting); true with `code: "SERVER_TIMEOUT"` is a read - * that failed and will fail the same way (re-reading is no remedy). + * on this field, not on the wording of `sentence`. It answers one + * question, "may the same request be sent again as it is?", and not + * "did it happen?", which is `outcome`. */ retrySafe: boolean | null; + /** + * Is it known whether the change was made? The second question after + * a failed write, beside `retrySafe`, so nobody derives it from a + * status and a method. + * - "unknown": a write (a request not safe to repeat) that got no + * confirmation: no answer, a timeout of the client's or the + * server's, a cancelled wait, a 5xx, an answer that could not be + * read. It may or may not have been applied: look before acting. + * - "notApplied": the server answered and refused before doing the + * work: a 4xx (a 429 included) in answer to a write, a guarded + * write that met a conflict, or, in the explanation of one failed + * command, that command. For a batch this speaks of that command + * alone: what became of the others is in the Outcome (`created`, + * `modified`, `failures`), not here. + * - null: a read, where there is nothing to apply; a request the + * SDK marks safe to repeat (a guarded batch with no creates, + * which cannot be told from a read by its error: send it again + * and the guard settles it); and an error that does not say what + * was asked. + */ + outcome: "unknown" | "notApplied" | null; /** The failed command's index in the batch, when this explains one; null otherwise. */ index: number | null; /** What was violated: Required, Invalid, Unresolved, Ambiguous, AssetCannotDeleteClosed, …; null when the message is not such a token. */ @@ -110,6 +128,16 @@ const typeTag = (type: string): string => `AssetType'${type}`; const isTag = (message: string): boolean => /^[A-Za-z]\w*'[^\s]+$/.test(message.trim()); type Said = Pick; + +/** What is known of the change an error's request asked for. See `Explanation.outcome`. */ +function outcomeOf(error: unknown): Explanation["outcome"] { + if (!(error instanceof ApiError)) return null; + // The guard compared and found a difference: it sent nothing, or the server applied nothing. + if (error.kind === "conflict") return "notApplied"; + if (!error.request || error.request.idempotent) return null; + // A write. The server answered a refusal (4xx; a 408 is a timeout, not a refusal), or nobody knows. + return error.status >= 400 && error.status < 500 && error.status !== 408 && error.code !== "SERVER_TIMEOUT" ? "notApplied" : "unknown"; +} const forUser = (sentence: string, retrySafe: boolean | null = null): Said => ({ sentence, audience: "user", echoed: false, retrySafe }); const forDeveloper = (sentence: string, echoed: boolean): Said => ({ sentence, audience: "developer", echoed, retrySafe: null }); @@ -196,7 +224,7 @@ function sentenceForError(error: unknown): Said { */ export async function explain(transport: Transport, input: unknown, options: loc2.LocalizeOptions = {}): Promise { const failures = failuresOf(input); - if (!failures) return [{ ...sentenceForError(input), index: null, rule: null, attribute: null, attributeLabel: null, typeLabel: null, relatedType: null, relatedTypeLabel: null, localized: null, message: input instanceof Error ? input.message : String(input) }]; + if (!failures) return [{ ...sentenceForError(input), outcome: outcomeOf(input), index: null, rule: null, attribute: null, attributeLabel: null, typeLabel: null, relatedType: null, relatedTypeLabel: null, localized: null, message: input instanceof Error ? input.message : String(input) }]; const problems = failures.map((f) => problemOf(f.message)); const tags = new Set(); failures.forEach((f, i) => { @@ -218,6 +246,7 @@ export async function explain(transport: Transport, input: unknown, options: loc const typeLabel = type ? label(typeTag(type)) ?? type : null; const related = p.related ? label(typeTag(p.related)) ?? p.related : null; const localized = isTag(f.message) ? label(f.message.trim()) : null; - return { ...sentenceOf(p, attributeLabel, related, localized, f.message), index: f.index, rule: p.rule, attribute: p.attribute, attributeLabel, typeLabel, relatedType: p.related, relatedTypeLabel: related, localized, message: f.message }; + // The server reported this command as failed: it was not applied. Nothing is said here of the batch's other commands. + return { ...sentenceOf(p, attributeLabel, related, localized, f.message), outcome: "notApplied", index: f.index, rule: p.rule, attribute: p.attribute, attributeLabel, typeLabel, relatedType: p.related, relatedTypeLabel: related, localized, message: f.message }; }); } diff --git a/test/unit/explain.test.ts b/test/unit/explain.test.ts index 53c8733..bd3df40 100644 --- a/test/unit/explain.test.ts +++ b/test/unit/explain.test.ts @@ -42,7 +42,7 @@ describe("explain", () => { "Agility Warning: Attempting to delete a closed item. This change was not saved." ]); expect(explained[0]).toEqual({ - sentence: "Project is required.", audience: "user", echoed: false, retrySafe: null, index: 0, rule: "Required", attribute: "Story.Scope", attributeLabel: "Project", typeLabel: "Backlog Item", relatedType: null, relatedTypeLabel: null, + sentence: "Project is required.", audience: "user", echoed: false, retrySafe: null, outcome: "notApplied", index: 0, rule: "Required", attribute: "Story.Scope", attributeLabel: "Project", typeLabel: "Backlog Item", relatedType: null, relatedTypeLabel: null, localized: LOC2["Violation'Required'AttributeDefinition'Scope'Story"], message: "Violation'Required'AttributeDefinition'Scope'Story" }); // A Resolution failure names the attribute as a token and then the related type; loc-2 has no label for these here, so their own names stand in. diff --git a/test/unit/timeout.test.ts b/test/unit/timeout.test.ts index 014c266..c72f3a6 100644 --- a/test/unit/timeout.test.ts +++ b/test/unit/timeout.test.ts @@ -148,7 +148,7 @@ describe("what to tell a person when a request got no answer", () => { const client = new AgilityApiClient({ baseUrl: "https://agility.example.com/I", retries: 0 }, { transport: failing(failure()) }); const error = await client.transport.request(request).catch((e: unknown) => e); const [said] = await client.explain(error); - return { stamp: (error as ApiError).request, sentence: said!.sentence, retrySafe: said!.retrySafe, audience: said!.audience }; + return { stamp: (error as ApiError).request, sentence: said!.sentence, retrySafe: said!.retrySafe, outcome: said!.outcome, audience: said!.audience }; }; const guarded: RequestOptions = { ...write, idempotent: true }; const timeout = () => new ApiError("Timed out after 60000 ms", 0, "TIMEOUT"); @@ -156,10 +156,38 @@ describe("what to tell a person when a request got no answer", () => { it("a write that got no answer, or a server failure for one, is never 'try again': the change may or may not have been made, and retrySafe is false", async () => { for (const failure of [timeout, dropped, () => new ApiError("Bad Gateway", 502), () => new ApiError("Internal Server Error", 500), () => new ApiError("Gateway Timeout", 504)]) { - expect(await say(failure, write)).toEqual({ stamp: { method: "POST", path: "/api/asset", idempotent: false }, audience: "user", retrySafe: false, sentence: "Agility did not confirm the change. It may or may not have been made: check before trying again." }); + expect(await say(failure, write)).toEqual({ stamp: { method: "POST", path: "/api/asset", idempotent: false }, audience: "user", retrySafe: false, outcome: "unknown", sentence: "Agility did not confirm the change. It may or may not have been made: check before trying again." }); } }); + it("outcome says whether it is known that the change was made, so nobody derives it from a status and a method", async () => { + const outcome = async (failure: () => ApiError, request: RequestOptions) => { const said = await say(failure, request); return [said.outcome, said.retrySafe]; }; + const sqlTimeout = () => apiErrorFromResponse(500, { error: "Server Error", exceptions: [{ type: "SqlException", message: "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding." }, { type: "Win32Exception", message: "The wait operation timed out" }] }); + // A write with no confirmation: unknown. Not to be resent. + for (const failure of [timeout, dropped, sqlTimeout, () => new ApiError("Request Timeout", 408), () => new ApiError("Bad Gateway", 502), () => new ApiError("Request aborted", 0, "ABORTED"), () => new ApiError("Response is not JSON", 200, "BAD_JSON")]) { + expect((await outcome(failure, write))[0]).toBe("unknown"); + } + expect(await outcome(timeout, write)).toEqual(["unknown", false]); + // A write the server answered and refused: not applied. A 429 may be sent again; the others say why. + for (const status of [400, 401, 403, 404, 413]) expect(await outcome(() => new ApiError("refused", status), write)).toEqual(["notApplied", null]); + expect(await outcome(() => new ApiError("Too Many Requests", 429), write)).toEqual(["notApplied", true]); + // A read has nothing to apply, whatever happened to it; the two meanings of retrySafe false are told apart here. + for (const failure of [timeout, dropped, sqlTimeout, () => new ApiError("Bad Request", 400), () => new ApiError("Too Many Requests", 429)]) { + expect((await outcome(failure, read))[0]).toBeNull(); + } + expect(await outcome(sqlTimeout, read)).toEqual([null, false]); + // A guarded batch is marked safe to repeat and cannot be told from a read by its error: null, and retrySafe true. + expect(await outcome(timeout, guarded)).toEqual([null, true]); + // A conflict applied nothing, stamped or not; an error that does not say what was asked says nothing. + const bare = new AgilityApiClient({ baseUrl: "https://agility.example.com/I" }, { transport: failing(timeout()) }); + expect((await bare.explain(new ApiError("changed since it was read", 200, "CONFLICT")))[0]!.outcome).toBe("notApplied"); + expect((await bare.explain(timeout()))[0]!.outcome).toBeNull(); + expect((await bare.explain(new Error("boom")))[0]!.outcome).toBeNull(); + // One failed command of a batch: that command was not applied. The others are in the Outcome, not here. + const [one] = await bare.explain([{ index: 1, message: "Violation'Required'AttributeDefinition'Scope'Story" }]); + expect(one).toMatchObject({ index: 1, outcome: "notApplied", retrySafe: null }); + }); + it("a read, or a guarded batch, that timed out is safe to repeat but may still be running; one that never got through may work in a moment", async () => { for (const request of [read, guarded]) { for (const failure of [timeout, () => new ApiError("Gateway Timeout", 504), () => new ApiError("Request Timeout", 408)]) { From 877df0b3ca3973e579c522917b786b210fe3ca7c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:57:58 +0000 Subject: [PATCH 5/6] A guarded write is never resent automatically A second send of a guarded batch harms no data (it matches nothing), but "matched nothing" is how a conflict reads. When the first send landed and only its answer was lost, the resend told the caller that someone else changed the asset and nothing was applied, about its own change. No write is marked idempotent now. A guarded write with no confirmation rejects like any write and is explained as an unconfirmed change with outcome "unknown"; the caller reads the asset again and decides. SendOptions.idempotent is removed from assetApi.send. Proved live: the second send lists no asset and reports no failure. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 29 ++++++++++++++++++++++++----- README.md | 4 ++-- examples/09-browser-session.ts | 4 ++-- specs/000-layers.md | 20 ++++++++++++++------ src/core/clientConfig.ts | 4 ++-- src/core/retry.ts | 2 +- src/core/transport.ts | 5 +++-- src/services/explain.ts | 19 +++++++++---------- src/services/guard.ts | 15 ++++++++++----- src/wire/assetApi.ts | 10 ++-------- test/integration/guard.test.ts | 4 +++- test/unit/fetchTransport.test.ts | 2 +- test/unit/guard.test.ts | 6 +++--- test/unit/retry.test.ts | 17 +++++++++++------ test/unit/timeout.test.ts | 13 +++++++------ test/unit/transportAuth.test.ts | 2 +- 16 files changed, 95 insertions(+), 61 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4afeff9..550f627 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,26 @@ knowing a costly request may then run twice. Applies to the built-in transport and to a custom one alike. +- **A guarded write is no longer sent again automatically.** Since + alpha.5 a guarded batch with no creates (`client.sendGuarded`, + `batch.run` with `guard: true`) was marked idempotent and sent once + more after a lost connection or a 5xx. A second send harms no data: it + matches nothing, because the first advanced the Moment. But "matched + nothing" is how a conflict is reported, so when the first send had + landed and only its answer was lost, the caller was told that someone + else changed the asset and nothing was applied, about its own change. + Now no write is ever resent. A guarded write that gets no answer + rejects like any write, `error.request.idempotent` is `false`, and + `explain` says "Agility did not confirm the change. It may or may not + have been made: check before trying again." with `outcome: + "unknown"`. Migration: on that error, read the asset again; you see + your change or you do not, and the guard makes sending it again safe. + The same holds for the unauthorized hook: `retryable` is now false + for a guarded write, so "retry" does not resend it after a 401 and + "retry-write" does, as for a plain write. + `SendOptions.idempotent` is removed from `/wire`'s `assetApi.send`; + drop it from a call that set it. + ### Changed - **`client.explain` no longer tells a person to try again after a write @@ -29,7 +49,7 @@ which for a write whose fate is unknown is how a duplicate gets made. Now: a write with no answer, a timeout or a 5xx is "Agility did not confirm the change. It may or may not have been made: check before - trying again."; a read or a guarded batch that timed out is "Agility + trying again."; a read that timed out is "Agility did not answer in time. The request may still be running: wait before trying again."; a 429 is "Agility is busy. The same request may work in a moment."; an error that does not say what was asked is "Agility could @@ -65,7 +85,7 @@ in this shape or in its own `Exceptions` list is not confirmed (both are recognised). - `Explanation.retrySafe`: `true` when sending the same request again is - safe (a read, a guarded batch, anything refused with a 429), `false` + safe (a read, anything refused with a 429), `false` for a write that got no answer or a server failure and for a read the server gave up on (the same request would cost and fail the same), `null` when the server answered and said why, or when it cannot be @@ -78,9 +98,8 @@ server answered a refusal before doing the work: a 4xx (a 429 included) in answer to a write, a guarded write that met a conflict, and each failed command when a batch's failures are explained (that - command alone: the others are in the Outcome). `null` for a read, for - a guarded batch with no creates (safe to send again, and the guard - settles it) and for an error that does not say what was asked. With + command alone: the others are in the Outcome). `null` for a read and + for an error that does not say what was asked. With `retrySafe` these are the two questions a consumer has after a failure, as two fields: `retrySafe: false` covers both a write whose fate is unknown (`outcome: "unknown"`) and a read that will fail the diff --git a/README.md b/README.md index 27cbfcb..ccfc866 100644 --- a/README.md +++ b/README.md @@ -147,8 +147,8 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `TypeCache` - one instance's loaded type definitions, shared by many clients (`new AgilityApiClient(config, { types })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded - `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401 (resends idempotent requests once), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one - **Timeouts are the client's business with any transport**: each attempt has `timeoutMs` (default 60000; 0 for none), and at the deadline the request rejects with an `ApiError` coded `TIMEOUT`, whether or not a custom transport lets go of it (the transport is handed a `signal` that fires then; a late answer is discarded). A timed-out write may still have been applied. A custom transport that waits for a person inside `request` (a sign-in prompt before it replays the request) sets `timeoutMs: 0`: the deadline cannot tell a person from a slow network. The built-in transport's `onUnauthorized` hook runs outside the deadline -- Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read or a guarded batch (which the guard makes safe to repeat) is `retrySafe: true`, except a read the server itself gave up on (`SERVER_TIMEOUT`), which is `false`: the same request would cost and fail the same. The two questions after a failure are two fields: `retrySafe` (may the same request be sent again as it is?) and `outcome` (is it known whether the change was made?). `outcome` is `"unknown"` for a write that got no confirmation (no answer, a timeout, a 5xx: look before acting), `"notApplied"` where the server answered a refusal before doing the work (a 4xx or a 429 in answer to a write, a conflict, and each failed command in the explanation of a batch, which says nothing of the batch's other commands: those are in the Outcome), and `null` for a read or when the error does not say what was asked. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) -- Resends and failures are the client's business with any transport: an idempotent request (a GET, a read, a guarded batch with no creates) is sent once more after a network failure, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403, and **never after a timeout**: the client's `TIMEOUT`, a 408, a 504, or the server's own SQL execution timeout, which arrives as an error document and is coded `SERVER_TIMEOUT` (ask for less: a smaller page, fewer selected paths, a tighter filter). A timeout or an abort ends the client's wait and does not stop the work on the server, so a query that timed out may still be running; `pages` and `all` stop at the first one), and `onError(error, request)` in the config is told about each request that finally failed +- Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read is `retrySafe: true`, except a read the server itself gave up on (`SERVER_TIMEOUT`), which is `false`: the same request would cost and fail the same. The two questions after a failure are two fields: `retrySafe` (may the same request be sent again as it is?) and `outcome` (is it known whether the change was made?). `outcome` is `"unknown"` for a write that got no confirmation (no answer, a timeout, a 5xx: look before acting), `"notApplied"` where the server answered a refusal before doing the work (a 4xx or a 429 in answer to a write, a conflict, and each failed command in the explanation of a batch, which says nothing of the batch's other commands: those are in the Outcome), and `null` for a read or when the error does not say what was asked. A guarded write (`sendGuarded`) is a write here too: it is never sent again by the client, because a second send of one that landed applies nothing and reports a conflict, which would tell you someone else changed the asset when the change was yours. When one gets no answer (`outcome: "unknown"`), read the asset again: you see your change or you do not, and the guard makes sending it again safe. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) +- Resends and failures are the client's business with any transport: an idempotent request (a GET, a read; never a write, guarded or not) is sent once more after a network failure, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403, and **never after a timeout**: the client's `TIMEOUT`, a 408, a 504, or the server's own SQL execution timeout, which arrives as an error document and is coded `SERVER_TIMEOUT` (ask for less: a smaller page, fewer selected paths, a tighter filter). A timeout or an abort ends the client's wait and does not stop the work on the server, so a query that timed out may still be running; `pages` and `all` stop at the first one), and `onError(error, request)` in the config is told about each request that finally failed - A custom `Transport` (`new AgilityApiClient(config, { transport })`) decides by itself where requests go; `config.baseUrl` is then used only for the links the client builds (`urls.*`, `embeddedImages.normalize`). `apiErrorFromResponse(status, data)` is the error the fetch transport throws for a refused response, for a custom transport to throw the same - `@versionone/agility-sdk/services` - the services as free functions over a `Transport` (`guard`, `batch`, `resolve`, `schema`, `attachments`, `fields`), for a caller that composes one differently; the client's methods are the same things - `@versionone/agility-sdk/wire` - the wire modules (`assetApi`, `queryV1`, `rest1`, `meta`, `loc2`, `attachment`, `fields`, `select`), for passthroughs and transport authors; they speak the endpoints' own shapes. diff --git a/examples/09-browser-session.ts b/examples/09-browser-session.ts index aff65d9..cbb2640 100644 --- a/examples/09-browser-session.ts +++ b/examples/09-browser-session.ts @@ -39,8 +39,8 @@ const client = new AgilityApiClient({ credentials: "include", // send the session cookie; no accessToken onUnauthorized: async ({ retryable }) => { if (!(await signInAgain())) return "fail"; - // "retry" resends what is safe to send twice: a read, a GET, a guarded - // batch with no creates. `retryable` says whether this request is one. + // "retry" resends what is safe to send twice: a GET, a read. Never a + // write, guarded or not. `retryable` says whether this request is one. if (retryable) return "retry"; // A plain write is never resent by "retry": if it ran before the // refusal, sending it again would apply it twice. "retry-write" resends diff --git a/specs/000-layers.md b/specs/000-layers.md index 227e490..04d18de 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -231,8 +231,7 @@ made), which api/asset's `execute` performs but does not report. The transport retries only idempotent requests (GET by default, and every query.v1 POST, since that endpoint cannot write), only on a network failure, a 5xx or a 429 (Retry-After honoured, up to 30 s), never -another 4xx, never after a timeout (below), and once by default (`retries: 1`); a batch write is never retried unless the -caller has made it idempotent with a guard and says so. That rule is +another 4xx, never after a timeout (below), and once by default (`retries: 1`); a batch write is never retried, guarded or not (below). That rule is the client's, not one transport's: the built-in fetch transport applies it itself (it can read Retry-After), and the client applies it around a custom Transport (`core/retry`), so a consumer's transport does not @@ -299,8 +298,8 @@ of the queries, so every query slot is null and the failures are the answer (thrown for reads and with throwOnFailure); a disagreement with no such failure is an error of its own. -The guard (`services/guard`) is what makes a write batch safe to resend: -each per-asset command of the server's projection is sent scoped to the +The guard (`services/guard`) is what makes a write safe to repeat by a +caller who has looked again: each per-asset command of the server's projection is sent scoped to the asset at the Moment read just before (`where { ID, Moment }`) and to that version still being the current one (`filter RetireDateUTC=''`), so a stale or repeated command matches nothing. The two terms always travel together: @@ -314,8 +313,17 @@ never a success and never confused with a no-op. A caller may supply the moment it read earlier, with the row a person is looking at; the guard then compares against what they saw. What the guard cannot see is a change that makes no new version of the asset (a child added to it): it protects an -asset's own attributes. A guarded batch with no creates is sent -idempotent; a plain one never is. Two commands on one asset are sent in +asset's own attributes. + +**A guarded batch is not resent automatically either.** A second send +harms no data (it matches nothing), but "matched nothing" is how a +conflict reads: if the first send landed and its answer was lost, the +resend would tell the caller that someone else changed the asset and +nothing was applied, about the caller's own change. An honest "unknown" +is better than that. So no write is ever marked idempotent; a guarded +write with no confirmation is explained as an unconfirmed change +(`outcome: "unknown"`), and the caller reads the asset again and +decides. Two commands on one asset are sent in passes: the second goes only if the first applied, guarded on the Moment read just after it (the response does not say the new moment, and a shared pre-batch stamp would make the second match nothing). `batch.run` takes diff --git a/src/core/clientConfig.ts b/src/core/clientConfig.ts index 4d51222..35562ad 100644 --- a/src/core/clientConfig.ts +++ b/src/core/clientConfig.ts @@ -41,8 +41,8 @@ export interface ClientConfig extends Pick(transport: Transport const offset = sent.length; let done: assetApi.Outcome; try { - const creates = commands.some((c) => "AssetType" in bodyOf(c)); - done = assetApi.outcomeOf(await assetApi.send(transport, commands, { ...options, idempotent: !creates })); + done = assetApi.outcomeOf(await assetApi.send(transport, commands, options)); } catch (error) { // Nothing applied yet: the error is the whole story, as for a single send. if (k === 0) throw error; diff --git a/src/wire/assetApi.ts b/src/wire/assetApi.ts index 1727c85..a2594ea 100644 --- a/src/wire/assetApi.ts +++ b/src/wire/assetApi.ts @@ -294,13 +294,6 @@ export interface SendOptions extends ReadOptions { * succeeded are committed either way; the error carries the response. */ throwOnFailure?: boolean; - /** - * The caller has made this batch safe to send twice (a guarded batch with - * no creates: services/guard) and says so; the transport may then retry it - * after a network failure or a 5xx. Never set it for a plain batch: a - * retried write after a timeout is a double write. - */ - idempotent?: boolean; } /** A command's body, aliased or bare. */ @@ -339,7 +332,8 @@ export async function send(transport: Transport, comm query: options.previewOnly ? { previewOnly: "true" } : undefined, body: toWire(commands), responseType: "json", - idempotent: options.idempotent === true + // A batch is never resent, guarded or not: a second send of a guarded batch that landed reads as a conflict (services/guard). + idempotent: false }); // A preview answers with the projection, not an envelope. if (options.previewOnly) return response; diff --git a/test/integration/guard.test.ts b/test/integration/guard.test.ts index 7dfdd52..1144ea8 100644 --- a/test/integration/guard.test.ts +++ b/test/integration/guard.test.ts @@ -45,13 +45,15 @@ describeInstance("guard (live)", () => { expect(await estimate(b)).toBe("7"); }); - it("sending the same guarded batch twice applies once: the first send advances the Moment the second was stamped with", async () => { + it("sending the same guarded batch twice applies once: the first send advances the Moment the second was stamped with. The second matches nothing and reports no failure, which is how a conflict reads: why a guarded batch is never resent automatically", async () => { const first = await sendGuarded(t, [{ from: a, update: { Estimate: 8 } }]); const second = await assetApi.send(t, first.details.sent); expect(first.modified).toEqual([a]); expect(first.conflicts).toEqual([]); expect(first.requestId).toEqual(expect.any(String)); expect(second.assetsModified.count).toBe(0); + expect(second.assetsOperatedOn.count).toBe(0); + expect(second.commandFailures.count).toBe(0); expect(await estimate(a)).toBe("8"); }); diff --git a/test/unit/fetchTransport.test.ts b/test/unit/fetchTransport.test.ts index ec88dce..5968c5e 100644 --- a/test/unit/fetchTransport.test.ts +++ b/test/unit/fetchTransport.test.ts @@ -73,7 +73,7 @@ describe("createFetchTransport", () => { const writer = createFetchTransport({ baseUrl: "https://x", fetchImpl: post, retries: 2 }); await expect(writer.request({ method: "POST", path: "/api/asset", body: [] })).rejects.toMatchObject({ code: "NETWORK_ERROR" }); expect(post).toHaveBeenCalledTimes(1); - // A caller that has made its write idempotent (a guard filter) may opt in. + // A POST the caller marks idempotent (a read sent by POST, as query.v1 is) is resent. The SDK never marks a write so. const guarded = vi.fn().mockRejectedValueOnce(new TypeError("fetch failed")).mockResolvedValueOnce(json({})); await createFetchTransport({ baseUrl: "https://x", fetchImpl: guarded, retries: 1 }).request({ method: "POST", path: "/api/asset", body: [], idempotent: true }); expect(guarded).toHaveBeenCalledTimes(2); diff --git a/test/unit/guard.test.ts b/test/unit/guard.test.ts index 2b29add..3dadc99 100644 --- a/test/unit/guard.test.ts +++ b/test/unit/guard.test.ts @@ -53,7 +53,7 @@ describe("guard", () => { ]).map((u) => [u.index, u.code])).toEqual([[1, "aliasedWrite"], [2, "bareAliasFrom"], [3, "inlineCreate"]]); }); - it("sendGuarded: preview, read Moments, send guarded and marked idempotent (no creates); the result is the Outcome plus the assets whose command matched nothing", async () => { + it("sendGuarded: preview, read Moments, send guarded, never marked idempotent (a resend of one that landed would read as a conflict); the result is the Outcome plus the assets whose command matched nothing", async () => { const t = fakeTransport( PROJECTED.slice(0, 2), envelope({ queryResult: { results: [[{ _oid: "Story:146020", Moment: "196330" }, { _oid: "Story:146021", Moment: "196333" }]], resultMetaData: [], count: 2 } }), @@ -63,7 +63,7 @@ describe("guard", () => { const res = await sendGuarded(t, [{ from: "Story", filter: ["Number=$n"], with: { $n: ["S-1", "S-2"] }, update: { Estimate: 2 } }]); expect(t.calls.map((c) => c.query?.previewOnly ?? "send")).toEqual(["true", "send", "send"]); expect(t.calls[1]!.body).toEqual([{ from: "Story", select: ["Moment"], filter: ["ID=$oids"], with: { $oids: ["Story:146020", "Story:146021"] }, page: { size: 2, start: 0 } }]); - expect(t.calls[2]!.idempotent).toBe(true); + expect(t.calls[2]!.idempotent).toBe(false); expect(res.details.stamps).toEqual({ "Story:146020": "196330", "Story:146021": "196333" }); expect(res).toMatchObject({ requestId: "r", modified: ["Story:146020"], operated: [], failures: [], touched: ["Story:146020", "Story:146021"], conflicts: ["Story:146021"] }); expect(res.details.sent).toHaveLength(2); @@ -95,7 +95,7 @@ describe("guard", () => { expect(none.calls).toHaveLength(2); }); - it("a guarded batch with a create is not marked idempotent — a resend would create twice", async () => { + it("a guarded batch with a create is not marked idempotent either: a resend would create twice", async () => { const t = fakeTransport(PROJECTED, envelope({ queryResult: { results: [[{ _oid: "Story:146020", Moment: "196330" }, { _oid: "Story:146021", Moment: "196333" }]], resultMetaData: [], count: 2 } }), envelope()); await sendGuarded(t, [{ from: "Story", update: { Estimate: 2 } }]); expect(t.calls[2]!.idempotent).toBe(false); diff --git a/test/unit/retry.test.ts b/test/unit/retry.test.ts index 8f4c08a..254076f 100644 --- a/test/unit/retry.test.ts +++ b/test/unit/retry.test.ts @@ -103,16 +103,21 @@ describe("the resend rule above a custom Transport", () => { expect(off.calls).toHaveLength(1); }); - it("a plain write is never resent, whatever happened to it; a guarded one with no creates may be", async () => { + it("a write is never resent, whatever happened to it, and a guarded one is a write: its lost answer is an unknown outcome, not a second send that would read as a conflict", async () => { const write = custom(new ApiError("Bad Gateway", 502), envelope); const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: write }); await expect(client.send([{ from: "Story:1", update: { Name: "x" } }])).rejects.toMatchObject({ status: 502 }); expect(write.calls).toHaveLength(1); - // preview, the Moment read, then the guarded send: it fails once and is sent again, because a resend of it matches nothing if the first one landed. - const guarded = custom([{ "@p": { oid: "Story:1", update: { Name: "x" } } }], { ...envelope, assetsModified: { oidTokens: [], count: 0 }, queryResult: { results: [[{ _oid: "Story:1", Moment: "7" }]], resultMetaData: [], count: 1 } }, new ApiError("Bad Gateway", 502), envelope); - const result = await new AgilityApiClient({ baseUrl: "https://x" }, { transport: guarded }).sendGuarded([{ from: "Story:1", update: { Name: "x" } }]); - expect(result).toMatchObject({ modified: ["Story:1"], conflicts: [] }); - expect(guarded.calls).toHaveLength(4); + // preview, the Moment read, then the guarded send, which fails and is NOT sent again: had the first send landed, the second + // would match nothing and tell the caller that someone else changed the asset and nothing was applied. + for (const failure of [new ApiError("Bad Gateway", 502), new ApiError("fetch failed", 0, "NETWORK_ERROR")]) { + const guarded = custom([{ "@p": { oid: "Story:1", update: { Name: "x" } } }], { ...envelope, assetsModified: { oidTokens: [], count: 0 }, queryResult: { results: [[{ _oid: "Story:1", Moment: "7" }]], resultMetaData: [], count: 1 } }, failure, envelope); + const client = new AgilityApiClient({ baseUrl: "https://x", retries: 3 }, { transport: guarded }); + const error = await client.sendGuarded([{ from: "Story:1", update: { Name: "x" } }]).catch((e: unknown) => e); + expect(error).toMatchObject({ status: failure.status, request: { method: "POST", path: "/api/asset", idempotent: false } }); + expect(guarded.calls).toHaveLength(3); + expect((await client.explain(error))[0]).toMatchObject({ outcome: "unknown", retrySafe: false, sentence: "Agility did not confirm the change. It may or may not have been made: check before trying again." }); + } }); it("a 401 or 403 is never resent (re-authentication is the unauthorized hook's business), nor any other 4xx, nor an aborted request", async () => { diff --git a/test/unit/timeout.test.ts b/test/unit/timeout.test.ts index c72f3a6..eca0a65 100644 --- a/test/unit/timeout.test.ts +++ b/test/unit/timeout.test.ts @@ -134,7 +134,7 @@ describe("the built-in transport under the same rule", () => { describe("what to tell a person when a request got no answer", () => { it("a read the server itself gave up on (its SQL execution timeout) is not 'wait and try again': the same request costs the same, so ask for less; a write keeps the sentence about the change", async () => { const gaveUp = () => apiErrorFromResponse(500, { error: "Server Error", exceptions: [{ type: "SqlException", message: "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding." }, { type: "Win32Exception", message: "The wait operation timed out" }] }); - for (const request of [read, guarded]) { + for (const request of [read, posted]) { expect(await say(gaveUp, request)).toMatchObject({ audience: "user", retrySafe: false, sentence: "Agility gave up on this request: it takes more work than the server allows. Sending it again will cost the same. Ask for less: a smaller page, fewer selected paths, a tighter filter." }); } expect(await say(gaveUp, write)).toMatchObject({ retrySafe: false, sentence: "Agility did not confirm the change. It may or may not have been made: check before trying again." }); @@ -150,7 +150,8 @@ describe("what to tell a person when a request got no answer", () => { const [said] = await client.explain(error); return { stamp: (error as ApiError).request, sentence: said!.sentence, retrySafe: said!.retrySafe, outcome: said!.outcome, audience: said!.audience }; }; - const guarded: RequestOptions = { ...write, idempotent: true }; + /** A read sent by POST and marked idempotent, as query.v1 is. */ + const posted: RequestOptions = { method: "POST", path: "/query.v1", body: [], idempotent: true }; const timeout = () => new ApiError("Timed out after 60000 ms", 0, "TIMEOUT"); const dropped = () => new ApiError("fetch failed", 0, "NETWORK_ERROR"); @@ -176,8 +177,8 @@ describe("what to tell a person when a request got no answer", () => { expect((await outcome(failure, read))[0]).toBeNull(); } expect(await outcome(sqlTimeout, read)).toEqual([null, false]); - // A guarded batch is marked safe to repeat and cannot be told from a read by its error: null, and retrySafe true. - expect(await outcome(timeout, guarded)).toEqual([null, true]); + // A read sent by POST is a read. + expect(await outcome(timeout, posted)).toEqual([null, true]); // A conflict applied nothing, stamped or not; an error that does not say what was asked says nothing. const bare = new AgilityApiClient({ baseUrl: "https://agility.example.com/I" }, { transport: failing(timeout()) }); expect((await bare.explain(new ApiError("changed since it was read", 200, "CONFLICT")))[0]!.outcome).toBe("notApplied"); @@ -188,8 +189,8 @@ describe("what to tell a person when a request got no answer", () => { expect(one).toMatchObject({ index: 1, outcome: "notApplied", retrySafe: null }); }); - it("a read, or a guarded batch, that timed out is safe to repeat but may still be running; one that never got through may work in a moment", async () => { - for (const request of [read, guarded]) { + it("a read, by GET or by POST, that timed out is safe to repeat but may still be running; one that never got through may work in a moment", async () => { + for (const request of [read, posted]) { for (const failure of [timeout, () => new ApiError("Gateway Timeout", 504), () => new ApiError("Request Timeout", 408)]) { expect(await say(failure, request)).toMatchObject({ retrySafe: true, sentence: "Agility did not answer in time. The request may still be running: wait before trying again." }); } diff --git a/test/unit/transportAuth.test.ts b/test/unit/transportAuth.test.ts index 04ae618..c7d2ab7 100644 --- a/test/unit/transportAuth.test.ts +++ b/test/unit/transportAuth.test.ts @@ -51,7 +51,7 @@ describe("transport for real callers", () => { await expect(transport.request({ method: "POST", path: "/api/asset", body: [] })).rejects.toMatchObject({ status: 401 }); expect(fetchImpl).toHaveBeenCalledTimes(1); expect(onUnauthorized.mock.calls[0]![0].retryable).toBe(false); - // A guarded (idempotent) write may be resent. + // A POST marked idempotent (a read sent by POST) may be resent. const guarded = vi.fn().mockResolvedValueOnce(unauthorized()).mockResolvedValueOnce(json({})); await createFetchTransport({ baseUrl: "https://x", fetchImpl: guarded, onUnauthorized }).request({ method: "POST", path: "/api/asset", body: [], idempotent: true }); expect(guarded).toHaveBeenCalledTimes(2); From b04afa3f49739961a479446dc957ffe52ea3136b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 17:16:53 +0000 Subject: [PATCH 6/6] Say what is known about retry-write and what a guarded write means to the unauthorized hook The premise of retry-write has been checked once (a missing and an invalid session on api/asset: a 401 before any command ran); the doc comment, spec 000, example 09 and the changelog say that and its limits. The removal of SendOptions.idempotent is its own Breaking entry. The conformance suite gains a 401 with an empty body; batch.run with a guard is tested to send once when its answer is lost. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 24 +++++++++++++++++++--- examples/09-browser-session.ts | 13 +++++++----- specs/000-layers.md | 10 ++++++++-- src/core/fetchTransport.ts | 31 +++++++++++++++++++---------- src/testing/transportConformance.ts | 2 ++ test/unit/batch.test.ts | 16 ++++++++++++++- 6 files changed, 75 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 550f627..68ac20b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,12 +37,30 @@ your change or you do not, and the guard makes sending it again safe. The same holds for the unauthorized hook: `retryable` is now false for a guarded write, so "retry" does not resend it after a 401 and - "retry-write" does, as for a plain write. - `SendOptions.idempotent` is removed from `/wire`'s `assetApi.send`; - drop it from a call that set it. + "retry-write" does, as for a plain write. `retryable: false` does not + mean a guarded write cannot be resumed after signing in again; it + means "retry-write" is the answer that resumes it. +- **`SendOptions.idempotent` is removed from `/wire`'s `assetApi.send`.** + It let a caller mark a batch safe to resend; no write is resent now, + so nothing can be marked. Migration: delete the option from the call. + A caller that guarded a batch itself and relied on the resend catches + the error instead, reads the assets again and decides; sending the + same guarded batch a second time is still harmless to the data, and + an asset it does not list as modified was either changed by someone + else or by the first send. ### Changed +- **What is known about `"retry-write"`** (the unauthorized hook's + answer that resends a write, added in alpha.8 as the consumer's own + assertion that a refusal means nothing ran). The premise has now been + checked once, by a browser-app consumer, on one product release: an + api/asset create sent with no session, and one with an invalid + session, were each answered 401 with an empty body before any command + ran, and nothing was created. Not checked: a session that was valid + and has expired, a 403, rest-1. The doc comment, spec 000 and example + 09 say this in place of "cannot be verified"; beyond that case it is + still the consumer's assertion. No behaviour changes. - **`client.explain` no longer tells a person to try again after a write that got no answer.** For any `transient` error it said "Agility could not be reached, or is busy. The same request may work in a moment.", diff --git a/examples/09-browser-session.ts b/examples/09-browser-session.ts index cbb2640..8c165ce 100644 --- a/examples/09-browser-session.ts +++ b/examples/09-browser-session.ts @@ -42,11 +42,14 @@ const client = new AgilityApiClient({ // "retry" resends what is safe to send twice: a GET, a read. Never a // write, guarded or not. `retryable` says whether this request is one. if (retryable) return "retry"; - // A plain write is never resent by "retry": if it ran before the - // refusal, sending it again would apply it twice. "retry-write" resends - // it anyway, and is YOUR assertion that on your server a refusal for an - // expired session means nothing in the request was executed. Answer it - // only if you know that; otherwise answer "fail" and let the user retry. + // A write is never resent by "retry": if it ran before the refusal, + // sending it again would apply it twice. "retry-write" resends it + // anyway, and is YOUR assertion that on your server a refusal for an + // expired session means nothing in the request was executed. It has + // been seen to hold for a missing and for an invalid session on one + // release (a 401 before any command ran); not for a session that + // expired, a 403, or rest-1. Answer it only if you know it holds for + // you; otherwise answer "fail" and let the user retry. return "retry-write"; } }); diff --git a/specs/000-layers.md b/specs/000-layers.md index 04d18de..ccb8a14 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -276,8 +276,14 @@ and the caller decides. There is one way round that, and it is the consumer's assertion, not the SDK's: a hook that answers "retry-write" has the refused request sent once more, a plain write included, on its own word that on its server such a refusal means nothing in the request -was executed. The SDK cannot verify that premise (its tests run where -every request is authenticated) and never assumes it. A request sent with `reauthorize: false` skips +was executed. The premise has been checked once, by a consumer, on one +product release: an api/asset create sent with no session, and one sent +with an invalid session, were each answered 401 with an empty body before +any command ran, and nothing was created. It has not been checked for a +session that was valid and has expired, for a 403, or for rest-1, and the +SDK's own tests (which run where every request is authenticated) check +none of it. So the SDK never assumes it. A guarded write is a write here +too: `retryable` is false for it, and "retry-write" is what resumes it. A request sent with `reauthorize: false` skips the hook: it is how a hook asks whether the session is alive without waiting on itself. A caller's abort (`signal`) ends the request as `ABORTED` and is never retried. diff --git a/src/core/fetchTransport.ts b/src/core/fetchTransport.ts index fc7d6f0..48f5204 100644 --- a/src/core/fetchTransport.ts +++ b/src/core/fetchTransport.ts @@ -52,12 +52,16 @@ export interface FetchTransportConfig { * the place to re-authenticate — open a login popup, re-run setup. Resolve * "retry" to send the request once more, "fail" to throw the error. * - * "retry" is honoured only for an idempotent request (every GET; a write - * the caller marked idempotent). A plain api/asset write is never resent - * on it, even after a 401: the hook still runs, so the session can be - * repaired, and the caller decides whether to send again. "retry-write" - * resends a plain write too, once, on the hook's own assertion that the - * refusal means nothing ran (see UnauthorizedDecision). + * "retry" is honoured only for an idempotent request (every GET, and a + * read sent by POST). No api/asset write is resent on it, even after a + * 401, and that includes a guarded write (`sendGuarded`, `batch.run` + * with a guard), which the SDK no longer marks idempotent: the hook + * still runs, so the session can be repaired, and the caller decides + * whether to send again. "retry-write" resends a write too, guarded or + * plain, once, on the hook's own assertion that the refusal means + * nothing ran (see UnauthorizedDecision). So `retryable: false` on a + * guarded write does not mean it cannot be resumed after signing in + * again: it means "retry-write" is the answer that resumes it. */ onUnauthorized?: (context: UnauthorizedContext) => UnauthorizedDecision | Promise; /** Which statuses call onUnauthorized. Default [401]; a cookie-session app may add 403. */ @@ -75,9 +79,16 @@ export interface FetchTransportConfig { * `unauthorizedStatuses` means nothing in the request was * executed — the sign-in was checked before any command * ran — so sending it again cannot apply anything twice. - * The SDK cannot know that and does not check it: its own - * tests run where every request is authenticated. Answer - * it only where that holds (a session that expired; not a + * What is known: on one product release, an api/asset + * create sent with no session and one sent with an + * invalid session were each answered 401 with an empty + * body before any command ran, and nothing was created + * (a consumer's check, by an exact-name query afterwards). + * What is not: a session that was valid and has expired, + * a 403, and rest-1. The SDK's own tests run where every + * request is authenticated and check none of it, so + * beyond that case it remains your assertion. Answer it + * only where it holds (a missing or lapsed sign-in; not a * permission problem, which api/asset reports per command * inside a 200). Honoured once per request, like "retry". */ @@ -86,7 +97,7 @@ export type UnauthorizedDecision = "retry" | "retry-write" | "fail"; export interface UnauthorizedContext { error: ApiError; request: RequestOptions; - /** Whether a "retry" will be honoured: false for a non-idempotent write (which only "retry-write" resends). */ + /** Whether a "retry" will be honoured: false for any write, guarded or plain (which only "retry-write" resends). */ retryable: boolean; } diff --git a/src/testing/transportConformance.ts b/src/testing/transportConformance.ts index bcf6da3..01d8891 100644 --- a/src/testing/transportConformance.ts +++ b/src/testing/transportConformance.ts @@ -158,6 +158,8 @@ export function transportConformance(make: (server: ConformanceServer) => Transp // A server-side SQL execution timeout, as an instance answers it: told by its body, coded SERVER_TIMEOUT. [500, { error: "Server Error", exceptions: [{ type: "SqlException", message: "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding." }, { type: "Win32Exception", message: "The wait operation timed out" }] }], [401, "Unauthorized"], + // As api/asset refuses a request with no session: a 401 with nothing in the body. The status alone makes it kind "auth". + [401, ""], [503, ""] ]; for (const [status, data] of bodies) { diff --git a/test/unit/batch.test.ts b/test/unit/batch.test.ts index 37e3327..b1a21eb 100644 --- a/test/unit/batch.test.ts +++ b/test/unit/batch.test.ts @@ -2,7 +2,8 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import { describe as group, expect, it, vi } from "vitest"; import type { RequestOptions, Transport } from "../../src/core/transport"; -import { UsageError } from "../../src/core/errors"; +import { AgilityApiClient } from "../../src/client"; +import { ApiError, UsageError } from "../../src/core/errors"; import { BatchRecordError, BatchSendError, ReceiptVersionError, describe, isReceipt, reverseOf, reversible, runBatch, type Receipt } from "../../src/services/batch"; import { UnguardableError } from "../../src/services/guard"; import { Schema } from "../../src/services/schema"; @@ -104,6 +105,19 @@ group("batch", () => { expect(r.notes.slice(1)).toEqual(["Epic:9: Split has no known inverse (was Active)"]); }); + it("a guarded batch whose send got no answer is sent once and its outcome is unknown: a second send of one that landed would read as a conflict", async () => { + for (const failure of [new ApiError("fetch failed", 0, "NETWORK_ERROR"), new ApiError("Bad Gateway", 502)]) { + let sends = 0; + const t = server({ preview: [PREVIEW[1]!], lookup, send: () => { sends += 1; throw failure; } }); + const client = new AgilityApiClient({ baseUrl: "https://x", retries: 3 }, { transport: t, types: schema.cache }); + const error = await client.batch.run([{ from: "Story:1", update: { Estimate: 5 } }], { guard: true }).catch((e: unknown) => e); + expect(sends).toBe(1); + expect(t.calls.at(-1)).toMatchObject({ path: "/api/asset", idempotent: false }); + const [said] = await client.explain((error as { details?: { cause?: unknown } }).details?.cause ?? error); + expect(said).toMatchObject({ outcome: "unknown", retrySafe: false, sentence: "Agility did not confirm the change. It may or may not have been made: check before trying again." }); + } + }); + it("an asset whose command failed is failed, not also a conflict (a CLI consumer finding)", async () => { const preview = [{ "@x": { oid: "Conversation:12", execute: { op: "Delete", args: {} } } }, { "@y": { oid: "Epic:9", execute: { op: "Inactivate", args: {} } } }] as unknown as Command[]; const t = server({