diff --git a/.changeset/33246-door-skips-stamped-timestamps-in-comparisons.md b/.changeset/33246-door-skips-stamped-timestamps-in-comparisons.md new file mode 100644 index 00000000000..d9a600ad2b6 --- /dev/null +++ b/.changeset/33246-door-skips-stamped-timestamps-in-comparisons.md @@ -0,0 +1,23 @@ +--- +'@objectstack/lint': minor +--- + +fix(lint): the flow and hook publish doors accept an unguarded ordering comparison over `created_at` / `updated_at`, the two system columns the platform stamps on every stored row, as `os build` does + +Clause-②: yes (widening) — the flow and hook publish doors (Studio, `/api/v1/meta`, the MCP and AI authoring doors) now accept a condition they refused and `os build` accepted: `created_at` or `updated_at` (as the registry injects them, on an object whose storage the platform provisions) read off the current row (bare in a flow, or `record.`) as an operand of `<`, `<=`, `>` or `>=` with no `!= null` guard, in a record-triggered flow or in a hook whose every event is `afterInsert`, `beforeUpdate`, `afterUpdate`, `beforeDelete` or `afterDelete`. Nothing that published before is refused, and no other verdict moves: arithmetic over either column, a `previous.` read, a `beforeInsert` or read-event hook, and the other six injected columns keep their verdicts. `os build`, `os validate`, `os lint` and the MCP `validate_expression` tool are unchanged. No exported type or signature changes. +Metadata-protocol: added +Skills-docs: none owed — no skill teaches that `created_at` or `updated_at` needs a null guard in a flow or hook condition, or that the door refuses one; the door now gives the verdict `os build` already gives on those two columns under an ordering comparison. + +**Before:** every runtime publish door hands the authoring rules the objects as the registry serves them, and a served object carries the columns the registry injects as declared fields with `required: false` and no default. The null-guard gate read every one of them as nullable, so the flow and hook publish doors refused `record.created_at > timestamp('2025-01-01T00:00:00Z')` or `record.updated_at > record.created_at` in a record-triggered flow's start condition, edge condition or `decision` branch, or in a hook `condition`, with `422 INVALID_METADATA` (`expression-invalid`), while `os build` and `validate_expression` accepted the same condition. + +**Now:** at a runtime publish door the null-guard gate does not report `created_at` or `updated_at` when the column is the platform's own injected definition on an object whose storage the platform provisions, the operand is the current row's column (a record-triggered flow's bare trigger-record name, or `record.created_at` / `record.updated_at`), and the operator is an ordering comparison (`<`, `<=`, `>`, `>=`). The warrant is the stamp: the platform writes both columns on every stored row in its own `beforeInsert` hook (`sys_stamp_audit_insert`, priority 10), so a read of the current row after it is never `null`. A record-triggered flow reads the stored row after it; so does a hook on `afterInsert`, `beforeUpdate`, `afterUpdate`, `beforeDelete` or `afterDelete`. A hook keeps every verdict unless each of its `events` is one of those five. + +**Unchanged:** + +- A `previous.created_at` / `previous.updated_at` read is judged as before: an insert binds `previous` itself to `null`, so `record.updated_at > previous.updated_at` in an `afterInsert` hook or a create-leg flow is refused, and the message names the full guard (`previous != null && previous.updated_at != null`). +- A hook whose `events` include `beforeInsert` (it can run before the stamp, at any `priority`) or a read event (`beforeFind`, `afterFind`: no record) is judged as before. +- Arithmetic over either column is refused at every door, as before: `record.created_at + 1 > 0` and `record.updated_at - record.created_at > duration('1h')` at a hook, at an action, and in a flow's `record.` spelling (where the null-guard is the door's refusal), and the bare `created_at + 1 > 0` in a flow (where the type verdict is). +- A `created_at` the author declares, and the one on an ADR-0015 `external` object, are judged as before. +- The door still judges six injected columns nullable: `owner_id`, `created_by`, `updated_by`, `owning_business_unit_id` and `queue`, which a stored row can hold `null` in, and `organization_id`, which org scoping stamps on insert. +- On those six, and on a `beforeInsert` or read-event hook's ordering over `created_at` / `updated_at`, the door and `os build` still differ (the build judges no injected column) until #33435 settles their verdict. +- The `object_extension` door, which reads the objects as authored, is unchanged. diff --git a/packages/lint/src/validate-expressions.flow-null-guards.test.ts b/packages/lint/src/validate-expressions.flow-null-guards.test.ts index a1134f89857..f419b83f6b7 100644 --- a/packages/lint/src/validate-expressions.flow-null-guards.test.ts +++ b/packages/lint/src/validate-expressions.flow-null-guards.test.ts @@ -8,6 +8,9 @@ import { describe, it, expect } from 'vitest'; +import { applyInjectedSystemColumns } from '@objectstack/metadata-core'; +import { EXPRESSION_INVALID, runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; import { runStackExpressionPasses, validateStackExpressions } from './validate-expressions.js'; // `budget` and `owner` are optional, as on `showcase_project`; `name` is @@ -228,3 +231,202 @@ describe('flow conditions under the null-guard gate (#29026)', () => { })])).toEqual([]); }); }); + +// #33246 — the runtime publish door hands the rules every object as the +// registry SERVES it: the system columns the registry injects (`created_at`, +// `updated_at`, `owner_id`, …) are declared fields there, `required: false` +// with no default. The platform stamps two of them (`created_at`, +// `updated_at`) on every stored row, so the door's null-guard gate leaves out +// one shape over them, the one `os build` accepts and a stored row cannot +// fault: an ordering comparison (`<`, `<=`, `>`, `>=`) on the CURRENT row's +// column (bare in a flow, or `record.`), in a record-triggered flow or in a +// hook whose every event reads a stamped stored row. Everything else keeps +// `main`'s verdict: arithmetic over either column, a `previous.` read (null on +// an insert), a `beforeInsert` hook (it can run before the stamp), a read-event +// hook (no record), and the other injected columns, which can hold null on a +// stored row. The type verdicts on an injected column are untouched: the door +// keeps the served types. +describe('the publish door judges a flow or hook condition over an injected system column by what a stored row holds (#33246)', () => { + /** The trigger object as authored; `sharingModel` keeps `security-owd-unset` quiet. */ + const account = { + name: 'crm_account', + label: 'Account', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' }, amount: { type: 'number', label: 'Amount' } }, + }; + /** The same object as the registry serves it to the door. */ + const served = applyInjectedSystemColumns(account); + + /** A record-triggered flow with the condition at one of the three slots the gate judges. */ + const flowAt = (slot: 'start' | 'edge' | 'branch', condition: string, objectName = 'crm_account', triggerType = 'record-after-update'): Rec => ({ + name: `at_${slot}`, + label: 'Probe', + type: 'autolaunched', + nodes: [ + { + id: 'start', type: 'start', label: 'Start', + config: { objectName, triggerType, ...(slot === 'start' ? { condition } : {}) }, + }, + { + id: 'triage', type: 'decision', label: 'Triage', + ...(slot === 'branch' ? { config: { conditions: [{ label: 'hit', expression: condition }, { label: 'rest', expression: 'true' }] } } : {}), + }, + { id: 'alert', type: 'end', label: 'Alert' }, + { id: 'calm', type: 'end', label: 'Calm' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'triage' }, + { id: 'e2', source: 'triage', target: 'alert', ...(slot === 'branch' ? { label: 'hit' } : slot === 'edge' ? { condition } : {}) }, + { id: 'e3', source: 'triage', target: 'calm', ...(slot === 'branch' ? { label: 'rest' } : { isDefault: true }) }, + ], + }); + const hookOn = (object: string | string[], condition: string): Rec => ({ + name: 'probe_hook', object, events: ['beforeUpdate'], condition, body: { language: 'js', source: 'return;' }, + }); + + type Write = { type: 'flow' | 'hook'; item: Rec; collection: 'flows' | 'hooks' }; + /** Every site kind the gate judges: three flow slots, a hook on one object and on a list. */ + const writes = (condition: string, objectName = 'crm_account'): Write[] => [ + ...(['start', 'edge', 'branch'] as const).map((slot): Write => ({ type: 'flow', item: flowAt(slot, condition, objectName), collection: 'flows' })), + { type: 'hook', item: hookOn(objectName, condition), collection: 'hooks' }, + { type: 'hook', item: hookOn([objectName], condition), collection: 'hooks' }, + ]; + const label = (w: Write, condition: string) => `${w.type} ${String(w.item.name)}: ${condition}`; + const shape = (f: { rule: string; where: string; path?: string; message: string }) => + ({ rule: f.rule, where: f.where, path: f.path, message: f.message }); + /** The door's expression findings on the write, over the given objects as served. */ + const atDoor = ({ type, item }: Write, objects: unknown[] = [served]) => { + const { errors, advisories } = runRuntimeAuthoringRules({ type, item, context: { objects } }); + return [...errors, ...advisories].filter((f) => f.rule === EXPRESSION_INVALID).map(shape); + }; + /** `os build`'s expression findings on the same item, over the object as authored. */ + const atBuild = ({ item, collection }: Write, objects: unknown[] = [account]) => { + const stack = { objects, [collection]: [item] }; + return runAuthoringRules('build', { normalized: stack, parsed: stack }) + .filter((f) => f.rule === EXPRESSION_INVALID).map(shape); + }; + const nullGuardOn = (column: string) => (f: { message: string }) => + f.message.includes(`\`record.${column}\``) && f.message.includes('declares as nullable'); + + it('serves the trigger object with the injected columns declared, nullable by the field\'s own keys', () => { + expect(Object.keys(served.fields)).toEqual(expect.arrayContaining([ + 'created_at', 'updated_at', 'owner_id', 'created_by', 'updated_by', 'owning_business_unit_id', 'queue', + ])); + }); + + it('⭐ LIT — an unguarded ordering over `created_at` / `updated_at` publishes at every flow slot and at a hook, as the build accepts it', () => { + for (const condition of [ + "record.created_at > timestamp('2025-01-01T00:00:00Z')", + 'record.updated_at > record.created_at', + ]) { + for (const write of writes(condition)) { + expect(atDoor(write), label(write, condition)).toEqual([]); + expect(atBuild(write), label(write, condition)).toEqual([]); + } + } + }); + + it('⭐ LIT — an unguarded ordering over an injected column a stored row can hold null in is still refused at the door', () => { + for (const column of ['owner_id', 'created_by', 'updated_by', 'owning_business_unit_id', 'queue']) { + const condition = `record.${column} > 'a'`; + for (const write of writes(condition)) { + const door = atDoor(write); + expect(door, label(write, condition)).toHaveLength(1); + expect(door.filter(nullGuardOn(column)), label(write, condition)).toHaveLength(1); + } + } + }); + + it('⭐ LIT — the door keeps its type verdict on an injected column: date arithmetic on `created_at` is refused at a hook, a flow and an action', () => { + // A hook reads `record.`; a record-triggered flow binds the trigger + // record's fields as bare names, and the type verdict reads that spelling. + const cases: Array<[label: string, type: 'flow' | 'hook' | 'action', item: Rec]> = [ + ['hook', 'hook', hookOn('crm_account', 'record.created_at + 1 > 0')], + ['hook', 'hook', hookOn('crm_account', "record.updated_at - record.created_at > duration('1h')")], + ['flow start', 'flow', flowAt('start', 'created_at + 1 > 0')], + ['flow edge', 'flow', flowAt('edge', 'created_at + 1 > 0')], + ['action', 'action', { name: 'touch', label: 'Touch', objectName: 'crm_account', type: 'script', visible: 'record.created_at + 1 > 0', body: { language: 'js', source: 'return;' } }], + ]; + for (const [where, type, item] of cases) { + const { errors } = runRuntimeAuthoringRules({ type, item, context: { objects: [served] } }); + const refused = errors.filter((f) => f.rule === EXPRESSION_INVALID); + expect(refused.map((f) => f.message).join(' | '), where).toContain('date arithmetic'); + } + }); + + it('⭐ LIT — arithmetic over `created_at` / `updated_at` in a flow\'s `record.` spelling is still refused: the skip covers an ordering comparison only', () => { + // A record-triggered flow type-checks the bare spelling, not `record.`; + // for these two shapes the null-guard verdict is the door's only refusal. + for (const [condition, column] of [ + ['record.created_at + 1 > 0', 'created_at'], + ["record.updated_at - record.created_at > duration('1h')", 'updated_at'], + ] as const) { + const write: Write = { type: 'flow', item: flowAt('start', condition), collection: 'flows' }; + const door = atDoor(write); + expect(door.filter(nullGuardOn(column)), label(write, condition)).toHaveLength(1); + } + }); + + it('⭐ LIT — a hook whose events include `beforeInsert` is still judged on `created_at` / `updated_at`: it can run before the stamp', () => { + const condition = "record.created_at > timestamp('2025-01-01T00:00:00Z')"; + for (const events of [['beforeInsert'], ['beforeInsert', 'beforeUpdate']]) { + for (const object of ['crm_account', ['crm_account']]) { + const write: Write = { type: 'hook', item: { ...hookOn(object, condition), events }, collection: 'hooks' }; + expect(atDoor(write).filter(nullGuardOn('created_at')), `${events.join(',')}: ${condition}`).toHaveLength(1); + } + } + // The same condition on an `afterInsert` hook: the row is stamped by then. + const after: Write = { type: 'hook', item: { ...hookOn('crm_account', condition), events: ['afterInsert'] }, collection: 'hooks' }; + expect(atDoor(after)).toEqual([]); + }); + + it('⭐ LIT — an ordering over `previous.updated_at` is still refused: `previous` is null on an insert', () => { + const condition = 'record.updated_at > previous.updated_at'; + const cases: Write[] = [ + { type: 'hook', item: { ...hookOn('crm_account', condition), events: ['afterInsert'] }, collection: 'hooks' }, + { type: 'flow', item: flowAt('start', condition, 'crm_account', 'record-after-create'), collection: 'flows' }, + ]; + for (const write of cases) { + const door = atDoor(write); + // Only the `previous.` read: the current row's `record.updated_at` is stamped. + expect(door, label(write, condition)).toHaveLength(1); + expect(door[0]!.message, label(write, condition)).toContain('`previous.updated_at`'); + expect(door[0]!.message, label(write, condition)).toContain('previous != null && previous.updated_at != null'); + } + }); + + it('⭐ LIT — a hook on a read event is still judged on `created_at`: a read carries no record', () => { + const condition = "record.created_at > timestamp('2025-01-01T00:00:00Z')"; + for (const events of [['beforeFind'], ['afterFind'], ['afterFind', 'afterUpdate']]) { + const write: Write = { type: 'hook', item: { ...hookOn('crm_account', condition), events }, collection: 'hooks' }; + expect(atDoor(write).filter(nullGuardOn('created_at')), `${events.join(',')}: ${condition}`).toHaveLength(1); + } + }); + + it('⭐ CONTROL — `created_at` stays judged where it is not the platform\'s own definition on platform-provisioned storage: an author\'s own declaration, an `external` object', () => { + const condition = "record.created_at > timestamp('2025-01-01T00:00:00Z')"; + // The author's own column (its own label): the stamp still writes it by + // name, but the build judges a declared field, and the door gives the + // build's verdict on it. + const declared = { ...account, fields: { ...account.fields, created_at: { type: 'datetime', label: 'Opened' } } }; + for (const write of writes(condition)) { + const door = atDoor(write, [applyInjectedSystemColumns(declared)]); + expect(door.filter(nullGuardOn('created_at')), label(write, condition)).toHaveLength(1); + expect(door, label(write, condition)).toEqual(atBuild(write, [declared])); + } + // An `external` object: the remote system owns the stored row, so the platform's stamp is no warrant. + const remote = { ...account, name: 'crm_remote', external: { connector: 'erp', remoteName: 'accounts' } }; + for (const write of writes(condition, 'crm_remote')) { + expect(atDoor(write, [applyInjectedSystemColumns(remote)]).filter(nullGuardOn('created_at')), label(write, condition)).toHaveLength(1); + } + }); + + it('⭐ CONTROL — an unguarded ordering over a declared nullable field is refused at the door and at the build alike', () => { + for (const write of writes('record.amount > 0')) { + const door = atDoor(write); + expect(door, label(write, 'record.amount > 0')).toHaveLength(1); + expect(door[0]!.message).toContain('declares as nullable'); + expect(door, label(write, 'record.amount > 0')).toEqual(atBuild(write)); + } + }); +}); diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 9de87306420..7ec64a38de5 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -4223,7 +4223,9 @@ const READ_SURFACES: Array<{ receiver: string; expected: string[]; declaredBy: s }, { receiver: 'hook', - expected: ['condition', 'name', 'object'], + // [#33246] `events` picks whether the null-guard gate may leave out an + // ordering over a platform-stamped timestamp (never on `beforeInsert`). + expected: ['condition', 'events', 'name', 'object'], declaredBy: 'ObjectStackSchema.hooks[]', keys: () => shapeKeysOf(ObjectStackSchema.shape.hooks), }, @@ -4467,6 +4469,15 @@ describe('validateStackExpressions — reads only keys the spec declares (meta-t // bare-name set. Their keys are that module's result key and Set // methods, never metadata keys. 'rootScope', 'declaredVariables', 'nullGuardBare', + // [#33246] The door's platform-stamped column index (object name → the + // stamped columns it serves) and one object's set of it. Their keys are + // Map / Set methods, never metadata keys; the metadata keys the index is + // built from are read off the tabled `obj` / `def` receivers. + 'platformStampedIndex', 'stamped', + // [#33246] A hook's `events` value, handed whole to the stamped-row + // check; its keys are Array methods. The metadata read is `hook.events`, + // on the tabled `hook` receiver. + 'hookEvents', // [#29926] The fault-outcome ledger's own site descriptor (`kind`, // `severity`, `triggerKind`, `sweepsTypedObject`), built at each call site from the // tabled receivers (`rule.severity`) — never read off metadata itself. diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index 0f0665c533c..68cab7c5183 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -134,7 +134,14 @@ import type { FlowNodeParsed, FlowEdgeParsed, FlowTriggerKind } from '@objectsta // hand-written notion of "blank" here — that drift is what #15662 built the // shared refusal to prevent. import { EvaluatedExpressionInputSchema, EVALUATED_EXPRESSION_SOURCE_REQUIRED } from '@objectstack/spec/shared'; -import { referenceCarrierOf, referenceTargetOf, REFERENCE_VALUE_TYPES } from '@objectstack/spec/data'; +import { + injectedSystemColumnDefs, + isInjectedColumnDefinition, + platformProvisionsStorage, + referenceCarrierOf, + referenceTargetOf, + REFERENCE_VALUE_TYPES, +} from '@objectstack/spec/data'; import { isStoredMetadataBodyObject, STORED_METADATA_BODY_PRESCRIPTION, @@ -157,7 +164,7 @@ import { import type { FlowCelEntrance } from './flow-cel-root-scope.js'; import { injectedColumnDefsFor, injectedColumnsFor, unprovisionedInjectedColumnsFor } from './system-fields.js'; import { findUnguardedNullableOperands, nullGuardMessage, provenNonNullKeys } from './validate-null-guards.js'; -import type { NullGuardOptions, NullGuardOutcome } from './validate-null-guards.js'; +import type { NullGuardFinding, NullGuardOptions, NullGuardOutcome } from './validate-null-guards.js'; import { stripInjectedSystemColumns } from '@objectstack/metadata-core'; import { objectExtensionsByTarget, objectsAsServed, objectsWithoutTiedFields, recordsOf } from './object-graph.js'; import { storedExpressionInputIssues } from './stored-expression-inputs.js'; @@ -567,6 +574,99 @@ interface FlowBareNames { readonly timeRelativeSweep: boolean; } +/** + * [#33246] The injected system columns the platform writes on EVERY stored + * row, so a read of one is never `null`: the wildcard audit hook + * (`sys_stamp_audit_insert` in `@objectstack/objectql`) writes `created_at` + * and `updated_at` unconditionally, and driver-sql creates both on every + * table it provisions (`PLATFORM_PROVISIONED_COLUMNS`, which adds the + * primary key `id`; the registry never injects `id` into the field map, so + * it has no entry here). The other injected columns are stamped only when + * there is something to stamp: a system-context insert stores `NULL` in + * `owner_id`, `created_by`, `updated_by`, `owning_business_unit_id` and + * `queue` (measured on the real engine), so they stay nullable. This package + * may not import a runtime, so the two names are spelled here. + */ +const PLATFORM_STAMPED_COLUMNS: ReadonlySet = new Set(['created_at', 'updated_at']); + +/** + * [#33246] Is this served field a platform-stamped column that is never `null` + * on a stored row? Only the platform's own definition counts + * (`isInjectedColumnDefinition` against the object's injection plan): a + * column the author declared keeps the author's keys and the author's + * verdict. An object whose schema the platform does not provision (an + * ADR-0015 `external` binding, `platformProvisionsStorage`) has no stamp + * behind the column, so it is no exception there. + */ +function isPlatformStampedColumn(obj: AnyRec, fname: string, def: AnyRec): boolean { + if (!PLATFORM_STAMPED_COLUMNS.has(fname) || !platformProvisionsStorage(obj)) return false; + const injected = injectedSystemColumnDefs(obj)[fname]; + return injected !== undefined && isInjectedColumnDefinition(def, injected); +} + +/** + * [#33246] object name → the platform-stamped columns + * ({@link isPlatformStampedColumn}) it serves. Read only at a runtime publish + * door, whose objects are SERVED: the registry injects its system columns as + * declared `required: false` fields with no default, so the null-guard gate + * reads `created_at` / `updated_at` as nullable there, while `os build` + * (declared fields only) never judges them. The nullable index keeps them; + * {@link isStampedComparisonFinding} says which of its findings the door + * leaves out. + */ +function buildPlatformStampedIndex(objects: AnyRec[]): Map> { + const idx = new Map>(); + for (const obj of objects) { + const name = typeof obj.name === 'string' ? obj.name : undefined; + if (!name) continue; + const stamped = new Set(); + for (const [fname, def] of fieldEntries(obj)) { + if (isPlatformStampedColumn(obj, fname, def)) stamped.add(fname); + } + if (stamped.size > 0) idx.set(name, stamped); + } + return idx; +} + +/** + * [#33246] The null-guard verdicts the door leaves out: an ORDERING comparison + * (`<`, `<=`, `>`, `>=`) whose operand is a platform-stamped column of the + * CURRENT row, spelled bare (a record-triggered flow's flattened trigger + * record) or `record.`, which a stored row never holds `null` in. + * Every other finding keeps its verdict: + * + * - an arithmetic operand (`+`, `-`, `*`, `/`, `%`): at a record-triggered + * flow's `record.` read the null guard is the only refusal date arithmetic + * on the column meets (the flattened site type-checks only the bare + * spelling); + * - a `previous.` operand: an insert binds `previous` itself to + * `null`, so the read faults there whatever the column holds, and the + * finding's message names the full guard (`PREVIOUS_GUARD_CLAUSE`). + */ +const STAMPED_COMPARISON_OPERATORS: ReadonlySet = new Set(['<', '<=', '>', '>=']); +function isStampedComparisonFinding(stamped: ReadonlySet | undefined, finding: NullGuardFinding): boolean { + if (!stamped || !stamped.has(finding.field) || !STAMPED_COMPARISON_OPERATORS.has(finding.operator)) return false; + return finding.operand === finding.field || finding.operand === 'record.' + finding.field; +} + +/** + * [#33246] The hook events on which a hook condition reads a STORED row the + * platform has already stamped: `record` is the stored row (overlaid with the + * write's payload) after the stamp on an `afterInsert`, and the prior row on + * an update or a delete. Not here: `beforeInsert`, which a hook can run on + * ahead of `sys_stamp_audit_insert` (priority 10) and read both columns as + * `null`, at any priority; `beforeFind` / `afterFind`, which carry no record + * at all. A hook keeps every stamped-column verdict unless each of its events + * is listed. + */ +const STAMPED_ROW_HOOK_EVENTS: ReadonlySet = new Set([ + 'afterInsert', 'beforeUpdate', 'afterUpdate', 'beforeDelete', 'afterDelete', +]); +function hookReadsStampedRow(hookEvents: unknown): boolean { + return Array.isArray(hookEvents) && hookEvents.length > 0 + && hookEvents.every((e) => typeof e === 'string' && STAMPED_ROW_HOOK_EVENTS.has(e)); +} + function buildNullableFieldIndex(objects: AnyRec[]): Map> { const idx = new Map>(); for (const obj of objects) { @@ -2374,7 +2474,10 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // through `stripInjectedSystemColumns` (`@objectstack/metadata-core`, the // write path's own strip of exactly those, as `authored-site-expression.ts` // reads the served objects), and the indexes re-derive the injected columns - // themselves, as they do at the build. + // themselves, as they do at the build. Every other runtime door keeps the + // served objects, so its type verdicts on an injected column stand; only an + // ordering comparison over the two platform-stamped timestamps leaves the + // null-guard verdicts (#33246, {@link buildPlatformStampedIndex}). if (extensionWrite) stack = { ...stack, objects: recordsOf(stack.objects).map((o) => stripInjectedSystemColumns(o)) }; const objects = recordsOf(stack.objects); // [#30471] The field indexes read the objects as the registry SERVES them, @@ -2394,6 +2497,11 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression const attachedOnReadIndex = buildAttachedOnReadIndex(objects); const fieldTypeIndex = buildFieldTypeIndex(typedObjects); const nullableIndex = buildNullableFieldIndex(typedObjects); + // [#33246] Read at a runtime publish door only: the build passes no write + // type, so its null-guard verdicts are what they were. + const platformStampedIndex = options.runtimeWriteType !== undefined + ? buildPlatformStampedIndex(typedObjects) + : new Map>(); // [#24316] object name → its references into a stored-metadata-body table, // read the first time a site of that object serves a hop, or (#24677) when // the walk reaches the object's fields, whichever comes first — never before @@ -2604,13 +2712,19 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression outcome: NullGuardOutcome = 'fail-closed', // [#29026] A flow's flattened bare names and its start condition's proofs. scope: Pick = {}, + // [#33246] At a runtime door, leave out an ordering comparison over a + // platform-stamped column ({@link isStampedComparisonFinding}). A caller + // whose predicate can run before the stamp passes `false`. + { stampedComparisons = true }: { stampedComparisons?: boolean } = {}, ): void => { if (!objectName) return; const nullableFields = nullableIndex.get(objectName); if (!nullableFields || nullableFields.size === 0) return; const source = celSourceOf(raw); if (!source) return; + const stamped = stampedComparisons ? platformStampedIndex.get(objectName) : undefined; for (const finding of findUnguardedNullableOperands(source, { nullableFields, ...scope })) { + if (isStampedComparisonFinding(stamped, finding)) continue; issues.push({ where, message: nullGuardMessage(subject, objectName, finding, outcome), @@ -4320,6 +4434,11 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // run on every record (or never) instead of the intended subset. for (const hook of objectWrite ? [] : recordsOf(stack.hooks)) { const hookName = (hook.name as string) ?? '?'; + // [#33246] Only a hook whose every event reads a stamped stored row may + // leave out an ordering over `created_at` / `updated_at` + // ({@link hookReadsStampedRow}): not on `beforeInsert`, `beforeFind` or + // `afterFind`. + const stampedComparisons = hookReadsStampedRow(hook.events); if (typeof hook.object === 'string') { check(`hook '${hookName}' (${hook.object}) condition`, hook.condition, hook.object, 'record', undefined, undefined, undefined, undefined, faultOutcomeOf({ kind: 'hook condition' })); // #4763 — the third instance the issue found lived on exactly this path. @@ -4328,6 +4447,9 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression `hook '${hookName}' condition`, hook.condition, hook.object, + undefined, + undefined, + { stampedComparisons }, ); continue; } @@ -4360,6 +4482,9 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression `hook '${hookName}' condition`, hook.condition, target, + undefined, + undefined, + { stampedComparisons }, ); for (let i = mark; i < issues.length; i++) { const issue = issues[i]; diff --git a/packages/runtime/src/domains/meta-flow-hook-injected-column-null-guard.test.ts b/packages/runtime/src/domains/meta-flow-hook-injected-column-null-guard.test.ts new file mode 100644 index 00000000000..6bc0727a99f --- /dev/null +++ b/packages/runtime/src/domains/meta-flow-hook-injected-column-null-guard.test.ts @@ -0,0 +1,189 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33246] The flow and hook publish doors judge an unguarded ordering over an + * injected system column by what a stored row holds in it. + * + * The business case: an administrator publishes, in Studio, a record-triggered + * flow that runs only for accounts created this year + * (`record.created_at > timestamp('2025-01-01T00:00:00Z')`), or a hook gated + * on `record.updated_at > record.created_at`. The registry serves the account + * with the system columns it injects declared as `required: false` fields, so + * the door's null-guard gate refused both, while `os build` of the same items + * accepts them. The platform stamps `created_at` and `updated_at` on every + * stored row; the door now leaves the current row's read of either unjudged + * under an ordering comparison, but not a `previous.` read, nor on a + * `beforeInsert` hook (it can run before the stamp) or a read-event hook. + * The injected columns a stored row can hold `null` in (`owner_id`, + * `created_by`, …) stay judged. + * + * ## The rig + * + * The rig of `meta-object-extension-item.test.ts`: better-sqlite3 `:memory:` + * behind the real `ObjectQL` engine, the real `sys_metadata*` objects and a + * real `ObjectStackProtocolImplementation` over its `SchemaRegistry`. The base + * is a code package registered through `registerApp`, so the door reads the + * account exactly as the registry serves it. Each item is saved as a draft in + * a writable package and published through `publishMetaItem`. + */ + +import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SysMetadata, SysMetadataHistoryObject, SysMetadataAuditObject } from '@objectstack/platform-objects/metadata'; +import { runAuthoringRules } from '@objectstack/lint'; +// The protocol's package door reaches `import('@objectstack/metadata')`; pay +// that load during collection, never inside a clocked case +// (check:test-source-alias). +import '@objectstack/metadata'; + +let home: string; +let priorHome: string | undefined; +beforeAll(() => { + priorHome = process.env.OS_HOME; + home = mkdtempSync(join(tmpdir(), 'os-injected-column-null-guard-')); + process.env.OS_HOME = home; +}); +afterAll(() => { + if (priorHome === undefined) delete process.env.OS_HOME; + else process.env.OS_HOME = priorHome; + rmSync(home, { recursive: true, force: true }); +}); + +const BASE = 'com.acme.crm'; +const PAIR = 'com.acme.crm.custom'; +const TARGET = 'crm_account'; + +/** The account as authored: no system column declared. */ +const account = { + name: TARGET, + label: 'Account', + sharingModel: 'private', + fields: { + name: { name: 'name', label: 'Name', type: 'text' }, + amount: { name: 'amount', label: 'Amount', type: 'number' }, + }, +}; + +const liveEngines: ObjectQL[] = []; +afterEach(async () => { + while (liveEngines.length) { + try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +async function boot() { + const engine = new ObjectQL(); + liveEngines.push(engine); + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }), true); + await engine.init(); + engine.registry.registerObject(SysMetadata as any, 'objectstack-test'); + engine.registry.registerObject(SysMetadataHistoryObject as any, 'objectstack-test'); + engine.registry.registerObject(SysMetadataAuditObject as any, 'objectstack-test'); + (engine.registry as unknown as { logLevel: string }).logLevel = 'silent'; + engine.registerApp({ id: BASE, name: 'crm', version: '3.4.1', type: 'app', namespace: 'crm', objects: [account] }); + await engine.syncSchemas(); + const protocol = new ObjectStackProtocolImplementation(engine as any, () => new Map()) as any; + await protocol.installPackage({ + manifest: { id: PAIR, name: 'crm-custom', version: '0.1.0', type: 'app', namespace: 'crm_custom', dependencies: { [BASE]: '^3' } }, + }); + /** Save as a draft in the writable package, then publish; the refusal, or `undefined` when it published. */ + const publish = async (type: 'flow' | 'hook', item: Record) => { + await protocol.saveMetaItem({ type, name: item.name, item, mode: 'draft', packageId: PAIR }); + return protocol.publishMetaItem({ type, name: item.name, packageId: PAIR }).then(() => undefined, (e: any) => e); + }; + const state = async (type: string, name: unknown) => + ((await engine.find('sys_metadata', { where: { type, name }, context: { isSystem: true } })) ?? []) + .map((r: any) => r.state); + return { engine, publish, state }; +} + +/** A record-triggered flow on the account whose start node carries the condition. */ +const flowOn = (name: string, condition: string) => ({ + name, + label: 'Probe', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: TARGET, triggerType: 'record-after-update', condition } }, + { id: 'done', type: 'end', label: 'Done' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'done' }], +}); +const hookOn = (name: string, condition: string) => ({ + name, object: TARGET, events: ['beforeUpdate'], condition, body: { language: 'js', source: 'return;' }, +}); + +/** `os build`'s expression findings on the item, over the account as authored. */ +const atBuild = (collection: 'flows' | 'hooks', item: unknown) => { + const stack = { objects: [account], [collection]: [item] }; + return runAuthoringRules('build', { normalized: stack, parsed: stack } as any) + .filter((f) => f.rule === 'expression-invalid'); +}; + +const SINCE = "record.created_at > timestamp('2025-01-01T00:00:00Z')"; +const ORDER = 'record.updated_at > record.created_at'; + +describe('[#33246] the flow and hook publish doors judge an injected column by what a stored row holds', () => { + it('a stored row holds the two stamped timestamps and can hold null in the other injected columns', async () => { + const rig = await boot(); + const served = rig.engine.registry.getObject(TARGET) as any; + // The door reads this definition: every injected column declared, none required. + for (const column of ['created_at', 'updated_at', 'owner_id', 'created_by']) { + expect(served?.fields?.[column]?.required, column).toBe(false); + } + const created: any = await rig.engine.insert(TARGET, { name: 'Acme', organization_id: 'org_1' }, { context: { isSystem: true } }); + const row: any = await rig.engine.findOne(TARGET, { where: { id: created.id }, context: { isSystem: true } }); + expect(row?.created_at).toBeTruthy(); + expect(row?.updated_at).toBeTruthy(); + expect(row?.owner_id ?? null).toBeNull(); + expect(row?.created_by ?? null).toBeNull(); + }, 60_000); + + for (const [type, collection, build] of [ + ['flow', 'flows', flowOn], + ['hook', 'hooks', hookOn], + ] as const) { + it(`⭐ LIT — a ${type} whose condition orders \`created_at\` / \`updated_at\` with no guard publishes, as \`os build\` accepts it`, async () => { + const rig = await boot(); + for (const [name, condition] of [[`${type}_since`, SINCE], [`${type}_order`, ORDER]] as const) { + const item = build(name, condition); + expect(atBuild(collection, item), condition).toEqual([]); + const err = await rig.publish(type, item); + expect(err?.issues ?? err, `${condition}: the door refused`).toBeUndefined(); + expect(await rig.state(type, name)).toEqual(['active']); + } + }, 60_000); + + it(`⭐ LIT — a ${type} whose condition orders \`owner_id\` with no guard is still refused: a stored row can hold null there`, async () => { + const rig = await boot(); + const item = build(`${type}_owner`, "record.owner_id > 'a'"); + const err: any = await rig.publish(type, item); + expect(err, 'the publish was admitted').toBeInstanceOf(Error); + expect({ code: err.code, status: err.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + const issues = (err.issues ?? []).filter((i: any) => i.rule === 'expression-invalid'); + expect(issues, JSON.stringify(err.issues)).toHaveLength(1); + expect(issues[0].message).toContain('`record.owner_id`'); + expect(await rig.state(type, item.name)).toEqual(['draft']); + }, 60_000); + } + + it('⭐ LIT — a `beforeInsert` hook whose condition orders `created_at` with no guard is still refused: it can run before the stamp', async () => { + const rig = await boot(); + const item = { ...hookOn('hook_before_insert', SINCE), events: ['beforeInsert'] }; + const err: any = await rig.publish('hook', item); + expect(err, 'the publish was admitted').toBeInstanceOf(Error); + expect({ code: err.code, status: err.status }).toEqual({ code: 'INVALID_METADATA', status: 422 }); + const issues = (err.issues ?? []).filter((i: any) => i.rule === 'expression-invalid'); + expect(issues, JSON.stringify(err.issues)).toHaveLength(1); + expect(issues[0].message).toContain('`record.created_at`'); + expect(await rig.state('hook', item.name)).toEqual(['draft']); + }, 60_000); +});