Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/35027-action-timeout-sentence.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/runtime': patch
---

fix(runtime): an action body that runs out of time answers a sentence naming the action and its limit, at the same `500 INTERNAL_ERROR`

Clause-②: no
Metadata-protocol: none

An action body that hit its time limit answered `500 INTERNAL_ERROR "Internal server error"` on the `/actions` door and MCP `run_action`, naming neither the action nor the limit, so a caller (an AI agent above all) could not tell a slow action from a broken platform. It now answers the same status and code with the sentence `Action 'NAME' timed out: it exceeded its N ms time limit and was stopped.`, where `N` is the CPU-time budget the body ran under (its `body.timeoutMs`, the enclosing timeout, or the `OS_SANDBOX_ACTION_TIMEOUT_MS` default). A body stuck waiting on platform calls past the wall-clock ceiling answers `Action 'NAME' timed out: it exceeded its N ms time limit while waiting on platform calls, and was stopped.` Both doors read one reader, so they answer the same sentence. The server log line is unchanged (`action 'NAME' exceeded CPU budget of Nms (after P pump iterations)`).

The same holds for an action that declares `refusals`. A timeout, like a body that does not compile, is the platform's own fault, so the action's refusal catalogue passes it through unchanged: the caller gets the sentence and the log keeps the runner's own line. Before, the catalogue read a compile failure on such an action as the body's code-less throw, answered the bare `500 "Internal server error"`, and logged "threw no code, and its refusals declares no such code". A body's own throw without a code is still refused that way.

