Skip to content

Commit b848c4a

Browse files
committed
Merge remote-tracking branch 'origin/main' into tmp-24472
2 parents ad7c8dd + 913fd6d commit b848c4a

22 files changed

Lines changed: 735 additions & 19 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
"@objectstack/spec": patch
3+
"@objectstack/lint": patch
4+
"@objectstack/service-analytics": patch
5+
---
6+
7+
fix(lint, service-analytics): a total over a formula field names the stored-number remedy, not a count
8+
9+
Clause-②: no
10+
11+
- **What changed.** A dataset or cube measure taking `sum`, `avg`, `min` or `max` over a `formula` field is still refused (`measure-aggregate-field-type-refused` in `os validate`, `400 DATASET_INVALID` at the dataset compile). The prescription changed. It used to name `count` / `count_distinct` as the way out, and a count read as a total is a plausible wrong number (3 records shown as "total leave days" where the true total is 10). It now reads: "The field is computed on read and stores no value: store the value as a number field (kept by a hook) and aggregate that. `count` / `count_distinct` answer a different question: how many records."
12+
- **One source.** The sentence lives in `@objectstack/spec/data` as `VIRTUAL_FIELD_AGGREGATE_REMEDY`, returned by `virtualFieldAggregateRemedy(aggregate, fieldType)` for a refused value-reading aggregate over a virtual type (`SEARCH_VIRTUAL_TYPES`, which is `formula`). The function returns `undefined` for every other pair. The lint hint, its `os explain measure-aggregate-field-type-refused` entry and the dataset compile leg all print this one sentence.
13+
- **What stays the same.** Nothing is newly accepted or refused. Every other refused pair keeps its own hint, including `count_distinct` over a JSON-stored or `multiple: true` field. The analytics door's cube-query refusal (`400 INVALID_FIELD`) and the engine's `aggregate` door keep their own wording.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/lint': minor
3+
---
4+
5+
fix(lint)!: a validation rule that reads, through a reference, a field the reference's target does not declare is refused where it is written
6+
7+
Clause-②: no (narrowing)
8+
9+
<!-- adr-0087: not-required (no-migration-prescription) No spec key, stored shape or authorable spelling is added, removed or renamed. The validation-rule pass now refuses one condition shape it accepted before: a one-hop read of a field the reference's target does not declare, which the runtime never judged (the rule had no verdict and refused every write it judged). Nothing stored changes, so there is nothing for `objectstack migrate meta` to rewrite. -->
10+
11+
**BREAKING** (an authoring narrowing), shipped as `minor` under the launch-window convention for breaking changes.
12+
13+
The validation-rule pass judges the field a rule's `condition` reads one hop through a reference against the target object's fields: the fields it declares, the system columns the platform adds to it, and `id`. It is the same check the field-formula pass makes for a formula. `os validate`, `os build` and the object save door (`PUT /api/v1/meta/object/:name`) run the same pass, under the existing `EXPRESSION_INVALID` rule. It covers a `script` or `cross_field` rule's `condition`, at the top level and inside a `conditional` rule's `then` / `otherwise`.
14+
15+
- FROM: `record.account.region == 'north'`, where `account` is a lookup to an object that declares no `region`, saved with a 200, and every write the rule judged was refused. TO: refused (`422 INVALID_METADATA` at the save door). The message names the field and the target: "unknown field `region` on `<target>`".
16+
- `record.account.status == 'closed'`, where the target declares `status`, passes as before.
17+
- A target the stack does not carry is not judged. At the save door the stack carries the live registry's objects in the written package's closure, so a target from a package it depends on is judged.
18+
- A reference read more than one hop deep (`record.account.owner.email`) keeps its own refusal and is not judged a second time.
19+
20+
What to do. Read a field the target declares, or declare the field on the target object. Do not declare it on the object that carries the rule. At `os build` and `os validate` this pass does not see a target field that an `objectExtensions` entry contributes, while the save door judges the merged object.
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 validation rule reading a field its reference's target does not declare no longer refuses every write through the other rules reading the same reference
6+
7+
Clause-②: no
8+
9+
A write loads, once per page, every column the object's validation rules read through each reference. When one rule named a field the target does not declare, the whole reference was answered as undeclared. Every rule reading through it then had no verdict and refused the write, each naming the other rule's field.
10+
11+
- The undeclared fields are left out of that shared read and judged for each rule on its own.
12+
- A rule that names one has no verdict and refuses the write, naming only its own undeclared fields.
13+
- A rule that reads only declared fields through the same reference gives the verdict it gives alone: it admits what it admits alone, and refuses with its own message.
14+
- The related read keeps its authority and its bound; an undeclared field never enters it.
15+
16+
What to do. Nothing. To find the rule at fault, re-save the object: the save door refuses the misspelt read and names the field.

