A channel's message slots are named from the client, on every backend
The IR called them react-message and django-message, so a FastAPI channel had to declare a DjangoMessage. They are client-message and server-message now, and the direction words hold wherever a channel is declared: Params / ClientMessage / ServerMessage, with mizan-core deriving <Pascal>Params and friends so no backend names a type itself. Django's ReactChannel and FastAPI's ReactChannel are both Channel. mizan-fastapi never registered a channels extension, so build_ir() emitted no channel at all and every payload type was invisible to codegen. It registers one now. RegistryExtension is an ABC requiring all(), which is what the IR reads — an extension that cannot enumerate its registrations no longer exists. The gate that should have caught the rename could not: tests/afi registered no channel because mizan-rust had no channel registry to register one in, so a five-package rename of the wire contract passed byte-parity without a channel byte crossing it. mizan-rust grows ChannelSlotKind, a CHANNELS slice, a #[mizan::channel] macro, and KDL emission whose wire_to_pascal matches Python's split; the AFI fixture now carries a channel with every slot and one with a single slot, so all three backends prove the contract byte for byte. MizanChannel held three Option<String> beside three has_*() predicates and unwrapped them with defaults; it holds an ordered slot vector, so an absent slot is absent rather than defaulted. The channels target emitted a React hooks file that a stage1-only consumer could not compile — react emits that now. The codegen's parity tests byte-compared emitted source against baselines without ever compiling it: they compile the generated crate and run its tests, import the generated Python package and call every method, and typecheck each TypeScript target against a consumer. Also fixed at source: app_visitor printed its import diagnostic to stdout, the stream export_mizan_ir writes KDL to, so a failed import silently corrupted the IR; the apps root was hardcoded to "apps"; _default_literal crashed build_ir on any non-JSON-serializable field default; Django and mizan-core derived Pascal names two different ways, disagreeing on every dotted channel name. ir.py builds a document and renders templates/ir/document.kdl.j2 rather than appending KDL strings with hand-tracked indentation, and named types resolve to a fixed point — a model reachable only through a union branch was referenced by a ref that no type block ever defined. The rest is the write-gate's own classifiers run over the standing tree: relative imports, silent swallows, Protocol contracts that should be ABCs, emitters hand-rendering target source, catch-all arms over closed enums, and comments narrating the project rather than the code. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,10 +1,7 @@
|
||||
"""
|
||||
Codegen entrypoint for the AFI fixture.
|
||||
"""Registers the AFI fixture as an import side effect.
|
||||
|
||||
`mizan_fastapi.ir` imports a module and runs `build_ir()` from a
|
||||
populated registry. The fixture's `register_fixture()` is a function
|
||||
call, not an import side effect; this thin wrapper invokes it on
|
||||
import so the CLI works without modifying fixture.py's semantics.
|
||||
`mizan_fastapi.ir` imports a module and then calls `build_ir()` against the
|
||||
registry, so registration has to have already happened at import time.
|
||||
"""
|
||||
|
||||
from fixture import register_fixture
|
||||
|
||||
@@ -7,7 +7,8 @@ class AfiAppConfig(AppConfig):
|
||||
name = "afi_app"
|
||||
|
||||
def ready(self) -> None:
|
||||
# tests/afi/ is on sys.path (added by manage.py), so `fixture` resolves
|
||||
# to tests/afi/fixture.py — the same module the FastAPI side imports.
|
||||
# manage.py puts tests/afi/ on sys.path, so `fixture` resolves there.
|
||||
from fixture import register_fixture
|
||||
from afi_app.channels import register_fixture_channels
|
||||
register_fixture()
|
||||
register_fixture_channels()
|
||||
|
||||
44
tests/afi/django_app/afi_app/channels.py
Normal file
44
tests/afi/django_app/afi_app/channels.py
Normal file
@@ -0,0 +1,44 @@
|
||||
"""The AFI fixture's two channels bound to Django's `Channel` base.
|
||||
|
||||
Payload models and wire names come from `fixture`; `authorize` and `group`
|
||||
are the obligations the Django base adds.
|
||||
"""
|
||||
|
||||
from mizan.channels import Channel, register
|
||||
|
||||
from fixture import (
|
||||
CHAT_CHANNEL,
|
||||
USER_ALERTS_CHANNEL,
|
||||
ChatClientMessage,
|
||||
ChatParams,
|
||||
ChatServerMessage,
|
||||
UserAlertsServerMessage,
|
||||
)
|
||||
|
||||
|
||||
class ChatChannel(Channel):
|
||||
Params = ChatParams
|
||||
ClientMessage = ChatClientMessage
|
||||
ServerMessage = ChatServerMessage
|
||||
|
||||
def authorize(self, params: ChatParams | None = None) -> bool:
|
||||
return True
|
||||
|
||||
def group(self, params: ChatParams | None = None) -> str:
|
||||
# Params are absent on the schema-export path, where no room is bound.
|
||||
return f"chat:{params.room_id}" if params else "chat"
|
||||
|
||||
|
||||
class UserAlertsChannel(Channel):
|
||||
ServerMessage = UserAlertsServerMessage
|
||||
|
||||
def authorize(self, params: None = None) -> bool:
|
||||
return True
|
||||
|
||||
def group(self, params: None = None) -> str:
|
||||
return "user_alerts"
|
||||
|
||||
|
||||
def register_fixture_channels() -> None:
|
||||
register(ChatChannel, CHAT_CHANNEL)
|
||||
register(UserAlertsChannel, USER_ALERTS_CHANNEL)
|
||||
@@ -1,3 +1 @@
|
||||
"""Empty URLconf — the AFI fixture only exercises the schema export."""
|
||||
|
||||
urlpatterns: list = []
|
||||
|
||||
@@ -5,18 +5,47 @@ from __future__ import annotations
|
||||
from fastapi import FastAPI
|
||||
|
||||
from mizan_fastapi import (
|
||||
Channel,
|
||||
MizanError,
|
||||
mizan_exception_handler,
|
||||
mizan_validation_handler,
|
||||
register_channel,
|
||||
router as mizan_router,
|
||||
)
|
||||
|
||||
from fixture import register_fixture
|
||||
from fixture import (
|
||||
CHAT_CHANNEL,
|
||||
USER_ALERTS_CHANNEL,
|
||||
ChatClientMessage,
|
||||
ChatParams,
|
||||
ChatServerMessage,
|
||||
UserAlertsServerMessage,
|
||||
register_fixture,
|
||||
)
|
||||
|
||||
|
||||
class ChatChannel(Channel):
|
||||
"""All three slots declared; the room keys the fan-out."""
|
||||
|
||||
Params = ChatParams
|
||||
ClientMessage = ChatClientMessage
|
||||
ServerMessage = ChatServerMessage
|
||||
|
||||
def group(self, params: ChatParams | None = None) -> str:
|
||||
return f"chat:{params.room_id}" if params else "chat"
|
||||
|
||||
|
||||
class UserAlertsChannel(Channel):
|
||||
"""Push-only: no params, nothing travels up."""
|
||||
|
||||
ServerMessage = UserAlertsServerMessage
|
||||
|
||||
|
||||
def make_app() -> FastAPI:
|
||||
"""Build a fresh FastAPI app with the AFI fixture registered."""
|
||||
register_fixture()
|
||||
register_channel(ChatChannel, CHAT_CHANNEL)
|
||||
register_channel(UserAlertsChannel, USER_ALERTS_CHANNEL)
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(mizan_router, prefix="/api/mizan")
|
||||
|
||||
@@ -1,17 +1,10 @@
|
||||
"""
|
||||
The AFI fixture — a small set of @client-decorated functions designed to
|
||||
exercise the protocol axes both backends must agree on:
|
||||
"""The @client-decorated functions and the channel wire contracts every AFI
|
||||
backend registers.
|
||||
|
||||
- plain function with typed input
|
||||
- plain function with no input
|
||||
- two context functions sharing a param (proves bundling + param elevation)
|
||||
- a mutation declaring `affects` on the context
|
||||
|
||||
No channels, no forms, no shapes — those aren't AFI-common.
|
||||
|
||||
`register_fixture()` registers the functions with mizan_core.registry.
|
||||
Backend test apps import this module and call register_fixture() during
|
||||
their setup so each backend's schema export sees the same registrations.
|
||||
`register_fixture()` binds the functions into mizan_core.registry. The channel
|
||||
classes live in each backend's own app module — the `Channel` base is
|
||||
backend-specific — and bind the payload models below under `CHAT_CHANNEL` and
|
||||
`USER_ALERTS_CHANNEL`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -49,48 +42,82 @@ class StatusOutput(BaseModel):
|
||||
ok: bool
|
||||
|
||||
|
||||
# ─── Channel wire contracts ─────────────────────────────────────────────────
|
||||
|
||||
CHAT_CHANNEL = "chat"
|
||||
USER_ALERTS_CHANNEL = "user_alerts"
|
||||
|
||||
|
||||
class ChatParams(BaseModel):
|
||||
room_id: str
|
||||
|
||||
|
||||
class ChatClientMessage(BaseModel):
|
||||
text: str
|
||||
|
||||
|
||||
class ChatServerMessage(BaseModel):
|
||||
text: str
|
||||
from_user: str
|
||||
|
||||
|
||||
class UserAlertsServerMessage(BaseModel):
|
||||
body: str
|
||||
unread: int
|
||||
|
||||
|
||||
# ─── Stored rows ────────────────────────────────────────────────────────────
|
||||
|
||||
_PROFILES = {5: "Ada Lovelace", 6: "Grace Hopper"}
|
||||
_ORDERS = [
|
||||
OrderOutput(id=1, user_id=5, total=1200),
|
||||
OrderOutput(id=2, user_id=5, total=350),
|
||||
]
|
||||
|
||||
|
||||
# ─── Fixture functions ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@client
|
||||
def echo(request, text: str) -> EchoOutput:
|
||||
"""Echoes the input back."""
|
||||
return EchoOutput(message=f"echo: {text}")
|
||||
|
||||
|
||||
@client
|
||||
def whoami(request) -> WhoamiOutput:
|
||||
"""Returns the current user identity."""
|
||||
return WhoamiOutput(email="anon@example.com", authenticated=False)
|
||||
|
||||
|
||||
@client(context="user")
|
||||
def user_profile(request, user_id: int) -> ProfileOutput:
|
||||
"""One half of the user context."""
|
||||
return ProfileOutput(user_id=user_id, name="placeholder")
|
||||
# A context member always answers, so an unstored id reads back under a
|
||||
# name derived from the id rather than an absence.
|
||||
return ProfileOutput(
|
||||
user_id=user_id, name=_PROFILES.get(user_id, f"user {user_id}")
|
||||
)
|
||||
|
||||
|
||||
@client(context="user")
|
||||
def user_orders(request, user_id: int) -> list[OrderOutput]:
|
||||
"""Other half of the user context — same param, proves param elevation."""
|
||||
return []
|
||||
return [order for order in _ORDERS if order.user_id == user_id]
|
||||
|
||||
|
||||
@client(affects="user")
|
||||
def update_profile(request, user_id: int, name: str) -> StatusOutput:
|
||||
"""Mutation declaring affects on the user context."""
|
||||
return StatusOutput(ok=True)
|
||||
return StatusOutput(ok=bool(name) and user_id in _PROFILES)
|
||||
|
||||
|
||||
@client
|
||||
def find_user(request, user_id: int) -> ProfileOutput | None:
|
||||
"""Optional return — exercises Pydantic `T | None` schema introspection."""
|
||||
if user_id in _PROFILES:
|
||||
return ProfileOutput(user_id=user_id, name=_PROFILES[user_id])
|
||||
return None
|
||||
|
||||
|
||||
@client(merge="user")
|
||||
def rename_user(request, user_id: int, name: str) -> ProfileOutput:
|
||||
"""Merge target — kernel splices return value into the user context."""
|
||||
# The merge target's return value is what the kernel splices into the
|
||||
# `user` context, so the renamed profile is the whole result.
|
||||
return ProfileOutput(user_id=user_id, name=name)
|
||||
|
||||
|
||||
@@ -98,7 +125,6 @@ def rename_user(request, user_id: int, name: str) -> ProfileOutput:
|
||||
|
||||
|
||||
def register_fixture() -> None:
|
||||
"""Register every fixture function with mizan_core.registry."""
|
||||
register(echo, "echo")
|
||||
register(whoami, "whoami")
|
||||
register(user_profile, "user_profile")
|
||||
|
||||
17
tests/afi/rust_app/Cargo.lock
generated
17
tests/afi/rust_app/Cargo.lock
generated
@@ -301,12 +301,28 @@ version = "2.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
|
||||
|
||||
[[package]]
|
||||
name = "memo-map"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38d1115007560874e373613744c6fba374c17688327a71c1476d1a5954cc857b"
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "minijinja"
|
||||
version = "2.21.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb3d648e68cea56d9858d535ee28f9538404e2dd8cb08ed0bd05dca379477f39"
|
||||
dependencies = [
|
||||
"memo-map",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.0"
|
||||
@@ -337,6 +353,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"linkme",
|
||||
"minijinja",
|
||||
"mizan-macros",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
//! Emit the AFI fixture's Mizan IR (KDL) to stdout. The codegen subprocess
|
||||
//! consumes this; the three-way codegen-parity test asserts it equals what
|
||||
//! Django and FastAPI emit.
|
||||
//! Print the registered fixture's Mizan IR (KDL) to stdout.
|
||||
|
||||
fn main() {
|
||||
// The fixture is registered via the `afi_rust_app` library crate at
|
||||
// link time — referencing any symbol keeps the linkme statics alive.
|
||||
// The fixture registers through linkme statics in the library crate;
|
||||
// referencing a symbol keeps the linker from dropping the crate.
|
||||
let _ = afi_rust_app::echo;
|
||||
print!("{}", mizan_core::build_ir());
|
||||
}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
//! Serve the AFI fixture under axum on `PORT` env var (or 8765 default).
|
||||
//! Used by the wire-parity test as the third-backend probe target.
|
||||
//! Serve the AFI fixture under axum on the port named by `PORT`, else 8765.
|
||||
|
||||
use axum::Router;
|
||||
use std::env::VarError;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// Keep the fixture's linkme statics alive by touching one of its
|
||||
// symbols (the bin would otherwise dead-strip the library crate).
|
||||
// The fixture registers through linkme statics in the library crate;
|
||||
// referencing a symbol keeps the linker from dropping the crate.
|
||||
let _ = afi_rust_app::echo;
|
||||
|
||||
let port: u16 = std::env::var("PORT")
|
||||
.ok()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(8765);
|
||||
let port: u16 = match std::env::var("PORT") {
|
||||
Ok(raw) => raw
|
||||
.parse()
|
||||
.unwrap_or_else(|e| panic!("PORT={raw:?} is not a port number: {e}")),
|
||||
Err(VarError::NotPresent) => 8765,
|
||||
Err(VarError::NotUnicode(raw)) => panic!("PORT={raw:?} is not valid unicode"),
|
||||
};
|
||||
|
||||
let app = Router::new().nest("/api/mizan", mizan_axum::router_stateless());
|
||||
|
||||
@@ -21,5 +24,7 @@ async fn main() {
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("bind {bind}: {e}"));
|
||||
eprintln!("afi_rust_app listening on http://{bind}");
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("serve {bind}: {e}"));
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
//! AFI fixture — Rust port of `tests/afi/fixture.py`.
|
||||
//!
|
||||
//! Same 7 functions, same 5 shared types, same context+affects+merge graph.
|
||||
//! The KDL emitted by `build_ir()` against this registry is byte-identical
|
||||
//! to the canonical Python-emitted `protocol/mizan-codegen/tests/fixtures/
|
||||
//! afi_ir.kdl` — gated by the three-way codegen-parity test.
|
||||
//! The AFI fixture for the Rust backend: seven client functions over the
|
||||
//! stored rows below, one `user` context reached by `context`/`affects`/
|
||||
//! `merge`, and two channels over their payload shapes.
|
||||
|
||||
use mizan_core as mizan;
|
||||
use mizan_core::prelude::*;
|
||||
@@ -39,9 +36,65 @@ pub struct StatusOutput {
|
||||
pub ok: bool,
|
||||
}
|
||||
|
||||
#[derive(Mizan, Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChatParams {
|
||||
pub room_id: String,
|
||||
}
|
||||
|
||||
#[derive(Mizan, Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChatClientMessage {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Mizan, Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChatServerMessage {
|
||||
pub text: String,
|
||||
pub from_user: String,
|
||||
}
|
||||
|
||||
#[derive(Mizan, Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct UserAlertsServerMessage {
|
||||
pub body: String,
|
||||
pub unread: i64,
|
||||
}
|
||||
|
||||
/// The rows the fixture serves, as `(user id, display name)`.
|
||||
const STORED_PROFILES: &[(i64, &str)] = &[(5, "Ada Lovelace"), (6, "Grace Hopper")];
|
||||
|
||||
const STORED_ORDERS: &[OrderOutput] = &[
|
||||
OrderOutput {
|
||||
id: 1,
|
||||
user_id: 5,
|
||||
total: 1200,
|
||||
},
|
||||
OrderOutput {
|
||||
id: 2,
|
||||
user_id: 5,
|
||||
total: 350,
|
||||
},
|
||||
];
|
||||
|
||||
fn stored_name(user_id: i64) -> Option<&'static str> {
|
||||
STORED_PROFILES
|
||||
.iter()
|
||||
.find(|(stored_id, _)| *stored_id == user_id)
|
||||
.map(|(_, name)| *name)
|
||||
}
|
||||
|
||||
#[mizan::context("user")]
|
||||
pub struct UserCtx;
|
||||
|
||||
#[mizan::channel(
|
||||
"chat",
|
||||
params = ChatParams,
|
||||
client_message = ChatClientMessage,
|
||||
server_message = ChatServerMessage
|
||||
)]
|
||||
pub struct ChatChannel;
|
||||
|
||||
#[mizan::channel("user_alerts", server_message = UserAlertsServerMessage)]
|
||||
pub struct UserAlertsChannel;
|
||||
|
||||
#[mizan::client]
|
||||
pub async fn echo(_req: &RequestHandle<'_>, text: String) -> EchoOutput {
|
||||
EchoOutput {
|
||||
@@ -59,29 +112,41 @@ pub async fn whoami(_req: &RequestHandle<'_>) -> WhoamiOutput {
|
||||
|
||||
#[mizan::client(context = UserCtx)]
|
||||
pub async fn user_profile(_req: &RequestHandle<'_>, user_id: i64) -> ProfileOutput {
|
||||
ProfileOutput {
|
||||
user_id,
|
||||
name: "placeholder".into(),
|
||||
}
|
||||
// A context member always answers, so an unstored id reads back under a
|
||||
// name derived from the id rather than an absence.
|
||||
let name = match stored_name(user_id) {
|
||||
Some(stored) => stored.to_string(),
|
||||
None => format!("user {user_id}"),
|
||||
};
|
||||
ProfileOutput { user_id, name }
|
||||
}
|
||||
|
||||
#[mizan::client(context = UserCtx)]
|
||||
pub async fn user_orders(_req: &RequestHandle<'_>, _user_id: i64) -> Vec<OrderOutput> {
|
||||
vec![]
|
||||
pub async fn user_orders(_req: &RequestHandle<'_>, user_id: i64) -> Vec<OrderOutput> {
|
||||
STORED_ORDERS
|
||||
.iter()
|
||||
.filter(|order| order.user_id == user_id)
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[mizan::client(affects = UserCtx)]
|
||||
pub async fn update_profile(
|
||||
_req: &RequestHandle<'_>,
|
||||
_user_id: i64,
|
||||
_name: String,
|
||||
user_id: i64,
|
||||
name: String,
|
||||
) -> StatusOutput {
|
||||
StatusOutput { ok: true }
|
||||
StatusOutput {
|
||||
ok: !name.is_empty() && stored_name(user_id).is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
#[mizan::client]
|
||||
pub async fn find_user(_req: &RequestHandle<'_>, _user_id: i64) -> Option<ProfileOutput> {
|
||||
None
|
||||
pub async fn find_user(_req: &RequestHandle<'_>, user_id: i64) -> Option<ProfileOutput> {
|
||||
stored_name(user_id).map(|stored| ProfileOutput {
|
||||
user_id,
|
||||
name: stored.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
#[mizan::client(merge = UserCtx)]
|
||||
@@ -90,5 +155,7 @@ pub async fn rename_user(
|
||||
user_id: i64,
|
||||
name: String,
|
||||
) -> ProfileOutput {
|
||||
// The merge target's return value is what the kernel splices into the
|
||||
// `user` context, so the renamed profile is the whole result.
|
||||
ProfileOutput { user_id, name }
|
||||
}
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
"""
|
||||
AFI conformance — same fixture, same Mizan IR (KDL), all three adapters.
|
||||
"""Byte-equivalence of the Mizan IR (KDL) that mizan-django, mizan-fastapi,
|
||||
and the Rust mizan-axum backend emit for one shared fixture.
|
||||
|
||||
Gates that mizan-django, mizan-fastapi, and the Rust mizan-axum backend
|
||||
emit byte-equivalent KDL for the same registered functions. The IR is the
|
||||
contract; whatever language wrote the backend, the wire/codegen-facing
|
||||
artifact is identical.
|
||||
|
||||
Substrate-level gate, not e2e. Catches adapter symmetry problems —
|
||||
type-introspection divergence, ordering non-determinism — across all
|
||||
backends in one place.
|
||||
Each adapter is reached the way its own runtime reaches it: Django through
|
||||
its management command in a subprocess, FastAPI in-process against a cleared
|
||||
registry, Rust through the `export-ir` bin.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,7 +22,6 @@ RUST_APP_DIR = HERE / "rust_app"
|
||||
|
||||
|
||||
def _fetch_django_ir() -> str:
|
||||
"""Spawn Django's management command and parse stdout as KDL."""
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(DJANGO_MANAGE), "export_mizan_ir"],
|
||||
capture_output=True,
|
||||
@@ -43,7 +37,7 @@ def _fetch_django_ir() -> str:
|
||||
|
||||
|
||||
def _fetch_fastapi_ir() -> str:
|
||||
"""Build the FastAPI app inline (fresh registry) and call build_ir()."""
|
||||
# tests/afi/ must be importable for `fixture` and `fastapi_app` to resolve.
|
||||
sys.path.insert(0, str(HERE))
|
||||
try:
|
||||
from mizan_core.registry import clear_registry
|
||||
@@ -58,7 +52,6 @@ def _fetch_fastapi_ir() -> str:
|
||||
|
||||
|
||||
def _fetch_rust_ir() -> str:
|
||||
"""Spawn the Rust `export-ir` bin and capture stdout."""
|
||||
result = subprocess.run(
|
||||
[
|
||||
"cargo", "run",
|
||||
@@ -93,23 +86,20 @@ def django_ir() -> str:
|
||||
|
||||
|
||||
def test_fastapi_matches_rust(fastapi_ir: str, rust_ir: str) -> None:
|
||||
"""FastAPI ≡ Rust. The Mizan IR is the contract across languages."""
|
||||
assert fastapi_ir == rust_ir, (
|
||||
"FastAPI and Rust emit divergent Mizan IR for the same registered "
|
||||
"functions. Substrate gate is red."
|
||||
"functions and channels."
|
||||
)
|
||||
|
||||
|
||||
def test_django_matches_fastapi(django_ir: str, fastapi_ir: str) -> None:
|
||||
"""Django ≡ FastAPI."""
|
||||
assert django_ir == fastapi_ir, (
|
||||
"Django and FastAPI emit divergent Mizan IR for the same "
|
||||
"registered functions. Substrate gate is red."
|
||||
"Django and FastAPI emit divergent Mizan IR for the same registered "
|
||||
"functions and channels."
|
||||
)
|
||||
|
||||
|
||||
def test_all_three_match(django_ir: str, fastapi_ir: str, rust_ir: str) -> None:
|
||||
"""All three backends emit byte-identical KDL."""
|
||||
assert django_ir == fastapi_ir == rust_ir, (
|
||||
"Three-way IR divergence — see test_django_matches_fastapi and "
|
||||
"test_fastapi_matches_rust for which pair drifts."
|
||||
|
||||
1
tests/rust/fixture_client/.gitattributes
generated
vendored
Normal file
1
tests/rust/fixture_client/.gitattributes
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
* linguist-generated=true
|
||||
2
tests/rust/fixture_client/src/contexts/mod.rs
generated
2
tests/rust/fixture_client/src/contexts/mod.rs
generated
@@ -1,3 +1 @@
|
||||
// AUTO-GENERATED by mizan — do not edit
|
||||
|
||||
pub mod user;
|
||||
|
||||
10
tests/rust/fixture_client/src/contexts/user.rs
generated
10
tests/rust/fixture_client/src/contexts/user.rs
generated
@@ -1,16 +1,13 @@
|
||||
// AUTO-GENERATED by mizan — do not edit
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use mizan_rust::{MizanClient, MizanError};
|
||||
|
||||
use crate::types::{UserProfileOutput, UserOrdersOutput};
|
||||
use crate::types::{UserOrdersOutput, UserProfileOutput};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct UserContextData {
|
||||
pub user_profile: UserProfileOutput,
|
||||
pub user_orders: UserOrdersOutput,
|
||||
pub user_profile: UserProfileOutput,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -22,7 +19,8 @@ pub async fn fetch_user_context(
|
||||
client: &MizanClient,
|
||||
params: &UserContextParams,
|
||||
) -> Result<UserContextData, MizanError> {
|
||||
let params_value = serde_json::to_value(params).unwrap_or(Value::Object(Default::default()));
|
||||
let params_value = serde_json::to_value(params)
|
||||
.map_err(|e| MizanError::transport(format!("encode user context params: {e}")))?;
|
||||
let raw = client.fetch_context("user", ¶ms_value).await?;
|
||||
serde_json::from_value(raw)
|
||||
.map_err(|e| MizanError::transport(format!("decode user context: {e}")))
|
||||
|
||||
7
tests/rust/fixture_client/src/functions/echo.rs
generated
7
tests/rust/fixture_client/src/functions/echo.rs
generated
@@ -1,13 +1,10 @@
|
||||
// AUTO-GENERATED by mizan — do not edit
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use mizan_rust::{MizanClient, MizanError};
|
||||
|
||||
use crate::types::{EchoOutput, EchoInput};
|
||||
|
||||
pub async fn call_echo(client: &MizanClient, args: &EchoInput) -> Result<EchoOutput, MizanError> {
|
||||
let args_value = serde_json::to_value(args).unwrap_or(Value::Object(Default::default()));
|
||||
let args_value = serde_json::to_value(args)
|
||||
.map_err(|e| MizanError::transport(format!("encode echo args: {e}")))?;
|
||||
let raw = client.call("echo", args_value).await?;
|
||||
serde_json::from_value(raw)
|
||||
.map_err(|e| MizanError::transport(format!("decode echo result: {e}")))
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
// AUTO-GENERATED by mizan — do not edit
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use mizan_rust::{MizanClient, MizanError};
|
||||
|
||||
use crate::types::{FindUserOutput, FindUserInput};
|
||||
|
||||
pub async fn call_find_user(client: &MizanClient, args: &FindUserInput) -> Result<Option<FindUserOutput>, MizanError> {
|
||||
let args_value = serde_json::to_value(args).unwrap_or(Value::Object(Default::default()));
|
||||
let args_value = serde_json::to_value(args)
|
||||
.map_err(|e| MizanError::transport(format!("encode find_user args: {e}")))?;
|
||||
let raw = client.call("find_user", args_value).await?;
|
||||
serde_json::from_value(raw)
|
||||
.map_err(|e| MizanError::transport(format!("decode find_user result: {e}")))
|
||||
|
||||
2
tests/rust/fixture_client/src/functions/mod.rs
generated
2
tests/rust/fixture_client/src/functions/mod.rs
generated
@@ -1,5 +1,3 @@
|
||||
// AUTO-GENERATED by mizan — do not edit
|
||||
|
||||
pub mod echo;
|
||||
pub mod find_user;
|
||||
pub mod rename_user;
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
// AUTO-GENERATED by mizan — do not edit
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use mizan_rust::{MizanClient, MizanError};
|
||||
|
||||
use crate::types::{RenameUserOutput, RenameUserInput};
|
||||
|
||||
pub async fn call_rename_user(client: &MizanClient, args: &RenameUserInput) -> Result<RenameUserOutput, MizanError> {
|
||||
let args_value = serde_json::to_value(args).unwrap_or(Value::Object(Default::default()));
|
||||
let args_value = serde_json::to_value(args)
|
||||
.map_err(|e| MizanError::transport(format!("encode rename_user args: {e}")))?;
|
||||
let raw = client.call("rename_user", args_value).await?;
|
||||
serde_json::from_value(raw)
|
||||
.map_err(|e| MizanError::transport(format!("decode rename_user result: {e}")))
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
// AUTO-GENERATED by mizan — do not edit
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use mizan_rust::{MizanClient, MizanError};
|
||||
|
||||
use crate::types::{WhoamiOutput};
|
||||
|
||||
pub async fn call_whoami(client: &MizanClient) -> Result<WhoamiOutput, MizanError> {
|
||||
let args_value = Value::Object(Default::default());
|
||||
let args_value = serde_json::Value::Object(Default::default());
|
||||
let raw = client.call("whoami", args_value).await?;
|
||||
serde_json::from_value(raw)
|
||||
.map_err(|e| MizanError::transport(format!("decode whoami result: {e}")))
|
||||
|
||||
2
tests/rust/fixture_client/src/lib.rs
generated
2
tests/rust/fixture_client/src/lib.rs
generated
@@ -1,5 +1,3 @@
|
||||
// AUTO-GENERATED by mizan — do not edit
|
||||
|
||||
pub mod types;
|
||||
pub mod contexts;
|
||||
pub mod mutations;
|
||||
|
||||
2
tests/rust/fixture_client/src/mutations/mod.rs
generated
2
tests/rust/fixture_client/src/mutations/mod.rs
generated
@@ -1,3 +1 @@
|
||||
// AUTO-GENERATED by mizan — do not edit
|
||||
|
||||
pub mod update_profile;
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
// AUTO-GENERATED by mizan — do not edit
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use mizan_rust::{MizanClient, MizanError};
|
||||
|
||||
use crate::types::{UpdateProfileOutput, UpdateProfileInput};
|
||||
|
||||
pub async fn call_update_profile(client: &MizanClient, args: &UpdateProfileInput) -> Result<UpdateProfileOutput, MizanError> {
|
||||
let args_value = serde_json::to_value(args).unwrap_or(Value::Object(Default::default()));
|
||||
let args_value = serde_json::to_value(args)
|
||||
.map_err(|e| MizanError::transport(format!("encode update_profile args: {e}")))?;
|
||||
let raw = client.call("update_profile", args_value).await?;
|
||||
serde_json::from_value(raw)
|
||||
.map_err(|e| MizanError::transport(format!("decode update_profile result: {e}")))
|
||||
|
||||
2
tests/rust/fixture_client/src/types.rs
generated
2
tests/rust/fixture_client/src/types.rs
generated
@@ -1,5 +1,3 @@
|
||||
// AUTO-GENERATED by mizan — do not edit
|
||||
|
||||
#![allow(non_camel_case_types)]
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -1,20 +1,13 @@
|
||||
"""Three-way wire-parity check.
|
||||
"""Run the wire-parity drivers against each backend.
|
||||
|
||||
For each backend (FastAPI, Rust axum):
|
||||
1. Boot the fixture server on a free port.
|
||||
2. Poll /api/mizan/session/ until the server responds.
|
||||
2. Poll the readiness surface until the server responds.
|
||||
3. Run the Rust `drive_kernel` binary (raw kernel calls) against it.
|
||||
4. Run the Rust `drive_emitted` binary (typed codegen functions) against it.
|
||||
5. Tear the server down.
|
||||
|
||||
Any non-zero driver exit propagates as the script's exit code. Adding the
|
||||
Rust backend here proves that mizan-axum honors the same wire contract as
|
||||
mizan-fastapi — same JSON shapes, same invalidate/merge semantics — beyond
|
||||
the static IR equivalence the codegen-parity test gates.
|
||||
|
||||
Readiness probe is `/api/mizan/session/` (Mizan-protocol-shaped) rather
|
||||
than `/openapi.json` (FastAPI-feature-shaped) so the harness reads the
|
||||
same surface across backends.
|
||||
Any non-zero driver exit propagates as the script's exit code.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -45,6 +38,7 @@ def pick_free_port() -> int:
|
||||
|
||||
def wait_for_server(port: int, timeout_s: float, label: str) -> bool:
|
||||
deadline = time.monotonic() + timeout_s
|
||||
# every backend serves /session/; /openapi.json exists only on FastAPI
|
||||
url = f"http://127.0.0.1:{port}/api/mizan/session/"
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
//! Drive the codegen-emitted `fixture_client` crate against a live
|
||||
//! FastAPI fixture. Validates not just the kernel wire (which
|
||||
//! `drive_kernel.rs` already covers) but that the codegen actually
|
||||
//! produces typed-functions that round-trip cleanly through the same
|
||||
//! kernel.
|
||||
//! Probe the AFI fixture's endpoints through the codegen-emitted
|
||||
//! `fixture_client` typed functions rather than raw kernel calls.
|
||||
//! Argument 1 is the Mizan base URL (default: the local uvicorn fixture).
|
||||
//! Each probe prints its decoded response; any failure sets a failing exit code.
|
||||
|
||||
use std::env;
|
||||
use std::process::ExitCode;
|
||||
|
||||
@@ -1,15 +1,6 @@
|
||||
//! Drive the mizan-rust kernel against a live FastAPI fixture app and
|
||||
//! print every response. Used by `run_wire_parity.sh` which:
|
||||
//!
|
||||
//! 1. Boots `tests/afi/fastapi_app.py` via uvicorn on port 8765.
|
||||
//! 2. Polls `/openapi.json` until the server is up.
|
||||
//! 3. Runs `cargo run --bin drive_kernel -- http://127.0.0.1:8765/api/mizan`.
|
||||
//! 4. Diffs the stdout against a committed snapshot.
|
||||
//!
|
||||
//! The kernel exercises every endpoint the fixture declares: the two
|
||||
//! plain functions (`echo`, `whoami`), the two-function `user` context,
|
||||
//! the `update_profile` mutation, the `find_user` Optional path, and
|
||||
//! the `rename_user` merge mutation.
|
||||
//! Probe the AFI fixture's endpoints through the raw `mizan-rust` kernel.
|
||||
//! Argument 1 is the Mizan base URL (default: the local uvicorn fixture).
|
||||
//! Each probe prints its response; any failed probe sets a failing exit code.
|
||||
|
||||
use std::env;
|
||||
use std::process::ExitCode;
|
||||
|
||||
Reference in New Issue
Block a user