Nothing else moves. A body that crashes (a `TypeError`, say) still answers the sanitised `500 "Internal server error"`, because its own text may carry the data it was reading. A hook's or a job's timeout is unchanged: it carries no caller sentence, and the `/data` door and import rows answer it as before. The action's sentence is declared at `500`, so the `/data` door, which relays a sandbox sentence only below the server band, never serves it as business text.
3 changes: 2 additions & 1 deletion content/docs/api/error-catalog.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -708,7 +708,8 @@ value directly (single wrap).
| Caller lacks `requiredPermissions` | **403** | `{ success: false, error: { message, code } }` |
| Type has no server dispatch (`url`/`modal`/`form`/`api`), or a param-contract violation | **400** | `{ success: false, error: { message, code } }` |
| Data engine or automation service unavailable | **503** | `{ success: false, error: { message, code } }` |
| Handler **crashed** (`TypeError`, driver error, sandbox timeout) | **500** | `{ success: false, error: { message, code } }` |
| Handler **crashed** (`TypeError`, driver error) | **500** | `{ success: false, error: { message, code } }` |
| Sandboxed body **timed out** (its CPU-time limit, or the wall-clock ceiling while waiting on platform calls) | **500** | `{ success: false, error: { message, code: 'INTERNAL_ERROR' } }` — `message` names the action and its limit: `Action 'NAME' timed out: it exceeded its N ms time limit and was stopped.` (the ceiling's adds `while waiting on platform calls`). MCP `run_action` answers the same sentence. A crash's own text is never served; a hook's or a job's timeout keeps `Internal server error` |
| Sandboxed body **does not compile** in its `(async (input, ctx) => { … })` wrapper | **500** | `{ success: false, error: { message, code: 'INTERNAL_ERROR' } }` — `message` names the action and the compile error |

A rejection and a crash are told apart by the thrown error: a plain
Expand Down
7 changes: 4 additions & 3 deletions content/docs/ui/actions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -699,9 +699,10 @@ Failures speak HTTP — the status code is the signal (#3962):
- **404 / 403 / 503** — it never dispatched: no such action, denied, service
unavailable. A `url`/`modal`/`form` type, or an `api` type whose `target`
is on another origin, has no server dispatch and is also a 400.
- **500** — it **crashed**: a `TypeError` in your handler, a driver error, a
sandbox timeout. A deliberate `throw new Error('…')` is a 400 rejection,
not a crash.
- **500** — it **crashed** (a `TypeError` in your handler, a driver error) or
**timed out**; a timeout's message names the action and its limit, while a
crash answers only `Internal server error`. A deliberate
`throw new Error('…')` is a 400 rejection, not a crash.

Full table in the [error catalog](/docs/api/error-catalog). The
[client SDK](/docs/api/client-sdk) folds all of it into one
Expand Down
22 changes: 22 additions & 0 deletions packages/mcp/src/mcp-coded-refusal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -990,6 +990,28 @@ describe('run_action / resume_run: a throw answers what the /actions door answer
expect([door.code, door.declaredCode, door.status]).toEqual([error.code, error.declaredCode, error.status]);
});

it(`${site.tool}: an action body that timed out answers the door's 500 INTERNAL_ERROR with the sentence naming the action and its limit`, async () => {
const log = vi.spyOn(console, 'error').mockImplementation(() => {});
// The shape `QuickJSScriptRunner` raises for an action that ran out of
// time (`@objectstack/runtime`'s `sandboxed-action-crash-is-a-fault.test.ts`
// measures it on a real run and on the HTTP door): the operator line in
// `.message`, the caller sentence in `innerMessage`, a declared 500, no code.
const sentence = "Action 'demo_leave_body' timed out: it exceeded its 50 ms time limit and was stopped.";
const thrown = () => Object.assign(
new Error("action 'demo_leave_body' exceeded CPU budget of 50ms (after 3 pump iterations)"),
{ name: 'SandboxError', innerMessage: sentence, status: 500 },
);
const result = await callTool(site, thrown());
expect(result.isError).toBe(true);
const { error } = JSON.parse(String(result.content[0].text));
expect(error).toEqual({ code: 'INTERNAL_ERROR', message: sentence, status: 500 });
const door = actionsDoorAnswerOf(thrown());
expect(error).toEqual({ code: door.code, message: door.message, status: door.status });
// The operator line reaches the log, and never the tool result.
expect(log).toHaveBeenCalledTimes(1);
expect(String(result.content[0].text)).not.toContain('pump iterations');
});

it(`${site.tool}: a fault carries no thrown details; a refusal still does`, async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
const details = { host: 'db-primary.internal', pool: 'writer' };
Expand Down
3 changes: 2 additions & 1 deletion packages/runtime/src/domains/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
* Success is now a SINGLE wrap (`data` = the handler's return value), a
* deliberate rejection (body `throw`, flow rejection, ValidationError) is a
* 400 carrying `code`/`fields` in `details`, and a crash (`TypeError`, driver
* class, sandbox timeout — told apart by the error's NAME, #3951) is a 500.
* class — told apart by the error's NAME, #3951) is a 500. A sandbox timeout
* is a 500 too, but not a crash: its message names the action and its limit.
*
* did a handler run? no → 404 / 403 / 400 / 503
* did it reject or crash? reject → 400; crash → 500
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco
import { HttpDispatcher } from './http-dispatcher.js';
import { actionBodyRunnerFactory } from './sandbox/body-runner.js';
import { QuickJSScriptRunner } from './sandbox/quickjs-runner.js';
// Paid during collection, never inside a case's clocked window: the door's
// reach loads this package lazily (`check:test-source-alias`).
import '@objectstack/metadata';

const PREFIX = '/api/v1';
/** `registry.registerObject` requires a package id (see the sibling real-stack tests). */
Expand Down Expand Up @@ -158,5 +161,9 @@ describe('[#23723] CONTROL — the door\'s other answers stand', () => {
const response = await postAction('never_settles');
expect(response.status, JSON.stringify(response.body)).toBe(500);
expect(response.body?.error?.code).toBe('INTERNAL_ERROR');
// The timeout names the action and its limit, never a refusal.
expect(response.body?.error?.message).toBe(
`Action 'never_settles' timed out: it exceeded its ${CEILING_MS} ms time limit while waiting on platform calls, and was stopped.`,
);
});
});
105 changes: 102 additions & 3 deletions packages/runtime/src/sandbox/action-refusal-catalogue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { describe, it, expect, vi } from 'vitest';
// Paid at collection, not inside a case's clocked window: the dispatcher's
// reach loads `@objectstack/metadata` lazily (`check:test-source-alias`).
import '@objectstack/metadata';
import { mapDataError } from '@objectstack/types';
import { actionsDoorAnswerOf, mapDataError } from '@objectstack/types';

import { actionBodyRunnerFactory } from './body-runner.js';
import { QuickJSScriptRunner, SandboxError } from './quickjs-runner.js';
Expand Down Expand Up @@ -52,13 +52,21 @@ const ZH_GLOBAL = '(全局)只有草稿发票可以签核。';
/** A `script` action with a `js` body and the catalogue, bound through the real factory. */
function boundAction(
source: string,
opts: { refusals?: object; objectName?: string | null; i18n?: () => HookRefusalI18nService | undefined } = {},
opts: {
refusals?: object;
objectName?: string | null;
i18n?: () => HookRefusalI18nService | undefined;
runner?: QuickJSScriptRunner;
logger?: Record<string, (...args: any[]) => void>;
timeoutMs?: number;
} = {},
) {
const objectName = opts.objectName === undefined ? 'crm_invoice' : opts.objectName ?? undefined;
const fn = actionBodyRunnerFactory(runner, { ql: {}, appId: 'crm', i18n: opts.i18n })({
const fn = actionBodyRunnerFactory(opts.runner ?? runner, { ql: {}, appId: 'crm', i18n: opts.i18n, logger: opts.logger as any })({
name: 'submit_signoff',
type: 'script',
...(objectName !== undefined ? { objectName, object: objectName } : {}),
...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),
body: { language: 'js', source, capabilities: [] },
refusals: 'refusals' in opts ? opts.refusals : REFUSALS,
} as any);
Expand Down Expand Up @@ -271,3 +279,94 @@ describe('[#34273] the `/actions` door answers the declared refusal in the calle
expect(response.body.error.userMessage).toBeUndefined();
});
});

/**
* The runner's own faults are the platform speaking, never a refusal the body
* chose, so an action that declares `refusals` answers them exactly as an
* action without one does. A timeout keeps the sentence naming the action and
* its limit, a body that does not compile keeps the sentence naming the
* compiler's reason, and the operator log keeps the runner's own line, never
* the catalogue's "threw no code" fault.
*
* Driven through the real bound handler (`actionBodyRunnerFactory`), which
* hands every throw to `resolveActionRefusal` before it logs and rethrows it,
* and read on both action doors: the `/actions` HTTP door and the reader the
* MCP `run_action` tool renders a throw with (`actionsDoorAnswerOf`).
*/
describe('the runner\'s own faults pass an action\'s refusal catalogue untouched', () => {
const CPU_SENTENCE = "Action 'submit_signoff' timed out: it exceeded its 50 ms time limit and was stopped.";
const WALL_SENTENCE =
"Action 'submit_signoff' timed out: it exceeded its 300 ms time limit while waiting on platform calls, and was stopped.";
const COMPILE_BODY = 'const input = ctx.input || {}; return 1;';

/**
* Records the `.message` of each error logged at `error`, read when it is
* logged: the door later rewrites `.message` to the caller sentence.
*/
function capturingLogger() {
const logged: string[] = [];
const error = vi.fn((_line: string, err: { message: string }) => { logged.push(err.message); });
return { error, logged, logger: { error, info: vi.fn(), warn: vi.fn(), debug: vi.fn() } };
}

/** Both doors' answers to one thrown error, as `{ status, code, message }`. */
async function bothDoors(err: unknown) {
const response = await throughActionsDoor(err);
const mcp = actionsDoorAnswerOf(err, 'crm_invoice');
return {
actions: { status: response.status, code: response.body.error.code, message: response.body.error.message },
mcp: { status: mcp.status, code: mcp.code, message: mcp.message },
};
}

it('a CPU timeout answers its sentence on both doors, and the log keeps the budget line', async () => {
const { error, logged, logger } = capturingLogger();
const err = await rejectionOf(boundAction('while (true) {}', { logger, timeoutMs: 50 })(actionCtx()));
expect(err).toBeInstanceOf(SandboxError);
const expected = { status: 500, code: 'INTERNAL_ERROR', message: CPU_SENTENCE };
expect(await bothDoors(err)).toEqual({ actions: expected, mcp: expected });

expect(error).toHaveBeenCalledTimes(1);
expect(error.mock.calls[0][1]).toBe(err);
expect(logged[0]).toMatch(/^action 'submit_signoff' exceeded CPU budget of 50ms/);
});

it('a wall-clock timeout answers its sentence on both doors, and the log keeps the ceiling line', async () => {
const { logged, logger } = capturingLogger();
const wallRunner = new QuickJSScriptRunner({ actionTimeoutMs: 250, wallCeilingMs: 300 });
const err = await rejectionOf(
boundAction('await new Promise(() => {});', { logger, runner: wallRunner })(actionCtx()),
);
const expected = { status: 500, code: 'INTERNAL_ERROR', message: WALL_SENTENCE };
expect(await bothDoors(err)).toEqual({ actions: expected, mcp: expected });
expect(logged).toHaveLength(1);
expect(logged[0]).toMatch(/^action 'submit_signoff' exceeded wall-clock ceiling of 300ms/);
});

it('a body that does not compile answers its sentence on both doors, and the log names the compiler', async () => {
const { logged, logger } = capturingLogger();
const err = await rejectionOf(boundAction(COMPILE_BODY, { logger })(actionCtx()));
const answers = await bothDoors(err);
expect(answers.mcp).toEqual(answers.actions);
expect(answers.actions.status).toBe(500);
expect(answers.actions.code).toBe('INTERNAL_ERROR');
expect(answers.actions.message).toContain("Action 'submit_signoff' cannot run: its body does not compile");
expect(logged).toHaveLength(1);
expect(logged[0]).toMatch(/^action 'submit_signoff' does not compile: SyntaxError/);
});

it('CONTROL: a body\'s own code-less throw is still refused as undeclared, a declared 500 and the timeout\'s own words included', async () => {
for (const source of [
"throw new Error('no code');",
"throw Object.assign(new Error('The server is busy.'), { status: 500 });",
`throw Object.assign(new Error(${JSON.stringify(CPU_SENTENCE)}), { status: 500 });`,
]) {
const err = await rejectionOf(boundAction(source)(actionCtx()));
expect(err.message, source).toContain('threw no `code`');
expect(err.innerMessage, source).toBeUndefined();
const answers = await bothDoors(err);
expect(answers.actions, source).toEqual({ status: 500, code: 'INTERNAL_ERROR', message: 'Internal server error' });
expect(answers.mcp, source).toEqual(answers.actions);
}
});
});
14 changes: 11 additions & 3 deletions packages/runtime/src/sandbox/hook-refusal-catalogue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@
* refusal of a `ctx.api` write, a nested hook's refusal), the engine's own
* error the runner relays as itself, a crash (`TypeError: …`) and the
* sandbox's own faults (budget, capability) all pass through as before: they
* are the platform speaking, or a bug, never a refusal the body chose.
* are the platform speaking, or a bug, never a refusal the body chose. An
* action's timeout and an action body that does not compile carry a caller
* sentence, so they pass by identity ({@link isRunnerOwnFault}), not by the
* missing `innerMessage` the other faults pass on.
*
* **Reasons and params (#33214, ruling 6879477573: S1 and params).** A code
* may hold further declared sentences under `reasons`; a throw that names a
Expand Down Expand Up @@ -82,6 +85,7 @@ import {
SandboxError,
isHostRelayedSandboxError,
isRelayedSandboxRefusal,
isRunnerOwnFault,
sandboxRefusalAddressOf,
type SandboxRefusalAddress,
} from './quickjs-runner.js';
Expand Down Expand Up @@ -453,8 +457,12 @@ function resolveSandboxedRefusal(
locale: unknown,
opts: { i18n?: HookRefusalI18nSource; logger?: { warn?: (...args: any[]) => void } },
): unknown {
// Not the body's own throw: the engine's error relayed as itself, the
// sandbox's own fault, a host error re-thrown unchanged, a nested refusal.
// Not the body's own throw: the runner's own fault that carries a caller
// sentence (an action's timeout, an action body that does not compile; by
// identity, before any field is read, since a body can throw the same
// fields), the engine's error relayed as itself, the sandbox's own fault, a
// host error re-thrown unchanged, a nested refusal.
if (isRunnerOwnFault(err)) return err;
if (!(err instanceof SandboxError) || err.innerMessage === undefined) return err;
if (isHostRelayedSandboxError(err) || isRelayedSandboxRefusal(err)) return err;
// A crash (`TypeError: …`) is a bug, not a refusal: it stays the fault it is.
Expand Down
Loading
Loading