‎packages/lint/src/rule-explanations.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1890,8 +1890,15 @@ const MEASURE_AGGREGATE_FIELD_TYPE_REFUSED_EXPLANATION: RuleExplanation = {
18901890
'toggle; `min` and `max`: number, currency, percent, rating, slider, progress, summary, date, ' +
18911891
'datetime, time, boolean, toggle.',
18921892
'So the fix is a field of an accepted type, or an aggregate the field\'s declaration accepts. A ' +
1893-
'quantity that must be added up or averaged has to be STORED as a numeric field (a computed ' +
1894-
'column) and aggregated as one.',
1893+
'quantity that must be added up or averaged has to be STORED as a numeric field and aggregated as ' +
1894+
'one.',
1895+
// Held equal to `VIRTUAL_FIELD_AGGREGATE_REMEDY` (`@objectstack/spec/data`) — the `fix:` line, and
1896+
// the compile leg's remedy, for this pair — by `validate-dataset-measure-aggregates.test.ts`.
1897+
'A `formula` field stores no value, whatever its `returnType` says, so `sum`, `avg`, `min` and `max` ' +
1898+
'over one have no column to read, and a count substituted for the total is a plausible wrong ' +
1899+
'number. Its fix line reads: The field is computed on read and stores no value: store the value as ' +
1900+
'a number field (kept by a hook) and aggregate that. `count` / `count_distinct` answer a different ' +
1901+
'question: how many records.',
18951902
JSON_STORED_COLUMN,
18961903
'The per-type row cannot see `multiple: true`, so `count_distinct` over a multi-capable field ' +
18971904
'flagged that way is refused by the declaration: the value is a list stored as JSON, and ' +

‎packages/lint/src/runtime-gate.object-validation-writes.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,3 +331,54 @@ describe('#22042 — a `conditional` rule\'s nested predicates meet the same ver
331331
expect(expressionFindings(result.errors), dump(result)).toEqual([]);
332332
});
333333
});
334+
335+
describe('#24468 — the object door refuses a rule hop to a field the target does not declare', () => {
336+
/** The lookup's target, delivered by ANOTHER package the written one depends on. */
337+
const account = {
338+
name: 'fx_account', label: 'Account', sharingModel: 'private', _packageId: 'com.example.accounts',
339+
fields: { status: { type: 'text', label: 'Status' } },
340+
};
341+
const order = (validations: unknown[]) => ({
342+
name: 'fx_order',
343+
label: 'Order',
344+
sharingModel: 'private',
345+
fields: { account: { type: 'lookup', label: 'Account', reference: 'fx_account' } },
346+
validations,
347+
});
348+
const rule = (name: string, condition: string) => ({ name, type: 'script', condition, message: 'x' });
349+
const gateOrder = (validations: unknown[]) => runRuntimeAuthoringRules({
350+
type: 'object',
351+
item: order(validations),
352+
context: { objects: [account] },
353+
packageScope: { packageId: 'com.example.orders', dependencies: ['com.example.accounts'] },
354+
});
355+
356+
it('⭐ LIT — the rule is REFUSED under EXPRESSION_INVALID, naming the field and the target from the other package; its valid sibling is not', () => {
357+
const result = gateOrder([rule('open_account', "record.account.status == 'closed'"), rule('north_only', "record.account.region == 'north'")]);
358+
359+
const errs = expressionFindings(result.errors);
360+
expect(errs, dump(result)).toHaveLength(1);
361+
const where = "object 'fx_order' · validation 'north_only'";
362+
expect(errs[0]).toMatchObject({ severity: 'error', where, path: where });
363+
expect(errs[0]!.message).toContain('unknown field `region` on `fx_account`');
364+
expect(errs[0]!.message).toContain('the rule has no verdict');
365+
});
366+
367+
it('⭐ LIT — a nested `condition` inside a `conditional` is judged too', () => {
368+
const result = gateOrder([{
369+
type: 'conditional', name: 'outer', when: 'record.account != null', message: 'x',
370+
then: rule('inner', "record.account.region == 'north'"),
371+
}]);
372+
373+
const errs = expressionFindings(result.errors);
374+
expect(errs.map((e) => e.where), dump(result)).toEqual(["object 'fx_order' · validation rule 'outer' then → 'inner'"]);
375+
expect(errs[0]!.message).toContain('unknown field `region` on `fx_account`');
376+
});
377+
378+
it('⭐ CONTROL — a rule reading a field the target declares publishes clean', () => {
379+
const result = gateOrder([rule('open_account', "record.account.status == 'closed'")]);
380+
381+
expect(expressionFindings(result.errors), dump(result)).toEqual([]);
382+
expect(expressionFindings(result.advisories), dump(result)).toEqual([]);
383+
});
384+
});

