Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .changeset/33246-door-skips-stamped-timestamps-in-comparisons.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
'@objectstack/lint': minor
---

fix(lint): the flow and hook publish doors accept an unguarded ordering comparison over `created_at` / `updated_at`, the two system columns the platform stamps on every stored row, as `os build` does

Clause-②: yes (widening) — the flow and hook publish doors (Studio, `/api/v1/meta`, the MCP and AI authoring doors) now accept a condition they refused and `os build` accepted: `created_at` or `updated_at` (as the registry injects them, on an object whose storage the platform provisions) read off the current row (bare in a flow, or `record.`) as an operand of `<`, `<=`, `>` or `>=` with no `!= null` guard, in a record-triggered flow or in a hook whose every event is `afterInsert`, `beforeUpdate`, `afterUpdate`, `beforeDelete` or `afterDelete`. Nothing that published before is refused, and no other verdict moves: arithmetic over either column, a `previous.` read, a `beforeInsert` or read-event hook, and the other six injected columns keep their verdicts. `os build`, `os validate`, `os lint` and the MCP `validate_expression` tool are unchanged. No exported type or signature changes.
Metadata-protocol: added
Skills-docs: none owed — no skill teaches that `created_at` or `updated_at` needs a null guard in a flow or hook condition, or that the door refuses one; the door now gives the verdict `os build` already gives on those two columns under an ordering comparison.

**Before:** every runtime publish door hands the authoring rules the objects as the registry serves them, and a served object carries the columns the registry injects as declared fields with `required: false` and no default. The null-guard gate read every one of them as nullable, so the flow and hook publish doors refused `record.created_at > timestamp('2025-01-01T00:00:00Z')` or `record.updated_at > record.created_at` in a record-triggered flow's start condition, edge condition or `decision` branch, or in a hook `condition`, with `422 INVALID_METADATA` (`expression-invalid`), while `os build` and `validate_expression` accepted the same condition.

**Now:** at a runtime publish door the null-guard gate does not report `created_at` or `updated_at` when the column is the platform's own injected definition on an object whose storage the platform provisions, the operand is the current row's column (a record-triggered flow's bare trigger-record name, or `record.created_at` / `record.updated_at`), and the operator is an ordering comparison (`<`, `<=`, `>`, `>=`). The warrant is the stamp: the platform writes both columns on every stored row in its own `beforeInsert` hook (`sys_stamp_audit_insert`, priority 10), so a read of the current row after it is never `null`. A record-triggered flow reads the stored row after it; so does a hook on `afterInsert`, `beforeUpdate`, `afterUpdate`, `beforeDelete` or `afterDelete`. A hook keeps every verdict unless each of its `events` is one of those five.

**Unchanged:**

- A `previous.created_at` / `previous.updated_at` read is judged as before: an insert binds `previous` itself to `null`, so `record.updated_at > previous.updated_at` in an `afterInsert` hook or a create-leg flow is refused, and the message names the full guard (`previous != null && previous.updated_at != null`).
- A hook whose `events` include `beforeInsert` (it can run before the stamp, at any `priority`) or a read event (`beforeFind`, `afterFind`: no record) is judged as before.
- Arithmetic over either column is refused at every door, as before: `record.created_at + 1 > 0` and `record.updated_at - record.created_at > duration('1h')` at a hook, at an action, and in a flow's `record.` spelling (where the null-guard is the door's refusal), and the bare `created_at + 1 > 0` in a flow (where the type verdict is).
- A `created_at` the author declares, and the one on an ADR-0015 `external` object, are judged as before.
- The door still judges six injected columns nullable: `owner_id`, `created_by`, `updated_by`, `owning_business_unit_id` and `queue`, which a stored row can hold `null` in, and `organization_id`, which org scoping stamps on insert.
- On those six, and on a `beforeInsert` or read-event hook's ordering over `created_at` / `updated_at`, the door and `os build` still differ (the build judges no injected column) until #33435 settles their verdict.
- The `object_extension` door, which reads the objects as authored, is unchanged.
202 changes: 202 additions & 0 deletions packages/lint/src/validate-expressions.flow-null-guards.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -228,3 +231,202 @@ describe('flow conditions under the null-guard gate (#29026)', () => {
})])).toEqual([]);
});
});

