From 0b0b34165d2ac63c81bd380a7ff3cd066135b588 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 20:16:58 +0000 Subject: [PATCH 1/9] fix(lint): every runtime publish door reads the objects without the injected system columns, as os build does Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mnBkyQ4d2mXNVg3Fd --- packages/lint/src/validate-expressions.ts | 37 ++++++++++++++--------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index 613f249dcbe..c95210e3876 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -2275,9 +2275,10 @@ export interface StackExpressionOptions { * same served fields (#33216: and a one-hop leaf through a reference an * extension adds judged as one through a declared reference), and located * at the entry - * (`object 'T' · objectExtensions[0] · validation 'N'`). On this write the - * live objects are read without the system columns the registry injects - * (`stripInjectedSystemColumns`), as the build reads them. The + * (`object 'T' · objectExtensions[0] · validation 'N'`). On this write, as + * on every runtime write (#33246), the live objects are read without the + * system columns the registry injects (`stripInjectedSystemColumns`), as + * the build reads them. The * object walk reads an empty list (the carried objects are the universe the * field or rule resolves in, not the subject) and so does every other pass; * the function returns after the extension walk. @@ -2365,17 +2366,25 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression if (options.runtimeWriteType === 'page') { return actionCopyTemplateIssues(stack, { actions: false, objects: false, pages: true }); } - // [#33154] The extension door hands the objects as the registry SERVES - // them, and a served definition carries the system columns the registry - // injects (`created_at`, `owner_id`, …) as declared fields; the build reads - // the objects as authored. Unstripped, the null-guard gate judged - // `record.created_at` as a declared nullable field and refused at the door - // an extension rule `os build` accepts. So on that write each object is read - // 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. - if (extensionWrite) stack = { ...stack, objects: recordsOf(stack.objects).map((o) => stripInjectedSystemColumns(o)) }; + // [#33154, #33246] Every runtime publish door hands the objects as the + // registry SERVES them (the gate's one `listRegisteredCollection` read, + // whatever the written type), and a served definition carries the system + // columns the registry injects (`created_at`, `owner_id`, …) as declared + // fields; the build reads the objects as authored. Unstripped, the + // null-guard gate judged `record.created_at` as a declared nullable field + // and refused at the door a flow condition, a hook `condition` or an + // extension rule that `os build` accepts. So on every runtime write each + // object is read 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: known fields, never judged nullable (`buildNullableFieldIndex`). + // One reading for every write type, not one per walk, so no pass at any + // door reads a column the build does not. The build passes no write type + // and reads its objects as they are. + if (options.runtimeWriteType !== undefined) { + 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, // every `objectExtensions` field of any body folded in (`objectsAsServed`, From 76a23423638652314f3a456df851d3ea557ab406 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 20:19:45 +0000 Subject: [PATCH 2/9] test(lint): the publish door judges a flow or hook condition over an injected system column as os build does Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mnBkyQ4d2mXNVg3Fd --- ...idate-expressions.flow-null-guards.test.ts | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) 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..d8d60e5ff02 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,105 @@ 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. `os build` reads the objects as authored, and its nullable +// index leaves every injected column out (`buildNullableFieldIndex`). The door +// reads its objects without those columns, so it gives the build's verdict. +describe('the publish door judges a flow or hook condition over an injected system column as `os build` does (#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): Rec => ({ + name: `at_${slot}`, + label: 'Probe', + type: 'autolaunched', + nodes: [ + { + id: 'start', type: 'start', label: 'Start', + config: { objectName: 'crm_account', triggerType: 'record-after-update', ...(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' }; + const writes = (condition: string): Write[] => [ + ...(['start', 'edge', 'branch'] as const).map((slot): Write => ({ type: 'flow', item: flowAt(slot, condition), collection: 'flows' })), + { type: 'hook', item: hookOn('crm_account', condition), collection: 'hooks' }, + { type: 'hook', item: hookOn(['crm_account'], condition), collection: 'hooks' }, + ]; + 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 objects as served. */ + const atDoor = ({ type, item }: Write) => { + const { errors, advisories } = runRuntimeAuthoringRules({ type, item, context: { objects: [served] } }); + 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) => { + const stack = { objects: [account], [collection]: [item] }; + return runAuthoringRules('build', { normalized: stack, parsed: stack }) + .filter((f) => f.rule === EXPRESSION_INVALID).map(shape); + }; + + 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'])); + }); + + it('⭐ PARITY — 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)) { + const label = `${write.type} ${String(write.item.name)}: ${condition}`; + expect(atBuild(write), label).toEqual([]); + expect(atDoor(write), label).toEqual([]); + } + } + }); + + it('⭐ PARITY — the door gives the build\'s verdict on every injected column the build leaves out of its nullable index', () => { + // The build's verdict per column is its index's docblock, not this file's: + // whatever it says about `owner_id`, the door says the same. + for (const condition of ["record.owner_id > 'a'", "record.created_by > 'a'", "record.owning_business_unit_id > 'a'"]) { + for (const write of writes(condition)) { + expect(atDoor(write), `${write.type} ${String(write.item.name)}: ${condition}`).toEqual(atBuild(write)); + } + } + }); + + 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 label = `${write.type} ${String(write.item.name)}`; + const door = atDoor(write); + expect(door, label).toHaveLength(1); + expect(door[0]!.message, label).toContain('declares as nullable'); + expect(door, label).toEqual(atBuild(write)); + } + }); +}); From 533eb60bdb742250584353fba3e50d5d17dccf13 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 20:21:54 +0000 Subject: [PATCH 3/9] chore(changeset): the publish door judges an injected system column in a flow or hook condition as os build does Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mnBkyQ4d2mXNVg3Fd --- .../33246-door-reads-objects-as-authored.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .changeset/33246-door-reads-objects-as-authored.md diff --git a/.changeset/33246-door-reads-objects-as-authored.md b/.changeset/33246-door-reads-objects-as-authored.md new file mode 100644 index 00000000000..7317055e1c7 --- /dev/null +++ b/.changeset/33246-door-reads-objects-as-authored.md @@ -0,0 +1,15 @@ +--- +'@objectstack/lint': minor +--- + +fix(lint): the runtime publish door judges a record-triggered flow condition and a hook `condition` over a system column the platform injects (`created_at`, `updated_at`, `owner_id`, …) as `os build` does + +Clause-②: yes (widening) — the flow and hook publish doors (Studio, `PUT /api/v1/meta/flow/NAME` and `/meta/hook/NAME`, the MCP and AI authoring doors) now accept a condition they refused and `os build` accepted: an ordering or arithmetic operator applied with no `!= null` guard to a column the platform injects and the object does not declare. Nothing that published before is refused; `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 an injected column 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, which is what `skills/objectstack-automation` and `skills/objectstack-data` describe. + +**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 (`created_at`, `created_by`, `updated_at`, `updated_by`, `owner_id`, `owning_business_unit_id`, `organization_id`, …) as declared fields with `required: false` and no default. The null-guard gate read them as declared nullable fields, 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 the MCP `validate_expression` tool accepted the same condition. Only the `object_extension` door read the objects without those columns. + +**Now:** every runtime publish door reads the objects without the injected columns, through the write path's own strip (`stripInjectedSystemColumns` from `@objectstack/metadata-core`), as `os build` reads the objects as authored. An injected column is still a known field, and the null-guard gate does not judge it nullable, at the door or the build. A field the object declares nullable is judged as before: `record.amount > 0` with no guard is refused at both. + +**Unchanged:** `os build`, `os validate`, `os lint`, the MCP `validate_expression` tool, every verdict on a field the object declares, and the advisory on an injected column with no storage behind it on an `external` object. From f348b545368f097072476022b8f0f87698b32bb8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:13:05 +0000 Subject: [PATCH 4/9] fix(lint): the publish door leaves only the platform-stamped timestamps out of its nullable index, and keeps every served type Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mnBkyQ4d2mXNVg3Fd --- ...idate-expressions.flow-null-guards.test.ts | 98 +++++++++++++------ packages/lint/src/validate-expressions.ts | 94 +++++++++++++----- 2 files changed, 137 insertions(+), 55 deletions(-) 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 d8d60e5ff02..150c4000fec 100644 --- a/packages/lint/src/validate-expressions.flow-null-guards.test.ts +++ b/packages/lint/src/validate-expressions.flow-null-guards.test.ts @@ -235,10 +235,12 @@ describe('flow conditions under the null-guard gate (#29026)', () => { // #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. `os build` reads the objects as authored, and its nullable -// index leaves every injected column out (`buildNullableFieldIndex`). The door -// reads its objects without those columns, so it gives the build's verdict. -describe('the publish door judges a flow or hook condition over an injected system column as `os build` does (#33246)', () => { +// with no default. The two the platform stamps on every stored row +// (`created_at`, `updated_at`) are never null, so the door's null-guard gate +// does not judge them, as `os build` does not. The other injected columns can +// hold null on a stored row and stay judged at the door. 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', @@ -250,14 +252,14 @@ describe('the publish door judges a flow or hook condition over an injected syst 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): Rec => ({ + const flowAt = (slot: 'start' | 'edge' | 'branch', condition: string, objectName = 'crm_account'): Rec => ({ name: `at_${slot}`, label: 'Probe', type: 'autolaunched', nodes: [ { id: 'start', type: 'start', label: 'Start', - config: { objectName: 'crm_account', triggerType: 'record-after-update', ...(slot === 'start' ? { condition } : {}) }, + config: { objectName, triggerType: 'record-after-update', ...(slot === 'start' ? { condition } : {}) }, }, { id: 'triage', type: 'decision', label: 'Triage', @@ -277,59 +279,97 @@ describe('the publish door judges a flow or hook condition over an injected syst }); type Write = { type: 'flow' | 'hook'; item: Rec; collection: 'flows' | 'hooks' }; - const writes = (condition: string): Write[] => [ - ...(['start', 'edge', 'branch'] as const).map((slot): Write => ({ type: 'flow', item: flowAt(slot, condition), collection: 'flows' })), - { type: 'hook', item: hookOn('crm_account', condition), collection: 'hooks' }, - { type: 'hook', item: hookOn(['crm_account'], condition), collection: '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 objects as served. */ - const atDoor = ({ type, item }: Write) => { - const { errors, advisories } = runRuntimeAuthoringRules({ type, item, context: { objects: [served] } }); + /** 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) => { - const stack = { objects: [account], [collection]: [item] }; + 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'])); + expect(Object.keys(served.fields)).toEqual(expect.arrayContaining([ + 'created_at', 'updated_at', 'owner_id', 'created_by', 'updated_by', 'owning_business_unit_id', 'queue', + ])); }); - it('⭐ PARITY — an unguarded ordering over `created_at` / `updated_at` publishes at every flow slot and at a hook, as the build accepts it', () => { + 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)) { - const label = `${write.type} ${String(write.item.name)}: ${condition}`; - expect(atBuild(write), label).toEqual([]); - expect(atDoor(write), label).toEqual([]); + expect(atDoor(write), label(write, condition)).toEqual([]); + expect(atBuild(write), label(write, condition)).toEqual([]); } } }); - it('⭐ PARITY — the door gives the build\'s verdict on every injected column the build leaves out of its nullable index', () => { - // The build's verdict per column is its index's docblock, not this file's: - // whatever it says about `owner_id`, the door says the same. - for (const condition of ["record.owner_id > 'a'", "record.created_by > 'a'", "record.owning_business_unit_id > 'a'"]) { + 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)) { - expect(atDoor(write), `${write.type} ${String(write.item.name)}: ${condition}`).toEqual(atBuild(write)); + 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('⭐ CONTROL — `created_at` stays judged where no stamp is behind it: 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): judged as any declared field, at both doors. + 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 owns the schema and nothing stamps the column. + 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 label = `${write.type} ${String(write.item.name)}`; const door = atDoor(write); - expect(door, label).toHaveLength(1); - expect(door[0]!.message, label).toContain('declares as nullable'); - expect(door, label).toEqual(atBuild(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.ts b/packages/lint/src/validate-expressions.ts index c95210e3876..202a8de3cec 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, @@ -567,13 +574,54 @@ interface FlowBareNames { readonly timeRelativeSweep: boolean; } -function buildNullableFieldIndex(objects: AnyRec[]): Map> { +/** + * [#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); +} + +function buildNullableFieldIndex( + objects: AnyRec[], + // [#33246] Set 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 two it stamps on every row would read as nullable + // and a flow or hook condition ordering `record.created_at` with no guard + // was refused where `os build` (declared fields only) accepts it. The other + // injected columns stay nullable here: they can hold `null`. The build reads + // authored objects and passes nothing, so its index is unchanged. + { platformStamped = false }: { platformStamped?: boolean } = {}, +): Map> { const idx = new Map>(); for (const obj of objects) { const name = typeof obj.name === 'string' ? obj.name : undefined; if (!name) continue; const nullable = new Set(); for (const [fname, def] of fieldEntries(obj)) { + if (platformStamped && isPlatformStampedColumn(obj, fname, def)) continue; if (isNullableField(def)) nullable.add(fname); } idx.set(name, nullable); @@ -2275,10 +2323,9 @@ export interface StackExpressionOptions { * same served fields (#33216: and a one-hop leaf through a reference an * extension adds judged as one through a declared reference), and located * at the entry - * (`object 'T' · objectExtensions[0] · validation 'N'`). On this write, as - * on every runtime write (#33246), the live objects are read without the - * system columns the registry injects (`stripInjectedSystemColumns`), as - * the build reads them. The + * (`object 'T' · objectExtensions[0] · validation 'N'`). On this write the + * live objects are read without the system columns the registry injects + * (`stripInjectedSystemColumns`), as the build reads them. The * object walk reads an empty list (the carried objects are the universe the * field or rule resolves in, not the subject) and so does every other pass; * the function returns after the extension walk. @@ -2366,25 +2413,20 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression if (options.runtimeWriteType === 'page') { return actionCopyTemplateIssues(stack, { actions: false, objects: false, pages: true }); } - // [#33154, #33246] Every runtime publish door hands the objects as the - // registry SERVES them (the gate's one `listRegisteredCollection` read, - // whatever the written type), and a served definition carries the system - // columns the registry injects (`created_at`, `owner_id`, …) as declared - // fields; the build reads the objects as authored. Unstripped, the - // null-guard gate judged `record.created_at` as a declared nullable field - // and refused at the door a flow condition, a hook `condition` or an - // extension rule that `os build` accepts. So on every runtime write each - // object is read 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: known fields, never judged nullable (`buildNullableFieldIndex`). - // One reading for every write type, not one per walk, so no pass at any - // door reads a column the build does not. The build passes no write type - // and reads its objects as they are. - if (options.runtimeWriteType !== undefined) { - stack = { ...stack, objects: recordsOf(stack.objects).map((o) => stripInjectedSystemColumns(o)) }; - } + // [#33154] The extension door hands the objects as the registry SERVES + // them, and a served definition carries the system columns the registry + // injects (`created_at`, `owner_id`, …) as declared fields; the build reads + // the objects as authored. Unstripped, the null-guard gate judged + // `record.created_at` as a declared nullable field and refused at the door + // an extension rule `os build` accepts. So on that write each object is read + // 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. Every other runtime door keeps the + // served objects, so its type verdicts on an injected column stand; only its + // null-guard reading of the two platform-stamped timestamps changes + // (#33246, {@link buildNullableFieldIndex}). + 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, // every `objectExtensions` field of any body folded in (`objectsAsServed`, @@ -2402,7 +2444,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression const fieldIndex = buildFieldIndex(servedObjects); const attachedOnReadIndex = buildAttachedOnReadIndex(objects); const fieldTypeIndex = buildFieldTypeIndex(typedObjects); - const nullableIndex = buildNullableFieldIndex(typedObjects); + const nullableIndex = buildNullableFieldIndex(typedObjects, { platformStamped: options.runtimeWriteType !== undefined }); // [#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 From 33cf7f3d1aa08e36421d659612d3b8bce9cdc1e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:18:25 +0000 Subject: [PATCH 5/9] test(runtime): the flow and hook publish doors accept an unguarded ordering over the stamped timestamps and refuse one over owner_id Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mnBkyQ4d2mXNVg3Fd --- ...ow-hook-injected-column-null-guard.test.ts | 174 ++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 packages/runtime/src/domains/meta-flow-hook-injected-column-null-guard.test.ts 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..8b68d167ea3 --- /dev/null +++ b/packages/runtime/src/domains/meta-flow-hook-injected-column-null-guard.test.ts @@ -0,0 +1,174 @@ +// 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 those two unjudged. 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); + } +}); From ddd834f5bddc6cce244fc3d162c99d4ecdb76015 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:19:38 +0000 Subject: [PATCH 6/9] chore(changeset): name the two stamped columns the door accepts and the five it still judges Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mnBkyQ4d2mXNVg3Fd --- .changeset/33246-door-reads-objects-as-authored.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.changeset/33246-door-reads-objects-as-authored.md b/.changeset/33246-door-reads-objects-as-authored.md index 7317055e1c7..74901e02a58 100644 --- a/.changeset/33246-door-reads-objects-as-authored.md +++ b/.changeset/33246-door-reads-objects-as-authored.md @@ -2,14 +2,14 @@ '@objectstack/lint': minor --- -fix(lint): the runtime publish door judges a record-triggered flow condition and a hook `condition` over a system column the platform injects (`created_at`, `updated_at`, `owner_id`, …) as `os build` does +fix(lint): the flow and hook publish doors accept an unguarded ordering or arithmetic operand 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, `PUT /api/v1/meta/flow/NAME` and `/meta/hook/NAME`, the MCP and AI authoring doors) now accept a condition they refused and `os build` accepted: an ordering or arithmetic operator applied with no `!= null` guard to a column the platform injects and the object does not declare. Nothing that published before is refused; `os build`, `os validate`, `os lint` and the MCP `validate_expression` tool are unchanged. No exported type or signature changes. +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) under an ordering or arithmetic operator with no `!= null` guard. Nothing that published before is refused, and no other verdict moves. `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 an injected column 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, which is what `skills/objectstack-automation` and `skills/objectstack-data` describe. +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. -**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 (`created_at`, `created_by`, `updated_at`, `updated_by`, `owner_id`, `owning_business_unit_id`, `organization_id`, …) as declared fields with `required: false` and no default. The null-guard gate read them as declared nullable fields, 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 the MCP `validate_expression` tool accepted the same condition. Only the `object_extension` door read the objects without those columns. +**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:** every runtime publish door reads the objects without the injected columns, through the write path's own strip (`stripInjectedSystemColumns` from `@objectstack/metadata-core`), as `os build` reads the objects as authored. An injected column is still a known field, and the null-guard gate does not judge it nullable, at the door or the build. A field the object declares nullable is judged as before: `record.amount > 0` with no guard is refused at both. +**Now:** at a runtime publish door the null-guard gate leaves out `created_at` and `updated_at` when they are the platform's own injected definitions on an object whose storage the platform provisions: the platform writes both on every stored row, so a read of either is never `null`. A `created_at` the author declares, and the one on an ADR-0015 `external` object, are judged as before. -**Unchanged:** `os build`, `os validate`, `os lint`, the MCP `validate_expression` tool, every verdict on a field the object declares, and the advisory on an injected column with no storage behind it on an `external` object. +**Unchanged:** the door keeps its type verdicts on every injected column (date arithmetic such as `record.created_at + 1 > 0` is still refused), and still judges `owner_id`, `created_by`, `updated_by`, `owning_business_unit_id` and `queue` nullable: a stored row can hold `null` in each. On those five the door and `os build` still differ (the build does not judge any injected column) until #33435 settles their verdict. The `object_extension` door, which reads the objects as authored, is unchanged. From efc8003b058caa5e8e3890c230e101f85aeed025 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:08:34 +0000 Subject: [PATCH 7/9] fix(lint): the door leaves out only an ordering comparison over the stamped timestamps, and not on a beforeInsert hook The null-guard skip at a runtime publish door now applies to an operand of `<`, `<=`, `>` or `>=` only. Arithmetic over created_at / updated_at keeps its verdict, so a flow's `record.created_at + 1 > 0` stays refused as on main. A hook whose events include beforeInsert can run before the platform's stamp, so it keeps the verdict too. The changeset is renamed for the mechanism and names the six injected columns still judged. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mnBkyQ4d2mXNVg3Fd --- .../33246-door-reads-objects-as-authored.md | 15 ---- ...skips-stamped-timestamps-in-comparisons.md | 21 +++++ ...idate-expressions.flow-null-guards.test.ts | 34 +++++++- packages/lint/src/validate-expressions.ts | 82 +++++++++++++++---- ...ow-hook-injected-column-null-guard.test.ts | 18 +++- 5 files changed, 133 insertions(+), 37 deletions(-) delete mode 100644 .changeset/33246-door-reads-objects-as-authored.md create mode 100644 .changeset/33246-door-skips-stamped-timestamps-in-comparisons.md diff --git a/.changeset/33246-door-reads-objects-as-authored.md b/.changeset/33246-door-reads-objects-as-authored.md deleted file mode 100644 index 74901e02a58..00000000000 --- a/.changeset/33246-door-reads-objects-as-authored.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -'@objectstack/lint': minor ---- - -fix(lint): the flow and hook publish doors accept an unguarded ordering or arithmetic operand 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) under an ordering or arithmetic operator with no `!= null` guard. Nothing that published before is refused, and no other verdict moves. `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. - -**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 leaves out `created_at` and `updated_at` when they are the platform's own injected definitions on an object whose storage the platform provisions: the platform writes both on every stored row, so a read of either is never `null`. A `created_at` the author declares, and the one on an ADR-0015 `external` object, are judged as before. - -**Unchanged:** the door keeps its type verdicts on every injected column (date arithmetic such as `record.created_at + 1 > 0` is still refused), and still judges `owner_id`, `created_by`, `updated_by`, `owning_business_unit_id` and `queue` nullable: a stored row can hold `null` in each. On those five the door and `os build` still differ (the build does not judge any injected column) until #33435 settles their verdict. The `object_extension` door, which reads the objects as authored, is unchanged. 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..4b93edf6e13 --- /dev/null +++ b/.changeset/33246-door-skips-stamped-timestamps-in-comparisons.md @@ -0,0 +1,21 @@ +--- +'@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) as an operand of `<`, `<=`, `>` or `>=` with no `!= null` guard, in a record-triggered flow or in a hook that does not run on `beforeInsert`. Nothing that published before is refused, and no other verdict moves: arithmetic over either column, a `beforeInsert` 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` as the operand of an ordering comparison (`<`, `<=`, `>`, `>=`) when the column is the platform's own injected definition on an object whose storage the platform provisions: the platform writes both on every stored row before any later hook reads it. A hook whose `events` include `beforeInsert` is judged as before, whatever its `priority`: it can run before the platform's stamp and read either column as `null`. + +**Unchanged:** + +- 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` 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 150c4000fec..29bf3dab702 100644 --- a/packages/lint/src/validate-expressions.flow-null-guards.test.ts +++ b/packages/lint/src/validate-expressions.flow-null-guards.test.ts @@ -348,16 +348,44 @@ describe('the publish door judges a flow or hook condition over an injected syst } }); - it('⭐ CONTROL — `created_at` stays judged where no stamp is behind it: an author\'s own declaration, an `external` object', () => { + 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('⭐ 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): judged as any declared field, at both doors. + // 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 owns the schema and nothing stamps the column. + // 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); diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index 202a8de3cec..f83a0078953 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -164,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'; @@ -604,24 +604,50 @@ function isPlatformStampedColumn(obj: AnyRec, fname: string, def: AnyRec): boole return injected !== undefined && isInjectedColumnDefinition(def, injected); } -function buildNullableFieldIndex( - objects: AnyRec[], - // [#33246] Set 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 two it stamps on every row would read as nullable - // and a flow or hook condition ordering `record.created_at` with no guard - // was refused where `os build` (declared fields only) accepts it. The other - // injected columns stay nullable here: they can hold `null`. The build reads - // authored objects and passes nothing, so its index is unchanged. - { platformStamped = false }: { platformStamped?: boolean } = {}, -): Map> { +/** + * [#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, which a + * stored row never holds `null` in. An arithmetic operand (`+`, `-`, `*`, + * `/`, `%`) keeps its verdict: 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). + */ +const STAMPED_COMPARISON_OPERATORS: ReadonlySet = new Set(['<', '<=', '>', '>=']); +function isStampedComparisonFinding(stamped: ReadonlySet | undefined, finding: NullGuardFinding): boolean { + return !!stamped && stamped.has(finding.field) && STAMPED_COMPARISON_OPERATORS.has(finding.operator); +} + +function buildNullableFieldIndex(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 = new Set(); for (const [fname, def] of fieldEntries(obj)) { - if (platformStamped && isPlatformStampedColumn(obj, fname, def)) continue; if (isNullableField(def)) nullable.add(fname); } idx.set(name, nullable); @@ -2423,9 +2449,9 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // 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. Every other runtime door keeps the - // served objects, so its type verdicts on an injected column stand; only its - // null-guard reading of the two platform-stamped timestamps changes - // (#33246, {@link buildNullableFieldIndex}). + // 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, @@ -2444,7 +2470,12 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression const fieldIndex = buildFieldIndex(servedObjects); const attachedOnReadIndex = buildAttachedOnReadIndex(objects); const fieldTypeIndex = buildFieldTypeIndex(typedObjects); - const nullableIndex = buildNullableFieldIndex(typedObjects, { platformStamped: options.runtimeWriteType !== undefined }); + 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 @@ -2655,13 +2686,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), @@ -4344,6 +4381,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] The platform stamps `created_at` / `updated_at` in its own + // `beforeInsert` hook (`sys_stamp_audit_insert`, priority 10), so a + // `beforeInsert` hook ordered ahead of it reads both as `null`. On such a + // hook (any priority) the stamped columns keep their null-guard verdict. + const stampedComparisons = !(Array.isArray(hook.events) && hook.events.includes('beforeInsert')); 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. @@ -4352,6 +4394,9 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression `hook '${hookName}' condition`, hook.condition, hook.object, + undefined, + undefined, + { stampedComparisons }, ); continue; } @@ -4384,6 +4429,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 index 8b68d167ea3..789c4dc9d98 100644 --- 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 @@ -11,8 +11,10 @@ * 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 those two unjudged. The injected columns a - * stored row can hold `null` in (`owner_id`, `created_by`, …) stay judged. + * stored row; the door now leaves those two unjudged under an ordering + * comparison, except on a `beforeInsert` hook, which can run before the stamp. + * The injected columns a stored row can hold `null` in (`owner_id`, + * `created_by`, …) stay judged. * * ## The rig * @@ -171,4 +173,16 @@ describe('[#33246] the flow and hook publish doors judge an injected column by w 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); }); From 10f6d63a53a6d58a88bc5028795ba6a92e89075d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:13:16 +0000 Subject: [PATCH 8/9] test(lint): the declared-key meta-test names the hook's events read and the stamped-column index locals Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mnBkyQ4d2mXNVg3Fd --- packages/lint/src/validate-expressions.test.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 9de87306420..0f2211ab9e3 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,11 @@ 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', // [#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. From df63888de1f086750170942ae50e2af2b3063756 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:02:14 +0000 Subject: [PATCH 9/9] fix(lint): the door leaves out only the current row's stamped timestamp, and only on a hook whose every event reads a stamped row An ordering over previous.created_at / previous.updated_at keeps its verdict: an insert binds previous to null. A hook on beforeFind or afterFind carries no record, so it keeps the verdict too; the skip now applies only when every event is afterInsert, beforeUpdate, afterUpdate, beforeDelete or afterDelete. The changeset and the test docblocks state this mechanism. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mnBkyQ4d2mXNVg3Fd --- ...skips-stamped-timestamps-in-comparisons.md | 8 ++-- ...idate-expressions.flow-null-guards.test.ts | 43 ++++++++++++++--- .../lint/src/validate-expressions.test.ts | 4 ++ packages/lint/src/validate-expressions.ts | 48 ++++++++++++++----- ...ow-hook-injected-column-null-guard.test.ts | 5 +- 5 files changed, 85 insertions(+), 23 deletions(-) diff --git a/.changeset/33246-door-skips-stamped-timestamps-in-comparisons.md b/.changeset/33246-door-skips-stamped-timestamps-in-comparisons.md index 4b93edf6e13..d9a600ad2b6 100644 --- a/.changeset/33246-door-skips-stamped-timestamps-in-comparisons.md +++ b/.changeset/33246-door-skips-stamped-timestamps-in-comparisons.md @@ -4,18 +4,20 @@ 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) as an operand of `<`, `<=`, `>` or `>=` with no `!= null` guard, in a record-triggered flow or in a hook that does not run on `beforeInsert`. Nothing that published before is refused, and no other verdict moves: arithmetic over either column, a `beforeInsert` 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. +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` as the operand of an ordering comparison (`<`, `<=`, `>`, `>=`) when the column is the platform's own injected definition on an object whose storage the platform provisions: the platform writes both on every stored row before any later hook reads it. A hook whose `events` include `beforeInsert` is judged as before, whatever its `priority`: it can run before the platform's stamp and read either column as `null`. +**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` 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. +- 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 29bf3dab702..f419b83f6b7 100644 --- a/packages/lint/src/validate-expressions.flow-null-guards.test.ts +++ b/packages/lint/src/validate-expressions.flow-null-guards.test.ts @@ -235,11 +235,17 @@ describe('flow conditions under the null-guard gate (#29026)', () => { // #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 two the platform stamps on every stored row -// (`created_at`, `updated_at`) are never null, so the door's null-guard gate -// does not judge them, as `os build` does not. The other injected columns can -// hold null on a stored row and stay judged at the door. The type verdicts on -// an injected column are untouched: the door keeps the served types. +// 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 = { @@ -252,14 +258,14 @@ describe('the publish door judges a flow or hook condition over an injected syst 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'): Rec => ({ + 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: 'record-after-update', ...(slot === 'start' ? { condition } : {}) }, + config: { objectName, triggerType, ...(slot === 'start' ? { condition } : {}) }, }, { id: 'triage', type: 'decision', label: 'Triage', @@ -374,6 +380,29 @@ describe('the publish door judges a flow or hook condition over an injected syst 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 diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 0f2211ab9e3..7ec64a38de5 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -4474,6 +4474,10 @@ describe('validateStackExpressions — reads only keys the spec declares (meta-t // 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 f83a0078953..54cede1f6d7 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -630,15 +630,41 @@ function buildPlatformStampedIndex(objects: AnyRec[]): Map> /** * [#33246] The null-guard verdicts the door leaves out: an ORDERING comparison - * (`<`, `<=`, `>`, `>=`) whose operand is a platform-stamped column, which a - * stored row never holds `null` in. An arithmetic operand (`+`, `-`, `*`, - * `/`, `%`) keeps its verdict: 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). + * (`<`, `<=`, `>`, `>=`) 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 { - return !!stamped && stamped.has(finding.field) && STAMPED_COMPARISON_OPERATORS.has(finding.operator); + 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> { @@ -4381,11 +4407,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] The platform stamps `created_at` / `updated_at` in its own - // `beforeInsert` hook (`sys_stamp_audit_insert`, priority 10), so a - // `beforeInsert` hook ordered ahead of it reads both as `null`. On such a - // hook (any priority) the stamped columns keep their null-guard verdict. - const stampedComparisons = !(Array.isArray(hook.events) && hook.events.includes('beforeInsert')); + // [#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. 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 index 789c4dc9d98..6bc0727a99f 100644 --- 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 @@ -11,8 +11,9 @@ * 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 those two unjudged under an ordering - * comparison, except on a `beforeInsert` hook, which can run before the stamp. + * 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. *