From 4b1c7dae0b32f44d678b9bcd1431923f7114733f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:04:08 +0000 Subject: [PATCH 1/5] test(objectql): pin the set_null walk's clear of a read-only lookup (red on main) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- ...ine-set-null-readonly-lookup-clear.test.ts | 275 ++++++++++++++++++ 1 file changed, 275 insertions(+) create mode 100644 packages/objectql/src/engine-set-null-readonly-lookup-clear.test.ts diff --git a/packages/objectql/src/engine-set-null-readonly-lookup-clear.test.ts b/packages/objectql/src/engine-set-null-readonly-lookup-clear.test.ts new file mode 100644 index 00000000000..2b2ab105ab9 --- /dev/null +++ b/packages/objectql/src/engine-set-null-readonly-lookup-clear.test.ts @@ -0,0 +1,275 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The `set_null` delete walk's clear of a READ-ONLY lookup. + * + * Deleting a record makes the engine clear every optional lookup pointing at + * it (`deleteBehavior: 'set_null'`, the default): an UPDATE of the holder, + * `{ id, LINK: null }` (or, on a `multiple: true` lookup, the member list + * without the deleted id), under the CALLER's context. When LINK was declared + * `readonly: true` — the normal shape for a stamp a system writes — the + * update-side read-only strip treated that clear as a forged caller write, + * dropped it and logged "DROPPED ... COMMITTED WITHOUT IT": the delete + * answered 200 and every holder kept the deleted row's id. + * + * ## What is pinned + * + * - the clear lands on a `readonly` lookup and on a `readonlyWhen`-locked + * one, single- and multi-valued, under a user context and under none, and + * no read-only drop line is logged for it; + * - the holder's `beforeUpdate` is handed the clear it is about to store; + * - a non-read-only lookup is cleared exactly as before (the control); + * - the exemption is the walk's alone: a caller update that carries the + * referential-clear marker on its context through the normal door is still + * stripped and still logged, and still refused under + * `strictReadonlyWrites`; + * - and it is one key wide: a second read-only key in the same write, or the + * cleared key holding any other value, is still stripped and still logged + * (unit level, where one payload can carry both). + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { ObjectQL } from './engine.js'; +import { stripReadonlyFields, stripReadonlyWhenFields } from './validation/rule-validator.js'; + +function makeStubDriver() { + const stores = new Map>>(); + const storeFor = (o: string) => { let s = stores.get(o); if (!s) { s = new Map(); stores.set(o, s); } return s; }; + let nextId = 0; + const holds = (value: unknown, cond: unknown): boolean => { + if (cond !== null && typeof cond === 'object' && !Array.isArray(cond)) { + const c = cond as Record; + if ('$eq' in c) return (value ?? null) === (c.$eq ?? null); + if ('$in' in c) return (c.$in as unknown[]).some((v) => String(v) === String(value)); + if ('$contains' in c) { + if (Array.isArray(value)) return value.some((m) => String(m).includes(String(c.$contains))); + return typeof value === 'string' && value.includes(String(c.$contains)); + } + if ('$ne' in c) return (value ?? null) !== (c.$ne ?? null); + return false; + } + return (value ?? null) === (cond ?? null); + }; + const matches = (row: Record, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + for (const [k, v] of Object.entries(where)) { + if (k === '$or') { if (!(v as any[]).some((sub) => matches(row, sub))) return false; continue; } + if (k === '$and') { if (!(v as any[]).every((sub) => matches(row, sub))) return false; continue; } + if (k.startsWith('$')) continue; + if (!holds(row[k], v)) return false; + } + return true; + }; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(o: string, ast: any) { + const rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where)); + return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + }, + async findOne(o: string, ast: any) { for (const r of storeFor(o).values()) if (matches(r, ast?.where)) return r; return null; }, + async create(o: string, data: Record) { + nextId += 1; const id = (data.id as string) ?? `r_${nextId}`; const row = { ...data, id }; storeFor(o).set(id, row); return row; + }, + async update(o: string, id: string, data: Record) { + const s = storeFor(o); const cur = s.get(id); if (!cur) throw new Error(`nf ${o}/${id}`); + const up = { ...cur, ...data, id }; s.set(id, up); return up; + }, + async delete(o: string, id: string) { return storeFor(o).delete(id); }, + async count(o: string, ast: any) { return (await this.find(o, ast)).length; }, + async bulkCreate(o: string, rows: Record[]) { return Promise.all(rows.map((r) => this.create(o, r))); }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, async commit() {}, async rollback() {}, + }; + return { driver, storeFor }; +} + +const milestone = { + name: 'ro_milestone', label: 'Milestone', + fields: { name: { name: 'name', type: 'text' as const } }, +}; +/** The holder: every lookup on the spec default `deleteBehavior` (`set_null`). */ +const entry = { + name: 'ro_entry', label: 'Entry', + fields: { + name: { name: 'name', type: 'text' as const }, + /** The reported shape: a stamp a system writes, read-only to callers. */ + billed_on: { name: 'billed_on', type: 'lookup' as const, reference: 'ro_milestone', readonly: true }, + /** A read-only SET of references. */ + billed_on_many: { name: 'billed_on_many', type: 'lookup' as const, reference: 'ro_milestone', multiple: true, readonly: true }, + /** A conditional lock that is always closed. */ + locked_link: { name: 'locked_link', type: 'lookup' as const, reference: 'ro_milestone', readonlyWhen: 'true' }, + /** The control: an ordinary, writable lookup. */ + plain_link: { name: 'plain_link', type: 'lookup' as const, reference: 'ro_milestone' }, + /** A second read-only column, for the one-key-wide pins. */ + stamp: { name: 'stamp', type: 'text' as const, readonly: true }, + }, +}; + +/** Every line the read-only strips write: the static one and the `readonlyWhen` one. */ +const isDropLine = (line: string) => /DROPPED|read-only \(readonlyWhen\)/.test(line); + +const CALLERS: Array<[label: string, ctx: Record | undefined]> = [ + ['a user context (an admin\'s REST DELETE)', { userId: 'u1' }], + ['no context at all', undefined], +]; + +describe('the set_null walk clears a read-only lookup', () => { + let engine: ObjectQL; + let storeFor: ReturnType['storeFor']; + let warns: string[]; + let hookSaw: Array<{ data: Record; marker: unknown }>; + + beforeEach(async () => { + warns = []; + const quiet = () => {}; + engine = new ObjectQL({ + logger: { debug: quiet, info: quiet, error: quiet, warn: (m: unknown) => { warns.push(String(m)); } }, + } as any); + const d = makeStubDriver(); + storeFor = d.storeFor; + engine.registerDriver(d.driver, true); + await engine.init(); + for (const o of [milestone, entry]) engine.registry.registerObject(o as any); + hookSaw = []; + engine.on('beforeUpdate', 'ro_entry', async (ctx: any) => { + hookSaw.push({ data: { ...(ctx.input?.data ?? {}) }, marker: ctx.referentialFieldClear }); + }); + }); + + /** Seed through the system door: a caller cannot write the read-only stamps. */ + const seed = async (values: Record) => + engine.insert('ro_entry', { name: 'e', ...values }, { context: { isSystem: true } } as any); + const del = (id: unknown, ctx: Record | undefined) => + engine.delete('ro_milestone', { where: { id }, ...(ctx ? { context: ctx } : {}) } as any); + + it.each(CALLERS)('a readonly lookup reads null after its target is deleted, with no drop line — %s', async (_l, ctx) => { + const m = await engine.insert('ro_milestone', { name: 'step 1' }); + const e = await seed({ billed_on: m.id }); + + await del(m.id, ctx); + + expect(storeFor('ro_milestone').has(m.id)).toBe(false); + expect(storeFor('ro_entry').get(e.id)?.billed_on, 'the deleted record\'s id is gone').toBeNull(); + expect(warns.filter(isDropLine), 'the engine\'s own clear is not a forged caller write').toEqual([]); + const cleanup = hookSaw.find((s) => s.marker === true); + expect(cleanup?.data.billed_on, 'the hook is handed the clear the write stores').toBeNull(); + }); + + it.each(CALLERS)('a readonly multi-value lookup keeps its remaining ids, with no drop line — %s', async (_l, ctx) => { + const a = await engine.insert('ro_milestone', { name: 'a' }); + const b = await engine.insert('ro_milestone', { name: 'b' }); + const e = await seed({ billed_on_many: [a.id, b.id] }); + + await del(a.id, ctx); + + expect(storeFor('ro_entry').get(e.id)?.billed_on_many).toEqual([b.id]); + expect(warns.filter(isDropLine)).toEqual([]); + }); + + it.each(CALLERS)('a readonlyWhen-locked lookup is cleared too, with no drop line — %s', async (_l, ctx) => { + const m = await engine.insert('ro_milestone', { name: 'step 1' }); + const e = await seed({ locked_link: m.id }); + + await del(m.id, ctx); + + expect(storeFor('ro_entry').get(e.id)?.locked_link).toBeNull(); + expect(warns.filter(isDropLine)).toEqual([]); + }); + + it('control: a writable lookup is cleared exactly as before', async () => { + const m = await engine.insert('ro_milestone', { name: 'step 1' }); + const e = await seed({ plain_link: m.id }); + + await del(m.id, { userId: 'u1' }); + + expect(storeFor('ro_entry').get(e.id)?.plain_link).toBeNull(); + expect(warns.filter(isDropLine)).toEqual([]); + }); + + describe('the exemption is the walk\'s alone — a caller carrying the marker through the normal door', () => { + const forged = (field: string, id: unknown, target: unknown) => ({ + userId: 'u1', + __referentialFieldClear: true, + __referentialFieldClearCause: { object: 'ro_milestone', id: target, referencingObject: 'ro_entry', referencingId: id, field }, + }); + + it('is still stripped and still logged', async () => { + const m = await engine.insert('ro_milestone', { name: 'step 1' }); + const e = await seed({ billed_on: m.id }); + + await engine.update('ro_entry', { id: e.id, billed_on: null }, { context: forged('billed_on', e.id, m.id) } as any); + + expect(storeFor('ro_entry').get(e.id)?.billed_on, 'the marker grants a caller nothing').toBe(m.id); + expect(warns.filter((w) => w.includes("'billed_on'") && w.includes('DROPPED'))).toHaveLength(1); + }); + + it('is still locked by readonlyWhen', async () => { + const m = await engine.insert('ro_milestone', { name: 'step 1' }); + const e = await seed({ locked_link: m.id }); + + await engine.update('ro_entry', { id: e.id, locked_link: null }, { context: forged('locked_link', e.id, m.id) } as any); + + expect(storeFor('ro_entry').get(e.id)?.locked_link).toBe(m.id); + expect(warns.filter((w) => w.includes("'locked_link'") && w.includes('readonlyWhen'))).toHaveLength(1); + }); + + it('is still refused under strictReadonlyWrites', async () => { + const m = await engine.insert('ro_milestone', { name: 'step 1' }); + const e = await seed({ billed_on: m.id }); + + const refusal = await engine + .update('ro_entry', { id: e.id, billed_on: null }, { context: forged('billed_on', e.id, m.id), strictReadonlyWrites: true } as any) + .then(() => undefined, (err: unknown) => err as { code?: unknown; fields?: unknown }); + + expect(refusal?.code).toBe('ERR_READONLY_FIELD_REJECTED'); + expect(refusal?.fields).toEqual(['billed_on']); + expect(storeFor('ro_entry').get(e.id)?.billed_on).toBe(m.id); + }); + }); +}); + +describe('the strips\' referential-clear exemption is one key, one value wide', () => { + const schema = { name: 'ro_entry', fields: entry.fields as Record }; + + it('static strip: keeps the cleared key at the walk\'s value; strips and logs every other read-only key', () => { + const warns: string[] = []; + const logger = { warn: (m: string) => { warns.push(m); } } as any; + const data = { billed_on: null, stamp: 'forged' }; + + const out = stripReadonlyFields(schema, data, { ...data }, logger, { referentialClear: { field: 'billed_on', value: null } }); + + expect(out).toEqual({ billed_on: null }); + expect(warns).toHaveLength(1); + expect(warns[0]).toContain("'stamp'"); + }); + + it('static strip: the cleared key holding any other value is stripped and logged', () => { + const warns: string[] = []; + const logger = { warn: (m: string) => { warns.push(m); } } as any; + const data = { billed_on: 'other_row' }; + + const out = stripReadonlyFields(schema, data, { ...data }, logger, { referentialClear: { field: 'billed_on', value: null } }); + + expect(out).toEqual({}); + expect(warns).toHaveLength(1); + expect(warns[0]).toContain("'billed_on'"); + }); + + it('readonlyWhen strip: keeps the cleared key at the walk\'s value; locks it at any other value', () => { + const warns: string[] = []; + const logger = { warn: (m: string) => { warns.push(m); } } as any; + + const kept = stripReadonlyWhenFields(schema, { locked_link: null }, { locked_link: 'm1' }, logger, undefined, { + referentialClear: { field: 'locked_link', value: null }, + }); + expect(kept).toEqual({ locked_link: null }); + expect(warns).toEqual([]); + + const locked = stripReadonlyWhenFields(schema, { locked_link: 'm2' }, { locked_link: 'm1' }, logger, undefined, { + referentialClear: { field: 'locked_link', value: null }, + }); + expect(locked).toEqual({}); + expect(warns).toHaveLength(1); + }); +}); From cc0d221bce74db965b4d8c86c86089d6b4d24bef Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:07:28 +0000 Subject: [PATCH 2/5] fix(objectql): the set_null walk's clear of a read-only lookup passes the read-only strips The delete walk hands update() the holder row and lookup it clears on a module-private symbol option; update() exempts exactly that key, at the value the walk wrote, from the static readonly strip, the readonlyWhen strip and the hide-from-hooks pass. The operation-private context marker grants nothing, and isSystem is not granted. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- .../34899-set-null-readonly-lookup-clear.md | 14 +++++ .../objectql/src/engine-cascade-planning.ts | 20 ++++-- .../src/engine-master-detail-related.ts | 4 +- packages/objectql/src/engine-top-level.ts | 32 +++++++++- packages/objectql/src/engine-update.ts | 35 ++++++++--- .../objectql/src/validation/rule-validator.ts | 63 ++++++++++++++++++- 6 files changed, 152 insertions(+), 16 deletions(-) create mode 100644 .changeset/34899-set-null-readonly-lookup-clear.md diff --git a/.changeset/34899-set-null-readonly-lookup-clear.md b/.changeset/34899-set-null-readonly-lookup-clear.md new file mode 100644 index 00000000000..4905e66d661 --- /dev/null +++ b/.changeset/34899-set-null-readonly-lookup-clear.md @@ -0,0 +1,14 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): deleting a record clears a read-only lookup that points at it + +Clause-②: no +Metadata-protocol: none + +Deleting a record makes the engine clear every optional lookup that points at it (`deleteBehavior: 'set_null'`, the default). That clear is an update of the referencing row under the caller's context. When the lookup was declared `readonly: true`, or locked by `readonlyWhen`, the read-only rule treated the clear as a value the caller had forged: it logged `... is read-only: the caller-supplied value was DROPPED and the update is being COMMITTED WITHOUT IT`, the delete answered 200, and every referencing row kept the deleted record's id. + +The read-only rule now leaves that one key to the engine: the lookup the delete is clearing on that row, at the value the delete writes (`null`, or on a `multiple: true` lookup the remaining ids). No read-only line is logged for it, and the row's `beforeUpdate` hook sees the clear it is about to store. The exemption travels on an engine-internal channel that only the delete holds. A caller update that carries the operation-private `__referentialFieldClear` marker on its context is still stripped, still logged and still refused under `strictReadonlyWrites`. Any other read-only key in the same write is judged as before. `isSystem` is not granted. + +Nothing to change in your metadata. Rows that already hold the id of a deleted record keep it: this fix does not rewrite them, so clear them with a system-context update. diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index 4170445fa47..d941938d7c4 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -51,9 +51,10 @@ import { declaredHttpStatus } from '@objectstack/types'; import { ORGANIZATION_OBJECT, resolveTenantFieldName } from './tenancy/system-write-organization.js'; import { isFederatedUnprovisionedInjectedColumn } from './federated-object.js'; import { - CascadeBatchNarrowed, cascadeMemberKey, cascadeSetAdd, cascadeSetHas, declaredMultiValued, deleteWalkTargetOf, - statesDeleteSemantics, + CascadeBatchNarrowed, REFERENTIAL_CLEAR_OPTION, cascadeMemberKey, cascadeSetAdd, cascadeSetHas, declaredMultiValued, + deleteWalkTargetOf, statesDeleteSemantics, } from './engine-top-level.js'; +import type { ReferentialClearOption } from './engine-top-level.js'; import { isExternalDriverFloor } from './external-driver-floor.js'; import { forgetCollectedProbes, takeCollectedProbe } from './engine-delete-cascade.js'; import type { CascadeDeleteSet } from './engine-top-level.js'; @@ -1149,6 +1150,17 @@ export class CascadePlanningFacet { object, id: String(id), referencingObject: childName, referencingId: String(depId), field: fieldName, }, } as ExecutionContext; + // The read-only strips' exemption for THIS clear: the holder row + // and the lookup, on the update's module-private symbol channel + // (`REFERENTIAL_CLEAR_OPTION`), never on the context above. A + // `readonly` / `readonlyWhen` lookup is the normal shape for a + // stamp a system writes, and the static strip runs on + // `!isSystem` alone, so without it this clear was dropped as a + // forged caller write and every holder kept the deleted row's id. + // `update()` exempts exactly this key at exactly the value written + // below; every other key is judged as before. + const referentialClear: ReferentialClearOption = { object: childName, id: String(depId), field: fieldName }; + const clearOptions = { context: referentialCtx, [REFERENTIAL_CLEAR_OPTION]: referentialClear }; // [ruling 6893104201 c1] The walk's first write: its hooks may // write a row a later probe must see. forgetCollectedProbes(cascadeSet); @@ -1178,9 +1190,9 @@ export class CascadePlanningFacet { // off-shape bare scalar normalized to the array spelling — is // documented there. const next = ObjectQL.remainderAfterMemberRemoval(dep?.[fieldName], id, cleared); - await this.update(childName, { id: depId, [fieldName]: next }, { context: referentialCtx } as any); + await this.update(childName, { id: depId, [fieldName]: next }, clearOptions as any); } else { - await this.update(childName, { id: depId, [fieldName]: null }, { context: referentialCtx } as any); + await this.update(childName, { id: depId, [fieldName]: null }, clearOptions as any); } // [#30237, ADR-0148 D2] The reference a restore re-links while // the field still lacks it: the live row, the field, and the id diff --git a/packages/objectql/src/engine-master-detail-related.ts b/packages/objectql/src/engine-master-detail-related.ts index 9545c102e2d..cb7e62376cb 100644 --- a/packages/objectql/src/engine-master-detail-related.ts +++ b/packages/objectql/src/engine-master-detail-related.ts @@ -71,7 +71,7 @@ import { collectPredicateRelationships, referentialClearBinding } from './valida // [#19911] The settlement's question "does judging the FK's own lock need the // header it names?" — asked of the same root reader the strips use. import { readonlyWhenFkJudgementReadsParent } from './validation/rule-validator.js'; -import type { RelatedFieldBinding, RelatedRecordBinding } from './validation/rule-validator.js'; +import type { ReferentialClearExemption, RelatedFieldBinding, RelatedRecordBinding } from './validation/rule-validator.js'; import { resolveMasterDetailRelation } from './master-detail.js'; import { isFederatedObject } from './federated-object.js'; import { masterIdOf, servedAsStored, staticReadonlyStoredView, undeclaredRelatedFields } from './engine.js'; @@ -138,6 +138,8 @@ function staticReadonlyStripTakes( hookWrittenKeys: ReadonlySet | undefined; /** [#24822] The wall's flag, read once by `update()` — see {@link staticReadonlyStoredView}. */ wallJudgesOrganization?: boolean; + /** The walk's referential clear, read once by `update()` — see {@link staticReadonlyStoredView}. */ + referentialClear?: ReferentialClearExemption; }, ): boolean { if (!strip.runs) return false; diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index dac2d18b839..1d491c8e251 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -44,7 +44,7 @@ import { ValidationError } from './validation/record-validator.js'; import { NotNullRefusalError } from './not-null-refusal-error.js'; import type { FieldValidationError } from './validation/record-validator.js'; import { collectReferenceTraversals, referenceTraversalConflicts, staticReadonlyInsertSubject, stripReadonlyFields } from './validation/rule-validator.js'; -import type { RelatedFieldBinding, RelatedRecordBinding } from './validation/rule-validator.js'; +import type { ReferentialClearExemption, RelatedFieldBinding, RelatedRecordBinding } from './validation/rule-validator.js'; import { declaredColumnSet } from './declared-read-columns.js'; /** @@ -4431,12 +4431,14 @@ export function staticReadonlyStoredView( preserveAudit: boolean; hookWrittenKeys: ReadonlySet | undefined; wallJudgesOrganization?: boolean; + /** The walk's referential clear, which the strip keeps — so the view keeps it too. */ + referentialClear?: ReferentialClearExemption; }, ): Record { if (!strip.runs) return data; return stripReadonlyFields( updateStaticReadonlySubject(schema, strip.wallJudgesOrganization === true) as any, data, supplied, undefined, - { preserveAudit: strip.preserveAudit, hookWrittenKeys: strip.hookWrittenKeys }, + { preserveAudit: strip.preserveAudit, hookWrittenKeys: strip.hookWrittenKeys, referentialClear: strip.referentialClear }, ) ?? data; } @@ -5225,13 +5227,37 @@ export const SECURITY_SERVICE_SOURCE_SLOT: unique symbol = Symbol.for('objectsta */ const WRITE_PRECONDITION_OPTION: unique symbol = Symbol('objectql.writePrecondition'); +/** + * The `set_null` delete walk's own channel for the reference it clears, on the + * `update` it issues to clear it (`cascadeDeleteRelations`): `{ object, id, + * field }` of the holder row and lookup. `update()` hands the read-only strips + * that one key, at the value the walk wrote, as engine-owned referential + * integrity rather than a caller write ({@link ReferentialClearOption}). + * + * A module-private symbol, the shape of {@link WRITE_PRECONDITION_OPTION}, and + * for the same reason: no options object a door builds, no hook's `ctx.api` + * write and nothing outside this package can carry it. ⛔ Not the + * operation-private `__referentialFieldClear` context key, which a write a + * hook issues through `ctx.api` during the cleanup dispatch INHERITS + * (`buildReferentialFieldClear`); and ⛔ not `isSystem`, whose exemption is + * total. ⛔ Not re-exported by `index.ts` or `core.ts`. + */ +const REFERENTIAL_CLEAR_OPTION: unique symbol = Symbol('objectql.referentialClear'); + +/** What the walk puts under {@link REFERENTIAL_CLEAR_OPTION}: the holder row and the lookup it clears. */ +interface ReferentialClearOption { + readonly object: string; + readonly id: string; + readonly field: string; +} + // [#29986 codemod] Declared above without `export`, and read by `engine.ts` or a section module. export { AUTONUMBER_COLLISION_ATTEMPTS, AUTONUMBER_SEED_PAGE_SIZE, AutonumberReaders, CascadeBatchNarrowed, CascadeIssuedDelete, DISPATCHABLE_HOOK_EVENTS, cascadeBatchIdsOf, ENGINE_AGGREGATE_OPTION_KEYS, ENGINE_DELETE_OPTION_KEYS, ENGINE_FIND_OPTION_KEYS, ENGINE_QUERY_SLOTS, ENGINE_UPDATE_OPTION_KEYS, ENGINE_WIRE_ONLY_SLOTS, FormulaFaultSink, FormulaRelated, IssuedAutonumber, METADATA_ARRAY_KEYS, ReadableIdsSecurityResolution, StoredExpressionServing, TransactionScope, - WIRE_ONLY_CANONICAL_SHAPES, WRITE_PRECONDITION_OPTION, applyFormulaPlan, applyStoredExpressionsToPatch, + REFERENTIAL_CLEAR_OPTION, ReferentialClearOption, WIRE_ONLY_CANONICAL_SHAPES, WRITE_PRECONDITION_OPTION, applyFormulaPlan, applyStoredExpressionsToPatch, assertDispatchableHookEvent, assertHookScopeNotSelfCancelling, assertOrderByIsMaterializable, assertProjectionHasNoDottedPaths, assertValidHookExcludeObjects, assertValidHookObject, assertValidUnscopedMultiWriteFlag, autonumberFieldNames, callerKeySets, callerSuppliedRow, computeStoredExpressions, diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 28044fb359b..8169e905476 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -57,6 +57,7 @@ import { stripSearchCompanion } from './search-companion.js'; import { declaredOptionLabels } from './formula-option-labels.js'; import { ValidationError, coerceBooleanFields, normalizeBlankTypedValues, normalizeMultiValueFields, normalizeNumericStringValues, validateRecord, validateRecordInScope } from './validation/record-validator.js'; import { emitValidationAdvisories, evaluateValidationRules, hasParentScopedReadonlyWhenInPayload, hasParentScopedRequiredWhen, hasReadonlyWhenInPayload, needsPriorRecord, stripReadonlyFields, stripReadonlyWhenFields, stripReadonlyWhenFieldsMulti } from './validation/rule-validator.js'; +import type { ReferentialClearExemption } from './validation/rule-validator.js'; import { recordHookPayloadWrites } from './hook-write-provenance.js'; import { dispatchHooksExplainingWithheldReadonly } from './hook-withheld-readonly-fault.js'; import { resolveMasterDetailRelation } from './master-detail.js'; @@ -65,14 +66,14 @@ import { externalPredicateWriteRefusal, isExternalDriverFloor } from './external import { ENGINE_UPDATE_REJECT_MESSAGE, engineUpdateDispatchRejectError, resolveEngineUpdateDispatch } from './engine-update-dispatch.js'; import type { EngineUpdateDispatchData, EngineUpdateDispatchInput } from './engine-update-dispatch.js'; import { - ENGINE_UPDATE_OPTION_KEYS, ENGINE_WHERE_SLOTS, WRITE_PRECONDITION_OPTION, applyStoredExpressionsToPatch, + ENGINE_UPDATE_OPTION_KEYS, ENGINE_WHERE_SLOTS, REFERENTIAL_CLEAR_OPTION, WRITE_PRECONDITION_OPTION, applyStoredExpressionsToPatch, computeStoredExpressions, declaredDatetimeLowering, foldEngineOptionAliases, hydrateWriteFormulas, lowerWhereFilterArray, masterIdOf, planStoredExpressions, rejectUnknownEngineOptions, replacedStoredExpressionFields, settleBulkStoredExpressions, shouldSkipStateMachine, staticReadonlyStoredView, stripComputedWriteFields, undeclaredWriteFieldErrors, updateStaticReadonlySubject, writeFailureLogMeta, callerInputRefusalLogMeta, } from './engine-top-level.js'; -import type { OperationContext, StoredExpressionServing } from './engine-top-level.js'; +import type { OperationContext, ReferentialClearOption, StoredExpressionServing } from './engine-top-level.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { ObjectQL as ObjectQLClass } from './engine.js'; @@ -277,6 +278,25 @@ export class UpdateFacet { ...((opCtx.data ?? {}) as Record), }; + // The `set_null` delete walk's clear of a reference (`cascadeDeleteRelations`): + // the one key the read-only strips below leave to the engine, at the value + // this write received — see `ReferentialClearExemption`. Read off the + // walk's module-private option only, never off the context: a caller (or + // a hook's `ctx.api` write, which inherits the cleanup context) carrying + // `__referentialFieldClear` gets nothing here. And only on the by-id write + // of the row and field the walk named, so the option forwarded into any + // other write exempts nothing there. + const referentialClearOption = (options as Record | undefined)?.[REFERENTIAL_CLEAR_OPTION] as + ReferentialClearOption | undefined; + const referentialClear: ReferentialClearExemption | undefined = + referentialClearOption !== undefined + && id !== undefined && id !== null + && referentialClearOption.object === object + && referentialClearOption.id === String(id) + && Object.prototype.hasOwnProperty.call(suppliedValues, referentialClearOption.field) + ? { field: referentialClearOption.field, value: suppliedValues[referentialClearOption.field] } + : undefined; + // [#3407] Structured strip observability. The readonly/readonlyWhen strips // below — and, since #6437, the primary-key strip at each branch's head — // are LEGAL semantics (the write still succeeds without the dropped @@ -575,9 +595,10 @@ export class UpdateFacet { delete suppliedDataOnly.id; // No logger, deliberately: this pass is SILENT by construction. The // strip below owns every word said about these keys. + // The walk's referential clear is stored, so its hooks see it. const hidden = stripReadonlyFields( readonlyUpdateSubject as any, preHookPayload, suppliedDataOnly, undefined, - { preserveAudit: opCtx.context?.preserveAudit === true }, + { preserveAudit: opCtx.context?.preserveAudit === true, referentialClear }, ) as Record; if (hidden !== preHookPayload) { readonlyHiddenFromHooks = {}; @@ -1372,13 +1393,13 @@ export class UpdateFacet { // [#24822] ...with the wall's flag read once above, so the views // these consumers read agree with the strip below about // `organization_id`. - const staticStrip = { runs: staticReadonlyStripRuns, preserveAudit: opCtx.context?.preserveAudit === true, hookWrittenKeys, wallJudgesOrganization }; + const staticStrip = { runs: staticReadonlyStripRuns, preserveAudit: opCtx.context?.preserveAudit === true, hookWrittenKeys, wallJudgesOrganization, referentialClear }; const landing = wantsParentBinding ? await this.settleMasterDetailLanding({ schema: updateSchema, data: preRoWhen, supplied: judgedSupplied, staticStrip, resolve: (view) => this.resolveMasterDetailParent(updateSchema, view, priorRecord, opCtx.context), - judgeFkLock: (named, fk) => stripReadonlyWhenFields(updateSchema as any, preRoWhen, priorRecord, this.logger, named, { supplied: judgedSupplied, only: fk, stored: inStoredMultiValueShape(staticReadonlyStoredView(updateSchema, preRoWhen, judgedSupplied, staticStrip)) }) as Record, + judgeFkLock: (named, fk) => stripReadonlyWhenFields(updateSchema as any, preRoWhen, priorRecord, this.logger, named, { supplied: judgedSupplied, only: fk, stored: inStoredMultiValueShape(staticReadonlyStoredView(updateSchema, preRoWhen, judgedSupplied, staticStrip)), referentialClear }) as Record, }) : undefined; const roWhenParent = landing?.header; @@ -1430,7 +1451,7 @@ export class UpdateFacet { // so a value forged for a static `readonly` field (stripped // below) cannot unlock a field whose predicate reads it. const roWhenSubject = landing?.subject ?? preRoWhen; - hookContext.input.data = stripReadonlyWhenFields(updateSchema as any, roWhenSubject, priorRecord, this.logger, roWhenParent, { supplied: landing?.supplied ?? judgedSupplied, stored: inStoredMultiValueShape(staticReadonlyStoredView(updateSchema, roWhenSubject, judgedSupplied, staticStrip)) }) as any; + hookContext.input.data = stripReadonlyWhenFields(updateSchema as any, roWhenSubject, priorRecord, this.logger, roWhenParent, { supplied: landing?.supplied ?? judgedSupplied, stored: inStoredMultiValueShape(staticReadonlyStoredView(updateSchema, roWhenSubject, judgedSupplied, staticStrip)), referentialClear }) as any; reportDroppedFields(preRoWhen, hookContext.input.data as Record, 'readonly_when'); // [#2948] Enforce STATIC `readonly` on the write path for // non-system callers (system writes legitimately set read-only @@ -1471,7 +1492,7 @@ export class UpdateFacet { // taken with the row's own organization kept; it is not // reported, and not refused under `strictReadonlyWrites`, // which refuses exactly what this strip takes. - hookContext.input.data = stripReadonlyFields(readonlyUpdateSubject as any, preRo, judgedSupplied, this.logger, { preserveAudit: opCtx.context?.preserveAudit === true, addressKey: idAddressesThisRow ? 'id' : undefined, strictReadonlyWrites, hookWrittenKeys }) as any; + hookContext.input.data = stripReadonlyFields(readonlyUpdateSubject as any, preRo, judgedSupplied, this.logger, { preserveAudit: opCtx.context?.preserveAudit === true, addressKey: idAddressesThisRow ? 'id' : undefined, strictReadonlyWrites, hookWrittenKeys, referentialClear }) as any; reportDroppedFields(preRo, hookContext.input.data as Record, 'readonly'); } // Both strips are done: wrap and judge what is left. diff --git a/packages/objectql/src/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index 311d8a0f165..cb5c7a24af8 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -976,6 +976,51 @@ interface ReadonlyWhenStripOptions { * that locks. */ only?: string; + /** + * The `set_null` delete walk's clear of a reference, which this strip does + * not judge ({@link ReferentialClearExemption}). Omit on every other write. + */ + referentialClear?: ReferentialClearExemption; +} + +/** + * The one key an UPDATE's read-only strips leave to the engine's referential + * integrity: the lookup the `set_null` delete walk is clearing on this row, at + * the value the walk wrote — `null`, or on a `multiple: true` lookup the member + * list without the deleted id. + * + * Deleting a record makes the engine clear every optional lookup pointing at + * it. That UPDATE runs under the CALLER's context (never `isSystem`, whose + * exemption is total), so a `readonly` or `readonlyWhen`-locked lookup — the + * normal shape for a stamp a system writes — was stripped as if the caller had + * forged it: the delete answered 200, the strip logged that the value was + * DROPPED, and every holder kept the deleted row's id. + * + * Narrow on three sides, each pinned in `engine-set-null-readonly-lookup-clear.test.ts`: + * - only `update()` builds it, and only from the walk's module-private option + * (`REFERENTIAL_CLEAR_OPTION` in `engine-top-level.ts`) on the by-id write + * of the row the walk named — never from the context, so a caller carrying + * the operation-private `__referentialFieldClear` marker gains nothing; + * - only `field`: every other read-only key in the same payload is stripped, + * logged, reported and refused under `strictReadonlyWrites` as before; + * - only while the key still holds `value` (by `Object.is`, the value the + * write received): the same key holding anything else is judged as before. + */ +export interface ReferentialClearExemption { + readonly field: string; + readonly value: unknown; +} + +/** Is `name` the walk's referential clear, still at the value the walk wrote? */ +function isReferentialClear( + data: Readonly>, + name: string, + exemption: ReferentialClearExemption | undefined, +): boolean { + return exemption !== undefined + && name === exemption.field + && Object.prototype.hasOwnProperty.call(data, name) + && Object.is(data[name], exemption.value); } /** @@ -1089,7 +1134,7 @@ export function stripReadonlyWhenFields( if (!fields || !data) return data; const supplied = options?.supplied ?? data; const stored = options?.stored ?? data; - const judged = judgedReadonlyWhenKeys(fields, data, supplied); + const judged = judgedReadonlyWhenKeys(fields, data, supplied, options?.referentialClear); if (judged.length === 0 || !judgesOnly(judged, options?.only)) return data; const settled = settleOrRefuse(logger, () => settleReadonlyWhenDrops( readonlyWhenLockGroups(fields, judged), @@ -1111,10 +1156,16 @@ function judgedReadonlyWhenKeys( fields: Record, data: Record, supplied: Readonly>, + referentialClear?: ReferentialClearExemption, ): string[] { const judged: string[] = []; for (const [name, def] of Object.entries(fields)) { if (!def?.readonlyWhen || !(name in data)) continue; + // The delete walk's clear of a reference to a row that no longer exists is + // not a change a state lock guards: keeping it locked keeps a dangling id + // (see ReferentialClearExemption). Not judged, so not taken and not warned + // about; every other locked key is judged as before. + if (isReferentialClear(data, name, referentialClear)) continue; // [#9107] Asked BEFORE any predicate runs, not after: a hook-written value // is not this strip's business at all, so there is nothing to evaluate and // nothing to warn about — including the unbound-root LOCKED branch, whose @@ -2145,6 +2196,13 @@ export function stripReadonlyFields( * remedy, which is UPDATE-only. */ verb?: 'update' | 'insert'; + /** + * The `set_null` delete walk's clear of a reference: that key, at that + * value, is engine-owned referential integrity, kept and not logged — + * {@link ReferentialClearExemption}. Only `update()` passes it, and only + * for the walk's own write; omit everywhere else. + */ + referentialClear?: ReferentialClearExemption; }, ): Record | undefined | null { const fields = objectSchema?.fields; @@ -2177,6 +2235,9 @@ export function stripReadonlyFields( // a `null` bug — `0`, `''`, `false` and a shared object reference collide // identically, which is why the fix is provenance and not a sentinel. if (hookWrittenKeys?.has(name)) continue; // the hook wrote this value — keep + // The delete walk's clear of this reference, still at the value it wrote: + // the engine's write, not the caller's — keep, and say nothing about it. + if (isReferentialClear(result as Record, name, options?.referentialClear)) continue; // [#5591] ...and it must still BE the caller's value. A hook that // overwrote this key wrote a PLATFORM value; deleting that is what put // `status = published` rows in the database with `published_at = null`. From fbe36bf78c0e957370d3213af3bceaf8bc1d93eb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:09:32 +0000 Subject: [PATCH 3/5] refactor(objectql): import the referential-clear option on its own line Keeps the shared engine-top-level import list untouched, which an open sibling PR also edits. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- packages/objectql/src/engine-update.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 8169e905476..b521c6ed7f9 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -66,7 +66,7 @@ import { externalPredicateWriteRefusal, isExternalDriverFloor } from './external import { ENGINE_UPDATE_REJECT_MESSAGE, engineUpdateDispatchRejectError, resolveEngineUpdateDispatch } from './engine-update-dispatch.js'; import type { EngineUpdateDispatchData, EngineUpdateDispatchInput } from './engine-update-dispatch.js'; import { - ENGINE_UPDATE_OPTION_KEYS, ENGINE_WHERE_SLOTS, REFERENTIAL_CLEAR_OPTION, WRITE_PRECONDITION_OPTION, applyStoredExpressionsToPatch, + ENGINE_UPDATE_OPTION_KEYS, ENGINE_WHERE_SLOTS, WRITE_PRECONDITION_OPTION, applyStoredExpressionsToPatch, computeStoredExpressions, declaredDatetimeLowering, foldEngineOptionAliases, hydrateWriteFormulas, lowerWhereFilterArray, masterIdOf, planStoredExpressions, rejectUnknownEngineOptions, replacedStoredExpressionFields, settleBulkStoredExpressions, shouldSkipStateMachine, staticReadonlyStoredView, @@ -74,6 +74,7 @@ import { callerInputRefusalLogMeta, } from './engine-top-level.js'; import type { OperationContext, ReferentialClearOption, StoredExpressionServing } from './engine-top-level.js'; +import { REFERENTIAL_CLEAR_OPTION } from './engine-top-level.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { ObjectQL as ObjectQLClass } from './engine.js'; From a0f8fd1cd69e7f3210d4c40685a61e9a90fcd1a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 18:24:15 +0000 Subject: [PATCH 4/5] fix(objectql): the recycle-bin restore re-links a read-only lookup and counts only landed re-links The re-link and its undo ride the engine's module-private referential channel, so update() leaves exactly that key on that row to the engine; relinked is read back from the store. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- packages/objectql/src/engine-top-level.ts | 14 ++-- packages/objectql/src/engine-update.ts | 12 ++-- .../objectql/src/recycle-bin/restore.test.ts | 70 +++++++++++++++++++ packages/objectql/src/recycle-bin/restore.ts | 27 +++++-- .../objectql/src/validation/rule-validator.ts | 11 ++- 5 files changed, 115 insertions(+), 19 deletions(-) diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 1d491c8e251..d425372132e 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -5228,11 +5228,13 @@ export const SECURITY_SERVICE_SOURCE_SLOT: unique symbol = Symbol.for('objectsta const WRITE_PRECONDITION_OPTION: unique symbol = Symbol('objectql.writePrecondition'); /** - * The `set_null` delete walk's own channel for the reference it clears, on the - * `update` it issues to clear it (`cascadeDeleteRelations`): `{ object, id, - * field }` of the holder row and lookup. `update()` hands the read-only strips - * that one key, at the value the walk wrote, as engine-owned referential - * integrity rather than a caller write ({@link ReferentialClearOption}). + * The engine's own channel for a referential write to one lookup on one row, + * on the `update` it issues: `{ object, id, field }` of the holder row and + * lookup. Two writers, both engine-owned referential integrity and never a + * caller write: the `set_null` delete walk's clear (`cascadeDeleteRelations`) + * and the recycle-bin restore's re-link of that clear and its undo (ADR-0148 + * D2, `recycle-bin/restore.ts`). `update()` hands the read-only strips that one + * key, at the value the write received ({@link ReferentialClearOption}). * * A module-private symbol, the shape of {@link WRITE_PRECONDITION_OPTION}, and * for the same reason: no options object a door builds, no hook's `ctx.api` @@ -5244,7 +5246,7 @@ const WRITE_PRECONDITION_OPTION: unique symbol = Symbol('objectql.writePrecondit */ const REFERENTIAL_CLEAR_OPTION: unique symbol = Symbol('objectql.referentialClear'); -/** What the walk puts under {@link REFERENTIAL_CLEAR_OPTION}: the holder row and the lookup it clears. */ +/** What the delete walk or the restore puts under {@link REFERENTIAL_CLEAR_OPTION}: the holder row and the lookup it writes. */ interface ReferentialClearOption { readonly object: string; readonly id: string; diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index b521c6ed7f9..15fffc17240 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -279,13 +279,15 @@ export class UpdateFacet { ...((opCtx.data ?? {}) as Record), }; - // The `set_null` delete walk's clear of a reference (`cascadeDeleteRelations`): - // the one key the read-only strips below leave to the engine, at the value - // this write received — see `ReferentialClearExemption`. Read off the - // walk's module-private option only, never off the context: a caller (or + // The engine's referential write to one lookup — the `set_null` delete + // walk's clear (`cascadeDeleteRelations`) or the recycle-bin restore's + // re-link and its undo (ADR-0148 D2): the one key the read-only strips + // below leave to the engine, at the value this write received — see + // `ReferentialClearExemption`. Read off the engine's module-private option + // only, never off the context: a caller (or // a hook's `ctx.api` write, which inherits the cleanup context) carrying // `__referentialFieldClear` gets nothing here. And only on the by-id write - // of the row and field the walk named, so the option forwarded into any + // of the row and field the writer named, so the option forwarded into any // other write exempts nothing there. const referentialClearOption = (options as Record | undefined)?.[REFERENTIAL_CLEAR_OPTION] as ReferentialClearOption | undefined; diff --git a/packages/objectql/src/recycle-bin/restore.test.ts b/packages/objectql/src/recycle-bin/restore.test.ts index 68709067bf6..56c282680cf 100644 --- a/packages/objectql/src/recycle-bin/restore.test.ts +++ b/packages/objectql/src/recycle-bin/restore.test.ts @@ -540,6 +540,76 @@ describe('re-linking the references the delete cleared (ADR-0148 D2)', () => { }); }); +describe('re-linking a READ-ONLY reference the delete cleared (ADR-0148 D2)', () => { + /** + * A stamp a system writes: a `readonly` `set_null` lookup. The delete's + * clear and the restore's re-link both run under the CALLER's context, so + * both reach the static read-only strip; both are the engine's referential + * write and ride its module-private channel, never `isSystem` and never the + * `__referentialFieldClear` context marker. + */ + const stampedDeal = { + name: 'stamped_deal', + label: 'Stamped deal', + fields: { + id: text('id'), + stamped_account: { name: 'stamped_account', type: 'lookup' as const, reference: 'account', deleteBehavior: 'set_null', readonly: true }, + organization_id: text('organization_id'), + }, + }; + const isDropLine = (args: unknown[]) => /DROPPED|read-only \(readonlyWhen\)/.test(String(args[0])); + + async function deleteStampedAcme() { + const made = await makeEngine(); + const { engine, driver } = made; + engine.registry.registerObject(stampedDeal as any, '__test__'); + const warn = vi.spyOn((engine as any).logger, 'warn'); + driver.seed('account', ACME); + driver.seed('stamped_deal', { id: 'sd1', stamped_account: 'acc1', organization_id: 'org_1' }); + await engine.delete('account', { where: { id: 'acc1' }, ...ORG1_USER }); + expect(driver.rowOf('stamped_deal', 'sd1')?.stamped_account, 'the delete cleared the read-only stamp').toBeNull(); + return { ...made, warn, entryId: entryOf(driver, 'acc1').id as string }; + } + + it('the reference holds the restored id again, counted once, with no drop line', async () => { + const { engine, driver, warn, entryId } = await deleteStampedAcme(); + + const result = await engine.restore(entryId, ORG1_USER); + + expect(result?.relinked).toBe(1); + expect(driver.rowOf('stamped_deal', 'sd1')?.stamped_account).toBe('acc1'); + expect(warn.mock.calls.filter(isDropLine), 'neither the clear nor the re-link is a forged caller write').toEqual([]); + }); + + it('a re-link that does not land is not counted', async () => { + const { engine, driver, entryId } = await deleteStampedAcme(); + // A holder hook that keeps the stamp empty: the re-link's update answers + // success, and the row does not hold the id. + engine.on('beforeUpdate', 'stamped_deal', async (ctx: any) => { ctx.input.data.stamped_account = null; }); + + const result = await engine.restore(entryId, ORG1_USER); + + expect(driver.rowOf('stamped_deal', 'sd1')?.stamped_account).toBeNull(); + expect(result?.relinked, 'relinked counts what the row holds, not what was asked').toBe(0); + }); + + it("a caller update carrying the option's shape through the normal door is still stripped", async () => { + const { engine, driver, warn } = await deleteStampedAcme(); + driver.seed('account', { id: 'acc9', name: 'Other', code: 'OTHER', organization_id: 'org_1' }); + warn.mockClear(); + const shape = { object: 'stamped_deal', id: 'sd1', field: 'stamped_account' }; + + await engine.update('stamped_deal', { id: 'sd1', stamped_account: 'acc9' }, { + context: { ...ORG1_USER.context, __referentialFieldClear: true }, + [Symbol('objectql.referentialClear')]: shape, + [Symbol.for('objectql.referentialClear')]: shape, + } as any); + + expect(driver.rowOf('stamped_deal', 'sd1')?.stamped_account, 'no look-alike key opens the channel').toBeNull(); + expect(warn.mock.calls.filter((c) => String(c[0]).includes("'stamped_account'") && String(c[0]).includes('DROPPED'))).toHaveLength(1); + }); +}); + describe('the four refusals (409, ADR-0148 D2): nothing is written and the entry stays', () => { it('RESTORE_PACKAGE_UNINSTALLED: an object of the entry is no longer registered', async () => { const { engine, driver } = await makeEngine(); diff --git a/packages/objectql/src/recycle-bin/restore.ts b/packages/objectql/src/recycle-bin/restore.ts index 328d49e0606..1575a182347 100644 --- a/packages/objectql/src/recycle-bin/restore.ts +++ b/packages/objectql/src/recycle-bin/restore.ts @@ -78,8 +78,8 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { Logger } from '@objectstack/core'; import { isUniqueViolationError, keysetWalk, redactBoundStatement, uniqueViolationField } from '@objectstack/types'; import { objectPermissionGrants, type EffectiveObjectPermission, type TenantLayer0Verdict } from '@objectstack/spec/security'; -import type { OperationContext } from '../engine-top-level.js'; -import { declaredMultiValued } from '../engine-top-level.js'; +import type { OperationContext, ReferentialClearOption } from '../engine-top-level.js'; +import { REFERENTIAL_CLEAR_OPTION, declaredMultiValued } from '../engine-top-level.js'; import { SummaryRecomputeError, type SummaryRecomputeFailure } from '../summary-errors.js'; import { displayLabels } from '../duplicate-record-error.js'; import type { ValidationMessageContext } from '../validation/record-validator.js'; @@ -699,16 +699,33 @@ async function writeBack( const previous = live[0][ref.field]; const next = relinkedValue(field, previous, ref.value); if (next === undefined) continue; - await this.update(ref.object, { id: ref.id, [ref.field]: next }, { context: writeContext }); - relinked += 1; + // The re-link is the engine's referential write, the inverse of the + // delete walk's `set_null` clear, so it rides the same module-private + // channel (`REFERENTIAL_CLEAR_OPTION`): `update()` leaves exactly this + // key on this row, at the value written here, to the engine, so a + // `readonly` or `readonlyWhen`-locked lookup is re-linked rather than + // stripped as a caller forgery under the caller's context. ⛔ Not + // `isSystem`, and ⛔ not the `__referentialFieldClear` context marker. + // The undo below is the same kind of write and carries the same channel. + const relink: ReferentialClearOption = { object: ref.object, id: ref.id, field: ref.field }; + await this.update(ref.object, { id: ref.id, [ref.field]: next }, { context: writeContext, [REFERENTIAL_CLEAR_OPTION]: relink }); // Through `engine.update`, so the re-link publishes `data.record.updated` // when it lands, and its undo publishes one more: a restore that fails // after a re-link outside a transaction leaves two update events for a // row that ends as it began. done.push({ covered: driverOptions?.transaction != null, - undo: async () => { await this.update(ref.object, { id: ref.id, [ref.field]: previous ?? null }, { context: writeContext }); }, + undo: async () => { await this.update(ref.object, { id: ref.id, [ref.field]: previous ?? null }, { context: writeContext, [REFERENTIAL_CLEAR_OPTION]: relink }); }, }); + // `relinked` counts a re-link that LANDED, read back from the store: + // a write a strip or a hook took the key out of answers success too, + // and counting it reported a link the row does not hold. + const after = ((await driver.find( + ref.object, + { object: ref.object, where: { id: ref.id }, fields: ['id', ref.field], limit: 1 }, + driverOptions, + )) ?? []) as Array>; + if (after.length > 0 && relinkedValue(field, after[0][ref.field], ref.value) === undefined) relinked += 1; } // The entry goes last: a restore that did not land keeps its entry. await binDriver.delete(RECYCLE_BIN_OBJECT, entryId, this.buildDriverOptions(RECYCLE_BIN_OBJECT, writeContext)); diff --git a/packages/objectql/src/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index cb5c7a24af8..15ff561922c 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -987,7 +987,8 @@ interface ReadonlyWhenStripOptions { * The one key an UPDATE's read-only strips leave to the engine's referential * integrity: the lookup the `set_null` delete walk is clearing on this row, at * the value the walk wrote — `null`, or on a `multiple: true` lookup the member - * list without the deleted id. + * list without the deleted id — or the lookup the recycle-bin restore re-links + * (ADR-0148 D2), at the value it writes back, and that re-link's undo. * * Deleting a record makes the engine clear every optional lookup pointing at * it. That UPDATE runs under the CALLER's context (never `isSystem`, whose @@ -996,10 +997,14 @@ interface ReadonlyWhenStripOptions { * forged it: the delete answered 200, the strip logged that the value was * DROPPED, and every holder kept the deleted row's id. * + * Without the restore half, a readonly reference the delete cleared stayed + * null after a restore — the re-link runs under the caller's context too — + * while the restore counted it as re-linked. + * * Narrow on three sides, each pinned in `engine-set-null-readonly-lookup-clear.test.ts`: - * - only `update()` builds it, and only from the walk's module-private option + * - only `update()` builds it, and only from the engine's module-private option * (`REFERENTIAL_CLEAR_OPTION` in `engine-top-level.ts`) on the by-id write - * of the row the walk named — never from the context, so a caller carrying + * of the row the delete walk or the restore named — never from the context, so a caller carrying * the operation-private `__referentialFieldClear` marker gains nothing; * - only `field`: every other read-only key in the same payload is stripped, * logged, reported and refused under `strictReadonlyWrites` as before; From 326cea5a8064f490096a8217c6574e213130a15f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 18:25:09 +0000 Subject: [PATCH 5/5] docs(changeset): the restore re-link of a read-only lookup Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH --- .changeset/34899-set-null-readonly-lookup-clear.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.changeset/34899-set-null-readonly-lookup-clear.md b/.changeset/34899-set-null-readonly-lookup-clear.md index 4905e66d661..7e60444ff14 100644 --- a/.changeset/34899-set-null-readonly-lookup-clear.md +++ b/.changeset/34899-set-null-readonly-lookup-clear.md @@ -11,4 +11,6 @@ Deleting a record makes the engine clear every optional lookup that points at it The read-only rule now leaves that one key to the engine: the lookup the delete is clearing on that row, at the value the delete writes (`null`, or on a `multiple: true` lookup the remaining ids). No read-only line is logged for it, and the row's `beforeUpdate` hook sees the clear it is about to store. The exemption travels on an engine-internal channel that only the delete holds. A caller update that carries the operation-private `__referentialFieldClear` marker on its context is still stripped, still logged and still refused under `strictReadonlyWrites`. Any other read-only key in the same write is judged as before. `isSystem` is not granted. +The recycle-bin restore re-links such a lookup the same way. Its re-link also runs under the caller's context, so once the clear landed, the read-only rule dropped the re-link: after a restore the lookup stayed empty, and the restore still counted it in `relinked`. The re-link, and its undo when a restore fails partway, now use the same engine-internal channel. `relinked` counts only re-links that the row actually holds after the write. + Nothing to change in your metadata. Rows that already hold the id of a deleted record keep it: this fix does not rewrite them, so clear them with a system-context update.