Skip to content

Commit 6380c4d

Browse files
committed
fix(runtime,service-automation): a body or flow node write that landed under a failing roll-up answers its success
ctx.engine, ctx.api and every sandboxed body's ctx.api answer a write the engine stored, whose parent roll-up could not be recomputed after it, with the write's own result; the flow record nodes answer it as the node's success. The stale column is logged once per field at error. A refusal before the write is unchanged. The REST action door and the MCP run_action door read an attached answer on the declarative-update arm only. Claude-Session: https://claude.ai/code/session_01ADHkmQEc6KnPaxi9d3soLZ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 897a4c5 commit 6380c4d

6 files changed

Lines changed: 250 additions & 31 deletions

File tree

‎packages/runtime/src/action-execution.ts‎

Lines changed: 67 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,11 @@ import {
8888
reconcileActionRegistrations as reconcileActionRegistrationsPure,
8989
resolveActionHandlerKeys,
9090
standaloneActionOwnerKey,
91+
SummaryRecomputeError,
9192
} from '@objectstack/objectql';
9293
import { earnedAnswerOf, staleSummaryRefusalOrThrow, withEarnedAnswer, type SummaryRecomputeRefusal } from '@objectstack/types';
94+
// [#28861] A landed write answers its success to the action handler's code.
95+
import { answerLandedWritesDespiteStaleSummary, landedWriteAnswer } from './landed-write-answer.js';
9396

