diff --git a/.changeset/33435-injected-column-null-guard-at-build.md b/.changeset/33435-injected-column-null-guard-at-build.md new file mode 100644 index 00000000000..74201f7e685 --- /dev/null +++ b/.changeset/33435-injected-column-null-guard-at-build.md @@ -0,0 +1,25 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': minor +--- + +fix(lint)!: `os build` refuses a flow or hook condition that orders or does arithmetic on an injected column a stored row can hold null in, as the publish gate already does + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: none — no skill under `skills/**` teaches a condition over an injected column or the null guard on one; `content/docs/automation/flows.mdx` and `content/docs/automation/hooks.mdx` gain the rule in this change. + + + +**BREAKING** for a stack whose record-triggered flow (start `condition`, edge `condition`, `decision` branch `expression`) or hook `condition` applies `<`, `<=`, `>`, `>=` or `+ - * / %` to an injected system column the object does not declare itself, with no `!= null` guard in the same branch. `os build` judged the null guard over the declared fields only and accepted these; the runtime publish gate, which reads the object as served with those columns declared, refused them. A stored row holds `null` there: a system-context insert stores `null` in `owner_id`, `created_by` and `updated_by`, a seeded row keeps `created_by` and `updated_by` `null`, nothing stamps `owning_business_unit_id` yet, `queue` is `null` until a queue write names one, a `beforeInsert` hook reads `organization_id` before it is resolved, and a `beforeInsert` hook with a `priority` below 10 reads `created_at` and `updated_at` before they are stamped. On such a row the flow run fails at the condition while the write that fired it lands, and a hook condition fails the write. + +What moves (each line FROM → TO): + +- `record.owner_id > 'a'` (or `created_by`, `updated_by`, `owning_business_unit_id`, `queue`, `organization_id`; bare in a flow too) at a record-triggered flow's start, edge or branch, or at a hook's `condition`: FROM accepted by `os build` and `os validate` TO refused with the publish gate's `expression-invalid` null-guard finding. +- `record.created_at > timestamp('2025-01-01T00:00:00Z')` (or `updated_at`) at a hook whose `events` include `beforeInsert`: FROM accepted by `os build` TO refused, as the publish gate refuses it. +- The MCP `validate_expression` tool at site `flow_condition` (it judges the object as authored): FROM a clean answer TO the publish gate's null-guard finding for the same conditions. +- A `publish-drafts` batch that carries a draft of the flow's or hook's own object (the draft body, which holds no injected column, replaces the served object): FROM published TO refused, as the single-item publish already refused it over the served object. + +The fix: guard the column in the same branch, `record.owner_id != null && record.owner_id > 'a'`. A flow's start-condition guard holds at every edge and branch; `has()` is no guard. + +Unchanged: the single-item publish gate's verdicts, and a batch's when it carries no draft of the flow's or hook's object; a column the object declares itself, which keeps the verdict its own keys give; `created_at` / `updated_at` at every other hook event and flow slot; equality (`==`, `!=`) on any column; and validation rules and `requiredWhen`, which both doors judge over the declared fields only. diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index 75cd35991a0..32c7df752a8 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -2602,6 +2602,11 @@ and is read as `vars["current_user"]` / `vars["vars"]`. while the write that fired it still lands. A bare `budget` is `record.budget`, and `os validate` judges it too; a start guard holds at every edge and branch — spell it `record.budget != null`, which both doors accept, and `has()` is no guard. + The columns the platform adds count too: `owner_id`, `created_by`, + `updated_by`, `owning_business_unit_id`, `queue` and `organization_id` are + `null` on a row a system write, a seed or a guest left them empty in, so they + need the same guard; `created_at` and `updated_at` are stamped on every + stored row and need none. diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index c93cf1d14f2..17d6b09b255 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -145,6 +145,17 @@ Because `record` now means the record's *state*, `record.done == true` alone is on **every** update of an already-done row. If you wrote a condition under the old payload semantics expecting "the write that changed it", add the `previous` half. +**A field that can be `null` needs a `!= null` guard before `<`, `>`, `+` and the +rest** — CEL has no ordering or arithmetic over `null`, so the condition faults and +the write fails. `os build` and the publish gate refuse the unguarded form. That +holds for the columns the platform adds as well: `owner_id`, `created_by`, +`updated_by`, `owning_business_unit_id`, `queue` and `organization_id` are `null` on +a row a system write, a seed or a guest left them empty in, so write +`record.owner_id != null && record.owner_id > 'a'`. `created_at` and `updated_at` +are stamped on every stored row and need no guard, except in a `beforeInsert` hook: +one with a `priority` below 10 runs before the stamp and reads them as `null`, so +`os build` and the publish gate ask for the guard at every `beforeInsert` hook. + ## Elevation — `runAs` A hook's `ctx.api` runs with the context of the write that **fired** it. That is usually what you want, and it is the one thing that makes a column both *guarded* and *maintained* impossible to express: author `editable: false` (or `readonly: true`) so nobody hand-writes the column, and the hook that computes it is refused by the very same check. The guard and the legitimate writer are the same door. diff --git a/packages/lint/src/authored-site-expression.test.ts b/packages/lint/src/authored-site-expression.test.ts index bb8a9b20395..bb05f23e1e4 100644 --- a/packages/lint/src/authored-site-expression.test.ts +++ b/packages/lint/src/authored-site-expression.test.ts @@ -720,6 +720,19 @@ describe('judgeAuthoredSiteExpression at a flow condition — every gate pass is expect(flowEntryOn([withOwn, BAL], "record.title == 'x'")).toEqual([]); }); + // [#33435] The entry strips the injected columns and runs the walk as a flow + // write, so the build's injected-column null guard reaches it: an unguarded + // ordering over `owner_id` comes back with the publish gate's finding (it + // answered clean before), and the guarded spelling stays clean. + it('an unguarded ordering over an injected column returns the publish gate\'s null-guard finding (#33435)', () => { + const served = applyInjectedSystemColumns(FLOW_OBJ); + const entry = flowEntryOn([served], "record.owner_id > 'a'"); + expect(entry).toHaveLength(1); + expect(entry[0]![1]).toContain('`record.owner_id`'); + expect(entry).toEqual(flowGateOn([served], "record.owner_id > 'a'")); + expect(flowEntryOn([served], "record.owner_id != null && record.owner_id > 'a'")).toEqual([]); + }); + it('answers nothing when the object is not among the definitions', () => { expect(judgeAuthoredSiteExpression({ site: 'flow_condition', objectName: 'nope', expression: 'record.days > 3', objects: [FLOW_OBJ] })) .toEqual([]); 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 f419b83f6b7..25552dde458 100644 --- a/packages/lint/src/validate-expressions.flow-null-guards.test.ts +++ b/packages/lint/src/validate-expressions.flow-null-guards.test.ts @@ -246,7 +246,13 @@ describe('flow conditions under the null-guard gate (#29026)', () => { // 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)', () => { +// #33435 — `os build` reads the objects as authored, with no injected column +// declared, and used to leave every one of them out of the null-guard gate, so +// it accepted what the door refused. The flow and hook condition sites now +// judge the injected columns the authored object does not declare as the door +// judges them over the served object: the six a stored row can hold null in +// at every site, and `created_at` / `updated_at` at a `beforeInsert` hook only. +describe('a flow or hook condition over an injected system column is judged by what a stored row holds, at the publish door and at os build alike (#33246, #33435)', () => { /** The trigger object as authored; `sharingModel` keeps `security-owd-unset` quiet. */ const account = { name: 'crm_account', @@ -421,6 +427,102 @@ describe('the publish door judges a flow or hook condition over an injected syst } }); + /** The six injected columns a stored row can hold null in. */ + const NULLABLE_INJECTED = ['owner_id', 'created_by', 'updated_by', 'owning_business_unit_id', 'queue', 'organization_id']; + + it('⭐ LIT — os build refuses an unguarded ordering over each injected column a stored row can hold null in, with the door\'s finding, at every flow slot and at a hook', () => { + for (const column of NULLABLE_INJECTED) { + const condition = `record.${column} > 'a'`; + for (const write of writes(condition)) { + const build = atBuild(write); + expect(build, label(write, condition)).toHaveLength(1); + expect(build.filter(nullGuardOn(column)), label(write, condition)).toHaveLength(1); + expect(build, label(write, condition)).toEqual(atDoor(write)); + } + } + }); + + it('⭐ LIT — os build judges a flow\'s bare spelling of an injected column as it judges a declared nullable field\'s', () => { + // The door's per-write snapshot judges no bare name, a declared field's + // included (the CONTROL leg), so the build is the one reader here. + for (const [condition, column] of [["owner_id > 'a'", 'owner_id'], ['amount > 0', 'amount']] as const) { + const write: Write = { type: 'flow', item: flowAt('start', condition), collection: 'flows' }; + const build = atBuild(write); + expect(build, condition).toHaveLength(1); + expect(build[0]!.message, condition).toContain(`applies \`>\` to \`${column}\``); + expect(atDoor(write), condition).toEqual([]); + } + }); + + it('⭐ LIT — on each ownership tier os build judges exactly the injected columns the tier carries, as the door does', () => { + for (const ownership of ['business_unit', 'org', 'none'] as const) { + const tiered = { ...account, ownership }; + const servedTier = applyInjectedSystemColumns(tiered); + for (const column of NULLABLE_INJECTED) { + const condition = `record.${column} > 'a'`; + for (const write of writes(condition)) { + const build = atBuild(write, [tiered]); + expect(build.filter(nullGuardOn(column)).length, `${ownership} · ${label(write, condition)}`) + .toBe(column in servedTier.fields ? 1 : 0); + expect(build, `${ownership} · ${label(write, condition)}`).toEqual(atDoor(write, [servedTier])); + } + } + } + }); + + it('⭐ LIT — os build refuses an ordering over `created_at` / `updated_at` at a `beforeInsert` hook, and only there, as the door does', () => { + for (const condition of [ + "record.created_at > timestamp('2025-01-01T00:00:00Z')", + 'record.updated_at > record.created_at', + ]) { + 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(atBuild(write).filter((f) => f.message.includes('declares as nullable')).length, `${events.join(',')}: ${condition}`) + .toBeGreaterThan(0); + expect(atBuild(write), `${events.join(',')}: ${condition}`).toEqual(atDoor(write)); + } + } + // A hook on a stamped stored row, and every flow slot: the build accepts, as the door does. + for (const write of [ + ...writes(condition), + { type: 'hook', item: { ...hookOn('crm_account', condition), events: ['afterInsert'] }, collection: 'hooks' } as Write, + ]) { + expect(atBuild(write), label(write, condition)).toEqual([]); + expect(atDoor(write), label(write, condition)).toEqual([]); + } + } + }); + + it('⭐ CONTROL — the guarded spelling publishes and builds over every injected column', () => { + for (const column of NULLABLE_INJECTED) { + const condition = `record.${column} != null && record.${column} > 'a'`; + for (const write of writes(condition)) { + expect(atBuild(write), label(write, condition)).toEqual([]); + expect(atDoor(write), label(write, condition)).toEqual([]); + } + } + }); + + it('⭐ CONTROL — an injected column the author declares keeps the author\'s verdict at the build, as at the door', () => { + // `required: true` is the author's own claim that the column is valued. + const declared = { ...account, fields: { ...account.fields, owner_id: { type: 'lookup', reference: 'sys_user', label: 'Owner', required: true } } }; + const condition = "record.owner_id > 'a'"; + for (const write of writes(condition)) { + expect(atBuild(write, [declared]), label(write, condition)).toEqual([]); + expect(atDoor(write, [applyInjectedSystemColumns(declared)]), label(write, condition)).toEqual([]); + } + }); + + it('⭐ CONTROL — a validation rule over an injected column keeps its verdict: the build judges declared fields only there, as the object door does', () => { + const ruled = { ...account, validations: [{ name: 'owner_named', type: 'script', condition: "record.owner_id > 'a'", message: 'Owner' }] }; + const stack = { objects: [ruled] }; + const build = runAuthoringRules('build', { normalized: stack, parsed: stack }).filter((f) => f.rule === EXPRESSION_INVALID).map(shape); + expect(build).toEqual([]); + const { errors, advisories } = runRuntimeAuthoringRules({ type: 'object', item: ruled, context: { objects: [served] } }); + expect([...errors, ...advisories].filter((f) => f.rule === EXPRESSION_INVALID)).toEqual([]); + }); + 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); diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 59f7ced888f..eb694bdc5c1 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -4482,6 +4482,12 @@ describe('validateStackExpressions — reads only keys the spec declares (meta-t // check; its keys are Array methods. The metadata read is `hook.events`, // on the tabled `hook` receiver. 'hookEvents', + // [#33435] The flow and hook sites' null-guard index (the declared one + // joined with the injected columns the object as read does not carry), + // the pre-stamp index, and the join's own Maps and Sets. Their keys are + // Map / Set methods, never metadata keys; the injected columns are read + // off the spec's `injectedSystemColumnDefs` over the tabled `obj`. + 'flowHookNullableIndex', 'preStampIndex', 'carriedFieldNames', 'joinedNullable', 'joinedFields', // [#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 ec8b49e78f0..add3f7ac219 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -512,18 +512,6 @@ function isNullableField(def: AnyRec): boolean { return true; } -/** - * object name → set of field names that may hold `null` (#4763). - * - * DECLARED fields only, like {@link buildFieldTypeIndex} and for a sharper - * reason: this index feeds a BUILD-BREAKING verdict, so adding the injected - * columns {@link buildFieldIndex} now resolves would turn `record.created_at` - * comparisons into errors on stacks that ship today. Nullability there is also - * genuinely per-column and not derivable from the existence plan — the driver - * always populates `created_at`, while `owner_id` really can be NULL — so it - * needs the registry's column definitions, not this module's guesses. Leaving - * them out costs coverage, never a false error. - */ /** * [#29026] A `count` / `sum` roll-up summary is always valued: zero children is * zero. `@objectstack/objectql`'s `summaryEmptySetValue` is the authority — the @@ -583,11 +571,32 @@ interface FlowBareNames { * 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. + * it has no entry here). This package may not import a runtime, so the two + * names are spelled here. + * + * [#33435] Every other injected column can hold `null` where a flow or hook + * condition reads it, measured on the showcase over the real REST door and + * engine (sqlite, `single` posture), on all three ownership tiers: + * + * - `owner_id`, `created_by`, `updated_by`: a signed-in user's REST create + * stamps all three, but a system-context insert stores `NULL` in each, a + * system-context update leaves them so, and a seeded row keeps `created_by` + * / `updated_by` `NULL` (seeds run before any user exists; the boot claims + * only `owner_id`). Such rows fire record-triggered flows and every hook: a + * `record.owner_id > 'a'` start condition failed the run on each system + * insert ("no such overload: dyn > string") and passed on the REST + * create. A guest write and a queue park or release leave `owner_id` empty + * by design (ADR-0138 D1, ADR-0142 D3). + * - `owning_business_unit_id`: nothing stamps it yet (ADR-0117 D1), so it is + * `NULL` on every row, both tiers that carry it, every writer. + * - `queue`: `NULL` until a queue write names one (ADR-0142 D3); a REST create + * naming none stores `NULL`. + * - `organization_id`: every stored row on driver-sql carried it, a + * system-context insert included (stamped with the Default Organization; + * the `isolated` posture refuses such a write with no organization, ADR-0131 + * D9), but a `beforeInsert` hook reads it `null` whoever writes (the driver + * fills it after the hook chain), and the memory driver never stamps a + * tenant column at all. Not every reachable row, so it stays nullable. */ const PLATFORM_STAMPED_COLUMNS: ReadonlySet = new Set(['created_at', 'updated_at']); @@ -669,6 +678,17 @@ function hookReadsStampedRow(hookEvents: unknown): boolean { && hookEvents.every((e) => typeof e === 'string' && STAMPED_ROW_HOOK_EVENTS.has(e)); } +/** + * object name → set of field names that may hold `null` (#4763). + * + * The fields the objects AS READ carry, judged by their own keys + * ({@link isNullableField}): at `os build` the declared fields, at a runtime + * door the served ones, the injected system columns among them. [#33435] The + * flow and hook condition sites add the injected columns the objects as read + * do not carry ({@link buildInjectedNullableIndex}, {@link buildPreStampIndex}), + * so the build gives the door's verdict there; every other site judges this + * index alone. + */ function buildNullableFieldIndex(objects: AnyRec[]): Map> { const idx = new Map>(); for (const obj of objects) { @@ -683,6 +703,81 @@ function buildNullableFieldIndex(objects: AnyRec[]): Map> { return idx; } +/** + * [#33435] The injected system columns the platform injects on this object + * that the object AS READ does not carry as a field. `os build` reads the + * objects as authored, so there every injected column the author did not + * declare is here; a runtime door reads them as the registry SERVES them, + * where each one is already a declared field and nothing is here. A column the + * author declared keeps the author's keys and the author's verdict, at both. + */ +function injectedColumnsNotCarried(obj: AnyRec): string[] { + const carriedFieldNames = new Set(fieldEntries(obj).map(([fname]) => fname)); + return Object.keys(injectedSystemColumnDefs(obj)).filter((fname) => !carriedFieldNames.has(fname)); +} + +/** + * [#33435] object name → the injected columns a stored row can hold `null` in + * ({@link PLATFORM_STAMPED_COLUMNS} says which ones it cannot), for the + * objects as read that do not carry them ({@link injectedColumnsNotCarried}). + * Read by the flow and hook condition sites only, beside + * {@link buildNullableFieldIndex}: a runtime door judges those two sites over + * the served objects, whose injected columns are `required: false` fields + * with no default, so this is what makes `os build` give the door's verdict + * there. Every other null-guard site (a validation rule, `requiredWhen`) is + * judged over the authored object at the door too, and keeps its declared + * fields only. + */ +function buildInjectedNullableIndex(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 nullable = injectedColumnsNotCarried(obj).filter((fname) => !PLATFORM_STAMPED_COLUMNS.has(fname)); + if (nullable.length > 0) idx.set(name, new Set(nullable)); + } + return idx; +} + +/** + * [#33435] object name → the platform-stamped columns + * ({@link PLATFORM_STAMPED_COLUMNS}) the object as read does not carry. Read + * only for a hook that can run before the stamp ({@link hookRunsBeforeStamp}): + * there `created_at` / `updated_at` are `null`, and the door judges them so + * over the served objects. + */ +function buildPreStampIndex(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 = injectedColumnsNotCarried(obj).filter((fname) => PLATFORM_STAMPED_COLUMNS.has(fname)); + if (stamped.length > 0) idx.set(name, new Set(stamped)); + } + return idx; +} + +/** + * [#33435] Can this hook run before `sys_stamp_audit_insert` writes + * `created_at` / `updated_at`? A `beforeInsert` hook can, at any priority + * below the stamp's, and its condition then reads both as `null`. + */ +function hookRunsBeforeStamp(hookEvents: unknown): boolean { + return Array.isArray(hookEvents) && hookEvents.includes('beforeInsert'); +} + +/** Each object's set from both indexes, joined. */ +function joinNullableIndexes(a: Map>, b: Map>): Map> { + const joinedNullable = new Map>(); + for (const [name, fields] of a) joinedNullable.set(name, new Set(fields)); + for (const [name, fields] of b) { + const joinedFields = joinedNullable.get(name) ?? new Set(); + for (const fname of fields) joinedFields.add(fname); + joinedNullable.set(name, joinedFields); + } + return joinedNullable; +} + /** * [#4889] Does this CEL source read the `parent` root — the master-detail * header the write path binds for a detail object's field predicates? @@ -2516,6 +2611,18 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression const attachedOnReadIndex = buildAttachedOnReadIndex(objects); const fieldTypeIndex = buildFieldTypeIndex(typedObjects); const nullableIndex = buildNullableFieldIndex(typedObjects); + // [#33435] The flow and hook condition sites also judge the injected + // columns a stored row can hold `null` in, and a `beforeInsert` hook the two + // stamped timestamps, wherever the objects as read do not carry them as + // fields: at `os build`, so it gives the verdict a runtime door gives over + // the served objects. Two runtime readers hand authored objects too and + // judge the same way: the MCP `validate_expression` tool at a flow condition + // (`judgeAuthoredSiteExpression` strips the injected columns), and a + // `publish-drafts` batch carrying a draft of the flow's or hook's own object + // (the pending-draft door: the draft body replaces the served object). Read off the objects as served, a tied field included: a column + // two packages tie on is carried, so it gets no verdict, as above. + const flowHookNullableIndex = joinNullableIndexes(nullableIndex, buildInjectedNullableIndex(servedObjects)); + const preStampIndex = buildPreStampIndex(servedObjects); // [#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 @@ -2734,11 +2841,22 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // [#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 } = {}, + // [#33435] `nullable`: the index the site judges against; a flow or hook + // condition passes `flowHookNullableIndex`. `beforeStamp`: a hook that can + // run before the stamp also judges the stamped columns the objects as read + // do not carry ({@link buildPreStampIndex}). + { + stampedComparisons = true, + nullable = nullableIndex, + beforeStamp = false, + }: { stampedComparisons?: boolean; nullable?: Map>; beforeStamp?: boolean } = {}, ): void => { if (!objectName) return; - const nullableFields = nullableIndex.get(objectName); - if (!nullableFields || nullableFields.size === 0) return; + const nullableFields = new Set([ + ...(nullable.get(objectName) ?? []), + ...(beforeStamp ? preStampIndex.get(objectName) ?? [] : []), + ]); + if (nullableFields.size === 0) return; const source = celSourceOf(raw); if (!source) return; const stamped = stampedComparisons ? platformStampedIndex.get(objectName) : undefined; @@ -3201,7 +3319,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression }; const nullGuardBare = new Set(); if (nullGuardObject && rootScope.provable) { - for (const name of nullableIndex.get(nullGuardObject) ?? []) { + for (const name of flowHookNullableIndex.get(nullGuardObject) ?? []) { if (!declaredVariables.has(name) && !screenFields.has(name) && !FLOW_ENGINE_BOUND_NAMES.has(name)) { nullGuardBare.add(name); } @@ -3216,7 +3334,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression checkNullGuards(where, where, raw, nullGuardObject, flowFaultOutcome, { bareFields: nullGuardBare, ...(afterStart ? { presumed: nullGuardPresumed } : {}), - }); + }, { nullable: flowHookNullableIndex }); }; /** @@ -4472,6 +4590,13 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // ({@link hookReadsStampedRow}): not on `beforeInsert`, `beforeFind` or // `afterFind`. const stampedComparisons = hookReadsStampedRow(hook.events); + // [#33435] …and every hook judges the injected columns a stored row can + // hold `null` in, and a `beforeInsert` one the stamped timestamps too. + const hookNullGuards = { + stampedComparisons, + nullable: flowHookNullableIndex, + beforeStamp: hookRunsBeforeStamp(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. @@ -4482,7 +4607,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression hook.object, undefined, undefined, - { stampedComparisons }, + hookNullGuards, ); continue; } @@ -4517,7 +4642,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression target, undefined, undefined, - { stampedComparisons }, + hookNullGuards, ); for (let i = mark; i < issues.length; i++) { const issue = issues[i]; diff --git a/packages/metadata-protocol/src/runtime-authoring-gate.injected-column-null-guard.test.ts b/packages/metadata-protocol/src/runtime-authoring-gate.injected-column-null-guard.test.ts new file mode 100644 index 00000000000..799816266d8 --- /dev/null +++ b/packages/metadata-protocol/src/runtime-authoring-gate.injected-column-null-guard.test.ts @@ -0,0 +1,68 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33435] A `publish-drafts` batch that carries a draft of a flow's or hook's + * own object: `mergePendingDeclarations` replaces the served object with the + * draft body, which is stored without the injected system columns, so the + * gate judges the flow or hook over the object as authored. The lint's + * flow/hook null guard now adds the injected columns such an object does not + * carry, so the batch refuses the same unguarded ordering the single-item + * publish refuses over the served object (it accepted it before). + */ + +import { describe, expect, it } from 'vitest'; +import { applyInjectedSystemColumns } from '@objectstack/metadata-core'; +import { evaluateRuntimeAuthoringGate } from './runtime-authoring-gate.js'; + +const account = { + name: 'crm_account', + label: 'Account', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' } }, +}; +const served = applyInjectedSystemColumns(account); + +const flowOn = (condition: string) => ({ + name: 'route_owner', + label: 'Route owner', + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'crm_account', triggerType: 'record-after-create', condition } }, + { id: 'done', type: 'end', label: 'Done' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'done' }], +}); +const hookOn = (condition: string) => ({ + name: 'stamp_probe', object: 'crm_account', events: ['beforeInsert'], condition, + body: { language: 'js', source: 'return;' }, +}); + +type Write = { type: 'flow' | 'hook'; body: { name: string } }; +const judge = ({ type, body }: Write, pendingObjects?: unknown[]) => { + const err = evaluateRuntimeAuthoringGate({ + type, name: body.name, state: 'active', body, + objects: [served], + ...(pendingObjects ? { pending: { objects: pendingObjects } } : {}), + }).error as (Error & { issues?: Array<{ message: string }> }) | null; + return (err?.issues ?? []).map((i) => i.message).filter((m) => m.includes('declares as nullable')); +}; + +describe('[#33435] a publish-drafts batch holding the object\'s own draft judges the injected columns as the single-item publish does', () => { + const cases: Array<[string, Write, string]> = [ + ['a flow start condition over `owner_id`', { type: 'flow', body: flowOn("record.owner_id > 'a'") }, '`record.owner_id`'], + ['a `beforeInsert` hook condition over `created_at`', { type: 'hook', body: hookOn("record.created_at > timestamp('2025-01-01T00:00:00Z')") }, '`record.created_at`'], + ]; + for (const [title, write, column] of cases) { + it(`${title}: refused with the object's draft in the batch, as over the served object`, () => { + const single = judge(write); + expect(single, 'the single-item publish refuses it over the served object').toHaveLength(1); + expect(single[0]).toContain(column); + expect(judge(write, [structuredClone(account)])).toEqual(single); + }); + } + + it('CONTROL: the guarded spelling publishes with the object\'s draft in the batch', () => { + const write: Write = { type: 'flow', body: flowOn("record.owner_id != null && record.owner_id > 'a'") }; + expect(judge(write, [structuredClone(account)])).toEqual([]); + }); +}); diff --git a/packages/spec/src/migrations/entries/semantic/18.flow-hook-condition-injected-column-null-guard-at-build.ts b/packages/spec/src/migrations/entries/semantic/18.flow-hook-condition-injected-column-null-guard-at-build.ts new file mode 100644 index 00000000000..7efae77e304 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.flow-hook-condition-injected-column-null-guard-at-build.ts @@ -0,0 +1,33 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +export const entry: SemanticMigration = { + id: 'flow-hook-condition-injected-column-null-guard-at-build', + surface: + 'automation.Flow start node config.condition, edges[].condition and decision branch expression of a ' + + 'record-triggered flow, and data.Hook condition: an ordering or arithmetic operator applied, with no ' + + '!= null guard, to an injected system column the object does not declare itself (owner_id, created_by, ' + + 'updated_by, owning_business_unit_id, queue, organization_id; and created_at / updated_at in a hook whose ' + + 'events include beforeInsert)', + replacement: + 'Guard the column in the same branch: record.owner_id != null && record.owner_id > \'a\'. A start ' + + 'condition\'s guard holds at every edge and branch of the flow. has() is no guard.', + reason: + 'os build judged the null guard over the declared fields only, so it accepted these conditions while the ' + + 'runtime publish gate, which reads the object as served with the injected columns declared, refused them. ' + + 'A stored row holds null in those columns: a system-context insert stores null in owner_id, created_by and ' + + 'updated_by, a seeded row keeps created_by and updated_by null, nothing stamps owning_business_unit_id, ' + + 'queue is null until a queue write names one, a beforeInsert hook reads organization_id as null (it is ' + + 'resolved after the hook chain), and a beforeInsert hook can read created_at and updated_at as null when ' + + 'it runs before the stamp (priority below 10). CEL has no ordering or arithmetic over null, so on ' + + 'such a row the flow run fails at the condition (the write that fired it still lands) and a hook condition ' + + 'fails the write. os build now refuses the same conditions the publish gate refuses, with the same ' + + 'finding; so do the MCP validate_expression tool at a flow condition and a publish-drafts batch that ' + + 'carries a draft of the flow\'s or hook\'s own object, which both judge the object as authored. There is no mechanical rewrite: whether a null value should pass or fail the condition is the ' + + 'author\'s call.', + acceptanceCriteria: + 'os build and os validate report no expression-invalid null-guard error naming the column on the flow or ' + + 'hook condition; POST /api/v1/packages/PKG/publish-drafts publishes the flow or hook; a system-context ' + + 'insert of a row with the column empty starts the flow and the run completes past the condition.', +};