// #33246 — the runtime publish door hands the rules every object as the
// registry SERVES it: the system columns the registry injects (`created_at`,
// `updated_at`, `owner_id`, …) are declared fields there, `required: false`
// with no default. The platform stamps two of them (`created_at`,
// `updated_at`) on every stored row, so the door's null-guard gate leaves out
// one shape over them, the one `os build` accepts and a stored row cannot
// fault: an ordering comparison (`<`, `<=`, `>`, `>=`) on the CURRENT row's
// column (bare in a flow, or `record.`), in a record-triggered flow or in a
// hook whose every event reads a stamped stored row. Everything else keeps
// `main`'s verdict: arithmetic over either column, a `previous.` read (null on
// an insert), a `beforeInsert` hook (it can run before the stamp), a read-event
// hook (no record), and the other injected columns, which can hold null on a
// stored row. The type verdicts on an injected column are untouched: the door
// keeps the served types.
describe('the publish door judges a flow or hook condition over an injected system column by what a stored row holds (#33246)', () => {
/** The trigger object as authored; `sharingModel` keeps `security-owd-unset` quiet. */
const account = {
name: 'crm_account',
label: 'Account',
sharingModel: 'private',
fields: { name: { type: 'text', label: 'Name' }, amount: { type: 'number', label: 'Amount' } },
};
/** The same object as the registry serves it to the door. */
const served = applyInjectedSystemColumns(account);

/** A record-triggered flow with the condition at one of the three slots the gate judges. */
const flowAt = (slot: 'start' | 'edge' | 'branch', condition: string, objectName = 'crm_account', triggerType = 'record-after-update'): Rec => ({
name: `at_${slot}`,
label: 'Probe',
type: 'autolaunched',
nodes: [
{
id: 'start', type: 'start', label: 'Start',
config: { objectName, triggerType, ...(slot === 'start' ? { condition } : {}) },
},
{
id: 'triage', type: 'decision', label: 'Triage',
...(slot === 'branch' ? { config: { conditions: [{ label: 'hit', expression: condition }, { label: 'rest', expression: 'true' }] } } : {}),
},
{ id: 'alert', type: 'end', label: 'Alert' },
{ id: 'calm', type: 'end', label: 'Calm' },
],
edges: [
{ id: 'e1', source: 'start', target: 'triage' },
{ id: 'e2', source: 'triage', target: 'alert', ...(slot === 'branch' ? { label: 'hit' } : slot === 'edge' ? { condition } : {}) },
{ id: 'e3', source: 'triage', target: 'calm', ...(slot === 'branch' ? { label: 'rest' } : { isDefault: true }) },
],
});
const hookOn = (object: string | string[], condition: string): Rec => ({
name: 'probe_hook', object, events: ['beforeUpdate'], condition, body: { language: 'js', source: 'return;' },
});

type Write = { type: 'flow' | 'hook'; item: Rec; collection: 'flows' | 'hooks' };
/** Every site kind the gate judges: three flow slots, a hook on one object and on a list. */
const writes = (condition: string, objectName = 'crm_account'): Write[] => [
...(['start', 'edge', 'branch'] as const).map((slot): Write => ({ type: 'flow', item: flowAt(slot, condition, objectName), collection: 'flows' })),
{ type: 'hook', item: hookOn(objectName, condition), collection: 'hooks' },
{ type: 'hook', item: hookOn([objectName], condition), collection: 'hooks' },
];
const label = (w: Write, condition: string) => `${w.type} ${String(w.item.name)}: ${condition}`;
const shape = (f: { rule: string; where: string; path?: string; message: string }) =>
({ rule: f.rule, where: f.where, path: f.path, message: f.message });
/** The door's expression findings on the write, over the given objects as served. */
const atDoor = ({ type, item }: Write, objects: unknown[] = [served]) => {
const { errors, advisories } = runRuntimeAuthoringRules({ type, item, context: { objects } });
return [...errors, ...advisories].filter((f) => f.rule === EXPRESSION_INVALID).map(shape);
};
/** `os build`'s expression findings on the same item, over the object as authored. */
const atBuild = ({ item, collection }: Write, objects: unknown[] = [account]) => {
const stack = { objects, [collection]: [item] };
return runAuthoringRules('build', { normalized: stack, parsed: stack })
.filter((f) => f.rule === EXPRESSION_INVALID).map(shape);
};
const nullGuardOn = (column: string) => (f: { message: string }) =>
f.message.includes(`\`record.${column}\``) && f.message.includes('declares as nullable');

it('serves the trigger object with the injected columns declared, nullable by the field\'s own keys', () => {
expect(Object.keys(served.fields)).toEqual(expect.arrayContaining([
'created_at', 'updated_at', 'owner_id', 'created_by', 'updated_by', 'owning_business_unit_id', 'queue',
]));
});

it('⭐ LIT — an unguarded ordering over `created_at` / `updated_at` publishes at every flow slot and at a hook, as the build accepts it', () => {
for (const condition of [
"record.created_at > timestamp('2025-01-01T00:00:00Z')",
'record.updated_at > record.created_at',
]) {
for (const write of writes(condition)) {
expect(atDoor(write), label(write, condition)).toEqual([]);
expect(atBuild(write), label(write, condition)).toEqual([]);
}
}
});

it('⭐ LIT — an unguarded ordering over an injected column a stored row can hold null in is still refused at the door', () => {
for (const column of ['owner_id', 'created_by', 'updated_by', 'owning_business_unit_id', 'queue']) {
const condition = `record.${column} > 'a'`;
for (const write of writes(condition)) {
const door = atDoor(write);
expect(door, label(write, condition)).toHaveLength(1);
expect(door.filter(nullGuardOn(column)), label(write, condition)).toHaveLength(1);
}
}
});

it('⭐ LIT — the door keeps its type verdict on an injected column: date arithmetic on `created_at` is refused at a hook, a flow and an action', () => {
// A hook reads `record.`; a record-triggered flow binds the trigger
// record's fields as bare names, and the type verdict reads that spelling.
const cases: Array<[label: string, type: 'flow' | 'hook' | 'action', item: Rec]> = [
['hook', 'hook', hookOn('crm_account', 'record.created_at + 1 > 0')],
['hook', 'hook', hookOn('crm_account', "record.updated_at - record.created_at > duration('1h')")],
['flow start', 'flow', flowAt('start', 'created_at + 1 > 0')],
['flow edge', 'flow', flowAt('edge', 'created_at + 1 > 0')],
['action', 'action', { name: 'touch', label: 'Touch', objectName: 'crm_account', type: 'script', visible: 'record.created_at + 1 > 0', body: { language: 'js', source: 'return;' } }],
];
for (const [where, type, item] of cases) {
const { errors } = runRuntimeAuthoringRules({ type, item, context: { objects: [served] } });
const refused = errors.filter((f) => f.rule === EXPRESSION_INVALID);
expect(refused.map((f) => f.message).join(' | '), where).toContain('date arithmetic');
}
});

it('⭐ LIT — arithmetic over `created_at` / `updated_at` in a flow\'s `record.` spelling is still refused: the skip covers an ordering comparison only', () => {
// A record-triggered flow type-checks the bare spelling, not `record.`;
// for these two shapes the null-guard verdict is the door's only refusal.
for (const [condition, column] of [
['record.created_at + 1 > 0', 'created_at'],
["record.updated_at - record.created_at > duration('1h')", 'updated_at'],
] as const) {
const write: Write = { type: 'flow', item: flowAt('start', condition), collection: 'flows' };
const door = atDoor(write);
expect(door.filter(nullGuardOn(column)), label(write, condition)).toHaveLength(1);
}
});

it('⭐ LIT — a hook whose events include `beforeInsert` is still judged on `created_at` / `updated_at`: it can run before the stamp', () => {
const condition = "record.created_at > timestamp('2025-01-01T00:00:00Z')";
for (const events of [['beforeInsert'], ['beforeInsert', 'beforeUpdate']]) {
for (const object of ['crm_account', ['crm_account']]) {
const write: Write = { type: 'hook', item: { ...hookOn(object, condition), events }, collection: 'hooks' };
expect(atDoor(write).filter(nullGuardOn('created_at')), `${events.join(',')}: ${condition}`).toHaveLength(1);
}
}
// The same condition on an `afterInsert` hook: the row is stamped by then.
const after: Write = { type: 'hook', item: { ...hookOn('crm_account', condition), events: ['afterInsert'] }, collection: 'hooks' };
expect(atDoor(after)).toEqual([]);
});

it('⭐ LIT — an ordering over `previous.updated_at` is still refused: `previous` is null on an insert', () => {
const condition = 'record.updated_at > previous.updated_at';
const cases: Write[] = [
{ type: 'hook', item: { ...hookOn('crm_account', condition), events: ['afterInsert'] }, collection: 'hooks' },
{ type: 'flow', item: flowAt('start', condition, 'crm_account', 'record-after-create'), collection: 'flows' },
];
for (const write of cases) {
const door = atDoor(write);
// Only the `previous.` read: the current row's `record.updated_at` is stamped.
expect(door, label(write, condition)).toHaveLength(1);
expect(door[0]!.message, label(write, condition)).toContain('`previous.updated_at`');
expect(door[0]!.message, label(write, condition)).toContain('previous != null && previous.updated_at != null');
}
});

it('⭐ LIT — a hook on a read event is still judged on `created_at`: a read carries no record', () => {
const condition = "record.created_at > timestamp('2025-01-01T00:00:00Z')";
for (const events of [['beforeFind'], ['afterFind'], ['afterFind', 'afterUpdate']]) {
const write: Write = { type: 'hook', item: { ...hookOn('crm_account', condition), events }, collection: 'hooks' };
expect(atDoor(write).filter(nullGuardOn('created_at')), `${events.join(',')}: ${condition}`).toHaveLength(1);
}
});

it('⭐ CONTROL — `created_at` stays judged where it is not the platform\'s own definition on platform-provisioned storage: an author\'s own declaration, an `external` object', () => {
const condition = "record.created_at > timestamp('2025-01-01T00:00:00Z')";
// The author's own column (its own label): the stamp still writes it by
// name, but the build judges a declared field, and the door gives the
// build's verdict on it.
const declared = { ...account, fields: { ...account.fields, created_at: { type: 'datetime', label: 'Opened' } } };
for (const write of writes(condition)) {
const door = atDoor(write, [applyInjectedSystemColumns(declared)]);
expect(door.filter(nullGuardOn('created_at')), label(write, condition)).toHaveLength(1);
expect(door, label(write, condition)).toEqual(atBuild(write, [declared]));
}
// An `external` object: the remote system owns the stored row, so the platform's stamp is no warrant.
const remote = { ...account, name: 'crm_remote', external: { connector: 'erp', remoteName: 'accounts' } };
for (const write of writes(condition, 'crm_remote')) {
expect(atDoor(write, [applyInjectedSystemColumns(remote)]).filter(nullGuardOn('created_at')), label(write, condition)).toHaveLength(1);
}
});

it('⭐ CONTROL — an unguarded ordering over a declared nullable field is refused at the door and at the build alike', () => {
for (const write of writes('record.amount > 0')) {
const door = atDoor(write);
expect(door, label(write, 'record.amount > 0')).toHaveLength(1);
expect(door[0]!.message).toContain('declares as nullable');
expect(door, label(write, 'record.amount > 0')).toEqual(atBuild(write));
}
});
});
13 changes: 12 additions & 1 deletion packages/lint/src/validate-expressions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
},
Expand Down Expand Up @@ -4467,6 +4469,15 @@ describe('validateStackExpressions — reads only keys the spec declares (meta-t
// bare-name set. Their keys are that module's result key and Set
// methods, never metadata keys.
'rootScope', 'declaredVariables', 'nullGuardBare',
// [#33246] The door's platform-stamped column index (object name → the
// stamped columns it serves) and one object's set of it. Their keys are
// Map / Set methods, never metadata keys; the metadata keys the index is
// built from are read off the tabled `obj` / `def` receivers.
'platformStampedIndex', 'stamped',
// [#33246] A hook's `events` value, handed whole to the stamped-row
// check; its keys are Array methods. The metadata read is `hook.events`,
// on the tabled `hook` receiver.
'hookEvents',
// [#29926] The fault-outcome ledger's own site descriptor (`kind`,
// `severity`, `triggerKind`, `sweepsTypedObject`), built at each call site from the
// tabled receivers (`rule.severity`) — never read off metadata itself.
Expand Down
Loading
Loading