|
| 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 { ScopedContext, SummaryRecomputeError } from '@objectstack/objectql'; |
| 42 | +import { earnedAnswerOf, withEarnedAnswer } from '@objectstack/types'; |
| 43 | + |
| 44 | +import { HttpDispatcher } from './http-dispatcher.js'; |
| 45 | + |
| 46 | +const OBJECT = 'stv_account'; |
| 47 | +const CHILD = 'stv_visit'; |
| 48 | +const ACTION = { |
| 49 | + name: 'log_visit', label: 'Log visit', objectName: OBJECT, type: 'script', target: 'logVisit', |
| 50 | + ai: { exposed: true, description: 'Log a visit.' }, |
| 51 | +}; |
| 52 | + |
| 53 | +/** One parent whose roll-up could not be recomputed, as the engine names it. */ |
| 54 | +const FAILURES = [{ childObject: CHILD, parentObject: OBJECT, parentId: 'a1', field: 'visit_count', error: new Error('sum over text') }]; |
| 55 | + |
| 56 | +type Handler = (ctx: any) => Promise<unknown>; |
| 57 | + |
| 58 | +/** |
| 59 | + * The dispatcher over an engine whose `insert` / `update` / `delete` apply the |
| 60 | + * write, then report the stale roll-up — or refuse before writing anything |
| 61 | + * when the payload or the id says `refused`. `handler` is the action body. |
| 62 | + */ |
| 63 | +function makeRig(handler: Handler) { |
| 64 | + const events: any[] = []; |
| 65 | + const audit = { recordActionInvocation: vi.fn(async (e: any) => { events.push(e); }) }; |
| 66 | + const rows = new Map<string, Record<string, unknown>>([['v0', { id: 'v0', title: 'old' }]]); |
| 67 | + const writes: string[] = []; |
| 68 | + const refuse = (object: string) => |
| 69 | + Object.assign(new Error(`You do not have permission to write ${object}`), { code: 'PERMISSION_DENIED', status: 403 }); |
| 70 | + |
| 71 | + const objectDef = { name: OBJECT, fields: { name: { type: 'text' } }, actions: [ACTION] }; |
| 72 | + const schemaOf = (n: string) => (n === OBJECT ? objectDef : undefined); |
| 73 | + const ql: any = { |
| 74 | + executeAction: vi.fn(async (object: string, key: string, ctx: any) => { |
| 75 | + if (object === OBJECT && key === ACTION.target) return handler(ctx); |
| 76 | + throw new Error(`Action '${key}' on object '${object}' not found`); |
| 77 | + }), |
| 78 | + getSchema: schemaOf, |
| 79 | + registry: { getObject: schemaOf, getItem: () => undefined }, |
| 80 | + find: vi.fn(async () => []), |
| 81 | + insert: vi.fn(async (object: string, data: any) => { |
| 82 | + if (data?.title === 'refused') throw refuse(object); |
| 83 | + const row = { ...data }; |
| 84 | + rows.set(String(data.id), row); |
| 85 | + writes.push(`insert:${data.id}`); |
| 86 | + throw new SummaryRecomputeError(FAILURES as any, { ...row }); |
| 87 | + }), |
| 88 | + update: vi.fn(async (object: string, data: any, options?: any) => { |
| 89 | + const id = String(options?.where?.id); |
| 90 | + if (id === 'refused') throw refuse(object); |
| 91 | + const row = { ...(rows.get(id) ?? { id }), ...data }; |
| 92 | + rows.set(id, row); |
| 93 | + writes.push(`update:${id}`); |
| 94 | + throw new SummaryRecomputeError(FAILURES as any, { ...row }); |
| 95 | + }), |
| 96 | + delete: vi.fn(async (object: string, options?: any) => { |
| 97 | + const id = String(options?.where?.id); |
| 98 | + if (id === 'refused') throw refuse(object); |
| 99 | + rows.delete(id); |
| 100 | + writes.push(`delete:${id}`); |
| 101 | + throw new SummaryRecomputeError(FAILURES as any, { id }); |
| 102 | + }), |
| 103 | + createContext: (ec: any) => new ScopedContext(ec, ql), |
| 104 | + }; |
| 105 | + const metadata: any = { |
| 106 | + load: vi.fn(async () => null), |
| 107 | + loadDiagnosed: vi.fn(async () => ({ data: null, degraded: false, errors: [] })), |
| 108 | + loadMany: vi.fn(async () => []), |
| 109 | + listObjects: vi.fn(async () => [objectDef]), |
| 110 | + getObject: vi.fn(async (n: string) => schemaOf(n)), |
| 111 | + }; |
| 112 | + const services: Record<string, unknown> = { objectql: ql, data: ql, metadata, audit }; |
| 113 | + const resolve = (n: string) => services[n] ?? null; |
| 114 | + const kernel: any = { getService: resolve, getServiceAsync: async (n: string) => resolve(n), context: { getService: resolve } }; |
| 115 | + const dispatcher = new HttpDispatcher(kernel); |
| 116 | + |
| 117 | + const ctx = (): any => ({ |
| 118 | + request: { headers: { host: 'app.example.test' } }, |
| 119 | + environmentId: 'platform', |
| 120 | + executionContext: { userId: 'u_member', tenantId: 'org_1', systemPermissions: [] }, |
| 121 | + }); |
| 122 | + |
| 123 | + /** REST `POST /actions/:object/:action` — the console's click, the SDK's call. */ |
| 124 | + const viaRest = async () => { |
| 125 | + const res: any = await dispatcher.handleActions(`/${OBJECT}/${ACTION.name}`, 'POST', {}, ctx()); |
| 126 | + return res.response; |
| 127 | + }; |
| 128 | + /** The real `/mcp` bridge's `runAction` — what the `run_action` tool calls. */ |
| 129 | + const viaMcp = async () => { |
| 130 | + const bridge = (dispatcher as any).buildMcpBridge(ctx()); |
| 131 | + try { |
| 132 | + return { value: await bridge.runAction(ACTION.name, { objectName: OBJECT }) }; |
| 133 | + } catch (err: any) { |
| 134 | + return { err }; |
| 135 | + } |
| 136 | + }; |
| 137 | + return { events, rows, writes, viaRest, viaMcp }; |
| 138 | +} |
| 139 | + |
| 140 | +/** Both doors over one body: the REST answer, the MCP answer, and what each wrote. */ |
| 141 | +async function viaBothDoors(handler: Handler) { |
| 142 | + const rest = makeRig(handler); |
| 143 | + const restRes = await rest.viaRest(); |
| 144 | + const mcp = makeRig(handler); |
| 145 | + const mcpOut = await mcp.viaMcp(); |
| 146 | + return { rest, restRes, mcp, mcpOut }; |
| 147 | +} |
| 148 | + |
| 149 | +/** The body's own result answered at both doors, every write applied once, both audit rows `succeeded`. */ |
| 150 | +function expectBodyResultAnswered(run: Awaited<ReturnType<typeof viaBothDoors>>, result: unknown, writes: string[]) { |
| 151 | + expect(run.restRes.status, JSON.stringify(run.restRes.body)).toBe(200); |
| 152 | + expect(run.restRes.body.data).toEqual(result); |
| 153 | + expect(run.rest.writes).toEqual(writes); |
| 154 | + expect(run.mcpOut.err, String(run.mcpOut.err)).toBeUndefined(); |
| 155 | + expect(run.mcpOut.value).toEqual({ ok: true, action: ACTION.name, objectName: OBJECT, result }); |
| 156 | + expect(run.mcp.writes).toEqual(writes); |
| 157 | + for (const events of [run.rest.events, run.mcp.events]) { |
| 158 | + expect(events).toHaveLength(1); |
| 159 | + expect(events[0]).toMatchObject({ actionName: ACTION.name, outcome: 'succeeded' }); |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +let errorLog: ReturnType<typeof vi.spyOn>; |
| 164 | +beforeAll(() => { errorLog = vi.spyOn(console, 'error').mockImplementation(() => {}); }); |
| 165 | +afterAll(() => { errorLog.mockRestore(); }); |
| 166 | + |
| 167 | +describe('[#28861] ctx.engine: a write that landed under a failing roll-up answers its success in the body', () => { |
| 168 | + it('insert answers the new id, and the body runs on to its own result', async () => { |
| 169 | + const run = await viaBothDoors(async (ctx) => { |
| 170 | + const created = await ctx.engine.insert(CHILD, { id: 'v1', title: 'visit' }); |
| 171 | + return { created, after: 'insert' }; |
| 172 | + }); |
| 173 | + expectBodyResultAnswered(run, { created: { id: 'v1' }, after: 'insert' }, ['insert:v1']); |
| 174 | + }); |
| 175 | + |
| 176 | + it('update resolves, and the body runs on to its own result', async () => { |
| 177 | + const run = await viaBothDoors(async (ctx) => { |
| 178 | + await ctx.engine.update(CHILD, 'v0', { title: 'revisited' }); |
| 179 | + return { after: 'update' }; |
| 180 | + }); |
| 181 | + expectBodyResultAnswered(run, { after: 'update' }, ['update:v0']); |
| 182 | + expect(run.rest.rows.get('v0')).toEqual({ id: 'v0', title: 'revisited' }); |
| 183 | + }); |
| 184 | + |
| 185 | + it('a multi-id delete deletes every id, each landed delete answered as the success it is', async () => { |
| 186 | + const run = await viaBothDoors(async (ctx) => { |
| 187 | + await ctx.engine.delete(CHILD, ['v0', 'v1']); |
| 188 | + return { after: 'delete' }; |
| 189 | + }); |
| 190 | + expectBodyResultAnswered(run, { after: 'delete' }, ['delete:v0', 'delete:v1']); |
| 191 | + }); |
| 192 | +}); |
| 193 | + |
| 194 | +describe('[#28861] ctx.api: a write that landed under a failing roll-up answers its success in the body', () => { |
| 195 | + it('object(x).insert answers the stored record, and the body runs on to its own result', async () => { |
| 196 | + const run = await viaBothDoors(async (ctx) => { |
| 197 | + const created = await ctx.api.object(CHILD).insert({ id: 'v2', title: 'via api' }); |
| 198 | + return { created, after: 'insert' }; |
| 199 | + }); |
| 200 | + expectBodyResultAnswered(run, { created: { id: 'v2', title: 'via api' }, after: 'insert' }, ['insert:v2']); |
| 201 | + }); |
| 202 | + |
| 203 | + it('object(x).update and object(x).delete answer what the engine answers, and the body runs on', async () => { |
| 204 | + const run = await viaBothDoors(async (ctx) => { |
| 205 | + const updated = await ctx.api.object(CHILD).update({ title: 'via api' }, { where: { id: 'v0' } }); |
| 206 | + const deleted = await ctx.api.object(CHILD).deleteById('v0'); |
| 207 | + return { updated, deleted, after: 'delete' }; |
| 208 | + }); |
| 209 | + expectBodyResultAnswered( |
| 210 | + run, |
| 211 | + { updated: { id: 'v0', title: 'via api' }, deleted: { id: 'v0' }, after: 'delete' }, |
| 212 | + ['update:v0', 'delete:v0'], |
| 213 | + ); |
| 214 | + }); |
| 215 | + |
| 216 | + it('a context the api derives answers the same way (sudo)', async () => { |
| 217 | + const run = await viaBothDoors(async (ctx) => { |
| 218 | + const created = await ctx.api.sudo().object(CHILD).insert({ id: 'v3', title: 'elevated' }); |
| 219 | + return { created }; |
| 220 | + }); |
| 221 | + expectBodyResultAnswered(run, { created: { id: 'v3', title: 'elevated' } }, ['insert:v3']); |
| 222 | + }); |
| 223 | +}); |
| 224 | + |
| 225 | +describe('[#28861] a refusal raised before the write is stored reaches the body exactly as before (NEGATIVE PIN)', () => { |
| 226 | + it.each([ |
| 227 | + ['ctx.engine.insert', (ctx: any) => ctx.engine.insert(CHILD, { id: 'x', title: 'refused' })], |
| 228 | + ['ctx.engine.update', (ctx: any) => ctx.engine.update(CHILD, 'refused', { title: 'x' })], |
| 229 | + ['ctx.engine.delete', (ctx: any) => ctx.engine.delete(CHILD, 'refused')], |
| 230 | + ['ctx.api insert', (ctx: any) => ctx.api.object(CHILD).insert({ id: 'x', title: 'refused' })], |
| 231 | + ['ctx.api deleteById', (ctx: any) => ctx.api.object(CHILD).deleteById('refused')], |
| 232 | + ])('%s: the body is handed the refusal, the doors answer it, nothing written', async (_label, write) => { |
| 233 | + const seen: string[] = []; |
| 234 | + const run = await viaBothDoors(async (ctx) => { |
| 235 | + try { |
| 236 | + await write(ctx); |
| 237 | + } catch (e: any) { |
| 238 | + seen.push(e?.code); |
| 239 | + throw e; |
| 240 | + } |
| 241 | + return { never: true }; |
| 242 | + }); |
| 243 | + expect(seen).toEqual(['PERMISSION_DENIED', 'PERMISSION_DENIED']); |
| 244 | + expect(run.restRes.status).toBe(403); |
| 245 | + expect(run.restRes.body.error.code).toBe('PERMISSION_DENIED'); |
| 246 | + expect(run.mcpOut.err?.code).toBe('PERMISSION_DENIED'); |
| 247 | + expect(run.rest.writes).toEqual([]); |
| 248 | + expect(run.mcp.writes).toEqual([]); |
| 249 | + expect(run.mcp.events.map((e) => e.outcome)).toEqual(['failed']); |
| 250 | + }); |
| 251 | +}); |
| 252 | + |
| 253 | +describe('[#28861] the doors read a write\'s attached answer on the declarative arm only (NEGATIVE PIN)', () => { |
| 254 | + /** A body that throws a refusal carrying a WRITE's data answer — never the action's own result. */ |
| 255 | + const carrying = () => withEarnedAnswer( |
| 256 | + new SummaryRecomputeError(FAILURES as any, { id: 'v9' }), |
| 257 | + { object: CHILD, id: 'v9', record: { id: 'v9', title: 'a write answer' } }, |
| 258 | + ); |
| 259 | + /** The same refusal with nothing attached: what the doors answer for a body's failure. */ |
| 260 | + const bare = () => new SummaryRecomputeError(FAILURES as any, { id: 'v9' }); |
| 261 | + |
| 262 | + it('REST answers the body\'s failure, never the attached write answer as the action\'s result', async () => { |
| 263 | + const carried = await viaBothDoors(async () => { throw carrying(); }); |
| 264 | + const control = await viaBothDoors(async () => { throw bare(); }); |
| 265 | + expect(control.restRes.status).not.toBe(200); |
| 266 | + expect(carried.restRes.status).toBe(control.restRes.status); |
| 267 | + expect(carried.restRes.body).toEqual(control.restRes.body); |
| 268 | + expect(JSON.stringify(carried.restRes.body)).not.toContain('a write answer'); |
| 269 | + expect(carried.rest.events.map((e) => e.outcome)).toEqual(control.rest.events.map((e) => e.outcome)); |
| 270 | + }); |
| 271 | + |
| 272 | + it('the MCP bridge throws the refusal with no answer attached, and the audit row says failed', async () => { |
| 273 | + const carried = await viaBothDoors(async () => { throw carrying(); }); |
| 274 | + expect(carried.mcpOut.value).toBeUndefined(); |
| 275 | + expect(carried.mcpOut.err?.code).toBe('ERR_SUMMARY_RECOMPUTE'); |
| 276 | + expect(earnedAnswerOf(carried.mcpOut.err)).toBeUndefined(); |
| 277 | + expect(carried.mcp.events).toHaveLength(1); |
| 278 | + expect(carried.mcp.events[0]).toMatchObject({ actionName: ACTION.name, outcome: 'failed' }); |
| 279 | + }); |
| 280 | +}); |
| 281 | + |
| 282 | +describe('[#28861] the stale column is said, at error', () => { |
| 283 | + it('once per field per process', () => { |
| 284 | + const lines = errorLog.mock.calls.map((c: unknown[]) => String(c[0])).filter((l: string) => l.includes('could not be recomputed')); |
| 285 | + expect(lines).toHaveLength(1); |
| 286 | + expect(lines[0]).toContain(`"${OBJECT}.visit_count"`); |
| 287 | + expect(lines[0]).toContain(`"${CHILD}"`); |
| 288 | + }); |
| 289 | +}); |
0 commit comments