Skip to content

Commit 4101f1f

Browse files
fix(objectql): a state machine judges every write from the stored state, a clear included (#36127)
Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: follow-up #36161 ## 维护者速读 - 用户能看到的变化:带状态机的记录,清空状态字段现在和其他状态变更一样要过状态机;状态机没允许的清空会被拒绝,接口仍返回原来的"非法状态变更"错误。 - 为什么做:让状态机说到做到,任何一串写入都不能把记录带出状态机本来一步就会拒绝离开的状态。 - 出错会怎样:原本依赖清空状态字段的应用会在清空时收到 400;作者在该状态的目标里加上空值即可恢复,改动可直接撤回。 - 要你做什么:无。 ## What changes A `state_machine` validation now judges every update from the record's **stored** state, and clearing the state field (writing `null` or `''`) is a transition like any other — a transition to the empty value `''`. A clear from a state that has a key in `transitions` is refused unless that state lists `''` among its targets. The refusal is the existing one, unchanged in shape and code: `VALIDATION_FAILED` / 400, field code `invalid_transition`, `constraint: { from, to: '' }`. - Producer: `checkStateMachine` in `packages/objectql/src/validation/rule-validator.ts` (the one evaluator every write path calls: insert, update by id, multi-row update, the validate dry-run). - Docs: `content/docs/protocol/objectql/state-machine.mdx`, *Enforcement semantics*, now states the enforced rule and how to keep a state clearable (`paused: ['open', '']`). - Changeset: `.changeset/sec2-v5c7.md`, `patch` on `@objectstack/objectql`, with its BREAKING banner and its ADR-0087 disposition (`not-required`). Unchanged: a write that does not touch the state field, an unchanged value, a declared transition, a stored state with no key in `transitions` (still lenient), inserts and `initialStates`, and the seed / historical-import exemptions. ## Why A declared state machine is a promise that the record cannot be moved by a sequence of writes the machine would refuse as one write. The empty value is a value the field can hold, so moving to it is a transition the machine has to admit. ## Tests New file `packages/objectql/src/engine-state-machine-stored-state.test.ts`: the real `ObjectQL` engine over a store-backed driver, a state field that is not `required`, run through both the update-by-id and the multi-row door (16 cases). - Refused, asserting `code` + `status` + field code + `constraint`: a clear written as `null` and as `''` from a declared dead-end, with the state still stored and the next move out of it still refused; a clear from a state that does not list `''`; the same for an elevated caller. - Controls: the direct illegal transition is still refused; a declared transition lands; a clear the machine lists lands; an empty field written empty again, and a write that leaves the state alone, are not judged. <details><summary>Red on base, green after, guard ablation</summary> - Base (`db9e34ad`, the file restored from base, blob verified on disk): `Tests 8 failed | 8 passed (16)` — every refusal case red, every control green. Restored, blob equal to HEAD, `git diff HEAD` empty. - Fix: `Tests 16 passed (16)`. - Ablation 1 (the clear judged as a transition, reverted to the old exemption) via `scripts/ablation-replace.mjs`, anchor 1 → 0: `Tests 8 failed | 8 passed (16)`; restored, blob == HEAD, `git diff HEAD` empty. - Ablation 2 (the clear's target spelled as the empty value, reverted to the raw value): `Tests 10 failed | 6 passed (16)` (the listed-clear control goes red as well); restored, blob == HEAD, `git diff HEAD` empty. - Through the REST door on a real `bootStack` engine (a scratch measurement, not committed): red on base; on the fix the clear answers `400 VALIDATION_FAILED`, field `invalid_transition`, `constraint {from: closed, to: ""}`, the state stays stored, and the next move out of the dead-end answers the same refusal. - `pnpm --filter @objectstack/objectql test`: `Test Files 626 passed (626)`, `Tests 14241 passed (14241)`. `pnpm --filter @objectstack/objectql typecheck`: exit 0. </details> ## Acceptance notes - Contract-tier (L2) review of this change is owed to the security seat. - Narrowing: an app that clears a state field on purpose needs `''` in that state's targets; the refusal's `from`/`to` pair names the state. ## Verification Two-minute check: `pnpm --filter @objectstack/objectql exec vitest run src/engine-state-machine-stored-state.test.ts` — expect `16 passed`. Read first, by risk: `packages/objectql/src/validation/rule-validator.ts` (`checkStateMachine`, the update arm), then the new test file, then the changeset. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcSYaW9hZEkvXQFhPpn)_ <!-- signed: security#2 · sunhaolin · session_017xRBcW9L8Noz9BxEwjwiov --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 64b278e commit 4101f1f

4 files changed

Lines changed: 257 additions & 8 deletions

File tree

‎.changeset/sec2-v5c7.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): a state machine judges every write from the stored state, a clear included
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: what moved is that the engine judges a write clearing a state_machine field against the machine's transitions. A state meant to be clearable lists the empty value among its targets; that is the one-line fix, and it is in the refusal's from/to pair. -->
11+
12+
A `state_machine` validation judges an update from the record's stored state, and clearing the state field — writing `null` or `''` — is now a transition like any other: a transition to the empty value. So no sequence of writes leaves a state the machine would refuse to leave in one write.
13+
14+
**BREAKING**: on an update, clearing the state field of a record whose stored state has a key in `transitions` is refused unless that state lists `''` among its targets. The refusal is the existing transition refusal — `VALIDATION_FAILED` / 400 with field code `invalid_transition` and `constraint: { from, to: '' }` — on every write path (by id, multi-row, REST, MCP), for every caller, elevated ones included. To keep a state clearable, add `''` to its targets, e.g. `paused: ['open', '']`. It ships `patch` because no metadata an author writes changes (`Metadata-protocol: none`): every existing declaration parses and means what its `transitions` say; the write that now meets the declared graph is a runtime write.
15+
16+
**Unchanged.** A write that does not touch the state field, an unchanged value, a declared transition, a stored state with no key in `transitions` (still lenient), inserts and their `initialStates` check, and seed and historical-import writes (still exempt).