‎packages/lint/src/validate-dataset-measure-aggregates.test.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
MULTI_OPTION_TYPES,
2323
NUMERIC_VALUE_TYPES,
2424
STRUCTURED_JSON_TYPES,
25+
VIRTUAL_FIELD_AGGREGATE_REMEDY,
2526
isAggregateCompatibleWithFieldType,
2627
isMultiValueField,
2728
type Field,
@@ -432,6 +433,54 @@ const flaggedStackWith = (aggregate: string, fieldType: string): Record<string,
432433
fields: { name: { type: 'text' }, measured: { type: fieldType, multiple: true } },
433434
});
434435

436+
// [#24426] A total over a VIRTUAL field. A `formula` stores no value, so the
437+
// way to its total is to store the value as a number field and aggregate that;
438+
// the hint used to name `count` / `count_distinct` as the way out instead,
439+
// which turns "total leave days" into a record count. The sentence is the
440+
// spec's, the one the compile leg prints too.
441+
describe('measure-aggregate-field-type-refused — a total over a formula names the stored-number remedy', () => {
442+
it('sum over a formula field: the hint is the spec\'s stored-number remedy, the count only another question', () => {
443+
const found = findings(stackWith('sum', 'formula'));
444+
expect(found).toHaveLength(1);
445+
const [issue] = found;
446+
expect(issue.rule).toBe(RULE);
447+
expect(issue.severity).toBe('error');
448+
expect(issue.path).toBe('datasets[0].measures[0].aggregate');
449+
expect(issue.hint).toBe(VIRTUAL_FIELD_AGGREGATE_REMEDY);
450+
expect(issue.hint).toContain('store the value as a number field');
451+
expect(issue.hint).toContain('answer a different question: how many records');
452+
// The remedy comes first, and no count is offered as the way to the total.
453+
expect(issue.hint.indexOf('number field')).toBeLessThan(issue.hint.indexOf('`count`'));
454+
expect(issue.hint).not.toContain('accepts: count');
455+
expect(issue.hint).not.toContain('Either point');
456+
});
457+
458+
it('avg, min and max over a formula read the same sentence', () => {
459+
for (const aggregate of ['avg', 'min', 'max']) {
460+
const [issue] = findings(stackWith(aggregate, 'formula'));
461+
expect(issue?.hint, aggregate).toBe(VIRTUAL_FIELD_AGGREGATE_REMEDY);
462+
}
463+
});
464+
465+
it('`os explain` holds the same sentence verbatim', () => {
466+
expect(explanationOf(RULE)).toContain(VIRTUAL_FIELD_AGGREGATE_REMEDY);
467+
});
468+
469+
it('the controls: a stored class and the count_distinct × JSON-list case keep their own hints', () => {
470+
const [text] = findings(stackWith('sum', 'text'));
471+
expect(text?.hint).toContain('type accepts: count, count_distinct.');
472+
expect(text?.hint).not.toBe(VIRTUAL_FIELD_AGGREGATE_REMEDY);
473+
const [list] = findings(flaggedStackWith('count_distinct', 'select'));
474+
expect(list?.hint).toContain('declaration accepts: count.');
475+
expect(list?.hint).not.toContain('number field');
476+
const [json] = findings(stackWith('count_distinct', 'json'));
477+
expect(json?.hint).toContain('type accepts: count.');
478+
expect(json?.hint).not.toContain('number field');
479+
// count over a formula is accepted — nothing to prescribe.
480+
expect(findings(stackWith('count', 'formula'))).toEqual([]);
481+
});
482+
});
483+
435484
describe('measure-aggregate-field-type-refused — reads the declaration, not the type alone', () => {
436485
// ⭐ The addendum's pin and its control, one pair.
437486
it('refuses count_distinct over a select declared multiple: true, and accepts it over a single select', () => {
@@ -1271,7 +1320,8 @@ describe('[#22161] one-line fixes — the two ids', () => {
12711320
const facts: Record<string, readonly string[]> = {
12721321
[MEASURE_AGGREGATE_FIELD_TYPE_REFUSED]: [
12731322
'`count` accepts every type, because it reads no value',
1274-
'STORED as a numeric field (a computed column)',
1323+
'STORED as a numeric field and aggregated as one',
1324+
VIRTUAL_FIELD_AGGREGATE_REMEDY,
12751325
"a dataset's by its compile (`400 DATASET_INVALID`)",
12761326
"a cube's by the analytics door when a query names the measure (`400 INVALID_FIELD`)",
12771327
],

‎packages/lint/src/validate-dataset-measure-aggregates.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ import {
199199
STRUCTURED_JSON_TYPES,
200200
isAggregateCompatibleWithFieldType,
201201
isMultiValueField,
202+
virtualFieldAggregateRemedy,
202203
type ValueShapeFieldDef,
203204
} from '@objectstack/spec/data';
204205

@@ -417,6 +418,12 @@ function jsonStoredDimensionFinding(
417418
* further, the stored-numeric route for a sum or an average, and which door
418419
* refuses the same pair later (a dataset's compile, a cube's query) are the
419420
* same explanation's.
421+
*
422+
* [#24426] Except over a VIRTUAL field (`formula`): there the remedy line is
423+
* the spec's `virtualFieldAggregateRemedy`, the sentence the compile leg prints
424+
* too — store the value as a number field and aggregate that — because naming
425+
* `count` as the way out steers a total to a plausible wrong number (a record
426+
* count read as a sum). The count stays named, as a different question.
420427
*/
421428
function refusedMeasureFinding(
422429
site: MemberSite,
@@ -441,6 +448,7 @@ function refusedMeasureFinding(
441448
: `${pair(`\`${fieldType}\``)} is refused by the aggregate × field-type table: the number would depend ` +
442449
'on the SQL dialect',
443450
hint:
451+
virtualFieldAggregateRemedy(aggregate, fieldType) ??
444452
`Either point "${aggregate}" at a field of an accepted type, or aggregate ` +
445453
`"${site.column}" with one its ${declaredAs(shape)} ${shape.multiple === true ? 'declaration' : 'type'} accepts: ` +
446454
`${aggregatesAccepting(shape).join(', ')}.`,
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#24468] A validation rule's `condition` reads ONE hop through a reference
5+
* field, and the validation-rule pass judges the hop's COLUMN against the
6+
* target's field index, as the field-formula pass does for a formula (#24410).
7+
*
8+
* ObjectQL's predicate read loads only the columns the target declares; a rule
9+
* naming one it does not declare has no verdict and refuses every write it
10+
* judges. So the build, `os validate` and the object save door refuse it,
11+
* naming the field and the target, under the existing `expression-invalid`
12+
* rule. The runtime half is `packages/objectql/src/engine-predicate-relationship.test.ts`.
13+
* Every fixture goes through `specValid`.
14+
*/
15+
import { describe, expect, it } from 'vitest';
16+
import { ObjectStackSchema } from '@objectstack/spec';
17+
18+
import { validateStackExpressions } from './validate-expressions.js';
19+
20+
const MANIFEST = { id: 'com.example.rule-hop', name: 'rule_hop', version: '1.0.0', type: 'app' } as const;
21+
22+
/** A fixture is only a fixture if the spec accepts it. */
23+
function specValid(stack: Record<string, unknown>): Record<string, unknown> {
24+
const result = ObjectStackSchema.safeParse({ manifest: MANIFEST, ...stack });
25+
if (!result.success) {
26+
throw new Error(
27+
'fixture is not spec-valid: '
28+
+ result.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; '),
29+
);
30+
}
31+
return result.data as unknown as Record<string, unknown>;
32+
}
33+
34+
const account = { name: 'hop_account', label: 'Account', fields: { status: { type: 'text', label: 'Status' } } };
35+
const order = (condition: string, reference = 'hop_account') => ({
36+
name: 'hop_order',
37+
label: 'Order',
38+
fields: {
39+
amount: { type: 'number', label: 'Amount' },
40+
account: { type: 'lookup', label: 'Account', reference },
41+
},
42+
validations: [{ name: 'r', type: 'script', severity: 'error', message: 'x', condition }],
43+
});
44+
45+
const WHERE = "object 'hop_order' · validation 'r'";
46+
47+
const errorsOf = (condition: string, reference?: string) =>
48+
validateStackExpressions(specValid({ objects: [account, order(condition, reference)] }))
49+
.filter((i) => i.where === WHERE && (i.severity ?? 'error') === 'error');
50+
51+
describe('[#24468] a validation rule reads one hop through a reference', () => {
52+
it('admits a read of a field the target declares', () => {
53+
expect(errorsOf("record.account.status == 'closed'")).toEqual([]);
54+
});
55+
56+
it('refuses a read of a field the target does not declare, naming the field and the target', () => {
57+
const errors = errorsOf("record.account.region == 'north' && record.account.status == 'open'");
58+
expect(errors).toHaveLength(1);
59+
expect(errors[0].message).toMatch(/^unknown field `region` on `hop_account`/);
60+
expect(errors[0].message).toContain('through the reference `record.account`');
61+
expect(errors[0].message).toContain("declare 'region' on 'hop_account' — not on 'hop_order', the object carrying this rule");
62+
expect(errors[0].source).toBe("record.account.region == 'north' && record.account.status == 'open'");
63+
});
64+
65+
it('admits the primary key and a column the platform injects on the target', () => {
66+
expect(errorsOf("record.account.id != ''")).toEqual([]);
67+
expect(errorsOf('record.account.created_at != null')).toEqual([]);
68+
});
69+
70+
it('does not judge a target the stack does not carry', () => {
71+
expect(errorsOf("record.account.region == 'north'", 'hop_elsewhere')).toEqual([]);
72+
});
73+
});

‎packages/lint/src/validate-expressions.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3549,6 +3549,10 @@ describe('validateStackExpressions — reads only keys the spec declares (meta-t
35493549
// metadata keys; the metadata keys the index is built from (`type`,
35503550
// `reference`) are read off the tabled `def` receiver.
35513551
'storedMetadataBodyReferenceIndex', 'familyRefs', 'traversals',
3552+
// [#24468] The undeclared-hop refusal's whole traversal analysis, read for
3553+
// its `traversals` and `multiHopFields` — the formula package's own
3554+
// result keys, never metadata keys.
3555+
'analysis',
35523556
]);
35533557
expect(receivers.filter((r) => !tabled.has(r) && !PLUMBING.has(r))).toEqual([]);
35543558
});

0 commit comments

Comments
 (0)