|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#34672] A roll-up `summary` field is read-only on UPDATE whether or not the |
| 5 | + * author declared `readonly: true`. |
| 6 | + * |
| 7 | + * The engine computes a roll-up from its child rows and writes it through |
| 8 | + * `update()` under an `isSystem` context. Before this card the update's static |
| 9 | + * `readonly` strip read only the declared flag, so a person's `PATCH`, an |
| 10 | + * import with `writeMode: 'update'` or a predicate update stored the typed |
| 11 | + * value, and it was read downstream until the next child write recomputed it. |
| 12 | + * Now the update's schema view (`updateStaticReadonlySubject`) reads every |
| 13 | + * `summary` field as `readonly: true`. So the write is taken and reported as |
| 14 | + * `readonly`, and refused under `strictReadonlyWrites`, exactly as for a |
| 15 | + * roll-up the author did declare read-only (the control below). |
| 16 | + * |
| 17 | + * Kept as before, each pinned here: |
| 18 | + * - the roll-up recompute's own write (`isSystem`), and any other `isSystem` |
| 19 | + * write of the column; |
| 20 | + * - a caller's initial value on INSERT (seed data, a historical import), the |
| 21 | + * boundary the `summary` note on `RUNTIME_OWNED_FIELD_TYPES` draws. |
| 22 | + * |
| 23 | + * The import door, end to end over HTTP and SQLite: |
| 24 | + * `packages/rest/src/import-summary-update-lock-34672.test.ts`. |
| 25 | + */ |
| 26 | + |
| 27 | +import { describe, it, expect, beforeEach } from 'vitest'; |
| 28 | +import type { DroppedFieldsEvent } from '@objectstack/spec/data'; |
| 29 | +import { ObjectQL } from './engine.js'; |
| 30 | +import { summaryFieldsLockedOnUpdate } from './engine-top-level.js'; |
| 31 | +import { READONLY_FIELD_REJECTED_CODE } from './readonly-strict-errors.js'; |
| 32 | + |
| 33 | +function makeDriver() { |
| 34 | + const stores = new Map<string, Map<string, any>>(); |
| 35 | + const storeFor = (o: string) => { |
| 36 | + let s = stores.get(o); |
| 37 | + if (!s) { s = new Map(); stores.set(o, s); } |
| 38 | + return s; |
| 39 | + }; |
| 40 | + // Flat equality, `$and` and a field's `$in`: the shapes the roll-up |
| 41 | + // aggregate and the predicate update below send. Any other operator throws. |
| 42 | + const matches = (row: any, where: any): boolean => { |
| 43 | + if (!where || typeof where !== 'object') return true; |
| 44 | + return Object.entries(where).every(([k, v]) => { |
| 45 | + if (k === '$and') return (v as any[]).every((sub) => matches(row, sub)); |
| 46 | + if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); |
| 47 | + if (v && typeof v === 'object' && !Array.isArray(v)) { |
| 48 | + const ops = Object.keys(v); |
| 49 | + if (ops.length === 1 && ops[0] === '$in' && Array.isArray((v as any).$in)) return (v as any).$in.includes(row?.[k]); |
| 50 | + throw new Error(`fake driver: unsupported condition on ${k}: ${JSON.stringify(v)}`); |
| 51 | + } |
| 52 | + return row?.[k] === v; |
| 53 | + }); |
| 54 | + }; |
| 55 | + let n = 0; |
| 56 | + const driver: any = { |
| 57 | + name: 'memory', version: '0.0.0', supports: {}, |
| 58 | + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, |
| 59 | + async find(object: string, ast: any) { |
| 60 | + const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)); |
| 61 | + const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; |
| 62 | + return page.map((r) => ({ ...r })); |
| 63 | + }, |
| 64 | + async findOne(object: string, ast: any) { |
| 65 | + for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r }; |
| 66 | + return null; |
| 67 | + }, |
| 68 | + async create(object: string, data: Record<string, unknown>) { |
| 69 | + n += 1; |
| 70 | + const id = (data.id as string) ?? `r_${n}`; |
| 71 | + const row = { ...data, id }; |
| 72 | + storeFor(object).set(id, row); |
| 73 | + return { ...row }; |
| 74 | + }, |
| 75 | + async update(object: string, id: string, data: Record<string, unknown>) { |
| 76 | + const s = storeFor(object); |
| 77 | + const row = { ...s.get(id), ...data, id }; |
| 78 | + s.set(id, row); |
| 79 | + return { ...row }; |
| 80 | + }, |
| 81 | + async updateMany(object: string, ast: any, data: Record<string, unknown>) { |
| 82 | + const s = storeFor(object); |
| 83 | + let count = 0; |
| 84 | + for (const row of [...s.values()]) { |
| 85 | + if (!matches(row, ast?.where)) continue; |
| 86 | + s.set(row.id, { ...row, ...data, id: row.id }); |
| 87 | + count += 1; |
| 88 | + } |
| 89 | + return count; |
| 90 | + }, |
| 91 | + async delete(object: string, id: string) { return storeFor(object).delete(id); }, |
| 92 | + async count() { return 0; }, |
| 93 | + async bulkCreate(object: string, rows: Record<string, unknown>[]) { |
| 94 | + return Promise.all(rows.map((r) => this.create(object, r, undefined))); |
| 95 | + }, |
| 96 | + async bulkUpdate() { return []; }, async bulkDelete() {}, |
| 97 | + async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; }, |
| 98 | + async commit() {}, async rollback() {}, |
| 99 | + }; |
| 100 | + return { driver, storeFor }; |
| 101 | +} |
| 102 | + |
| 103 | +const silentLogger: any = (() => { |
| 104 | + const l: any = { debug() {}, info() {}, error() {}, trace() {}, fatal() {}, warn() {}, child() { return l; } }; |
| 105 | + return l; |
| 106 | +})(); |
| 107 | + |
| 108 | +/** A signed-in person: not the system principal. */ |
| 109 | +const PERSON = { userId: 'u_rep' } as any; |
| 110 | + |
| 111 | +async function rejection(p: Promise<unknown>): Promise<any> { |
| 112 | + try { |
| 113 | + await p; |
| 114 | + } catch (err) { |
| 115 | + return err; |
| 116 | + } |
| 117 | + throw new Error('expected the write to be refused, but it resolved'); |
| 118 | +} |
| 119 | + |
| 120 | +const ACCOUNT = { |
| 121 | + name: 'acct', |
| 122 | + fields: { |
| 123 | + name: { type: 'text' }, |
| 124 | + note: { type: 'text' }, |
| 125 | + // The card's shape: a roll-up with no `readonly`. |
| 126 | + order_total: { type: 'summary', summaryOperations: { object: 'ord', field: 'amount', function: 'sum' } }, |
| 127 | + // The control: the same roll-up, declared read-only by its author. |
| 128 | + order_total_ro: { type: 'summary', readonly: true, summaryOperations: { object: 'ord', field: 'amount', function: 'sum' } }, |
| 129 | + }, |
| 130 | +}; |
| 131 | + |
| 132 | +const ORDER = { |
| 133 | + name: 'ord', |
| 134 | + fields: { |
| 135 | + amount: { type: 'number' }, |
| 136 | + acct: { type: 'master_detail', reference: 'acct' }, |
| 137 | + }, |
| 138 | +}; |
| 139 | + |
| 140 | +const ROLL_UP: DroppedFieldsEvent = { object: 'acct', fields: ['order_total'], reason: 'readonly' }; |
| 141 | + |
| 142 | +describe('[#34672] a roll-up summary without readonly: true is read-only on update', () => { |
| 143 | + let engine: ObjectQL; |
| 144 | + let storeFor: ReturnType<typeof makeDriver>['storeFor']; |
| 145 | + |
| 146 | + beforeEach(async () => { |
| 147 | + engine = new ObjectQL({ logger: silentLogger }); |
| 148 | + const d = makeDriver(); |
| 149 | + storeFor = d.storeFor; |
| 150 | + engine.registerDriver(d.driver, true); |
| 151 | + await engine.init(); |
| 152 | + engine.registry.registerObject(ACCOUNT as any); |
| 153 | + engine.registry.registerObject(ORDER as any); |
| 154 | + const a = await engine.insert('acct', { id: 'a1', name: 'A' }, { context: PERSON } as any); |
| 155 | + const b = await engine.insert('acct', { id: 'a2', name: 'B' }, { context: PERSON } as any); |
| 156 | + await engine.insert('ord', { acct: a.id, amount: 10 }, { context: PERSON } as any); |
| 157 | + await engine.insert('ord', { acct: a.id, amount: 32 }, { context: PERSON } as any); |
| 158 | + await engine.insert('ord', { acct: b.id, amount: 5 }, { context: PERSON } as any); |
| 159 | + }); |
| 160 | + |
| 161 | + const acct = (id: string) => storeFor('acct').get(id); |
| 162 | + |
| 163 | + it('the seeded roll-ups are the engine\'s (the baseline every case reads)', () => { |
| 164 | + expect(acct('a1')).toMatchObject({ order_total: 42, order_total_ro: 42 }); |
| 165 | + expect(acct('a2')).toMatchObject({ order_total: 5, order_total_ro: 5 }); |
| 166 | + }); |
| 167 | + |
| 168 | + it('a by-id update (REST PATCH): the roll-up value is dropped and reported as readonly, the rest is written', async () => { |
| 169 | + const events: DroppedFieldsEvent[] = []; |
| 170 | + await engine.update( |
| 171 | + 'acct', |
| 172 | + { id: 'a1', note: 'typed', order_total: 90 }, |
| 173 | + { context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, |
| 174 | + ); |
| 175 | + expect(events).toEqual([ROLL_UP]); |
| 176 | + expect(acct('a1')).toMatchObject({ note: 'typed', order_total: 42 }); |
| 177 | + }); |
| 178 | + |
| 179 | + it('a predicate update (multi): the roll-up value is dropped from every matched row and reported once', async () => { |
| 180 | + const events: DroppedFieldsEvent[] = []; |
| 181 | + await engine.update( |
| 182 | + 'acct', |
| 183 | + { note: 'bulk', order_total: 2 }, |
| 184 | + { where: { id: { $in: ['a1', 'a2'] } }, multi: true, context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, |
| 185 | + ); |
| 186 | + expect(events).toEqual([ROLL_UP]); |
| 187 | + expect(acct('a1')).toMatchObject({ note: 'bulk', order_total: 42 }); |
| 188 | + expect(acct('a2')).toMatchObject({ note: 'bulk', order_total: 5 }); |
| 189 | + }); |
| 190 | + |
| 191 | + it('under strictReadonlyWrites the update is refused and writes nothing, on both branches', async () => { |
| 192 | + const byId = await rejection(engine.update( |
| 193 | + 'acct', { id: 'a1', note: 'typed', order_total: 90 }, |
| 194 | + { context: PERSON, strictReadonlyWrites: true } as any, |
| 195 | + )); |
| 196 | + expect(byId.code).toBe(READONLY_FIELD_REJECTED_CODE); |
| 197 | + expect(byId.fields).toEqual(['order_total']); |
| 198 | + expect(byId.drops).toEqual([ROLL_UP]); |
| 199 | + expect(byId.operation).toBe('update'); |
| 200 | + |
| 201 | + const multi = await rejection(engine.update( |
| 202 | + 'acct', { note: 'bulk', order_total: 2 }, |
| 203 | + { where: { id: { $in: ['a1', 'a2'] } }, multi: true, context: PERSON, strictReadonlyWrites: true } as any, |
| 204 | + )); |
| 205 | + expect(multi.code).toBe(READONLY_FIELD_REJECTED_CODE); |
| 206 | + expect(multi.fields).toEqual(['order_total']); |
| 207 | + |
| 208 | + expect(acct('a1')).toMatchObject({ order_total: 42 }); |
| 209 | + expect(acct('a2')).toMatchObject({ order_total: 5 }); |
| 210 | + expect([acct('a1').note, acct('a2').note]).toEqual([undefined, undefined]); |
| 211 | + }); |
| 212 | + |
| 213 | + it('the update-mode preview (validate) reports the same drop the write makes', async () => { |
| 214 | + const events: DroppedFieldsEvent[] = []; |
| 215 | + const preview = await engine.validate( |
| 216 | + 'acct', { id: 'a1', note: 'typed', order_total: 90 }, |
| 217 | + { mode: 'update', context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) }, |
| 218 | + ); |
| 219 | + expect(events).toEqual([ROLL_UP]); |
| 220 | + expect(preview.results[0]).toMatchObject({ valid: true, droppedFields: [ROLL_UP] }); |
| 221 | + }); |
| 222 | + |
| 223 | + it('the roll-up still recomputes after a refused write: the next child write lands the engine\'s value', async () => { |
| 224 | + await engine.update('acct', { id: 'a1', order_total: 90 }, { context: PERSON } as any); |
| 225 | + await engine.insert('ord', { acct: 'a1', amount: 8 }, { context: PERSON } as any); |
| 226 | + expect(acct('a1')).toMatchObject({ order_total: 50, order_total_ro: 50 }); |
| 227 | + }); |
| 228 | + |
| 229 | + it('an isSystem write of the column is kept, as for a declared readonly column (the recompute\'s exemption)', async () => { |
| 230 | + const events: DroppedFieldsEvent[] = []; |
| 231 | + await engine.update( |
| 232 | + 'acct', { id: 'a1', order_total: 7 }, |
| 233 | + { context: { isSystem: true }, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, |
| 234 | + ); |
| 235 | + expect(events).toEqual([]); |
| 236 | + expect(acct('a1')).toMatchObject({ order_total: 7 }); |
| 237 | + }); |
| 238 | + |
| 239 | + it('CONTROL: a roll-up declared readonly: true answers the same, and one payload naming both reports both once', async () => { |
| 240 | + const events: DroppedFieldsEvent[] = []; |
| 241 | + await engine.update( |
| 242 | + 'acct', { id: 'a1', order_total: 1, order_total_ro: 1 }, |
| 243 | + { context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, |
| 244 | + ); |
| 245 | + expect(events).toEqual([{ object: 'acct', fields: ['order_total', 'order_total_ro'], reason: 'readonly' }]); |
| 246 | + expect(acct('a1')).toMatchObject({ order_total: 42, order_total_ro: 42 }); |
| 247 | + }); |
| 248 | + |
| 249 | + it('INSERT is not narrowed: a caller\'s initial value is kept (seed data, a historical import)', async () => { |
| 250 | + const events: DroppedFieldsEvent[] = []; |
| 251 | + await engine.insert( |
| 252 | + 'acct', { id: 'a3', name: 'C', order_total: 7 }, |
| 253 | + { context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, |
| 254 | + ); |
| 255 | + expect(events).toEqual([]); |
| 256 | + expect(acct('a3')).toMatchObject({ order_total: 7 }); |
| 257 | + }); |
| 258 | +}); |
| 259 | + |
| 260 | +describe('[#34672] summaryFieldsLockedOnUpdate', () => { |
| 261 | + it('names each summary field not declared readonly, and nothing else', () => { |
| 262 | + expect(summaryFieldsLockedOnUpdate(ACCOUNT)).toEqual(['order_total']); |
| 263 | + expect(summaryFieldsLockedOnUpdate(ORDER)).toEqual([]); |
| 264 | + }); |
| 265 | + |
| 266 | + it('answers empty for a schema with no field map', () => { |
| 267 | + expect(summaryFieldsLockedOnUpdate(undefined)).toEqual([]); |
| 268 | + expect(summaryFieldsLockedOnUpdate({ fields: [] })).toEqual([]); |
| 269 | + }); |
| 270 | +}); |
0 commit comments