From 808c9122d1c5503d72b4fcac658738201638a781 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 11:56:40 -0500 Subject: [PATCH 1/8] fix(python): arrays off Postgres, unrestricted routes, eject --force skip - A primitive array (string, number, date, uuid, enum) persists on SQLite and MySQL as a JSON array; an int-backed enum's elements as their integers. roundtrip-int-enum-array now runs on both engines. A date/time/timestamp array is parsed element by element on write (it was refused on every engine). - The generator-selection check counts only the objects a generator writes output for: an unlimited `routes` is no longer refused over abstract or sourceless objects the limited `filter-allowlist` leaves out. - `eject --force` over a copy identical to the reference writes nothing. - The TPH foreign-discriminator scenario runs in Python's generated lane; the stale skip and KNOWN_GAPS entry are removed. --- .claude/rules/cross-language-porting.md | 2 +- CHANGELOG.md | 16 ++++- docs/features/field-types.md | 2 +- docs/ports/python.md | 7 +- server/python/src/metaobjects/cli.py | 9 ++- .../src/metaobjects/codegen/KNOWN_GAPS.md | 12 ---- .../python/src/metaobjects/codegen/eject.py | 10 ++- .../metaobjects/codegen/generator_registry.py | 8 +++ .../python/src/metaobjects/runtime/dialect.py | 62 +++++++++++++++- .../python/src/metaobjects/runtime/values.py | 27 ++++--- server/python/tests/codegen/test_eject.py | 15 ++++ .../tests/codegen/test_generator_settings.py | 28 ++++++++ .../test_api_contract_tph_generated.py | 12 +--- .../tests/integration/test_query_scenarios.py | 14 +--- .../test_object_manager_db_dialects.py | 72 +++++++++++++++++++ 15 files changed, 245 insertions(+), 51 deletions(-) diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index c2ae2489a4..1adc6c31c6 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -31,7 +31,7 @@ Preserve the following contracts exactly across all language ports: - Currency attrs: `@currency` (ISO 4217), `@locale` (BCP 47) - Schema attrs: `@schema` on `source.rdb` (DB schema name; Postgres default `public`, SQLite rejects non-default values) - Storage attrs: `@storage` on `field.object` (with `@objectRef`) — values `flattened` / `jsonb` / `subdocument`. Unifies "owned types" (flattened storage) and "structured JSONB" (jsonb storage). Defaults to single-jsonb-column when absent (back-compat). -- Enum: `field.enum` is a first-class field subtype (peer of `currency`), string-backed. Required `@values` string-array attr (member symbols). Members must be a non-empty set, each matching `^[A-Za-z_][A-Za-z0-9_]*$`, no duplicates — every port's loader enforces this (own-only) emitting `ERR_BAD_ATTR_VALUE` (missing `@values` → `ERR_MISSING_REQUIRED_ATTR`). Reuse via abstract `field.enum` + `extends`. Codegen: TS union + `z.enum`, C# `enum` + EF `HasConversion()`, DB `varchar` + `CHECK`. **Int-backed storage shipped** (`@intValueMap`, a `{memberSymbol: int}` map, switches the column to `integer` + int `CHECK` while the wire format, the generated type and every runtime value stay the member SYMBOL; a MAP rather than a positional array so reordering `@values` cannot silently re-map every member; an int-backed enum array loads in every port and stores each element as its declared integer — TypeScript, C#, Java (OMDB) and Kotlin (Exposed) persist it on every engine, Python on Postgres only; an unmapped stored integer THROWS in all five ports). Display labels and native PG enum remain deferred (see `docs/superpowers/specs/2026-05-23-enum-datatype-design.md`). +- Enum: `field.enum` is a first-class field subtype (peer of `currency`), string-backed. Required `@values` string-array attr (member symbols). Members must be a non-empty set, each matching `^[A-Za-z_][A-Za-z0-9_]*$`, no duplicates — every port's loader enforces this (own-only) emitting `ERR_BAD_ATTR_VALUE` (missing `@values` → `ERR_MISSING_REQUIRED_ATTR`). Reuse via abstract `field.enum` + `extends`. Codegen: TS union + `z.enum`, C# `enum` + EF `HasConversion()`, DB `varchar` + `CHECK`. **Int-backed storage shipped** (`@intValueMap`, a `{memberSymbol: int}` map, switches the column to `integer` + int `CHECK` while the wire format, the generated type and every runtime value stay the member SYMBOL; a MAP rather than a positional array so reordering `@values` cannot silently re-map every member; an int-backed enum array loads in every port and stores each element as its declared integer — TypeScript, C#, Java (OMDB), Kotlin (Exposed) and Python persist it on every engine; an unmapped stored integer THROWS in all five ports). Display labels and native PG enum remain deferred (see `docs/superpowers/specs/2026-05-23-enum-datatype-design.md`). - Documentation common attrs (any node): `description`, `title`, `notes`, `deprecated`, `replacedBy`, `seeAlso`, `aliases`. Registered via the cross-language `commonAttrs` registry hook (`registerCommonAttrs` / `RegisterCommonAttrs` / `register_common_attrs` / Java `MetaDataRegistry.registerCommonAttribute` — wired in all four ports). `notes` is the internal-only rationale slot — never emitted to user-facing doc-gen (JSDoc / XML-doc / Postgres `COMMENT ON` / Mermaid prose). **The `description` / `notes` split is by CONTENT KIND, not audience** — an audience split invites writing the same content twice at two levels of politeness. `description` states what the element IS and COVERS (scope and boundary, derivable from the model); `notes` states what you had to look OUTSIDE the model to learn (evidence, citations, what breaks if it changes). Mechanical test: a sentence belongs in `notes` exactly when it would have to change because the IMPLEMENTATION changed while the model did not. `title` is a noun phrase, `summary` a one-line sentence. TS doc-gen ships all three tiers; C# ships XML-doc + COMMENT ON. See `docs/superpowers/specs/2026-05-24-documentation-provider-design.md`. **Wire format:** diff --git a/CHANGELOG.md b/CHANGELOG.md index 664bd0207b..d067cad37b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -178,6 +178,18 @@ here.** included every filterable text field, and an int-backed (`@intValueMap`) enum is an integer column, so Postgres refused the ILIKE. Search now covers only fields whose operator band includes `like`. +- **Python: a primitive array persists on SQLite and MySQL.** The `ObjectManagerDb`'s SQLite and + MySQL dialects bound no list, so an `isArray` string, number, date, uuid or enum field could not be + written there. The column the TypeScript-owned schema gives it (`TEXT` on SQLite, `JSON` on MySQL) + now holds a JSON array, an int-backed enum's as its integers (`[5,0]`), and each element reads back + through the scalar decode. `roundtrip-int-enum-array` runs on both engines instead of being deferred. + A `field.date`, `field.time` or `field.timestamp` array was refused on write on every engine, + Postgres included (the list was parsed as one value); it is now parsed element by element. +- **Python: an unrestricted `routes` is no longer refused for objects it writes no router for.** + `metaobjects gen` refused a config that limits `filter-allowlist` (or `entity`) to some packages + while `routes` is left unlimited, whenever another package held an abstract or sourceless object, + saying `routes` covered it. `routes` writes nothing for those objects, so only the objects it + routes count now. - **C#: a `@sequenceStart` whose migrations project lacks the design-time services line is a generation error.** When `dotnet meta gen` can see the context's `ModelSnapshot.cs` in another project and that project does not carry `[assembly: DesignTimeServicesReference]`, the next `dotnet ef migrations add` @@ -869,8 +881,8 @@ Each item below is described in full under Security, Added, Changed or Fixed; th the only int-backed enum, projection and report-row enum arrays get the element converter (they read stored ints as ordinals before), and a non-required int-backed enum array is nullable. - - Python: ObjectManager maps elements on write, read and filter operands on Postgres. Its - SQLite and MySQL dialects store no primitive array, so the new scenario is deferred there. + - Python: ObjectManager maps elements on write, read and filter operands, on Postgres, SQLite + and MySQL (the last two store a JSON array of numbers). - Java: OMDB stores an int-backed enum array as a native `integer[]` on Postgres and a JSON array of numbers on SQLite, MySQL and Derby; a member with no declared integer is refused on write, and a stored integer with no member fails the read. Kotlin: the Exposed table generator emits an diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 0edcfb714b..b06f07283b 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -292,7 +292,7 @@ sharing the enum keeps its integer `CHECK`. The generated type is the port's lis | C# | Postgres, SQLite, MySQL | the element converter of an EF Core primitive collection; a non-required array is `IList?` | | Java | Postgres, SQLite, MySQL, Derby | the OMDB codec (`JdbcCodecs`; `PostgresDriver.nativeArrayElementType` on Postgres). A member with no declared integer is refused on write with an `SQLException` naming the field. A repository you write yourself maps each element through the generated enum's `dbValue()` and `fromDbValue(int)` | | Kotlin | Postgres, SQLite, MySQL | the generated `portableIntEnumArray(name, { toInt }, { fromInt })` column, emitted into `MetaIntEnumArrayColumnType.kt` only in a package that has such a column. Its two lambdas are generated `when` expressions, so a member with no integer is a compile error | -| Python | Postgres only | the codec in `metaobjects.runtime.values`, called by `ObjectManagerDb`. SQLite and MySQL store no primitive array in this runtime, so an enum array of either kind is Postgres-only there | +| Python | Postgres, SQLite, MySQL | the codec in `metaobjects.runtime.values`, called by `ObjectManagerDb`; the SQLite and MySQL dialects bind the array as JSON text and decode each element | The `roundtrip-int-enum-array` persistence scenario ([fixtures/persistence-conformance/README.md](../../fixtures/persistence-conformance/README.md#int-backed-enum-array-scenario)) diff --git a/docs/ports/python.md b/docs/ports/python.md index b9146d0b01..b9b07c341f 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -781,10 +781,13 @@ that file's root package, so `package` on such a node is already the full A `field.enum` with `@intValueMap` (own or inherited from a shared abstract enum) is stored as its declared integers while `ObjectManager` callers pass and receive member symbols. The codec in `metaobjects.runtime.values` (called by `ObjectManagerDb`) encodes on every write and on filter operands, and decodes on -every read. On an `isArray: true` field it does this for each element, on Postgres only (see +every read. On an `isArray: true` field it does this for each element, on every engine (see [Int-backed enum arrays](../features/field-types.md#int-backed-enum-arrays)); a null element stays a null element. An int that has no member raises `ValueError` on read, whether it is a scalar or an -array element. +array element. On SQLite and MySQL, which have no array type, the column is `TEXT` / `JSON` holding a +JSON array (`[5,0]`). This holds for every primitive array (strings, numbers, dates, uuids): each +element is written as the JSON form of what the scalar column binds and read back through the scalar +decode. ### Run-time validation diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index 8475365aeb..8b223f5e77 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -968,7 +968,14 @@ def _unmet_requires_by_selection( if entry is None: continue inner_filter = getattr(gen, "filter", None) - covered = [o for o in objects if not callable(inner_filter) or inner_filter(o)] + # Only the objects whose output imports the required generator's: `routes` writes no + # router for an abstract or sourceless object, so limiting `filter-allowlist` away from + # one leaves nothing dangling. + covered = [ + o for o in objects + if (not callable(inner_filter) or inner_filter(o)) + and (entry.covers is None or entry.covers(o)) + ] for dep, dep_token in zip(gens, tokens): if dep_token not in entry.requires or not isinstance(dep, SelectedGenerator): continue diff --git a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md index 359a1f422e..3f14a45b92 100644 --- a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md +++ b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md @@ -56,18 +56,6 @@ import wiring itself (`from ._entity import `), which still needs path-resolution/import-base machinery; the config's per-target `outDir` is the prerequisite that is now in place. -## TPH body discriminator: 400, not a silent drop - -**Status:** known divergence, out of scope for the 1.2.x input patch. - -A per-subtype write route (`POST /api/auths/bridge`) validates the request body with -that subtype's model, whose discriminator accepts only the route's own value. A body -that names another subtype (`"type": "Coupon"`) is answered `400 {"error":"validation"}`. -Nothing is stored, so this is not a security hole, but the other ports drop the key -and create the row with the route's subtype. The shared -`tph-input-foreign-discriminator-dropped` scenario asserts the drop, and this port's -runner skips it with this reason (`tests/integration/test_api_contract_tph_generated.py`). - ## FR-015 stored-procedure callables are NOT generated by this port **Contract.** FR-015 gives a `source.rdb @kind: storedProc` / `tableFunction` a generated diff --git a/server/python/src/metaobjects/codegen/eject.py b/server/python/src/metaobjects/codegen/eject.py index f4df97c42f..51ddcddf14 100644 --- a/server/python/src/metaobjects/codegen/eject.py +++ b/server/python/src/metaobjects/codegen/eject.py @@ -147,8 +147,14 @@ def eject(names: list[str], root: Path, *, force: bool = False) -> EjectResult: for n in names: entry = known[n] target = owned_path(root, n) - target.write_text(ejected_source(entry), encoding="utf-8") - out.append(f"ejected {n} -> {target.relative_to(root)}") + source = ejected_source(entry) + # `--force` over a copy that already IS the reference writes nothing: an unchanged + # file is never rewritten. + if target.exists() and target.read_bytes() == source.encode("utf-8"): + out.append(f"unchanged {n} -> {target.relative_to(root)} (already the reference)") + else: + target.write_text(source, encoding="utf-8") + out.append(f"ejected {n} -> {target.relative_to(root)}") out.append(f" wire it: replace \"{n}\" in `generators` with {owned_token(entry)}") for module in entry.runtime: rt = runtime_path(root, module) diff --git a/server/python/src/metaobjects/codegen/generator_registry.py b/server/python/src/metaobjects/codegen/generator_registry.py index 1cabf29c37..8b26864772 100644 --- a/server/python/src/metaobjects/codegen/generator_registry.py +++ b/server/python/src/metaobjects/codegen/generator_registry.py @@ -55,6 +55,8 @@ from metaobjects.codegen.generators.shared_model_generator import shared_model_generator from metaobjects.codegen.generators.template_generator import template_generator from metaobjects.codegen.generators.trace_helper_generator import trace_helper_generator +from metaobjects.codegen.runtime.shared_predicates import emits_router +from metaobjects.meta.core.object.meta_object import MetaObject from metaobjects.render.verify import InMemoryProvider GeneratorTier = str # "native" | "neutral" @@ -241,6 +243,11 @@ class GeneratorEntry: #: Not gated cross-port (the manifest carries no such column); surfaced by ``--list`` #: and warned about by :func:`unsatisfied_requires`. requires: tuple[str, ...] = () + #: The objects whose output imports what ``requires`` names: limiting a required generator + #: away from one of these leaves a dangling import, limiting it away from any other object + #: does not. ``None`` = every object. ``routes`` writes nothing for an abstract or + #: sourceless object, so a limit that leaves those out is no gap. + covers: Callable[[MetaObject], bool] | None = None #: The settings an ``options:`` mapping on this generator's ``generators`` entry may carry. #: A generator that lists none refuses any. options: tuple[GeneratorOption, ...] = () @@ -362,6 +369,7 @@ def _render_helper_default(ctx: GeneratorBuildContext) -> Generator: # FIELDS/OPS constants from _filter_allowlist; without either the # generated package fails at import (ModuleNotFoundError). requires=("entity", "filter-allowlist"), + covers=emits_router, source=router_generator, runtime=_ROUTER_RUNTIME + (_EXPORT_RUNTIME,) + _SHARED_PREDICATES + (_FR010_FIELD_MAPPING, _M2M_CODEGEN), ), diff --git a/server/python/src/metaobjects/runtime/dialect.py b/server/python/src/metaobjects/runtime/dialect.py index a23cae8324..a1cbe677b9 100644 --- a/server/python/src/metaobjects/runtime/dialect.py +++ b/server/python/src/metaobjects/runtime/dialect.py @@ -17,6 +17,12 @@ has the column types Postgres has (a SQLite boolean is ``0``/``1``, its date and uuid are ``TEXT``; a MySQL ``TIME`` arrives as a ``timedelta``, its ``SUM`` of an integer as a ``Decimal``), so the declared type is the only authority on what a value means. + +A primitive array (``isArray`` on a scalar field: strings, numbers, an int-backed enum's +integers) is a native ``text[]`` / ``integer[]`` on Postgres. SQLite and MySQL have no array +type, so the TypeScript-owned schema gives the column ``TEXT`` / ``JSON`` and the value is a +JSON array: each element is bound as the JSON form of what the scalar binds, and read back +element by element through the scalar decode. """ from __future__ import annotations @@ -165,8 +171,46 @@ def _as_int(value: Any) -> Any: return value +def _json_array_text(values: list[Any], element: Any) -> str: + """A primitive array as the JSON text a SQLite ``TEXT`` / MySQL ``JSON`` column holds. + + ``element`` binds one member. What it returns is written as JSON: a number stays a + number (an int-backed enum's ``[5,0]``), anything else the engine stores as text stays + the same text.""" + out: list[Any] = [] + for v in values: + if v is None or isinstance(v, (bool, int, float, str)): + out.append(v) + continue + if isinstance(v, _decimal.Decimal): + out.append(str(v)) + continue + bound = element(v) + out.append(bound if isinstance(bound, (bool, int, float, str)) else str(bound)) + return _json.dumps(out) + + def _decode_storage_value(field: MetaField, value: Any) -> Any: - """Decode a SQLite / MySQL value by the field's declared subtype.""" + """Decode a SQLite / MySQL value by the field's declared subtype. + + A primitive array arrives as its JSON text (MySQL may already hand back the parsed + list); each element is decoded as the scalar would be.""" + if value is None: + return None + if field.resolved_is_array() and field.sub_type not in ( + fc.FIELD_SUBTYPE_OBJECT, fc.FIELD_SUBTYPE_MAP, + ): + if isinstance(value, (bytes, bytearray)): + value = value.decode("utf-8") + if isinstance(value, str): + value = _json.loads(value) + if isinstance(value, list): + return [_decode_storage_scalar(field, v) for v in value] + return value + return _decode_storage_scalar(field, value) + + +def _decode_storage_scalar(field: MetaField, value: Any) -> Any: if value is None: return None sub = field.sub_type @@ -267,6 +311,10 @@ def false_predicate(self) -> str: return "0 = 1" def encode_param(self, value: Any) -> Any: + if isinstance(value, list): + # A primitive array column is TEXT holding a JSON array. A filter's `in` list never + # reaches here: it is expanded to one placeholder per element. + return _json_array_text(value, self.encode_param) if isinstance(value, bool): return int(value) if isinstance(value, _uuid.UUID): @@ -315,6 +363,10 @@ def like_clause(self, quoted_column: str, pattern: str) -> tuple[str, list[Any]] return f"{quoted_column} LIKE BINARY {self.placeholder}", [pattern] def encode_param(self, value: Any) -> Any: + if isinstance(value, list): + # A primitive array column is JSON. A filter's `in` list never reaches here: it is + # expanded to one placeholder per element. + return _json_array_text(value, self._json_element) if isinstance(value, _uuid.UUID): return str(value) if isinstance(value, _dt.datetime) and value.tzinfo is not None: @@ -328,6 +380,14 @@ def encode_param(self, value: Any) -> Any: return to_stored_micros(value) return value + def _json_element(self, value: Any) -> Any: + # Inside JSON a DATETIME is text, so an instant is written the way SQLite stores one. + if isinstance(value, _dt.datetime): + return _timestamp_text(value) + if isinstance(value, _dt.date): + return value.isoformat() + return self.encode_param(value) + def decode_value(self, field: MetaField, value: Any) -> Any: return _decode_storage_value(field, value) diff --git a/server/python/src/metaobjects/runtime/values.py b/server/python/src/metaobjects/runtime/values.py index 49d18bb9e5..a899daf532 100644 --- a/server/python/src/metaobjects/runtime/values.py +++ b/server/python/src/metaobjects/runtime/values.py @@ -180,15 +180,11 @@ def coerce_write_value(field: MetaField, value: Any, *, for_filter: bool = False # driven by the field so the driver binds the correct physical type. ADR-0036 # Wave 2: field.timestamp is instant / tz-aware BY DEFAULT (→ timestamptz); the # rare naive wall-clock case opts out with @localTime:true (→ plain timestamp). - if sub == fc.FIELD_SUBTYPE_DATE: - return value if isinstance(value, _dt.date) else _dt.date.fromisoformat(str(value)) - if sub == fc.FIELD_SUBTYPE_TIME: - return value if isinstance(value, _dt.time) else _dt.time.fromisoformat(str(value)) - if sub == fc.FIELD_SUBTYPE_TIMESTAMP: - if isinstance(value, _dt.datetime): - return value - is_tz = field.get_meta_attr(dbc.FIELD_ATTR_LOCAL_TIME) is not True # ADR-0039 resolving: @localTime may be inherited - return _parse_datetime(str(value), tz_aware=is_tz) + # An array of them is parsed element by element. + if sub in (fc.FIELD_SUBTYPE_DATE, fc.FIELD_SUBTYPE_TIME, fc.FIELD_SUBTYPE_TIMESTAMP): + if field_is_array(field) and isinstance(value, list): + return [None if v is None else _temporal_write_value(field, v) for v in value] + return _temporal_write_value(field, value) # field.object / field.map stored as a single jsonb column: serialize to a # JSON text string so pg8000 sends it as jsonb text (PG assignment-casts text @@ -249,6 +245,19 @@ def coerce_write_value(field: MetaField, value: Any, *, for_filter: bool = False return value +def _temporal_write_value(field: MetaField, value: Any) -> Any: + """One ``field.date`` / ``field.time`` / ``field.timestamp`` value, as its native type.""" + sub = field.sub_type + if sub == fc.FIELD_SUBTYPE_DATE: + return value if isinstance(value, _dt.date) else _dt.date.fromisoformat(str(value)) + if sub == fc.FIELD_SUBTYPE_TIME: + return value if isinstance(value, _dt.time) else _dt.time.fromisoformat(str(value)) + if isinstance(value, _dt.datetime): + return value + is_tz = field.get_meta_attr(dbc.FIELD_ATTR_LOCAL_TIME) is not True # ADR-0039 resolving: @localTime may be inherited + return _parse_datetime(str(value), tz_aware=is_tz) + + def _write_duration_member(field: MetaField, value: Any) -> str: """A ``field.duration`` member of a value object, as the canonical string its JSON holds.""" try: diff --git a/server/python/tests/codegen/test_eject.py b/server/python/tests/codegen/test_eject.py index 105f001b8a..a72c3e6c9b 100644 --- a/server/python/tests/codegen/test_eject.py +++ b/server/python/tests/codegen/test_eject.py @@ -7,6 +7,7 @@ from __future__ import annotations import importlib +import os import sys from pathlib import Path @@ -66,6 +67,20 @@ def test_eject_copies_verbatim_and_refuses_to_overwrite(tmp_path: Path, monkeypa assert copy.read_text(encoding="utf-8") == _packaged_source("entity") +def test_eject_force_over_the_reference_writes_nothing( + tmp_path: Path, monkeypatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.chdir(tmp_path) + assert main(["eject", "routes"]) == 0 + copy = tmp_path / "codegen" / "generators" / "routes.py" + # A sentinel mtime: a rewrite of the same bytes would move it. + os.utime(copy, ns=(1_000_000_000, 1_000_000_000)) + capsys.readouterr() + assert main(["eject", "routes", "--force"]) == 0 + assert copy.stat().st_mtime_ns == 1_000_000_000 + assert "unchanged routes -> codegen/generators/routes.py" in capsys.readouterr().out + + def test_eject_unknown_name_writes_nothing(tmp_path: Path, monkeypatch) -> None: monkeypatch.chdir(tmp_path) assert main(["eject", "entity", "nope"]) == 2 diff --git a/server/python/tests/codegen/test_generator_settings.py b/server/python/tests/codegen/test_generator_settings.py index d4ee21cc2b..0f1d5e1ab5 100644 --- a/server/python/tests/codegen/test_generator_settings.py +++ b/server/python/tests/codegen/test_generator_settings.py @@ -173,6 +173,34 @@ def test_a_generator_may_not_cover_what_its_required_generator_is_limited_away_f assert not out.exists() or not _stems(out) +def test_an_unlimited_generator_does_not_count_objects_it_writes_nothing_for( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # `routes` writes no router for an abstract object or a sourceless one, so limiting the + # allowlist to the packages that hold the routed entities leaves nothing dangling. + out = _project( + tmp_path, + "- entity\n- {name: filter-allowlist, packages: ['acme::sales', 'acme::hr']}\n- routes\n", + ) + (tmp_path / "metaobjects" / "meta.common.json").write_text( + json.dumps({"metadata.root": {"package": "acme::common", "children": [ + {"object.entity": {"name": "Base", "abstract": True, "children": [ + {"field.long": {"name": "id"}}, + ]}}, + {"object.entity": {"name": "Remote", "children": [ + {"field.long": {"name": "id"}}, + {"identity.primary": {"name": "pk", "@fields": ["id"]}}, + ]}}, + ]}}), + encoding="utf-8", + ) + monkeypatch.chdir(tmp_path) + assert main(["gen"]) == 0 + stems = _stems(out) + assert {"order_router", "invoice_router", "person_router"} <= stems + assert "remote_router" not in stems and "base_router" not in stems + + def test_limiting_a_generator_and_the_one_it_requires_to_the_same_entity_is_accepted( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/server/python/tests/integration/test_api_contract_tph_generated.py b/server/python/tests/integration/test_api_contract_tph_generated.py index b84fb01b84..8cb2c28b79 100644 --- a/server/python/tests/integration/test_api_contract_tph_generated.py +++ b/server/python/tests/integration/test_api_contract_tph_generated.py @@ -56,15 +56,9 @@ def _load_scenarios() -> list[tuple[str, dict[str, Any]]]: _SCENARIOS = _load_scenarios() -# Scenarios this port's generated routes answer differently, each with its reason. The routes -# validate the body's discriminator against the route's subtype and answer 400 rather than -# dropping it; nothing is stored either way. See codegen/KNOWN_GAPS.md. -_PORT_SKIPS: dict[str, str] = { - "tph-input-foreign-discriminator-dropped": ( - "a body discriminator naming another subtype is a 400 here, not a silent drop " - "(KNOWN_GAPS.md: TPH body discriminator)" - ), -} +# Scenarios this port's generated routes answer differently, each with its reason. None: a +# body discriminator naming another subtype is dropped, as in every port. +_PORT_SKIPS: dict[str, str] = {} _APP, _REPO = build_generated_tph_app(_TPH_DIR) _CLIENT = TestClient(_APP) diff --git a/server/python/tests/integration/test_query_scenarios.py b/server/python/tests/integration/test_query_scenarios.py index 020ec1d78a..101bbce569 100644 --- a/server/python/tests/integration/test_query_scenarios.py +++ b/server/python/tests/integration/test_query_scenarios.py @@ -34,17 +34,9 @@ # ``tph-*`` scenarios run green and are no longer skipped. EXPECTED_FAILURES: dict[str, str] = {} -# The same, for one engine only: (engine, scenario name) -> reason. The Python runtime's -# SQLite and MySQL dialects bind no list parameter (``runtime/dialect.py`` encode_param has -# no list case), so no primitive array -- string- or int-backed -- persists on those engines. -_NO_ARRAYS = ( - "the Python runtime stores no primitive array on this engine " - "(SqliteDialect/MySqlDialect.encode_param have no list case)" -) -ENGINE_EXPECTED_FAILURES: dict[tuple[str, str], str] = { - ("sqlite", "roundtrip-int-enum-array"): _NO_ARRAYS, - ("mysql", "roundtrip-int-enum-array"): _NO_ARRAYS, -} +# The same, for one engine only: (engine, scenario name) -> reason. Empty: a primitive +# array (``roundtrip-int-enum-array``) persists on SQLite and MySQL as a JSON array. +ENGINE_EXPECTED_FAILURES: dict[tuple[str, str], str] = {} def _skip_if_expected(engine: str, scenario: QueryScenario) -> None: diff --git a/server/python/tests/runtime/test_object_manager_db_dialects.py b/server/python/tests/runtime/test_object_manager_db_dialects.py index 216126e5c7..67d5ba01ba 100644 --- a/server/python/tests/runtime/test_object_manager_db_dialects.py +++ b/server/python/tests/runtime/test_object_manager_db_dialects.py @@ -426,3 +426,75 @@ def test_order_term_puts_nulls_largest_on_every_dialect() -> None: my = MySqlDialect() assert my.order_term("`c`", False) == "(`c` IS NULL) ASC, `c` ASC" assert my.order_term("`c`", True) == "(`c` IS NULL) DESC, `c` DESC" + + +# ---------------------------------------------------------------------------- +# Primitive arrays off Postgres: a JSON array in a TEXT (SQLite) / JSON (MySQL) column +# ---------------------------------------------------------------------------- + +_ARRAY_META = { + "metadata.root": { + "package": "acme::shop", + "children": [ + {"field.enum": {"name": "State", "abstract": True, + "@values": ["DRAFT", "PUBLISHED"], + "@intValueMap": {"DRAFT": 0, "PUBLISHED": 5}}}, + { + "object.entity": { + "name": "Tagged", + "children": [ + {"source.rdb": {"@table": "tagged"}}, + {"field.long": {"name": "id"}}, + {"field.string": {"name": "tags", "isArray": True}}, + {"field.date": {"name": "days", "isArray": True}}, + {"field.enum": {"name": "history", "extends": "State", "isArray": True}}, + {"identity.primary": {"name": "pk", "@fields": ["id"], "@generation": "increment"}}, + ], + } + }, + ], + } +} + + +def _array_root() -> Any: + root = load_string(json.dumps(_ARRAY_META)).root + root.naming = NamingRules(columns="literal") + return root + + +def test_sqlite_stores_a_primitive_array_as_a_json_array_and_reads_it_back() -> None: + real = sqlite3.connect(":memory:") + real.execute( + 'CREATE TABLE "tagged" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, ' + '"tags" TEXT, "days" TEXT, "history" TEXT)' + ) + om = ObjectManagerDb(_array_root(), SqliteDriver(Recording(real))) # type: ignore[arg-type] + created = om.create( + "Tagged", + {"tags": ["a", "b"], "days": ["2026-05-01"], "history": ["PUBLISHED", "DRAFT"]}, + ) + # The int-backed enum's elements are stored as their integers, the rest as their text. + stored = real.execute('SELECT "tags", "days", "history" FROM "tagged"').fetchone() + assert [json.loads(c) for c in stored] == [["a", "b"], ["2026-05-01"], [5, 0]] + assert created["tags"] == ["a", "b"] + assert created["days"] == [dt.date(2026, 5, 1)] + assert created["history"] == ["PUBLISHED", "DRAFT"] + + empty = om.create("Tagged", {"tags": [], "history": None}) + assert empty["tags"] == [] and empty["history"] is None and empty["days"] is None + [reread] = om.find_many("Tagged", {"id": empty["id"]}) + assert reread["tags"] == [] and reread["history"] is None + + +def test_mysql_binds_a_primitive_array_as_json_and_decodes_the_column() -> None: + root = _array_root() + tagged = next(o for o in root.own_children() if getattr(o, "name", None) == "Tagged") + fields = {f.name: f for f in tagged.fields()} + assert MYSQL.encode_param([5, 0]) == "[5, 0]" + assert MYSQL.encode_param(["a", None]) == '["a", null]' + assert MYSQL.encode_param([dt.date(2026, 5, 1)]) == '["2026-05-01"]' + assert MYSQL.decode_value(fields["days"], '["2026-05-01"]') == [dt.date(2026, 5, 1)] + # PyMySQL hands a JSON column back as text; a list is decoded the same way. + assert MYSQL.decode_value(fields["tags"], ["a"]) == ["a"] + assert MYSQL.decode_value(fields["history"], b"[5,0]") == [5, 0] From 159ebf316478ad1c34e9fde1577e4af078029664 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:08:24 -0500 Subject: [PATCH 2/8] fix(python): check @union and @grain projections at load (C3) --- CHANGELOG.md | 6 + .../metaobjects/loader/validation_passes.py | 107 ++++++++++++++++++ .../meta/core/field/field_constants.py | 4 +- .../conformance-expected-failures.json | 4 - .../loader/test_projection_union_and_grain.py | 71 ++++++++++++ 5 files changed, 187 insertions(+), 5 deletions(-) create mode 100644 server/python/tests/loader/test_projection_union_and_grain.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d067cad37b..62e9bd8be4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,12 @@ here.** Python had none. `Renderer` now strips standalone comment lines before mustache.java parses them. A template with such a line renders differently in Java, so a prompt body with one changes bytes (and its prompt-cache prefix) on upgrade. The `render-standalone-*` fixtures pin the whitespace rules. +- **Python: `@union` and `@grain` projections are checked at load.** A union member whose fields + differ in name, subtype, array-ness, `@column` or enum shape, a member that is the projection + itself or declares its own `@union`, `@unionAll` without `@union`, a `@grain` that does not name a + base-entity `field.object` jsonb array with `@objectRef`, an aggregate in a `@grain` view, and a + malformed `@grainOrdinal` are now `ERR_BAD_ATTR_VALUE`, as in TypeScript and C#. Python passes the + `error-projection-union-shape` and `error-projection-grain-not-object-array` fixtures. - **C#: an unchanged file is never rewritten.** `dotnet meta gen` already left identical output alone when the project keeps a hash manifest. It now does the same on the path with no manifest (output written outside the project, or a program that runs the generators with no state directory), which diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 9205b36253..7485d989dc 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -36,6 +36,7 @@ from ..meta.core.field.field_constants import ( ENUM_MEMBER_PATTERN, FIELD_ATTR_COERCE_DEFAULT, + FIELD_ATTR_COLUMN, FIELD_ATTR_DEFAULT, FIELD_ATTR_INT_VALUE_MAP, FIELD_ATTR_STRING_VALUE_MAP, @@ -45,6 +46,7 @@ FIELD_ATTR_SORTABLE, FIELD_ATTR_FLATTENED_COLUMN_PREFIX, STORAGE_FLATTENED, + STORAGE_JSONB, FIELD_ATTR_STORAGE, FIELD_ATTR_VALUE_TYPE, FIELD_ATTR_VALUES, @@ -153,6 +155,10 @@ ) from ..shared.separators import PACKAGE_SEP from ..meta.core.object.object_constants import ( + OBJECT_PROJECTION_ATTR_GRAIN, + OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL, + OBJECT_PROJECTION_ATTR_UNION, + OBJECT_PROJECTION_ATTR_UNION_ALL, OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_PROJECTION, OBJECT_SUBTYPE_VALUE, @@ -234,6 +240,8 @@ def run_validations( # Origin @segment names a segment of the related entity; a correlated @filter operand names # a base-row field. _validate_origin_segments_and_correlation(root, errors) + # rc.21 part B — @union shapes and @grain projections. + _validate_projection_union_and_grain(root, errors) # FR-044 — the reporting vocabulary (dimension / measure / segment / # object.report) and relative-date filter values (rules D1-F2). validate_reporting(root, errors) @@ -1933,6 +1941,105 @@ def _filter_keys(filter_value: object, out: list[str] | None = None) -> list[str return out +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``: + + - ``@union`` names projections whose rows join this one's: each must be an + object.projection other than this one, with the same effective fields in order (name, + subtype, array-ness, ``@column`` and an enum's members and value maps), and must not + declare its own ``@union``; ``@unionAll`` needs ``@union``; + - ``@grain`` names a base-entity field.object array stored as jsonb with an + ``@objectRef``; such a projection holds no origin.aggregate, and ``@grainOrdinal`` + names one of its own field.int / field.long fields with no origin and no extends. + Every finding is ``ERR_BAD_ATTR_VALUE`` on the projection.""" + # ADR-0039 sanctioned own: root has no super, and every projection is declared at root level. + for obj in root.own_children(): + if obj.type != TYPE_OBJECT or obj.sub_type != OBJECT_SUBTYPE_PROJECTION: + continue + + def bad(message: str, obj: MetaData = obj) -> None: + errors.append(MetaError( + f"object.projection {obj.name}: {message}", + ErrorCode.ERR_BAD_ATTR_VALUE, envelope=obj.source)) + + # ADR-0039 sanctioned own: validating the own declaration — a projection's @union and + # @grain name ITS view's shape; an extender declares its own. + union = obj.attr(OBJECT_PROJECTION_ATTR_UNION) + if obj.attr(OBJECT_PROJECTION_ATTR_UNION_ALL) is not None and union is None: + bad(f"@{OBJECT_PROJECTION_ATTR_UNION_ALL} needs @{OBJECT_PROJECTION_ATTR_UNION}.") + if union is not None: + referrer_pkg = referrer_package_of(obj) + mine = [_union_shape(f) for f in obj.children() if f.type == TYPE_FIELD] + for name in union if isinstance(union, list) else [union]: + member = resolve_object_ref(root, name, referrer_pkg) if isinstance(name, str) else None + if member is None or member.type != TYPE_OBJECT or member.sub_type != OBJECT_SUBTYPE_PROJECTION: + bad(f'@{OBJECT_PROJECTION_ATTR_UNION} names "{name}", which is not an object.projection.') + continue + if member is obj: + bad(f"@{OBJECT_PROJECTION_ATTR_UNION} names the projection itself.") + continue + # ADR-0039 sanctioned own: a member's own @union would be flattened away, silently. + if member.attr(OBJECT_PROJECTION_ATTR_UNION) is not None: + bad(f'@{OBJECT_PROJECTION_ATTR_UNION} member "{member.name}" declares its own ' + f"@{OBJECT_PROJECTION_ATTR_UNION}; name its members here instead.") + theirs = [_union_shape(f) for f in member.children() if f.type == TYPE_FIELD] + if mine != theirs: + bad(f'@{OBJECT_PROJECTION_ATTR_UNION} member "{member.name}" has a different shape: ' + f"({', '.join(theirs)}) where this view is ({', '.join(mine)}). " + "A union's members have the same fields, in order.") + + # ADR-0039 sanctioned own: validating the own declaration (see above). + grain = obj.attr(OBJECT_PROJECTION_ATTR_GRAIN) + ordinal = obj.attr(OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL) + if ordinal is not None and grain is None: + bad(f"@{OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL} needs @{OBJECT_PROJECTION_ATTR_GRAIN}.") + if not isinstance(grain, str): + continue + 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) + storage = None if field is None else field.get_meta_attr(FIELD_ATTR_STORAGE) + if ( + field is None + or field.sub_type != FIELD_SUBTYPE_OBJECT + or not field.resolved_is_array() + or (storage is not None and storage != STORAGE_JSONB) + or bound_ref_target(field, FIELD_ATTR_OBJECT_REF) is None + ): + of_base = "" if base is None else f' "{base.name}"' + bad(f'@{OBJECT_PROJECTION_ATTR_GRAIN} "{grain}" must name a field.object array ' + f"(isArray, jsonb storage, with @objectRef) of the base entity{of_base}.") + for f in (c for c in obj.children() if c.type == TYPE_FIELD): + # ADR-0039 sanctioned own: origin.* never inherits (ADR-0029). + if any(c.type == TYPE_ORIGIN and c.sub_type == ORIGIN_SUBTYPE_AGGREGATE for c in f.own_children()): + bad(f'"{f.name}" is an origin.aggregate; a @grain view has one row per element and groups nothing.') + if ordinal is not None: + f = next((c for c in obj.children() if c.type == TYPE_FIELD and c.name == ordinal), None) + # ADR-0039 sanctioned own: origin.* never inherits (ADR-0029). + if ( + f is None + or f.sub_type not in (FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG) + or any(c.type == TYPE_ORIGIN for c in f.own_children()) + or f.super_data is not None + ): + bad(f'@{OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL} "{ordinal}" must name a field.int or ' + "field.long of the projection, with no origin and no extends.") + + +def _union_shape(f: MetaData) -> str: + """One field as a ``@union`` compares it: name, subtype, array-ness, ``@column``, and for + an enum its members and value maps (they are part of the column's meaning).""" + arr = "[]" if f.resolved_is_array() else "" + col = f.get_meta_attr(FIELD_ATTR_COLUMN) + enum_shape = "" if f.sub_type != FIELD_SUBTYPE_ENUM else " " + json.dumps([ + f.get_meta_attr(FIELD_ATTR_VALUES), + f.get_meta_attr(FIELD_ATTR_INT_VALUE_MAP), + f.get_meta_attr(FIELD_ATTR_STRING_VALUE_MAP), + ], sort_keys=True) + return f"{f.name}: field.{f.sub_type}{arr}" + (f" @column {col}" if isinstance(col, str) else "") + enum_shape + + def _validate_projection_filter( root: MetaData, errors: list[MetaError], diff --git a/server/python/src/metaobjects/meta/core/field/field_constants.py b/server/python/src/metaobjects/meta/core/field/field_constants.py index 9557a3cc22..48a2a28ba0 100644 --- a/server/python/src/metaobjects/meta/core/field/field_constants.py +++ b/server/python/src/metaobjects/meta/core/field/field_constants.py @@ -140,7 +140,9 @@ FIELD_ATTR_STORAGE = "storage" #: @storage "flattened": the nested object's columns expand into the parent table. STORAGE_FLATTENED = "flattened" -STORAGE_VALUES = (STORAGE_FLATTENED, "jsonb", "subdocument") +#: @storage "jsonb": the nested object (or array of them) is one JSON column. +STORAGE_JSONB = "jsonb" +STORAGE_VALUES = (STORAGE_FLATTENED, STORAGE_JSONB, "subdocument") # Physical column name override (cross-port; renamed from @dbColumn). FIELD_ATTR_COLUMN = "column" # @flattenedColumnPrefix on a field.object @storage "flattened": the text before each member's column, diff --git a/server/python/tests/conformance/conformance-expected-failures.json b/server/python/tests/conformance/conformance-expected-failures.json index 2672849cec..656792b04b 100644 --- a/server/python/tests/conformance/conformance-expected-failures.json +++ b/server/python/tests/conformance/conformance-expected-failures.json @@ -2,16 +2,12 @@ "language": "python", "fixtures": [ "error-origin-function-free-sql", - "error-projection-grain-not-object-array", - "error-projection-union-shape", "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", - "error-projection-grain-not-object-array": "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", - "error-projection-union-shape": "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" } } diff --git a/server/python/tests/loader/test_projection_union_and_grain.py b/server/python/tests/loader/test_projection_union_and_grain.py new file mode 100644 index 0000000000..3980afd4fe --- /dev/null +++ b/server/python/tests/loader/test_projection_union_and_grain.py @@ -0,0 +1,71 @@ +"""``@union`` and ``@grain`` projections are checked at load (rc.21 part B; plan row C3). + +The shared must-fail fixtures ``error-projection-union-shape`` and +``error-projection-grain-not-object-array`` hold the two headline refusals; these cases cover +the rest of the rule, mirroring the TypeScript ``validateProjectionUnionAndGrain``. +""" +from __future__ import annotations + +import json +from typing import Any + +import pytest + +from metaobjects import load_string +from metaobjects.errors import ErrorCode + +_CUSTOMER = {"object.entity": {"name": "Customer", "children": [ + {"source.rdb": {"@table": "customers"}}, + {"field.long": {"name": "id"}}, + {"field.string": {"name": "zip"}}, + {"field.object": {"name": "lines", "isArray": True, "@objectRef": "Line", "@storage": "jsonb"}}, + {"identity.primary": {"name": "id", "@fields": "id"}}, +]}} +_LINE = {"object.value": {"name": "Line", "children": [{"field.int": {"name": "qty"}}]}} + + +def _projection(name: str, attrs: dict[str, Any], fields: list[dict[str, Any]]) -> dict[str, Any]: + return {"object.projection": {"name": name, **attrs, "children": [ + {"source.rdb": {"@kind": "view", "@view": name.lower()}}, *fields]}} + + +_ID = {"field.long": {"name": "customerId", "extends": "Customer.id"}} + + +def _messages(*nodes: dict[str, Any]) -> list[str]: + result = load_string(json.dumps( + {"metadata.root": {"package": "acme::views", "children": [_LINE, _CUSTOMER, *nodes]}})) + return [e.message for e in result.errors if e.code is ErrorCode.ERR_BAD_ATTR_VALUE] + + +def test_a_union_of_the_same_shape_and_a_well_formed_grain_load_clean() -> None: + assert _messages( + _projection("B", {}, [_ID]), + _projection("U", {"@union": ["B"], "@unionAll": True}, [_ID]), + _projection("G", {"@grain": "lines", "@grainOrdinal": "n"}, + [_ID, {"field.int": {"name": "n"}}]), + ) == [] + + +@pytest.mark.parametrize( + ("nodes", "fragment"), + [ + ([_projection("U", {"@unionAll": True}, [_ID])], "@unionAll needs @union"), + ([_projection("U", {"@union": ["U"]}, [_ID])], "names the projection itself"), + ([_projection("U", {"@union": ["Customer"]}, [_ID])], 'names "Customer", which is not an object.projection'), + ( + [_projection("C", {}, [_ID]), _projection("B", {"@union": ["C"]}, [_ID]), + _projection("U", {"@union": ["B"]}, [_ID])], + 'member "B" declares its own @union', + ), + ([_projection("G", {"@grainOrdinal": "n"}, [_ID, {"field.int": {"name": "n"}}])], + "@grainOrdinal needs @grain"), + ([_projection("G", {"@grain": "lines", "@grainOrdinal": "n"}, + [_ID, {"field.string": {"name": "n"}}])], + '@grainOrdinal "n" must name a field.int or field.long'), + ([_projection("G", {"@grain": "zip"}, [_ID])], '@grain "zip" must name a field.object array'), + ], +) +def test_a_malformed_union_or_grain_is_refused(nodes: list[dict[str, Any]], fragment: str) -> None: + messages = _messages(*nodes) + assert any(fragment in m for m in messages), messages From 6fb85549e771f15030ea280c68f7e9af9968293a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:22:31 -0500 Subject: [PATCH 3/8] feat(python): write the entity model generator through the code writer (W-PY-2) The model modules, the shared enums module and the duration codec banner are built on a PyWriter and ruff no longer runs over them (ADR-0063). Checked against 1,561 modules generated from the repository's fixtures: 1,146 are byte-identical and the other 415 match once both versions get the same ruff import sort and format. PyWriter.gap() before the first body line now gives two blank lines after the imports, with a new py-gap-after-imports writer-conformance case. --- CHANGELOG.md | 17 + docs/ports/python.md | 10 +- .../cases/py-gap-after-imports.json | 24 + .../codegen/generators/entity_model.py | 505 +++++++++++------- .../metaobjects/codegen/writer/py_writer.py | 10 +- .../codegen/golden/scalars/expected/Report.py | 1 - .../codegen/layout_ratchet/allowlist.json | 1 - .../python/tests/codegen/test_entity_model.py | 12 +- spec/code-writer.md | 4 +- 9 files changed, 362 insertions(+), 222 deletions(-) create mode 100644 fixtures/writer-conformance/cases/py-gap-after-imports.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 62e9bd8be4..2e7876125f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,23 @@ here.** Python had none. `Renderer` now strips standalone comment lines before mustache.java parses them. A template with such a line renders differently in Java, so a prompt body with one changes bytes (and its prompt-cache prefix) on upgrade. The `render-standalone-*` fixtures pin the whitespace rules. +- **Python: the entity model generator writes through the code writer (ADR-0063).** The model + modules (`.py` with `Create` and `Patch`), the shared `enums.py` and the + `_duration_wire.py` banner are built on a `PyWriter`, and `ruff` no longer runs over them, so the + bytes no longer depend on whether `ruff` is installed. Over 1,561 model modules generated from the + repository's fixtures, 1,146 are byte-identical, and the other 415 match once both versions are + put through the same `ruff` import sort and format. What moves: the standard-library and + third-party imports share one section (no blank line between `import datetime` and + `from pydantic import ...`, the writer's import order); a `Field(...)` too long for its line puts + one keyword per line; and a `field.duration` annotation too long for its line breaks inside + `Annotated[...]`. `PyWriter.gap()` asked for before the first body line now gives the two blank + lines PEP 8 sets after the imports and before a top-level class (a new `py-gap-after-imports` + writer-conformance case). For subclasses of `EntityModelGenerator` (not a stability contract, + ADR-0063 item 7): `_emit_field_lines`, `_emit_create_lines` and `_emit_patch_lines` return writer + pieces without indentation (`"name: int | None = None"`) instead of indented strings, + `_emit_cross_field_rules` returns a step that writes the method onto the writer (or `None`) instead + of lines, a new `_write_model` writes one class, and `render_entity_model` returns the finished + module rather than text for `ruff` to tidy. - **Python: `@union` and `@grain` projections are checked at load.** A union member whose fields differ in name, subtype, array-ness, `@column` or enum shape, a member that is the projection itself or declares its own `@union`, `@unionAll` without `@union`, a `@grain` that does not name a diff --git a/docs/ports/python.md b/docs/ports/python.md index b9b07c341f..3d76e9c280 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -1056,10 +1056,12 @@ already have it. The `[email]` extra is needed as soon as any field carries generator types that field `EmailStr`, which imports `email-validator` when the class is defined. Without it the generated module fails at import, not at `gen`. -**Note on emitted output.** Both generators run `ruff_format(content)` on the -file before writing, so the literal emitted layout may reflow whitespace -slightly vs the snippets above. Function signatures, class definitions, and -import lines are stable. +**Note on emitted output.** The entity generator lays its modules out with the +Python code writer (ADR-0063); no formatter runs over them, so what is written does +not depend on whether `ruff` is installed. The output-parser generator still runs +`ruff_format(content)` on the file until it is converted, so its literal layout may +reflow whitespace slightly vs the snippets above. Function signatures, class +definitions, and import lines are stable. ## Capability snapshot diff --git a/fixtures/writer-conformance/cases/py-gap-after-imports.json b/fixtures/writer-conformance/cases/py-gap-after-imports.json new file mode 100644 index 0000000000..a819cc6a16 --- /dev/null +++ b/fixtures/writer-conformance/cases/py-gap-after-imports.json @@ -0,0 +1,24 @@ +{ + "description": "gap() asked for before the first body line puts two blank lines between the imports and the body, so a class or def right after the imports gets the two PEP 8 sets before a top-level definition; without it the sections stay one blank line apart.", + "dialect": "python", + "ops": [ + ["header", "# @generated by MetaObjects."], + ["use", "annotations", "__future__"], + ["use", "BaseModel", "pydantic"], + ["gap"], + ["open", "class A(BaseModel):"], + ["line", "x: int"], + ["dedent"] + ], + "expected": [ + "# @generated by MetaObjects.", + "", + "from __future__ import annotations", + "", + "from pydantic import BaseModel", + "", + "", + "class A(BaseModel):", + " x: int" + ] +} diff --git a/server/python/src/metaobjects/codegen/generators/entity_model.py b/server/python/src/metaobjects/codegen/generators/entity_model.py index 025d884a62..95da6944fa 100644 --- a/server/python/src/metaobjects/codegen/generators/entity_model.py +++ b/server/python/src/metaobjects/codegen/generators/entity_model.py @@ -10,6 +10,7 @@ from __future__ import annotations import re +from collections.abc import Callable from pathlib import Path from metaobjects.meta.core.field.meta_field import MetaField @@ -46,9 +47,9 @@ ) from metaobjects.shared.base_types import TYPE_ORIGIN, TYPE_VALIDATOR from metaobjects.codegen.config import GenConfig -from metaobjects.codegen.constants import GENERATED_MARKER, generated_header +from metaobjects.codegen.constants import GENERATED_MARKER, generated_header_lines from metaobjects.codegen.type_map import field_is_array, py_type_for -from metaobjects.codegen.format import ruff_format +from metaobjects.codegen.writer import CodeWriter, Piece, PyWriter, call, flat, group, str_lit from metaobjects.codegen.generator import EmittedFile, GenContext, Generator, per_entity from metaobjects.codegen.generators.tph_plan import tph_subtype_binding from metaobjects.codegen.import_path import ( @@ -98,10 +99,11 @@ def _is_int(value: object) -> bool: #: numbers, clock text and calendar spans, never sees a value; in JSON the canonical form is #: written (Pydantic writes ``PT5400S`` for 90 minutes). A Python-mode dump keeps the native #: ``timedelta``. -DURATION_TYPE = ( - "Annotated[datetime.timedelta, BeforeValidator(parse_duration_input), " - 'PlainSerializer(format_duration, return_type=str, when_used="json")]' -) +DURATION_TYPE: Piece = group("Annotated[", [ + "datetime.timedelta", + "BeforeValidator(parse_duration_input)", + 'PlainSerializer(format_duration, return_type=str, when_used="json")', +], "]") #: The generated package's copy of the duration codec, emitted beside the models when any of #: them has a ``field.duration`` (:func:`duration_wire_module`). A copy rather than an import of #: the installed ``metaobjects``, so the generated package runs on its own, as an owned router's @@ -131,10 +133,13 @@ def duration_wire_module() -> EmittedFile: """The ``_duration_wire.py`` module a model with a ``field.duration`` imports its codec from: ``codegen/runtime/duration_wire.py``, verbatim, under a generated header.""" src = _RUNTIME_SOURCE_DIR / "duration_wire.py" + banner = CodeWriter().line( + f"# {GENERATED_MARKER} — DO NOT EDIT. Copied from codegen/runtime/duration_wire.py: " + "edit that file and regenerate." + ) return EmittedFile( path=f"{DURATION_WIRE_MODULE}.py", - content=f"# {GENERATED_MARKER} — DO NOT EDIT. Copied from codegen/runtime/duration_wire.py: " - "edit that file and regenerate.\n" + src.read_text(encoding="utf-8"), + content=banner.to_string() + src.read_text(encoding="utf-8"), ) @@ -304,19 +309,48 @@ def _validator_constraints(field: MetaField, *, wire: bool) -> dict[str, object] def _constraint_parts(constraints: dict[str, object]) -> list[str]: - """The ``Field(...)`` constraint kwargs rendered in the stable, deterministic order.""" - return [_constraint_source(k, constraints[k]) for k in _CONSTRAINT_ORDER if k in constraints] + """The ``Field(...)`` constraint kwargs, one per keyword, in the stable order.""" + return [kw for k in _CONSTRAINT_ORDER if k in constraints for kw in _constraint_source(k, constraints[k])] -def _constraint_source(key: str, value: object) -> str: +def _constraint_source(key: str, value: object) -> list[str]: + """The keyword argument(s) one constraint becomes.""" if isinstance(value, _AsciiPattern): # json_schema_extra overrides the schema ``pattern`` (the compiled one carries the # Python-only ``\\Z`` anchor) with an ECMA-262-valid form for OpenAPI consumers. - return ( - f"{key}=re.compile({str(value)!r}, re.ASCII), " - f"json_schema_extra={{'pattern': {value.schema_pattern!r}}}" - ) - return f"{key}={value!r}" + return [ + f"{key}=re.compile({str_lit(str(value))}, re.ASCII)", + f"json_schema_extra={{{str_lit('pattern')}: {str_lit(value.schema_pattern)}}}", + ] + return [f"{key}={py_literal(value)}"] + + +def py_literal(value: object) -> str: + """*value* as Python source: strings double-quoted (:func:`str_lit`), lists and dicts + spelled item by item, anything else by ``repr``.""" + if isinstance(value, str): + return str_lit(str(value)) + if isinstance(value, list): + return "[" + ", ".join(py_literal(v) for v in value) + "]" + if isinstance(value, dict): + return "{" + ", ".join(f"{py_literal(k)}: {py_literal(v)}" for k, v in value.items()) + "}" + return repr(value) + + +def _member(name: str, annotation: Piece, value: Piece | None) -> Piece: + """A model member: ``name: annotation`` with its ``= value`` when it has one.""" + declaration = (f"{name}: ", annotation) + return declaration if value is None else (*declaration, " = ", value) + + +def _optional(type_expr: Piece) -> Piece: + return (type_expr, " | None") + + +def _field_call(parts: list[str], default: str | None = None) -> Piece: + """``Field(default=..., )``: one breakable list, so a member too long for the + line puts each keyword on its own line.""" + return call("Field", parts if default is None else [f"default={default}", *parts]) def _type_expr_for_field( @@ -326,8 +360,8 @@ def _type_expr_for_field( *, wire: bool, scope: ModuleScope = ModuleScope(), -) -> tuple[str, str | None]: - """The Python annotation text for *field* (arrays wrapped in ``list[...]``) plus the +) -> tuple[Piece, str | None]: + """The Python annotation for *field* (arrays wrapped in ``list[...]``) plus the shared-enum class name when the field resolves to one (used to render an enum default). Collects any required imports into *imports*. Shared by the create-model and patch-model emitters so both carry byte-identical typing. @@ -350,6 +384,7 @@ def _type_expr_for_field( else None ) enum_type_name: str | None = None + type_expr: Piece if shared is not None: type_name, enum_import = fr019.enum_type_and_import(shared, config, scope) imports.add(enum_import) @@ -371,13 +406,14 @@ def _type_expr_for_field( if field.sub_type == fc.FIELD_SUBTYPE_DURATION: # `wire.durations: native` leaves Pydantic's own timedelta handling in place, both ways; # `iso` holds the field to the ISO-8601 wire rule. + duration_type: Piece if wire_of(field).durations == WIRE_DURATIONS_ISO: imports.update(duration_imports(scope)) duration_type = DURATION_TYPE else: imports.add("import datetime") duration_type = "datetime.timedelta" - type_expr = f"list[{duration_type}]" if field_is_array(field) else duration_type + type_expr = ("list[", duration_type, "]") if field_is_array(field) else duration_type if field.sub_type in (fc.FIELD_SUBTYPE_OBJECT, fc.FIELD_SUBTYPE_MAP): # A field.object (-> VO) and a field.map with @objectRef (-> dict[str, VO]) both # reference a value-object; import its model so the emitted annotation resolves. @@ -419,36 +455,21 @@ def origin_guaranteed_non_null(field: MetaField) -> bool: return False -def _with_type_checking(imports: list[str]) -> list[str]: - """Add ``TYPE_CHECKING`` to the emitted ``typing`` import. - - Folded into the existing ``from typing import ...`` when there is one, rather than - emitted as a second line from the same module — two imports of one module is - something every linter in the ecosystem flags, and generated code an adopter has to - silence is generated code they stop trusting. - """ - for i, imp in enumerate(imports): - if imp.startswith("from typing import "): - names = sorted({*imp[len("from typing import ") :].split(", "), "TYPE_CHECKING"}) - return [*imports[:i], f"from typing import {', '.join(names)}", *imports[i + 1 :]] - return sorted([*imports, "from typing import TYPE_CHECKING"]) - - def _literal_default_expr(field: MetaField, enum_type_name: str | None) -> str: """The Python source of a literal @default: the list an array default spells, an enum member (Type.MEMBER, UPPER_CASE), or the value's own literal.""" default_raw = field.attrs().get(fc.FIELD_ATTR_DEFAULT) if field_is_array(field): - return repr(array_default(field)) + return py_literal(array_default(field)) if enum_type_name is not None: return f"{enum_type_name}.{str(default_raw).upper()}" - return repr(default_raw) + return py_literal(default_raw) def _field_line( field: MetaField, imports: set[str], config: GenConfig, scope: ModuleScope = ModuleScope() -) -> tuple[str, bool]: - """Return (source line, uses_field). Collects required imports into *imports*.""" +) -> tuple[Piece, bool]: + """Return (member, uses_field). Collects required imports into *imports*.""" type_expr, enum_type_name = _type_expr_for_field(field, imports, config, wire=False, scope=scope) required = field.attrs().get(fc.FIELD_ATTR_REQUIRED) is True # A server-side expression default (now(), gen_random_uuid(), CURRENT_TIMESTAMP) @@ -467,19 +488,20 @@ def _field_line( # origin.computed stay the conservative nullable default. mandatory = required or origin_guaranteed_non_null(field) # A field is Optional only when it is neither mandatory nor carries a @default. - annotation = type_expr if (mandatory or has_default) else f"{type_expr} | None" + annotation = type_expr if (mandatory or has_default) else _optional(type_expr) + value: Piece | None if has_default and uses_field: - assignment = f" = Field(default={default_expr}, {', '.join(parts)})" + value = _field_call(parts, default_expr) elif has_default: - assignment = f" = {default_expr}" + value = default_expr elif mandatory and uses_field: - assignment = f" = Field({', '.join(parts)})" + value = _field_call(parts) elif mandatory: - assignment = "" + value = None elif uses_field: - assignment = f" = Field(default=None, {', '.join(parts)})" + value = _field_call(parts, "None") else: - assignment = " = None" + value = "None" # Pydantic field name = field.name, ALWAYS. `@column` is the physical column name, # a different axis: it is what the persistence layer binds to, never what the model @@ -494,7 +516,7 @@ def _field_line( # lever for it: `columnNamingStrategy` applied to field.name is, because @column is # free-form — `callPurpose` + `@column: purpose_code` used to emit a field # `purpose_code`, which is neither the wire name nor derived from the field name. - return f" {field.name}: {annotation}{assignment}", uses_field + return _member(field.name, annotation, value), uses_field def _primary_identity_field_names(entity: MetaObject) -> list[str]: @@ -608,8 +630,8 @@ def _equals_literal(raw: object, when_field: MetaField, imports: set[str]) -> st return repr(float(text)) if sub in _DECIMAL_SUBTYPES and _NUMERIC_LITERAL.match(text): imports.add("from decimal import Decimal") - return f"Decimal({text!r})" - return repr(text) + return f"Decimal({str_lit(text)})" + return str_lit(text) # --- @condition: a rule is checked only where its condition is TRUE ----------- @@ -617,25 +639,37 @@ def _equals_literal(raw: object, when_field: MetaField, imports: set[str]) -> st # three-valued logic) lets the record through. The condition is generated as a small Python # expression of type ``bool | None`` (``None`` is SQL NULL); the helpers below are declared # inside the generated method, so the generated model imports nothing from MetaObjects. -_HELPER_CMP = ( - " def _cmp(a: object, b: object) -> int | None:\n" - " if a is None or b is None:\n" - " return None\n" - " try:\n" - " return (a > b) - (a < b) # type: ignore[operator]\n" - " except TypeError:\n" - " return None\n" -) -_HELPER_TRI = ( - " def _all(*v: bool | None) -> bool | None:\n" - " return False if False in v else None if None in v else True\n" - "\n" - " def _any(*v: bool | None) -> bool | None:\n" - " return True if True in v else None if None in v else False\n" - "\n" - " def _not(v: bool | None) -> bool | None:\n" - " return None if v is None else not v\n" -) +#: A piece of the generated model written straight onto the writer. +WriteStep = Callable[[PyWriter], None] + + +def _write_helper_cmp(w: PyWriter) -> None: + w.text(""" + def _cmp(a: object, b: object) -> int | None: + if a is None or b is None: + return None + try: + return (a > b) - (a < b) # type: ignore[operator] + except TypeError: + return None + """) + + +def _write_helper_tri(w: PyWriter) -> None: + w.text(""" + def _all(*v: bool | None) -> bool | None: + return False if False in v else None if None in v else True + + def _any(*v: bool | None) -> bool | None: + return True if True in v else None if None in v else False + + def _not(v: bool | None) -> bool | None: + return None if v is None else not v + """) + + +_HELPER_CMP: WriteStep = _write_helper_cmp +_HELPER_TRI: WriteStep = _write_helper_tri _CONDITION_HELPERS = (_HELPER_CMP, _HELPER_TRI) _NUMERIC_SUBTYPES = (*_INT_SUBTYPES, *_FLOAT_SUBTYPES, *_DECIMAL_SUBTYPES) EXPR_OP_IS_NULL, EXPR_OP_AND, EXPR_OP_OR = "isNull", "and", "or" @@ -682,7 +716,7 @@ class _ConditionBuilder: def __init__(self, by_name: dict[str, MetaField], imports: set[str]) -> None: self.by_name = by_name self.imports = imports - self.helpers: set[str] = set() + self.helpers: set[WriteStep] = set() def _node_field(self, node: object) -> MetaField | None: if not isinstance(node, dict): @@ -728,8 +762,8 @@ def _literal(self, value: object, kind: str, field: MetaField | None) -> str | N parser = _TEMPORAL_PARSERS.get(field.sub_type) if parser is not None: self.imports.add("import datetime") - return f"{parser}({value!r})" - return repr(value) + return f"{parser}({str_lit(value)})" + return py_literal(value) def value(self, node: object, kind: str, ref: MetaField | None) -> str | None: if not isinstance(node, dict): @@ -788,17 +822,45 @@ def condition(self, node: object) -> str | None: return None +def _raise_if(condition: str, label: str) -> WriteStep: + """``if : raise ValueError(