Skip to content

Commit 153869d

Browse files
fix(runtime,service-automation): a write in an action, hook or job body, or a flow record node, that landed under a failing roll-up answers its own success (#29283)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi98nf8o68Xa2qqqX5Z9XoQ7N)_ Fixes #28861 Clause-②: yes (widening) Metadata-protocol: none Skills-docs: none — no file under `skills/**` or the docs teaches what a body's or a flow node's write answers when a parent roll-up cannot be recomputed after it, and this changes no authorable shape ## 维护者速读 - 改了什么:动作处理器的 `ctx.engine` / `ctx.api`、沙箱里 hook / 动作 / 任务正文的 `ctx.api.object(x)`、以及流程的 `create_record` / `update_record` / `delete_record` 节点,在写入已落库、只是父记录汇总重算失败(`ERR_SUMMARY_RECOMPUTE`)时,返回这次写入本来的成功结果,正文和流程继续往下跑;过期汇总列按字段每进程以 error 记一次日志。REST 动作入口和 MCP `run_action` 只在声明式 update 动作上把拒绝里挂的结果当作成功。 - 为什么改:以前这个拒绝直接抛进作者代码:写入其实已经生效,但正文下一行不再执行,动作、hook、任务或流程都报失败,调用方重试就会再写一遍。数据入口和 MCP 工具早已按成功答复,作者代码这一侧没有跟上(席位裁定 6570987196)。 - 风险与回滚:写入前的拒绝(校验、权限、约束)完全照旧;没有新错误码、字段或形状,也没加事务。回滚就是整体 revert 本 PR,没有数据或元数据迁移。 - 先看:`packages/runtime/src/action-execution.ts`(`invokeBusinessAction` 的 catch 和 `withoutWriteAnswer`、`buildActionEngineFacade` 的多 id 删除);`packages/runtime/src/landed-write-answer.ts`;`packages/services/service-automation/src/builtin/crud-nodes.ts`。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run src/action-body-write-stale-summary.test.ts src/sandbox/body-write-stale-summary.test.ts`,应看到 2 个文件、19 个测试全部通过。 - 需要你做的:无,席位落地。 ## What changes Seat ruling 6570987196 on #28861: a write the engine stored answers its own success at every author-visible write surface when only the parent roll-up recompute after it fails. The refusal is objectql's `SummaryRecomputeError` (`ERR_SUMMARY_RECOMPUTE`), whose `written` is exactly what the call returns on a healthy recompute. Each surface returns that `written` value and logs the stale column through `staleSummaryAnswerLines` (`@objectstack/types`), the same line the data doors log. Every other throw, including a refusal raised before the write is stored, is rethrown unchanged (`staleSummaryRefusalOrThrow`). No new error code, member, shape or transaction. - **Shared layer** (new `packages/runtime/src/landed-write-answer.ts`): - `landedWriteAnswer(e, object, surface)` is the one `catch` body. - `answerLandedWritesDespiteStaleSummary(api, surface)` wraps every repository write verb of a scoped API, on the API and on every context it derives (`object(name)`, `sudo()`, `withRunAs(...)`, a `transaction(fn)` callback's context, `beginTransaction()`'s `ctx`). It walks the API through the existing `deriveThroughSeam`, and the verb list is the existing `WRITE_RETURN_VERBS`. Both are now exported from `stored-metadata-reader-seam.ts`, so there is one definition of what a write is and what an API derives. Idempotent. - **`ctx.engine`** (`buildActionEngineFacade`, `action-execution.ts`): `insert` answers `{ id }` read from the written record; `update` resolves. A multi-id `delete` catches per id, so a stale roll-up after one id no longer leaves the later ids undeleted. - **`ctx.api`** (`buildActionApi`, objectql `createContext`): wrapped beneath `serveStoredMetadataReadsThrough`, so the answer is served by the reader seam like any write's return. - **Sandbox `ctx.api.object(x)`** (`buildSandboxApi`, `sandbox/body-runner.ts`): wrapped beneath both body refusal layers, over whichever source the API is built from: the engine's hook API, the host's action `api`, or a job's `executionContext` + `createContext` fallback. Hook, action and job bodies all go through it. - **Flow record nodes** (`builtin/crud-nodes.ts`, `@objectstack/service-automation`): `create_record` / `update_record` / `delete_record` wrap their one data call. The node answers the same `output`, `outputVariable`, `droppedFields` and `acted` it answers on a clean write, with the stale line on the node's logger at `error`. A non-stale throw reaches the node's existing `catch` and is `success: false` as before. `packages/runtime/src/domains/automation.ts` (#29097's file) is not touched. - **The action doors' generic `earnedAnswerOf` reading is pinned to the declarative-update arm.** That arm composes and attaches the ACTION's result (#28856). Any other arm's refusal could only carry a WRITE's data answer, for example a handler that let out a refusal a data door had attached its answer to. - REST action door (`dispatchAdmittedRestAction`'s catch, `domains/actions.ts`): reads it only when `isDeclarativeUpdateAction(actionDef)`; any other arm answers the failure as before #28856. - `invokeBusinessAction` (MCP): the audit row is `succeeded` only on the declarative arm. Any other arm's throw leaves with nothing attached (`withoutWriteAnswer` rebuilds the same `SummaryRecomputeError`: class, `failures`, `written`, message, stack). So `run_action`'s generic `landedWriteResultOrError` in `packages/mcp/src/mcp-http-tools.ts` (not edited) cannot relay a write's answer as the action's result either. - **Changesets:** new `.changeset/28861-body-write-stale-summary-answer.md` (runtime and service-automation patch). The last sentence of the still-pending `.changeset/28856-action-stale-summary-answer.md` is corrected: it said a `flow` action's record nodes turn the refusal into a node failure and that script/body was a follow-up, and both stop being true with this PR. This deliberately reds `check-empty-changeset` (its DELIBERATE CORRECTION class: "do NOT restore it -- say so on the PR and get it confirmed"). Confirmation is asked of the seat here. ## Tests No existing test was edited (no forced test edits). Three new files, red first on the test-only commit `897a4c53` over `origin/main` `2af0ae2a`. Each engine double opens its `update` / `delete` / `findOne` with the producer's predicate (`assertEngineUpdateDispatch` / `assertEngineDeleteDispatch` / `assertEngineFindOnePredicate`, `@objectstack/metadata-core`), so it refuses what ObjectQL refuses; `scripts/engine-double-contract.pinned.json` records the 7 new pinned rows (`check-engine-double-contract --write`, 0 lost). - `packages/runtime/src/action-body-write-stale-summary.test.ts` (14). The real `HttpDispatcher` over objectql's real `ScopedContext` (`createContext`), with an audit service and an engine double whose writes apply and then throw objectql's own `SummaryRecomputeError`. - `ctx.engine` insert, update and a multi-id delete (every id deleted). - `ctx.api` `object(x).insert`, `update` + `delete`, and a derived context (`sudo()`). - NEGATIVE PIN: five pre-write refusals (`it.each`) reach the body as before, nothing written. - Door pin: a script action body that throws a stale refusal carrying an attached answer. REST answers exactly what the same body answers when it throws the bare refusal, and never the attached answer. The MCP bridge throws the refusal with `earnedAnswerOf` undefined, code `ERR_SUMMARY_RECOMPUTE`, and an audit row `failed`. - One `error` line naming `"stv_account.visit_count"`. - Red on base: 8 of 14. The 5 negatives and the log pin were green; on base the log line came from the REST door's generic carrier reading of the door pin, a reading this PR removes. - `packages/runtime/src/sandbox/body-write-stale-summary.test.ts` (5), on the QuickJS runner: a hook body (the engine's hook API, patch merged), an action body (update + delete, own value returned), a job body (`createContext` fallback, own outcome), a NEGATIVE PIN (`VALIDATION_FAILED` / `400` caught in the body, nothing written), and one `error` line naming `"stb_order.line_total"`. Red on base: 4 of 5, the negative green. - `packages/services/service-automation/src/builtin/crud-stale-summary.test.ts` (3): a `create_record` → `update_record` → `delete_record` run reaching its end, with exactly one stale line; the `create_record` executor's output (`record`, `droppedFields`, `acted: 1`, `outputVariable`); and a NEGATIVE PIN where a `PERMISSION_DENIED` before the write still fails the run with nothing written. Red on base: 2 of 3, the negative green. <details><summary>Ablations: each mutation landed on disk with <code>ablation-replace</code>, red, then restored to blob == HEAD (final head <code>e591f329</code>)</summary> | # | ablation | file | red | |---|---|---|---| | A1 | `ctx.engine.insert` rethrows | `action-execution.ts` | 1 of 14 | | A2 | `ctx.engine.update` rethrows | `action-execution.ts` | 1 of 14 | | A3 | `ctx.engine.delete` rethrows | `action-execution.ts` | 1 of 14 | | A4 | `buildActionApi` without the layer | `action-execution.ts` | 3 of 14 | | A5 | `buildSandboxApi` without the layer | `sandbox/body-runner.ts` | 4 of 5 | | A6 | `create_record` rethrows | `crud-nodes.ts` | 2 of 3 | | A7 | `update_record` rethrows | `crud-nodes.ts` | 1 of 3 | | A8 | `delete_record` rethrows | `crud-nodes.ts` | 1 of 3 | | N1 | a pre-write refusal answered as success (`landedWriteAnswer` swallows every throw) | `landed-write-answer.ts` | 8 of 19 | | N2 | the same in the flow nodes | `crud-nodes.ts` | 1 of 3 | | N3 | REST door reads every arm's attached answer | `domains/actions.ts` | 1 of 14 | | N4 | `invokeBusinessAction` lets a write's answer out | `action-execution.ts` | 1 of 14 | | N5 | the audit row reads every arm's attached answer | `action-execution.ts` | 1 of 14 | All 13 were first measured on `13f35e09`, then rerun on `7c5f3e55` (after the double pinning) and on the final head `e591f329` (after merging `main` with #29036), with the same counts each time. On the first round, the tries at A5, N3 and N5 were refused by `ablation-replace` with nothing changed on disk ("the replacement count moved 1 -> 1"), because the replacement sat inside its anchor. They were rerun with a `/* ablated */`-prefixed replacement; the counts above are those runs. </details> ## Acceptance notes - **Clause-② measured as widening.** Each changed call answers success where it threw or failed before. The doors' narrowing to the declarative arm narrows only #28856's generic reading (PR #28882, merged 2026-11-02). That reading is unreleased: `.changeset/28856-action-stale-summary-answer.md` is still pending, and `@objectstack/runtime` is at `18.2.0`. No published surface narrows. - **Out of the ruling's reach on purpose:** objectql's `ScopedContext` and the engine itself. Bulk callers (the seed loader, the import runner) read the refusal as "written, with a stale summary" in their own results. An in-process code hook's `HookContext.api` is platform or deployer code, not an author's body. Both are unchanged. - **Noted, not filed:** objectql's `ObjectRepository.execute()` hands a nested handler a raw `ScopedContext`. Its own census lists zero callers, so it reaches no author today. - The engine's own `warn` per failed recompute is unchanged; the surfaces add the doors' once-per-field `error` line. - No `packages/spec/**` or `ui/**` edit, and no workflow file. ## Verification <details><summary>Suites and typecheck</summary> - `@objectstack/runtime` full local suite on `281d91ae` (after merging `main` at `692a4e4a`): 516 of 516 files, 8337 passed and 19 skipped (`os-verify-lock` VERDICT command-exit 0). - `@objectstack/service-automation` typecheck exit 0 and full suite 258 of 258 files, 3312 of 3312 tests, on `281d91ae`. - `@objectstack/mcp` stale-summary neighbours (`mcp-run-action-`, `mcp-create-record-`, `mcp-update-delete-record-stale-summary.test.ts`): 13 of 13. - `pnpm --filter @objectstack/runtime typecheck` (`tsc --noEmit` and `check:test-typecheck`): exit 0. The first read was exit 1 on the untouched `organization-ownership-boot-guard.turso-remote.kernel.test.ts` (TS2307, `@objectstack/driver-turso`). That was a missing `dist` of the optional peer, not this diff; it was green after building `@objectstack/driver-turso`. - After merging `main` again at `c44c8ac4` (head `7365c82a`; `main` touched objectql and service-automation, not `packages/runtime`): service-automation typecheck exit 0 and full suite 259 of 259 files, 3317 of 3317 tests; runtime `tsc --noEmit` exit 0; runtime vitest over the new files, `src/domains` and `src/sandbox`: 219 of 219 files, 4192 of 4192 tests. - `7c5f3e55` (the doubles opened with the producer predicates): the three new files 19 of 19 and 3 of 3. - Final head `e591f329`, after merging `main` at `0c0d3b68` (#29036 landed there as `af8448fe`, editing `action-execution.ts`; merged clean, both intents kept). Every `packages/**` package built (78 of 78). `pnpm --filter @objectstack/runtime typecheck` and `pnpm --filter @objectstack/service-automation typecheck`: exit 0. service-automation full suite: 260 of 260 files, 3338 of 3338 tests. runtime vitest over `src/action-*`, `src/domains` and `src/sandbox` (#29036's `api-action-forward.test.ts` among them): 248 of 248 files, 4665 of 4665 tests. </details> <details><summary>Gates</summary> On the final head `e591f329`, after building every `packages/**` package (`turbo run build --filter='./packages/**'`, 78 of 78 tasks). The same 71 commands also ran on `7c5f3e55` with the same result: - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 71 commands; each was run with `< /dev/null`, and `--ran` reconciles **71 derived, 71 run, 0 NOT-MEASURED, 0 UNRUN** (exit 0). - 70 of 71 exit 0. The one red is `node scripts/check-empty-changeset.mjs --base origin/main` (exit 1), by design: it names `.changeset/28856-action-stale-summary-answer.md` as "present on the merge base and CHANGED by this PR". This is its DELIBERATE CORRECTION class (see What changes), declared here for the seat to confirm. `Check Changeset` is not a required check. - First pass on this branch (`7365c82a`): `check:engine-double-contract` exit 1, because the three new doubles did not open with the producer predicates. This was fixed in `7c5f3e55` (doubles pinned, ledger written), not by a baseline entry. `check-plugin-teardown-shape --self-test` exit 3 (prerequisite: the pinned fixture commit `621a4876` was missing from the shallow clone); green after `git fetch --depth=1 origin 621a487…`. - `pnpm lint`: exit 0. - PR body offline: `node scripts/check-changeset-no-major.mjs --base origin/main --event <this body>`: exit 0 (LEVEL AXIS: `yes (widening)` and `none` at `patch`). `check-closing-keyword-parity --body`: only `Fixes #28861` binds. </details> No live probe: storing a stale roll-up needs the lint roll-up gate turned off at the runtime door (the #28782 recipe). The producer half, the engine raising `SummaryRecomputeError` with `written` after the write, is objectql's and pinned there (`engine-summary-retry.test.ts`, `summary-recompute-code-constant.test.ts`); this change is the author-facing surfaces, pinned above through the real `HttpDispatcher`, `ScopedContext`, QuickJS runner and `AutomationEngine`. Full dogfood is not owed (no `!`, no narrowing arm). --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmQEc6KnPaxi9d3soLZ)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent affba40 commit 153869d

12 files changed

Lines changed: 889 additions & 32 deletions

‎.changeset/28856-action-stale-summary-answer.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@ When a declarative update action (`operation: 'update'`) writes its record but a
1515
- **MCP `run_action`**: the usual `{ ok, action, objectName, recordId, result }`.
1616
- The action's invocation audit row records `succeeded`, the outcome the door answers.
1717

18-
The runtime composes the action's result once and attaches it to the refusal through the existing carrier; each door relays it. The stale summary column is logged at `error` once per field per process. A refusal before the write answers exactly as before. Other action kinds are unchanged: an `api` action's forward already lands on a data door that answers success, a `flow` action's record nodes turn the refusal into a node failure, and a script or body action is a separate follow-up.
18+
The runtime composes the action's result once and attaches it to the refusal through the existing carrier; each door relays it. The stale summary column is logged at `error` once per field per process. A refusal before the write answers exactly as before. Other action kinds: an `api` action's forward already lands on a data door that answers success, and a `flow` action's record nodes and a script or body action's own writes answer a landed write's success since #28861.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/runtime': patch
3+
'@objectstack/service-automation': patch
4+
---
5+
6+
fix(runtime,service-automation): a write in an action, hook or job body, or a flow record node, that landed under a failing roll-up answers its own success (#28861)
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
When a child write is stored but a parent's roll-up summary cannot be recomputed after it (`ERR_SUMMARY_RECOMPUTE`, "the triggering records WERE written"), the data doors and MCP tools already answer the write's success. The write surfaces an author's code holds now do the same, so the code's next line runs instead of stopping on a write that landed. Each answers exactly what the same write answers when every roll-up recomputes — no new code, member or shape:
12+
13+
- **`ctx.engine`** in an action handler: `insert` resolves `{ id }`, `update` and `delete` resolve. A multi-id `delete` deletes every id; a stale roll-up after one id no longer leaves the later ids undeleted.
14+
- **`ctx.api`** in an action handler, and every context it derives (`sudo()`, `withRunAs(...)`, a `transaction(fn)` callback's context): each repository write verb resolves with the engine's result.
15+
- **A sandboxed hook, action or job body's `ctx.api.object(...)`**: the write resolves in the body with the engine's result, so a hook no longer refuses the write that fired it, an action body returns its own value, and a job run reports its own outcome.
16+
- **Flow `create_record`, `update_record` and `delete_record`**: the node succeeds with the output it gives on a clean write (`output`, `outputVariable`, `droppedFields`, `acted`), and the run goes on to its next node.
17+
18+
The stale summary column is logged at `error` once per field per process, with the fix, as on the data doors. A refusal raised before the write is stored (validation, permission, constraint) reaches the author's code exactly as before. No transaction is added: a body's earlier writes stay committed, as they always did. Inside a transaction the body opens itself (`ctx.api.transaction(fn)`), such a write now answers its success in the callback too, so that transaction commits where the refusal used to roll it back.
19+
20+
The REST and MCP action doors answer a refusal carrying a write's attached answer as the action's success only for a declarative update action, whose refusal carries the action's own result. Any other action that throws such a refusal is answered as the failure it is, and its invocation audit row records `failed`.
Lines changed: 292 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,292 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#28861] A write an action body makes through `ctx.engine` or `ctx.api` that
5+
* the engine STORED, but whose parent roll-up summary it could not recompute
6+
* after it, answers the write's own success in the body — never the
7+
* refusal, which stopped the body's later steps and made the action door
8+
* report a failure for a write that had landed (the caller then retried).
9+
*
10+
* ## The defect, measured on `origin/main` (`2af0ae2a`) before this file
11+
*
12+
* The engine reports that case as objectql's `SummaryRecomputeError`
13+
* (`ERR_SUMMARY_RECOMPUTE`, "the triggering records WERE written", carrying
14+
* `written`). `buildActionEngineFacade` (`ctx.engine`) and `buildActionApi`
15+
* (`ctx.api`, objectql's `createContext`) handed it straight into the body,
16+
* so a body's next line never ran, the action had no result, and both doors
17+
* answered the throw: REST a `500`, the MCP bridge a throw with the audit row
18+
* `failed`.
19+
*
20+
* ## What is pinned (seat ruling 6570987196)
21+
*
22+
* - each write surface returns what the call returns when every roll-up
23+
* recomputes: `ctx.engine.insert` its `{ id }`, `update` and `delete`
24+
* resolve, a multi-id `delete` deletes every id, and `ctx.api.object(x)`'s
25+
* verbs answer the engine's result — so the body runs on and the door
26+
* answers the body's OWN result, the audit row `succeeded`;
27+
* - the stale column is logged once per field, at `error`;
28+
* - a refusal raised before the write is stored reaches the body exactly as
29+
* before (NEGATIVE PIN);
30+
* - the doors read a write's attached answer only on the declarative-update
31+
* arm (addendum 6567869052 point 2): a body that throws a refusal carrying
32+
* a write's data answer is answered as the failure it is — never with that
33+
* data as the action's result — at REST, on the MCP bridge and in the audit
34+
* row (NEGATIVE PIN).
35+
*
36+
* The engine is a double whose writes apply and then throw objectql's own
37+
* `SummaryRecomputeError`; `ctx.api` is objectql's real `ScopedContext` over it.
38+
*/
39+
40+
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
41+
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/metadata-core';
42+
import { ScopedContext, SummaryRecomputeError } from '@objectstack/objectql';
43+
import { earnedAnswerOf, withEarnedAnswer } from '@objectstack/types';
44+
45+
import { HttpDispatcher } from './http-dispatcher.js';
46+
47+
const OBJECT = 'stv_account';
48+
const CHILD = 'stv_visit';
49+
const ACTION = {
50+
name: 'log_visit', label: 'Log visit', objectName: OBJECT, type: 'script', target: 'logVisit',
51+
ai: { exposed: true, description: 'Log a visit.' },
52+
};
53+
54+
/** One parent whose roll-up could not be recomputed, as the engine names it. */
55+
const FAILURES = [{ childObject: CHILD, parentObject: OBJECT, parentId: 'a1', field: 'visit_count', error: new Error('sum over text') }];
56+
57+
type Handler = (ctx: any) => Promise<unknown>;
58+
59+
/**
60+
* The dispatcher over an engine whose `insert` / `update` / `delete` apply the
61+
* write, then report the stale roll-up — or refuse before writing anything
62+
* when the payload or the id says `refused`. `handler` is the action body.
63+
*/
64+
function makeRig(handler: Handler) {
65+
const events: any[] = [];
66+
const audit = { recordActionInvocation: vi.fn(async (e: any) => { events.push(e); }) };
67+
const rows = new Map<string, Record<string, unknown>>([['v0', { id: 'v0', title: 'old' }]]);
68+
const writes: string[] = [];
69+
const refuse = (object: string) =>
70+
Object.assign(new Error(`You do not have permission to write ${object}`), { code: 'PERMISSION_DENIED', status: 403 });
71+
72+
const objectDef = { name: OBJECT, fields: { name: { type: 'text' } }, actions: [ACTION] };
73+
const schemaOf = (n: string) => (n === OBJECT ? objectDef : undefined);
74+
const ql: any = {
75+
executeAction: vi.fn(async (object: string, key: string, ctx: any) => {
76+
if (object === OBJECT && key === ACTION.target) return handler(ctx);
77+
throw new Error(`Action '${key}' on object '${object}' not found`);
78+
}),
79+
getSchema: schemaOf,
80+
registry: { getObject: schemaOf, getItem: () => undefined },
81+
find: vi.fn(async () => []),
82+
insert: vi.fn(async (object: string, data: any) => {
83+
if (data?.title === 'refused') throw refuse(object);
84+
const row = { ...data };
85+
rows.set(String(data.id), row);
86+
writes.push(`insert:${data.id}`);
87+
throw new SummaryRecomputeError(FAILURES as any, { ...row });
88+
}),
89+
update: vi.fn(async (object: string, data: any, options?: any) => {
90+
assertEngineUpdateDispatch(data, options);
91+
const id = String(options?.where?.id);
92+
if (id === 'refused') throw refuse(object);
93+
const row = { ...(rows.get(id) ?? { id }), ...data };
94+
rows.set(id, row);
95+
writes.push(`update:${id}`);
96+
throw new SummaryRecomputeError(FAILURES as any, { ...row });
97+
}),
98+
delete: vi.fn(async (object: string, options?: any) => {
99+
assertEngineDeleteDispatch(options);
100+
const id = String(options?.where?.id);
101+
if (id === 'refused') throw refuse(object);
102+
rows.delete(id);
103+
writes.push(`delete:${id}`);
104+
throw new SummaryRecomputeError(FAILURES as any, { id });
105+
}),
106+
createContext: (ec: any) => new ScopedContext(ec, ql),
107+
};
108+
const metadata: any = {
109+
load: vi.fn(async () => null),
110+
loadDiagnosed: vi.fn(async () => ({ data: null, degraded: false, errors: [] })),
111+
loadMany: vi.fn(async () => []),
112+
listObjects: vi.fn(async () => [objectDef]),
113+
getObject: vi.fn(async (n: string) => schemaOf(n)),
114+
};
115+
const services: Record<string, unknown> = { objectql: ql, data: ql, metadata, audit };
116+
const resolve = (n: string) => services[n] ?? null;
117+
const kernel: any = { getService: resolve, getServiceAsync: async (n: string) => resolve(n), context: { getService: resolve } };
118+
const dispatcher = new HttpDispatcher(kernel);
119+
120+
const ctx = (): any => ({
121+
request: { headers: { host: 'app.example.test' } },
122+
environmentId: 'platform',
123+
executionContext: { userId: 'u_member', tenantId: 'org_1', systemPermissions: [] },
124+
});
125+
126+
/** REST `POST /actions/:object/:action` — the console's click, the SDK's call. */
127+
const viaRest = async () => {
128+
const res: any = await dispatcher.handleActions(`/${OBJECT}/${ACTION.name}`, 'POST', {}, ctx());
129+
return res.response;
130+
};
131+
/** The real `/mcp` bridge's `runAction` — what the `run_action` tool calls. */
132+
const viaMcp = async () => {
133+
const bridge = (dispatcher as any).buildMcpBridge(ctx());
134+
try {
135+
return { value: await bridge.runAction(ACTION.name, { objectName: OBJECT }) };
136+
} catch (err: any) {
137+
return { err };
138+
}
139+
};
140+
return { events, rows, writes, viaRest, viaMcp };
141+
}
142+
143+
/** Both doors over one body: the REST answer, the MCP answer, and what each wrote. */
144+
async function viaBothDoors(handler: Handler) {
145+
const rest = makeRig(handler);
146+
const restRes = await rest.viaRest();
147+
const mcp = makeRig(handler);
148+
const mcpOut = await mcp.viaMcp();
149+
return { rest, restRes, mcp, mcpOut };
150+
}
151+
152+
/** The body's own result answered at both doors, every write applied once, both audit rows `succeeded`. */
153+
function expectBodyResultAnswered(run: Awaited<ReturnType<typeof viaBothDoors>>, result: unknown, writes: string[]) {
154+
expect(run.restRes.status, JSON.stringify(run.restRes.body)).toBe(200);
155+
expect(run.restRes.body.data).toEqual(result);
156+
expect(run.rest.writes).toEqual(writes);
157+
expect(run.mcpOut.err, String(run.mcpOut.err)).toBeUndefined();
158+
expect(run.mcpOut.value).toEqual({ ok: true, action: ACTION.name, objectName: OBJECT, result });
159+
expect(run.mcp.writes).toEqual(writes);
160+
for (const events of [run.rest.events, run.mcp.events]) {
161+
expect(events).toHaveLength(1);
162+
expect(events[0]).toMatchObject({ actionName: ACTION.name, outcome: 'succeeded' });
163+
}
164+
}
165+
166+
let errorLog: ReturnType<typeof vi.spyOn>;
167+
beforeAll(() => { errorLog = vi.spyOn(console, 'error').mockImplementation(() => {}); });
168+
afterAll(() => { errorLog.mockRestore(); });
169+
170+
describe('[#28861] ctx.engine: a write that landed under a failing roll-up answers its success in the body', () => {
171+
it('insert answers the new id, and the body runs on to its own result', async () => {
172+
const run = await viaBothDoors(async (ctx) => {
173+
const created = await ctx.engine.insert(CHILD, { id: 'v1', title: 'visit' });
174+
return { created, after: 'insert' };
175+
});
176+
expectBodyResultAnswered(run, { created: { id: 'v1' }, after: 'insert' }, ['insert:v1']);
177+
});
178+
179+
it('update resolves, and the body runs on to its own result', async () => {
180+
const run = await viaBothDoors(async (ctx) => {
181+
await ctx.engine.update(CHILD, 'v0', { title: 'revisited' });
182+
return { after: 'update' };
183+
});
184+
expectBodyResultAnswered(run, { after: 'update' }, ['update:v0']);
185+
expect(run.rest.rows.get('v0')).toEqual({ id: 'v0', title: 'revisited' });
186+
});
187+
188+
it('a multi-id delete deletes every id, each landed delete answered as the success it is', async () => {
189+
const run = await viaBothDoors(async (ctx) => {
190+
await ctx.engine.delete(CHILD, ['v0', 'v1']);
191+
return { after: 'delete' };
192+
});
193+
expectBodyResultAnswered(run, { after: 'delete' }, ['delete:v0', 'delete:v1']);
194+
});
195+
});
196+
197+
describe('[#28861] ctx.api: a write that landed under a failing roll-up answers its success in the body', () => {
198+
it('object(x).insert answers the stored record, and the body runs on to its own result', async () => {
199+
const run = await viaBothDoors(async (ctx) => {
200+
const created = await ctx.api.object(CHILD).insert({ id: 'v2', title: 'via api' });
201+
return { created, after: 'insert' };
202+
});
203+
expectBodyResultAnswered(run, { created: { id: 'v2', title: 'via api' }, after: 'insert' }, ['insert:v2']);
204+
});
205+
206+
it('object(x).update and object(x).delete answer what the engine answers, and the body runs on', async () => {
207+
const run = await viaBothDoors(async (ctx) => {
208+
const updated = await ctx.api.object(CHILD).update({ title: 'via api' }, { where: { id: 'v0' } });
209+
const deleted = await ctx.api.object(CHILD).deleteById('v0');
210+
return { updated, deleted, after: 'delete' };
211+
});
212+
expectBodyResultAnswered(
213+
run,
214+
{ updated: { id: 'v0', title: 'via api' }, deleted: { id: 'v0' }, after: 'delete' },
215+
['update:v0', 'delete:v0'],
216+
);
217+
});
218+
219+
it('a context the api derives answers the same way (sudo)', async () => {
220+
const run = await viaBothDoors(async (ctx) => {
221+
const created = await ctx.api.sudo().object(CHILD).insert({ id: 'v3', title: 'elevated' });
222+
return { created };
223+
});
224+
expectBodyResultAnswered(run, { created: { id: 'v3', title: 'elevated' } }, ['insert:v3']);
225+
});
226+
});
227+
228+
describe('[#28861] a refusal raised before the write is stored reaches the body exactly as before (NEGATIVE PIN)', () => {
229+
it.each([
230+
['ctx.engine.insert', (ctx: any) => ctx.engine.insert(CHILD, { id: 'x', title: 'refused' })],
231+
['ctx.engine.update', (ctx: any) => ctx.engine.update(CHILD, 'refused', { title: 'x' })],
232+
['ctx.engine.delete', (ctx: any) => ctx.engine.delete(CHILD, 'refused')],
233+
['ctx.api insert', (ctx: any) => ctx.api.object(CHILD).insert({ id: 'x', title: 'refused' })],
234+
['ctx.api deleteById', (ctx: any) => ctx.api.object(CHILD).deleteById('refused')],
235+
])('%s: the body is handed the refusal, the doors answer it, nothing written', async (_label, write) => {
236+
const seen: string[] = [];
237+
const run = await viaBothDoors(async (ctx) => {
238+
try {
239+
await write(ctx);
240+
} catch (e: any) {
241+
seen.push(e?.code);
242+
throw e;
243+
}
244+
return { never: true };
245+
});
246+
expect(seen).toEqual(['PERMISSION_DENIED', 'PERMISSION_DENIED']);
247+
expect(run.restRes.status).toBe(403);
248+
expect(run.restRes.body.error.code).toBe('PERMISSION_DENIED');
249+
expect(run.mcpOut.err?.code).toBe('PERMISSION_DENIED');
250+
expect(run.rest.writes).toEqual([]);
251+
expect(run.mcp.writes).toEqual([]);
252+
expect(run.mcp.events.map((e) => e.outcome)).toEqual(['failed']);
253+
});
254+
});
255+
256+
describe('[#28861] the doors read a write\'s attached answer on the declarative arm only (NEGATIVE PIN)', () => {
257+
/** A body that throws a refusal carrying a WRITE's data answer — never the action's own result. */
258+
const carrying = () => withEarnedAnswer(
259+
new SummaryRecomputeError(FAILURES as any, { id: 'v9' }),
260+
{ object: CHILD, id: 'v9', record: { id: 'v9', title: 'a write answer' } },
261+
);
262+
/** The same refusal with nothing attached: what the doors answer for a body's failure. */
263+
const bare = () => new SummaryRecomputeError(FAILURES as any, { id: 'v9' });
264+
265+
it('REST answers the body\'s failure, never the attached write answer as the action\'s result', async () => {
266+
const carried = await viaBothDoors(async () => { throw carrying(); });
267+
const control = await viaBothDoors(async () => { throw bare(); });
268+
expect(control.restRes.status).not.toBe(200);
269+
expect(carried.restRes.status).toBe(control.restRes.status);
270+
expect(carried.restRes.body).toEqual(control.restRes.body);
271+
expect(JSON.stringify(carried.restRes.body)).not.toContain('a write answer');
272+
expect(carried.rest.events.map((e) => e.outcome)).toEqual(control.rest.events.map((e) => e.outcome));
273+
});
274+
275+
it('the MCP bridge throws the refusal with no answer attached, and the audit row says failed', async () => {
276+
const carried = await viaBothDoors(async () => { throw carrying(); });
277+
expect(carried.mcpOut.value).toBeUndefined();
278+
expect(carried.mcpOut.err?.code).toBe('ERR_SUMMARY_RECOMPUTE');
279+
expect(earnedAnswerOf(carried.mcpOut.err)).toBeUndefined();
280+
expect(carried.mcp.events).toHaveLength(1);
281+
expect(carried.mcp.events[0]).toMatchObject({ actionName: ACTION.name, outcome: 'failed' });
282+
});
283+
});
284+
285+
describe('[#28861] the stale column is said, at error', () => {
286+
it('once per field per process', () => {
287+
const lines = errorLog.mock.calls.map((c: unknown[]) => String(c[0])).filter((l: string) => l.includes('could not be recomputed'));
288+
expect(lines).toHaveLength(1);
289+
expect(lines[0]).toContain(`"${OBJECT}.visit_count"`);
290+
expect(lines[0]).toContain(`"${CHILD}"`);
291+
});
292+
});

0 commit comments

Comments
 (0)