From 8842b2ccfbe50fc28f01f3f3592ed785d9f6bf77 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 18:58:04 -0500 Subject: [PATCH 01/12] fix(python): enforce the rc.21 view vocabulary and run the key-types and xpkg corpora The Python loader now ports the TypeScript origin.function, dotted-path origin.computed, correlated origin.first filter, grain passthrough and derived-cycle checks, so error-origin-function-free-sql and projection-view-vocabulary-rc21 pass and the expected-failures ledger is empty. A bare @from on a projection resolves in the file's default package. The generated key-types api-contract lane and the xpkg-value-object-refs codegen corpus now run in Python; the docs no longer claim single-int keys. --- docs/ports/python.md | 4 +- .../src/metaobjects/codegen/KNOWN_GAPS.md | 33 +- .../metaobjects/loader/validation_passes.py | 393 +++++++++++++----- .../persistence/origin/origin_constants.py | 6 + ...test_xpkg_value_object_refs_conformance.py | 105 +++++ .../conformance-expected-failures.json | 13 +- .../integration/generated_key_types_app.py | 174 ++++++++ .../test_api_contract_key_types.py | 69 +++ ...test_origin_function_and_derived_cycles.py | 76 ++++ 9 files changed, 745 insertions(+), 128 deletions(-) create mode 100644 server/python/tests/codegen/test_xpkg_value_object_refs_conformance.py create mode 100644 server/python/tests/integration/generated_key_types_app.py create mode 100644 server/python/tests/integration/test_api_contract_key_types.py create mode 100644 server/python/tests/loader/test_origin_function_and_derived_cycles.py diff --git a/docs/ports/python.md b/docs/ports/python.md index 0ecc0f11e0..d42f3f9c93 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -368,8 +368,8 @@ envelope is `{"error": "not_found"}`. Filter operators (`eq` / `ne` / …) **do* a per-entity filter allowlist is generated and the router parses `filter[field][op]` into typed predicates. Remaining gaps are listed in [KNOWN_GAPS.md](https://github.com/metaobjectsdev/metaobjects/blob/main/server/python/src/metaobjects/codegen/KNOWN_GAPS.md); in short: the generated -router assumes a single-field `int` primary key (other types generate but need a hand edit to the -`: int` typing), the router's request and response types are `dict[str, Any]` rather than +router takes its key type from the `identity.primary` field (`uuid.UUID`, `str` or `int`; a composite +key routes by its first field), the router's request and response types are `dict[str, Any]` rather than per-entity Pydantic models, and there is no stored-procedure callable generator (FR-015 ships in TypeScript, C# and Kotlin only). diff --git a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md index 3f14a45b92..03118554f3 100644 --- a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md +++ b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md @@ -3,26 +3,19 @@ This document tracks deliberate Day-1 deferrals in the Python codegen (`metaobjects.codegen.generators`). -## Single-field, `int`-typed primary keys only - -**Status:** assumption baked into Day 1. - -The generated router assumes the entity's primary key is a single field -of type `int` (the canonical `BaseEntity` convention across the shared -corpus). The path-parameter type is hard-coded to `int` (e.g. -`def get_author(author_id: int, ...)`); the `find_by_id` / `update` / -`delete` repository methods take `id: int`. - -Composite PKs would require a URL grammar for composite ids -(`/api//{id_a}_{id_b}` or similar) that the cross-port contract -has not yet specified. Entities with non-`int` single-field PKs (e.g. -`UUID`) still generate, but the `: int` typing in the generated code -will need a hand-edit until typed-PK threading lands in the generator. - -**Why deferred:** non-`int` PKs are uncommon and composite PKs are -rarer still. Adding generic PK-type threading to the generator is a -non-trivial spec change that should be discussed at the cross-port -contract level first. +## Composite primary keys are not served + +**Status:** deliberate; the single-field key types are NOT a gap. + +The generated router derives the key's Python type from the `identity.primary` field through +the same mapper the Pydantic model uses: `field.uuid` is `uuid.UUID`, `field.string` is `str`, +`field.int` and `field.long` are `int`. The path parameter, the repository Protocol's +`find_by_id` / `update` / `delete` and the M:N traversal all take that type. The shared +`api-contract-conformance/key-types/` sub-corpus gates it in the generated lane. + +A composite key would need a URL grammar for composite ids (`/api//{id_a}_{id_b}` or +similar) that the cross-port contract has not specified, so a composite key routes by its first +`@fields` member, as TypeScript does. ## DTO equals `dict[str, Any]` (no separate request / response Pydantic models) diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 7485d989dc..6959297553 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -124,8 +124,14 @@ ORIGIN_ATTR_CONVERT, ORIGIN_ATTR_DISTINCT, ORIGIN_ATTR_EXPR, + ORIGIN_ATTR_ARGS, ORIGIN_ATTR_FILTER, ORIGIN_ATTR_FROM, + ORIGIN_ATTR_FUNCTION, + ORIGIN_ATTR_PARAMS, + ORIGIN_ATTR_RETURNS, + ORIGIN_ATTR_SCHEMA, + ORIGIN_FUNCTION_IDENTIFIER, ORIGIN_ATTR_SEGMENT, CORRELATED_FILTER_OPS, FILTER_OP_IS_DISTINCT_FROM, @@ -137,6 +143,7 @@ ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, ORIGIN_SUBTYPE_PASSTHROUGH, ) from ..meta.core.relationship.relationship_constants import ( @@ -250,6 +257,8 @@ def run_validations( _validate_origin_paths(root, errors) # FR-024 B6 — an entity's origin-bearing field needs a read-capable source. _validate_derived_field_providability(root, errors) + # rc.21 part B fix round 2 (N3): a derived field that depends on itself has no SQL. + _validate_derived_cycles(root, errors) _validate_relationships(root, errors) # Rule (e) (#368) — registered alongside _validate_relationships (the M:N # slim-vocabulary pass, rule (d)): same deferred-resolution timing (after @@ -1837,7 +1846,7 @@ def _validate_origin_segments_and_correlation(root: MetaData, errors: list[MetaE for obj in root.own_children(): if obj.type != TYPE_OBJECT or obj.sub_type not in (OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_ENTITY): continue - pkg = obj.package or "" + pkg = referrer_package_of(obj) # ADR-0039 sanctioned own: origin.* never inherits; each is judged where declared. for field in (c for c in obj.own_children() if c.type == TYPE_FIELD): for origin in field.own_children(): @@ -1862,7 +1871,10 @@ def _validate_origin_segments_and_correlation(root: MetaData, errors: list[MetaE continue base = _derive_base_entity(obj, root, pkg, field.name, origin.source, []) if base is not None: - _check_correlated_operands(filter_value, base, where, origin.source, errors) + _check_correlated_operands( + filter_value, base, where, origin.source, errors, + obj.sub_type == OBJECT_SUBTYPE_PROJECTION, + ) def _origin_related_entity(origin: MetaData, root: MetaData, pkg: str) -> MetaData | None: @@ -1882,7 +1894,8 @@ def _origin_related_entity(origin: MetaData, root: MetaData, pkg: str) -> MetaDa def _check_correlated_operands( - filter_value: object, base: MetaData, where: str, source: object, errors: list[MetaError] + filter_value: object, base: MetaData, where: str, source: object, errors: list[MetaError], + on_projection: bool, ) -> None: if not isinstance(filter_value, dict): return @@ -1890,7 +1903,7 @@ def _check_correlated_operands( if key in (_FILTER_COMPOSE_AND, _FILTER_COMPOSE_OR): if isinstance(clause, list): for sub in clause: - _check_correlated_operands(sub, base, where, source, errors) + _check_correlated_operands(sub, base, where, source, errors, on_projection) continue if not isinstance(clause, dict): continue @@ -1915,10 +1928,28 @@ def _check_correlated_operands( if not (isinstance(name, str) and any( c.type == TYPE_FIELD and c.name == name for c in base.children() )): - errors.append(MetaError( - f'{where}: @filter on "{key}" names base-row field "{name}", which "{base.name}" ' - f"does not declare.", - ErrorCode.ERR_BAD_ATTR_FILTER, envelope=source)) + # rc.21 part B (U4): on a projection, the operand may be a PATH of to-one hops from + # the base row and a field of the entity reached ("orderId.customerId"), joined on + # the outer row. + path = ( + resolve_filter_path(base, name) + if isinstance(name, str) and "." in name and on_projection else None + ) + if path is not None and not isinstance(path, str): + continue + if isinstance(path, str): + message = f'{where}: @filter on "{key}" compares with the base-row path "{name}": {path}.' + elif isinstance(name, str) and "." in name and not on_projection: + message = ( + f'{where}: @filter on "{key}" compares with the path "{name}"; a path operand ' + f"is legal only on a projection, whose view joins it." + ) + else: + message = ( + f'{where}: @filter on "{key}" names base-row field "{name}", which ' + f'"{base.name}" does not declare.' + ) + errors.append(MetaError(message, ErrorCode.ERR_BAD_ATTR_FILTER, envelope=source)) def _entity_field_aggregates(f: MetaData) -> bool: @@ -1941,6 +1972,20 @@ def _filter_keys(filter_value: object, out: list[str] | None = None) -> list[str return out +def _grain_value_object(obj: MetaData, root: MetaData) -> MetaData | None: + """rc.21 part B (U14): the value object a ``@grain`` projection's rows are elements of, if it + has one. Mirrors the TS ``_grainValueObject``.""" + if obj.sub_type != OBJECT_SUBTYPE_PROJECTION: + return None + grain = obj.attr(OBJECT_PROJECTION_ATTR_GRAIN) + if not isinstance(grain, str): + return None + base = _derive_base_entity(obj, root, referrer_package_of(obj), "@grain", obj.source, []) + field = None if base is None else next( + (c for c in base.children() if c.type == TYPE_FIELD and c.name == grain), None) + return None if field is None else bound_ref_target(field, FIELD_ATTR_OBJECT_REF) + + def _validate_projection_union_and_grain(root: MetaData, errors: list[MetaError]) -> None: """rc.21 part B — the projection shapes beside a plain view. Mirrors the TS ``validateProjectionUnionAndGrain``: @@ -2073,7 +2118,7 @@ def _validate_projection_filter( # A field of the BASE entity the view does not output is filterable too (a WHERE reads # the base row); a projection field of the same name wins. No base, no fallback: the # origin passes report why one cannot be derived. - base = _derive_base_entity(obj, root, obj.package or "", "@filter", obj.source, []) + base = _derive_base_entity(obj, root, referrer_package_of(obj), "@filter", obj.source, []) if base is not None and base is not obj: for f in base.children(): if f.type == TYPE_FIELD and f.name not in fields: @@ -2986,6 +3031,40 @@ def _validate_origin_paths( from_target = _validate_entity_field_ref( from_ref, ORIGIN_ATTR_FROM, ctx, root, host_pkg, errors, origin, referrer ) + # rc.21 part B (U14): on a @grain projection, a @from on the grain field's value + # object reads a member of the array element; there is no path to walk. + if from_target is not None and from_target[0] is _grain_value_object(obj, root): + convert = origin.attr(ORIGIN_ATTR_CONVERT) is True + _check_passthrough_type( + node, from_target[1], from_ref, convert, obj, origin.source, referrer, errors + ) + member = from_target[1] + if ( + member.resolved_is_array() + or member.sub_type == FIELD_SUBTYPE_OBJECT + or member.sub_type == FIELD_SUBTYPE_MAP + ): + errors.append(MetaError( + f'origin.passthrough on {obj.name}.{node.name}: @from "{from_ref}" is not a ' + f"scalar member of the @grain element.", + ErrorCode.ERR_INVALID_ORIGIN, envelope=origin.source)) + if origin.attr(ORIGIN_ATTR_VIA) is not None: + errors.append(MetaError( + f'origin.passthrough on {obj.name}.{node.name}: @from "{from_ref}" reads the ' + f"@grain element, which takes no @via.", + ErrorCode.ERR_INVALID_ORIGIN, envelope=origin.source)) + # A value object's enum member is held in the document as its symbol; a value + # map (@intValueMap / @stringValueMap) describes a column the element does not have. + if member.sub_type == FIELD_SUBTYPE_ENUM and ( + member.attrs().get(FIELD_ATTR_INT_VALUE_MAP) is not None + or member.attrs().get(FIELD_ATTR_STRING_VALUE_MAP) is not None + ): + errors.append(MetaError( + f'origin.passthrough on {obj.name}.{node.name}: @from "{from_ref}" is an enum ' + f"with a value map, but a @grain element holds the member's symbol; read it as " + f"a field.string, or drop the map on the value object's member.", + ErrorCode.ERR_INVALID_ORIGIN, envelope=origin.source)) + continue # FR-024 B6 — extends/origin agreement (host-agnostic). if from_target is not None: _check_extends_origin_agreement( @@ -3277,53 +3356,41 @@ def _validate_origin_paths( continue # A ref names one of the projection's own fields first (a passthrough — joined - # or not —, an origin.first or another origin.computed), else a base field. - # Never itself, never an aggregate (it would need the grouped row). - def _resolve_field( + # or not —, an origin.first, another origin.computed or, rc.21 U13, a scalar + # origin.aggregate, read on the grouped row), else a base field, else (rc.21 U3, a + # projection only) a PATH of to-one hops from the base and a field of the entity + # reached, joined but not output. Never itself; never a collect (an array). + def _field_node( name: str, _base: MetaData = base, _obj: MetaData = obj, _self: str = node.name - ) -> str | None: + ) -> MetaData | None: if _obj is not _base and name != _self: - for own in _obj.children(): - if own.type != TYPE_FIELD or own.name != name: - continue - own_origin = _own_origin_of(own) - if own_origin is not None and own_origin.sub_type == ORIGIN_SUBTYPE_AGGREGATE: - return None - return own.sub_type - for f in _base.children(): - if f.type == TYPE_FIELD and f.name == name: - return f.sub_type - return None - - reached = _computed_reach(obj, node.name) if obj is not base else set() - if node.name in reached: - # One error per cycle, on its first-declared member. - first = next( - f for f in obj.children() - if f.type == TYPE_FIELD and f.name in reached - and node.name in _computed_reach(obj, f.name) - ) - if first.name == node.name: - errors.append(MetaError( - f"origin.computed on {obj.name}.{node.name}: @expr refers back to this " - f"field through other computed fields; a view cannot inline a cycle.", - ErrorCode.ERR_INVALID_ORIGIN, envelope=src)) - continue + own = next((o for o in _obj.children() if o.type == TYPE_FIELD and o.name == name), None) + if own is not None: + return own + base_field = next( + (f for f in _base.children() if f.type == TYPE_FIELD and f.name == name), None) + if base_field is not None or _obj is _base or "." not in name: + return base_field + path = resolve_filter_path(_base, name) + return path.field if path is not None and not isinstance(path, str) else None + + def _resolve_field(name: str, _self: MetaData = node) -> str | None: + found = _field_node(name) + if found is None: + return None + found_origin = _own_origin_of(found) + if ( + found is not _self and found_origin is not None + and found_origin.sub_type == ORIGIN_SUBTYPE_AGGREGATE + and found_origin.attr(ORIGIN_ATTR_AGG) == AGG_COLLECT + ): + return None + return found.sub_type - def _is_int_stored_enum( - name: str, _base: MetaData = base, _obj: MetaData = obj, _self: str = node.name - ) -> bool: + def _is_int_stored_enum(name: str) -> bool: # A cast needs it: an enum stored as an integer (@intValueMap), resolved as the - # inference resolved the ref (the projection's own field first, else a base field). - target = None - if _obj is not _base and name != _self: - target = next( - (o for o in _obj.children() if o.type == TYPE_FIELD and o.name == name), None - ) - if target is None: - target = next( - (f for f in _base.children() if f.type == TYPE_FIELD and f.name == name), None - ) + # inference resolved the ref. + target = _field_node(name) return ( target is not None and target.sub_type == FIELD_SUBTYPE_ENUM and target.attrs().get(FIELD_ATTR_INT_VALUE_MAP) is not None @@ -3338,24 +3405,8 @@ def _is_int_stored_enum( continue # A literal compared with a field must be able to equal it: of its kind, and for # an enum one of its @values (the rule a validator's @condition follows). Resolved - # as the inference resolved the ref: a projection field first, else a base field. - def _field_of( - name: str, _base: MetaData = base, _obj: MetaData = obj, _self: str = node.name - ) -> MetaData | None: - if _obj is not _base and name != _self: - for own in _obj.children(): - if own.type != TYPE_FIELD or own.name != name: - continue - own_origin = _own_origin_of(own) - if own_origin is not None and own_origin.sub_type == ORIGIN_SUBTYPE_AGGREGATE: - return None - return own - for f in _base.children(): - if f.type == TYPE_FIELD and f.name == name: - return f - return None - - literal_problem = literal_comparison_problem(expr, _field_of) + # as the inference resolved the ref. + literal_problem = literal_comparison_problem(expr, _field_node) if literal_problem is not None: errors.append(MetaError( f"origin.computed on {obj.name}.{node.name}: @expr {literal_problem}", @@ -3424,6 +3475,9 @@ def _field_of( of_target[0] if of_target is not None else None, obj, node.name, "origin.first", src, errors) + elif origin.sub_type == ORIGIN_SUBTYPE_FUNCTION: + _validate_function_origin(origin, obj, node, root, host_pkg, errors) + # --------------------------------------------------------------------------- # Pass: M:N relationship validation (FR-017 slim vocabulary) @@ -4145,16 +4199,18 @@ def _validate_identity_passthrough(root: MetaData, errors: list[MetaError]) -> N # Mirrors TS validateDerivedFieldProvidability. -def _projection_reached_entity_fields(root: MetaData) -> set[int]: +def _projection_reached_entity_fields(root: MetaData) -> dict[int, MetaData]: """ids of the entity fields projections REACH without outputting them: a projection ``@filter`` key naming a base field or a to-one path, and a passthrough ``@from``. A derived field reached this way is lowered inline where it is reached. Mirrors the TS ``projectionReachedEntityFields``.""" - reached: set[int] = set() + reached: dict[int, MetaData] = {} for obj in root.own_children(): if obj.type != TYPE_OBJECT or obj.sub_type != OBJECT_SUBTYPE_PROJECTION: continue - pkg = obj.package or "" + # ADR-0042: a bare @from / base head resolves in the projection's package, which a + # file-level default package supplies when the node restates none. + pkg = referrer_package_of(obj) base = _derive_base_entity(obj, root, pkg, "@filter", obj.source, []) # The effective filter: an extender reaches what its supers' filters name, too. filter_value = effective_projection_filter(obj) @@ -4163,11 +4219,11 @@ def _projection_reached_entity_fields(root: MetaData) -> set[int]: path = resolve_filter_path(base, key) if path is not None: if not isinstance(path, str): - reached.add(id(path.field)) + reached[id(path.field)] = path.field continue f = next((c for c in base.children() if c.type == TYPE_FIELD and c.name == key), None) if f is not None: - reached.add(id(f)) + reached[id(f)] = f # ADR-0039: resolving — inherited fields carry their own origins (read own). for field in (c for c in obj.children() if c.type == TYPE_FIELD): for origin in field.own_children(): @@ -4181,10 +4237,40 @@ def _projection_reached_entity_fields(root: MetaData) -> set[int]: from_ref, ORIGIN_ATTR_FROM, "", root, pkg, [], origin, "" ) if target is not None: - reached.add(id(target[1])) + reached[id(target[1])] = target[1] + # rc.21 part B (U3): a computed expression's path ref reaches the field at its end. + for origin in field.own_children(): + if origin.type != TYPE_ORIGIN or origin.sub_type != ORIGIN_SUBTYPE_COMPUTED: + continue + if base is None or base is obj: + continue + for name in _expression_field_refs(origin.attr(ORIGIN_ATTR_EXPR)): + if "." not in name: + continue + path = resolve_filter_path(base, name) + if path is not None and not isinstance(path, str): + reached[id(path.field)] = path.field + # A reached origin.function inlines its arguments on the same row, so a derived argument (an + # origin.computed cast, say) is reached too. + for f in list(reached.values()): + _reach_function_args(f, reached) return reached +def _reach_function_args(f: MetaData, reached: dict[int, MetaData]) -> None: + # ADR-0039: own — origin.* never inherits (ADR-0029). + origin = next( + (c for c in f.own_children() if c.type == TYPE_ORIGIN and c.sub_type == ORIGIN_SUBTYPE_FUNCTION), None) + host = f.parent + if origin is None or host is None: + return + for name in _as_list(origin.attr(ORIGIN_ATTR_ARGS)): + arg = next((c for c in host.children() if c.type == TYPE_FIELD and c.name == name), None) + if arg is not None and id(arg) not in reached: + reached[id(arg)] = arg + _reach_function_args(arg, reached) + + def _validate_derived_field_providability( root: MetaData, errors: list[MetaError] ) -> None: @@ -4214,7 +4300,9 @@ def _validate_derived_field_providability( continue # A derived field a projection reaches (its @filter or a passthrough @from) is # lowered inline there, so it needs no read source. Only the inlinable origins. - if origin.sub_type in (ORIGIN_SUBTYPE_FIRST, ORIGIN_SUBTYPE_COMPUTED) and id(field) in reached: + if origin.sub_type in ( + ORIGIN_SUBTYPE_FIRST, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FUNCTION + ) and id(field) in reached: continue errors.append( MetaError( @@ -4756,27 +4844,140 @@ def _own_origin_of(field: MetaData) -> MetaData | None: return next((c for c in field.own_children() if c.type == TYPE_ORIGIN), None) -def _computed_reach(obj: MetaData, start: str) -> set[str]: - """The projection's computed fields reachable from ``start``'s @expr through sibling - computed refs (a view inlines each one, so the walk must not return to its start).""" +def _expression_field_refs(node: object) -> list[str]: + """Every field name an attr.expression tree reads, in tree order (repeats kept).""" + return [n["field"] for n in _expr_nodes(node) if isinstance(n.get("field"), str)] - def refs(name: str) -> set[str]: - out: set[str] = set() - field = next((f for f in obj.children() if f.type == TYPE_FIELD and f.name == name), None) - origin = _own_origin_of(field) if field is not None else None - if origin is not None and origin.sub_type == ORIGIN_SUBTYPE_COMPUTED: - _expr_field_refs(origin.attr(ORIGIN_ATTR_EXPR), out) - out.discard(name) - return out - seen: set[str] = set() - pending = list(refs(start)) - while pending: - r = pending.pop() - if r not in seen: - seen.add(r) - pending.extend(refs(r)) - return seen +def _as_list(raw: object) -> list[object]: + return [] if raw is None else list(raw) if isinstance(raw, (list, tuple)) else [raw] + + +def _js_str(value: object) -> str: + """``String(value)`` as the TS port interpolates it into a message.""" + return value if isinstance(value, str) else _json_literal(value) + + +def _is_array_field(f: MetaData) -> bool: + return f.resolved_is_array() if hasattr(f, "resolved_is_array") else False + + +def _validate_function_origin( + origin: MetaData, obj: MetaData, field: MetaData, root: MetaData, host_pkg: str, errors: list[MetaError] +) -> None: + """rc.21 part B (U10) — origin.function: a call of a database function the project owns. Its + name and schema are plain identifiers (never free SQL); each argument names a scalar field of + the host (an entity), or of the projection (not an aggregate, not the field itself) or its + base. Mirrors the TS ``_validateFunctionOrigin``.""" + src = origin.source + where = f"origin.function on {obj.name}.{field.name}" + + def bad(message: str) -> None: + errors.append(MetaError(message, ErrorCode.ERR_INVALID_ORIGIN, envelope=src)) + + # ADR-0039: own — origin.* never inherits (ADR-0029). + for attr in (ORIGIN_ATTR_FUNCTION, ORIGIN_ATTR_SCHEMA): + v = origin.attr(attr) + if v is not None and (not isinstance(v, str) or not ORIGIN_FUNCTION_IDENTIFIER.match(v)): + bad(f"{where}: @{attr} {_json_literal(v)} is not a plain identifier ([A-Za-z_][A-Za-z0-9_]*); " + f"a function is named, never written as SQL.") + args = _as_list(origin.attr(ORIGIN_ATTR_ARGS)) + # The declared signature. Each parameter and the result is a field subtype (the cast targets); + # the result is the carrying field's, each argument its parameter's. + params = _as_list(origin.attr(ORIGIN_ATTR_PARAMS)) + returns = origin.attr(ORIGIN_ATTR_RETURNS) + for t in [*params, *([] if returns is None else [returns])]: + if not isinstance(t, str) or t not in EXPR_CAST_TARGETS: + bad(f"{where}: {_json_literal(t)} is not a parameter or return type; use one of " + f"{', '.join(EXPR_CAST_TARGETS)}.") + if isinstance(returns, str) and returns != field.sub_type: + bad(f"{where}: @returns {returns}, but the field is field.{field.sub_type}; the declared return " + f"type must be the field's type.") + if len(params) != len(args): + bad(f"{where}: @params declares {len(params)} parameter type(s) for {len(args)} argument(s); " + f"declare one per @args entry.") + is_projection = obj.sub_type == OBJECT_SUBTYPE_PROJECTION + base = _derive_base_entity(obj, root, host_pkg, field.name, src, []) if is_projection else obj + for index, name in enumerate(args): + own = None + if isinstance(name, str) and name != field.name: + own = next((c for c in obj.children() if c.type == TYPE_FIELD and c.name == name), None) + own_origin = _own_origin_of(own) if own is not None else None + arg = own + if arg is None and isinstance(name, str) and base is not None: + arg = next((c for c in base.children() if c.type == TYPE_FIELD and c.name == name), None) + if arg is None or name == field.name: + where_from = "the projection or its base entity" if is_projection else f'"{obj.name}"' + bad(f'{where}: @args names "{_js_str(name)}", which is not a field of {where_from}.') + elif own_origin is not None and own_origin.sub_type == ORIGIN_SUBTYPE_AGGREGATE: + bad(f'{where}: @args names "{_js_str(name)}", an origin.aggregate; a function takes values of ' + f"the row, not of the group.") + elif arg.sub_type in (FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP) or _is_array_field(arg): + array = " array" if _is_array_field(arg) else "" + bad(f'{where}: @args names "{_js_str(name)}", a field.{arg.sub_type}{array}; a function ' + f"argument is a scalar.") + elif index < len(params) and isinstance(params[index], str) and arg.sub_type != params[index]: + bad(f'{where}: argument {index + 1} "{_js_str(name)}" is a field.{arg.sub_type}, but parameter ' + f"{index + 1} is declared {params[index]}; pass an origin.computed field that casts it " + f"({{ cast: {{ field: {_js_str(name)} }}, as: {params[index]} }}).") + + +def _validate_derived_cycles(root: MetaData, errors: list[MetaError]) -> None: + """rc.21 part B fix round 2 (N3): no derived field depends on itself. A view inlines a derived + field's dependencies on the same row — an origin.function's @args, an origin.computed + expression's field refs — so a cycle among them has no SQL and would recurse forever. Refused + at load, once per cycle, naming the path (ERR_INVALID_ORIGIN). Mirrors the TS + ``validateDerivedCycles``.""" + for obj in (c for c in root.own_children() if c.type == TYPE_OBJECT): + # ADR-0039: effective — an inherited field's origin is inlined on the extender's row too. + fields = [c for c in obj.children() if c.type == TYPE_FIELD] + by_name = {f.name: f for f in fields} + origin_of = _own_origin_of + + def deps(f: MetaData, _obj: MetaData = obj, _by_name: dict[str, MetaData] = by_name) -> list[MetaData]: + origin = origin_of(f) + names: list[str] = [] + # A function naming itself in @args is refused by _validate_function_origin already. On + # an entity, a computed expression reading its own name reads itself: a one-node cycle, + # reported here. On a projection that name is the base entity's field, so it is no cycle. + self_allowed = False + if origin is not None and origin.sub_type == ORIGIN_SUBTYPE_FUNCTION: + names.extend(n for n in _as_list(origin.attr(ORIGIN_ATTR_ARGS)) if isinstance(n, str)) + elif origin is not None and origin.sub_type == ORIGIN_SUBTYPE_COMPUTED: + self_allowed = _obj.sub_type != OBJECT_SUBTYPE_PROJECTION + names.extend(n.split(".")[0] for n in _expression_field_refs(origin.attr(ORIGIN_ATTR_EXPR))) + return [ + d for d in (_by_name.get(n) for n in names) + if d is not None and (self_allowed or d is not f) and origin_of(d) is not None + ] + + done: set[int] = set() + reported: set[str] = set() + + def visit(f: MetaData, path: list[MetaData], _obj: MetaData = obj) -> None: + at = next((i for i, x in enumerate(path) if x is f), -1) + if at >= 0: + cycle = [x.name for x in [*path[at:], f]] + key = ",".join(sorted(cycle[:-1])) + if key not in reported: + reported.add(key) + origin = origin_of(f) + errors.append(MetaError( + f"{_obj.name}.{f.name}: a derived field depends on itself through " + f"{' → '.join(cycle)}; a view inlines each dependency on the same row, so the " + f"cycle has no SQL. Break it.", + ErrorCode.ERR_INVALID_ORIGIN, + envelope=origin.source if origin is not None else f.source)) + return + if id(f) in done: + return + for d in deps(f): + visit(d, [*path, f]) + done.add(id(f)) + + for f in fields: + if origin_of(f) is not None: + visit(f, []) # What a literal compared with a field.duration must be. diff --git a/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py b/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py index dfa76e353a..4af1570356 100644 --- a/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py +++ b/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py @@ -1,4 +1,6 @@ """Origin subtype vocabulary (colocated).""" +import re + from ....shared.base_types import SUBTYPE_BASE ORIGIN_SUBTYPE_PASSTHROUGH = "passthrough" @@ -28,6 +30,10 @@ ORIGIN_ATTR_FUNCTION = "function" ORIGIN_ATTR_SCHEMA = "schema" ORIGIN_ATTR_ARGS = "args" +ORIGIN_ATTR_PARAMS = "params" +ORIGIN_ATTR_RETURNS = "returns" +#: A plain SQL identifier: what @function and @schema may hold (never free SQL). +ORIGIN_FUNCTION_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\Z") # #210 — the ASSEMBLY origins: they derive a value by rolling up, computing, or # collecting from a backing store, which is what an object.projection is for. diff --git a/server/python/tests/codegen/test_xpkg_value_object_refs_conformance.py b/server/python/tests/codegen/test_xpkg_value_object_refs_conformance.py new file mode 100644 index 0000000000..542a4b5734 --- /dev/null +++ b/server/python/tests/codegen/test_xpkg_value_object_refs_conformance.py @@ -0,0 +1,105 @@ +"""fixtures/codegen-conformance/xpkg-value-object-refs/ (Python lane). + +One generated module meets two same-named types from two packages: ``acme::app::Host`` holds +``acme::alpha::Note`` and ``acme::beta::Note``, and the projection ``acme::app::Summary`` sits +beside the value object ``acme::alpha::Summary``. Nothing is renamed. Under the package layout +(each package its own subpackage) every module that meets a pair binds it unambiguously: a +module-qualified reference or an ``as`` alias, never a bare name that one import shadows. + +Python's compile check is the one the codegen-compile gate uses: import the generated package, +then ruff for undefined and redefined names. Under the flat layout the pairs share one module +directory and the generator refuses the model with ``ERR_NAME_COLLISION``. +""" +from __future__ import annotations + +import ast +import importlib +import subprocess +import sys +from pathlib import Path + +import pytest + +from metaobjects import load_uris +from metaobjects.codegen.config import GenConfig +from metaobjects.codegen.generators.entity_model import entity_model +from metaobjects.codegen.generators.filter_allowlist_generator import filter_allowlist_generator +from metaobjects.codegen.generators.names_generator import names_generator +from metaobjects.codegen.generators.router_generator import router_generator +from metaobjects.codegen.runner import run_gen + +CORPUS = Path(__file__).parents[4] / "fixtures" / "codegen-conformance" / "xpkg-value-object-refs" / "input" + + +def _load(): + result = load_uris([p.as_uri() for p in sorted(CORPUS.glob("*.json"))]) + assert not result.errors, [f"{e.code}: {e.message}" for e in result.errors] + return result.root + + +def _generate(out_dir: Path, layout: str) -> list[Path]: + config = GenConfig(out_dir=str(out_dir), emit_package_init=True, output_layout=layout) + run_gen(config, _load(), generators=[entity_model(), names_generator(), filter_allowlist_generator(), router_generator()]) + return sorted(out_dir.rglob("*.py")) + + +def test_flat_layout_refuses_the_pairs(tmp_path: Path) -> None: + with pytest.raises(Exception, match=r"ERR_NAME_COLLISION"): + _generate(tmp_path / "generated", "flat") + + +def test_package_layout_imports_checks_and_binds_every_pair(tmp_path: Path) -> None: + out_dir = tmp_path / "generated" + written = _generate(out_dir, "package") + names = {p.relative_to(out_dir).as_posix() for p in written} + for expected in ("acme/app/Host.py", "acme/alpha/Note.py", "acme/beta/Note.py", + "acme/alpha/Summary.py", "acme/app/Summary.py"): + assert expected in names, f"expected {expected}; saw {sorted(names)}" + + sys.path.insert(0, str(tmp_path)) + try: + failures: list[str] = [] + for path in written: + dotted = ".".join(path.relative_to(tmp_path).with_suffix("").parts) + if dotted.endswith(".__init__"): + dotted = dotted[: -len(".__init__")] + if path.name.endswith("_router.py"): + continue # the framework tier imports FastAPI: ruff below, the api-contract lane boots it + try: + importlib.import_module(dotted) + except Exception as exc: # noqa: BLE001 - every failure mode is a finding + failures.append(f"{path.relative_to(out_dir)}: {type(exc).__name__}: {exc}") + assert not failures, "\n".join(failures) + finally: + sys.path.remove(str(tmp_path)) + for name in [m for m in sys.modules if m.split(".")[0] == "generated"]: + del sys.modules[name] + + proc = subprocess.run( + [sys.executable, "-m", "ruff", "check", "--no-cache", "--isolated", + "--select", "F821,F822,F811,E9", "--output-format", "concise", str(out_dir)], + capture_output=True, text=True, + ) + assert proc.returncode == 0, proc.stdout + proc.stderr + + # Every module that imports a same-named pair binds each under a distinct local name. + for path in written: + tree = ast.parse(path.read_text()) + bound: dict[str, list[str]] = {} + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom): + for alias in node.names: + bound.setdefault(alias.asname or alias.name, []).append(f"{node.module}.{alias.name}") + elif isinstance(node, ast.Import): + for alias in node.names: + bound.setdefault(alias.asname or alias.name, []).append(alias.name) + clashes = {k: v for k, v in bound.items() if len(set(v)) > 1} + assert not clashes, f"{path.relative_to(out_dir)} binds one local name to two types: {clashes}" + + host = (out_dir / "acme/app/Host.py").read_text() + # Both Notes are reachable from Host under different names. + assert "from ..alpha.Note import Note as AcmeAlphaNote" in host + assert "from ..beta.Note import Note as AcmeBetaNote" in host + assert "fromAlpha: AcmeAlphaNote | None" in host + assert "fromBeta: list[AcmeBetaNote] | None" in host + assert "byKey: dict[str, AcmeBetaNote] | None" in host diff --git a/server/python/tests/conformance/conformance-expected-failures.json b/server/python/tests/conformance/conformance-expected-failures.json index 656792b04b..39d43eea1d 100644 --- a/server/python/tests/conformance/conformance-expected-failures.json +++ b/server/python/tests/conformance/conformance-expected-failures.json @@ -1,13 +1,6 @@ { "language": "python", - "fixtures": [ - "error-origin-function-free-sql", - "projection-view-vocabulary-rc21" - ], - "_comment_fr024": "FR-024 Phase-E validation parity SHIPPED in this port. The full FR-024 loader contract now holds: object.projection registration + per-subtype projection child rules + dotted Entity.child extends-resolution (type-scoped, ERR_EXTENDS_TARGET_MISMATCH), AND the validation passes \u2014 identity names required + projection identity pass-through/key-correspondence (B3), value-purity + projection-licensing subtype rules (B4a), the entity-primary-source-readonly hard cutover (B4b), @via single-hop-unique inference + origin cardinality (B5), and extends/origin agreement + derived-field providability (B6). Every former FR-024 error fixture (error-identity-name-required, error-projection-identity-not-extended, error-identity-key-mismatch, error-projection-extends-entity, error-projection-source-writable, error-value-with-identity-secondary, error-value-with-source, error-origin-via-ambiguous, error-origin-passthrough-to-many, error-origin-aggregate-no-to-many, error-extends-origin-mismatch, error-derived-field-no-read-source, error-entity-primary-source-readonly) now emits its expected code with the byte-identical source envelope and is un-ledgered.", - "notes": "The Python expected failures are the keys of \"reasons\" below. The AI LLM-call trace fixtures ai-trace-prompt-nested and ai-trace-sti load + canonical-serialize cleanly in the Python port (@responseRef registered on template.prompt, carved out of the cross-port registry manifest as ExclusionReason.TS_PILOT_VOCAB until the atomic all-ports flip; template.* admitted as an object.entity child).", - "reasons": { - "error-origin-function-free-sql": "the line registers the rc.21 view vocabulary in Python so a strict load accepts it but no loader check exists; also fails identically on origin/fix/rc19; implementedIn: typescript, csharp", - "projection-view-vocabulary-rc21": "Python accepts the view functions and the cast node (C2) but not yet the rest of what this fixture declares: a dotted path in an origin.computed @expr (customerId.zip), a scalar origin.aggregate read from a computed field, a path operand in an origin.first @filter, an origin.passthrough through a path, and a derived field on an entity that declares a read source; implementedIn: typescript, csharp" - } + "fixtures": [], + "notes": "The Python expected failures are the keys of \"reasons\" below; the ledger is empty. The AI LLM-call trace fixtures ai-trace-prompt-nested and ai-trace-sti load + canonical-serialize cleanly in the Python port (@responseRef registered on template.prompt, carved out of the cross-port registry manifest as ExclusionReason.TS_PILOT_VOCAB until the atomic all-ports flip; template.* admitted as an object.entity child).", + "reasons": {} } diff --git a/server/python/tests/integration/generated_key_types_app.py b/server/python/tests/integration/generated_key_types_app.py new file mode 100644 index 0000000000..2473c5e1af --- /dev/null +++ b/server/python/tests/integration/generated_key_types_app.py @@ -0,0 +1,174 @@ +"""Boot the GENERATED routers for entities keyed by a uuid, a string and an int. + +Peer of ``generated_router_app.py`` for ``fixtures/api-contract-conformance/key-types/``. +Runs the real generators, imports the emitted modules unmodified and mounts each router over an +in-memory repo behind its generated consumer seam. The key of each entity is read from the +loaded ``identity.primary`` and the seeded value is held in that key's native Python type +(``uuid.UUID`` for a ``field.uuid``), as a real driver hands it back. +""" +from __future__ import annotations + +import importlib.util +import shutil +import sys +import tempfile +import uuid +from pathlib import Path +from typing import Any + +from fastapi import FastAPI + +from metaobjects import MetaDataLoader +from metaobjects.codegen.generators.entity_model import render_entity_model +from metaobjects.codegen.generators.filter_allowlist_generator import render_filter_allowlist +from metaobjects.codegen.generators.router_generator import render_router +from metaobjects.meta.core.field.field_constants import FIELD_SUBTYPE_UUID +from metaobjects.meta.core.object.meta_object import MetaObject +from metaobjects.shared.base_types import TYPE_OBJECT + +from .corpus_config import attach_corpus_wire +from .generated_router_app import filter_rows + +#: entity name -> seed.json table holding its rows. +TABLES: dict[str, str] = {"Device": "devices", "Country": "countries", "Level": "levels"} + + +def _snake(name: str) -> str: + return "".join("_" + c.lower() if c.isupper() and i else c.lower() for i, c in enumerate(name)) + + +def _key_field(entity: MetaObject) -> str: + from metaobjects.codegen.generators.router_generator import pk_field_name + + return pk_field_name(entity) + + +class InMemoryKeyedRepository: + """In-memory impl of a GENERATED ``Repository``, addressed by the entity's own key.""" + + def __init__(self, key: str, uuid_fields: frozenset[str]) -> None: + self._key = key + self._uuid_fields = uuid_fields + self._rows: list[dict[str, Any]] = [] + + def _native(self, row: dict[str, Any]) -> dict[str, Any]: + return { + k: (uuid.UUID(v) if k in self._uuid_fields and isinstance(v, str) else v) + for k, v in row.items() + } + + def reset(self) -> None: + self._rows = [] + + def seed(self, rows: list[dict[str, Any]]) -> None: + self._rows = [self._native(r) for r in rows] + + def list(self, limit: int, offset: int, sort: Any, filters: Any) -> list[Any]: + rows = filter_rows(self._rows, filters) + if sort is not None: + rows = sorted( + rows, + key=lambda r: (r.get(sort.field) is None, r.get(sort.field)), + reverse=(sort.direction == "desc"), + ) + else: + rows = sorted(rows, key=lambda r: r[self._key]) + return [dict(r) for r in rows[offset : offset + limit]] + + def count(self, filters: Any) -> int: + return len(filter_rows(self._rows, filters)) + + def find_by_id(self, id: Any) -> Any | None: + for r in self._rows: + if r[self._key] == id: + return dict(r) + return None + + def create(self, dto: Any) -> Any: + row = self._native(dict(dto)) + self._rows.append(dict(row)) + return row + + def update(self, id: Any, dto: Any) -> Any | None: + for r in self._rows: + if r[self._key] == id: + r.update({k: v for k, v in self._native(dict(dto)).items() if k != self._key}) + return dict(r) + return None + + def delete(self, id: Any) -> bool: + before = len(self._rows) + self._rows = [r for r in self._rows if r[self._key] != id] + return len(self._rows) != before + + +def _load_entities(meta_json: Path) -> dict[str, MetaObject]: + tmp = Path(tempfile.mkdtemp(prefix="apic-keytypes-meta-")) + shutil.copy(meta_json, tmp / "meta.json") + result = MetaDataLoader.from_directory(str(tmp)) + attach_corpus_wire(result.root, meta_json) + if result.errors: + raise RuntimeError("; ".join(f"{e.code}: {e.message}" for e in result.errors)) + found = { + c.name.split("::")[-1]: c + for c in result.root.children() + if c.type == TYPE_OBJECT and isinstance(c, MetaObject) + } + missing = [n for n in TABLES if n not in found] + if missing: + raise RuntimeError(f"entities not found: {missing}") + return {n: found[n] for n in TABLES} + + +def _seam(repo: InMemoryKeyedRepository) -> Any: + # A closure, not ``lambda r=repo: r``: FastAPI would read ``r`` as a parameter and copy its default. + return lambda: repo + + +def build_key_types_app(corpus_root: Path) -> tuple[FastAPI, dict[str, InMemoryKeyedRepository]]: + entities = _load_entities(corpus_root / "meta.json") + pkg_name = f"genkeytypes_{uuid.uuid4().hex[:8]}" + tmp = Path(tempfile.mkdtemp(prefix="apic-keytypes-gen-")) + pkg_dir = tmp / pkg_name + pkg_dir.mkdir() + (pkg_dir / "__init__.py").write_text("") + for name, entity in entities.items(): + router_src = render_router(entity) + allowlist_src = render_filter_allowlist(entity) + if router_src is None or allowlist_src is None: + raise RuntimeError(f"generators returned None for {name}") + snake = _snake(name) + (pkg_dir / f"{snake}_filter_allowlist.py").write_text(allowlist_src) + (pkg_dir / f"{name}.py").write_text(render_entity_model(entity)) + (pkg_dir / f"{snake}_router.py").write_text(router_src) + + sys.path.insert(0, str(tmp)) + pkg_spec = importlib.util.spec_from_file_location( + pkg_name, pkg_dir / "__init__.py", submodule_search_locations=[str(pkg_dir)] + ) + pkg_mod = importlib.util.module_from_spec(pkg_spec) + sys.modules[pkg_name] = pkg_mod + pkg_spec.loader.exec_module(pkg_mod) + + app = FastAPI() + repos: dict[str, InMemoryKeyedRepository] = {} + for name, entity in entities.items(): + snake = _snake(name) + spec = importlib.util.spec_from_file_location( + f"{pkg_name}.{snake}_router", pkg_dir / f"{snake}_router.py" + ) + router_mod = importlib.util.module_from_spec(spec) + sys.modules[f"{pkg_name}.{snake}_router"] = router_mod + spec.loader.exec_module(router_mod) + uuid_fields = frozenset(f.name for f in entity.fields() if f.sub_type == FIELD_SUBTYPE_UUID) + repo = InMemoryKeyedRepository(_key_field(entity), uuid_fields) + app.include_router(router_mod.router) + app.dependency_overrides[router_mod.get_repository] = _seam(repo) + repos[name] = repo + return app, repos + + +def seed_all(repos: dict[str, InMemoryKeyedRepository], seed: dict[str, list[dict[str, Any]]]) -> None: + for name, repo in repos.items(): + repo.reset() + repo.seed(seed.get(TABLES[name], [])) diff --git a/server/python/tests/integration/test_api_contract_key_types.py b/server/python/tests/integration/test_api_contract_key_types.py new file mode 100644 index 0000000000..824aac8ebc --- /dev/null +++ b/server/python/tests/integration/test_api_contract_key_types.py @@ -0,0 +1,69 @@ +"""Cross-port API contract for entities keyed by a uuid, a string and an int. + +Drives ``fixtures/api-contract-conformance/key-types/`` against the GENERATED +routers. Generated lane only, by design: a hand-rolled reference server would accept any key type +by construction, and what is under test is whether the GENERATOR types the key from the model. + + cd server/python + uv run --extra dev pytest tests/integration/test_api_contract_key_types.py -v +""" +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest +import yaml +from fastapi.testclient import TestClient + +from . import api_contract_assertions +from .generated_key_types_app import build_key_types_app, seed_all + + +def _find_corpus_root() -> Path: + cur = Path(__file__).resolve() + while cur != cur.parent: + candidate = cur / "fixtures" / "api-contract-conformance" / "key-types" + if candidate.is_dir(): + return candidate + cur = cur.parent + raise RuntimeError("Could not find fixtures/api-contract-conformance/key-types") + + +_CORPUS = _find_corpus_root() +_SCENARIOS = [ + (raw["name"], raw) + for raw in (yaml.safe_load(p.read_text()) for p in sorted((_CORPUS / "scenarios").glob("*.yaml"))) +] +_SEED = json.loads((_CORPUS / "seed.json").read_text()) +_APP, _REPOS = build_key_types_app(_CORPUS) +_CLIENT = TestClient(_APP) + + +def _parse(text: str | None) -> Any: + if not text: + return None + try: + return api_contract_assertions.parse_body(text) + except json.JSONDecodeError: + return text + + +@pytest.mark.parametrize("scenario_name,scenario", _SCENARIOS, ids=[n for n, _ in _SCENARIOS]) +def test_key_types_scenario(scenario_name: str, scenario: dict[str, Any]) -> None: + seed_all(_REPOS, _SEED) + for req in scenario["requests"]: + kwargs: dict[str, Any] = {} + if req.get("body") is not None: + kwargs["json"] = req["body"] + response = _CLIENT.request(str(req["method"]).upper(), str(req["path"]), **kwargs) + expect = req["expect"] + api_contract_assertions.assert_response( + scenario_name=scenario_name, + request_id=str(req.get("id", "?")), + expect_status=int(expect["status"]), + expect_body=expect.get("body"), + status=response.status_code, + body=_parse(response.text), + ) diff --git a/server/python/tests/loader/test_origin_function_and_derived_cycles.py b/server/python/tests/loader/test_origin_function_and_derived_cycles.py new file mode 100644 index 0000000000..2671898da3 --- /dev/null +++ b/server/python/tests/loader/test_origin_function_and_derived_cycles.py @@ -0,0 +1,76 @@ +"""rc.21 part B: ``origin.function`` signature rules and derived-field cycles. + +The conformance corpus gates the identifier rule and the happy path +(``error-origin-function-free-sql``, ``projection-view-vocabulary-rc21``, +``error-origin-computed-cycle``); this file pins the rest of what the TypeScript loader refuses. +""" +from __future__ import annotations + +import json +import tempfile +from pathlib import Path + +from metaobjects import MetaDataLoader +from metaobjects.errors import ErrorCode + +from ..conformance.conformance_adapter import _resolve_providers + +_PROVIDERS = _resolve_providers(["metaobjects-core-types", "metaobjects-db", "metaobjects-view-expressions"]) + + +def _customer(extra: list[object]) -> dict[str, object]: + return {"object.entity": {"name": "Customer", "children": [ + {"source.rdb": {"@table": "customers", "@role": "primary"}}, + {"source.rdb": {"@kind": "view", "@view": "v_customers", "@role": "replica"}}, + {"field.long": {"name": "id"}}, + {"field.string": {"name": "zip"}}, + {"identity.primary": {"name": "id", "@fields": "id"}}, + *extra, + ]}} + + +def _load(extra: list[object]): + doc = {"metadata.root": {"package": "t::fn", "children": [_customer(extra)]}} + with tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / "meta.fn.json").write_text(json.dumps(doc)) + return MetaDataLoader.from_directory(tmp, providers=_PROVIDERS, strict=True) + + +def _fn(name: str, **attrs: object) -> dict[str, object]: + return {"field.string": {"name": name, "children": [{"origin.function": { + "@function": "tier_of", "@args": ["id", "zip"], "@params": ["long", "string"], + "@returns": "string", **attrs}}]}} + + +def _messages(result) -> list[str]: + return [e.message for e in result.errors if e.code == ErrorCode.ERR_INVALID_ORIGIN] + + +def test_a_well_formed_function_loads_clean() -> None: + assert _load([_fn("tier")]).errors == [] + + +def test_args_naming_no_field_is_refused() -> None: + msgs = _messages(_load([_fn("tier", **{"@args": ["id", "nope"]})])) + assert any('@args names "nope", which is not a field of "Customer"' in m for m in msgs) + + +def test_params_must_match_args_in_count_and_type() -> None: + assert any("declares 1 parameter type(s) for 2 argument(s)" in m + for m in _messages(_load([_fn("tier", **{"@params": ["long"]})]))) + assert any('argument 2 "zip" is a field.string, but parameter 2 is declared long' in m + for m in _messages(_load([_fn("tier", **{"@params": ["long", "long"]})]))) + + +def test_returns_must_be_the_fields_type() -> None: + assert any("@returns long, but the field is field.string" in m + for m in _messages(_load([_fn("tier", **{"@returns": "long"})]))) + + +def test_a_function_and_a_computed_field_that_feed_each_other_are_a_cycle() -> None: + computed = {"field.string": {"name": "b", "children": [ + {"origin.computed": {"@expr": {"field": "a"}}}]}} + fn = {"field.string": {"name": "a", "children": [{"origin.function": { + "@function": "f", "@args": ["b"], "@params": ["string"], "@returns": "string"}}]}} + msgs = _messages(_load([fn, computed])) + assert any("a derived field depends on itself through a → b → a" in m for m in msgs), msgs From 88a94a5a713eea3d0906e689c4364552763026ea Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 19:03:18 -0500 Subject: [PATCH 02/12] feat: add the key-types api-contract corpus; remove the C# codegen shims fixtures/api-contract-conformance/key-types/ drives generated CRUD for a client-assigned uuid, natural string and int primary key. It runs in the C#, Rust and TypeScript generated lanes. C# found that a Guid key's routes did not compile (no using System); the key type is now spelled global::System.Guid. Removes the obsolete C# ValueObjectNames.Names shim and the string forms of XmlDocBuilder (AppendTo, Indent, Prepend); output is unchanged. --- fixtures/api-contract-conformance/README.md | 3 +- .../key-types/README.md | 35 ++++ .../key-types/meta.json | 34 ++++ .../country-create-patch-delete.yaml | 66 +++++++ .../scenarios/country-get-by-id.yaml | 13 ++ .../scenarios/country-get-missing.yaml | 11 ++ .../key-types/scenarios/country-list.yaml | 11 ++ .../scenarios/device-create-patch-delete.yaml | 66 +++++++ .../key-types/scenarios/device-get-by-id.yaml | 13 ++ .../scenarios/device-get-missing.yaml | 11 ++ .../key-types/scenarios/device-list.yaml | 11 ++ .../scenarios/level-create-patch-delete.yaml | 66 +++++++ .../key-types/scenarios/level-get-by-id.yaml | 13 ++ .../scenarios/level-get-missing.yaml | 11 ++ .../key-types/scenarios/level-list.yaml | 11 ++ .../key-types/seed.json | 14 ++ .../EntityGeneratorTests.cs | 21 ++ .../ValueObjectReuseTests.cs | 12 -- .../MetaObjects.Codegen/Docs/XmlDocBuilder.cs | 44 ----- .../Generators/RoutesGenerator.cs | 12 +- .../Templates/metamodel/index.md.mustache | 2 +- .../MetaObjects.Codegen/ValueObjectNames.cs | 10 - .../Api/ApiContractCorpusPaths.cs | 6 + .../Api/ApiContractKeyTypesConformanceTest.cs | 81 ++++++++ .../Api/KeyTypesFixture.cs | 58 ++++++ .../Api/KeyTypesGeneratedServerFactory.cs | 183 ++++++++++++++++++ .../MetaObjects/SpecMetamodel/object.json | 2 +- .../SpecMetamodel/view-expressions.json | 10 +- .../MetaObjects/SpecMetamodel/view.json | 26 +-- .../metaobjects-codegen/tests/api_contract.rs | 39 +++- ...api-contract-key-types-generated-server.ts | 116 +++++++++++ .../packages/integration-tests/src/paths.ts | 4 + .../test/api-contract-key-types.test.ts | 55 ++++++ 33 files changed, 979 insertions(+), 91 deletions(-) create mode 100644 fixtures/api-contract-conformance/key-types/README.md create mode 100644 fixtures/api-contract-conformance/key-types/meta.json create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/country-create-patch-delete.yaml create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/country-get-by-id.yaml create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/country-get-missing.yaml create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/country-list.yaml create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/device-create-patch-delete.yaml create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/device-get-by-id.yaml create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/device-get-missing.yaml create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/device-list.yaml create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/level-create-patch-delete.yaml create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/level-get-by-id.yaml create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/level-get-missing.yaml create mode 100644 fixtures/api-contract-conformance/key-types/scenarios/level-list.yaml create mode 100644 fixtures/api-contract-conformance/key-types/seed.json create mode 100644 server/csharp/MetaObjects.IntegrationTests/Api/ApiContractKeyTypesConformanceTest.cs create mode 100644 server/csharp/MetaObjects.IntegrationTests/Api/KeyTypesFixture.cs create mode 100644 server/csharp/MetaObjects.IntegrationTests/Api/KeyTypesGeneratedServerFactory.cs create mode 100644 server/typescript/packages/integration-tests/src/api-contract-key-types-generated-server.ts create mode 100644 server/typescript/packages/integration-tests/test/api-contract-key-types.test.ts diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 9bdf7b930f..f9eacfca8c 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -57,7 +57,7 @@ fixtures/api-contract-conformance/ ``` Beside the 34 core scenarios above sit twelve **sub-corpora**, each a directory with its -own `meta.json`, `seed.json`, `scenarios/` and `README.md` (145 scenarios in all, 179 with the +own `meta.json`, `seed.json`, `scenarios/` and `README.md` (157 scenarios in all, 191 with the core): | Directory | Scenarios | Gates | Lanes | @@ -68,6 +68,7 @@ core): | `write-through/` | 2 | an entity that writes a table and reads a view | generated only | | `secret-fields/` | 4 | #484: a `@formExclude` or credential (`view.password`) field is ignored on create, PATCH and PUT, and a credential is never returned; a `readOnly` field is ignored the same way and still returned; a credential is on no filter or sort allowlist, so a filter or sort naming it is `400` (the `tph/` sub-directory checks this for a column one subtype of a single-table hierarchy marks as a credential) | generated only | | `enum-default/` | 2 | a create that omits a `field.enum` carrying `@default` stores the default (echo and GET by id), and a supplied member is kept | generated only | +| `key-types/` | 12 | generated CRUD routes for a primary key that is not an integer sequence: a `field.uuid` key (`Device`), a natural `field.string` key (`Country`, a code) and a `field.int` key (`Level`), each client-assigned (`@generation: assigned`): list, GET by key, a missing key is `404`, create `201` with the key in the body, PATCH, DELETE `204`, then `404` | generated only | | `projection/` | 12 | a read-only `object.projection`: reads served, every write `405`; no declared identity means no `/{id}` route; a key not named `id` addresses the row; decimal and float filters. Its `docs-routes.json` pins the routes each port documents | generated only | | `report/` | 37 | a view-backed `object.report` (FR-044): list, filter, sort and paging on derived fields, `POST` is `405`, no `/{id}` route; a `@spine` report keeps a row with no facts, and a measure with `@default` filters and sorts as its default; a dimension over an array or a map is neither filterable nor sortable. Also carries `schema.postgres.sql`, the TypeScript-produced table and views the C# lane executes | generated only | | `decimal/` | 11 | `field.decimal` is an exact canonical string on the wire (ADR-0019 Amendment 1): read, filter, sort, write and a report over decimals. A scenario's `engines:` key is exact; the `-15` twins run on SQLite and D1 as well. Also carries `schema.postgres.sql` / `schema.sqlite.sql` / `schema.mysql.sql` | generated only | diff --git a/fixtures/api-contract-conformance/key-types/README.md b/fixtures/api-contract-conformance/key-types/README.md new file mode 100644 index 0000000000..ca0477cd5e --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/README.md @@ -0,0 +1,35 @@ +# `api-contract-conformance/key-types/` — keys that are not an integer sequence + +Cross-port REST contract for the generated CRUD routes of an entity whose primary key is not a +single sequence-generated integer. Three entities, each with a client-assigned key +(`identity.primary @generation: assigned`): + +| Entity | Key | Path | +|---|---|---| +| `Device` | `field.uuid` `id` | `/api/devices/{uuid}` | +| `Country` | `field.string` `code` (a natural key, `@maxLength: 3`) | `/api/countries/{code}` | +| `Level` | `field.int` `rank` | `/api/levels/{rank}` | + +## The contract + +For each entity: list returns the seeded rows; GET by key returns the row; GET of a key no row +holds is `404 {"error": "not_found"}`; `POST` with the key in the body is `201` and the row reads +back; `PATCH` by key changes a non-key field; `DELETE` is `204` and a later GET and a second +DELETE are `404`. + +The `invalid_id` `400` refusal is deliberately not here: it is part of the REST standard work the +Java, Kotlin and Python ports have not landed. + +## Files + +``` +key-types/ +├── README.md +├── meta.json # Device, Country, Level +├── seed.json # two rows each, keyed by table name +└── scenarios/ # -list, -get-by-id, -get-missing, -create-patch-delete +``` + +Generated lane only: what is under test is whether each port's GENERATOR emits routes that parse, +bind and address a uuid, string or int key, which a hand-rolled reference server would satisfy by +construction. diff --git a/fixtures/api-contract-conformance/key-types/meta.json b/fixtures/api-contract-conformance/key-types/meta.json new file mode 100644 index 0000000000..af8ccd1c09 --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/meta.json @@ -0,0 +1,34 @@ +{ + "metadata.root": { + "package": "acme::keys", + "children": [ + { "object.entity": { + "name": "Device", + "children": [ + { "source.rdb": { "@table": "devices" } }, + { "field.uuid": { "name": "id", "@filterable": true, "@sortable": true } }, + { "field.string": { "name": "label", "@required": true, "@maxLength": 100, "@filterable": true, "@sortable": true } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "assigned" } } + ] + }}, + { "object.entity": { + "name": "Country", + "children": [ + { "source.rdb": { "@table": "countries" } }, + { "field.string": { "name": "code", "@required": true, "@maxLength": 3, "@filterable": true, "@sortable": true } }, + { "field.string": { "name": "name", "@required": true, "@maxLength": 100, "@filterable": true, "@sortable": true } }, + { "identity.primary": { "name": "code", "@fields": "code", "@generation": "assigned" } } + ] + }}, + { "object.entity": { + "name": "Level", + "children": [ + { "source.rdb": { "@table": "levels" } }, + { "field.int": { "name": "rank", "@required": true, "@filterable": true, "@sortable": true } }, + { "field.string": { "name": "title", "@required": true, "@maxLength": 100, "@filterable": true, "@sortable": true } }, + { "identity.primary": { "name": "rank", "@fields": "rank", "@generation": "assigned" } } + ] + }} + ] + } +} diff --git a/fixtures/api-contract-conformance/key-types/scenarios/country-create-patch-delete.yaml b/fixtures/api-contract-conformance/key-types/scenarios/country-create-patch-delete.yaml new file mode 100644 index 0000000000..5c7959c118 --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/country-create-patch-delete.yaml @@ -0,0 +1,66 @@ +name: country-create-patch-delete +description: > + Create with a client-supplied key answers 201, the row reads back, PATCH changes it, DELETE answers 204 and a later GET is 404. +requests: + - id: r1 + method: POST + path: /api/countries + body: + code: "NO" + name: "Norway" + expect: + status: 201 + body: + row: + code: "NO" + name: "Norway" + - id: r2 + method: GET + path: /api/countries/NO + expect: + status: 200 + body: + equals: + code: "NO" + name: "Norway" + - id: r3 + method: PATCH + path: /api/countries/NO + body: + name: "Kingdom of Norway" + expect: + status: 200 + body: + row: + code: "NO" + name: "Kingdom of Norway" + - id: r4 + method: GET + path: /api/countries/NO + expect: + status: 200 + body: + equals: + code: "NO" + name: "Kingdom of Norway" + - id: r5 + method: DELETE + path: /api/countries/NO + expect: + status: 204 + body: + empty: true + - id: r6 + method: GET + path: /api/countries/NO + expect: + status: 404 + body: + error: "not_found" + - id: r7 + method: DELETE + path: /api/countries/NO + expect: + status: 404 + body: + error: "not_found" diff --git a/fixtures/api-contract-conformance/key-types/scenarios/country-get-by-id.yaml b/fixtures/api-contract-conformance/key-types/scenarios/country-get-by-id.yaml new file mode 100644 index 0000000000..cdd9206b5e --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/country-get-by-id.yaml @@ -0,0 +1,13 @@ +name: country-get-by-id +description: > + GET by the key returns that row. +requests: + - id: r1 + method: GET + path: /api/countries/NZ + expect: + status: 200 + body: + equals: + code: "NZ" + name: "New Zealand" diff --git a/fixtures/api-contract-conformance/key-types/scenarios/country-get-missing.yaml b/fixtures/api-contract-conformance/key-types/scenarios/country-get-missing.yaml new file mode 100644 index 0000000000..36b7225c25 --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/country-get-missing.yaml @@ -0,0 +1,11 @@ +name: country-get-missing +description: > + GET of a key no row holds answers 404. +requests: + - id: r1 + method: GET + path: /api/countries/NO + expect: + status: 404 + body: + error: "not_found" diff --git a/fixtures/api-contract-conformance/key-types/scenarios/country-list.yaml b/fixtures/api-contract-conformance/key-types/scenarios/country-list.yaml new file mode 100644 index 0000000000..5ec046f55e --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/country-list.yaml @@ -0,0 +1,11 @@ +name: country-list +description: > + List returns both seeded rows. +requests: + - id: r1 + method: GET + path: /api/countries + expect: + status: 200 + body: + length: 2 diff --git a/fixtures/api-contract-conformance/key-types/scenarios/device-create-patch-delete.yaml b/fixtures/api-contract-conformance/key-types/scenarios/device-create-patch-delete.yaml new file mode 100644 index 0000000000..0adb0a0754 --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/device-create-patch-delete.yaml @@ -0,0 +1,66 @@ +name: device-create-patch-delete +description: > + Create with a client-supplied key answers 201, the row reads back, PATCH changes it, DELETE answers 204 and a later GET is 404. +requests: + - id: r1 + method: POST + path: /api/devices + body: + id: "33333333-3333-4333-8333-333333333333" + label: "Sensor C" + expect: + status: 201 + body: + row: + id: "33333333-3333-4333-8333-333333333333" + label: "Sensor C" + - id: r2 + method: GET + path: /api/devices/33333333-3333-4333-8333-333333333333 + expect: + status: 200 + body: + equals: + id: "33333333-3333-4333-8333-333333333333" + label: "Sensor C" + - id: r3 + method: PATCH + path: /api/devices/33333333-3333-4333-8333-333333333333 + body: + label: "Sensor C renamed" + expect: + status: 200 + body: + row: + id: "33333333-3333-4333-8333-333333333333" + label: "Sensor C renamed" + - id: r4 + method: GET + path: /api/devices/33333333-3333-4333-8333-333333333333 + expect: + status: 200 + body: + equals: + id: "33333333-3333-4333-8333-333333333333" + label: "Sensor C renamed" + - id: r5 + method: DELETE + path: /api/devices/33333333-3333-4333-8333-333333333333 + expect: + status: 204 + body: + empty: true + - id: r6 + method: GET + path: /api/devices/33333333-3333-4333-8333-333333333333 + expect: + status: 404 + body: + error: "not_found" + - id: r7 + method: DELETE + path: /api/devices/33333333-3333-4333-8333-333333333333 + expect: + status: 404 + body: + error: "not_found" diff --git a/fixtures/api-contract-conformance/key-types/scenarios/device-get-by-id.yaml b/fixtures/api-contract-conformance/key-types/scenarios/device-get-by-id.yaml new file mode 100644 index 0000000000..9c787ca13c --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/device-get-by-id.yaml @@ -0,0 +1,13 @@ +name: device-get-by-id +description: > + GET by the key returns that row. +requests: + - id: r1 + method: GET + path: /api/devices/11111111-1111-4111-8111-111111111111 + expect: + status: 200 + body: + equals: + id: "11111111-1111-4111-8111-111111111111" + label: "Sensor A" diff --git a/fixtures/api-contract-conformance/key-types/scenarios/device-get-missing.yaml b/fixtures/api-contract-conformance/key-types/scenarios/device-get-missing.yaml new file mode 100644 index 0000000000..5ded51cb1f --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/device-get-missing.yaml @@ -0,0 +1,11 @@ +name: device-get-missing +description: > + GET of a key no row holds answers 404. +requests: + - id: r1 + method: GET + path: /api/devices/33333333-3333-4333-8333-333333333333 + expect: + status: 404 + body: + error: "not_found" diff --git a/fixtures/api-contract-conformance/key-types/scenarios/device-list.yaml b/fixtures/api-contract-conformance/key-types/scenarios/device-list.yaml new file mode 100644 index 0000000000..5eb5dd2789 --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/device-list.yaml @@ -0,0 +1,11 @@ +name: device-list +description: > + List returns both seeded rows. +requests: + - id: r1 + method: GET + path: /api/devices + expect: + status: 200 + body: + length: 2 diff --git a/fixtures/api-contract-conformance/key-types/scenarios/level-create-patch-delete.yaml b/fixtures/api-contract-conformance/key-types/scenarios/level-create-patch-delete.yaml new file mode 100644 index 0000000000..403177248f --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/level-create-patch-delete.yaml @@ -0,0 +1,66 @@ +name: level-create-patch-delete +description: > + Create with a client-supplied key answers 201, the row reads back, PATCH changes it, DELETE answers 204 and a later GET is 404. +requests: + - id: r1 + method: POST + path: /api/levels + body: + rank: 3 + title: "Gold" + expect: + status: 201 + body: + row: + rank: 3 + title: "Gold" + - id: r2 + method: GET + path: /api/levels/3 + expect: + status: 200 + body: + equals: + rank: 3 + title: "Gold" + - id: r3 + method: PATCH + path: /api/levels/3 + body: + title: "Gold plus" + expect: + status: 200 + body: + row: + rank: 3 + title: "Gold plus" + - id: r4 + method: GET + path: /api/levels/3 + expect: + status: 200 + body: + equals: + rank: 3 + title: "Gold plus" + - id: r5 + method: DELETE + path: /api/levels/3 + expect: + status: 204 + body: + empty: true + - id: r6 + method: GET + path: /api/levels/3 + expect: + status: 404 + body: + error: "not_found" + - id: r7 + method: DELETE + path: /api/levels/3 + expect: + status: 404 + body: + error: "not_found" diff --git a/fixtures/api-contract-conformance/key-types/scenarios/level-get-by-id.yaml b/fixtures/api-contract-conformance/key-types/scenarios/level-get-by-id.yaml new file mode 100644 index 0000000000..95c6793c27 --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/level-get-by-id.yaml @@ -0,0 +1,13 @@ +name: level-get-by-id +description: > + GET by the key returns that row. +requests: + - id: r1 + method: GET + path: /api/levels/1 + expect: + status: 200 + body: + equals: + rank: 1 + title: "Bronze" diff --git a/fixtures/api-contract-conformance/key-types/scenarios/level-get-missing.yaml b/fixtures/api-contract-conformance/key-types/scenarios/level-get-missing.yaml new file mode 100644 index 0000000000..4a3a9122ef --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/level-get-missing.yaml @@ -0,0 +1,11 @@ +name: level-get-missing +description: > + GET of a key no row holds answers 404. +requests: + - id: r1 + method: GET + path: /api/levels/3 + expect: + status: 404 + body: + error: "not_found" diff --git a/fixtures/api-contract-conformance/key-types/scenarios/level-list.yaml b/fixtures/api-contract-conformance/key-types/scenarios/level-list.yaml new file mode 100644 index 0000000000..84f9ef4dad --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/scenarios/level-list.yaml @@ -0,0 +1,11 @@ +name: level-list +description: > + List returns both seeded rows. +requests: + - id: r1 + method: GET + path: /api/levels + expect: + status: 200 + body: + length: 2 diff --git a/fixtures/api-contract-conformance/key-types/seed.json b/fixtures/api-contract-conformance/key-types/seed.json new file mode 100644 index 0000000000..93096c2a06 --- /dev/null +++ b/fixtures/api-contract-conformance/key-types/seed.json @@ -0,0 +1,14 @@ +{ + "devices": [ + { "id": "11111111-1111-4111-8111-111111111111", "label": "Sensor A" }, + { "id": "22222222-2222-4222-8222-222222222222", "label": "Sensor B" } + ], + "countries": [ + { "code": "NZ", "name": "New Zealand" }, + { "code": "SE", "name": "Sweden" } + ], + "levels": [ + { "rank": 1, "title": "Bronze" }, + { "rank": 2, "title": "Silver" } + ] +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs index a3c34f379d..087bcb4993 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs @@ -99,6 +99,27 @@ public void DbContext_exposes_a_dbset_per_entity() Assert.Contains("public DbSet Subscribers { get; set; } = default!;", file.Content); } + [Fact] + public void Routes_for_a_uuid_key_spell_the_Guid_in_full() + { + // The routes file carries no `using System;`, so a bare `Guid` would not compile. + const string model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Device", "children": [ + { "source.rdb": { "@table": "devices" } }, + { "field.uuid": { "name": "id" } }, + { "field.string": { "name": "label", "@required": true } }, + { "identity.primary": { "@fields": "id", "@generation": "assigned" } } + ]}} + ]}} + """; + var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "uuid.json")]); + Assert.Empty(r.Errors); + var src = Assert.Single(new RoutesGenerator().Generate(Ctx(r.Root))).Content; + Assert.Contains("RouteErrors.TryReadId(http, out var id)", src); + Assert.DoesNotContain("TryReadId", src); + } + [Fact] public void Routes_generator_emits_crud_endpoints() { diff --git a/server/csharp/MetaObjects.Codegen.Tests/ValueObjectReuseTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ValueObjectReuseTests.cs index 1628cf86ff..1b417dbe84 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ValueObjectReuseTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ValueObjectReuseTests.cs @@ -105,18 +105,6 @@ public void Two_value_objects_sharing_a_short_name_keep_it_in_their_own_package_ Assert.Equal("Note", ValueObjectNames.TypeName(root.Objects().First(o => o.ResolutionKey() == "acme::alpha::Note"), root)); } - [Fact] -#pragma warning disable CS0618 - public void The_obsolete_name_map_is_the_identity_map_of_value_objects() - { - var root = Load(Alpha, Beta); - var names = ValueObjectNames.Names(root); - - Assert.Equal("Note", names["acme::alpha::Note"]); - Assert.Equal("Note", names["acme::beta::Note"]); - } -#pragma warning restore CS0618 - [Fact] public void A_unique_short_name_stays_bare() { diff --git a/server/csharp/MetaObjects.Codegen/Docs/XmlDocBuilder.cs b/server/csharp/MetaObjects.Codegen/Docs/XmlDocBuilder.cs index c87b8a81d6..f0f8a6011a 100644 --- a/server/csharp/MetaObjects.Codegen/Docs/XmlDocBuilder.cs +++ b/server/csharp/MetaObjects.Codegen/Docs/XmlDocBuilder.cs @@ -82,32 +82,6 @@ public static (string XmlDoc, string? ObsoleteAttribute) Render(MetaData node) return (sb.ToString().TrimEnd(), obsolete); } - /// Prefix every non-empty line of with the given indent. - public static string Indent(string xmlDoc, string indent) - { - if (string.IsNullOrEmpty(xmlDoc)) return xmlDoc; - return string.Join("\n", xmlDoc.Split('\n').Select(l => l.Length == 0 ? l : indent + l)); - } - - /// - /// Render 's doc block + [Obsolete] (if any) and append both - /// to , each line prefixed by . No-op - /// when neither attribute is present. Convenience over the raw - /// tuple for "emit at the current position in a class body" callers. - /// - public static void AppendTo(StringBuilder sb, MetaData node, string indent = "") - { - (string doc, string? obsolete) = Render(node); - if (!string.IsNullOrEmpty(doc)) - { - sb.AppendLine(indent.Length == 0 ? doc : Indent(doc, indent)); - } - if (obsolete is not null) - { - sb.Append(indent).AppendLine(obsolete); - } - } - /// /// Write 's doc block and [Obsolete] (if any) on the writer, one /// line each, at the writer's current indent. Writes nothing when neither attribute is present. @@ -122,24 +96,6 @@ public static void WriteTo(CsWriter w, MetaData node) if (obsolete is not null) w.Line(obsolete); } - /// - /// Return with 's doc block + - /// [Obsolete] prepended (each line prefixed by ). Returns - /// unchanged when no doc attrs are set. Convenience for - /// "stitch the doc above a pre-built member string" callers. - /// - public static string Prepend(string member, MetaData node, string indent) - { - (string doc, string? obsolete) = Render(node); - if (string.IsNullOrEmpty(doc) && obsolete is null) return member; - - var sb = new StringBuilder(); - if (!string.IsNullOrEmpty(doc)) sb.Append(Indent(doc, indent)).Append('\n'); - if (obsolete is not null) sb.Append(indent).Append(obsolete).Append('\n'); - sb.Append(member); - return sb.ToString(); - } - private static (string Summary, string? Remainder) SplitSummary(string s) { int idx = s.IndexOf('\n'); diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index cf797a8126..a978b322d7 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -265,7 +265,7 @@ protected virtual StandardRoutesPlan PlanStandardRoutes(MetaObject entity, GenCo var pkField = entity.Fields().FirstOrDefault(f => f.Name == pkFields[0]); if (pkField is not null) { - pkType = CSharpNaming.ScalarFor(pkField.SubType); + pkType = KeyClrType(pkField.SubType); pkProp = CSharpNaming.PropertyName(pkField, ctx.Config); } } @@ -700,7 +700,7 @@ protected virtual TphRoutesPlan PlanTphRoutes(MetaObject baseEntity, TphPlan tph "emitting polymorphic collection GET only."); } var pkField = pkFields.Count == 1 ? baseEntity.Fields().FirstOrDefault(f => f.Name == pkFields[0]) : null; - var pkType = pkField is not null ? CSharpNaming.ScalarFor(pkField.SubType) : null; + var pkType = pkField is not null ? KeyClrType(pkField.SubType) : null; var pkProp = pkField is not null ? CSharpNaming.PropertyName(pkField, ctx.Config) : null; bool hasItem = pkType is not null; @@ -1180,6 +1180,14 @@ protected virtual void WriteUnknownFieldsCheck(CsWriter w, MetaRoot root, string // The first line of an item handler: the `{id}` route value read as the key's type, or 400 invalid_id // (RouteErrors). The handler binds no typed id itself, because ASP.NET Core's binding answers an // unparsable one with an empty 400. + // The CLR type a route names for the key. The routes file carries no `using System;`, so a + // Guid key is spelled out in full (a bare `Guid` fails to compile in the file). + private static string KeyClrType(string subType) + { + var clr = CSharpNaming.ScalarFor(subType); + return clr == "Guid" ? "global::System.Guid" : clr!; + } + protected virtual void WriteReadId(CsWriter w, string pkType) => w.Line($"if (!RouteErrors.TryReadId<{pkType}>(http, out var id)) return RouteErrors.InvalidId();"); diff --git a/server/csharp/MetaObjects.Codegen/Templates/metamodel/index.md.mustache b/server/csharp/MetaObjects.Codegen/Templates/metamodel/index.md.mustache index fa7feae9bc..db0bf966ff 100644 --- a/server/csharp/MetaObjects.Codegen/Templates/metamodel/index.md.mustache +++ b/server/csharp/MetaObjects.Codegen/Templates/metamodel/index.md.mustache @@ -6,7 +6,7 @@ This page documents the **metamodel itself**: the type, subtype and attribute vocabulary the loader accepts, generated from the strict registry. Your own -entities are documented by the `docs` generator (`docsFile()`). +entities are documented by the model explorer (the `docs-site` generator). Each row links to its type page, which has the full attribute table, the allowed children and the cardinality of that subtype. Documentation attributes diff --git a/server/csharp/MetaObjects.Codegen/ValueObjectNames.cs b/server/csharp/MetaObjects.Codegen/ValueObjectNames.cs index c5cc1ff7a6..3e1cbfbf7c 100644 --- a/server/csharp/MetaObjects.Codegen/ValueObjectNames.cs +++ b/server/csharp/MetaObjects.Codegen/ValueObjectNames.cs @@ -35,16 +35,6 @@ public static bool IsValueShape(MetaData obj) => /// public static string TypeName(MetaData obj, MetaData root) => CSharpNaming.Pascal(obj.Name); - /// - /// The value-object name map: ResolutionKey() → emitted C# name. A value object is never - /// renamed, so this is the identity map (resolution key → PascalCase name). - /// - [Obsolete("A value object is never renamed; use TypeName(obj, root). Removed after one release.")] - public static IReadOnlyDictionary Names(MetaData root) => - root.Children() - .Where(IsValueShape) - .ToDictionary(o => o.ResolutionKey(), o => CSharpNaming.Pascal(o.Name), StringComparer.Ordinal); - /// The namespace 's type is emitted into (package binding). public static string Namespace(MetaData obj, GenConfig config) => PackageBindingResolver.Resolve( diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs index 45a72f0d17..1bfb9a5fa1 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs @@ -129,6 +129,12 @@ internal static class ApiContractCorpusPaths public static readonly string EnumDefaultSeedFile = Path.Combine(EnumDefaultDir, "seed.json"); public static readonly string EnumDefaultMetaJson = Path.Combine(EnumDefaultDir, "meta.json"); + // key-types subcorpus (uuid, natural string and int primary keys), generated lane only. + public static readonly string KeyTypesDir = Path.Combine(Corpus, "key-types"); + public static readonly string KeyTypesScenariosDir = Path.Combine(KeyTypesDir, "scenarios"); + public static readonly string KeyTypesSeedFile = Path.Combine(KeyTypesDir, "seed.json"); + public static readonly string KeyTypesMetaJson = Path.Combine(KeyTypesDir, "meta.json"); + // list-query subcorpus (the REST standard's list handling over a 60-row Part seed), generated lane only. public static readonly string ListQueryDir = Path.Combine(Corpus, "list-query"); public static readonly string ListQueryScenariosDir = Path.Combine(ListQueryDir, "scenarios"); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractKeyTypesConformanceTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractKeyTypesConformanceTest.cs new file mode 100644 index 0000000000..a83fa53ecb --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractKeyTypesConformanceTest.cs @@ -0,0 +1,81 @@ +// ApiContractKeyTypesConformanceTest — the C# key-types api-contract lane. +// +// Drives the fixtures/api-contract-conformance/key-types/ scenarios over HTTP against the +// GENERATED Device, Country and Level routes booted unmodified on Kestrel against a Postgres testcontainer. +// Proves generated CRUD works for a uuid, a natural string and an int primary key. +// Generated lane only. + +using System.Text.Json; +using System.Text.Json.Nodes; +using MetaObjects.IntegrationTests.Runner; +using Xunit; + +namespace MetaObjects.IntegrationTests.Api; + +public sealed class ApiContractKeyTypesConformanceTest +{ + [Theory] + [MemberData(nameof(Scenarios))] + public async Task Api_contract_key_types_generated(string scenarioPath) + { + var scenario = ApiContractScenarioLoader.LoadScenario(scenarioPath); + await using var pg = await PostgresContainer.StartAsync(); + await using var server = await KeyTypesGeneratedServerFactory.StartAsync(pg); + await server.ApplySeedAsync(); + await RunAsync(scenario, server.BaseUrl); + } + + private static async Task RunAsync(ApiScenario scenario, string baseUrl) + { + using var client = new HttpClient { BaseAddress = new Uri(baseUrl) }; + foreach (var req in scenario.Requests) + { + var request = new HttpRequestMessage(new HttpMethod(req.Method), ApiContractWire.VerbatimUri(client, req.Path)); + if (req.Body is not null) + { + string json = JsonSerializer.Serialize(req.Body, JsonOpts); + request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); + } + var response = await client.SendAsync(request); + string bodyText = await response.Content.ReadAsStringAsync(); + object? parsed = string.IsNullOrEmpty(bodyText) ? null : ToObject(JsonNode.Parse(bodyText)); + ApiContractAssertions.AssertResponse(scenario.Name, req, (int)response.StatusCode, parsed); + } + } + + public static IEnumerable Scenarios() => + Directory.EnumerateFiles(ApiContractCorpusPaths.KeyTypesScenariosDir, "*.yaml", SearchOption.TopDirectoryOnly) + .OrderBy(p => p, StringComparer.Ordinal) + .Select(p => new object[] { p }); + + private static readonly JsonSerializerOptions JsonOpts = new() + { + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.Never, + }; + + private static object? ToObject(JsonNode? node) + { + if (node is null) return null; + if (node is JsonObject obj) + { + var d = new Dictionary(StringComparer.Ordinal); + foreach (var kvp in obj) d[kvp.Key] = ToObject(kvp.Value); + return d; + } + if (node is JsonArray arr) + { + var l = new List(arr.Count); + foreach (var item in arr) l.Add(ToObject(item)); + return l; + } + if (node is JsonValue jv) + { + if (jv.TryGetValue(out var b)) return b; + if (jv.TryGetValue(out var lv)) return lv; + if (jv.TryGetValue(out var dv)) return dv; // exact: never a double (ADR-0019 Amendment 1) + if (jv.TryGetValue(out var sv)) return sv; + return jv.ToString(); + } + return null; + } +} diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/KeyTypesFixture.cs b/server/csharp/MetaObjects.IntegrationTests/Api/KeyTypesFixture.cs new file mode 100644 index 0000000000..bfe9b8cf21 --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/Api/KeyTypesFixture.cs @@ -0,0 +1,58 @@ +// KeyTypesFixture — schema + seed for the key-types api-contract GENERATED lane. +using System.Text.Json.Nodes; +using Npgsql; + +namespace MetaObjects.IntegrationTests.Api; + +internal static class KeyTypesFixture +{ + public const string SchemaDdl = """ + CREATE TABLE "devices" ( + "id" UUID NOT NULL, + "label" VARCHAR(100) NOT NULL, + CONSTRAINT "devices_pkey" PRIMARY KEY ("id") + ); + CREATE TABLE "countries" ( + "code" VARCHAR(3) NOT NULL, + "name" VARCHAR(100) NOT NULL, + CONSTRAINT "countries_pkey" PRIMARY KEY ("code") + ); + CREATE TABLE "levels" ( + "rank" INTEGER NOT NULL, + "title" VARCHAR(100) NOT NULL, + CONSTRAINT "levels_pkey" PRIMARY KEY ("rank") + ); + """; + + public static async Task ProvisionSchemaAsync(string connString) + { + await using var c = new NpgsqlConnection(connString); + await c.OpenAsync(); + await using var cmd = c.CreateCommand(); + cmd.CommandText = SchemaDdl; + await cmd.ExecuteNonQueryAsync(); + } + + public static async Task ApplySeedAsync(string connString, string seedPath) + { + var root = JsonNode.Parse(File.ReadAllText(seedPath)) as JsonObject + ?? throw new InvalidOperationException($"{seedPath}: top-level must be an object"); + await using var c = new NpgsqlConnection(connString); + await c.OpenAsync(); + foreach (var row in root["devices"]!.AsArray()) + await InsertAsync(c, "devices", ("id", Guid.Parse(row!["id"]!.GetValue())), ("label", row["label"]!.GetValue())); + foreach (var row in root["countries"]!.AsArray()) + await InsertAsync(c, "countries", ("code", row!["code"]!.GetValue()), ("name", row["name"]!.GetValue())); + foreach (var row in root["levels"]!.AsArray()) + await InsertAsync(c, "levels", ("rank", row!["rank"]!.GetValue()), ("title", row["title"]!.GetValue())); + } + + private static async Task InsertAsync(NpgsqlConnection c, string table, params (string Col, object Val)[] cols) + { + await using var ins = c.CreateCommand(); + ins.CommandText = $"INSERT INTO \"{table}\" (" + string.Join(", ", cols.Select(x => "\"" + x.Col + "\"")) + + ") VALUES (" + string.Join(", ", cols.Select((_, i) => "@p" + i)) + ")"; + for (int i = 0; i < cols.Length; i++) ins.Parameters.AddWithValue("@p" + i, cols[i].Val); + await ins.ExecuteNonQueryAsync(); + } +} diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/KeyTypesGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/KeyTypesGeneratedServerFactory.cs new file mode 100644 index 0000000000..bac0bd5611 --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/Api/KeyTypesGeneratedServerFactory.cs @@ -0,0 +1,183 @@ +// KeyTypesGeneratedServerFactory — the C# GENERATED-server lane for the key-types +// corpus. Runs the real Codegen generators (Entity + DbContext + FilterAllowlist + Routes) on the +// Account model, Roslyn-compiles the output in memory and hosts it on Kestrel against Postgres. + +using MetaObjects.Meta; +using System.Reflection; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.IntegrationTests.Runner; +using MetaObjects.Loader; + +namespace MetaObjects.IntegrationTests.Api; + +internal sealed class KeyTypesGeneratedServerFactory : IAsyncDisposable +{ + private const string GeneratedNamespace = "MetaObjects.ApiContract.KeyTypesGenerated"; + + private readonly PostgresContainer _pg; + private readonly WebApplication _app; + + public string BaseUrl { get; } + + private KeyTypesGeneratedServerFactory(PostgresContainer pg, WebApplication app, string baseUrl) + { + _pg = pg; + _app = app; + BaseUrl = baseUrl; + } + + public static async Task StartAsync(PostgresContainer pg) + { + await KeyTypesFixture.ProvisionSchemaAsync(pg.ConnectionString); + + var (assembly, entityNames) = CompileGeneratedServer(); + var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + ?? throw new InvalidOperationException("generated AppDbContext type not found"); + + var builder = WebApplication.CreateBuilder(); + LoopbackKestrel.BindAnyPort(builder); + builder.Logging.ClearProviders(); + // Wire enums are strings: the host registers the converter, as the TPH and report lanes do. + builder.Services.ConfigureHttpJsonOptions(o => + o.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter())); + RegisterGeneratedDbContext(builder.Services, dbContextType, pg.ConnectionString); + + var app = builder.Build(); + + // Mount each generated MapRoutes(app, "/api"). + foreach (var entity in entityNames) + { + var routesType = assembly.GetType($"{GeneratedNamespace}.{entity}Routes"); + if (routesType is null) continue; + var mapMethod = routesType.GetMethod($"Map{entity}Routes", BindingFlags.Public | BindingFlags.Static); + mapMethod?.Invoke(null, new object[] { app, "/api" }); + } + + await app.StartAsync(); + return new KeyTypesGeneratedServerFactory(pg, app, LoopbackKestrel.BoundUrl(app)); + } + + public async Task ApplySeedAsync() => + await KeyTypesFixture.ApplySeedAsync(_pg.ConnectionString, ApiContractCorpusPaths.KeyTypesSeedFile); + + public async ValueTask DisposeAsync() + { + try { await _app.StopAsync(); } catch { /* ignored */ } + try { await _app.DisposeAsync(); } catch { /* ignored */ } + } + + private static (Assembly Assembly, IReadOnlyList EntityNames) CompileGeneratedServer() + { + var loadResult = new MetaDataLoader().Load([new FileSource(ApiContractCorpusPaths.KeyTypesMetaJson)]); + // ADR-0058 — the corpus's committed naming rule, not a hardcoded default. + loadResult.Root.PhysicalNaming = ApiContractCorpusPaths.Naming; + loadResult.Root.WireFormat = ApiContractCorpusPaths.Wire; + if (loadResult.Errors.Count != 0) + throw new InvalidOperationException( + "key-types corpus metadata failed to load: " + + string.Join("; ", loadResult.Errors.Select(e => e.ToString()))); + + var entityNames = loadResult.Root.Objects() + .Where(o => o.IsEntity()) + .Select(o => CSharpNaming.Pascal(o.Name)) + .ToList(); + + var ctx = new GenContext + { + Entities = loadResult.Root.Objects(), + Root = loadResult.Root, + Config = new GenConfig + { + OutDir = "/unused", + Namespace = GeneratedNamespace, + ColumnNamingStrategy = ApiContractCorpusPaths.Naming.Columns, + EmitAbstractShapes = false, + // GenConfig.IncludeNames defaults to false (§A6 task 4); without it + // here the entity/DbContext output below never references the + // Names constants, and the .Concat(new NamesGenerator()...) + // a few lines down is dead input the compile never depends on. This + // is the only lane that proves an Names.NAME reference + // actually RESOLVES against a real EF Core compile. + IncludeNames = true, + }, + }; + + // §A6 (task 4) -- the entity/DbContext output now references the names artifact. + var files = new EntityGenerator().Generate(ctx) + .Concat(new DbContextGenerator().Generate(ctx)) + .Concat(new FilterAllowlistGenerator().Generate(ctx)) + .Concat(new RoutesGenerator().Generate(ctx)) + .Concat(new NamesGenerator().Generate(ctx)) + .ToList(); + + var trees = files + .Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12))) + .ToArray(); + + var refs = BuildReferenceSet(); + var comp = CSharpCompilation.Create( + "apicontract_enumdefault_generated_" + Guid.NewGuid().ToString("N"), + trees, refs, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + + using var ms = new MemoryStream(); + var emit = comp.Emit(ms); + if (!emit.Success) + { + var errors = emit.Diagnostics + .Where(d => d.Severity == DiagnosticSeverity.Error) + .Select(d => $"{d.Id}: {d.GetMessage()}") + .ToList(); + throw new InvalidOperationException( + "generated key-types server failed to compile:\n " + string.Join("\n ", errors)); + } + + ms.Seek(0, SeekOrigin.Begin); + return (Assembly.Load(ms.ToArray()), entityNames); + } + + private static List BuildReferenceSet() + { + var byFileName = new Dictionary(StringComparer.OrdinalIgnoreCase); + var tpa = (string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? ""; + foreach (var path in tpa.Split(Path.PathSeparator)) + if (path.Length > 0 && path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) + byFileName[Path.GetFileName(path)] = path; + + var aspNetDir = Path.GetDirectoryName(typeof(WebApplication).Assembly.Location); + if (aspNetDir is not null && Directory.Exists(aspNetDir)) + foreach (var dll in Directory.EnumerateFiles(aspNetDir, "*.dll")) + byFileName[Path.GetFileName(dll)] = dll; + + return byFileName.Values + .Select(loc => (MetadataReference)MetadataReference.CreateFromFile(loc)) + .ToList(); + } + + private static void RegisterGeneratedDbContext( + IServiceCollection services, Type dbContextType, string connString) + { + var addDbContext = typeof(EntityFrameworkServiceCollectionExtensions) + .GetMethods(BindingFlags.Public | BindingFlags.Static) + .First(m => m.Name == "AddDbContext" + && m.IsGenericMethodDefinition + && m.GetGenericArguments().Length == 1 + && m.GetParameters().Length == 4) + .MakeGenericMethod(dbContextType); + + Action configure = opts => opts.UseNpgsql(connString); + addDbContext.Invoke(null, new object?[] + { + services, configure, ServiceLifetime.Scoped, ServiceLifetime.Scoped, + }); + } +} diff --git a/server/csharp/MetaObjects/SpecMetamodel/object.json b/server/csharp/MetaObjects/SpecMetamodel/object.json index ad288e6015..c6b9cf74f8 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/object.json +++ b/server/csharp/MetaObjects/SpecMetamodel/object.json @@ -12,7 +12,7 @@ { "type": "layout", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "source", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "index", "subType": "*", "name": "*", "min": 0, "max": null }, - { "type": "attr", "subType": "string", "name": "object", "min": 0, "max": 1, "implementedIn": ["java"], "description": "The native class an object binds to (ADR-0001), in place of its default runtime class: on the JVM, a fully-qualified class name. Cross-port vocabulary only Java implements so far; every port loads and type-checks it, and the others do not act on it yet." }, + { "type": "attr", "subType": "string", "name": "object", "min": 0, "max": 1, "ports": ["java", "kotlin"], "description": "JVM-only (ADR-0001): the native class an object binds to, in place of its default runtime class, a fully-qualified class name. Every port loads and type-checks it; only Java and Kotlin (the JVM runtime) act on it." }, { "type": "attr", "subType": "string", "name": "objectAdapter", "min": 0, "max": 1, "ports": ["java", "kotlin"], "description": "JVM-only (ADR-0005): the fully-qualified name of an ObjectAdapter that takes over value access for this object's instances. Every port loads and type-checks it; only Java and Kotlin act on it." } ] }, diff --git a/server/csharp/MetaObjects/SpecMetamodel/view-expressions.json b/server/csharp/MetaObjects/SpecMetamodel/view-expressions.json index 4db3c0ca57..5378469a67 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/view-expressions.json +++ b/server/csharp/MetaObjects/SpecMetamodel/view-expressions.json @@ -4,7 +4,7 @@ { "type": "origin", "subType": "function", - "implementedIn": ["typescript", "csharp"], + "implementedIn": ["csharp", "python", "typescript"], "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ @@ -21,10 +21,10 @@ "type": "object", "subType": "projection", "children": [ - { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, - { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, - { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, - { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." } + { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "implementedIn": ["csharp", "python", "typescript"], "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, + { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "implementedIn": ["csharp", "python", "typescript"], "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, + { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "implementedIn": ["csharp", "python", "typescript"], "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, + { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "implementedIn": ["csharp", "python", "typescript"], "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." } ] } ] diff --git a/server/csharp/MetaObjects/SpecMetamodel/view.json b/server/csharp/MetaObjects/SpecMetamodel/view.json index d839d9c431..e08d497583 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/view.json +++ b/server/csharp/MetaObjects/SpecMetamodel/view.json @@ -9,73 +9,73 @@ { "type": "view", "subType": "text", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Single-line text input/display." }, { "type": "view", "subType": "textarea", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Multi-line text area." }, { "type": "view", "subType": "date", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Date picker / date display." }, { "type": "view", "subType": "month", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Month picker / month display." }, { "type": "view", "subType": "hotlink", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Renders the value as a clickable link." }, { "type": "view", "subType": "dropdown", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Single-select dropdown control." }, { "type": "view", "subType": "radio", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Radio-button selection control." }, { "type": "view", "subType": "checkbox", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Checkbox selection control." }, { "type": "view", "subType": "number", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Numeric input control." }, { "type": "view", "subType": "password", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Masked input for sensitive values." }, { "type": "view", "subType": "hidden", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Not rendered; carried but not shown." }, { "type": "view", "subType": "web", - "implementedIn": ["typescript"], + "ports": ["typescript"], "description": "Abstract base for web-rendered views." }, { @@ -83,6 +83,6 @@ "subType": "currency", "description": "Currency display formatting (locale-aware via @locale)." }, - { "type": "view", "subType": "image", "implementedIn": ["typescript"], "description": "Image upload/display control; the field stores an opaque storage key (field.string)." } + { "type": "view", "subType": "image", "ports": ["typescript"], "description": "Image upload/display control; the field stores an opaque storage key (field.string)." } ] } diff --git a/server/rust/metaobjects-codegen/tests/api_contract.rs b/server/rust/metaobjects-codegen/tests/api_contract.rs index 0516e2ba52..c7912212a0 100644 --- a/server/rust/metaobjects-codegen/tests/api_contract.rs +++ b/server/rust/metaobjects-codegen/tests/api_contract.rs @@ -4,8 +4,8 @@ //! every scenario), and every scenario's requests are sent to it and checked against what the //! scenario expects. //! -//! The Rust lane runs `core` (the root corpus), `write-through`, `secret-fields`, `list-query` -//! and `rules` with its settings variants. The rest are on [`LEDGER`]: what each needs is a +//! The Rust lane runs `core` (the root corpus), `write-through`, `secret-fields`, `list-query`, +//! `key-types` and `rules` with its settings variants. The rest are on [`LEDGER`]: what each needs is a //! capability the Rust port does not have yet, and `docs/ports/rust.md` lists the same set. mod common; @@ -143,6 +143,32 @@ pub fn app(pool: sqlx::SqlitePool) -> axum::Router { } "#; +const KEY_TYPES_SCHEMA: &str = r#"CREATE TABLE "devices" ( + "id" TEXT PRIMARY KEY NOT NULL, + "label" TEXT NOT NULL +); +CREATE TABLE "countries" ( + "code" TEXT PRIMARY KEY NOT NULL, + "name" TEXT NOT NULL +); +CREATE TABLE "levels" ( + "rank" INTEGER PRIMARY KEY NOT NULL, + "title" TEXT NOT NULL +); +"#; + +const KEY_TYPES_MODULE: &str = r#" +pub const TABLES: &[(&str, &meta_store::Table)] = &[ + ("devices", &acme_keys_store::device::TABLE), + ("countries", &acme_keys_store::country::TABLE), + ("levels", &acme_keys_store::level::TABLE), +]; + +pub fn app(pool: sqlx::SqlitePool) -> axum::Router { + acme_keys_http::router(acme_keys_service::KeysService::<_, ()>::new(pool), ()) +} +"#; + const RULES_SCHEMA: &str = r#"CREATE TABLE "purchase_requests" ( "id" INTEGER PRIMARY KEY NOT NULL, "title" TEXT NOT NULL, @@ -252,6 +278,15 @@ fn corpora() -> Vec { "acme_stockroom_http", ], }, + Corpus { + tag: "key-types", + dir: "key-types", + config: Some(ROOT_CONFIG), + scenarios: "key-types/scenarios", + schema: KEY_TYPES_SCHEMA, + module: KEY_TYPES_MODULE, + crates: &["acme_keys_store", "acme_keys_service", "acme_keys_http"], + }, rules("rules", None, "rules/scenarios"), rules( "rules-commands-all", diff --git a/server/typescript/packages/integration-tests/src/api-contract-key-types-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-key-types-generated-server.ts new file mode 100644 index 0000000000..0f3296afc6 --- /dev/null +++ b/server/typescript/packages/integration-tests/src/api-contract-key-types-generated-server.ts @@ -0,0 +1,116 @@ +// api-contract-key-types-generated-server.ts — boots the GENERATED Ticket routes (the +// deployed artifact) over HTTP and drives them against the key-types corpus. +// +// Same shape as api-contract-secret-fields-generated-server.ts: runGen over the corpus meta into +// a temp dir, provision the table the emitted Drizzle binding reads, mount the EMITTED routes. + +import type { FastifyInstance } from "fastify"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; +import { indexEmitted, type OutputLayout } from "./output-layout.ts"; +import { entityFile, routesFile } from "@metaobjectsdev/codegen-ts/generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; +import type pg from "pg"; +import { executeSql } from "./postgres-sql.ts"; +import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; +import { loadMetadataFile } from "./load-metadata.ts"; + +export interface KeyTypesSeed { + devices: Array<{ id: string; label: string }>; + countries: Array<{ code: string; name: string }>; + levels: Array<{ rank: number; title: string }>; +} + +export interface GeneratedKeyTypesServerHandle { + baseUrl: string; + applySeed(seed: KeyTypesSeed): Promise; + close(): Promise; +} + +export async function startGeneratedKeyTypesServer( + connectionUri: string, + metaPath: string, + outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", +): Promise { + const here = dirname(fileURLToPath(import.meta.url)); + const genTmpRoot = join(here, "..", ".gen-tmp"); + mkdirSync(genTmpRoot, { recursive: true }); + const tmp = mkdtempSync(join(genTmpRoot, "api-contract-key-types-")); + + const root = await loadMetadataFile(metaPath); + root.physicalNaming = DEFAULT_PHYSICAL_NAMING; + const lr = await runGen({ + config: defineConfig({ + outDir: tmp, + extStyle: "none", + outputLayout, + dbImport: "./db", + dialect: "postgres", + apiPrefix: "/api", + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), + }), + metadata: root, + }); + const emitted = indexEmitted(tmp, lr.files, outputLayout); + if (lr.warnings.length > 0) { + throw new Error(`codegen produced warnings: ${lr.warnings.join("; ")}`); + } + + const bigintTypesImport = pathToFileURL(join(here, "pg-bigint-number-types.ts")).href; + writeFileSync( + join(tmp, "db.ts"), + ` +import { drizzle } from "drizzle-orm/node-postgres"; +import pg from "pg"; +import { bigintAsNumberTypes } from ${JSON.stringify(bigintTypesImport)}; +export const pool = new pg.Pool({ connectionString: ${JSON.stringify(connectionUri)}, types: bigintAsNumberTypes }); +export const db = drizzle(pool); +`, + "utf8", + ); + + await executeSql( + connectionUri, + `CREATE TABLE IF NOT EXISTS "devices" ("id" uuid PRIMARY KEY, "label" varchar(100) NOT NULL); + CREATE TABLE IF NOT EXISTS "countries" ("code" varchar(3) PRIMARY KEY, "name" varchar(100) NOT NULL); + CREATE TABLE IF NOT EXISTS "levels" ("rank" integer PRIMARY KEY, "title" varchar(100) NOT NULL);`, + ); + + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const [file, fn] of [["Device", "deviceRoutes"], ["Country", "countryRoutes"], ["Level", "levelRoutes"]] as const) { + const mod = (await import(pathToFileURL(emitted.locate(`${file}.routes.ts`)).href)) as Record< + string, + (f: FastifyInstance) => Promise + >; + await fastify.register(mod[fn]!); + } + }); + const baseUrl = served.baseUrl; + + return { + baseUrl, + applySeed: async (seed: KeyTypesSeed) => { + await executeSql(connectionUri, `TRUNCATE TABLE "devices", "countries", "levels";`); + for (const r of seed.devices) + await executeSql(connectionUri, `INSERT INTO "devices" ("id","label") VALUES (${str(r.id)}, ${str(r.label)})`); + for (const r of seed.countries) + await executeSql(connectionUri, `INSERT INTO "countries" ("code","name") VALUES (${str(r.code)}, ${str(r.name)})`); + for (const r of seed.levels) + await executeSql(connectionUri, `INSERT INTO "levels" ("rank","title") VALUES (${r.rank}, ${str(r.title)})`); + }, + close: async () => { + await served.close(); + await dbMod.pool.end(); + rmSync(tmp, { recursive: true, force: true }); + }, + }; +} + +function str(v: string): string { + return `'${v.replace(/'/g, "''")}'`; +} diff --git a/server/typescript/packages/integration-tests/src/paths.ts b/server/typescript/packages/integration-tests/src/paths.ts index 16718a327c..cd70574f94 100644 --- a/server/typescript/packages/integration-tests/src/paths.ts +++ b/server/typescript/packages/integration-tests/src/paths.ts @@ -54,6 +54,10 @@ export const API_CONTRACT_SECRET_FIELDS_TPH_SCENARIOS_DIR = resolve(API_CONTRACT // Enum @default applied on create subcorpus (GENERATED lane only, every port). export const API_CONTRACT_ENUM_DEFAULT_DIR = resolve(API_CONTRACT_DIR, "enum-default"); export const API_CONTRACT_ENUM_DEFAULT_SCENARIOS_DIR = resolve(API_CONTRACT_ENUM_DEFAULT_DIR, "scenarios"); + +// Non-sequence primary keys (uuid, natural string, int) subcorpus (GENERATED lane only, every port). +export const API_CONTRACT_KEY_TYPES_DIR = resolve(API_CONTRACT_DIR, "key-types"); +export const API_CONTRACT_KEY_TYPES_SCENARIOS_DIR = resolve(API_CONTRACT_KEY_TYPES_DIR, "scenarios"); export const API_CONTRACT_RULES_DIR = resolve(API_CONTRACT_DIR, "rules"); export const API_CONTRACT_RULES_SCENARIOS_DIR = resolve(API_CONTRACT_RULES_DIR, "scenarios"); export const API_CONTRACT_RULES_SETTINGS_DIR = resolve(API_CONTRACT_RULES_DIR, "settings"); diff --git a/server/typescript/packages/integration-tests/test/api-contract-key-types.test.ts b/server/typescript/packages/integration-tests/test/api-contract-key-types.test.ts new file mode 100644 index 0000000000..1c26dd9dbf --- /dev/null +++ b/server/typescript/packages/integration-tests/test/api-contract-key-types.test.ts @@ -0,0 +1,55 @@ +// key-types api-contract conformance (GENERATED lane). +// +// Drives fixtures/api-contract-conformance/key-types/ over HTTP against the GENERATED +// Device (uuid), Country (string) and Level (int) routes. Generated lane only — see the corpus README. One Postgres testcontainer per scenario. + +import { describe, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { API_CONTRACT_KEY_TYPES_DIR, API_CONTRACT_KEY_TYPES_SCENARIOS_DIR } from "../src/paths.ts"; +import { loadScenarios, assertResponse, type ApiScenario, parseBodyExact } from "../src/api-contract-scenario.ts"; +import { OUTPUT_LAYOUTS, postgresFor } from "../src/output-layout.ts"; +import { + startGeneratedKeyTypesServer, + type GeneratedKeyTypesServerHandle, + type KeyTypesSeed, +} from "../src/api-contract-key-types-generated-server.ts"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; + +const SEED = JSON.parse(readFileSync(join(API_CONTRACT_KEY_TYPES_DIR, "seed.json"), "utf8")) as KeyTypesSeed; +const META_PATH = join(API_CONTRACT_KEY_TYPES_DIR, "meta.json"); + +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract key types — ${laneLabel(lane)} [${layout}]`, () => { + const startDb = postgresFor(layout); + for (const scenario of loadScenarios(API_CONTRACT_KEY_TYPES_SCENARIOS_DIR)) { + test(scenario.name, async () => { + const pg = await startDb(); + let server: GeneratedKeyTypesServerHandle | null = null; + try { + server = await startGeneratedKeyTypesServer(pg.connectionUri, META_PATH, layout, lane); + await server.applySeed(SEED); + await runScenario(scenario, server); + } finally { + if (server) await server.close(); + await pg.stop(); + } + }, { timeout: 60_000 }); + } +}); + +async function runScenario(scenario: ApiScenario, server: GeneratedKeyTypesServerHandle): Promise { + for (const req of scenario.requests) { + const init: RequestInit = { method: req.method }; + if (req.body !== undefined) { + init.body = JSON.stringify(req.body); + init.headers = { "content-type": "application/json" }; + } + const res = await fetch(server.baseUrl + req.path, init); + const bodyText = await res.text(); + let body: unknown = null; + if (bodyText.length > 0) { + try { body = parseBodyExact(bodyText); } catch { body = bodyText; } + } + assertResponse(scenario.name, req, res.status, body); + } +} From 327c07539f767a3fadfe07dc824fbedc75bd93a0 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 19:03:29 -0500 Subject: [PATCH 03/12] docs: describe the 1.3.0 removals and add the owned-generator upgrade page The docs, the agent-context skills and their shipped copies no longer describe docsFile(), the classic site, the legacy generator markers, formatTs or the Biome owned-copy comparison as current. A new upgrade page covers owned 1.2 generator copies, which no longer load. --- .../files/1798b962425d3bb5.md | 2 +- .../files/ad2ac665832abd65.md | 15 +- .../files/b0da43ca5875f8a4.md | 14 +- ...1fcc1b45dff7950.md => c6661fa20a4ea9df.md} | 16 +- .../files/e67be23f21c753da.md | 2 +- .../files/f16e73013983b1b6.md | 7 +- agent-context-shipped/manifest.json | 288 +++++++++--------- .../references/reporting.md | 2 +- .../skills/metaobjects-codegen/SKILL.md | 2 +- .../metaobjects-codegen/references/python.md | 7 +- .../references/typescript-docs.md | 14 +- .../references/typescript.md | 15 +- .../references/typescript.md | 16 +- docs/features/cli.md | 22 +- docs/features/codegen-data-shapes.md | 24 +- docs/features/explorer-site.md | 17 +- .../migrations/docs-are-generators.md | 43 ++- .../migrations/owned-generators-1.2-to-1.3.md | 37 +++ docs/features/own-your-codegen.md | 82 +++-- docs/features/reporting.md | 2 +- docs/llms/llms-full.txt | 2 +- docs/llms/llms.txt | 4 +- docs/ports/typescript.md | 8 +- docs/recipes/write-your-own-generator.md | 10 +- .../shipped/files/1798b962425d3bb5.md | 2 +- ...324dedeb09d7f35.md => ad2ac665832abd65.md} | 15 +- ...5b68292c9103dcc.md => b0da43ca5875f8a4.md} | 14 +- ...1fcc1b45dff7950.md => c6661fa20a4ea9df.md} | 16 +- .../shipped/files/e67be23f21c753da.md | 2 +- ...a2afb9dca07470e.md => f16e73013983b1b6.md} | 7 +- .../agent_context/shipped/manifest.json | 288 +++++++++--------- .../files/1798b962425d3bb5.md} | 2 +- .../files/ad2ac665832abd65.md | 15 +- .../files/b0da43ca5875f8a4.md | 14 +- ...1fcc1b45dff7950.md => c6661fa20a4ea9df.md} | 16 +- ...7c4b5191d819879.md => e67be23f21c753da.md} | 2 +- .../files/f16e73013983b1b6.md | 7 +- .../agent-context-shipped/manifest.json | 288 +++++++++--------- spec/code-writer.md | 7 +- 39 files changed, 687 insertions(+), 659 deletions(-) rename server/rust/metaobjects-cli/agent-context-shipped/files/f80806308b356cb6.md => agent-context-shipped/files/1798b962425d3bb5.md (98%) rename server/rust/metaobjects-cli/agent-context-shipped/files/7324dedeb09d7f35.md => agent-context-shipped/files/ad2ac665832abd65.md (97%) rename server/rust/metaobjects-cli/agent-context-shipped/files/c5b68292c9103dcc.md => agent-context-shipped/files/b0da43ca5875f8a4.md (88%) rename agent-context-shipped/files/{01fcc1b45dff7950.md => c6661fa20a4ea9df.md} (93%) rename server/python/src/metaobjects/agent_context/shipped/files/57c4b5191d819879.md => agent-context-shipped/files/e67be23f21c753da.md (99%) rename server/rust/metaobjects-cli/agent-context-shipped/files/ea2afb9dca07470e.md => agent-context-shipped/files/f16e73013983b1b6.md (98%) create mode 100644 docs/features/migrations/owned-generators-1.2-to-1.3.md rename agent-context-shipped/files/f80806308b356cb6.md => server/python/src/metaobjects/agent_context/shipped/files/1798b962425d3bb5.md (98%) rename server/python/src/metaobjects/agent_context/shipped/files/{7324dedeb09d7f35.md => ad2ac665832abd65.md} (97%) rename server/python/src/metaobjects/agent_context/shipped/files/{c5b68292c9103dcc.md => b0da43ca5875f8a4.md} (88%) rename server/python/src/metaobjects/agent_context/shipped/files/{01fcc1b45dff7950.md => c6661fa20a4ea9df.md} (93%) rename agent-context-shipped/files/57c4b5191d819879.md => server/python/src/metaobjects/agent_context/shipped/files/e67be23f21c753da.md (99%) rename server/python/src/metaobjects/agent_context/shipped/files/{ea2afb9dca07470e.md => f16e73013983b1b6.md} (98%) rename server/{python/src/metaobjects/agent_context/shipped/files/f80806308b356cb6.md => rust/metaobjects-cli/agent-context-shipped/files/1798b962425d3bb5.md} (98%) rename agent-context-shipped/files/7324dedeb09d7f35.md => server/rust/metaobjects-cli/agent-context-shipped/files/ad2ac665832abd65.md (97%) rename agent-context-shipped/files/c5b68292c9103dcc.md => server/rust/metaobjects-cli/agent-context-shipped/files/b0da43ca5875f8a4.md (88%) rename server/rust/metaobjects-cli/agent-context-shipped/files/{01fcc1b45dff7950.md => c6661fa20a4ea9df.md} (93%) rename server/rust/metaobjects-cli/agent-context-shipped/files/{57c4b5191d819879.md => e67be23f21c753da.md} (99%) rename agent-context-shipped/files/ea2afb9dca07470e.md => server/rust/metaobjects-cli/agent-context-shipped/files/f16e73013983b1b6.md (98%) diff --git a/server/rust/metaobjects-cli/agent-context-shipped/files/f80806308b356cb6.md b/agent-context-shipped/files/1798b962425d3bb5.md similarity index 98% rename from server/rust/metaobjects-cli/agent-context-shipped/files/f80806308b356cb6.md rename to agent-context-shipped/files/1798b962425d3bb5.md index eaa55e3356..be43b2d95e 100644 --- a/server/rust/metaobjects-cli/agent-context-shipped/files/f80806308b356cb6.md +++ b/agent-context-shipped/files/1798b962425d3bb5.md @@ -171,7 +171,7 @@ A concrete report whose read source is `@kind: view` is served by every port's g - **Every derived field with filter operators is filterable and sortable**, dimension and measure alike, with its type's own operators. You cannot narrow that set: a report has no field to put `@filterable` on. A field of the `@from` entity that the report does not expose is refused with a `400`. - A time dimension at `day` or coarser is `YYYY-MM-DD`; a null measure is `null` with the key present (a measure with `@default` is never null); `currency` is integer minor units. - **A decimal (`avg`, a ratio, a `sum` of a decimal) is written per the project's `wire` setting**: by default, the port's language-standard form (a JSON number in C#, Java and Kotlin; a string in Python and TypeScript), and under `"wire": { "decimals": "string" }` one canonical string in every port (`12.5`, never `12.50` or an exponent). Do not parse it as a float to compare. -- `meta gen` writes a model page for every report (`docsFile()`; a sourceless one is marked "Not served") and an API page for a served one (`apiDocsFile()`) — each an ordinary entry in `generators`. +- `meta gen` shows every report in the model explorer (`docsSiteFile()`; a sourceless one is marked "Not served") and writes an API page for a served one (`apiDocsFile()`) — each an ordinary entry in `generators`. The files each port generates are in the `metaobjects-codegen` skill's reference for that language ("Reports"). diff --git a/server/rust/metaobjects-cli/agent-context-shipped/files/7324dedeb09d7f35.md b/agent-context-shipped/files/ad2ac665832abd65.md similarity index 97% rename from server/rust/metaobjects-cli/agent-context-shipped/files/7324dedeb09d7f35.md rename to agent-context-shipped/files/ad2ac665832abd65.md index 4ae0b3964a..3c3b010c8f 100644 --- a/server/rust/metaobjects-cli/agent-context-shipped/files/7324dedeb09d7f35.md +++ b/agent-context-shipped/files/ad2ac665832abd65.md @@ -48,7 +48,7 @@ Everything a generator reads comes from `@metaobjectsdev/codegen-ts`: `perEntity `perPackage` / `perModel`, `isAbstract`, `hasAnyRdbSource`, `isProjection`, `servesReadApi` / `servesWriteApi`, `objectRefTarget`, `enumValues`, `effectivePackage`, `packageToPath`, `servedPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / -`pluralize`, and `formatTs` (a no-op kept so an owned copy still loads). The config's `apiPrefix` is +`pluralize`. (The `formatTs` no-op export was removed in 1.3.0; delete the import from an owned copy.) The config's `apiPrefix` is `ctx.renderContext?.apiPrefix`. Worked JSON Schema and OpenAPI 3.1 generators to copy: `docs/recipes/generators/typescript/` in the MetaObjects repository. @@ -146,18 +146,19 @@ package, and an owned copy imports it from `@metaobjectsdev/codegen-ts/engine`. Some ejectable entries behave differently from the rest: -- **`docs`, `api-docs`, `requirements` and `agent-docs` are run by `meta gen`, like any +- **`api-docs`, `requirements` and `agent-docs` are run by `meta gen`, like any other entry.** There is no separate docs command (removed in 1.1.0, ADR-0034 Amendment - 9): list `docsFile()`, `apiDocsFile()`, `requirementsFile()` and `agentDocsFile()` in + 9): list `apiDocsFile()`, `requirementsFile()` and `agentDocsFile()` in `generators` the same way you list `entityFile()`. Each defaults to a target named `docs` (`targets.docs.outDir`) unless given its own `target`, and a run that lists one while `targets` has no `docs` entry is refused, naming the generator. To change the - pages, `meta eject docs` (or `api-docs`, `requirements`, `agent-docs`) and list the copy + pages, `meta eject api-docs` (or `requirements`, `agent-docs`) and list the copy in `generators` in place of the packaged factory — there is no separate `docs` block to - put it in. To change only a page's wording, put your own - `templates/docs/entity-page.md.mustache` in the project instead. Full reference: + put it in. To change only a page's wording, point the factory's `templates` option at your own + directory. For people, list `docsSiteFile()` (the model explorer); `docsFile()` (per-object + Markdown pages) was removed in 1.3.0 and `meta gen` refuses it. Full reference: `typescript-docs.md`. -- **The ER diagram comes from `docsFile()`** (overview page, and each entity's page). The +- **The ER diagram is in the model explorer** (`docsSiteFile()`). The standalone `mermaidErDiagram()` / `"mermaid-er"` generator was removed in 1.1; a config that still wires it fails with a message saying so. Remove it and run `meta gen`. - **`shared-model` ejects with its artifact builder.** The copy decides which source files diff --git a/server/rust/metaobjects-cli/agent-context-shipped/files/c5b68292c9103dcc.md b/agent-context-shipped/files/b0da43ca5875f8a4.md similarity index 88% rename from server/rust/metaobjects-cli/agent-context-shipped/files/c5b68292c9103dcc.md rename to agent-context-shipped/files/b0da43ca5875f8a4.md index ff88a88e8a..4b84b257c4 100644 --- a/server/rust/metaobjects-cli/agent-context-shipped/files/c5b68292c9103dcc.md +++ b/agent-context-shipped/files/b0da43ca5875f8a4.md @@ -18,29 +18,28 @@ generate, docs included). Each factory is an ordinary entry in `generators`, fro | Factory | Registry name | Writes | |---|---|---| -| `docsFile()` | `docs` | the neutral model surface — one page per entity and per template (`.md`, `