‎content/docs/protocol/objectql/state-machine.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ transitions: {
107107
### Enforcement semantics
108108

109109
- **On insert**, the `transitions` table is not consulted — there is no prior state to transition from. If the rule declares `initialStates`, the created value must be one of them, or the write is rejected with `invalid_initial_state` (the FSM entry point). Without `initialStates`, insert is a no-op and the starting value is constrained only by the field-level `select` option-membership check (`invalid_option`), so any declared option is a legal start.
110-
- **On update**, if the state field changed and the new value is **not** in `transitions[oldValue]`, the write is rejected. Clearing the field (writing `null`) is exempt.
110+
- **On update**, if the state field changed and the new value is **not** in `transitions[oldValue]`, the write is rejected. `oldValue` is always the **stored** state. **Clearing the field is a transition too**: writing `null` or `''` moves the record to the empty value, which is rejected (`invalid_transition`, `to: ''`) unless the stored state lists `''` among its targets — so no sequence of writes leaves a state the machine would refuse to leave in one write. A state you mean to be clearable lists `''`, e.g. `paused: ['open', '']`.
111111
- The check is **lenient where it cannot reason**: if the prior state has no key in `transitions` (legacy or externally-written data, or a state you simply forgot to declare), it does not block. Only an explicit `[]` makes a state a hard dead-end.
112112
- Only a rule with `severity: 'error'` (the default) blocks the write. `warning`/`info` are advisory: logged per write on an ordinary write, folded into **one summary line per rule** on a seed/boot load, and not evaluated at all on an `update` whose payload touches only platform-injected system columns (#13889).
113113
- **Seed writes are exempt** (#3433). Curated seed data — package bootstrap fixtures, marketplace templates, per-org replay, all loaded by `SeedLoaderService` — is a snapshot of established facts, not a record walking its lifecycle, so it bypasses the `state_machine` rule entirely: a seed may be born mid-lifecycle (a `completed` project, a `closed_won` opportunity) and neither `initialStates` (insert) nor `transitions` (update) is enforced. Every *other* validation still runs, so a seed must still satisfy field shape, `format`, `script`, and the rest. `os lint` warns when a seeded value is not a state the machine declares, so a typo is still caught before boot.
Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A declared `state_machine` judges every write from the record's STORED
5+
* state, and clearing the state field is itself a transition the machine must
6+
* admit — so no sequence of writes leaves a state the machine would refuse to
7+
* leave in one write.
8+
*
9+
* ## The rig
10+
*
11+
* The real `ObjectQL` engine over a store-backed driver (what is stored is
12+
* what a later read answers), one object whose state field is NOT required, so
13+
* the field validator never refuses an empty value on its own. Its machine:
14+
* `open → closed`, `closed` a declared dead-end (`[]`), and `paused`, which
15+
* lists the empty value `''` and so may be cleared.
16+
*
17+
* ## Pins
18+
*
19+
* - a clear from a declared state is refused with the transition refusal
20+
* (`VALIDATION_FAILED` / 400, field code `invalid_transition`, `from → ''`),
21+
* by id and through the bulk door, for an elevated caller too, written as
22+
* `null` or as `''`; nothing is written, so the next write is judged from
23+
* the state still stored;
24+
* - the direct illegal transition is still refused (control);
25+
* CONTROLS: a declared transition lands; a clear the machine lists lands; an
26+
* empty field written empty again, and a write that does not touch the state
27+
* field, are not judged.
28+
*/
29+
30+
import { describe, it, expect, beforeEach } from 'vitest';
31+
import { resolveThrownHttpError } from '@objectstack/types';
32+
import { ObjectQL } from './engine.js';
33+
import { ValidationError } from './validation/record-validator.js';
34+
35+
const OBJ = 'smss_ticket';
36+
37+
const TICKET = {
38+
name: OBJ,
39+
label: 'Ticket',
40+
fields: {
41+
title: { name: 'title', label: 'Title', type: 'text' },
42+
status: {
43+
name: 'status',
44+
label: 'Status',
45+
type: 'select',
46+
options: [
47+
{ value: 'open', label: 'Open' },
48+
{ value: 'paused', label: 'Paused' },
49+
{ value: 'closed', label: 'Closed' },
50+
],
51+
},
52+
},
53+
validations: [{
54+
type: 'state_machine',
55+
name: 'smss_flow',
56+
message: 'That status change is not allowed.',
57+
field: 'status',
58+
events: ['update'],
59+
transitions: { open: ['closed', 'paused'], paused: ['open', ''], closed: [] },
60+
}],
61+
};
62+
63+
/** A store-backed driver: what is stored is what a later read answers. */
64+
function makeStoreDriver() {
65+
const rows = new Map<string, Record<string, any>>();
66+
const matches = (row: any, where: any): boolean => {
67+
if (!where || typeof where !== 'object') return true;
68+
return Object.entries(where).every(([k, v]: [string, any]) => {
69+
if (k === '$and') return (v as any[]).every((w) => matches(row, w));
70+
if (k.startsWith('$')) throw new Error(`store driver: unsupported combinator ${k}`);
71+
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
72+
return Object.entries(v).every(([op, target]) => {
73+
if (op === '$eq') return row?.[k] === target;
74+
if (op === '$in') return Array.isArray(target) && target.includes(row?.[k]);
75+
throw new Error(`store driver: unsupported operator ${op}`);
76+
});
77+
}
78+
return row?.[k] === v;
79+
});
80+
};
81+
let n = 0;
82+
const driver: any = {
83+
name: 'smss-store', version: '0.0.0', supports: {},
84+
async connect() {}, async disconnect() {}, async checkHealth() { return true; },
85+
async syncSchema() {},
86+
async find(_o: string, ast: any) {
87+
const hits = Array.from(rows.values()).filter((r) => matches(r, ast?.where));
88+
return (typeof ast?.limit === 'number' ? hits.slice(0, ast.limit) : hits).map((r) => ({ ...r }));
89+
},
90+
async findOne(_o: string, ast: any) {
91+
for (const r of rows.values()) if (matches(r, ast?.where)) return { ...r };
92+
return null;
93+
},
94+
async create(_o: string, data: Record<string, unknown>) {
95+
n += 1;
96+
const id = (data.id as string) ?? `rec_${n}`;
97+
const row = { ...data, id };
98+
rows.set(id, row);
99+
return { ...row };
100+
},
101+
async update(_o: string, id: string, data: Record<string, unknown>) {
102+
const row = { ...rows.get(id), ...data, id };
103+
rows.set(id, row);
104+
return { ...row };
105+
},
106+
async updateMany(_o: string, ast: any, data: Record<string, unknown>) {
107+
const hits = Array.from(rows.values()).filter((r) => matches(r, ast?.where));
108+
for (const r of hits) rows.set(r.id, { ...r, ...data, id: r.id });
109+
return hits.length;
110+
},
111+
async delete(_o: string, id: string) { return rows.delete(id); },
112+
async count(_o: string, ast: any) {
113+
return Array.from(rows.values()).filter((r) => matches(r, ast?.where)).length;
114+
},
115+
};
116+
return { driver, rows };
117+
}
118+
119+
type Envelope = { status: number; code: string; fields: Array<{ field: string; code: string; constraint?: unknown }> };
120+
121+
/** The refusal as every HTTP door reads it (ADR-0112), plus its field codes. */
122+
function envelopeOf(err: unknown): Envelope {
123+
const thrown = resolveThrownHttpError(err);
124+
const fields = ((err as any)?.fields ?? []).map((f: any) => ({ field: f.field, code: f.code, constraint: f.constraint }));
125+
return { status: thrown.status, code: thrown.code, fields };
126+
}
127+
128+
async function refusalOf(run: () => Promise<unknown>): Promise<unknown> {
129+
try {
130+
await run();
131+
} catch (e) {
132+
return e;
133+
}
134+
throw new Error('expected the write to be refused, but it succeeded');
135+
}
136+
137+
const transitionRefusal = (from: string, to: string): Envelope => ({
138+
status: 400, code: 'VALIDATION_FAILED', fields: [{ field: 'status', code: 'invalid_transition', constraint: { from, to } }],
139+
});
140+
141+
const ALICE = { userId: 'alice' };
142+
const SYSTEM = { isSystem: true, userId: 'alice' };
143+
144+
type Door = 'update by id' | 'bulk update';
145+
const DOORS: Door[] = ['update by id', 'bulk update'];
146+
147+
describe('a state machine judges every write from the stored state, a clear included', () => {
148+
let engine: ObjectQL;
149+
let rows: Map<string, Record<string, any>>;
150+
151+
beforeEach(() => {
152+
const store = makeStoreDriver();
153+
rows = store.rows;
154+
engine = new ObjectQL();
155+
engine.registerDriver(store.driver, true);
156+
engine.registerApp({ id: 'smss', name: 'State machine stored state', objects: [TICKET] } as any);
157+
});
158+
159+
const seed = (status: string | null) => rows.set('t1', { id: 't1', title: 'stored', status });
160+
const write = (door: Door, payload: Record<string, unknown>, context: Record<string, unknown> = ALICE) => {
161+
if (door === 'update by id') return engine.update(OBJ, payload, { where: { id: 't1' }, context } as any);
162+
return engine.update(OBJ, payload, { where: { id: { $in: ['t1'] } }, multi: true, context } as any);
163+
};
164+
const stored = () => rows.get('t1')?.status;
165+
166+
describe.each(DOORS)('%s', (door) => {
167+
it.each([['null', null], ['the empty string', '']] as const)(
168+
'a clear (written as %s) from a declared dead-end is refused as a transition, and the state stays stored',
169+
async (_label, empty) => {
170+
seed('closed');
171+
const err = await refusalOf(() => write(door, { status: empty }));
172+
expect(err).toBeInstanceOf(ValidationError);
173+
expect(envelopeOf(err)).toEqual(transitionRefusal('closed', ''));
174+
expect(stored()).toBe('closed');
175+
// The next write is judged from the state still stored: leaving it is refused.
176+
expect(envelopeOf(await refusalOf(() => write(door, { status: 'open' })))).toEqual(transitionRefusal('closed', 'open'));
177+
expect(stored()).toBe('closed');
178+
},
179+
);
180+
181+
it('a clear from a state that does not list the empty value is refused', async () => {
182+
seed('open');
183+
expect(envelopeOf(await refusalOf(() => write(door, { status: null })))).toEqual(transitionRefusal('open', ''));
184+
expect(stored()).toBe('open');
185+
});
186+
187+
it('an elevated caller is judged the same way', async () => {
188+
seed('closed');
189+
expect(envelopeOf(await refusalOf(() => write(door, { status: null }, SYSTEM)))).toEqual(transitionRefusal('closed', ''));
190+
expect(stored()).toBe('closed');
191+
});
192+
193+
it('control: the direct illegal transition is still refused', async () => {
194+
seed('closed');
195+
expect(envelopeOf(await refusalOf(() => write(door, { status: 'open' })))).toEqual(transitionRefusal('closed', 'open'));
196+
expect(stored()).toBe('closed');
197+
});
198+
199+
it('control: a declared transition lands', async () => {
200+
seed('open');
201+
await write(door, { status: 'closed' });
202+
expect(stored()).toBe('closed');
203+
});
204+
205+
it('control: a clear the machine lists lands', async () => {
206+
seed('paused');
207+
await write(door, { status: null });
208+
expect(stored() ?? null).toBeNull();
209+
});
210+
211+
it('control: an empty field written empty again, and a write that leaves the state alone, are not judged', async () => {
212+
seed(null);
213+
await write(door, { status: null });
214+
expect(stored() ?? null).toBeNull();
215+
seed('closed');
216+
await write(door, { title: 'renamed' });
217+
expect(rows.get('t1')).toMatchObject({ title: 'renamed', status: 'closed' });
218+
});
219+
});
220+
});

‎packages/objectql/src/validation/rule-validator.ts‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4143,9 +4143,12 @@ function evaluateRule(rule: BaseRule, ctx: RuleContext): FieldValidationError |
41434143
* State-machine check.
41444144
*
41454145
* On UPDATE (with a prior record): if the state field changed, the new value
4146-
* must appear in `transitions[oldValue]`. Lenient where it cannot reason (no
4147-
* prior record, unchanged value, or a prior state with no declared transitions)
4148-
* so it never blocks legitimate or legacy data.
4146+
* must appear in `transitions[oldValue]`, where `oldValue` is the STORED state.
4147+
* Clearing the field is a transition to the empty value `''`, judged the same
4148+
* way, so no sequence of writes leaves a state the machine would refuse to
4149+
* leave in one write. Lenient where it cannot reason (no prior record,
4150+
* unchanged value, or a prior state with no declared transitions) so it never
4151+
* blocks legitimate or legacy data.
41494152
*
41504153
* On INSERT: if the rule declares `initialStates` (#3165), the state field's
41514154
* (defaulted) value must be one of them — the FSM entry point, since a `select`
@@ -4222,19 +4225,24 @@ function checkStateMachine(
42224225
// The PATCH didn't touch the state field → no transition to validate.
42234226
if (!(rule.field in data)) return null;
42244227

4228+
// Judged from the STORED state (`previous`), never from the payload.
42254229
const from = previous[rule.field];
42264230
const to = data[rule.field];
4227-
// No change, or clearing the value → nothing to enforce.
4228-
if (from === to || to === undefined || to === null) return null;
4231+
// Clearing the field is itself a transition — to the empty value, spelled
4232+
// `''` as a choice field's empty value is — and is judged like any other,
4233+
// so no sequence of writes leaves a state the machine would refuse to leave
4234+
// in one write. A state meant to be clearable lists `''` among its targets.
4235+
if (from === to) return null; // no change
4236+
const cleared = isEmptyStateValue(to);
42294237

42304238
const fromKey = String(from);
42314239
const allowed = rule.transitions[fromKey];
42324240
// Prior state not described by the FSM (legacy / external write) — cannot
42334241
// reason about its legal targets, so don't block.
42344242
if (!Array.isArray(allowed)) return null;
42354243

4236-
if (!allowed.includes(String(to))) {
4237-
const toKey = String(to);
4244+
const toKey = cleared ? '' : String(to);
4245+
if (!allowed.includes(toKey)) {
42384246
// `constraint` carries the raw option values a client acts on; the
42394247
// built-in sentence names the same two states the way the user sees them.
42404248
return fallback('invalid_transition', { from: fromKey, to: toKey }, undefined, () => {
@@ -4248,6 +4256,11 @@ function checkStateMachine(
42484256
return null;
42494257
}
42504258

4259+
/** A state field carrying no state: absent, `null`, or the empty string. */
4260+
function isEmptyStateValue(value: unknown): boolean {
4261+
return value === undefined || value === null || value === '';
4262+
}
4263+
42514264
/**
42524265
* One option of a choice field, named the way the user sees it, in the
42534266
* caller's locale: the field's own translation

0 commit comments

Comments
 (0)