Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
Stop four wrap serializers from erasing their serialization JSON Schema (#1159)
Louis Choquele3432c3dda0f
diff --git a/.claude/skills/bump-mthds/SKILL.md b/.claude/skills/bump-mthds/SKILL.mdindex 8455a961f..fdc104b07 100644--- a/.claude/skills/bump-mthds/SKILL.md+++ b/.claude/skills/bump-mthds/SKILL.md@@ -1,13 +1,13 @@---name: bump-mthdsdescription: >- Move this repo's `mthds` dependency floor to the latest release on PyPI (or a- version you name), re-lock, adapt the engine source to whatever the new+ Move this repo's exact `mthds` dependency pin to the latest release on PyPI+ (or a version you name), re-lock, adapt the engine source to whatever the newrelease broke, run the checks, and write the CHANGELOG entry — stopping beforethe commit. Use whenever the user says "bump mthds", "update mthds", "upgrademthds", "move to mthds 0.10.0", "get us on the latest mthds", "is our mthds- floor stale", "what's the latest mthds", or asks to build against a newly- published `mthds` release. Also use when a failure looks like an mthds+ pin stale", "is our mthds floor stale", "what's the latest mthds", or asks to+ build against a newly published `mthds` release. Also use when a failure looks like an mthdsversion mismatch — a pyright `reportAttributeAccessIssue` on something under`mthds.protocol`, an ImportError for a name that used to be there, a pydantic`Extra inputs are not permitted` from a protocol model, or a `uv lock` saying@@ -31,7 +31,7 @@ dependency: an upstream rename is not an internal detail this repo absorbs, itis a **breaking change to pipelex's own API**, and it has to reach the changelogas one.-The job is to land the new floor in a state a human can read and commit: floor+The job is to land the new pin in a state a human can read and commit: pinmoved, lock regenerated, source adapted, checks green, changelog written, ledgersquared. **Stop before committing** — the user stages and commits.@@ -39,29 +39,38 @@ squared. **Stop before committing** — the user stages and commits.| File | Why it moves ||---|---|-| `pyproject.toml` | The floor itself, one line in `[project].dependencies` — `mthds>=X.Y.Z` |+| `pyproject.toml` | The pin itself, one line in `[project].dependencies` — `mthds==X.Y.Z` || `uv.lock` | Regenerated by `make li` || `pipelex/**` | Wherever the new release renamed, split, or tightened something this engine imports || `tests/**` | Same, plus any test asserting on a shape that moved |-| `CHANGELOG.md` | An entry under `## [Unreleased]` — always at least the floor line |+| `CHANGELOG.md` | An entry under `## [Unreleased]` — always at least the pin line || `.badges/tests.json`, `.test_durations` | Only if the adaptation added, removed or renamed tests |Do **not** touch `[project].version`. That is this package's own version and itmoves only at release time, via the `release` skill.-## The floor is a floor, and it always tracks latest--The pin is `mthds>=X.Y.Z`, not `==`. pipelex is a published library, so the floor-is a statement to *its* consumers about the minimum they must have.--**The standing policy is to raise the floor to the latest release, every time**,-even when the new release carries nothing this engine uses. Keeping the floor in-lockstep with the lock means the version this repo tests against is the version-it demands, with no gap for a consumer to fall into. The cost is real and worth-naming when you report: everyone downstream — `pipelex-sdk-python`,-`pipelex-server`, every user install — is forced onto that `mthds` too. Say so-in the changelog when the bump is otherwise uneventful, because for a consumer-"pipelex now requires mthds 0.10.0" *is* the change.+## The pin is exact, and it always tracks latest++The pin is `mthds==X.Y.Z`, not `>=`. That is deliberate and it is newer than it+looks — the dependency was a `>=` floor until v0.54.0, which moved it to an+exact pin and recorded the move as a breaking change. **Never relax it back to+`>=` while bumping**, and never widen it to get a resolve unstuck.++The reason is what this engine does with mthds: it re-exports mthds' wire models+as part of pipelex's own public surface, so a consumer resolving a different+mthds would be handed one version's classes through the `__all__` of a pipelex+built against another — `isinstance` narrowing over a protocol union failing in+a way no version specifier explains. An exact pin makes the version this repo+tests against the version it demands, with no gap for a consumer to fall into.++**The standing policy is to move the pin to the latest release, every time**,+even when the new release carries nothing this engine uses. The cost is real and+worth naming when you report: everyone downstream — `pipelex-sdk-python`,+`pipelex-server`, every user install — is forced onto that exact `mthds`, and a+consumer that also depends on `mthds` directly must now move in step with+pipelex rather than resolving its own. Say so in the changelog when the bump is+otherwise uneventful, because for a consumer "pipelex now requires mthds+0.11.2" *is* the change.## Three numbers, none of which is the others@@ -82,17 +91,18 @@ in the upstream notes against this table before repeating it in ours.### 1. Orient-Read the floor **from `pyproject.toml`**, not from the virtualenv:+Read the pin **from `pyproject.toml`**, not from the virtualenv:```bashgrep -n '"mthds' pyproject.toml.venv/bin/python -c "import importlib.metadata as m; print(m.version('mthds'))"```-They disagree more often than you would think, and each disagreement means-something different. The venv ahead of the floor is normal — the floor is a-minimum. The venv *behind* the floor means someone edited `pyproject.toml`-without re-running `make li`.+Under an exact pin these two should agree, in both directions — unlike a floor,+where a venv running ahead was normal. Any disagreement means the venv is stale:+someone edited `pyproject.toml` without re-running `make li`, or installed+something over it. Re-sync with `make li` before you measure anything against+the venv.Check `git status` and note what was already dirty **before** you start.Concurrent work in this worktree is normal, and at the end you need to separate@@ -126,16 +136,16 @@ curl -s https://pypi.org/pypi/mthds/json \````info.version` is the latest non-prerelease, which is what "latest" means for a-floor other people inherit.+pin other people inherit exactly.**Ask PyPI, never the sibling checkout.** `mthds-python/pyproject.toml` is aworking tree and is frequently *ahead* of what has been published — a version-sitting there under `## [Unreleased]` is not installable, and a floor naming it+sitting there under `## [Unreleased]` is not installable, and a pin naming itmakes `uv lock` fail. If you notice the sibling is ahead, that is worthmentioning in your report (it is a preview of the next bump) but it does notchange the target.-If the resolved version equals the current floor, say so and stop: there is+If the resolved version equals the current pin, say so and stop: there isnothing to do, and manufacturing lock churn is worse than reporting "alreadycurrent". If the venv disagrees, mention that — `make li` is the real fix there.@@ -151,7 +161,7 @@ cascade into a set of expected edits:```The helper reads `../mthds-python/CHANGELOG.md` and prints the released sections-strictly after the old floor up to and including the new one. It skips+strictly after the old pin up to and including the new one. It skips`## [Unreleased]` — that section describes work that is *not* in the version youare adopting, and this repo's changelog is read by people deciding whether anupgrade will break them. If the checkout predates the target release the script@@ -166,10 +176,11 @@ imports, parse-time tightening (mthds models are `extra="forbid"`, so a shapethis engine constructs can start failing at construction), and any move of`MTHDS_STANDARD_VERSION`.-### 4. Move the floor+### 4. Move the pin-One line in `pyproject.toml`. Make it a substring edit — replace `>=0.9.0` with-`>=0.10.0` on that line and leave every other character alone. Use your editor+One line in `pyproject.toml`. Make it a substring edit — replace `==0.11.1` with+`==0.11.2` on that line, **keeping the `==`**, and leave every other character+alone. Use your editorrather than a shell one-liner: `sed -i` takes a separate empty argument on macOSand an attached suffix on GNU/Linux, so no single invocation is portable, andthe `release` skill edits this same file the same way.@@ -188,10 +199,10 @@ downstream of here depends on.**Do not reach for `make update`.** That is `uv lock --upgrade` and it movesevery dependency in the tree at once, which turns a reviewable one-package bump-into a diff nobody can reason about. Raising the floor is already enough to make-plain `uv lock` re-resolve mthds upward.+into a diff nobody can reason about. Moving the pin is already enough to make+plain `uv lock` re-resolve mthds.-Check the lock actually moved — a floor edit that didn't take is silent:+Check the lock actually moved — a pin edit that didn't take is silent:```bashgrep -A1 '^name = "mthds"' uv.lock@@ -201,8 +212,10 @@ If `uv lock` reports the requirement is unsatisfiable, the version is almostcertainly not on PyPI yet. Re-run the query from step 2. If it genuinely isn'tpublished, stop and tell the user rather than inventing a git or path source:adding one is a deliberate decision with a real cost (in uv, a *source* outranks-a version specifier, so the floor you wrote becomes decorative), not a-workaround to apply quietly.+a version specifier, so the pin you wrote becomes decorative), not a workaround+to apply quietly. An exact pin can also be reported unsatisfiable because+another member of the resolve wants a different mthds — widening this pin is not+the fix, moving the other requirement is.### 6. Check whether `MTHDS_STANDARD_VERSION` moved@@ -292,12 +305,13 @@ Add to `CHANGELOG.md` under `## [Unreleased]`, creating that heading right afterrelease cuts it into a version heading — do not add a `## [vX.Y.Z]` headingyourself, and do not bump `[project].version`.-Every bump gets at least the floor line. Follow the house form, which names the+Every bump gets at least the pin line. Follow the house form, which names therelease *by what it carries*:```markdown-- **Minimum `mthds` version**: The floor moves to `mthds>=0.10.0`, <the release- that carries / the release fixing …>.+- **`mthds` version**: The pin moves to `mthds==0.11.2`, <the release that+ carries / the release fixing …>. Everyone downstream inherits that exact+ version.```Anything that reached pipelex's own surface gets its own entry under@@ -315,11 +329,15 @@ ones harder to spot.- **Close what you actually landed**, with evidence — the file and line youchanged, and the check that went green. `Closes <id>` goes in the PR body whenthe user opens one.-- **File the cascade.** A breaking bump here does not stay here.- `pipelex-sdk-python` declares its own `mthds` floor, and `pipelex-server` pins- `pipelex` exactly at several sites. Neither is yours to edit from this repo:- file it (`ledger new --owner <repo> …`) with the symbol that moved and the- version that moved it. The `ledger` skill has the full gesture.+- **File the cascade, and note that the exact pin makes it sharper.**+ `pipelex-sdk-python` pins `mthds` exactly too, and `pipelex-server` pins+ `pipelex` exactly at several sites — so any bump here, breaking or not, puts+ a consumer that installs both this package and `pipelex-sdk-python` into an+ unsatisfiable resolve until that repo moves to the same version. Check where+ it stands (`grep mthds ../pipelex-sdk-python/pyproject.toml`) and say so in+ your report. Neither repo is yours to edit from here: file it+ (`ledger new --owner <repo> …`) with the version that moved and, when there+ was one, the symbol. The `ledger` skill has the full gesture.- **File the reverse direction if you moved the wire.** `mthds-python` commitsprotocol parity fixtures captured *from this engine*, so a change here thatalters emitted output means those fixtures need recapturing — an item owned by@@ -330,7 +348,7 @@ ones harder to spot.Show the user:-- The floor move, old → new, and whether `uv.lock` actually followed.+- The pin move, old → new, and whether `uv.lock` actually followed.- Whether `MTHDS_STANDARD_VERSION` moved, and what that changes for users.- Every file you changed, separated from what was already dirty when you started.- The check results, honestly — if `agent-test` failed, say so with the output@@ -348,13 +366,16 @@ and PRs target `dev`.## Traps worth remembering-- **The floor is not the lock.** Because `>=` already admits newer releases, a- fresh resolve can pull a new mthds into someone's environment with nobody- bumping anything. That is exactly why this bump is done deliberately, and why- step 5 verifies the lock actually moved.+- **Nothing in this repo enforces the `==`.** No check fails if the pin is+ relaxed to `>=`; `pyproject.toml` is the only place the policy is written, and+ the changelog is where it was announced. A widened pin ships silently.+- **The pin is not the lock.** Editing `pyproject.toml` without re-locking+ leaves `uv.lock` on the old version, which is what the venv and the suite+ actually use — a green run against the version you meant to leave behind.+ That is why step 5 verifies the lock actually moved.- **The sibling checkout is routinely ahead of PyPI.** Read `mthds-python`'s- changelog for *understanding*, PyPI for *the target version*. A floor naming- an unpublished version fails `uv lock`.+ changelog for *understanding*, PyPI for *the target version*. A pin naming an+ unpublished version fails `uv lock`.- **`## [Unreleased]` upstream is not in the version you adopted.** Never quoteit as part of the release. The helper script skips it for you.- **`MTHDS_STANDARD_VERSION` moves silently.** Nothing pins it; the suitediff --git a/.claude/skills/bump-mthds/scripts/upstream_notes.py b/.claude/skills/bump-mthds/scripts/upstream_notes.pyindex f7895e515..ab6c1e93a 100755--- a/.claude/skills/bump-mthds/scripts/upstream_notes.py+++ b/.claude/skills/bump-mthds/scripts/upstream_notes.py@@ -12,7 +12,7 @@ Three boundaries this exists to get right:error about what the upgrade contains -- and in this pairing it is a livehazard rather than a theoretical one, because `mthds-python`'s working tree isroutinely ahead of PyPI.-- The old floor's own section is excluded (it was already in effect) while the+- The old pin's own section is excluded (it was already in effect) while thenew one's is included.- A checkout that predates the target release cannot answer, and says so insteadof printing a plausible-looking short range.@@ -81,7 +81,7 @@ def split_sections(text: str) -> list[tuple[str, str]]:def main() -> int:parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)- parser.add_argument("old_version", help="the floor currently declared, excluded from the output")+ parser.add_argument("old_version", help="the version currently pinned, excluded from the output")parser.add_argument("new_version", help="the version being adopted, included in the output")parser.add_argument("--changelog",@@ -122,7 +122,7 @@ def main() -> int:print("\n\n".join(body for _, body in wanted))if low not in known:print(- f"\nNote: no section for the old floor {args.old_version} in this checkout, so the range may start earlier than the true gap.",+ f"\nNote: no section for the old pin {args.old_version} in this checkout, so the range may start earlier than the true gap.",file=sys.stderr,)return 0diff --git a/AGENTS.md b/AGENTS.mdindex ecee6cb0b..4fe056dae 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -210,6 +210,8 @@- Use Field(default_factory=...) for mutable defaults- Use `# pyright: ignore[specificError]` or `# type: ignore` only as a last resort. In particular, if you are sure about the type, you often solve issues by using cast() or creating a new typed variable.+One scoped exception to "every function return must be typed": a pydantic `@model_serializer` / `@field_serializer` return must stay **unannotated** unless the annotation is the exact type the model publishes. Pydantic turns a serializer's return annotation into the model's serialization JSON Schema and prefers it over the schema it would generate, so a `-> dict[str, Any]` publishes the whole model as an opaque `{"type": "object", "additionalProperties": true}` — no properties, no `required`, no closed shape — for every consumer that generates response schemas, which FastAPI always does for its responses. A precise annotation is fine and desirable (`-> str` on a model that serializes to its raw string); a `dict`/`Any` one erases the model, and nothing in a normal test suite notices because validation-mode schemas and `model_dump()` both stay correct.+#### Data-holder shapes (NamedTuple, dataclass, BaseModel)The deciding question is **does this value ever get serialized** — sent across a process or network boundary, persisted to disk or a database, or round-tripped through (de)serialization? If yes, it must be one of the two serialization-safe forms (a `BaseModel` or a pydantic dataclass): a `NamedTuple` or stdlib `@dataclass` loses its type on the way through and silently corrupts the data across the boundary. (A distributed executor like Temporal is the canonical case — its payloads cross the wire between worker processes — but the same applies to any cache, queue, API response, or on-disk record.) Stdlib `@dataclass` is banned outright; pick one of these four forms:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f6d14b915..6986ee052 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,11 @@# Changelog+## [Unreleased]++### Fixed++- **Blueprint serialization schemas**: `ConceptBlueprint`, `ConceptStructureBlueprint`, `InputSlotBlueprint` and `ConstructBlueprint` publish their real shape again in serialization mode. Each carries a `@model_serializer(mode="wrap")` annotated `-> dict[str, Any]`, and pydantic turns a serializer's return annotation into the model's serialization JSON Schema in preference to the one it would generate — so all four came back as an opaque `{"type": "object", "additionalProperties": true}` with no properties, no `required` and no closed shape. This is the same annotation `mthds` 0.11.1 dropped for the input-form field descriptors. Nothing here noticed, because validation-mode schemas and `model_dump()` were both correct throughout; the damage landed in consumers that generate response-model schemas, which FastAPI always does, so a downstream OpenAPI artifact regains its field-level detail on its next `pipelex` bump. A new sweep test holds every Pipelex model to the rule, and the agent rules now scope "every function return must be typed" so a serializer's return stays unannotated.+## [v0.54.0] - 2026-08-28### Addeddiff --git a/pipelex/core/concepts/concept_blueprint.py b/pipelex/core/concepts/concept_blueprint.pyindex 2ba1c9bd8..707fbbc79 100644--- a/pipelex/core/concepts/concept_blueprint.py+++ b/pipelex/core/concepts/concept_blueprint.py@@ -31,11 +31,17 @@ class ConceptBlueprint(BaseModel):return dict(sorted(hints.items())) if hints else None@model_serializer(mode="wrap")- def serialize_without_absent_hints(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:+ def serialize_without_absent_hints(self, handler: SerializerFunctionWrapHandler):"""Absent hints are an absent member — never `null` (spec rule; keeps hint-free cratefingerprints byte-identical to before hints existed). Deliberately NOT a blanket`exclude_none`: the crate spec's general absent-members canonicalization is a separateforward contract whose adoption would migrate every existing fingerprint.++ The return is deliberately unannotated, and stays that way. Pydantic turns a serializer's+ return annotation into the model's serialization JSON Schema and prefers it over the schema+ it would generate, so a `-> dict[str, Any]` here publishes this model as an opaque+ `{"type": "object", "additionalProperties": true}` — no properties, no `required`, no+ closed shape — for every consumer that generates response schemas (FastAPI always does)."""dumped: dict[str, Any] = handler(self)if dumped.get("hints") is None:diff --git a/pipelex/core/concepts/concept_structure_blueprint.py b/pipelex/core/concepts/concept_structure_blueprint.pyindex b2f3f1df0..7638ac1b6 100644--- a/pipelex/core/concepts/concept_structure_blueprint.py+++ b/pipelex/core/concepts/concept_structure_blueprint.py@@ -82,9 +82,12 @@ class ConceptStructureBlueprint(BaseModel):return dict(sorted(hints.items())) if hints else None@model_serializer(mode="wrap")- def serialize_without_absent_hints(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:+ def serialize_without_absent_hints(self, handler: SerializerFunctionWrapHandler):"""Absent hints are an absent member — never `null` (spec rule; keeps hint-free cratefingerprints byte-identical to before hints existed).++ The return is deliberately unannotated — see `ConceptBlueprint.serialize_without_absent_hints`:+ an annotation here becomes the model's serialization JSON Schema and erases its shape."""dumped: dict[str, Any] = handler(self)if dumped.get("hints") is None:diff --git a/pipelex/kit/agent_rules/python_standards.md b/pipelex/kit/agent_rules/python_standards.mdindex a173c81c6..12e040f67 100644--- a/pipelex/kit/agent_rules/python_standards.md+++ b/pipelex/kit/agent_rules/python_standards.md@@ -95,6 +95,8 @@- Use Field(default_factory=...) for mutable defaults- Use `# pyright: ignore[specificError]` or `# type: ignore` only as a last resort. In particular, if you are sure about the type, you often solve issues by using cast() or creating a new typed variable.+One scoped exception to "every function return must be typed": a pydantic `@model_serializer` / `@field_serializer` return must stay **unannotated** unless the annotation is the exact type the model publishes. Pydantic turns a serializer's return annotation into the model's serialization JSON Schema and prefers it over the schema it would generate, so a `-> dict[str, Any]` publishes the whole model as an opaque `{"type": "object", "additionalProperties": true}` — no properties, no `required`, no closed shape — for every consumer that generates response schemas, which FastAPI always does for its responses. A precise annotation is fine and desirable (`-> str` on a model that serializes to its raw string); a `dict`/`Any` one erases the model, and nothing in a normal test suite notices because validation-mode schemas and `model_dump()` both stay correct.+### Data-holder shapes (NamedTuple, dataclass, BaseModel)The deciding question is **does this value ever get serialized** — sent across a process or network boundary, persisted to disk or a database, or round-tripped through (de)serialization? If yes, it must be one of the two serialization-safe forms (a `BaseModel` or a pydantic dataclass): a `NamedTuple` or stdlib `@dataclass` loses its type on the way through and silently corrupts the data across the boundary. (A distributed executor like Temporal is the canonical case — its payloads cross the wire between worker processes — but the same applies to any cache, queue, API response, or on-disk record.) Stdlib `@dataclass` is banned outright; pick one of these four forms:diff --git a/pipelex/pipe_machinery/pipe_blueprint.py b/pipelex/pipe_machinery/pipe_blueprint.pyindex 8238b8ba9..30483c2ff 100644--- a/pipelex/pipe_machinery/pipe_blueprint.py+++ b/pipelex/pipe_machinery/pipe_blueprint.py@@ -205,10 +205,13 @@ class InputSlotBlueprint(BaseModel):return dict(sorted(hints.items())) if hints else None@model_serializer(mode="wrap")- def serialize_without_absent_hints(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:+ def serialize_without_absent_hints(self, handler: SerializerFunctionWrapHandler):"""Absent hints are an absent member — never `null` (spec rule). Unreachable for ahint-free slot in practice (the parse-time collapse leaves it a plain string), kept so anydirectly-constructed instance still serializes canonically.++ The return is deliberately unannotated — see `ConceptBlueprint.serialize_without_absent_hints`:+ an annotation here becomes the model's serialization JSON Schema and erases its shape."""dumped: dict[str, Any] = handler(self)if dumped.get("hints") is None:diff --git a/pipelex/pipe_operators/compose/construct_blueprint.py b/pipelex/pipe_operators/compose/construct_blueprint.pyindex b5b9e643e..b0d63a745 100644--- a/pipelex/pipe_operators/compose/construct_blueprint.py+++ b/pipelex/pipe_operators/compose/construct_blueprint.py@@ -279,11 +279,14 @@ class ConstructBlueprint(BaseModel):return {field_name: field_bp.to_mthds_dict() for field_name, field_bp in self.fields.items()}@model_serializer(mode="wrap")- def serialize_with_context(self, handler: SerializerFunctionWrapHandler, info: SerializationInfo) -> dict[str, Any]:+ def serialize_with_context(self, handler: SerializerFunctionWrapHandler, info: SerializationInfo):"""Serialize with format-aware context.When context contains {"format": "mthds"}, outputs MTHDS-format dict.Otherwise, uses default Pydantic serialization.++ The return is deliberately unannotated — see `ConceptBlueprint.serialize_without_absent_hints`:+ an annotation here becomes the model's serialization JSON Schema and erases its shape."""if info.context and info.context.get("format") == "mthds":return self.to_mthds_dict()diff --git a/tests/unit/pipelex/test_serialization_json_schema.py b/tests/unit/pipelex/test_serialization_json_schema.pynew file mode 100644index 000000000..4d38f097c--- /dev/null+++ b/tests/unit/pipelex/test_serialization_json_schema.py@@ -0,0 +1,193 @@+"""No Pipelex model publishes an opaque serialization JSON Schema.++Pydantic derives a model's *serialization* schema from its `@model_serializer`'s return+annotation and prefers it over the schema it would generate. A `-> dict[str, Any]` therefore+replaces the real shape with `{"type": "object", "additionalProperties": true}` — no properties,+no `required`, no closed shape — while validation-mode schemas stay complete and every runtime+`model_dump()` keeps working. Nothing in this repo notices: the suite is green, and no call to+`model_json_schema()` in `pipelex/` asks for serialization mode (the MTHDS schema generator asks+for `mode="validation"` explicitly). The damage lands one repo away, in a consumer that generates+response-model schemas — FastAPI always does — where a whole blueprint reaches clients as an+opaque object and a client generator produces nothing useful from it.++The bug class already recurred: it hit four models here and the input-form field descriptors+upstream in `mthds`. Hence a sweep rather than four hand-written assertions — the next model to+grow a wrap serializer is caught the day it is written, not the next time a consumer regenerates+an artifact.+"""++from __future__ import annotations++import importlib+import pkgutil+from typing import Any, cast++import pytest+from pydantic import BaseModel+from pydantic.errors import PydanticInvalidForJsonSchema++import pipelex+from pipelex.core.concepts.concept_blueprint import ConceptBlueprint+from pipelex.core.concepts.concept_structure_blueprint import ConceptStructureBlueprint+from pipelex.pipe_machinery.pipe_blueprint import InputSlotBlueprint+from pipelex.pipe_operators.compose.construct_blueprint import ConstructBlueprint++# The models that carry a `@model_serializer(mode="wrap")` and once published nothing because of it.+WRAP_SERIALIZER_MODELS = [+ ConceptBlueprint,+ ConceptStructureBlueprint,+ InputSlotBlueprint,+ ConstructBlueprint,+]++# `FuncRegistry` holds live callables, which have no JSON Schema at all — pydantic refuses to build+# one. Pinned by name rather than skipped silently: a model that newly stops being describable drops+# out of the sweep, and this is what makes that visible instead of quietly shrinking the guard.+MODELS_WITHOUT_A_JSON_SCHEMA = {+ "pipelex.system.registries.func_registry.FuncRegistry",+}++REMEDY = (+ "Drop the return annotation from the model's `@model_serializer` — pydantic turns it into the "+ "model's serialization JSON Schema and prefers it over the generated one."+)+++def _import_every_pipelex_module() -> int:+ """Import every `pipelex.*` module and return how many loaded.++ Nothing is caught. A module that fails to import takes the sweep down with its own traceback,+ which is the root cause; recording it as a string and carrying on would both discard that+ traceback and leave the sweep running over a partially imported package — a guard gone quiet+ exactly where the tree got interesting.+ """+ imported = 0+ for module_info in pkgutil.walk_packages(pipelex.__path__, prefix=f"{pipelex.__name__}."):+ importlib.import_module(module_info.name)+ imported += 1+ return imported+++def _discover_pipelex_models() -> list[type[BaseModel]]:+ """Every `BaseModel` subclass declared under `pipelex.`, after loading the whole package."""+ _import_every_pipelex_module()++ seen: set[type[BaseModel]] = set()++ def walk(cls: type[BaseModel]) -> None:+ for sub in cls.__subclasses__():+ if sub not in seen:+ seen.add(sub)+ walk(sub)++ walk(BaseModel)+ models = [cls for cls in seen if cls.__module__.startswith(f"{pipelex.__name__}.")]+ return sorted(models, key=lambda cls: f"{cls.__module__}.{cls.__qualname__}")+++def _resolve_root(schema: dict[str, Any]) -> dict[str, Any]:+ """Follow a top-level `$ref` into `$defs`.++ A self-referential model (`ConstructBlueprint` nests itself) publishes `{"$defs": …, "$ref": …}`+ at the top, so reading `properties` off the raw schema would judge every recursive model opaque.+ """+ ref = schema.get("$ref")+ if not isinstance(ref, str):+ return schema+ definition_name = ref.rsplit("/", maxsplit=1)[-1]+ defs: dict[str, Any] = schema.get("$defs") or {}+ resolved: Any = defs.get(definition_name)+ if isinstance(resolved, dict):+ return cast("dict[str, Any]", resolved)+ return schema+++def _is_opaque_object(schema: dict[str, Any]) -> bool:+ """The exact shape an erasing return annotation produces: an object that says nothing."""+ root = _resolve_root(schema)+ return root.get("type") == "object" and not root.get("properties") and root.get("additionalProperties") is True+++def _erases_its_shape(model: type[BaseModel]) -> bool:+ """The model is opaque when serialized but not when validated — the erasure signature.++ Asymmetry is what makes this a defect rather than a fact. A model that is honestly open —+ `extra="allow"` with no declared fields (`CompositeContent`), or a `RootModel[dict[str, Any]]`+ (`SdkClientRegistry`) — is opaque in *both* modes, and an open dict really is its shape. Testing+ the asymmetry instead of the shape is what lets this sweep run without an allowlist to maintain,+ and an allowlist is the wrong instrument here anyway: it would have to be extended by the very+ person adding the next erasing serializer.+ """+ return _is_opaque_object(model.model_json_schema(mode="serialization")) and not _is_opaque_object(model.model_json_schema(mode="validation"))+++def _sweep_serialization_shapes() -> dict[str, bool]:+ """Every describable Pipelex model, mapped to whether it erases its shape when serialized."""+ verdicts: dict[str, bool] = {}+ for model in _discover_pipelex_models():+ qualified_name = f"{model.__module__}.{model.__qualname__}"+ if qualified_name in MODELS_WITHOUT_A_JSON_SCHEMA:+ continue+ verdicts[qualified_name] = _erases_its_shape(model)+ return verdicts+++def _models_without_a_json_schema() -> set[str]:+ """The models pydantic refuses to describe at all, discovered rather than assumed."""+ undescribable: set[str] = set()+ for model in _discover_pipelex_models():+ try:+ model.model_json_schema(mode="serialization")+ except PydanticInvalidForJsonSchema:+ undescribable.add(f"{model.__module__}.{model.__qualname__}")+ return undescribable+++class TestSerializationJsonSchema:+ def test_discovery_is_not_vacuous(self) -> None:+ """Anti-vacuity: the walk really loaded the package and really found models.++ Deliberately not parametrized — pytest reports `got empty parameter set` and exits 0 on an+ empty list, so the guard would be unreachable exactly when it matters.+ """+ imported = _import_every_pipelex_module()+ assert imported, "No pipelex module imported — the sweep would compare two empty sets and pass vacuously."++ models = _discover_pipelex_models()+ assert models, "No pipelex BaseModel discovered — the sweep would pass vacuously."++ discovered_names = {cls.__qualname__ for cls in models}+ assert "ConceptBlueprint" in discovered_names, "The blueprint layer is missing from the sweep — discovery is not reaching the wire surface."++ assert _models_without_a_json_schema() == MODELS_WITHOUT_A_JSON_SCHEMA, (+ "The set of models pydantic cannot describe has moved. A model that newly stops being describable silently "+ "leaves the sweep below, so update MODELS_WITHOUT_A_JSON_SCHEMA deliberately — after checking the model "+ f"really has no wire form.\n expected: {sorted(MODELS_WITHOUT_A_JSON_SCHEMA)}\n actual: {sorted(_models_without_a_json_schema())}"+ )++ def test_no_pipelex_model_publishes_an_opaque_serialization_schema(self) -> None:+ """A model whose serialization schema says nothing is invisible to every client generator."""+ offenders = [name for name, erased in _sweep_serialization_shapes().items() if erased]++ assert not offenders, (+ "These models describe themselves when validated but publish an opaque object when serialized:\n"+ + "\n".join(f" - {name}" for name in offenders)+ + f"\n\n{REMEDY}"+ )++ @pytest.mark.parametrize("model", WRAP_SERIALIZER_MODELS, ids=lambda model: model.__qualname__)+ def test_wrap_serializer_models_keep_their_property_lists(self, model: type[BaseModel]) -> None:+ """Serialization mode describes the same fields as validation mode.++ Sharper than the opaque-shape sweep: it catches a *partial* erasure, where a schema keeps a+ property or two and loses the rest, which the sweep above would wave through.+ """+ serialization_properties = sorted(_resolve_root(model.model_json_schema(mode="serialization")).get("properties", {}))+ validation_properties = sorted(_resolve_root(model.model_json_schema(mode="validation")).get("properties", {}))++ assert serialization_properties, f"{model.__qualname__} publishes no properties in serialization mode. {REMEDY}"+ assert serialization_properties == validation_properties, (+ f"{model.__qualname__} describes different fields depending on the schema mode.\n"+ f" serialization: {serialization_properties}\n"+ f" validation: {validation_properties}\n\n{REMEDY}"+ )