From 815a75529e1fc3e1930e852ce9dbacc0f131da7f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 3 Dec 2026 15:53:01 -0500 Subject: [PATCH 1/4] feat(metadata): reference facet targetType may list several types; role.token @heldBy names an organization or a system TypeScript reader, resolver, manifest and tests; spec text and definition schema; three shared conformance fixtures; registry and metamodel-docs corpora regenerated. --- .../expected-errors.json | 15 +++ .../input/meta.parcels.json | 15 +++ .../input/meta.tidewell.json | 9 ++ .../expected-errors.json | 15 +++ .../input/meta.parcels.json | 16 +++ .../ref-target-type-list-heldby/expected.json | 38 +++++++ .../input/meta.feeds.json | 8 ++ .../input/meta.parcels.json | 16 +++ .../input/meta.parties.json | 8 ++ .../metamodel-docs/data/types/role.md.json | 2 +- .../metamodel-docs/expected/types/role.md | 2 +- .../expected-registry.json | 7 +- .../MetaObjects/SpecMetamodel/systems.json | 2 +- .../metaobjects/spec_metamodel/systems.json | 2 +- .../metaobjects/data/metamodel/systems.json | 2 +- .../systems/systems-definition.embedded.ts | 7 +- .../typescript/packages/metadata/src/index.ts | 2 +- .../metadata/src/loader/symbol-table.ts | 81 ++++++++++++--- .../src/loader/validation-registry.ts | 24 +++-- .../packages/metadata/src/provider-data.ts | 15 ++- .../metadata/src/registry-manifest.ts | 8 +- .../packages/metadata/src/validation-types.ts | 16 ++- .../metadata/test/definition-schema.test.ts | 15 ++- .../metadata/test/reference-facet.test.ts | 99 +++++++++++++++++++ .../metadata/test/validation-registry.test.ts | 2 +- spec/metamodel-definition.schema.json | 20 +++- spec/metamodel-definitions.md | 32 +++--- spec/metamodel/systems.json | 2 +- 28 files changed, 419 insertions(+), 61 deletions(-) create mode 100644 fixtures/conformance/error-ref-ambiguous-heldby/expected-errors.json create mode 100644 fixtures/conformance/error-ref-ambiguous-heldby/input/meta.parcels.json create mode 100644 fixtures/conformance/error-ref-ambiguous-heldby/input/meta.tidewell.json create mode 100644 fixtures/conformance/error-ref-wrong-kind-heldby/expected-errors.json create mode 100644 fixtures/conformance/error-ref-wrong-kind-heldby/input/meta.parcels.json create mode 100644 fixtures/conformance/ref-target-type-list-heldby/expected.json create mode 100644 fixtures/conformance/ref-target-type-list-heldby/input/meta.feeds.json create mode 100644 fixtures/conformance/ref-target-type-list-heldby/input/meta.parcels.json create mode 100644 fixtures/conformance/ref-target-type-list-heldby/input/meta.parties.json diff --git a/fixtures/conformance/error-ref-ambiguous-heldby/expected-errors.json b/fixtures/conformance/error-ref-ambiguous-heldby/expected-errors.json new file mode 100644 index 0000000000..5d9b02d803 --- /dev/null +++ b/fixtures/conformance/error-ref-ambiguous-heldby/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_REF_UNRESOLVED", + "source": { + "format": "json", + "files": [ + "meta.parcels.json" + ], + "jsonPath": "$['metadata.root'].children[0]['system.software'].children[0]['role.token']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-ref-ambiguous-heldby/input/meta.parcels.json b/fixtures/conformance/error-ref-ambiguous-heldby/input/meta.parcels.json new file mode 100644 index 0000000000..026f2f0ca0 --- /dev/null +++ b/fixtures/conformance/error-ref-ambiguous-heldby/input/meta.parcels.json @@ -0,0 +1,15 @@ +{ + "metadata.root": { + "package": "acme::parcels", + "children": [ + { + "system.software": { + "name": "Parcels", + "children": [ + { "role.token": { "name": "tidewellFeeds", "@heldBy": "acme::tidewell::Tidewell" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-ref-ambiguous-heldby/input/meta.tidewell.json b/fixtures/conformance/error-ref-ambiguous-heldby/input/meta.tidewell.json new file mode 100644 index 0000000000..bfd9abb08e --- /dev/null +++ b/fixtures/conformance/error-ref-ambiguous-heldby/input/meta.tidewell.json @@ -0,0 +1,9 @@ +{ + "metadata.root": { + "package": "acme::tidewell", + "children": [ + { "organization.company": { "name": "Tidewell" } }, + { "system.software": { "name": "Tidewell" } } + ] + } +} diff --git a/fixtures/conformance/error-ref-wrong-kind-heldby/expected-errors.json b/fixtures/conformance/error-ref-wrong-kind-heldby/expected-errors.json new file mode 100644 index 0000000000..5faf0f2901 --- /dev/null +++ b/fixtures/conformance/error-ref-wrong-kind-heldby/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_REF_WRONG_KIND", + "source": { + "format": "json", + "files": [ + "meta.parcels.json" + ], + "jsonPath": "$['metadata.root'].children[0]['system.software'].children[1]['role.token']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-ref-wrong-kind-heldby/input/meta.parcels.json b/fixtures/conformance/error-ref-wrong-kind-heldby/input/meta.parcels.json new file mode 100644 index 0000000000..b93946826a --- /dev/null +++ b/fixtures/conformance/error-ref-wrong-kind-heldby/input/meta.parcels.json @@ -0,0 +1,16 @@ +{ + "metadata.root": { + "package": "acme::parcels", + "children": [ + { + "system.software": { + "name": "Parcels", + "children": [ + { "resource.rdb": { "name": "db" } }, + { "role.token": { "name": "exporter", "@heldBy": "db" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/ref-target-type-list-heldby/expected.json b/fixtures/conformance/ref-target-type-list-heldby/expected.json new file mode 100644 index 0000000000..a5ff729e7f --- /dev/null +++ b/fixtures/conformance/ref-target-type-list-heldby/expected.json @@ -0,0 +1,38 @@ +{ + "metadata.root": { + "children": [ + { + "system.software": { + "name": "Feeds", + "package": "acme::feeds" + } + }, + { + "system.software": { + "name": "Parcels", + "package": "acme::parcels", + "children": [ + { + "role.token": { + "name": "tidewellFeeds", + "@heldBy": "acme::common::Tidewell" + } + }, + { + "role.token": { + "name": "feedsPull", + "@heldBy": "acme::feeds::Feeds" + } + } + ] + } + }, + { + "organization.company": { + "name": "Tidewell", + "package": "acme::common" + } + } + ] + } +} diff --git a/fixtures/conformance/ref-target-type-list-heldby/input/meta.feeds.json b/fixtures/conformance/ref-target-type-list-heldby/input/meta.feeds.json new file mode 100644 index 0000000000..4ca698adef --- /dev/null +++ b/fixtures/conformance/ref-target-type-list-heldby/input/meta.feeds.json @@ -0,0 +1,8 @@ +{ + "metadata.root": { + "package": "acme::feeds", + "children": [ + { "system.software": { "name": "Feeds" } } + ] + } +} diff --git a/fixtures/conformance/ref-target-type-list-heldby/input/meta.parcels.json b/fixtures/conformance/ref-target-type-list-heldby/input/meta.parcels.json new file mode 100644 index 0000000000..652af24291 --- /dev/null +++ b/fixtures/conformance/ref-target-type-list-heldby/input/meta.parcels.json @@ -0,0 +1,16 @@ +{ + "metadata.root": { + "package": "acme::parcels", + "children": [ + { + "system.software": { + "name": "Parcels", + "children": [ + { "role.token": { "name": "tidewellFeeds", "@heldBy": "acme::common::Tidewell" } }, + { "role.token": { "name": "feedsPull", "@heldBy": "acme::feeds::Feeds" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/ref-target-type-list-heldby/input/meta.parties.json b/fixtures/conformance/ref-target-type-list-heldby/input/meta.parties.json new file mode 100644 index 0000000000..4f8f15f769 --- /dev/null +++ b/fixtures/conformance/ref-target-type-list-heldby/input/meta.parties.json @@ -0,0 +1,8 @@ +{ + "metadata.root": { + "package": "acme::common", + "children": [ + { "organization.company": { "name": "Tidewell" } } + ] + } +} diff --git a/fixtures/metamodel-docs/data/types/role.md.json b/fixtures/metamodel-docs/data/types/role.md.json index cfb86275ad..e122e565ca 100644 --- a/fixtures/metamodel-docs/data/types/role.md.json +++ b/fixtures/metamodel-docs/data/types/role.md.json @@ -137,7 +137,7 @@ "default": "", "allowed": "", "provider": "metaobjects-systems-core", - "description": "Who was handed the token: an organization node, by name (`tidewell::Tidewell`). Optional. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. ADR-0070 call 9 also admits a system here; that waits on the reference facet accepting more than one target type." + "description": "Who was handed the token: an organization or a system node, by name (`tidewell::Tidewell`, `tidewell::Feeds`). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND." }, { "name": "memberOf", diff --git a/fixtures/metamodel-docs/expected/types/role.md b/fixtures/metamodel-docs/expected/types/role.md index 24a6a92f6a..1a9f1f90cc 100644 --- a/fixtures/metamodel-docs/expected/types/role.md +++ b/fixtures/metamodel-docs/expected/types/role.md @@ -78,7 +78,7 @@ Automation outside the system's own apps, given a scoped token: a deploy pipelin | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@credential` | string | no | | | metaobjects-systems-core | The name of an existing key this role adopts (`keys/ANTHROPIC_API_KEY`). Never a value. Written only for a key the model cannot create: a role's credential is otherwise implied, with a derived name. | -| `@heldBy` | string | no | | | metaobjects-systems-core | Who was handed the token: an organization node, by name (`tidewell::Tidewell`). Optional. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. ADR-0070 call 9 also admits a system here; that waits on the reference facet accepting more than one target type. | +| `@heldBy` | string | no | | | metaobjects-systems-core | Who was handed the token: an organization or a system node, by name (`tidewell::Tidewell`, `tidewell::Feeds`). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. | | `@memberOf` | string[] | no | | | metaobjects-systems-core | The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND. | **Allowed children** diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 6ec4e0cd79..9fe5e46633 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -5420,9 +5420,12 @@ "isArray": false, "required": false, "ref": { - "targetType": "organization" + "targetType": [ + "organization", + "system" + ] }, - "description": "Who was handed the token: an organization node, by name (`tidewell::Tidewell`). Optional. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. ADR-0070 call 9 also admits a system here; that waits on the reference facet accepting more than one target type." + "description": "Who was handed the token: an organization or a system node, by name (`tidewell::Tidewell`, `tidewell::Feeds`). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND." }, { "name": "memberOf", diff --git a/server/csharp/MetaObjects/SpecMetamodel/systems.json b/server/csharp/MetaObjects/SpecMetamodel/systems.json index 8ff1f9e598..8515c412d0 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/systems.json +++ b/server/csharp/MetaObjects/SpecMetamodel/systems.json @@ -216,7 +216,7 @@ "description": "Automation outside the system's own apps, given a scoped token: a deploy pipeline, CI, an outside consumer.", "whenToUse": "Access handed to something that is not one of the system's apps.", "children": [ - { "type": "attr", "subType": "string", "name": "heldBy", "min": 0, "max": 1, "description": "Who was handed the token: an organization node, by name (`tidewell::Tidewell`). Optional. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. ADR-0070 call 9 also admits a system here; that waits on the reference facet accepting more than one target type.", "ref": { "targetType": "organization" } } + { "type": "attr", "subType": "string", "name": "heldBy", "min": 0, "max": 1, "description": "Who was handed the token: an organization or a system node, by name (`tidewell::Tidewell`, `tidewell::Feeds`). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": ["organization", "system"] } } ] } ], diff --git a/server/python/src/metaobjects/spec_metamodel/systems.json b/server/python/src/metaobjects/spec_metamodel/systems.json index 8ff1f9e598..8515c412d0 100644 --- a/server/python/src/metaobjects/spec_metamodel/systems.json +++ b/server/python/src/metaobjects/spec_metamodel/systems.json @@ -216,7 +216,7 @@ "description": "Automation outside the system's own apps, given a scoped token: a deploy pipeline, CI, an outside consumer.", "whenToUse": "Access handed to something that is not one of the system's apps.", "children": [ - { "type": "attr", "subType": "string", "name": "heldBy", "min": 0, "max": 1, "description": "Who was handed the token: an organization node, by name (`tidewell::Tidewell`). Optional. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. ADR-0070 call 9 also admits a system here; that waits on the reference facet accepting more than one target type.", "ref": { "targetType": "organization" } } + { "type": "attr", "subType": "string", "name": "heldBy", "min": 0, "max": 1, "description": "Who was handed the token: an organization or a system node, by name (`tidewell::Tidewell`, `tidewell::Feeds`). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": ["organization", "system"] } } ] } ], diff --git a/server/rust/metaobjects/data/metamodel/systems.json b/server/rust/metaobjects/data/metamodel/systems.json index 8ff1f9e598..8515c412d0 100644 --- a/server/rust/metaobjects/data/metamodel/systems.json +++ b/server/rust/metaobjects/data/metamodel/systems.json @@ -216,7 +216,7 @@ "description": "Automation outside the system's own apps, given a scoped token: a deploy pipeline, CI, an outside consumer.", "whenToUse": "Access handed to something that is not one of the system's apps.", "children": [ - { "type": "attr", "subType": "string", "name": "heldBy", "min": 0, "max": 1, "description": "Who was handed the token: an organization node, by name (`tidewell::Tidewell`). Optional. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. ADR-0070 call 9 also admits a system here; that waits on the reference facet accepting more than one target type.", "ref": { "targetType": "organization" } } + { "type": "attr", "subType": "string", "name": "heldBy", "min": 0, "max": 1, "description": "Who was handed the token: an organization or a system node, by name (`tidewell::Tidewell`, `tidewell::Feeds`). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": ["organization", "system"] } } ] } ], diff --git a/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts b/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts index 9e67d038a0..cbd37cda4e 100644 --- a/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts @@ -392,9 +392,12 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = { "name": "heldBy", "min": 0, "max": 1, - "description": "Who was handed the token: an organization node, by name (`tidewell::Tidewell`). Optional. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. ADR-0070 call 9 also admits a system here; that waits on the reference facet accepting more than one target type.", + "description": "Who was handed the token: an organization or a system node, by name (`tidewell::Tidewell`, `tidewell::Feeds`). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { - "targetType": "organization" + "targetType": [ + "organization", + "system" + ] } } ] diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index 0419b292b4..cb50c49c9a 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -353,7 +353,7 @@ export type { ReferenceDescriptor, ReferenceMatch, } from "./validation-types.js"; -export { REF_UNRESOLVED_CODE, REF_WRONG_KIND_CODE } from "./validation-types.js"; +export { REF_UNRESOLVED_CODE, REF_WRONG_KIND_CODE, referenceTargetTypes } from "./validation-types.js"; // DataType classification export { diff --git a/server/typescript/packages/metadata/src/loader/symbol-table.ts b/server/typescript/packages/metadata/src/loader/symbol-table.ts index 05f00f8005..7d2eec45a4 100644 --- a/server/typescript/packages/metadata/src/loader/symbol-table.ts +++ b/server/typescript/packages/metadata/src/loader/symbol-table.ts @@ -14,7 +14,12 @@ import type { MetaData } from "../shared/meta-data.js"; import { ownerCandidateKeys, RefOverDropError, splitChildTail } from "../naming-refs.js"; import { CHILD_REF_SEPARATOR, PACKAGE_SEPARATOR } from "../shared/structural.js"; import { TYPE_OBJECT } from "../shared/base-types.js"; -import type { ReferenceFacet, ReferenceMatch, SymbolTable } from "../validation-types.js"; +import { referenceTargetTypes, type ReferenceFacet, type ReferenceMatch, type SymbolTable } from "../validation-types.js"; + +/** Nodes of two or more of a facet's listed types sharing one name at one step (rule 1). */ +interface Ambiguous { + readonly ambiguous: readonly MetaData[]; +} /** Children of one node grouped by name, in child order (ADR-0039: resolving). */ type ChildIndex = Map; @@ -90,33 +95,39 @@ export class SymbolTableImpl implements SymbolTable { } // A `fieldPath` target is top-level: the referrer's containers are not searched. const from = facet.fieldPath === true ? undefined : referrer; - const path = this.find(from, ref, facet.targetType, referrerPkg); - if (path !== undefined) return { path }; + const found = this.find(from, ref, referenceTargetTypes(facet), referrerPkg); + if (found !== undefined && "ambiguous" in found) return { ambiguous: found.ambiguous }; + if (found !== undefined) return { path: found }; // Rule 6: the untyped lookup, along the same order, only picks the error code. const wrongKind = this.find(from, ref, undefined, referrerPkg); - return wrongKind !== undefined ? { wrongKind: wrongKind[wrongKind.length - 1]! } : {}; + return wrongKind !== undefined && !("ambiguous" in wrongKind) ? { wrongKind: wrongKind[wrongKind.length - 1]! } : {}; } /** The path, top-level owner first, to the node `ref` names whose final segment is - * of `type` (any type when undefined). With no `referrer`, no container is searched. */ + * of one of `types` (any type when undefined), or the nodes of two or more of + * `types` that share the name at the step that finds it (rule 1). With no + * `referrer`, no container is searched. */ private find( referrer: MetaData | undefined, ref: string, - type: string | undefined, + types: readonly string[] | undefined, referrerPkg: string, - ): readonly MetaData[] | undefined { + ): readonly MetaData[] | Ambiguous | undefined { const { owner, tail } = splitChildTail(ref); if (tail === "") { // Rule 4: a bare value is looked for among the children of each container of // the referrer, nearest first, up to and including its top-level node. if (referrer !== undefined && !owner.includes(PACKAGE_SEPARATOR)) { for (let c = referrer.parent; c !== undefined && c !== this.root; c = c.parent) { - const hit = this.childNamed(c, owner, type); - if (hit !== undefined) return [...this.containersTo(c), hit]; + const hit = this.childNamed(c, owner, types); + if (hit !== undefined) return Array.isArray(hit) ? [...this.containersTo(c), hit[0]!] : hit; } } - const top = type !== undefined ? this.resolve(type, owner, referrerPkg) : this.topLevelNamed(owner, referrerPkg)[0]; - return top !== undefined ? [top] : undefined; + if (types === undefined) { + const top = this.topLevelNamed(owner, referrerPkg)[0]; + return top !== undefined ? [top] : undefined; + } + return this.resolveTyped(types, owner, referrerPkg); } // Rule 3: `Owner.child[.grand]` — the owner by its form, then each segment by name. const segments = tail.slice(CHILD_REF_SEPARATOR.length).split(CHILD_REF_SEPARATOR); @@ -132,8 +143,34 @@ export class SymbolTableImpl implements SymbolTable { path.push(named[0]!); } // Rule 1: the final segment is typed. - const last = this.childNamed(path[path.length - 1]!, segments[segments.length - 1]!, type); - return last !== undefined ? [...path, last] : undefined; + const last = this.childNamed(path[path.length - 1]!, segments[segments.length - 1]!, types); + if (last === undefined || !Array.isArray(last)) return last; + return [...path, last[0]!]; + } + + /** A top-level node of one of `types` by ADR-0059 R2 form: the first candidate key + * that holds any, ambiguous when it holds nodes of two of them. */ + private resolveTyped(types: readonly string[], ref: string, referrerPkg: string): readonly MetaData[] | Ambiguous | undefined { + if (types.length === 1) { + const hit = this.resolve(types[0]!, ref, referrerPkg); + return hit !== undefined ? [hit] : undefined; + } + let keys: readonly string[]; + try { + keys = ownerCandidateKeys(ref, referrerPkg); + } catch (e) { + if (e instanceof RefOverDropError) return undefined; + throw e; + } + for (const key of keys) { + const hits = types.flatMap((t) => { + const hit = this.byType.get(t)?.get(key); + return hit !== undefined ? [hit] : []; + }); + if (hits.length === 1) return hits; + if (hits.length > 1) return { ambiguous: hits }; + } + return undefined; } /** The physical containers from the top-level node down to `container`, inclusive. */ @@ -159,11 +196,23 @@ export class SymbolTableImpl implements SymbolTable { return []; } - /** The first child of `parent` named `name`, of `type` when given. */ - private childNamed(parent: MetaData, name: string, type: string | undefined): MetaData | undefined { + /** The first child of `parent` named `name`, of one of `types` when given (as a + * one-element list), or the children of two or more of `types` sharing the name. */ + private childNamed( + parent: MetaData, + name: string, + types: readonly string[] | undefined, + ): readonly [MetaData] | Ambiguous | undefined { const named = this.childIndex(parent).get(name); if (named === undefined) return undefined; - return type === undefined ? named[0] : named.find((c) => c.type === type); + if (types === undefined) return [named[0]!]; + // Names are unique per type within one parent, so each listed type has at most one. + const hits = types.flatMap((t) => { + const hit = named.find((c) => c.type === t); + return hit !== undefined ? [hit] : []; + }); + if (hits.length === 0) return undefined; + return hits.length === 1 ? [hits[0]!] : { ambiguous: hits }; } private childIndex(parent: MetaData): ChildIndex { diff --git a/server/typescript/packages/metadata/src/loader/validation-registry.ts b/server/typescript/packages/metadata/src/loader/validation-registry.ts index 45b229d567..61d66a3173 100644 --- a/server/typescript/packages/metadata/src/loader/validation-registry.ts +++ b/server/typescript/packages/metadata/src/loader/validation-registry.ts @@ -13,6 +13,7 @@ import { TYPE_OBJECT, TYPE_SYSTEM } from "../shared/base-types.js"; import type { TypeDefinition, TypeRegistry } from "../registry.js"; import { REF_UNRESOLVED_CODE, + referenceTargetTypes, REF_WRONG_KIND_CODE, type LoaderCode, type ReferenceDescriptor, @@ -71,12 +72,14 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): // locatable from the message alone, not just the source envelope. const qname = node.parent?.name ? `${node.parent.name}.${node.name}` : node.name; const label = (value: string): string => `${node.type}.${node.subType} "${qname}" @${desc.attr} "${value}"`; + const targetTypes = referenceTargetTypes(desc); + const article = (t: string): string => `${/^[aeiou]/i.test(t) ? "an" : "a"} ${t}`; const wantKind = desc.targetSubTypes === undefined - ? desc.targetType === TYPE_OBJECT - ? "an object" - : `a ${desc.targetType}` - : desc.targetSubTypes.map((s) => `${desc.targetType}.${s}`).join(" or "); + ? targetTypes.map(article).join(" or ") + : targetTypes.length === 1 + ? desc.targetSubTypes.map((s) => `${targetTypes[0]}.${s}`).join(" or ") + : `${targetTypes.map(article).join(" or ")} of subtype ${desc.targetSubTypes.join(" or ")}`; for (const value of values) { if (value === "") continue; // absence is the required-attr pass's job const found = ctx.symbols.lookup(declarer, value, desc, refPkg); @@ -88,11 +91,20 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): ); continue; } + if (found.ambiguous !== undefined) { + const names = found.ambiguous.map((n) => `${n.type}.${n.subType} "${n.name}"`).join(" and "); + ctx.error( + desc.errorCode ?? REF_UNRESOLVED_CODE, + node, + `${label(value)} is ambiguous: it names both ${names}. Rename one of them.`, + ); + continue; + } const path = found.path; if (path === undefined) { // `did-you-mean` is object-scoped (its candidate scan is over objects), so only // append it for object targets; a non-object target names its own kind. - const hint = desc.targetType === TYPE_OBJECT ? didYouMeanHint(root, value) : ""; + const hint = targetTypes.includes(TYPE_OBJECT) ? didYouMeanHint(root, value) : ""; if (found.wrongKind !== undefined) { const w = found.wrongKind; ctx.error( @@ -114,7 +126,7 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): const where = theirs === undefined ? "no system" : `system "${theirs.resolutionKey()}"`; const resolved = `${label(value)} resolves to ${target.type}.${target.subType} "${target.name}" in ${where}`; if (desc.targetSubTypes !== undefined && !desc.targetSubTypes.includes(target.subType)) { - // The typed lookup already guarantees target.type === desc.targetType; only the + // The typed lookup already guarantees target.type is a listed type; only the // subType can still mismatch. ctx.error( desc.errorCode ?? REF_WRONG_KIND_CODE, diff --git a/server/typescript/packages/metadata/src/provider-data.ts b/server/typescript/packages/metadata/src/provider-data.ts index 4d9bbc67f9..c6874c5e68 100644 --- a/server/typescript/packages/metadata/src/provider-data.ts +++ b/server/typescript/packages/metadata/src/provider-data.ts @@ -527,8 +527,17 @@ function toReferenceFacet(provider: string, typeKey: string, child: ChildDef): R for (const key of Object.keys(r)) if (!known.has(key)) fail(`unknown key "${key}"`); if (child.subType !== ATTR_SUBTYPE_STRING) fail(`only a string attr may be a reference (this one is "${String(child.subType)}")`); const { targetType, targetSubTypes, fieldPath, sameSystem, errorCode, wrongSystemCode } = r; - if (typeof targetType !== "string" || targetType === "" || targetType === CHILD_RULE_WILDCARD) { - fail("targetType must name one type, never \"*\""); + const isTypeName = (t: unknown): boolean => typeof t === "string" && t !== "" && t !== CHILD_RULE_WILDCARD; + if ( + !isTypeName(targetType) && + !( + Array.isArray(targetType) && + targetType.length >= 2 && + targetType.every(isTypeName) && + new Set(targetType).size === targetType.length + ) + ) { + fail("targetType must name one type, or list two or more distinct types, never \"*\""); } if (targetSubTypes !== undefined) { if ( @@ -552,7 +561,7 @@ function toReferenceFacet(provider: string, typeKey: string, child: ChildDef): R fail("wrongSystemCode is present exactly when sameSystem is true"); } return { - targetType: targetType as string, + targetType: typeof targetType === "string" ? targetType : [...(targetType as string[])], ...(targetSubTypes !== undefined ? { targetSubTypes: [...(targetSubTypes as string[])] } : {}), ...(fieldPath !== undefined ? { fieldPath: fieldPath as boolean } : {}), ...(sameSystem !== undefined ? { sameSystem: sameSystem as boolean } : {}), diff --git a/server/typescript/packages/metadata/src/registry-manifest.ts b/server/typescript/packages/metadata/src/registry-manifest.ts index 0175bc3f75..3b9aec1158 100644 --- a/server/typescript/packages/metadata/src/registry-manifest.ts +++ b/server/typescript/packages/metadata/src/registry-manifest.ts @@ -70,13 +70,15 @@ export interface ManifestAttr { } /** - * An attr's reference facet in the manifest. Key order is fixed: `targetType`, then + * An attr's reference facet in the manifest. Key order is fixed: `targetType` (a string + * for one type, a sorted list for several), then * `targetSubTypes` (sorted), `fieldPath` and `sameSystem` (each only when true), * `errorCode`, `wrongSystemCode` (each only when present). An absent key is the * facet's default, so two ports that read the same facet write the same bytes. */ export interface ManifestRef { - targetType: string; + /** One type as a string; several as a sorted list. */ + targetType: string | readonly string[]; targetSubTypes?: readonly string[]; fieldPath?: true; sameSystem?: true; @@ -206,7 +208,7 @@ function toManifestAttr(attr: AttrSchema): ManifestAttr { /** The manifest form of a reference facet: defaults omitted, fixed key order. */ function toManifestRef(ref: ReferenceFacet): ManifestRef { return { - targetType: ref.targetType, + targetType: typeof ref.targetType === "string" ? ref.targetType : [...ref.targetType].sort(compareStrings), ...(ref.targetSubTypes !== undefined ? { targetSubTypes: [...ref.targetSubTypes].sort(compareStrings) } : {}), ...(ref.fieldPath === true ? { fieldPath: true as const } : {}), ...(ref.sameSystem === true ? { sameSystem: true as const } : {}), diff --git a/server/typescript/packages/metadata/src/validation-types.ts b/server/typescript/packages/metadata/src/validation-types.ts index 29a01efa1b..7fbfdbf89f 100644 --- a/server/typescript/packages/metadata/src/validation-types.ts +++ b/server/typescript/packages/metadata/src/validation-types.ts @@ -18,9 +18,11 @@ export type LoaderCode = ErrorCode | (string & {}); * and the loader enforces it with no code per provider. */ export interface ReferenceFacet { - /** The type the value must resolve to. Never `*`. */ - readonly targetType: string; - /** The subtypes of `targetType` the value may resolve to. Absent: any. Never empty. */ + /** The type the value must resolve to, or a list of two or more distinct types it may + * resolve to. Never `*`. Read it through `referenceTargetTypes`. */ + readonly targetType: string | readonly string[]; + /** The subtypes the value may resolve to, whichever listed type it resolves to. Absent: + * any. Never empty. */ readonly targetSubTypes?: readonly string[]; /** The value is `Target.field`: only `Target` is resolved, and it is top-level. */ readonly fieldPath?: boolean; @@ -33,6 +35,11 @@ export interface ReferenceFacet { readonly wrongSystemCode?: LoaderCode; } +/** The types a facet's value may resolve to: `targetType` as a list. */ +export function referenceTargetTypes(facet: ReferenceFacet): readonly string[] { + return typeof facet.targetType === "string" ? [facet.targetType] : facet.targetType; +} + /** The code a facet with no `errorCode` raises when its value names no node. */ export const REF_UNRESOLVED_CODE = "ERR_REF_UNRESOLVED"; /** The code a facet with no `errorCode` raises when its value names a node of the wrong kind. */ @@ -60,6 +67,9 @@ export interface ReferenceMatch { * physical parents. */ readonly path?: readonly MetaData[]; readonly wrongKind?: MetaData; + /** Nodes of two or more listed types that share the name at the step that finds the + * target: the value is ambiguous and resolves to none of them (rule 1). */ + readonly ambiguous?: readonly MetaData[]; readonly overDrop?: boolean; } diff --git a/server/typescript/packages/metadata/test/definition-schema.test.ts b/server/typescript/packages/metadata/test/definition-schema.test.ts index 9ab2c64d70..98e6dd65f8 100644 --- a/server/typescript/packages/metadata/test/definition-schema.test.ts +++ b/server/typescript/packages/metadata/test/definition-schema.test.ts @@ -91,7 +91,7 @@ describe("definition schema — the existing definition files", () => { `relationship.composition @objectRef ${relationship}`, `app.base @runsAs ${JSON.stringify({ targetType: "role", targetSubTypes: ["service"] })}`, `role.base @memberOf ${JSON.stringify({ targetType: "role", targetSubTypes: ["group"] })}`, - `role.token @heldBy ${JSON.stringify({ targetType: "organization" })}`, + `role.token @heldBy ${JSON.stringify({ targetType: ["organization", "system"] })}`, `system.base @owner ${JSON.stringify({ targetType: "organization" })}`, ].sort(), ); @@ -133,6 +133,19 @@ describe("definition schema — the reference facet", () => { expect(errorsOf(withAttr({ ref: { targetType: "*" } }))).not.toBe(""); }); + test("targetType may list two or more distinct types", () => { + expect(errorsOf(withAttr({ ref: { targetType: ["organization", "system"] } }))).toBe(""); + expect(errorsOf(withAttr({ ref: { targetType: ["system", "organization", "app"] } }))).toBe(""); + }); + + test("a targetType list may not be short, repeat, or hold the wildcard", () => { + expect(errorsOf(withAttr({ ref: { targetType: [] } }))).not.toBe(""); + expect(errorsOf(withAttr({ ref: { targetType: ["organization"] } }))).not.toBe(""); + expect(errorsOf(withAttr({ ref: { targetType: ["system", "system"] } }))).not.toBe(""); + expect(errorsOf(withAttr({ ref: { targetType: ["system", "*"] } }))).not.toBe(""); + expect(errorsOf(withAttr({ ref: { targetType: ["system", ""] } }))).not.toBe(""); + }); + test("targetSubTypes may not be empty, repeat, or hold the wildcard", () => { expect(errorsOf(withAttr({ ref: { targetType: "resource", targetSubTypes: [] } }))).not.toBe(""); expect(errorsOf(withAttr({ ref: { targetType: "resource", targetSubTypes: ["rdb", "rdb"] } }))).not.toBe(""); diff --git a/server/typescript/packages/metadata/test/reference-facet.test.ts b/server/typescript/packages/metadata/test/reference-facet.test.ts index 90fd8e858d..97be2146e4 100644 --- a/server/typescript/packages/metadata/test/reference-facet.test.ts +++ b/server/typescript/packages/metadata/test/reference-facet.test.ts @@ -63,6 +63,7 @@ const DEFINITION: ProviderDefinition = { attr("runsAs", { ref: { targetType: "role", sameSystem: true, wrongSystemCode: "ERR_RUNSAS_OTHER_SYSTEM" } }), attr("calls", { isArray: true, max: 1, ref: { targetType: "app" } }), attr("reads", { ref: { targetType: "resource", fieldPath: true } }), + attr("uses", { ref: { targetType: ["role", "resource"] } }), ], }, { @@ -97,6 +98,7 @@ const DEFINITION: ProviderDefinition = { attr("anyRole", { ref: { targetType: "role", errorCode: "ERR_TEST_ROLE" } }), attr("pinnedRole", { ref: { targetType: "role", sameSystem: true, wrongSystemCode: "ERR_TEST_OUTSIDE" } }), attr("via", { ref: { targetType: "role" } }), + attr("holder", { ref: { targetType: ["system", "app"], targetSubTypes: ["software", "service"] } }), ], }, ], @@ -207,6 +209,17 @@ describe("reference facet — the spec reader", () => { expect(refuse({ targetType: "role", targetSubType: "rdb" })).toThrow(/unknown key "targetSubType"/); }); + it("lowers a targetType list as written, and refuses a short, repeated or wildcard list", () => { + const defs = defineProviderFromData(DEFINITION, FACTORIES); + const app = defs.find((d) => d.typeId.type === "app")!; + expect(app.attributes.find((a) => a.name === "uses")!.ref).toEqual({ targetType: ["role", "resource"] }); + expect(refuse({ targetType: [] })).toThrow(/targetType/); + expect(refuse({ targetType: ["role"] })).toThrow(/targetType/); + expect(refuse({ targetType: ["role", "role"] })).toThrow(/targetType/); + expect(refuse({ targetType: ["role", "*"] })).toThrow(/targetType/); + expect(refuse({ targetType: ["role", 7] })).toThrow(/targetType/); + }); + it("refuses a facet on a structural child", () => { const child: ChildDef = { ...any("role"), ref: { targetType: "role" } }; expect(() => @@ -348,6 +361,92 @@ async function roundTrip(yaml: string, referrer: string[], attrName: string, tar return at(second.root, ...referrer).attr(attrName); } +describe("reference facet — a list of target types", () => { + const deploy = (holder: string, extraTop = "") => ` +metadata.root: + package: acme + children: + - system.software: + name: Ledger + children: + - app.service: { name: web } + - app.service: { name: Feeds } +${extraTop} + - deployment.test: { name: d1, holder: ${holder} } +`; + + it("a value resolves to a node of any listed type", async () => { + for (const [holder, type] of [["Ledger", "system"], ["Feeds", "app"], ["Ledger.web", "app"]] as const) { + const { root, errors } = await load(deploy(holder)); + expect(errors).toEqual([]); + const d1 = root.children().find((c) => c.name === "d1")!; + expect(refTarget(d1, "holder")?.type).toBe(type); + } + }); + + it("a node of an unlisted type is the wrong kind, and the message lists every type", async () => { + const wrong = await load(` +metadata.root: + package: acme + children: + - resource.rdb: { name: Store } + - deployment.test: { name: d1, holder: Store } +`); + expect(codes(wrong.errors)).toEqual(["ERR_REF_WRONG_KIND"]); + expect(wrong.errors[0]!.message).toContain("not a system or an app of subtype software or service"); + }); + + it("targetSubTypes narrows whichever listed type the value resolves to", async () => { + const yaml = ` +metadata.root: + package: acme + children: + - system.software: + name: Ledger + children: + - role.service: { name: clerk } + - resource.rdb: { name: books } + - resource.queue: { name: jobs } + - app.service: { name: web, uses: clerk } + - app.service: { name: worker, uses: books } + - app.service: { name: pump, uses: jobs } +`; + const { errors } = await load(yaml); + expect(errors).toEqual([]); + }); + + it("two listed types sharing the name at the top level are ambiguous", async () => { + const { errors } = await load(deploy("Shared", " - system.software: { name: Shared }\n - app.service: { name: Shared }")); + expect(codes(errors)).toEqual(["ERR_REF_UNRESOLVED"]); + expect(errors[0]!.message).toMatch(/ambiguous: it names both system\.software "Shared" and app\.service "Shared"/); + }); + + it("two listed types sharing the name in a container are ambiguous; a nearer container still shadows", async () => { + const yaml = (uses: string) => ` +metadata.root: + package: acme + children: + - system.software: + name: Ledger + children: + - role.service: { name: shared } + - resource.rdb: { name: shared } + - app.service: { name: web, uses: ${uses} } + - resource.rdb: { name: top } +`; + expect(codes((await load(yaml("shared"))).errors)).toEqual(["ERR_REF_UNRESOLVED"]); + expect(codes((await load(yaml("top"))).errors)).toEqual([]); + }); + + it("the manifest writes a targetType list sorted", () => { + const manifest = buildRegistryManifest(composeRegistry([...baseProviders, testProvider])); + const deployment = manifest.types.find((t) => t.type === "deployment")!; + expect(JSON.stringify(deployment.attrs.find((a) => a.name === "holder")!.ref)).toBe( + JSON.stringify({ targetType: ["app", "system"], targetSubTypes: ["service", "software"] }), + ); + }); +}); + describe("reference facet — inheritance and canonical spelling", () => { it("an inherited reference is looked up where it was written, not from the inheritor", async () => { // Ledger has no role `api`: `web` inherits `runsAs: api` from Parcels' `base`. diff --git a/server/typescript/packages/metadata/test/validation-registry.test.ts b/server/typescript/packages/metadata/test/validation-registry.test.ts index c7e137b826..8b624077db 100644 --- a/server/typescript/packages/metadata/test/validation-registry.test.ts +++ b/server/typescript/packages/metadata/test/validation-registry.test.ts @@ -170,6 +170,6 @@ metadata.root: ]); expect(errors.map((e) => (e as { code?: string }).code)).toContain("ERR_PROBE_ADAPTER_UNRESOLVED"); // The message names the target's own kind, not a hardcoded "object". - expect(errors.some((e) => /does not resolve to a adapter/.test(e.message))).toBe(true); + expect(errors.some((e) => /does not resolve to an adapter/.test(e.message))).toBe(true); }); }); diff --git a/spec/metamodel-definition.schema.json b/spec/metamodel-definition.schema.json index 25ac06703c..e04afc29fd 100644 --- a/spec/metamodel-definition.schema.json +++ b/spec/metamodel-definition.schema.json @@ -134,6 +134,12 @@ } ] }, + "referenceTargetType": { + "description": "One type a reference may resolve to. Never the `*` wildcard.", + "type": "string", + "minLength": 1, + "not": { "const": "*" } + }, "referenceFacet": { "description": "What a reference attribute may point at (spec/metamodel-definitions.md, 'The reference facet'). Read by every port's spec reader and enforced by its loader.", "type": "object", @@ -141,10 +147,16 @@ "additionalProperties": false, "properties": { "targetType": { - "description": "The type the value must resolve to (`resource`, `object`, `role`). Never the `*` wildcard.", - "type": "string", - "minLength": 1, - "not": { "const": "*" } + "description": "The type the value must resolve to (`resource`, `object`, `role`), or a list of two or more distinct types it may resolve to (`[\"organization\", \"system\"]`). Never the `*` wildcard, and a list never contains it.", + "oneOf": [ + { "$ref": "#/$defs/referenceTargetType" }, + { + "type": "array", + "items": { "$ref": "#/$defs/referenceTargetType" }, + "minItems": 2, + "uniqueItems": true + } + ] }, "targetSubTypes": { "description": "The admitted subtypes of targetType. Absent: any subtype.", diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md index ea2275d099..cde98f8ed6 100644 --- a/spec/metamodel-definitions.md +++ b/spec/metamodel-definitions.md @@ -51,8 +51,8 @@ of data, and every port's loader enforces it without code of its own for each pa | Key | Required | Meaning | |---|---|---| -| `targetType` | yes | The type the value must resolve to. Never `*`. | -| `targetSubTypes` | no | The subtypes of `targetType` the value may resolve to. Absent: any. Never empty, never `*`. | +| `targetType` | yes | The type the value must resolve to: one type, or a list of two or more distinct types when the value may resolve to any of them (`["organization", "system"]`). Never `*`, and a list never contains `*`. | +| `targetSubTypes` | no | The subtypes the value may resolve to, whichever listed type it resolves to. Absent: any. Never empty, never `*`. | | `fieldPath` | no, default `false` | The value is `Target.field`: the reference resolves `Target`, and the last dotted segment names a field of it that this facet does not resolve. Only for a top-level target, and never with `sameSystem`. `identity.reference @references` has this shape. | | `sameSystem` | no, default `false` | The target must be in the same system as the node that declares the attribute (below). | | `errorCode` | no | The code raised when the value does not resolve or resolves to the wrong kind. Absent: `ERR_REF_UNRESOLVED` and `ERR_REF_WRONG_KIND`. | @@ -78,7 +78,7 @@ default codes apply to references that are new with the facet. **The manifest.** The registry manifest (`fixtures/registry-conformance/`) writes `ref` on an attribute only when the attribute has one, after `ports` and before `description`. Its keys come -in the table's order: `targetType`, `targetSubTypes` (sorted), `fieldPath` and `sameSystem` (each +in the table's order: `targetType` (a string for one type, a sorted list for several), `targetSubTypes` (sorted), `fieldPath` and `sameSystem` (each only when `true`), then `errorCode` and `wrongSystemCode` (each only when present). A registry with no facet writes the manifest it writes today, byte for byte, so a port can learn to read the facet before any definition file uses it. @@ -93,10 +93,15 @@ lookup is **typed by the facet**, and a bare name may be found **inside the refe containers**. 1. **Kind-typed final segment.** The last segment of the path matches only nodes of - `targetType`. A role and an app in one system may both be named `api`: `runsAs: api` finds - the role, because `runsAs` targets `role`, and `app: Parcels.api` finds the app. Names are - unique per type within one parent, so the final segment finds at most one node of the - target type under a given parent. + `targetType`, or of any type in it when it is a list. A role and an app in one system may + both be named `api`: `runsAs: api` finds the role, because `runsAs` targets `role`, and + `app: Parcels.api` finds the app. Names are unique per type within one parent, so the final + segment finds at most one node of each target type under a given parent. When the facet lists + several types and nodes of two of them share the name at the step that finds the target + (under one container, or under one top-level key), the value is ambiguous: it does not + resolve, and the loader raises `errorCode`, else `ERR_REF_UNRESOLVED`, naming both nodes. + `heldBy: tidewell::Tidewell`, where the package holds both an organization and a system + named `Tidewell`, is ambiguous; a nearer container's match still shadows a farther one. 2. **Intermediate segments match by name.** Each segment before the last matches a child by name, of any type. If two children of one parent share that name (an app and a role both @@ -153,7 +158,7 @@ references are bound (ADR-0059 §5): | Step | The check | Code when it fails | |---|---|---| -| 1 | The typed lookup (rules 1 to 4) finds a node of `targetType` | When it finds none, the untyped lookup (rule 6) runs. It finds a same-named node: `errorCode`, else `ERR_REF_WRONG_KIND`. It finds none: `errorCode`, else `ERR_REF_UNRESOLVED` | +| 1 | The typed lookup (rules 1 to 4) finds one node of `targetType` (of a listed type, when it is a list) | When it finds two of different listed types under one name (rule 1): `errorCode`, else `ERR_REF_UNRESOLVED`. When it finds none, the untyped lookup (rule 6) runs. It finds a same-named node: `errorCode`, else `ERR_REF_WRONG_KIND`. It finds none: `errorCode`, else `ERR_REF_UNRESOLVED` | | 2 | The node's subtype is in `targetSubTypes`, when the facet lists them | `errorCode`, else `ERR_REF_WRONG_KIND` | | 3 | `sameSystem`: the target is in the declaring node's system | `wrongSystemCode` | @@ -194,10 +199,9 @@ shipped definition file sets `sameSystem` yet. The format and the schema are specified here. The four core references above use `ref`, and so does the systems vocabulary (`spec/metamodel/systems.json`, provider `metaobjects-systems-core`, -ADR-0070): `system.* @owner` and `role.token @heldBy` name an `organization`, `app.* @runsAs` a -`role.service`, and `role.* @memberOf` a `role.group`, all with the default codes. `@heldBy` takes -one target type today, so a token held by a system raises `ERR_REF_WRONG_KIND` until the facet -accepts a list of target types. +ADR-0070): `system.* @owner` names an `organization`, `role.token @heldBy` an `organization` or a +`system`, `app.* @runsAs` a `role.service`, and `role.* @memberOf` a `role.group`, all with the +default codes. `@heldBy` is the first facet with a list of target types (ADR-0070, call 9). Ports whose spec reader reads and enforces `ref`: TypeScript, C#, Java, Kotlin, Python, Rust. Each reads the four core references from the definition files (in Rust, from its vendored copy in @@ -208,4 +212,6 @@ vendored Rust copy, and in the TypeScript, Python, Java (Kotlin shares it) and C catalogs. Rust lists only the codes it raises, so its reader change adds them there. The two worked cases are the conformance fixtures `error-ref-wrong-kind-runsas` and `error-ref-unresolved-runsas`, added with the systems vocabulary, the first new vocabulary to use -the facet. +the facet. The list form is proved by `ref-target-type-list-heldby` (a token held by an +organization and one held by a system load), `error-ref-wrong-kind-heldby` (a token held by a +resource) and `error-ref-ambiguous-heldby` (an organization and a system share the name). diff --git a/spec/metamodel/systems.json b/spec/metamodel/systems.json index 8ff1f9e598..8515c412d0 100644 --- a/spec/metamodel/systems.json +++ b/spec/metamodel/systems.json @@ -216,7 +216,7 @@ "description": "Automation outside the system's own apps, given a scoped token: a deploy pipeline, CI, an outside consumer.", "whenToUse": "Access handed to something that is not one of the system's apps.", "children": [ - { "type": "attr", "subType": "string", "name": "heldBy", "min": 0, "max": 1, "description": "Who was handed the token: an organization node, by name (`tidewell::Tidewell`). Optional. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. ADR-0070 call 9 also admits a system here; that waits on the reference facet accepting more than one target type.", "ref": { "targetType": "organization" } } + { "type": "attr", "subType": "string", "name": "heldBy", "min": 0, "max": 1, "description": "Who was handed the token: an organization or a system node, by name (`tidewell::Tidewell`, `tidewell::Feeds`). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": ["organization", "system"] } } ] } ], From db5ee087e284e2afa6d183f31cbaa0675aa68fc7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 3 Dec 2026 15:55:51 -0500 Subject: [PATCH 2/4] feat(metadata): reference facet targetType list in C#, Java/Kotlin, Python and Rust; docs and counts Every port's spec reader, typed lookup (ambiguity across listed types -> ERR_REF_UNRESOLVED), wrong-kind message and registry manifest (sorted list) match the TypeScript reference. ERROR-CODES descriptions, conformance counts 596 -> 599, Rust minPassing, site payload, the V1 changelog note on @heldBy, and one new changelog fragment. --- AGENTS.md | 2 +- README.md | 2 +- changelog.d/csharp-reference-facet.md | 2 +- .../reference-facet-target-type-list.md | 18 ++ changelog.d/systems-vocabulary-core.md | 4 +- docs/CONFORMANCE.md | 8 +- docs/ports/rust.md | 2 +- examples/showcase/site-payload.json | 2 +- fixtures/conformance/ERROR-CODES.json | 4 +- fixtures/registry-conformance/README.md | 4 +- .../ReferenceFacetTests.cs | 115 +++++++++++- .../Registry/Spec/SpecMetamodelReader.cs | 24 ++- server/csharp/MetaObjects/RegistryManifest.cs | 10 +- .../Validation/RegisteredValidation.cs | 19 +- .../MetaObjects/Validation/SymbolTable.cs | 80 ++++++--- .../MetaObjects/Validation/ValidationTypes.cs | 26 ++- .../validation/RegisteredValidation.java | 26 ++- .../registry/RegistryManifest.java | 10 +- .../registry/spec/SpecMetamodelReader.java | 26 ++- .../validation/ReferenceFacet.java | 11 +- .../validation/ReferenceMatch.java | 8 +- .../metaobjects/validation/SymbolTable.java | 97 +++++++--- .../validation/ReferenceFacetTest.java | 99 ++++++++++- .../loader/registered_validation.py | 32 +++- .../src/metaobjects/loader/symbol_table.py | 83 ++++++--- .../src/metaobjects/registry_manifest.py | 6 +- .../metaobjects/spec_metamodel/__init__.py | 19 +- .../src/metaobjects/validation_types.py | 12 +- .../python/tests/unit/test_reference_facet.py | 117 +++++++++++- server/rust/metaobjects/data/ERROR-CODES.json | 4 +- server/rust/metaobjects/src/manifest.rs | 6 +- server/rust/metaobjects/src/providers.rs | 22 ++- server/rust/metaobjects/src/registry.rs | 9 +- server/rust/metaobjects/src/validate/refs.rs | 167 +++++++++++++----- .../metaobjects/src/validate/refs_tests.rs | 103 ++++++++++- .../tests/conformance-expected-failures.json | 2 +- 36 files changed, 989 insertions(+), 192 deletions(-) create mode 100644 changelog.d/reference-facet-target-type-list.md diff --git a/AGENTS.md b/AGENTS.md index 0842410041..4eb1697b48 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (laid out by `KotlinWriter`, ADR-0063, on the JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (596 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (599 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python / C# / Rust byte-identical; the C# and Rust drift ledgers are empty (`docs/CONFORMANCE.md`). - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (the Node reference helper writes them; a native tool is equally first-class, ADR-0015 Amendment 2). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/README.md b/README.md index fb7239b343..9f1b27b9ff 100644 --- a/README.md +++ b/README.md @@ -172,7 +172,7 @@ first-week wedge plan — and `meta init` picks up from there. | Kotlin | **Maven Central `8.3.1`** — codegen tier on top of Java: 17 generators (entity, Exposed table, names, relations, repository, output-parser, output-prompt, render-helper, extractor, filter-allowlist, validator, Spring config, storedProc, Spring controller, requirement-tests, api-docs, report-export); 24 / 24 persistence-conformance | [`docs/ports/kotlin.md`](docs/ports/kotlin.md) | [`server/java/codegen-kotlin/`](server/java/codegen-kotlin/) · [`server/java/metadata-ktx/`](server/java/metadata-ktx/) | | C# | **NuGet `1.3.1`** — loader + conformance + EF Core codegen + render engine + `dotnet meta` CLI all shipped | [`docs/ports/csharp.md`](docs/ports/csharp.md) | [`server/csharp/`](server/csharp/) | | Python | **PyPI `1.3.1`** — loader + conformance + render + entity-model codegen + ObjectManager runtime shipped; schema migrations in your own tool or the Node `meta migrate` reference helper (ADR-0015) | [`docs/ports/python.md`](docs/ports/python.md) | [`server/python/`](server/python/) | -| Rust | **Crates ready to publish, not yet published** — loader (JSON + YAML), project and source resolution, naming and all 41 validation passes; 596 / 596 metamodel conformance; prompt render and the reply parser (`metaobjects-render`); `cargo meta init` / `gen` / `verify` / `eject` with generators: the model crate through the sqlx store, the service and its opt-in axum routes (`service-routes`) to a typed client and its commands (ADR-0065). Schema migrations stay with the Node `meta` tool | [`docs/ports/rust.md`](docs/ports/rust.md) | [`server/rust/`](server/rust/) | +| Rust | **Crates ready to publish, not yet published** — loader (JSON + YAML), project and source resolution, naming and all 41 validation passes; 599 / 599 metamodel conformance; prompt render and the reply parser (`metaobjects-render`); `cargo meta init` / `gen` / `verify` / `eject` with generators: the model crate through the sqlx store, the service and its opt-in axum routes (`service-routes`) to a typed client and its commands (ADR-0065). Schema migrations stay with the Node `meta` tool | [`docs/ports/rust.md`](docs/ports/rust.md) | [`server/rust/`](server/rust/) | ## Capability matrix diff --git a/changelog.d/csharp-reference-facet.md b/changelog.d/csharp-reference-facet.md index fd0fd0e977..e8322146ce 100644 --- a/changelog.d/csharp-reference-facet.md +++ b/changelog.d/csharp-reference-facet.md @@ -13,6 +13,6 @@ Upgrading: C# `ReferenceDescriptor` is now `(Attr, Facet)`. A provider that sets `TypeDefinition.References` in code builds `new ReferenceDescriptor(attr, new ReferenceFacet(...))`. - `TargetType` and `ErrorCode` move onto `ReferenceFacet` (where `ErrorCode` is optional), + `TargetType` (now the list `TargetTypes`, since a facet may name several types; a constructor taking one type name remains) and `ErrorCode` move onto `ReferenceFacet` (where `ErrorCode` is optional), `TargetSubType` becomes the list `ReferenceFacet.TargetSubTypes`, and `DottedFieldPath` becomes `ReferenceFacet.FieldPath`. diff --git a/changelog.d/reference-facet-target-type-list.md b/changelog.d/reference-facet-target-type-list.md new file mode 100644 index 0000000000..c9466e7a6d --- /dev/null +++ b/changelog.d/reference-facet-target-type-list.md @@ -0,0 +1,18 @@ +- **The reference facet's `targetType` may list several types, in every port, and + `role.token @heldBy` names an organization or a system (ADR-0070, call 9).** A definition file + may now write `"targetType": ["organization", "system"]`: a list of two or more distinct types, + never `*`, where a value resolves to a node of any listed type and `targetSubTypes` still + narrows whichever type it found. One type stays a plain string. When nodes of two listed types + share the name at the step that finds the target (two children of one container, or one + top-level key), the value is ambiguous and raises the facet's `errorCode`, else + `ERR_REF_UNRESOLVED`; a value naming another kind of node keeps `ERR_REF_WRONG_KIND`. The + TypeScript, C#, Java and Kotlin, Python and Rust readers, resolvers and registry manifests all + take the list, and the manifest writes it sorted. `spec/metamodel-definitions.md` and + `spec/metamodel-definition.schema.json` describe it. `role.token @heldBy` moves from + `organization` to `[organization, system]`, so a token held by a system now loads. New + conformance fixtures `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby` and + `error-ref-ambiguous-heldby` pin the three cases. `metamodelVersion` stays `1.4`: 1.4 is not + yet published. + + Upgrading: TypeScript code that reads `ReferenceFacet.targetType` now gets `string | readonly + string[]`; `referenceTargetTypes(facet)` returns it as a list. diff --git a/changelog.d/systems-vocabulary-core.md b/changelog.d/systems-vocabulary-core.md index a1868c27f6..23d3d6eb27 100644 --- a/changelog.d/systems-vocabulary-core.md +++ b/changelog.d/systems-vocabulary-core.md @@ -9,8 +9,8 @@ and Rust, so a model that declares none of these types is unchanged. `@owner`, `@runsAs`, `@memberOf` and `@heldBy` are checked by the reference facet with its default codes: a name that resolves to nothing is `ERR_REF_UNRESOLVED`, and one that names the wrong kind of node is - `ERR_REF_WRONG_KIND`. `@heldBy` names an organization only for now: a token held by a system - raises `ERR_REF_WRONG_KIND` until the facet accepts more than one target type. New conformance + `ERR_REF_WRONG_KIND`. `@heldBy` names an organization or a system (see the reference facet's + target type list). New conformance fixtures `systems-vocabulary`, `error-ref-wrong-kind-runsas` and `error-ref-unresolved-runsas` pin the vocabulary and the facet's two worked cases. `@residency` is a closed set (`free`, `confined`) in every port: any other value is `ERR_BAD_ATTR_VALUE` (fixture diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 08b1db0936..26e32e5744 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | Rust | |---|---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 596 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (596 / 596, empty ledger) | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 599 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (599 / 599, empty ledger) | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | — | @@ -82,7 +82,7 @@ and render ledgers; the api-contract runner's list of sub-corpora not built yet) shrink, and the corpora without one assert each case outright. A new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard failure when ADR-0065 turns the warning off. A regression still fails: the ledger's -`minPassing` (596) is the number of fixtures known to pass, and the run fails when fewer do. +`minPassing` (599) is the number of fixtures known to pass, and the run fails when fewer do. Beside the corpora it runs the codegen-compile gate (below) with every shipped generator, a scale gate over twenty copies of the fitness model, and `examples/rust-service/`'s HTTP test. [The Rust port page](ports/rust.md#conformance) has the detail. @@ -445,7 +445,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (596) +### `fixtures/conformance/` — metamodel loader + canonical serializer (599) | Fixture prefix | Feature doc | |---|---| @@ -961,7 +961,7 @@ shared input. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 596 + yaml 19 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 599 + yaml 19 + verify 45 + render 26 + persistence 68 + api-contract 191 + source-resolution 30 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the `cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 02c82b895a..e5e8d022aa 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -651,7 +651,7 @@ outright. | Corpus | Rust today | |---|---| | `registry-conformance` | byte-identical manifest | -| `conformance` (the metamodel corpus) | **596 of 596**, and the ledger is empty | +| `conformance` (the metamodel corpus) | **599 of 599**, and the ledger is empty | | `yaml-conformance` | all 19, and the ledger is empty | | `source-resolution-conformance` | all 30 cases | | `reference-source-conformance` | all 6 cases: a `reference: true` source loads so references resolve against it, a node declared only in reference files is a reference node no generator emits, and a `template.*` declared only there is refused (`ERR_REFERENCE_SOURCE_TEMPLATE`) | diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index e7ec69bd59..aa7d4f9ff3 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.4" }, "counts": { - "fixtures": 596, + "fixtures": 599, "corpora": 49, "baseTypes": 27 }, diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index d816b26a1f..cdf78765f9 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -64,8 +64,8 @@ "ERR_STORAGE_WITHOUT_OBJECT_REF": "@storage was set on a field that has no @objectRef.", "ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF": "ADR-0013: a field.object declares no @objectRef. A field.object models a typed nested value and REQUIRES @objectRef. The message states the whole ladder rather than only the escape hatch: a known key set is an object.value the field @objectRefs; dynamic keys over a known value type are a field.map (@objectRef for a value object, @valueType for a scalar); only a bag no reader pins a key in is @dbColumnType: jsonb on a field.string. Naming the escape hatch alone is what taught adopters to reach for the bag by default.", "ERR_UNRESOLVED_OBJECT_REF": "ADR-0042: a field.object / field.map @objectRef does not resolve to any object in the loaded tree (a dangling target). The ref resolves package-locally when bare (referrer's package, else root-level) and exactly when FQN — a bare cross-package ref no longer binds elsewhere. The error names same-short-name objects in other packages so the author can qualify it.", - "ERR_REF_UNRESOLVED": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node that resolves to nothing, by the typed lookup or by the untyped lookup the loader runs to choose its error. The default code when the facet names no `errorCode`.", - "ERR_REF_WRONG_KIND": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node of another type than the facet's `targetType`, or a subtype outside its `targetSubTypes`. The default code when the facet names no `errorCode`.", + "ERR_REF_UNRESOLVED": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node that resolves to nothing, by the typed lookup or by the untyped lookup the loader runs to choose its error, or names nodes of two of the facet's listed target types that share the name (ambiguous). The default code when the facet names no `errorCode`.", + "ERR_REF_WRONG_KIND": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node of another type than the facet's `targetType` (or than every type in it, when it is a list), or a subtype outside its `targetSubTypes`. The default code when the facet names no `errorCode`.", "ERR_RESERVED_ATTR": "An @-prefixed reserved structural keyword (e.g. @name, @isArray, @children) was used as an inline attribute.", "ERR_SCOPE_PATTERN_INVALID": "Phase-1 metadata-source-resolution: a scope include/exclude package pattern is malformed (empty pattern or empty :: segment).", "ERR_SOURCE_NO_PRIMARY": "An object declares source nodes but none has role=primary.", diff --git a/fixtures/registry-conformance/README.md b/fixtures/registry-conformance/README.md index 6a2681198c..7e9ae46d46 100644 --- a/fixtures/registry-conformance/README.md +++ b/fixtures/registry-conformance/README.md @@ -279,7 +279,9 @@ still fails everywhere. ### The reference facet (`ref`) An attr whose definition entry carries the reference facet (`spec/metamodel-definitions.md`) -carries `"ref"` in the manifest, after any `ports` and before `description`: `targetType`, then +carries `"ref"` in the manifest, after any `ports` and before `description`: `targetType` (a +string for one type, a sorted list for several, as `role.token @heldBy` writes +`["organization", "system"]`), then `targetSubTypes` (sorted), `fieldPath` and `sameSystem` (only when `true`), `errorCode` and `wrongSystemCode` (only when present). An attr with no facet writes no `ref`. In the core definitions the facet is on core's four older references (`relationship.* @objectRef`, diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs index aab87d5129..1079b71ba5 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs @@ -35,7 +35,9 @@ private sealed class SystemTestNode(TypeId typeId, string name) : MetaData(typeI { "type": "attr", "subType": "string", "name": "calls", "isArray": true, "min": 0, "max": 1, "description": "Test.", "ref": { "targetType": "app" } }, { "type": "attr", "subType": "string", "name": "reads", "min": 0, "max": 1, "description": "Test.", - "ref": { "targetType": "resource", "fieldPath": true } } + "ref": { "targetType": "resource", "fieldPath": true } }, + { "type": "attr", "subType": "string", "name": "uses", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": ["role", "resource"] } } ] }, { "type": "grant", "subType": "rdb", "children": [ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "Test.", @@ -50,7 +52,9 @@ private sealed class SystemTestNode(TypeId typeId, string name) : MetaData(typeI { "type": "attr", "subType": "string", "name": "pinnedRole", "min": 0, "max": 1, "description": "Test.", "ref": { "targetType": "role", "sameSystem": true, "wrongSystemCode": "ERR_TEST_OUTSIDE" } }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Test.", - "ref": { "targetType": "role" } } + "ref": { "targetType": "role" } }, + { "type": "attr", "subType": "string", "name": "holder", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": ["system", "app"], "targetSubTypes": ["software", "service"] } } ] } ] } @@ -195,7 +199,7 @@ public void The_reader_lowers_ref_onto_the_attribute_schema() { var schema = Registry().FindAttrSchema("grant", "rdb", "resource"); Assert.NotNull(schema?.Ref); - Assert.Equal("resource", schema!.Ref!.TargetType); + Assert.Equal(["resource"], schema!.Ref!.TargetTypes); Assert.Equal(["rdb"], schema.Ref.TargetSubTypes!); Assert.True(schema.Ref.SameSystem); Assert.False(schema.Ref.FieldPath); @@ -229,6 +233,26 @@ public void The_reader_refuses_a_facet_the_format_does_not_allow(string referenc Assert.Contains("attr \"to\" on \"widget.x\"", ex.Message); } + [Fact] + public void The_reader_lowers_a_targetType_list_as_written() + { + var uses = Registry().FindAttrSchema("app", "service", "uses"); + Assert.Equal(["role", "resource"], uses!.Ref!.TargetTypes); + } + + [Theory] + [InlineData("""[]""")] + [InlineData("""["role"]""")] + [InlineData("""["role", "role"]""")] + [InlineData("""["role", "*"]""")] + [InlineData("""["role", 7]""")] + public void The_reader_refuses_a_short_repeated_or_wildcard_targetType_list(string list) + { + var ex = Assert.Throws( + () => SpecMetamodelReader.FromJson(WithRef($$"""{ "targetType": {{list}} }"""))); + Assert.Contains("targetType", ex.Message); + } + [Fact] public void The_reader_refuses_a_facet_on_a_structural_child() { @@ -263,7 +287,7 @@ public void The_reader_carries_a_facet_on_a_types_entry_attr() "role.base @memberOf role False ", "role.group @memberOf role False ", "role.service @memberOf role False ", - "role.token @heldBy organization False ", + "role.token @heldBy organization|system False ", "role.token @memberOf role False ", "role.user @memberOf role False ", "system.base @owner organization False ", @@ -295,12 +319,12 @@ public void The_core_definitions_declare_exactly_the_four_core_references() { // The systems vocabulary: no sameSystem, no custom codes. Assert.False(f.SameSystem); - found.Add($"{id.Type}.{id.SubType} @{a.Name} {f.TargetType} {f.FieldPath} {f.ErrorCode}"); + found.Add($"{id.Type}.{id.SubType} @{a.Name} {string.Join("|", f.TargetTypes)} {f.FieldPath} {f.ErrorCode}"); continue; } Assert.Null(f.TargetSubTypes); Assert.False(f.SameSystem); - found.Add($"{id.Type}.{id.SubType} @{a.Name} {f.TargetType} {f.FieldPath} {f.ErrorCode}"); + found.Add($"{id.Type}.{id.SubType} @{a.Name} {string.Join("|", f.TargetTypes)} {f.FieldPath} {f.ErrorCode}"); } } found.Sort(StringComparer.Ordinal); @@ -735,6 +759,76 @@ public void A_parent_relative_references_value_resolves_its_owner() Assert.Equal("acme::Address.id", reference.Attr("references")); } + // ------------------------------------------------------------------ + // A list of target types + // ------------------------------------------------------------------ + + private static string Deploy(string holder, string extraTop = "") => $""" + metadata.root: + package: acme + children: + - system.software: + name: Ledger + children: + - app.service: {"{"} name: web {"}"} + - app.service: {"{"} name: Feeds {"}"} + {extraTop} + - deployment.test: {"{"} name: d1, holder: {holder} {"}"} + """; + + [Theory] + [InlineData("Ledger", "system")] + [InlineData("Feeds", "app")] + [InlineData("Ledger.web", "app")] + public void A_value_resolves_to_a_node_of_any_listed_type(string holder, string type) + { + var r = Load(Deploy(holder)); + Clean(r); + Assert.Equal(type, NamingRefs.RefTarget(At(r.Root, "d1"), "holder")?.Type); + } + + [Fact] + public void A_node_of_an_unlisted_type_is_the_wrong_kind_and_the_message_lists_every_type() + { + var r = Load(""" + metadata.root: + package: acme + children: + - resource.rdb: { name: Store } + - deployment.test: { name: d1, holder: Store } + """); + Assert.Equal(["ERR_REF_WRONG_KIND"], Codes(r)); + Assert.Contains("not a system or an app of subtype software or service", r.Errors[0].Message); + } + + [Fact] + public void Two_listed_types_sharing_the_name_at_the_top_level_are_ambiguous() + { + var r = Load(Deploy("Shared", " - system.software: { name: Shared }\n - app.service: { name: Shared }")); + Assert.Equal(["ERR_REF_UNRESOLVED"], Codes(r)); + Assert.Contains("ambiguous: it names both system.software \"Shared\" and app.service \"Shared\"", r.Errors[0].Message); + Assert.Null(NamingRefs.RefTarget(At(r.Root, "d1"), "holder")); + } + + [Fact] + public void Two_listed_types_sharing_the_name_in_a_container_are_ambiguous_and_a_nearer_container_shadows() + { + static string Yaml(string uses) => $""" + metadata.root: + package: acme + children: + - system.software: + name: Ledger + children: + - role.service: {"{"} name: shared {"}"} + - resource.rdb: {"{"} name: shared {"}"} + - app.service: {"{"} name: web, uses: {uses} {"}"} + - resource.rdb: {"{"} name: top {"}"} + """; + Assert.Equal(["ERR_REF_UNRESOLVED"], Codes(Load(Yaml("shared")))); + Clean(Load(Yaml("top"))); + } + // ------------------------------------------------------------------ // The registry manifest // ------------------------------------------------------------------ @@ -771,4 +865,13 @@ public void An_attribute_with_no_facet_writes_no_ref_key() var manifest = RegistryManifest.Emit(Provider.ComposeRegistry(CoreTypes.LibraryProviders)); Assert.Equal(CoreFacets.Length + SystemsFacets.Length, manifest.Split("\"ref\"").Length - 1); } + + [Fact] + public void The_manifest_writes_a_targetType_list_sorted() + { + using var manifest = JsonDocument.Parse(RegistryManifest.Emit(Registry())); + Assert.Equal( + """{"targetType":["app","system"],"targetSubTypes":["service","software"]}""", + JsonSerializer.Serialize(ManifestAttr(manifest, "deployment", "test", "holder").GetProperty("ref"))); + } } diff --git a/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs b/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs index 7de31bc5e8..670da98f83 100644 --- a/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs +++ b/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs @@ -527,9 +527,25 @@ private static ReferenceFacet ToReferenceFacet(JsonElement r, string? valueType, } if (valueType != StringValueType) Fail($"only a string attr may be a reference (this one is \"{valueType}\")"); - string? targetType = r.TryGetProperty("targetType", out JsonElement tt) && tt.ValueKind == JsonValueKind.String - ? tt.GetString() : null; - if (string.IsNullOrEmpty(targetType) || targetType == Wildcard) Fail("targetType must name one type, never \"*\""); + const string TargetTypeRule = "targetType must name one type, or list two or more distinct types, never \"*\""; + var targetTypes = new List(); + if (!r.TryGetProperty("targetType", out JsonElement tt)) Fail(TargetTypeRule); + bool IsTypeName(JsonElement e) => + e.ValueKind == JsonValueKind.String && !string.IsNullOrEmpty(e.GetString()) && e.GetString() != Wildcard; + if (tt.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement e in tt.EnumerateArray()) + { + if (!IsTypeName(e) || targetTypes.Contains(e.GetString()!)) Fail(TargetTypeRule); + targetTypes.Add(e.GetString()!); + } + if (targetTypes.Count < 2) Fail(TargetTypeRule); + } + else + { + if (!IsTypeName(tt)) Fail(TargetTypeRule); + targetTypes.Add(tt.GetString()!); + } List? targetSubTypes = null; if (r.TryGetProperty("targetSubTypes", out JsonElement ts)) @@ -569,7 +585,7 @@ private static ReferenceFacet ToReferenceFacet(JsonElement r, string? valueType, Fail("wrongSystemCode is present exactly when sameSystem is true"); } return new ReferenceFacet( - targetType!, + targetTypes, targetSubTypes, fieldPath ?? false, sameSystem ?? false, diff --git a/server/csharp/MetaObjects/RegistryManifest.cs b/server/csharp/MetaObjects/RegistryManifest.cs index 71726846e0..55f1f3c167 100644 --- a/server/csharp/MetaObjects/RegistryManifest.cs +++ b/server/csharp/MetaObjects/RegistryManifest.cs @@ -545,7 +545,7 @@ private static void WriteAttr(Utf8JsonWriter writer, ManifestAttr a) } /// - /// Write an attr's reference facet. Key order is fixed: targetType, then + /// Write an attr's reference facet. Key order is fixed: targetType (a string for one type, a sorted list for several), then /// targetSubTypes (sorted), fieldPath and sameSystem (each only when /// true), errorCode, wrongSystemCode (each only when present). An absent key is /// the facet's default, so two ports that read the same facet write the same bytes. @@ -553,7 +553,13 @@ private static void WriteAttr(Utf8JsonWriter writer, ManifestAttr a) private static void WriteRef(Utf8JsonWriter writer, MetaObjects.Validation.ReferenceFacet r) { writer.WriteStartObject("ref"); - writer.WriteString("targetType", r.TargetType); + if (r.TargetTypes.Count == 1) writer.WriteString("targetType", r.TargetTypes[0]); + else + { + writer.WriteStartArray("targetType"); + foreach (string t in r.TargetTypes.OrderBy(x => x, StringComparer.Ordinal)) writer.WriteStringValue(t); + writer.WriteEndArray(); + } if (r.TargetSubTypes is not null) { writer.WriteStartArray("targetSubTypes"); diff --git a/server/csharp/MetaObjects/Validation/RegisteredValidation.cs b/server/csharp/MetaObjects/Validation/RegisteredValidation.cs index 91ce36a92e..9b37a7f315 100644 --- a/server/csharp/MetaObjects/Validation/RegisteredValidation.cs +++ b/server/csharp/MetaObjects/Validation/RegisteredValidation.cs @@ -86,9 +86,13 @@ private static void CheckReference(MetaData root, MetaData node, ReferenceDescri // locatable from the message alone, not just the source envelope. var qname = string.IsNullOrEmpty(node.Parent?.Name) ? node.Name : $"{node.Parent!.Name}.{node.Name}"; string Label(string value) => $"{node.Type}.{node.SubType} \"{qname}\" @{desc.Attr} \"{value}\""; + var targetTypes = facet.TargetTypes; + static string Article(string t) => $"{(t.Length > 0 && "aeiouAEIOU".Contains(t[0]) ? "an" : "a")} {t}"; string wantKind = facet.TargetSubTypes is null - ? (facet.TargetType == TYPE_OBJECT ? "an object" : $"a {facet.TargetType}") - : string.Join(" or ", facet.TargetSubTypes.Select(s => $"{facet.TargetType}.{s}")); + ? string.Join(" or ", targetTypes.Select(Article)) + : targetTypes.Count == 1 + ? string.Join(" or ", facet.TargetSubTypes.Select(s => $"{targetTypes[0]}.{s}")) + : $"{string.Join(" or ", targetTypes.Select(Article))} of subtype {string.Join(" or ", facet.TargetSubTypes)}"; foreach (string value in values) { if (value.Length == 0) continue; // absence is the required-attr pass's job @@ -99,11 +103,18 @@ private static void CheckReference(MetaData root, MetaData node, ReferenceDescri $"{Label(value)} climbs above the root package — each '..::' drops one segment of the declaring package."); continue; } + if (found.Ambiguous is { } both) + { + string names = string.Join(" and ", both.Select(n => $"{n.Type}.{n.SubType} \"{n.Name}\"")); + ctx.Error(facet.ErrorCode ?? ReferenceFacet.UnresolvedCode, node, + $"{Label(value)} is ambiguous: it names both {names}. Rename one of them."); + continue; + } if (found.Path is not { Count: > 0 } path) { // ADR-0042 §5: `did-you-mean` is object-scoped (its candidate scan is over // objects), so only append it for object targets. - string hint = facet.TargetType == TYPE_OBJECT ? NamingRefs.DidYouMeanHint(root, value) : ""; + string hint = targetTypes.Contains(TYPE_OBJECT) ? NamingRefs.DidYouMeanHint(root, value) : ""; if (found.WrongKind is { } w) { ctx.Error(facet.ErrorCode ?? ReferenceFacet.WrongKindCode, node, @@ -121,7 +132,7 @@ private static void CheckReference(MetaData root, MetaData node, ReferenceDescri string resolved = $"{Label(value)} resolves to {target.Type}.{target.SubType} \"{target.Name}\" in {where}"; if (facet.TargetSubTypes is not null && !facet.TargetSubTypes.Contains(target.SubType)) { - // The typed lookup already guarantees target.Type == TargetType; only the subType + // The typed lookup already guarantees target.Type is a listed type; only the subType // can still mismatch. ctx.Error(facet.ErrorCode ?? ReferenceFacet.WrongKindCode, node, $"{resolved}, not {wantKind}."); continue; diff --git a/server/csharp/MetaObjects/Validation/SymbolTable.cs b/server/csharp/MetaObjects/Validation/SymbolTable.cs index b0180b6baa..008aef6907 100644 --- a/server/csharp/MetaObjects/Validation/SymbolTable.cs +++ b/server/csharp/MetaObjects/Validation/SymbolTable.cs @@ -82,17 +82,24 @@ public ReferenceMatch Lookup(MetaData referrer, string value, ReferenceFacet fac catch (RefOverDropException) { return new ReferenceMatch(OverDrop: true); } // A `fieldPath` target is top-level: the referrer's containers are not searched. MetaData? from = facet.FieldPath ? null : referrer; - var path = Find(from, reference, facet.TargetType, referrerPkg); - if (path is not null) return new ReferenceMatch(Path: path); + var found = Find(from, reference, facet.TargetTypes, referrerPkg); + if (found.Ambiguous is not null) return new ReferenceMatch(Ambiguous: found.Ambiguous); + if (found.Path is not null) return new ReferenceMatch(Path: found.Path); // Rule 6: the untyped lookup, along the same order, only picks the error code. - var wrongKind = Find(from, reference, null, referrerPkg); + var wrongKind = Find(from, reference, null, referrerPkg).Path; return wrongKind is not null ? new ReferenceMatch(WrongKind: wrongKind[^1]) : new ReferenceMatch(); } + /// The outcome of one lookup step: the path, or the nodes of two or more listed types that share the name. + private readonly record struct Found(IReadOnlyList? Path = null, IReadOnlyList? Ambiguous = null); + + private static readonly Found NotFound = new(); + /// The path, top-level owner first, to the node names whose - /// final segment is of (any type when null). With no + /// final segment is of one of (any type when null), or the nodes + /// of two or more of them that share the name at the step that finds it (rule 1). With no /// , no container is searched. - private IReadOnlyList? Find(MetaData? referrer, string reference, string? type, string referrerPkg) + private Found Find(MetaData? referrer, string reference, IReadOnlyList? types, string referrerPkg) { var (owner, tail) = NamingRefs.SplitChildTail(reference); if (tail.Length == 0) @@ -103,31 +110,55 @@ public ReferenceMatch Lookup(MetaData referrer, string value, ReferenceFacet fac { for (var c = referrer.Parent; c is not null && !ReferenceEquals(c, _root); c = c.Parent) { - var hit = ChildNamed(c, owner, type); - if (hit is not null) return [.. ContainersTo(c), hit]; + var hit = ChildNamed(c, owner, types); + if (hit is { Count: 1 }) return new Found(Path: [.. ContainersTo(c), hit[0]]); + if (hit is not null) return new Found(Ambiguous: hit); } } - var top = type is not null ? Resolve(type, owner, referrerPkg) : FirstOrNull(TopLevelNamed(owner, referrerPkg)); - return top is not null ? [top] : null; + if (types is null) + { + var top = FirstOrNull(TopLevelNamed(owner, referrerPkg)); + return top is not null ? new Found(Path: [top]) : NotFound; + } + return ResolveTyped(types, owner, referrerPkg); } // Rule 3: `Owner.child[.grand]` — the owner by its form, then each segment by name. string[] segments = tail[CHILD_REF_SEPARATOR.Length..].Split(CHILD_REF_SEPARATOR); - if (segments.Any(p => p.Length == 0)) return null; + if (segments.Any(p => p.Length == 0)) return NotFound; var owners = TopLevelNamed(owner, referrerPkg); - if (owners.Count != 1) return null; + if (owners.Count != 1) return NotFound; var walked = new List { owners[0] }; // Rule 2: an intermediate segment matches a child by name, of any type; two children // sharing the name make the step ambiguous. for (int i = 0; i < segments.Length - 1; i++) { - if (!ChildIndex(walked[^1]).TryGetValue(segments[i], out var named) || named.Count != 1) return null; + if (!ChildIndex(walked[^1]).TryGetValue(segments[i], out var named) || named.Count != 1) return NotFound; walked.Add(named[0]); } // Rule 1: the final segment is typed. - var last = ChildNamed(walked[^1], segments[^1], type); - if (last is null) return null; - walked.Add(last); - return walked; + var last = ChildNamed(walked[^1], segments[^1], types); + if (last is null) return NotFound; + if (last.Count > 1) return new Found(Ambiguous: last); + walked.Add(last[0]); + return new Found(Path: walked); + } + + /// A top-level node of one of by ADR-0059 R2 form: the first + /// candidate key that holds any, ambiguous when it holds nodes of two of them. + private Found ResolveTyped(IReadOnlyList types, string reference, string referrerPkg) + { + IReadOnlyList keys; + try { keys = NamingRefs.OwnerCandidateKeys(reference, referrerPkg); } + catch (RefOverDropException) { return NotFound; } + foreach (string key in keys) + { + var hits = new List(); + foreach (string t in types) + if (_byType.TryGetValue(t, out var bucket) && bucket.TryGetValue(key, out var hit)) hits.Add(hit); + if (hits.Count == 1) return new Found(Path: hits); + if (hits.Count > 1) return new Found(Ambiguous: hits); + } + return NotFound; } private static MetaData? FirstOrNull(IReadOnlyList nodes) => nodes.Count > 0 ? nodes[0] : null; @@ -151,12 +182,21 @@ private IReadOnlyList TopLevelNamed(string owner, string referrerPkg) return []; } - /// The first child of named , of - /// when given. - private MetaData? ChildNamed(MetaData parent, string name, string? type) + /// The first child of named , of one + /// of when given (a one-element list), or the children of two or more + /// of sharing the name. + private IReadOnlyList? ChildNamed(MetaData parent, string name, IReadOnlyList? types) { if (!ChildIndex(parent).TryGetValue(name, out var named)) return null; - return type is null ? named[0] : named.FirstOrDefault(c => c.Type == type); + if (types is null) return [named[0]]; + // Names are unique per type within one parent, so each listed type has at most one. + var hits = new List(); + foreach (string t in types) + { + var hit = named.FirstOrDefault(c => c.Type == t); + if (hit is not null) hits.Add(hit); + } + return hits.Count == 0 ? null : hits; } private Dictionary> ChildIndex(MetaData parent) diff --git a/server/csharp/MetaObjects/Validation/ValidationTypes.cs b/server/csharp/MetaObjects/Validation/ValidationTypes.cs index 85e36a3e3b..35a83e386c 100644 --- a/server/csharp/MetaObjects/Validation/ValidationTypes.cs +++ b/server/csharp/MetaObjects/Validation/ValidationTypes.cs @@ -9,9 +9,10 @@ namespace MetaObjects.Validation; /// , and the loader enforces it with no code per provider. /// Mirrors the TS ReferenceFacet. /// -/// The type the value must resolve to. Never *. -/// The subtypes of the value may -/// resolve to. Null: any. Never empty. +/// The types the value may resolve to: one, or two or more distinct +/// ones (a list is the declared shape, and the manifest writes it sorted). Never *. +/// The subtypes the value may resolve to, whichever listed type it +/// resolves to. Null: any. Never empty. /// The value is Target.field: only the top-level Target is resolved. /// The target must be in the same system as the node that declares the attribute. /// Raised when the value does not resolve or resolves to the wrong kind. @@ -19,13 +20,25 @@ namespace MetaObjects.Validation; /// Raised when fails. Present exactly /// when is true. public sealed record ReferenceFacet( - string TargetType, + IReadOnlyList TargetTypes, IReadOnlyList? TargetSubTypes = null, bool FieldPath = false, bool SameSystem = false, string? ErrorCode = null, string? WrongSystemCode = null) { + /// A facet that names one target type. + public ReferenceFacet( + string targetType, + IReadOnlyList? targetSubTypes = null, + bool fieldPath = false, + bool sameSystem = false, + string? errorCode = null, + string? wrongSystemCode = null) + : this([targetType], targetSubTypes, fieldPath, sameSystem, errorCode, wrongSystemCode) + { + } + /// The code a facet with no raises when its value names no node. public const string UnresolvedCode = "ERR_REF_UNRESOLVED"; @@ -50,10 +63,13 @@ public sealed record ReferenceDescriptor(string Attr, ReferenceFacet Facet); /// The nodes the lookup walked, from the top-level owner to the target (the last /// entry). A child inherited through extends is reached through the node it was looked up /// in, so the path is the address the value used, not the target's physical parents. +/// Nodes of two or more listed types that share the name at the step that +/// finds the target: the value is ambiguous and resolves to none of them. public sealed record ReferenceMatch( IReadOnlyList? Path = null, MetaData? WrongKind = null, - bool OverDrop = false) + bool OverDrop = false, + IReadOnlyList? Ambiguous = null) { /// The node the value names, or null. public MetaData? Target => Path is { Count: > 0 } p ? p[^1] : null; diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java index 4c0fd6dae7..57a05e844e 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java @@ -122,13 +122,18 @@ private static void checkReference(MetaRoot root, MetaData node, ReferenceDescri && !node.getParent().getShortName().isEmpty()) ? node.getParent().getShortName() + "." + node.getShortName() : node.getShortName(); + List targetTypes = facet.targetTypes(); + List articled = new ArrayList<>(); + for (String t : targetTypes) articled.add((isVowel(t) ? "an " : "a ") + t); String wantKind; if (facet.targetSubTypes() == null) { - wantKind = MetaObject.TYPE_OBJECT.equals(facet.targetType()) ? "an object" : "a " + facet.targetType(); - } else { + wantKind = String.join(" or ", articled); + } else if (targetTypes.size() == 1) { List kinds = new ArrayList<>(); - for (String s : facet.targetSubTypes()) kinds.add(facet.targetType() + "." + s); + for (String s : facet.targetSubTypes()) kinds.add(targetTypes.get(0) + "." + s); wantKind = String.join(" or ", kinds); + } else { + wantKind = String.join(" or ", articled) + " of subtype " + String.join(" or ", facet.targetSubTypes()); } for (String value : values) { if (value.isEmpty()) continue; // absence is the required-attr pass's job @@ -140,11 +145,20 @@ private static void checkReference(MetaRoot root, MetaData node, ReferenceDescri + " climbs above the root package — each '..::' drops one segment of the declaring package."); continue; } + if (found.ambiguous() != null) { + List names = new ArrayList<>(); + for (MetaData n : found.ambiguous()) { + names.add(n.getType() + "." + n.getSubType() + " \"" + n.getShortName() + "\""); + } + ctx.error(facet.errorCode() != null ? facet.errorCode() : ReferenceFacet.UNRESOLVED_CODE, node, + label + " is ambiguous: it names both " + String.join(" and ", names) + ". Rename one of them."); + continue; + } List path = found.path(); if (path == null || path.isEmpty()) { // ADR-0042 §5: `did-you-mean` is object-scoped (its candidate scan is over // objects), so only append it for object targets. - String hint = MetaObject.TYPE_OBJECT.equals(facet.targetType()) + String hint = targetTypes.contains(MetaObject.TYPE_OBJECT) ? didYouMeanHint(root, References.splitChildTail(value).owner()) : ""; MetaData w = found.wrongKind(); if (w != null) { @@ -184,6 +198,10 @@ private static void checkReference(MetaRoot root, MetaData node, ReferenceDescri } } + private static boolean isVowel(String t) { + return !t.isEmpty() && "aeiouAEIOU".indexOf(t.charAt(0)) >= 0; + } + /** A reference attribute's value as a list: one string, or each string of a list. */ private static List stringValues(Object value) { if (value instanceof String) return List.of((String) value); diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java b/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java index 3c2ceb210b..109fda141d 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java +++ b/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java @@ -1010,7 +1010,7 @@ private static String childSubTypeJson(Object childSubType) { } /** - * Append an attr's reference facet. Key order is fixed: {@code targetType}, then + * Append an attr's reference facet. Key order is fixed: {@code targetType} (a string for one type, a sorted list for several), then * {@code targetSubTypes} (sorted), {@code fieldPath} and {@code sameSystem} (each only when * true), {@code errorCode}, {@code wrongSystemCode} (each only when present). An absent key is * the facet's default, so two ports that read the same facet write the same bytes. @@ -1018,7 +1018,13 @@ private static String childSubTypeJson(Object childSubType) { private static void appendRef(StringBuilder sb, com.metaobjects.validation.ReferenceFacet r, String baseIndent) { String indent = baseIndent + " "; List lines = new ArrayList<>(); - lines.add(indent + "\"targetType\": " + jsonString(r.targetType())); + if (r.targetTypes().size() == 1) { + lines.add(indent + "\"targetType\": " + jsonString(r.targetTypes().get(0))); + } else { + StringBuilder types = new StringBuilder(indent + "\"targetType\": "); + appendStringArray(types, sortedCopy(r.targetTypes()), indent); + lines.add(types.toString()); + } if (r.targetSubTypes() != null) { StringBuilder subs = new StringBuilder(indent + "\"targetSubTypes\": "); appendStringArray(subs, sortedCopy(r.targetSubTypes()), indent); diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/spec/SpecMetamodelReader.java b/server/java/metadata/src/main/java/com/metaobjects/registry/spec/SpecMetamodelReader.java index 9db4644d34..214ddf5072 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/registry/spec/SpecMetamodelReader.java +++ b/server/java/metadata/src/main/java/com/metaobjects/registry/spec/SpecMetamodelReader.java @@ -433,9 +433,23 @@ private static ReferenceFacet toReferenceFacet(JsonElement el, String valueType, throw invalidFacet(where, "only a string attr may be a reference (this one is \"" + valueType + "\")"); } JsonElement tt = r.get("targetType"); - String targetType = isString(tt) ? tt.getAsString() : null; - if (targetType == null || targetType.isEmpty() || WILDCARD.equals(targetType)) { - throw invalidFacet(where, "targetType must name one type, never \"*\""); + List targetTypes = new ArrayList<>(); + if (isTypeName(tt)) { + targetTypes.add(tt.getAsString()); + } else if (tt != null && tt.isJsonArray()) { + for (JsonElement t : tt.getAsJsonArray()) { + if (!isTypeName(t) || targetTypes.contains(t.getAsString())) { + targetTypes = null; + break; + } + targetTypes.add(t.getAsString()); + } + if (targetTypes != null && targetTypes.size() < 2) targetTypes = null; + } else { + targetTypes = null; + } + if (targetTypes == null) { + throw invalidFacet(where, "targetType must name one type, or list two or more distinct types, never \"*\""); } List targetSubTypes = null; if (r.has("targetSubTypes")) { @@ -461,10 +475,14 @@ private static ReferenceFacet toReferenceFacet(JsonElement el, String valueType, if (Boolean.TRUE.equals(sameSystem) != (wrongSystemCode != null)) { throw invalidFacet(where, "wrongSystemCode is present exactly when sameSystem is true"); } - return new ReferenceFacet(targetType, targetSubTypes, Boolean.TRUE.equals(fieldPath), + return new ReferenceFacet(targetTypes, targetSubTypes, Boolean.TRUE.equals(fieldPath), Boolean.TRUE.equals(sameSystem), errorCode, wrongSystemCode); } + private static boolean isTypeName(JsonElement e) { + return isString(e) && !e.getAsString().isEmpty() && !WILDCARD.equals(e.getAsString()); + } + private static boolean isString(JsonElement e) { return e != null && e.isJsonPrimitive() && e.getAsJsonPrimitive().isString(); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/validation/ReferenceFacet.java b/server/java/metadata/src/main/java/com/metaobjects/validation/ReferenceFacet.java index ee4ee7b040..4934a983a8 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/validation/ReferenceFacet.java +++ b/server/java/metadata/src/main/java/com/metaobjects/validation/ReferenceFacet.java @@ -9,8 +9,10 @@ * loader enforces it with no code per provider. Mirrors the TS {@code ReferenceFacet} and the C# * {@code ReferenceFacet}. * - * @param targetType the type the value must resolve to. Never {@code *}. - * @param targetSubTypes the subtypes of {@code targetType} the value may resolve to; {@code null} + * @param targetTypes the type the value must resolve to (one entry), or the two or more distinct + * types it may resolve to. Never {@code *}. One entry is written to the + * registry manifest as a string, several as a sorted list. + * @param targetSubTypes the subtypes of the listed types the value may resolve to; {@code null} * for any. Never empty. * @param fieldPath the value is {@code Target.field}: only the top-level {@code Target} is * resolved @@ -21,7 +23,7 @@ * @param wrongSystemCode raised when {@code sameSystem} fails; present exactly when * {@code sameSystem} is true */ -public record ReferenceFacet(String targetType, List targetSubTypes, boolean fieldPath, +public record ReferenceFacet(List targetTypes, List targetSubTypes, boolean fieldPath, boolean sameSystem, String errorCode, String wrongSystemCode) { /** The code a facet with no {@code errorCode} raises when its value names no node. */ @@ -31,11 +33,12 @@ public record ReferenceFacet(String targetType, List targetSubTypes, boo public static final String WRONG_KIND_CODE = "ERR_REF_WRONG_KIND"; public ReferenceFacet { + targetTypes = List.copyOf(targetTypes); targetSubTypes = targetSubTypes == null ? null : List.copyOf(targetSubTypes); } /** A facet on {@code targetType} that raises {@code errorCode} — the shape the core object references use. */ public static ReferenceFacet of(String targetType, String errorCode) { - return new ReferenceFacet(targetType, null, false, false, errorCode, null); + return new ReferenceFacet(List.of(targetType), null, false, false, errorCode, null); } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/validation/ReferenceMatch.java b/server/java/metadata/src/main/java/com/metaobjects/validation/ReferenceMatch.java index 53b5db907e..ea7ef1f8b8 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/validation/ReferenceMatch.java +++ b/server/java/metadata/src/main/java/com/metaobjects/validation/ReferenceMatch.java @@ -14,14 +14,18 @@ * inherited through {@code extends} is reached through the node it was looked up * in, so the path is the address the value used, not the target's physical parents. * @param wrongKind a same-named node of another kind the untyped lookup found, or {@code null} + * @param ambiguous nodes of two or more of the facet's listed types that share the name at the step + * that finds the target: the value resolves to none of them; {@code null} otherwise * @param overDrop the value's {@code ..::} climbs above the root package */ -public record ReferenceMatch(List path, MetaData wrongKind, boolean overDrop) { +public record ReferenceMatch(List path, MetaData wrongKind, List ambiguous, + boolean overDrop) { - static final ReferenceMatch NONE = new ReferenceMatch(null, null, false); + static final ReferenceMatch NONE = new ReferenceMatch(null, null, null, false); public ReferenceMatch { path = path == null ? null : List.copyOf(path); + ambiguous = ambiguous == null ? null : List.copyOf(ambiguous); } /** The node the value names, or {@code null}. */ diff --git a/server/java/metadata/src/main/java/com/metaobjects/validation/SymbolTable.java b/server/java/metadata/src/main/java/com/metaobjects/validation/SymbolTable.java index 555e2bb8a7..34f7efb35f 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/validation/SymbolTable.java +++ b/server/java/metadata/src/main/java/com/metaobjects/validation/SymbolTable.java @@ -116,22 +116,33 @@ public ReferenceMatch lookup(MetaData referrer, String value, ReferenceFacet fac try { References.ownerCandidateKeys(References.splitChildTail(reference).owner(), referrerPkg); } catch (References.OverDropException e) { - return new ReferenceMatch(null, null, true); + return new ReferenceMatch(null, null, null, true); } // A `fieldPath` target is top-level: the referrer's containers are not searched. MetaData from = facet.fieldPath() ? null : referrer; - List path = find(from, reference, facet.targetType(), referrerPkg); - if (path != null) return new ReferenceMatch(path, null, false); + Found found = find(from, reference, facet.targetTypes(), referrerPkg); + if (found != null && found.ambiguous != null) return new ReferenceMatch(null, null, found.ambiguous, false); + if (found != null) return new ReferenceMatch(found.path, null, null, false); // Rule 6: the untyped lookup, along the same order, only picks the error code. - List wrongKind = find(from, reference, null, referrerPkg); - return wrongKind != null - ? new ReferenceMatch(null, wrongKind.get(wrongKind.size() - 1), false) + Found wrongKind = find(from, reference, null, referrerPkg); + return wrongKind != null && wrongKind.path != null + ? new ReferenceMatch(null, wrongKind.path.get(wrongKind.path.size() - 1), null, false) : ReferenceMatch.NONE; } + /** What {@link #find} found: a path, or the nodes of two or more listed types sharing the name + * at the step that finds it (rule 1: the value is ambiguous). Exactly one is non-null. */ + private record Found(List path, List ambiguous) { + static Found ofPath(List path) { + return new Found(path, null); + } + } + /** The path, top-level owner first, to the node {@code reference} names whose final segment is - * of {@code type} (any type when null). With no {@code referrer}, no container is searched. */ - private List find(MetaData referrer, String reference, String type, String referrerPkg) { + * of one of {@code types} (any type when null), or the nodes of two or more of {@code types} + * that share the name at the step that finds it. With no {@code referrer}, no container is + * searched. */ + private Found find(MetaData referrer, String reference, List types, String referrerPkg) { References.Split split = References.splitChildTail(reference); String owner = split.owner(); String tail = split.tail(); @@ -140,16 +151,20 @@ private List find(MetaData referrer, String reference, String type, St // referrer, nearest first, up to and including its top-level node. if (referrer != null && !owner.contains(MetaData.PKG_SEPARATOR)) { for (MetaData c = referrer.getParent(); c != null && c != root; c = c.getParent()) { - MetaData hit = childNamed(c, owner, type); - if (hit != null) { + List hits = childNamed(c, owner, types); + if (hits.size() > 1) return new Found(null, hits); + if (hits.size() == 1) { List path = containersTo(c); - path.add(hit); - return path; + path.add(hits.get(0)); + return Found.ofPath(path); } } } - MetaData top = type != null ? resolve(type, owner, referrerPkg) : first(topLevelNamed(owner, referrerPkg)); - return top != null ? new ArrayList<>(List.of(top)) : null; + if (types == null) { + MetaData top = first(topLevelNamed(owner, referrerPkg)); + return top != null ? Found.ofPath(new ArrayList<>(List.of(top))) : null; + } + return resolveTyped(types, owner, referrerPkg); } // Rule 3: `Owner.child[.grand]` — the owner by its form, then each segment by name. String[] segments = tail.substring(1).split("\\.", -1); @@ -168,10 +183,33 @@ private List find(MetaData referrer, String reference, String type, St walked.add(named.get(0)); } // Rule 1: the final segment is typed. - MetaData last = childNamed(walked.get(walked.size() - 1), segments[segments.length - 1], type); - if (last == null) return null; - walked.add(last); - return walked; + List lasts = childNamed(walked.get(walked.size() - 1), segments[segments.length - 1], types); + if (lasts.isEmpty()) return null; + if (lasts.size() > 1) return new Found(null, lasts); + walked.add(lasts.get(0)); + return Found.ofPath(walked); + } + + /** A top-level node of one of {@code types} by ADR-0059 R2 form: the first candidate key that + * holds any, ambiguous when it holds nodes of two of them. */ + private Found resolveTyped(List types, String ref, String referrerPkg) { + List keys; + try { + keys = References.ownerCandidateKeys(ref, referrerPkg); + } catch (References.OverDropException e) { + return null; + } + for (String key : keys) { + List hits = new ArrayList<>(); + for (String t : types) { + Map bucket = byType.get(t); + MetaData hit = bucket == null ? null : bucket.get(key); + if (hit != null) hits.add(hit); + } + if (hits.size() == 1) return Found.ofPath(hits); + if (hits.size() > 1) return new Found(null, hits); + } + return null; } private static MetaData first(List nodes) { @@ -200,15 +238,24 @@ private List topLevelNamed(String owner, String referrerPkg) { return List.of(); } - /** The first child of {@code parent} named {@code name}, of {@code type} when given. */ - private MetaData childNamed(MetaData parent, String name, String type) { + /** The first child of {@code parent} named {@code name}, of one of {@code types} when given (as + * a one-element list), or the children of two or more of {@code types} sharing the name. + * Empty when none. */ + private List childNamed(MetaData parent, String name, List types) { List named = childIndex(parent).get(name); - if (named == null) return null; - if (type == null) return named.get(0); - for (MetaData c : named) { - if (type.equals(c.getType())) return c; + if (named == null) return List.of(); + if (types == null) return List.of(named.get(0)); + // Names are unique per type within one parent, so each listed type has at most one. + List hits = new ArrayList<>(); + for (String t : types) { + for (MetaData c : named) { + if (t.equals(c.getType())) { + hits.add(c); + break; + } + } } - return null; + return hits; } private Map> childIndex(MetaData parent) { diff --git a/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java b/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java index d82bc429d9..4031c2d993 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java @@ -74,7 +74,9 @@ public SystemTestNode(String type, String subType, String name) { { "type": "attr", "subType": "string", "name": "calls", "isArray": true, "min": 0, "max": 1, "description": "Test.", "ref": { "targetType": "app" } }, { "type": "attr", "subType": "string", "name": "reads", "min": 0, "max": 1, "description": "Test.", - "ref": { "targetType": "resource", "fieldPath": true } } + "ref": { "targetType": "resource", "fieldPath": true } }, + { "type": "attr", "subType": "string", "name": "uses", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": ["role", "resource"] } } ] }, { "type": "grant", "subType": "rdb", "children": [ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "Test.", @@ -88,6 +90,8 @@ public SystemTestNode(String type, String subType, String name) { "ref": { "targetType": "role", "errorCode": "ERR_TEST_ROLE" } }, { "type": "attr", "subType": "string", "name": "pinnedRole", "min": 0, "max": 1, "description": "Test.", "ref": { "targetType": "role", "sameSystem": true, "wrongSystemCode": "ERR_TEST_OUTSIDE" } }, + { "type": "attr", "subType": "string", "name": "holder", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": ["resource", "app"], "targetSubTypes": ["web", "pg"] } }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Test.", "ref": { "targetType": "role" } } ] } @@ -234,7 +238,7 @@ public void theReaderLowersRefOntoTheAttributeRequirement() { ChildRequirement req = registry().getTypeDefinition("grant", "rdb").getChildRequirement("resource"); ReferenceFacet ref = req.getRef(); assertNotNull(ref); - assertEquals("resource", ref.targetType()); + assertEquals(List.of("resource"), ref.targetTypes()); assertEquals(List.of("pg"), ref.targetSubTypes()); assertTrue(ref.sameSystem()); assertFalse(ref.fieldPath()); @@ -266,6 +270,11 @@ public void theReaderRefusesAFacetTheFormatDoesNotAllow() { {"{ \"targetType\": \"role\", \"targetSubType\": \"rdb\" }", "string", "unknown key \"targetSubType\""}, {"{ \"targetType\": \"role\", \"fieldPath\": \"yes\" }", "string", "fieldPath must be a boolean"}, {"[ \"role\" ]", "string", "ref must be an object"}, + {"{ \"targetType\": [] }", "string", "targetType"}, + {"{ \"targetType\": [\"role\"] }", "string", "targetType"}, + {"{ \"targetType\": [\"role\", \"role\"] }", "string", "targetType"}, + {"{ \"targetType\": [\"role\", \"*\"] }", "string", "targetType"}, + {"{ \"targetType\": [\"role\", 7] }", "string", "targetType"}, }; for (String[] c : cases) { IllegalStateException ex = assertThrows(c[0], IllegalStateException.class, @@ -295,6 +304,13 @@ public void theReaderCarriesAFacetOnATypesEntryAttr() { assertEquals(List.of("b", "a"), facet.targetSubTypes()); } + @Test + public void theReaderCarriesATargetTypeListAsWritten() { + ReferenceFacet facet = SpecMetamodelReader.fromJson(withRef("{ \"targetType\": [\"role\", \"resource\"] }", "string")) + .attrDoc("widget", "x", "to").ref(); + assertEquals(List.of("role", "resource"), facet.targetTypes()); + } + /** The seven attributes that carry a facet in the core definitions. Only core's four * older references carry one (spec/metamodel-definitions.md, "Existing references keep * their codes"), each naming its existing code. */ @@ -334,7 +350,7 @@ public void theCoreDefinitionsDeclareExactlyTheFourCoreReferences() { } assertNull(f.targetSubTypes()); assertFalse(f.sameSystem()); - found.add(id.type() + "." + id.subType() + " @" + req.getName() + " " + f.targetType() + found.add(id.type() + "." + id.subType() + " @" + req.getName() + " " + String.join("|", f.targetTypes()) + " " + f.fieldPath() + " " + f.errorCode()); } } @@ -371,6 +387,73 @@ public void aRoleAndAnAppBothNamedApiTheLookupIsKindTyped() { } } + private static String deployHolder(String holder, String extraTop) { + return """ + metadata.root: + package: acme + children: + - system.test: + name: Ledger + children: + - app.web: { name: web } + - resource.pg: { name: Feeds } + """ + extraTop + """ + - deployment.test: { name: d1, holder: %s } + """.formatted(holder); + } + + @Test + public void aTargetTypeListResolvesToANodeOfAnyListedType() { + for (String[] c : new String[][] {{"Feeds", "resource"}, {"Ledger.web", "app"}}) { + Result r = load(deployHolder(c[0], "")); + clean(r); + assertEquals(c[1], boundTo(at(r.root(), "d1"), "holder").getType()); + } + } + + @Test + public void aNodeOfAnUnlistedTypeIsWrongKindAndTheMessageListsEveryType() { + Result r = load(deployHolder("Ledger", "")); + assertEquals(List.of("ERR_REF_WRONG_KIND"), codes(r)); + assertTrue(message(r, 0), message(r, 0).contains("not a resource or an app of subtype web or pg")); + } + + @Test + public void targetSubTypesNarrowsWhicheverListedTypeWasFound() { + Result r = load(deployHolder("Feeds", " - resource.mq: { name: Jobs }\n")); + clean(r); + assertEquals(List.of("ERR_REF_WRONG_KIND"), codes(load(deployHolder("Jobs", " - resource.mq: { name: Jobs }\n")))); + } + + @Test + public void twoListedTypesSharingTheNameAtTheTopLevelAreAmbiguous() { + Result r = load(deployHolder("Shared", " - resource.pg: { name: Shared }\n - app.web: { name: Shared }\n")); + assertEquals(List.of("ERR_REF_UNRESOLVED"), codes(r)); + assertTrue(message(r, 0), message(r, 0) + .contains("is ambiguous: it names both resource.pg \"Shared\" and app.web \"Shared\"")); + assertNull(r.root().getChildren(MetaData.class, false).stream() + .filter(c -> "d1".equals(c.getShortName())).findFirst().orElseThrow() + .getMetaAttr("holder").getResolvedTarget()); + } + + @Test + public void twoListedTypesSharingTheNameInAContainerAreAmbiguousButANearerContainerShadows() { + String yaml = """ + metadata.root: + package: acme + children: + - system.test: + name: Ledger + children: + - role.agent: { name: shared } + - resource.pg: { name: shared } + - app.web: { name: web, uses: %s } + - resource.pg: { name: top } + """; + assertEquals(List.of("ERR_REF_UNRESOLVED"), codes(load(yaml.formatted("shared")))); + clean(load(yaml.formatted("top"))); + } + @Test public void unresolvedAValueNamingNoNode() { Result r = load(model(" - app.web: { name: worker, calls: [nobody] }")); @@ -908,6 +991,16 @@ public void theManifestWritesRefOnlyOnAnAttributeThatHasOneInTheFixedKeyOrder() gson.toJson(manifestAttr(manifest, "app", "web", "reads").get("ref"))); } + @Test + public void theManifestWritesATargetTypeListSortedAndOneTypeAsAString() { + JsonObject manifest = JsonParser.parseString(RegistryManifest.emit(registry())).getAsJsonObject(); + Gson gson = new Gson(); + assertEquals("{\"targetType\":[\"app\",\"resource\"],\"targetSubTypes\":[\"pg\",\"web\"]}", + gson.toJson(manifestAttr(manifest, "deployment", "test", "holder").get("ref"))); + assertEquals("{\"targetType\":[\"resource\",\"role\"]}", + gson.toJson(manifestAttr(manifest, "app", "web", "uses").get("ref"))); + } + @Test public void anAttributeWithNoFacetWritesNoRefKey() { // One "ref" per facet in the core and systems definitions, and none anywhere else. diff --git a/server/python/src/metaobjects/loader/registered_validation.py b/server/python/src/metaobjects/loader/registered_validation.py index 086efd9f74..a1f398bbcb 100644 --- a/server/python/src/metaobjects/loader/registered_validation.py +++ b/server/python/src/metaobjects/loader/registered_validation.py @@ -15,7 +15,12 @@ from ..naming_refs import _declaring_node_for, did_you_mean_hint, referrer_package_of from ..registry import TypeDefinition, TypeRegistry from ..shared.base_types import TYPE_OBJECT, TYPE_SYSTEM -from ..validation_types import REF_UNRESOLVED_CODE, REF_WRONG_KIND_CODE, ReferenceDescriptor +from ..validation_types import ( + REF_UNRESOLVED_CODE, + REF_WRONG_KIND_CODE, + ReferenceDescriptor, + reference_target_types, +) from .symbol_table import SymbolTable @@ -96,10 +101,20 @@ def _check_reference(node: MetaData, desc: ReferenceDescriptor, ctx: ValidationC def label(value: str) -> str: return f'{node.type}.{node.sub_type} "{qname}" @{desc.attr} "{value}"' + target_types = reference_target_types(facet) + + def article(t: str) -> str: + return f"{'an' if t[:1].lower() in 'aeiou' else 'a'} {t}" + if facet.target_sub_types is None: - want_kind = "an object" if facet.target_type == TYPE_OBJECT else f"a {facet.target_type}" + want_kind = " or ".join(article(t) for t in target_types) + elif len(target_types) == 1: + want_kind = " or ".join(f"{target_types[0]}.{s}" for s in facet.target_sub_types) else: - want_kind = " or ".join(f"{facet.target_type}.{s}" for s in facet.target_sub_types) + want_kind = ( + f"{' or '.join(article(t) for t in target_types)} of subtype " + f"{' or '.join(facet.target_sub_types)}" + ) for value in values: if value == "": continue # absence is the required-attr pass's job @@ -111,11 +126,18 @@ def label(value: str) -> str: "segment of the declaring package.", ) continue + if found.ambiguous is not None: + names = " and ".join(f'{n.type}.{n.sub_type} "{n.name}"' for n in found.ambiguous) + ctx.error( + facet.error_code or REF_UNRESOLVED_CODE, node, + f"{label(value)} is ambiguous: it names both {names}. Rename one of them.", + ) + continue path = found.path if not path: # ADR-0042 section 5: `did-you-mean` is object-scoped (its candidate scan is over # objects), so only append it for object targets. - hint = did_you_mean_hint(ctx.root, value) if facet.target_type == TYPE_OBJECT else "" + hint = did_you_mean_hint(ctx.root, value) if TYPE_OBJECT in target_types else "" w = found.wrong_kind if w is not None: ctx.error( @@ -135,7 +157,7 @@ def label(value: str) -> str: where = "no system" if theirs is None else f'system "{theirs.resolution_key()}"' resolved = f'{label(value)} resolves to {target.type}.{target.sub_type} "{target.name}" in {where}' if facet.target_sub_types is not None and target.sub_type not in facet.target_sub_types: - # The typed lookup already guarantees target.type == target_type; only the + # The typed lookup already guarantees target.type is a listed type; only the # subtype can still mismatch. ctx.error(facet.error_code or REF_WRONG_KIND_CODE, node, f"{resolved}, not {want_kind}.") continue diff --git a/server/python/src/metaobjects/loader/symbol_table.py b/server/python/src/metaobjects/loader/symbol_table.py index ac9061e6b4..c96e40884f 100644 --- a/server/python/src/metaobjects/loader/symbol_table.py +++ b/server/python/src/metaobjects/loader/symbol_table.py @@ -21,7 +21,14 @@ from ..naming_refs import CHILD_REF_SEP, RefOverDropError, owner_candidate_keys, split_child_tail from ..shared.base_types import TYPE_OBJECT from ..shared.separators import PACKAGE_SEP -from ..validation_types import ReferenceFacet, ReferenceMatch +from ..validation_types import ReferenceFacet, ReferenceMatch, reference_target_types + + +class _Ambiguous: + """Nodes of two or more of a facet's listed types sharing one name at one step.""" + + def __init__(self, nodes: list[MetaData]) -> None: + self.nodes = tuple(nodes) class SymbolTable: @@ -87,23 +94,28 @@ def lookup( return ReferenceMatch(over_drop=True) # A `fieldPath` target is top-level: the referrer's containers are not searched. from_ = None if facet.field_path else referrer - path = self._find(from_, reference, facet.target_type, referrer_pkg) - if path is not None: - return ReferenceMatch(path=path) + found = self._find(from_, reference, reference_target_types(facet), referrer_pkg) + if isinstance(found, _Ambiguous): + return ReferenceMatch(ambiguous=found.nodes) + if found is not None: + return ReferenceMatch(path=found) # Rule 6: the untyped lookup, along the same order, only picks the error code. wrong_kind = self._find(from_, reference, None, referrer_pkg) - return ReferenceMatch(wrong_kind=wrong_kind[-1]) if wrong_kind is not None else ReferenceMatch() + if wrong_kind is None or isinstance(wrong_kind, _Ambiguous): + return ReferenceMatch() + return ReferenceMatch(wrong_kind=wrong_kind[-1]) def _find( self, referrer: Optional[MetaData], reference: str, - type_: Optional[str], + types: Optional[tuple[str, ...]], referrer_pkg: str, - ) -> Optional[tuple[MetaData, ...]]: + ) -> "Optional[tuple[MetaData, ...] | _Ambiguous]": """The path, top-level owner first, to the node *reference* names whose final - segment is of *type_* (any type when None). With no *referrer*, no container is - searched.""" + segment is of one of *types* (any type when None), or the nodes of two or more of + *types* sharing the name at the step that finds it. With no *referrer*, no + container is searched.""" owner, tail = split_child_tail(reference) if tail == "": # Rule 4: a bare value is looked for among the children of each container of the @@ -111,16 +123,16 @@ def _find( if referrer is not None and PACKAGE_SEP not in owner: c = referrer.parent while c is not None and c is not self._root: - hit = self._child_named(c, owner, type_) + hit = self._child_named(c, owner, types) + if isinstance(hit, _Ambiguous): + return hit if hit is not None: return (*self._containers_to(c), hit) c = c.parent - if type_ is not None: - top = self.resolve(type_, owner, referrer_pkg) - else: + if types is None: named = self._top_level_named(owner, referrer_pkg) - top = named[0] if named else None - return (top,) if top is not None else None + return (named[0],) if named else None + return self._resolve_typed(types, owner, referrer_pkg) # Rule 3: `Owner.child[.grand]` -- the owner by its form, then each segment by name. segments = tail[len(CHILD_REF_SEP):].split(CHILD_REF_SEP) if any(p == "" for p in segments): @@ -137,12 +149,32 @@ def _find( return None walked.append(named[0]) # Rule 1: the final segment is typed. - last = self._child_named(walked[-1], segments[-1], type_) - if last is None: - return None + last = self._child_named(walked[-1], segments[-1], types) + if last is None or isinstance(last, _Ambiguous): + return last walked.append(last) return tuple(walked) + def _resolve_typed( + self, types: tuple[str, ...], reference: str, referrer_pkg: str + ) -> "Optional[tuple[MetaData, ...] | _Ambiguous]": + """A top-level node of one of *types* by ADR-0059 R2 form: the first candidate key + that holds any, ambiguous when it holds nodes of two of them.""" + if len(types) == 1: + hit = self.resolve(types[0], reference, referrer_pkg) + return (hit,) if hit is not None else None + try: + keys = owner_candidate_keys(reference, referrer_pkg) + except RefOverDropError: + return None + for key in keys: + hits = [h for t in types if (h := self._by_type.get(t, {}).get(key)) is not None] + if len(hits) == 1: + return (hits[0],) + if len(hits) > 1: + return _Ambiguous(hits) + return None + def _containers_to(self, container: MetaData) -> list[MetaData]: """The physical containers from the top-level node down to *container*, inclusive.""" out: list[MetaData] = [] @@ -164,14 +196,21 @@ def _top_level_named(self, owner: str, referrer_pkg: str) -> list[MetaData]: return hits return [] - def _child_named(self, parent: MetaData, name: str, type_: Optional[str]) -> Optional[MetaData]: - """The first child of *parent* named *name*, of *type_* when given.""" + def _child_named( + self, parent: MetaData, name: str, types: Optional[tuple[str, ...]] + ) -> "Optional[MetaData | _Ambiguous]": + """The first child of *parent* named *name*, of one of *types* when given, or the + children of two or more of *types* sharing the name.""" named = self._child_index(parent).get(name) if not named: return None - if type_ is None: + if types is None: return named[0] - return next((c for c in named if c.type == type_), None) + # Names are unique per type within one parent, so each listed type has at most one. + hits = [h for t in types if (h := next((c for c in named if c.type == t), None)) is not None] + if not hits: + return None + return hits[0] if len(hits) == 1 else _Ambiguous(hits) def _child_index(self, parent: MetaData) -> dict[str, list[MetaData]]: index = self._child_indexes.get(id(parent)) diff --git a/server/python/src/metaobjects/registry_manifest.py b/server/python/src/metaobjects/registry_manifest.py index 05012d038b..c61f55e49c 100644 --- a/server/python/src/metaobjects/registry_manifest.py +++ b/server/python/src/metaobjects/registry_manifest.py @@ -162,11 +162,13 @@ def _to_manifest_attr(attr: AttrSchema) -> dict[str, object]: def _to_manifest_ref(ref: ReferenceFacet) -> dict[str, object]: - """The manifest form of a reference facet. Key order is fixed: ``targetType``, then + """The manifest form of a reference facet. Key order is fixed: ``targetType`` (a string for one type, a sorted list for several), then ``targetSubTypes`` (sorted), ``fieldPath`` and ``sameSystem`` (each only when true), ``errorCode``, ``wrongSystemCode`` (each only when present). An absent key is the facet's default, so two ports that read the same facet write the same bytes.""" - out: dict[str, object] = {"targetType": ref.target_type} + out: dict[str, object] = { + "targetType": ref.target_type if isinstance(ref.target_type, str) else sorted(ref.target_type) + } if ref.target_sub_types is not None: out["targetSubTypes"] = sorted(ref.target_sub_types) if ref.field_path: diff --git a/server/python/src/metaobjects/spec_metamodel/__init__.py b/server/python/src/metaobjects/spec_metamodel/__init__.py index 64b89260b3..02231eb147 100644 --- a/server/python/src/metaobjects/spec_metamodel/__init__.py +++ b/server/python/src/metaobjects/spec_metamodel/__init__.py @@ -131,8 +131,21 @@ def fail(why: str) -> NoReturn: fail(f'only a string attr may be a reference (this one is "{value_type}")') target_type = r.get("targetType") - if not isinstance(target_type, str) or target_type == "" or target_type == _WILDCARD: - fail('targetType must name one type, never "*"') + def is_type_name(t: object) -> bool: + return isinstance(t, str) and t != "" and t != _WILDCARD + + target_types: str | tuple[str, ...] + if is_type_name(target_type): + target_types = str(target_type) + elif ( + isinstance(target_type, list) + and len(target_type) >= 2 + and all(is_type_name(t) for t in target_type) + and len(set(target_type)) == len(target_type) + ): + target_types = tuple(target_type) + else: + fail('targetType must name one type, or list two or more distinct types, never "*"') target_sub_types: tuple[str, ...] | None = None if "targetSubTypes" in r: @@ -172,7 +185,7 @@ def opt_code(key: str) -> str | None: if (same_system is True) != (wrong_system_code is not None): fail("wrongSystemCode is present exactly when sameSystem is true") return ReferenceFacet( - target_type=str(target_type), + target_type=target_types, target_sub_types=target_sub_types, field_path=field_path is True, same_system=same_system is True, diff --git a/server/python/src/metaobjects/validation_types.py b/server/python/src/metaobjects/validation_types.py index 0523f44377..0c97e6e700 100644 --- a/server/python/src/metaobjects/validation_types.py +++ b/server/python/src/metaobjects/validation_types.py @@ -30,12 +30,15 @@ class ReferenceFacet: ``type: "attr"`` child; the spec reader lowers it onto the attribute's ``AttrSchema``, and the loader enforces it with no code per provider. Mirrors the TS ``ReferenceFacet``. + ``target_type`` is one type name, or a tuple of two or more distinct type names (the value + may name a node of any of them; two of them sharing the name is ambiguous). + ``target_sub_types`` is ``None`` for any subtype (never empty). ``error_code`` is raised when the value does not resolve or resolves to the wrong kind (``None``: the two default codes). ``wrong_system_code`` is raised when ``same_system`` fails, and is present exactly when ``same_system`` is true.""" - target_type: str + target_type: "str | tuple[str, ...]" target_sub_types: tuple[str, ...] | None = None field_path: bool = False same_system: bool = False @@ -43,6 +46,12 @@ class ReferenceFacet: wrong_system_code: str | None = None +def reference_target_types(facet: ReferenceFacet) -> tuple[str, ...]: + """The facet's target types as a tuple: one entry for a single type.""" + t = facet.target_type + return (t,) if isinstance(t, str) else tuple(t) + + @dataclass(frozen=True) class ReferenceDescriptor: """Declares that one attr on a node is a cross-reference to another node: the attribute @@ -67,6 +76,7 @@ class ReferenceMatch: path: tuple["MetaData", ...] | None = None wrong_kind: "MetaData | None" = None + ambiguous: tuple["MetaData", ...] | None = None over_drop: bool = False @property diff --git a/server/python/tests/unit/test_reference_facet.py b/server/python/tests/unit/test_reference_facet.py index 810bd70916..d70fad697c 100644 --- a/server/python/tests/unit/test_reference_facet.py +++ b/server/python/tests/unit/test_reference_facet.py @@ -48,7 +48,9 @@ { "type": "attr", "subType": "string", "name": "calls", "isArray": true, "min": 0, "max": 1, "description": "Test.", "ref": { "targetType": "app" } }, { "type": "attr", "subType": "string", "name": "reads", "min": 0, "max": 1, "description": "Test.", - "ref": { "targetType": "resource", "fieldPath": true } } + "ref": { "targetType": "resource", "fieldPath": true } }, + { "type": "attr", "subType": "string", "name": "uses", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": ["role", "resource"] } } ] }, { "type": "grant", "subType": "rdb", "children": [ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "Test.", @@ -63,7 +65,9 @@ { "type": "attr", "subType": "string", "name": "pinnedRole", "min": 0, "max": 1, "description": "Test.", "ref": { "targetType": "role", "sameSystem": true, "wrongSystemCode": "ERR_TEST_OUTSIDE" } }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Test.", - "ref": { "targetType": "role" } } + "ref": { "targetType": "role" } }, + { "type": "attr", "subType": "string", "name": "holder", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": ["system", "app"], "targetSubTypes": ["software", "service"] } } ] } ] } @@ -212,6 +216,11 @@ def _with_ref(reference: str, sub_type: str = "string") -> str: [ ('{ "targetType": "role" }', "int", "only a string attr"), ('{ "targetType": "*" }', "string", "targetType"), + ('{ "targetType": [] }', "string", "targetType"), + ('{ "targetType": ["role"] }', "string", "targetType"), + ('{ "targetType": ["role", "role"] }', "string", "targetType"), + ('{ "targetType": ["role", "*"] }', "string", "targetType"), + ('{ "targetType": ["role", 7] }', "string", "targetType"), ('{ "targetType": "role", "targetSubTypes": [] }', "string", "targetSubTypes"), ('{ "targetType": "role", "targetSubTypes": ["*"] }', "string", "targetSubTypes"), ('{ "targetType": "role", "targetSubTypes": ["a", "a"] }', "string", "targetSubTypes"), @@ -235,6 +244,12 @@ def test_the_reader_refuses_a_facet_the_format_does_not_allow(reference: str, su assert 'attr "to" on "widget.x"' in str(exc.value) +def test_the_reader_lowers_a_target_type_list_as_written() -> None: + schema = _registry().attr_schema("app", "service", "uses") + assert schema is not None and schema.ref is not None + assert schema.ref.target_type == ("role", "resource") + + def test_the_reader_refuses_a_facet_on_a_structural_child() -> None: text = """ { "provider": "bad", "types": [ { "type": "widget", "subType": "x", "description": "x", "children": [ @@ -718,7 +733,103 @@ def test_the_shipped_systems_definition_declares_the_four_systems_references() - ) assert found == [ ("app", "runsAs", "role"), - ("role", "heldBy", "organization"), + ("role", "heldBy", ("organization", "system")), ("role", "memberOf", "role"), ("system", "owner", "organization"), ] + + +# --------------------------------------------------------------------------- +# A list of target types +# --------------------------------------------------------------------------- + + +def _deploy(holder: str, extra_top: str = "") -> str: + return f""" +metadata.root: + package: acme + children: + - system.software: + name: Ledger + children: + - app.service: {{ name: web }} + - app.service: {{ name: Feeds }} +{extra_top} + - deployment.test: {{ name: d1, holder: {holder} }} +""" + + +@pytest.mark.parametrize(("holder", "type_"), [("Ledger", "system"), ("Feeds", "app"), ("Ledger.web", "app")]) +def test_a_value_resolves_to_a_node_of_any_listed_type(holder: str, type_: str) -> None: + r = _load(_deploy(holder)) + _clean(r) + target = ref_target(_at(r.root, "d1"), "holder") + assert target is not None and target.type == type_ + + +def test_a_node_of_an_unlisted_type_is_the_wrong_kind_and_the_message_lists_every_type() -> None: + r = _load( + """ +metadata.root: + package: acme + children: + - resource.rdb: { name: Store } + - deployment.test: { name: d1, holder: Store } +""" + ) + assert _codes(r) == ["ERR_REF_WRONG_KIND"] + assert "not a system or an app of subtype software or service" in r.errors[0].message + + +def test_target_sub_types_narrows_whichever_listed_type_the_value_resolves_to() -> None: + _clean( + _load( + """ +metadata.root: + package: acme + children: + - system.software: + name: Ledger + children: + - role.service: { name: clerk } + - resource.rdb: { name: books } + - resource.queue: { name: jobs } + - app.service: { name: web, uses: clerk } + - app.service: { name: worker, uses: books } + - app.service: { name: pump, uses: jobs } +""" + ) + ) + + +def test_two_listed_types_sharing_the_name_at_the_top_level_are_ambiguous() -> None: + r = _load(_deploy("Shared", " - system.software: { name: Shared }\n - app.service: { name: Shared }")) + assert _codes(r) == ["ERR_REF_UNRESOLVED"] + assert 'ambiguous: it names both system.software "Shared" and app.service "Shared"' in r.errors[0].message + + +def test_two_listed_types_sharing_the_name_in_a_container_are_ambiguous_but_a_nearer_container_shadows() -> None: + def model(uses: str) -> str: + return f""" +metadata.root: + package: acme + children: + - system.software: + name: Ledger + children: + - role.service: {{ name: shared }} + - resource.rdb: {{ name: shared }} + - app.service: {{ name: web, uses: {uses} }} + - resource.rdb: {{ name: top }} +""" + + assert _codes(_load(model("shared"))) == ["ERR_REF_UNRESOLVED"] + assert _codes(_load(model("top"))) == [] + + +def test_the_manifest_writes_a_target_type_list_sorted() -> None: + manifest = json.loads(emit_registry_manifest(_registry())) + holder = _manifest_attr(manifest, "deployment", "test", "holder") + assert json.dumps(holder["ref"]) == json.dumps( + {"targetType": ["app", "system"], "targetSubTypes": ["service", "software"]} + ) diff --git a/server/rust/metaobjects/data/ERROR-CODES.json b/server/rust/metaobjects/data/ERROR-CODES.json index d816b26a1f..cdf78765f9 100644 --- a/server/rust/metaobjects/data/ERROR-CODES.json +++ b/server/rust/metaobjects/data/ERROR-CODES.json @@ -64,8 +64,8 @@ "ERR_STORAGE_WITHOUT_OBJECT_REF": "@storage was set on a field that has no @objectRef.", "ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF": "ADR-0013: a field.object declares no @objectRef. A field.object models a typed nested value and REQUIRES @objectRef. The message states the whole ladder rather than only the escape hatch: a known key set is an object.value the field @objectRefs; dynamic keys over a known value type are a field.map (@objectRef for a value object, @valueType for a scalar); only a bag no reader pins a key in is @dbColumnType: jsonb on a field.string. Naming the escape hatch alone is what taught adopters to reach for the bag by default.", "ERR_UNRESOLVED_OBJECT_REF": "ADR-0042: a field.object / field.map @objectRef does not resolve to any object in the loaded tree (a dangling target). The ref resolves package-locally when bare (referrer's package, else root-level) and exactly when FQN — a bare cross-package ref no longer binds elsewhere. The error names same-short-name objects in other packages so the author can qualify it.", - "ERR_REF_UNRESOLVED": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node that resolves to nothing, by the typed lookup or by the untyped lookup the loader runs to choose its error. The default code when the facet names no `errorCode`.", - "ERR_REF_WRONG_KIND": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node of another type than the facet's `targetType`, or a subtype outside its `targetSubTypes`. The default code when the facet names no `errorCode`.", + "ERR_REF_UNRESOLVED": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node that resolves to nothing, by the typed lookup or by the untyped lookup the loader runs to choose its error, or names nodes of two of the facet's listed target types that share the name (ambiguous). The default code when the facet names no `errorCode`.", + "ERR_REF_WRONG_KIND": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node of another type than the facet's `targetType` (or than every type in it, when it is a list), or a subtype outside its `targetSubTypes`. The default code when the facet names no `errorCode`.", "ERR_RESERVED_ATTR": "An @-prefixed reserved structural keyword (e.g. @name, @isArray, @children) was used as an inline attribute.", "ERR_SCOPE_PATTERN_INVALID": "Phase-1 metadata-source-resolution: a scope include/exclude package pattern is malformed (empty pattern or empty :: segment).", "ERR_SOURCE_NO_PRIMARY": "An object declares source nodes but none has role=primary.", diff --git a/server/rust/metaobjects/src/manifest.rs b/server/rust/metaobjects/src/manifest.rs index 1e05ab1b82..ee8030ee9f 100644 --- a/server/rust/metaobjects/src/manifest.rs +++ b/server/rust/metaobjects/src/manifest.rs @@ -77,7 +77,11 @@ fn manifest_attr(attr: &AttrSchema) -> Value { /// `wrongSystemCode` (each only when present). fn manifest_ref(r: &ReferenceFacet) -> Value { let mut m = Map::new(); - m.insert("targetType".into(), json!(r.target_type)); + // One type is a string; a list is sorted (ordinal). + match r.target_types.as_slice() { + [one] => m.insert("targetType".into(), json!(one)), + many => m.insert("targetType".into(), sorted(many)), + }; if let Some(list) = &r.target_sub_types { m.insert("targetSubTypes".into(), sorted(list)); } diff --git a/server/rust/metaobjects/src/providers.rs b/server/rust/metaobjects/src/providers.rs index 48bfbb1715..aecc90ddb0 100644 --- a/server/rust/metaobjects/src/providers.rs +++ b/server/rust/metaobjects/src/providers.rs @@ -350,6 +350,8 @@ const FACET_KEYS: &[&str] = &[ "errorCode", "wrongSystemCode", ]; +const TARGET_TYPE_RULE: &str = + "targetType must name one type, or list two or more distinct types, never \"*\""; const SUB_TYPES_RULE: &str = "targetSubTypes must be a non-empty list of distinct subtype names, never \"*\""; @@ -395,9 +397,21 @@ fn to_reference_facet( value_type.unwrap_or("") ))); } - let target_type = match r.get("targetType").and_then(Value::as_str) { - Some(t) if !t.is_empty() && t != WILDCARD => t.to_string(), - _ => return Err(fail("targetType must name one type, never \"*\"")), + let target_types = match r.get("targetType") { + Some(Value::String(t)) if !t.is_empty() && t != WILDCARD => vec![t.clone()], + Some(Value::Array(items)) if items.len() >= 2 => { + let mut list: Vec = Vec::new(); + for item in items { + match item.as_str() { + Some(t) if !t.is_empty() && t != WILDCARD && !list.iter().any(|l| l == t) => { + list.push(t.to_string()); + } + _ => return Err(fail(TARGET_TYPE_RULE)), + } + } + list + } + _ => return Err(fail(TARGET_TYPE_RULE)), }; let target_sub_types = match r.get("targetSubTypes") { None => None, @@ -449,7 +463,7 @@ fn to_reference_facet( )); } Ok(ReferenceFacet { - target_type, + target_types, target_sub_types, field_path, same_system, diff --git a/server/rust/metaobjects/src/registry.rs b/server/rust/metaobjects/src/registry.rs index 6bb12877ed..a5843262e1 100644 --- a/server/rust/metaobjects/src/registry.rs +++ b/server/rust/metaobjects/src/registry.rs @@ -66,9 +66,10 @@ impl AttrSchema { /// `type: "attr"` child, and the loader enforces it with no code per provider. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ReferenceFacet { - /// The type the value must resolve to. Never `*`. - pub target_type: String, - /// The subtypes of `target_type` the value may resolve to. `None`: any. Never empty. + /// The types the value may resolve to: one, or two or more distinct ones when the + /// facet declares a list. Never empty, never `*`. + pub target_types: Vec, + /// The subtypes of whichever listed type the value resolves to. `None`: any. Never empty. pub target_sub_types: Option>, /// The value is `Target.field`: only the top-level `Target` is resolved. pub field_path: bool, @@ -85,7 +86,7 @@ impl ReferenceFacet { /// A facet that targets `target_type` and reports `error_code` for every failure. pub fn of(target_type: &str, error_code: &str) -> Self { Self { - target_type: target_type.to_string(), + target_types: vec![target_type.to_string()], target_sub_types: None, field_path: false, same_system: false, diff --git a/server/rust/metaobjects/src/validate/refs.rs b/server/rust/metaobjects/src/validate/refs.rs index d9c73cbe90..23f0e99056 100644 --- a/server/rust/metaobjects/src/validate/refs.rs +++ b/server/rust/metaobjects/src/validate/refs.rs @@ -87,12 +87,28 @@ pub(crate) enum RefMatch { Found(Vec), /// The untyped lookup found this node: the value names the wrong kind of node. WrongKind(NodeId), + /// Nodes of two or more of the facet's listed types share the name at the step that + /// finds the target: the value resolves to none of them (rule 1). + Ambiguous(Vec), /// Nothing of that name. Unresolved, /// A `..::` that climbs above the root package. OverDrop, } +/// What `find` returns: the path to the target, or nodes of several listed types that +/// share its name. +enum Hit { + Path(Vec), + Ambiguous(Vec), +} + +/// What one container yields for a name. +enum Child { + One(NodeId), + Ambiguous(Vec), +} + /// Every top-level node by type then resolution key, and by key alone, built once per /// load (ADR-0042: no short-name fallback). pub(crate) struct SymbolTable<'t> { @@ -125,17 +141,6 @@ impl<'t> SymbolTable<'t> { } } - /// A top-level node of `type_name` by ADR-0059 R2 form: `::Rest` root-absolute, - /// `..::Rest` parent-relative, `pkg::Name` exact, bare `Name` in the referrer's - /// package then root-level. - fn resolve(&self, type_name: &str, reference: &str, pkg: &str) -> Option { - let bucket = self.by_type.get(type_name)?; - owner_candidate_keys(reference, pkg) - .ok()? - .iter() - .find_map(|k| bucket.get(k).copied()) - } - /// The top-level nodes of any type under the first candidate key that has any. fn top_level_named(&self, owner: &str, pkg: &str) -> &[NodeId] { owner_candidate_keys(owner, pkg) @@ -155,11 +160,46 @@ impl<'t> SymbolTable<'t> { .collect() } - /// The first child of `parent` named `name`, of `type_name` when given. - fn child_named(&self, parent: NodeId, name: &str, type_name: Option<&str>) -> Option { - self.children_named(parent, name) - .into_iter() - .find(|&c| type_name.is_none_or(|t| self.tree.node(c).type_name == t)) + /// The first child of `parent` named `name`, of one of `types` when given; with + /// several listed types, the children of two or more of them sharing the name. + fn child_named(&self, parent: NodeId, name: &str, types: Option<&[String]>) -> Option { + let named = self.children_named(parent, name); + let Some(types) = types else { + return named.first().copied().map(Child::One); + }; + // Names are unique per type within one parent, so each listed type has at most one. + let hits: Vec = types + .iter() + .filter_map(|t| { + named + .iter() + .copied() + .find(|&c| &self.tree.node(c).type_name == t) + }) + .collect(); + match hits.as_slice() { + [] => None, + [one] => Some(Child::One(*one)), + _ => Some(Child::Ambiguous(hits)), + } + } + + /// A top-level node of one of `types` by ADR-0059 R2 form: the first candidate key + /// that holds any, ambiguous when it holds nodes of two of them. + fn resolve_typed(&self, types: &[String], reference: &str, pkg: &str) -> Option { + let keys = owner_candidate_keys(reference, pkg).ok()?; + for key in &keys { + let hits: Vec = types + .iter() + .filter_map(|t| self.by_type.get(t.as_str())?.get(key).copied()) + .collect(); + match hits.as_slice() { + [] => {} + [one] => return Some(Hit::Path(vec![*one])), + _ => return Some(Hit::Ambiguous(hits)), + } + } + None } /// The physical containers from the top-level node down to `container`, inclusive. @@ -194,26 +234,29 @@ impl<'t> SymbolTable<'t> { } // A `fieldPath` target is top-level: the referrer's containers are not searched. let from = (!facet.field_path).then_some(referrer); - if let Some(path) = self.find(from, reference, Some(&facet.target_type), pkg) { - return RefMatch::Found(path); + match self.find(from, reference, Some(&facet.target_types), pkg) { + Some(Hit::Path(path)) => return RefMatch::Found(path), + Some(Hit::Ambiguous(nodes)) => return RefMatch::Ambiguous(nodes), + None => {} } // Rule 6: the untyped lookup, along the same order, only picks the error code. match self.find(from, reference, None, pkg) { - Some(path) => RefMatch::WrongKind(path[path.len() - 1]), - None => RefMatch::Unresolved, + Some(Hit::Path(path)) => RefMatch::WrongKind(path[path.len() - 1]), + _ => RefMatch::Unresolved, } } /// The path, top-level owner first, to the node `reference` names whose final segment - /// is of `type_name` (any type when `None`). With no `referrer`, no container is + /// is of one of `types` (any type when `None`), or the nodes of two or more of `types` + /// sharing the name at the step that finds it. With no `referrer`, no container is /// searched. fn find( &self, referrer: Option, reference: &str, - type_name: Option<&str>, + types: Option<&[String]>, pkg: &str, - ) -> Option> { + ) -> Option { let (owner, tail) = split_child_tail(reference); if tail.is_empty() { // Rule 4: a bare value is looked for among the children of each container of @@ -223,19 +266,25 @@ impl<'t> SymbolTable<'t> { { let mut cur = self.tree.node(referrer).parent; while let Some(c) = cur.filter(|&c| c != self.root) { - if let Some(hit) = self.child_named(c, owner, type_name) { - let mut path = self.containers_to(c); - path.push(hit); - return Some(path); + match self.child_named(c, owner, types) { + Some(Child::One(hit)) => { + let mut path = self.containers_to(c); + path.push(hit); + return Some(Hit::Path(path)); + } + Some(Child::Ambiguous(nodes)) => return Some(Hit::Ambiguous(nodes)), + None => {} } cur = self.tree.node(c).parent; } } - let top = match type_name { - Some(t) => self.resolve(t, owner, pkg), - None => self.top_level_named(owner, pkg).first().copied(), + return match types { + Some(types) => self.resolve_typed(types, owner, pkg), + None => self + .top_level_named(owner, pkg) + .first() + .map(|&t| Hit::Path(vec![t])), }; - return top.map(|t| vec![t]); } // Rule 3: `Owner.child[.grand]`: the owner by its form, then each segment by name. let segments: Vec<&str> = tail[CHILD_REF_SEP.len_utf8()..] @@ -257,13 +306,17 @@ impl<'t> SymbolTable<'t> { walked.push(next); } // Rule 1: the final segment is typed. - let last = self.child_named( + match self.child_named( walked[walked.len() - 1], segments[segments.len() - 1], - type_name, - )?; - walked.push(last); - Some(walked) + types, + )? { + Child::One(last) => { + walked.push(last); + Some(Hit::Path(walked)) + } + Child::Ambiguous(nodes) => Some(Hit::Ambiguous(nodes)), + } } } @@ -344,14 +397,24 @@ fn check_reference( n.type_name, n.sub_type, desc.attr ) }; - let want = match &facet.target_sub_types { - None if facet.target_type == TYPE_OBJECT => "an object".to_string(), - None => format!("a {}", facet.target_type), - Some(subs) => subs + let article = |t: &str| { + let an = t.starts_with(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']); + format!("{} {t}", if an { "an" } else { "a" }) + }; + let all_types = facet + .target_types + .iter() + .map(|t| article(t)) + .collect::>() + .join(" or "); + let want = match (&facet.target_sub_types, facet.target_types.as_slice()) { + (None, _) => all_types, + (Some(subs), [one]) => subs .iter() - .map(|s| format!("{}.{s}", facet.target_type)) + .map(|s| format!("{one}.{s}")) .collect::>() .join(" or "), + (Some(subs), _) => format!("{all_types} of subtype {}", subs.join(" or ")), }; let kind_code = |default: &'static str| facet.error_code.as_deref().unwrap_or(default); for value in values.into_iter().filter(|v| !v.is_empty()) { @@ -370,9 +433,29 @@ fn check_reference( )); continue; } + RefMatch::Ambiguous(nodes) => { + let names = nodes + .iter() + .map(|&n| { + let n = tree.node(n); + format!("{}.{} \"{}\"", n.type_name, n.sub_type, n.name) + }) + .collect::>() + .join(" and "); + out.errors.push(facet_error( + tree, + node, + kind_code(ERR_REF_UNRESOLVED), + format!( + "{} is ambiguous: it names both {names}. Rename one of them.", + label(value) + ), + )); + continue; + } miss => { // ADR-0042 §5: the did-you-mean hint is object-scoped. - let hint = if facet.target_type == TYPE_OBJECT { + let hint = if facet.target_types.iter().any(|t| t == TYPE_OBJECT) { did_you_mean_hint(tree, ctx.root, value) } else { String::new() diff --git a/server/rust/metaobjects/src/validate/refs_tests.rs b/server/rust/metaobjects/src/validate/refs_tests.rs index b3ccae8503..d7e8f303cf 100644 --- a/server/rust/metaobjects/src/validate/refs_tests.rs +++ b/server/rust/metaobjects/src/validate/refs_tests.rs @@ -46,7 +46,11 @@ fn definition() -> Value { { "type": "attr", "subType": "string", "name": "pinnedRole", "min": 0, "max": 1, "description": "Test.", "ref": { "targetType": "role", "sameSystem": true, "wrongSystemCode": "ERR_TEST_OUTSIDE" } }, { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Test.", - "ref": { "targetType": "role" } } + "ref": { "targetType": "role" } }, + { "type": "attr", "subType": "string", "name": "either", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": ["role", "app"] } }, + { "type": "attr", "subType": "string", "name": "eitherTop", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": ["resource", "app"] } } ] } ] }) @@ -209,7 +213,7 @@ fn type_of(r: &LoadResult, id: Option) -> Option { fn the_reader_lowers_ref_onto_the_attribute_schema() { let r = registry(); let facet = facet_of(&r, "grant", "rdb", "resource").expect("a facet"); - assert_eq!(facet.target_type, "resource"); + assert_eq!(facet.target_types, ["resource"]); assert_eq!(facet.target_sub_types, Some(vec!["rdb".to_string()])); assert!(facet.same_system); assert!(!facet.field_path); @@ -239,6 +243,24 @@ fn the_reader_refuses_a_facet_the_format_does_not_allow() { let cases: &[(Value, &str, &str)] = &[ (json!({ "targetType": "role" }), "int", "only a string attr"), (json!({ "targetType": "*" }), "string", "targetType"), + (json!({ "targetType": [] }), "string", "targetType"), + (json!({ "targetType": ["role"] }), "string", "targetType"), + ( + json!({ "targetType": ["role", "role"] }), + "string", + "targetType", + ), + ( + json!({ "targetType": ["role", "*"] }), + "string", + "targetType", + ), + ( + json!({ "targetType": ["role", ""] }), + "string", + "targetType", + ), + (json!({ "targetType": ["role", 3] }), "string", "targetType"), ( json!({ "targetType": "role", "targetSubTypes": [] }), "string", @@ -389,7 +411,7 @@ fn the_core_definitions_declare_exactly_the_four_core_references() { def.type_name, def.sub_type, a.name, - f.target_type, + f.target_types.join("|"), f.field_path, f.error_code.as_deref().unwrap_or("-") )); @@ -982,3 +1004,78 @@ fn every_code_is_in_the_shared_catalogue() { ); } } + +// ---- a facet that lists several target types ------------------------------------------ + +#[test] +fn the_reader_keeps_a_listed_target_type_as_a_list() { + let r = registry(); + let facet = facet_of(&r, "deployment", "test", "either").expect("a facet"); + assert_eq!(facet.target_types, ["role", "app"]); +} + +#[test] +fn a_listed_target_type_resolves_to_either_type() { + let (reg, r) = load(&model( + "", + " - deployment.test: { name: d1, either: Ledger.clerk }\n - deployment.test: { name: d2, either: Ledger.web }", + )); + clean(&r); + let d1 = at(&r, &["d1"]); + let d2 = at(&r, &["d2"]); + assert_eq!( + type_of(&r, bound_to(®, &r, d1, "either")).as_deref(), + Some("role") + ); + assert_eq!( + type_of(&r, bound_to(®, &r, d2, "either")).as_deref(), + Some("app") + ); +} + +#[test] +fn a_listed_target_type_still_refuses_another_kind_and_nothing() { + let (_, r) = load(&model( + "", + " - deployment.test: { name: d1, either: Ledger.books }\n - deployment.test: { name: d2, either: Ledger.nope }", + )); + assert_eq!(codes(&r), ["ERR_REF_WRONG_KIND", "ERR_REF_UNRESOLVED"]); +} + +#[test] +fn a_listed_target_type_is_ambiguous_in_a_container() { + // `Parcels.api` names both a role and an app. + let (reg, r) = load(&model( + "", + " - deployment.test: { name: d1, either: Parcels.api }", + )); + assert_eq!(codes(&r), ["ERR_REF_UNRESOLVED"]); + let m = &r.errors[0].message; + assert!( + m.contains("ambiguous") + && m.contains("role.service \"api\"") + && m.contains("app.service \"api\""), + "{m}" + ); + let d1 = at(&r, &["d1"]); + assert_eq!(bound_to(®, &r, d1, "either"), None); +} + +#[test] +fn a_listed_target_type_is_ambiguous_at_the_top_level() { + let (_, r) = load(&model( + "", + " - app.service: { name: Dup }\n - resource.rdb: { name: Dup }\n - deployment.test: { name: d1, eitherTop: Dup }", + )); + assert_eq!(codes(&r), ["ERR_REF_UNRESOLVED"]); + assert!(r.errors[0].message.contains("ambiguous")); +} + +#[test] +fn the_manifest_writes_a_listed_target_type_sorted() { + let manifest = build_manifest(®istry()); + assert_eq!( + manifest_attr(&manifest, "deployment", "test", "either")["ref"].to_string(), + r#"{"targetType":["app","role"]}"# + ); +} diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json index 61a82748f7..1930e6185a 100644 --- a/server/rust/metaobjects/tests/conformance-expected-failures.json +++ b/server/rust/metaobjects/tests/conformance-expected-failures.json @@ -1,6 +1,6 @@ { "language": "rust", "notes": "The Rust port passes every fixture of the shared metamodel corpus, so the ledger is empty. The ledger may only shrink and is kept for the day a new fixture lands that Rust does not pass yet: list it here with the reason, and it leaves when the work that covers it lands. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.", - "minPassing": 596, + "minPassing": 599, "fixtures": [] } From 6fae2598d7b4b87bfb0cd9d185a56c17df415aad Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 3 Dec 2026 15:58:40 -0500 Subject: [PATCH 3/4] docs(site): regenerate the role reference page --- site-reference/types/role.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/site-reference/types/role.html b/site-reference/types/role.html index 632ac8ee8f..d94389dd43 100644 --- a/site-reference/types/role.html +++ b/site-reference/types/role.html @@ -196,7 +196,7 @@

role.token

metaobjects-systems-core -Who was handed the token: an organization node, by name (tidewell::Tidewell). Optional. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. ADR-0070 call 9 also admits a system here; that waits on the reference facet accepting more than one target type. +Who was handed the token: an organization or a system node, by name (tidewell::Tidewell, tidewell::Feeds). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. @memberOf From bee5b87c8e9a6010cab69c95fe4be5dfaaf1969c Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 3 Dec 2026 16:29:41 -0500 Subject: [PATCH 4/4] no-mistakes(document): sync docs for ref facet target type list --- docs/CONFORMANCE.md | 2 +- spec/metamodel-definitions.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 26e32e5744..a59c04be84 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -468,7 +468,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack | `origin-*`, `error-origin-*` | [features/templates-and-payloads.md](features/templates-and-payloads.md) (payload origins) | | `projection-*`, `error-projection-*`, `field-readonly-on-view-projection` | [features/source-kinds.md](features/source-kinds.md) (projections + the object taxonomy, ADR-0028) | | `requirement-*`, `error-unknown-attr-requirement` | [features/requirements.md](features/requirements.md) (vocabulary only — the gate has its own corpus, `requirement-check-conformance/`; see "Split coverage" above) | -| `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's two worked cases, the closed `@residency` set, and an app's one build, counting a build it inherits) | +| `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby`, `error-ref-ambiguous-heldby`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's worked cases, including the target type list behind `@heldBy`, the closed `@residency` set, and an app's one build, counting a build it inherits) | | `reporting-*`, `error-dimension-*`, `error-measure-*`, `error-ratio-*`, `error-segment-*`, `error-report-*`, `error-relative-date-*` | [features/reporting.md](features/reporting.md) (the `dimension` / `measure` / `segment` / `object.report` vocabulary and its load-time rules; design in the [FR-044 spec](superpowers/specs/2026-10-02-fr-044-core-reporting-design.md)) | | `rules-*`, `error-rules-*` | [features/business-rules.md](features/business-rules.md) (operations, permission names and lifecycles: the vocabulary and its load-time rules, ADR-0066; the `verify` gate has its own corpus, `rules-check-conformance/`) | | `provider-extension-*`, `provider-custom-vocabulary-*` | [features/extending-with-providers.md](features/extending-with-providers.md) (a project's own provider: a new subtype plus attributes on an existing type load with it and are refused without it, every port writing the provider in its own language) | diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md index cde98f8ed6..aff7c790ce 100644 --- a/spec/metamodel-definitions.md +++ b/spec/metamodel-definitions.md @@ -122,7 +122,8 @@ containers**. 4. **Bare values look in the referrer's containers first.** A bare value (no `::`, no dot) is looked for among the children of each container of the referrer, nearest first, up to and including the referrer's top-level node. At each container only a child of `targetType` - counts, and the first one found is the target. When no container has one, the value resolves + counts (a child of any listed type, when `targetType` is a list), and the first one found is + the target. When no container has one, the value resolves as a top-level node under ADR-0042 (the referrer's package, else root). So a `grant.rdb` under `role.service api` under `system.software Parcels` reads `resource: db` as `Parcels.db`. An `object` is always top-level and no container ever holds one, so the four