Skip to content

Commit 961f474

Browse files
fix(runtime): an action body that runs out of time answers a sentence naming the action and its limit (#35093)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBLW6dHPW6sSheA32XPKZzPV)_ repo:objectstack#3 · os-support-ai · session_01WGufziunkXbDT7wUWqfmWz Fixes #35027 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:动作脚本超时(CPU 时限,或等待平台调用超过墙钟上限)时,REST `/actions` 与 MCP `run_action` 仍回答 `500 INTERNAL_ERROR`,但消息从光秃秃的 "Internal server error" 变成点名动作和时限的一句话,例如 `Action 'X' timed out: it exceeded its 50 ms time limit and was stopped.` - 为什么改:按裁决 C(「35027 C」,记录 6965765884)。调用方(尤其 MCP 里的 AI)以前分不清"这个动作慢"和"平台坏了"。状态码与错误码不变,只换句子;句子只含动作名和毫秒数,不含任何数据。 - 风险与回滚:只动 `budgetError` 的动作分支;钩子、定时任务的超时完全不变(无 `innerMessage`、无 `status`),崩溃仍是消毒后的 500。句子声明为 500,所以 `/data` 门不会把它当业务原文转出。第 3 轮修了合同审查的 F1:声明了 `refusals` 的动作以前会把这句话(以及编译失败那句)当成"没带 code 的抛出"改写成裸 500,日志也记错原因;现在运行器按身份标记自己的故障,拒绝目录直接放行。动作自己抛的无 code 错误(哪怕带 500、哪怕抄了超时原文)仍按未声明拒绝。回滚即 revert。 - 先看:`packages/runtime/src/sandbox/hook-refusal-catalogue.ts`(`resolveSandboxedRefusal` 第一行的 `isRunnerOwnFault` 放行);`packages/runtime/src/sandbox/quickjs-runner.ts`(`budgetError` 的两个 `action` 分支、`actionTimeoutSentence` 与 `runnerOwnFaults`);`packages/runtime/src/sandbox/action-refusal-catalogue.test.ts`(末尾新 describe 的四个钉子)。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run src/sandbox/sandboxed-action-crash-is-a-fault.test.ts src/sandbox/action-refusal-catalogue.test.ts`,预期 31 条全过,其中声明了 `refusals` 的动作超时,在 HTTP 门与 MCP 读取器上同样给出那句话,日志保留 CPU 时限那一行。 - 需要你做的:无,席位落地。 ## What changes - **`@objectstack/runtime`, `quickjs-runner.ts`.** `budgetError` gains an `action` arm on each of its two limits. For an action, the `SandboxError` keeps its operator line in `.message` (`action 'NAME' exceeded CPU budget of Nms (after P pump iterations)`, unchanged), and now carries `innerMessage` = `actionTimeoutSentence(...)` and a declared `status: 500`, with no `code`. This is the shape of the compile-failure precedent (`actionBodyCompileFailure`, merged in 743308b). The two sentences: - CPU budget: `Action 'NAME' timed out: it exceeded its N ms time limit and was stopped.` - Wall-clock ceiling: `Action 'NAME' timed out: it exceeded its N ms time limit while waiting on platform calls, and was stopped.` - **What answers it.** `actionsDoorAnswerOf` (`@objectstack/types`, not edited) reads the sentence through `sandboxBusinessMessage`. Arm 2 (crash) does not take it, because the sentence is not native-error-named. Arm 3 serves the declared status, with the status's own `INTERNAL_ERROR` and the sentence (`looksLikeInternalErrorLeak` reads false). The HTTP door (`HttpDispatcher.handleActions`) and MCP `run_action` / `resume_run` (`errorResultFromThrown`) both render that one reader, so they give the same sentence. - **Ruling conditions, as measured:** 1. Only a timeout gains a sentence. Status and code stay `500` / `INTERNAL_ERROR`. A crash keeps `Internal server error`: the crash path is untouched, and a pin holds it on both doors. 2. Actions only. Hook and job timeouts keep the 1-argument `SandboxError` with no `innerMessage` and no `status`. On `/data`, `mapDataError` relays a sandbox `innerMessage` only below the server band, so the declared `500` keeps the action sentence off that door too. A pin measures this. `sandbox-business-message.ts` needed no edit. 3. Both doors give the same sentence, and `content/docs/api/error-catalog.mdx` gains a "Sandboxed body timed out" row under Action Errors. "sandbox timeout" moves out of the crash row. - **Core sandbox-fault census** (`packages/core/src/utils/import-runner-sandbox-fault-row.test.ts`, not edited). Each new construction keeps a literal template as its message, using interpolations the census already samples (`args.origin.name`, `cpuBudget`, `wallCeiling`, `pumps`). The census picks the new sites up (`quickjs-runner.ts:250` and `:262` in its §2) with no new sample, and still finds the hook/job fault sites its `CPU budget` / `wall-clock ceiling` floors need. 48/48 green. - **Tests.** Two existing pins asserted the old action-timeout shape, so they now assert the sentence. `unreadable-rejection-recorded.test.ts`: the never-settles control expected `innerMessage` undefined. `sandbox-unreadable-rejection-door.test.ts`: a real-stack `/actions` door case now also asserts the message. That file also gains the module-top `import '@objectstack/metadata'` that `check:test-source-alias` asks of an edited door test. - **Docs made consistent (round 2, L1 S1 / N1).** `content/docs/ui/actions.mdx`: the 500 bullet now reads "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`", matching the catalog row. The header comment of `packages/runtime/src/domains/actions.ts` no longer lists a sandbox timeout under crash. - **Fix round 3 (contract review 6972256765, F1).** An action that declares `refusals` lost the timeout sentence: `boundActionHandler` hands every throw to `resolveActionRefusal`, and the catalogue read the sentence as the body's code-less throw, replaced it with the undeclared-refusal fault, answered the bare 500 on both doors and logged "threw no code" instead of the budget line. Measured before the fix on this branch's head `ddee9584b9`, through the real bound handler: both doors answered `Internal server error`. The compile-failure fault (`actionBodyCompileFailure`) had the same route, and the same mark covers it with no extra path. - `quickjs-runner.ts`: a module-level `runnerOwnFaults` WeakSet beside `hostRelayedErrors`. The runner marks the faults it makes itself that carry a caller sentence: the action arms of `budgetError` (CPU budget, wall-clock ceiling) and `actionBodyCompileFailure`. `isRunnerOwnFault` reads the mark. Identity, not a field: a body can throw `innerMessage` + `status: 500` + no code itself, so no field tells the two apart. The runner's other faults carry no `innerMessage` and pass as before. - `hook-refusal-catalogue.ts`: `resolveSandboxedRefusal` passes a runner-own fault through before it reads any field. There is no pass-through on a declared server-band status: a body's own code-less throw with `status: 500`, even one spelled with the timeout's exact words, is still refused as undeclared. The module header says so. - `action-refusal-catalogue.test.ts` (the action-catalogue harness): a new top-level describe, through the real `actionBodyRunnerFactory` and read on the `/actions` door and `actionsDoorAnswerOf` (the reader MCP `run_action` renders). A CPU timeout and a wall-clock timeout each answer `500 INTERNAL_ERROR` with the sentence on both doors, and the error logged at `error` still carries the runner's operator line, read at log time. A compile failure answers its sentence on both doors, and the log names the compiler. A control holds three code-less body throws (plain, `status: 500`, and `status: 500` with the timeout's own sentence) to the undeclared refusal and the bare 500 on both doors. - **Changeset:** `@objectstack/runtime` patch. Round 3 adds one paragraph: the same holds for an action that declares `refusals`. ## Tests <details><summary>Round 3 (head 48170d2): F1 red then green, ablation, package suite</summary> - **Red before the fix.** The new describe, run against the unfixed runner and catalogue (`ddee9584b9` plus the test only): `Tests 3 failed | 17 passed (20)`. CPU timeout, received on both doors `"message": "Internal server error"` where the sentence was expected. Wall-clock timeout, the same. Compile failure: `expected 'Internal server error' to contain 'Action 'submit_signoff' cannot run:…'`. The control (code-less body throws stay refused) was green. - **Green after the fix** (331f618): `action-refusal-catalogue`, `sandboxed-action-crash-is-a-fault`, `hook-refusal-catalogue`, `unreadable-rejection-recorded`, `sandbox-unreadable-rejection-door`, `quickjs-runner`: `Test Files 6 passed (6)`, `Tests 145 passed (145)`. - **Ablation** through `scripts/ablation-replace.mjs`: in `hook-refusal-catalogue.ts`, replaced the line `if (isRunnerOwnFault(err)) return err;` with a comment. `ok mutation landed: anchor 1 -> 0, blob 1d140e6 -> 7bd11f4783b5`. The suite imports the catalogue from `src/` by relative path, so no dist rebuild was needed. Result: `Tests 3 failed | 17 passed (20)`; red: the CPU-timeout, wall-clock-timeout and compile-failure pins; the control stayed green. Restore: `ok restored: blob == HEAD (1d140e6) and git diff HEAD is empty`. - `pnpm --filter @objectstack/runtime test` (`--project local`): `Test Files 619 passed (619)`, `Tests 11500 passed | 23 skipped (11523)`, exit 0. The run was on the fix's code. The commit after it changes only the changeset. - `pnpm --filter @objectstack/runtime typecheck`: exit 0, `check:test-typecheck: OK`. - Core census `import-runner-sandbox-fault-row.test.ts` (`repo` project, run locally because it parses the edited runner): `Tests 48 passed (48)`. </details> <details><summary>Targeted files, package suites, typecheck (head d50f969 for the re-runs after the last edit)</summary> - `pnpm exec vitest run` (runtime) on `sandboxed-action-crash-is-a-fault`, `unreadable-rejection-recorded`, `sandbox-unreadable-rejection-door` and `quickjs-runner`: `Test Files 4 passed (4)`, `Tests 87 passed (87)`. - Re-run after the import fix (d50f969), `sandbox-unreadable-rejection-door` and `sandboxed-action-crash-is-a-fault`: `Test Files 2 passed (2)`, `Tests 16 passed (16)`. - `pnpm --filter @objectstack/runtime test` (`--project local`): `Test Files 618 passed (618)`, `Tests 11470 passed | 23 skipped (11493)`, exit 0. This ran on 1a88607. The only change since then is a module-top side-effect import in one test file, and that file was re-run above. - `pnpm --filter @objectstack/mcp test`: `Test Files 71 passed (71)`, `Tests 1260 passed (1260)`, exit 0. - `mcp-coded-refusal.test.ts`: 180/180. `import-runner-sandbox-fault-row.test.ts` (core census, `repo` project, run locally because it parses the edited runner): 48/48. - `pnpm --filter @objectstack/runtime typecheck`: exit 0 (`check:test-typecheck: OK`). The first run was red on two untouched files, `TS2307 Cannot find module '@objectstack/driver-turso'`, because that dist had not been built. It went green once the dist was built. `@objectstack/mcp typecheck`: `tsc --noEmit` and `check:test-typecheck: OK`. </details> <details><summary>Ablations: three pins, each mutated once through scripts/ablation-replace.mjs, restored to blob == HEAD</summary> The mutations are all in `quickjs-runner.ts`, which the suite imports from `src/` by relative path, so no dist rebuild was needed. `ablation-replace` reported each mutation as landed (anchor 1 -> 0). After each leg, the restore showed `git hash-object` = HEAD blob `bd7078824818` and `git diff HEAD` empty. - **(a) The timeout sentence, the same on both doors.** Replaced `actionTimeoutSentence(args.origin.name, cpuBudget, false),` with `undefined,`. Result: `Tests 2 failed | 9 passed (11)`. Red: "the runner keeps its operator line, and declares 500 with the sentence and no code" and "the /actions door and the MCP run_action reader answer 500 INTERNAL_ERROR with the same sentence". - **(b) A crash still sanitised.** Prefixed the crash relay's `innerMessage` with `'Action failed internally: '`, so it no longer reads as a native error. Result: `Tests 5 failed | 6 passed (11)`. Red: the new "control: a crash beside it keeps the sanitised 500 on both doors", plus the existing crash, runtime-SyntaxError and negative-control pins. - **(c) A hook timeout unchanged on /data.** Widened the CPU arm's `args.origin.kind === 'action'` to `!== 'job'`, which pulls hooks into the action arm. Result: `Tests 1 failed | 10 passed (11)`. Red: "control: a hook timeout is unchanged, and the /data door answers it the sanitised fault". </details> ## Acceptance notes - `Clause-②: no` and `Metadata-protocol: none` hold after round 3: the fix restores the ruled answer on a path the round-1 pins did not reach, and refuses nothing it accepted before. - Round 2 fixed `content/docs/ui/actions.mdx` (the 500 bullet) and the `domains/actions.ts` header comment, after the claim amendment added both to the surface. - The MCP pin (`mcp-coded-refusal.test.ts`) drives `run_action` / `resume_run` with the runner's measured timeout shape. `@objectstack/mcp` does not depend on `@objectstack/runtime`, so the real-run half lives in the runtime file. That file feeds the same real error to the HTTP door and to `actionsDoorAnswerOf`, the reader the MCP tools render. ## Verification <details><summary>Gates, round 3 (head 48170d2)</summary> - `dispatch-gates --commands` derived 100 commands. All 100 were run, and each exited 0 (exit codes captured per command before any pipe). On the first pass `check:skill-examples` and `check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET, dists missing). After a whole-workspace build (`turbo run build`, 120/120 tasks) both exited 0. The changeset gates and the text gates that read `.changeset/` were re-run on 48170d2, the changeset commit. - `--ran` reconciliation: `100 derived, 100 run, 0 NOT-MEASURED, 0 UNRUN`. - The derivation warned that the tree is behind origin/main, and that one gate file changed on main across that range: `scripts/check-skill-identifier-liveness.mjs`. Its family ran from this branch's copy and exited 0. Main was not merged: the branch has no conflict and main does not make it red. - `overlap-check` before each push: `VERDICT clean exit 0` against origin/main `f7960893cd` and `99a0e4fbfc`, with no open PR head overlapping. </details> <details><summary>Gates, round 2 (head 8010091)</summary> - `dispatch-gates --commands` on 8010091 derived 98 commands (round 1's 96, plus `check:adr-symbol-anchors` and `check:route-envelope`). I ran 97 of them on 8010091, and each exited 0. - NOT MEASURED: `pnpm check:dual-build-cjs-loads`. It exited 3 with PREREQUISITE NOT MET, because it reads built output and this fresh worktree has no dist for `@objectstack/account`, `@objectstack/setup`, `@objectstack/studio`, `@objectstack/cloud-connection` and 30-odd more. A whole-tree build was not started, because the maintainer's hand-off order said to start no new long steps. CI's Lint lane runs it. On d50f969 it passed (124 entries / 72 packages). - `--ran` reconciliation over the 97 measured commands: `98 derived, 97 run, 0 NOT-MEASURED, 1 UNRUN`. The UNRUN entry is `check:dual-build-cjs-loads`, above. - Re-run on 8010091 (diff since d50f969: docs bullet + one code comment): runtime pins `sandboxed-action-crash-is-a-fault`, `unreadable-rejection-recorded`, `sandbox-unreadable-rejection-door` and `quickjs-runner`: 4/4 files, 87/87 tests. `mcp-coded-refusal`: 180/180. Core census: 48/48. The package suites and typecheck were not re-run; the round-1 readings on d50f969 stand for unchanged code. - `overlap-check` before the push: `VERDICT clean exit 0` against origin/main 154cb72, and against #35085, which shares `content/docs/ui/actions.mdx` and `quickjs-runner.ts` and merges cleanly. </details> <details><summary>Gates, round 1 (head d50f969)</summary> - `node scripts/pm/dispatch-gates.mjs --commands`: 96 derived commands. All 96 were run on d50f969 and every one exited 0 (exit codes captured per command before any pipe). `--ran` reconciliation: `96 derived famil(ies) accounted for — 96 run, 0 NOT-MEASURED`. - On the earlier pass, three gates refused or failed: `check:skill-examples` (exit 3, client-react dist missing), `check:dual-build-cjs-loads` (exit 3, dists missing) and `check:test-source-alias` (exit 1, the door test's missing module-top import, now fixed). All three exit 0 on the final pass. - `node scripts/pm/overlap-check.mjs` before each push: `VERDICT clean exit 0` (origin/main 301b7c1; #35085 shares `quickjs-runner.ts` and merges cleanly). - NOT MEASURED, CI-owned: the families `dispatch-gates` lists as CI-measured-only or workflow-valued, the type-check lanes, and the path-scheduled CI jobs. The full dogfood is not owed (no `!`, no `(narrowing)` arm). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufziunkXbDT7wUWqfmWz)_ <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbXGvw43spR79ztEvWt --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 2fea6d2 commit 961f474

11 files changed

Lines changed: 350 additions & 17 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/runtime': patch
3+
---
4+
5+
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`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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)`).
11+
12+
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.
13+
14+
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.