9497
// [ADR-0110] The addressing vocabulary and the D5 reconciliation moved to
9598
// @objectstack/objectql (the engine owns the map they describe, and its
@@ -3130,23 +3133,35 @@ export function buildActionExecutionContext(ec: any): Record<string, unknown> {
31303133
* hash keyed) and never the stored row. [#21594] An action BODY's API is built
31313134
* over this one by the sandbox (`buildSandboxApi`), whose body layers refuse a
31323135
* family read or write before it reaches this seam.
3136+
*
3137+
* [#28861] A write through it that the engine stored, whose parent roll-up
3138+
* could not be recomputed after it, answers the write's success to the
3139+
* handler (`landed-write-answer.ts`), on this context and every one it
3140+
* derives. That layer sits beneath the reader seam, so the answer is served
3141+
* like any write's return.
31333142
*/
31343143
export function buildActionApi(_deps: ActionExecutionDeps, ql: any, ec: any): any | undefined {
31353144
if (!ql || typeof ql.createContext !== 'function') return undefined;
3145+
const served = (scoped: unknown) =>
3146+
serveStoredMetadataReadsThrough(answerLandedWritesDespiteStaleSummary(scoped, ACTION_API_SURFACE), ql);
31363147
try {
3137-
return serveStoredMetadataReadsThrough(ql.createContext(buildActionExecutionContext(ec)), ql);
3148+
return served(ql.createContext(buildActionExecutionContext(ec)));
31383149
} catch {
31393150
// A malformed caller envelope must not sink the action — fall back to
31403151
// the bare elevated context (the same shape hooks default to), marked
31413152
// as the body's elevation like every other (#25653).
31423153
try {
3143-
return serveStoredMetadataReadsThrough(ql.createContext(buildActionExecutionContext(undefined)), ql);
3154+
return served(ql.createContext(buildActionExecutionContext(undefined)));
31443155
} catch {
31453156
return undefined;
31463157
}
31473158
}
31483159
}
31493160

3161+
/** [#28861] The surfaces the stale-column line names, for an action handler's two data handles. */
3162+
const ACTION_API_SURFACE = 'action ctx.api';
3163+
const ACTION_ENGINE_SURFACE = 'action ctx.engine';
3164+
31503165
/**
31513166
* The sentence a caller still on the WITHDRAWN bare-filter shape must read
31523167
* (#15124). Exported because the wording IS the contract here: this refusal is
@@ -3234,17 +3249,31 @@ function assertActionEngineFindEnvelope(object: string, query: Record<string, un
32343249
* use. Every call carries {@link buildActionExecutionContext} so `ctx.engine`
32353250
* and `ctx.api` write under the SAME identity (#3914); passing `ec` is what
32363251
* separates a trusted write from a context-less one.
3252+
*
3253+
* [#28861] A write the engine stored, whose parent roll-up could not be
3254+
* recomputed after it, answers the write's success here, as on `ctx.api`
3255+
* ({@link landedWriteAnswer}): the handler's next line runs. Every other
3256+
* throw, a refusal before the write among them, reaches the handler as is.
32373257
*/
32383258
export function buildActionEngineFacade(_deps: ActionExecutionDeps, ql: any, ec?: any): any {
32393259
const context = buildActionExecutionContext(ec);
32403260
return {
32413261
async insert(object: string, data: Record<string, unknown>): Promise<{ id: string }> {
3242-
const res = await ql.insert(object, data, { context });
3262+
let res: unknown;
3263+
try {
3264+
res = await ql.insert(object, data, { context });
3265+
} catch (e) {
3266+
res = landedWriteAnswer(e, object, ACTION_ENGINE_SURFACE);
3267+
}
32433268
const id = (res && (res as any).id) ?? (data as any).id;
32443269
return { id };
32453270
},
32463271
async update(object: string, id: string, data: Record<string, unknown>): Promise<void> {
3247-
await ql.update(object, data, { where: { id }, context });
3272+
try {
3273+
await ql.update(object, data, { where: { id }, context });
3274+
} catch (e) {
3275+
landedWriteAnswer(e, object, ACTION_ENGINE_SURFACE);
3276+
}
32483277
},
32493278
// Both spellings are DECLARED contract (#15117), not a tolerance: the
32503279
// spec's `ActionEngineFacade.delete` takes `string | string[]`.
@@ -3263,10 +3292,17 @@ export function buildActionEngineFacade(_deps: ActionExecutionDeps, ql: any, ec?
32633292
// it pulls the runtime back onto the contract that is already on the
32643293
// record, here, in the spec member doc, and in the `never a null id`
32653294
// pin at `packages/spec/src/ui/action-params.test.ts`.
3295+
//
3296+
// [#28861] Each id's landed delete is answered on its own, so a stale
3297+
// roll-up after one id's delete does not leave the later ids undeleted.
32663298
async delete(object: string, idOrIds: string | string[]): Promise<void> {
32673299
const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
32683300
for (const id of ids) {
3269-
await ql.delete(object, { where: { id }, context });
3301+
try {
3302+
await ql.delete(object, { where: { id }, context });
3303+
} catch (e) {
3304+
landedWriteAnswer(e, object, ACTION_ENGINE_SURFACE);
3305+
}
32703306
}
32713307
},
32723308
// [#15124] The ENVELOPE goes through — this arm no longer builds one.
@@ -4037,15 +4073,39 @@ export async function invokeBusinessAction(deps: ActionExecutionDeps,
40374073
} catch (err) {
40384074
// [#28856] A refusal carrying the action's answer is answered as the
40394075
// success it is by the `run_action` tool, so the row records that.
4040-
await recordActionInvocation(deps, requestContext, envId, earnedAnswerOf(err)
4076+
//
4077+
// [#28861] Read on the declarative-update arm only: that arm composes
4078+
// the ACTION's answer and attaches it (`dispatchAdmittedBusinessAction`).
4079+
// Any other arm's refusal can carry only a WRITE's data answer — a
4080+
// handler that let out a refusal a data door attached its answer to —
4081+
// and the action that threw has no result. It is answered as the
4082+
// failure it is, and leaves this door with nothing attached, so the
4083+
// `run_action` tool, which reads every throw, cannot relay it either.
4084+
const declarative = isDeclarativeUpdateAction(action);
4085+
await recordActionInvocation(deps, requestContext, envId, declarative && earnedAnswerOf(err)
40414086
? { ...invocation, outcome: 'succeeded' }
40424087
: { ...invocation, outcome: 'failed', ...actionInvocationFailure(err) });
4043-
throw err;
4088+
throw declarative ? err : withoutWriteAnswer(err);
40444089
}
40454090
await recordActionInvocation(deps, requestContext, envId, { ...invocation, outcome: 'succeeded' });
40464091
return answer;
40474092
}
40484093

4094+
/**
4095+
* [#28861] `err` with no write answer attached: a stale-roll-up refusal a data
4096+
* door attached its answer to comes back as the same refusal — objectql's
4097+
* class, `failures`, `written`, message and stack — with nothing attached;
4098+
* every other value is returned as is. For a non-declarative arm's throw,
4099+
* whose attached answer is a write's, never the action's.
4100+
*/
4101+
function withoutWriteAnswer(err: unknown): unknown {
4102+
if (earnedAnswerOf(err) === undefined) return err;
4103+
const stale = err as SummaryRecomputeRefusal;
4104+
const bare = new SummaryRecomputeError([...(stale.failures ?? [])] as SummaryRecomputeError['failures'], stale.written);
4105+
if (typeof stale.stack === 'string') bare.stack = stale.stack;
4106+
return bare;
4107+
}
4108+
40494109
/**
40504110
* The MCP `run_action` dispatch, once every admission gate in
40514111
* {@link invokeBusinessAction} has passed: the declarative update, the

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1071,7 +1071,14 @@ async function dispatchAdmittedRestAction(
10711071
// [#28856] An action whose write landed under a failing roll-up answers
10721072
// the result the runtime composed and attached (`executeDeclarativeUpdateAction`),
10731073
// as when the recompute succeeds; the stale column is logged once.
1074-
const earned = earnedAnswerOf(err);
1074+
//
1075+
// [#28861] Read on the declarative-update arm only: that arm's refusal
1076+
// carries the ACTION's result. Any other arm's can carry only a WRITE's
1077+
// data answer — a handler that let out a refusal a data door attached
1078+
// its answer to — and the action that threw has no result, so it is
1079+
// answered below as the failure it is. (A handler's own `ctx.engine` /
1080+
// `ctx.api` writes answer a landed write's success and never throw it.)
1081+
const earned = actionExec.isDeclarativeUpdateAction(actionDef) ? earnedAnswerOf(err) : undefined;
10751082
if (earned) {
10761083
const log = deps.logger && typeof deps.logger.error === 'function'
10771084
? (line: string) => deps.logger.error(`[HttpDispatcher] ${line}`)
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#28861] A write an author's code makes, which the engine STORED, answers its
5+
* own success to that code — even when a parent's roll-up summary could not be
6+
* recomputed after it (seat ruling 6570987196 on #28861).
7+
*
8+
* ## The case
9+
*
10+
* The engine reports it as objectql's `SummaryRecomputeError`
11+
* (`ERR_SUMMARY_RECOMPUTE`, "the triggering records WERE written"), carrying as
12+
* `written` the result the call returns when every roll-up recomputes. The
13+
* data doors and the MCP tools answer it as the write's success (#28781,
14+
* #28843, #28854, #28882). The write surfaces an author's code holds handed it
15+
* straight in: the body's next line never ran, its own result never existed,
16+
* and the action, hook or job reported a failure for a write that had landed,
17+
* so a caller that retried wrote it twice. No transaction wraps a body, so its
18+
* earlier writes stayed committed either way.
19+
*
20+
* ## The answer
21+
*
22+
* The `written` result, returned as the call's own answer — exactly what the
23+
* same write answers on a healthy recompute, nothing added — with the stale
24+
* column said once per field per process at `error`, in the line the doors
25+
* log (`staleSummaryAnswerLines`). Every other error, a refusal raised before
26+
* the write was stored among them, is rethrown unchanged.
27+
*
28+
* The surfaces, each built here or calling in here:
29+
* - `ctx.engine` in an action handler (`buildActionEngineFacade`);
30+
* - `ctx.api` in an action handler (`buildActionApi`, objectql's
31+
* `createContext`), and every context it derives;
32+
* - a sandboxed hook, action or job body's `ctx.api`, whatever source the
33+
* sandbox builds it from (`buildSandboxApi`, `sandbox/body-runner.ts`).
34+
*
35+
* The flow record nodes answer the same refusal the same way in
36+
* `@objectstack/service-automation` (`builtin/crud-nodes.ts`).
37+
*
38+
* ⛔ Not in the engine, and not in objectql's `ScopedContext`: a bulk caller
39+
* (the seed loader, the import runner) reads the refusal as "written, with a
40+
* stale summary" and reports that in its own result, and platform code holding
41+
* a `HookContext.api` reads it as before. The ruling covers what an author's
42+
* code holds, so the answer is given where that surface is built.
43+
*/
44+
45+
import { staleSummaryAnswerLines, staleSummaryRefusalOrThrow } from '@objectstack/types';
46+
47+
import { deriveThroughSeam, WRITE_RETURN_VERBS } from './stored-metadata-reader-seam.js';
48+
49+
/**
50+
* A write's `catch` on an author-visible surface: the stale-roll-up refusal
51+
* answers the result the write earned (its `written`), the stale column said
52+
* at `error` under `surface`; every other error is rethrown unchanged.
53+
*/
54+
export function landedWriteAnswer(e: unknown, object: string | undefined, surface: string): any {
55+
const stale = staleSummaryRefusalOrThrow(e);
56+
for (const line of staleSummaryAnswerLines(stale, object)) console.error(`[${surface}] ${line}`);
57+
return stale.written;
58+
}
59+
60+
/** Marks a scoped API whose landed writes are already answered, so a second wrap is a no-op. */
61+
const LANDED_WRITES_ANSWERED = Symbol.for('objectstack.runtime.landedWritesAnswered');
62+
63+
/** One repository, every write verb answering its landed write; every other member handed through. */
64+
function answerRepositoryLandedWrites(objectName: string, repo: unknown, surface: string): unknown {
65+
if (repo === null || typeof repo !== 'object') return repo;
66+
return new Proxy(repo as Record<PropertyKey, unknown>, {
67+
get(target, prop) {
68+
const value = Reflect.get(target, prop, target);
69+
if (typeof value !== 'function') return value;
70+
if (!WRITE_RETURN_VERBS.has(prop)) return value.bind(target);
71+
return async (...args: unknown[]) => {
72+
try {
73+
return await value.apply(target, args);
74+
} catch (e) {
75+
return landedWriteAnswer(e, objectName, surface);
76+
}
77+
};
78+
},
79+
});
80+
}
81+
82+
/**
83+
* The scoped data API an author's code holds (`ctx.api`), with every
84+
* repository's write answering a landed write's success
85+
* ({@link landedWriteAnswer}), on `api` and every context it derives
86+
* (`object(name)`, `sudo()`, `withRunAs(...)`, a `transaction(fn)` callback's
87+
* context, the `ctx` `beginTransaction()` returns). Everything else is the same
88+
* object, by delegation.
89+
*
90+
* Wrap it BENEATH the stored-metadata reader seam, so the result it answers is
91+
* served by that seam like any write's return. Idempotent; a value that is not
92+
* an object is returned as is.
93+
*/
94+
export function answerLandedWritesDespiteStaleSummary<T>(api: T, surface: string): T {
95+
return deriveThroughSeam(api, LANDED_WRITES_ANSWERED, (name, repo) => answerRepositoryLandedWrites(name, repo, surface));
96+
}

‎packages/runtime/src/sandbox/body-runner.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ import {
6565
type FormulaServingChannel,
6666
} from '@objectstack/objectql';
6767
import { refuseStoredMetadataBodyReads, refuseStoredMetadataBodyWrites } from '../stored-metadata-reader-seam.js';
68+
import { answerLandedWritesDespiteStaleSummary } from '../landed-write-answer.js';
6869
import { isStoredMetadataBodyObject } from '@objectstack/spec/kernel';
6970
import {
7071
isWildcardHookTarget,
@@ -1153,10 +1154,19 @@ function buildEngineRepoFacade(ql: any, objectName: string, context?: any) {
11531154
* body's, and is served by the reader-context seam
11541155
* (`serveStoredMetadataReadsThrough`) with its writes kept (deployer code,
11551156
* outside the boundary).
1157+
*
1158+
* [#28861] Beneath both refusals, every body face's write that the engine
1159+
* stored, whose parent roll-up could not be recomputed after it, answers the
1160+
* write's success in the VM (`landed-write-answer.ts`), whatever source below
1161+
* the API is built from: the body runs on to its own result. An action's
1162+
* host-built `api` already answers so (`buildActionApi`); the layer is
1163+
* idempotent.
11561164
*/
11571165
function buildSandboxApi(engineCtx: any, ql: any, errLabel: string) {
11581166
return refuseStoredMetadataBodyWrites(
1159-
refuseStoredMetadataBodyReads(buildSandboxApiSource(engineCtx, ql, errLabel)),
1167+
refuseStoredMetadataBodyReads(
1168+
answerLandedWritesDespiteStaleSummary(buildSandboxApiSource(engineCtx, ql, errLabel), errLabel),
1169+
),
11601170
);
11611171
}
11621172

‎packages/runtime/src/stored-metadata-reader-seam.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -229,8 +229,11 @@ async function serveStoredMetadataWriteReturn<A>(object: string, answer: A, engi
229229
const ROW_SERVING_READS: ReadonlySet<PropertyKey> = new Set(['find', 'findOne', 'aggregate']);
230230
/** The verb whose answer is a number: guarded against the evaluate oracle, nothing to serve. */
231231
const COUNT_READ: PropertyKey = 'count';
232-
/** The write verbs whose RETURN can carry family content (every alias ObjectRepository exposes). */
233-
const WRITE_RETURN_VERBS: ReadonlySet<PropertyKey> = new Set([
232+
/**
233+
* The write verbs whose RETURN can carry family content (every alias ObjectRepository exposes).
234+
* [#28861] Also the verbs whose landed write `landed-write-answer.ts` answers: one list of what a write is.
235+
*/
236+
export const WRITE_RETURN_VERBS: ReadonlySet<PropertyKey> = new Set([
234237
'insert', 'create', 'update', 'updateById', 'upsert', 'delete', 'deleteById', 'updateMany', 'deleteMany',
235238
]);
236239

@@ -401,9 +404,10 @@ export function refuseStoredMetadataBodyReads<T>(api: T): T {
401404
* `object(name)`, `sudo()`, `withRunAs(...)`, the context a `transaction(fn)`
402405
* callback receives, and the `ctx` `beginTransaction()` returns — with each
403406
* repository passed through `wrapRepository`. One definition of what a scoped
404-
* API can derive, so neither layer can leave a route around it.
407+
* API can derive, so neither layer can leave a route around it. [#28861] The
408+
* landed-write layer (`landed-write-answer.ts`) walks it too.
405409
*/
406-
function deriveThroughSeam<T>(
410+
export function deriveThroughSeam<T>(
407411
api: T,
408412
marker: symbol,
409413
wrapRepository: (name: string, repo: unknown) => unknown,

0 commit comments

Comments
 (0)