‎content/docs/api/error-catalog.mdx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -708,7 +708,8 @@ value directly (single wrap).
708708
| Caller lacks `requiredPermissions` | **403** | `{ success: false, error: { message, code } }` |
709709
| Type has no server dispatch (`url`/`modal`/`form`/`api`), or a param-contract violation | **400** | `{ success: false, error: { message, code } }` |
710710
| Data engine or automation service unavailable | **503** | `{ success: false, error: { message, code } }` |
711-
| Handler **crashed** (`TypeError`, driver error, sandbox timeout) | **500** | `{ success: false, error: { message, code } }` |
711+
| Handler **crashed** (`TypeError`, driver error) | **500** | `{ success: false, error: { message, code } }` |
712+
| 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` |
712713
| 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 |
713714

714715
A rejection and a crash are told apart by the thrown error: a plain

‎content/docs/ui/actions.mdx‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -699,9 +699,10 @@ Failures speak HTTP — the status code is the signal (#3962):
699699
- **404 / 403 / 503** — it never dispatched: no such action, denied, service
700700
unavailable. A `url`/`modal`/`form` type, or an `api` type whose `target`
701701
is on another origin, has no server dispatch and is also a 400.
702-
- **500** — it **crashed**: a `TypeError` in your handler, a driver error, a
703-
sandbox timeout. A deliberate `throw new Error('…')` is a 400 rejection,
704-
not a crash.
702+
- **500** — it **crashed** (a `TypeError` in your handler, a driver error) or
703+
**timed out**; a timeout's message names the action and its limit, while a
704+
crash answers only `Internal server error`. A deliberate
705+
`throw new Error('…')` is a 400 rejection, not a crash.
705706
706707
Full table in the [error catalog](/docs/api/error-catalog). The
707708
[client SDK](/docs/api/client-sdk) folds all of it into one

‎packages/mcp/src/mcp-coded-refusal.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -990,6 +990,28 @@ describe('run_action / resume_run: a throw answers what the /actions door answer
990990
expect([door.code, door.declaredCode, door.status]).toEqual([error.code, error.declaredCode, error.status]);
991991
});
992992

993+
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 () => {
994+
const log = vi.spyOn(console, 'error').mockImplementation(() => {});
995+
// The shape `QuickJSScriptRunner` raises for an action that ran out of
996+
// time (`@objectstack/runtime`'s `sandboxed-action-crash-is-a-fault.test.ts`
997+
// measures it on a real run and on the HTTP door): the operator line in
998+
// `.message`, the caller sentence in `innerMessage`, a declared 500, no code.
999+
const sentence = "Action 'demo_leave_body' timed out: it exceeded its 50 ms time limit and was stopped.";
1000+
const thrown = () => Object.assign(
1001+
new Error("action 'demo_leave_body' exceeded CPU budget of 50ms (after 3 pump iterations)"),
1002+
{ name: 'SandboxError', innerMessage: sentence, status: 500 },
1003+
);
1004+
const result = await callTool(site, thrown());
1005+
expect(result.isError).toBe(true);
1006+
const { error } = JSON.parse(String(result.content[0].text));
1007+
expect(error).toEqual({ code: 'INTERNAL_ERROR', message: sentence, status: 500 });
1008+
const door = actionsDoorAnswerOf(thrown());
1009+
expect(error).toEqual({ code: door.code, message: door.message, status: door.status });
1010+
// The operator line reaches the log, and never the tool result.
1011+
expect(log).toHaveBeenCalledTimes(1);
1012+
expect(String(result.content[0].text)).not.toContain('pump iterations');
1013+
});
1014+
9931015
it(`${site.tool}: a fault carries no thrown details; a refusal still does`, async () => {
9941016
vi.spyOn(console, 'error').mockImplementation(() => {});
9951017
const details = { host: 'db-primary.internal', pool: 'writer' };

‎packages/runtime/src/domains/actions.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@
5151
* Success is now a SINGLE wrap (`data` = the handler's return value), a
5252
* deliberate rejection (body `throw`, flow rejection, ValidationError) is a
5353
* 400 carrying `code`/`fields` in `details`, and a crash (`TypeError`, driver
54-
* class, sandbox timeout — told apart by the error's NAME, #3951) is a 500.
54+
* class — told apart by the error's NAME, #3951) is a 500. A sandbox timeout
55+
* is a 500 too, but not a crash: its message names the action and its limit.
5556
*
5657
* did a handler run? no → 404 / 403 / 400 / 503
5758
* did it reject or crash? reject → 400; crash → 500

‎packages/runtime/src/sandbox-unreadable-rejection-door.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco
3434
import { HttpDispatcher } from './http-dispatcher.js';
3535
import { actionBodyRunnerFactory } from './sandbox/body-runner.js';
3636
import { QuickJSScriptRunner } from './sandbox/quickjs-runner.js';
37+
// Paid during collection, never inside a case's clocked window: the door's
38+
// reach loads this package lazily (`check:test-source-alias`).
39+
import '@objectstack/metadata';
3740

3841
const PREFIX = '/api/v1';
3942
/** `registry.registerObject` requires a package id (see the sibling real-stack tests). */
@@ -158,5 +161,9 @@ describe('[#23723] CONTROL — the door\'s other answers stand', () => {
158161
const response = await postAction('never_settles');
159162
expect(response.status, JSON.stringify(response.body)).toBe(500);
160163
expect(response.body?.error?.code).toBe('INTERNAL_ERROR');
164+
// The timeout names the action and its limit, never a refusal.
165+
expect(response.body?.error?.message).toBe(
166+
`Action 'never_settles' timed out: it exceeded its ${CEILING_MS} ms time limit while waiting on platform calls, and was stopped.`,
167+
);
161168
});
162169
});

‎packages/runtime/src/sandbox/action-refusal-catalogue.test.ts‎

Lines changed: 102 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import { describe, it, expect, vi } from 'vitest';
1616
// Paid at collection, not inside a case's clocked window: the dispatcher's
1717
// reach loads `@objectstack/metadata` lazily (`check:test-source-alias`).
1818
import '@objectstack/metadata';
19-
import { mapDataError } from '@objectstack/types';
19+
import { actionsDoorAnswerOf, mapDataError } from '@objectstack/types';
2020

2121
import { actionBodyRunnerFactory } from './body-runner.js';
2222
import { QuickJSScriptRunner, SandboxError } from './quickjs-runner.js';
@@ -52,13 +52,21 @@ const ZH_GLOBAL = '(全局)只有草稿发票可以签核。';
5252
/** A `script` action with a `js` body and the catalogue, bound through the real factory. */
5353
function boundAction(
5454
source: string,
55-
opts: { refusals?: object; objectName?: string | null; i18n?: () => HookRefusalI18nService | undefined } = {},
55+
opts: {
56+
refusals?: object;
57+
objectName?: string | null;
58+
i18n?: () => HookRefusalI18nService | undefined;
59+
runner?: QuickJSScriptRunner;
60+
logger?: Record<string, (...args: any[]) => void>;
61+
timeoutMs?: number;
62+
} = {},
5663
) {
5764
const objectName = opts.objectName === undefined ? 'crm_invoice' : opts.objectName ?? undefined;
58-
const fn = actionBodyRunnerFactory(runner, { ql: {}, appId: 'crm', i18n: opts.i18n })({
65+
const fn = actionBodyRunnerFactory(opts.runner ?? runner, { ql: {}, appId: 'crm', i18n: opts.i18n, logger: opts.logger as any })({
5966
name: 'submit_signoff',
6067
type: 'script',
6168
...(objectName !== undefined ? { objectName, object: objectName } : {}),
69+
...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),
6270
body: { language: 'js', source, capabilities: [] },
6371
refusals: 'refusals' in opts ? opts.refusals : REFUSALS,
6472
} as any);
@@ -271,3 +279,94 @@ describe('[#34273] the `/actions` door answers the declared refusal in the calle
271279
expect(response.body.error.userMessage).toBeUndefined();
272280
});
273281
});
282+
283+
/**
284+
* The runner's own faults are the platform speaking, never a refusal the body
285+
* chose, so an action that declares `refusals` answers them exactly as an
286+
* action without one does. A timeout keeps the sentence naming the action and
287+
* its limit, a body that does not compile keeps the sentence naming the
288+
* compiler's reason, and the operator log keeps the runner's own line, never
289+
* the catalogue's "threw no code" fault.
290+
*
291+
* Driven through the real bound handler (`actionBodyRunnerFactory`), which
292+
* hands every throw to `resolveActionRefusal` before it logs and rethrows it,
293+
* and read on both action doors: the `/actions` HTTP door and the reader the
294+
* MCP `run_action` tool renders a throw with (`actionsDoorAnswerOf`).
295+
*/
296+
describe('the runner\'s own faults pass an action\'s refusal catalogue untouched', () => {
297+
const CPU_SENTENCE = "Action 'submit_signoff' timed out: it exceeded its 50 ms time limit and was stopped.";
298+
const WALL_SENTENCE =
299+
"Action 'submit_signoff' timed out: it exceeded its 300 ms time limit while waiting on platform calls, and was stopped.";
300+
const COMPILE_BODY = 'const input = ctx.input || {}; return 1;';
301+
302+
/**
303+
* Records the `.message` of each error logged at `error`, read when it is
304+
* logged: the door later rewrites `.message` to the caller sentence.
305+
*/
306+
function capturingLogger() {
307+
const logged: string[] = [];
308+
const error = vi.fn((_line: string, err: { message: string }) => { logged.push(err.message); });
309+
return { error, logged, logger: { error, info: vi.fn(), warn: vi.fn(), debug: vi.fn() } };
310+
}
311+
312+
/** Both doors' answers to one thrown error, as `{ status, code, message }`. */
313+
async function bothDoors(err: unknown) {
314+
const response = await throughActionsDoor(err);
315+
const mcp = actionsDoorAnswerOf(err, 'crm_invoice');
316+
return {
317+
actions: { status: response.status, code: response.body.error.code, message: response.body.error.message },
318+
mcp: { status: mcp.status, code: mcp.code, message: mcp.message },
319+
};
320+
}
321+
322+
it('a CPU timeout answers its sentence on both doors, and the log keeps the budget line', async () => {
323+
const { error, logged, logger } = capturingLogger();
324+
const err = await rejectionOf(boundAction('while (true) {}', { logger, timeoutMs: 50 })(actionCtx()));
325+
expect(err).toBeInstanceOf(SandboxError);
326+
const expected = { status: 500, code: 'INTERNAL_ERROR', message: CPU_SENTENCE };
327+
expect(await bothDoors(err)).toEqual({ actions: expected, mcp: expected });
328+
329+
expect(error).toHaveBeenCalledTimes(1);
330+
expect(error.mock.calls[0][1]).toBe(err);
331+
expect(logged[0]).toMatch(/^action 'submit_signoff' exceeded CPU budget of 50ms/);
332+
});
333+
334+
it('a wall-clock timeout answers its sentence on both doors, and the log keeps the ceiling line', async () => {
335+
const { logged, logger } = capturingLogger();
336+
const wallRunner = new QuickJSScriptRunner({ actionTimeoutMs: 250, wallCeilingMs: 300 });
337+
const err = await rejectionOf(
338+
boundAction('await new Promise(() => {});', { logger, runner: wallRunner })(actionCtx()),
339+
);
340+
const expected = { status: 500, code: 'INTERNAL_ERROR', message: WALL_SENTENCE };
341+
expect(await bothDoors(err)).toEqual({ actions: expected, mcp: expected });
342+
expect(logged).toHaveLength(1);
343+
expect(logged[0]).toMatch(/^action 'submit_signoff' exceeded wall-clock ceiling of 300ms/);
344+
});
345+
346+
it('a body that does not compile answers its sentence on both doors, and the log names the compiler', async () => {
347+
const { logged, logger } = capturingLogger();
348+
const err = await rejectionOf(boundAction(COMPILE_BODY, { logger })(actionCtx()));
349+
const answers = await bothDoors(err);
350+
expect(answers.mcp).toEqual(answers.actions);
351+
expect(answers.actions.status).toBe(500);
352+
expect(answers.actions.code).toBe('INTERNAL_ERROR');
353+
expect(answers.actions.message).toContain("Action 'submit_signoff' cannot run: its body does not compile");
354+
expect(logged).toHaveLength(1);
355+
expect(logged[0]).toMatch(/^action 'submit_signoff' does not compile: SyntaxError/);
356+
});
357+
358+
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 () => {
359+
for (const source of [
360+
"throw new Error('no code');",
361+
"throw Object.assign(new Error('The server is busy.'), { status: 500 });",
362+
`throw Object.assign(new Error(${JSON.stringify(CPU_SENTENCE)}), { status: 500 });`,
363+
]) {
364+
const err = await rejectionOf(boundAction(source)(actionCtx()));
365+
expect(err.message, source).toContain('threw no `code`');
366+
expect(err.innerMessage, source).toBeUndefined();
367+
const answers = await bothDoors(err);
368+
expect(answers.actions, source).toEqual({ status: 500, code: 'INTERNAL_ERROR', message: 'Internal server error' });
369+
expect(answers.mcp, source).toEqual(answers.actions);
370+
}
371+
});
372+
});

‎packages/runtime/src/sandbox/hook-refusal-catalogue.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@
3636
* refusal of a `ctx.api` write, a nested hook's refusal), the engine's own
3737
* error the runner relays as itself, a crash (`TypeError: …`) and the
3838
* sandbox's own faults (budget, capability) all pass through as before: they
39-
* are the platform speaking, or a bug, never a refusal the body chose.
39+
* are the platform speaking, or a bug, never a refusal the body chose. An
40+
* action's timeout and an action body that does not compile carry a caller
41+
* sentence, so they pass by identity ({@link isRunnerOwnFault}), not by the
42+
* missing `innerMessage` the other faults pass on.
4043
*
4144
* **Reasons and params (#33214, ruling 6879477573: S1 and params).** A code
4245
* may hold further declared sentences under `reasons`; a throw that names a
@@ -82,6 +85,7 @@ import {
8285
SandboxError,
8386
isHostRelayedSandboxError,
8487
isRelayedSandboxRefusal,
88+
isRunnerOwnFault,
8589
sandboxRefusalAddressOf,
8690
type SandboxRefusalAddress,
8791
} from './quickjs-runner.js';
@@ -453,8 +457,12 @@ function resolveSandboxedRefusal(
453457
locale: unknown,
454458
opts: { i18n?: HookRefusalI18nSource; logger?: { warn?: (...args: any[]) => void } },
455459
): unknown {
456-
// Not the body's own throw: the engine's error relayed as itself, the
457-
// sandbox's own fault, a host error re-thrown unchanged, a nested refusal.
460+
// Not the body's own throw: the runner's own fault that carries a caller
461+
// sentence (an action's timeout, an action body that does not compile; by
462+
// identity, before any field is read, since a body can throw the same
463+
// fields), the engine's error relayed as itself, the sandbox's own fault, a
464+
// host error re-thrown unchanged, a nested refusal.
465+
if (isRunnerOwnFault(err)) return err;
458466
if (!(err instanceof SandboxError) || err.innerMessage === undefined) return err;
459467
if (isHostRelayedSandboxError(err) || isRelayedSandboxRefusal(err)) return err;
460468
// A crash (`TypeError: …`) is a bug, not a refusal: it stays the fault it is.

0 commit comments

Comments
 (0)