test(wasmguest): reactor fixture plugin + throwaway wazero host (WO-WZ-002)

testdata/fixture is the acceptance fixture: one block, one template, one
admin page, plus the two-line reactor boilerplate main. wasmhost_test.go
compiles it with GOOS=wasip1 GOARCH=wasm -buildmode=c-shared (15.7 MiB,
the WO-WZ-012 memory-budget baseline) and drives it through wazero
exactly per wasm-abi.md: _initialize as the start function, request
bytes through bn_alloc, DESCRIBE returning a decodable manifest,
same-instance block+template renders, a panicking BlockFunc surfacing as
ABI_ERROR_CODE_INTERNAL with the instance still callable, and a
non-bn_alloc request pointer rejected as DECODE.

wazero v1.12.0 joins go.mod as a test-only dependency (approved).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Alex Dunmow 2026-07-03 13:53:39 +08:00
parent c35199f0bc
commit 9bbc793563
5 changed files with 321 additions and 3 deletions

3
go.mod
View File

@ -12,6 +12,7 @@ require (
github.com/jackc/pgx/v5 v5.9.2 github.com/jackc/pgx/v5 v5.9.2
github.com/klauspost/compress v1.18.6 github.com/klauspost/compress v1.18.6
github.com/spf13/cobra v1.10.2 github.com/spf13/cobra v1.10.2
github.com/tetratelabs/wazero v1.12.0
golang.org/x/mod v0.34.0 golang.org/x/mod v0.34.0
google.golang.org/protobuf v1.36.11 google.golang.org/protobuf v1.36.11
) )
@ -28,6 +29,6 @@ require (
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/rogpeppe/go-internal v1.15.0 // indirect github.com/rogpeppe/go-internal v1.15.0 // indirect
github.com/spf13/pflag v1.0.9 // indirect github.com/spf13/pflag v1.0.9 // indirect
golang.org/x/sys v0.42.0 // indirect golang.org/x/sys v0.44.0 // indirect
golang.org/x/text v0.36.0 // indirect golang.org/x/text v0.36.0 // indirect
) )

6
go.sum
View File

@ -62,14 +62,16 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU=
github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI= golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI=
golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY= golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg= golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=

View File

@ -0,0 +1,8 @@
//go:build wasip1
package main
import "git.dev.alexdunmow.com/block/core/plugin/wasmguest"
func init() { wasmguest.Serve(Registration) }
func main() {} // never called — reactor mode

View File

@ -0,0 +1,54 @@
// Package main is the WO-WZ-002 acceptance fixture: a minimal plugin with
// one block, one template, and one admin page, compiled to wasm with only
// the wasmguest boilerplate (main.go).
package main
import (
"context"
"fmt"
"io"
"git.dev.alexdunmow.com/block/core/blocks"
"git.dev.alexdunmow.com/block/core/plugin"
"git.dev.alexdunmow.com/block/core/templates"
)
// Registration is the fixture's plugin registration — the same shape a .so
// plugin exports, untouched by the wasm migration.
var Registration = plugin.PluginRegistration{
Name: "wasmfixture",
Version: "0.0.1",
Register: func(tr templates.TemplateRegistry, br blocks.BlockRegistry) error {
br.Register(blocks.BlockMeta{
Key: "greeting",
Title: "Greeting",
Description: "Renders a greeting",
Category: blocks.CategoryContent,
}, func(ctx context.Context, content map[string]any) string {
if boom, _ := content["boom"].(bool); boom {
panic("fixture kaboom")
}
name, _ := content["name"].(string)
if name == "" {
name = "world"
}
return fmt.Sprintf("<p>hello %s</p>", name)
})
return tr.Register("wasmfixture-page", func(ctx context.Context, doc map[string]any) templates.HTMLComponent {
title, _ := doc["title"].(string)
return htmlString("<!doctype html><title>" + title + "</title>")
})
},
AdminPages: func() []plugin.AdminPage {
return []plugin.AdminPage{{
Key: "wasmfixture", Title: "Wasm Fixture", Icon: "flask", Route: "/admin/wasmfixture",
}}
},
}
type htmlString string
func (s htmlString) Render(_ context.Context, w io.Writer) error {
_, err := io.WriteString(w, string(s))
return err
}

View File

@ -0,0 +1,253 @@
package wasmguest
// Throwaway wazero host: proves the compiled fixture module honors the ABI
// end to end (WO-WZ-002 acceptance) without the real cms host WO. It builds
// testdata/fixture in reactor mode, instantiates it, and drives bn_alloc /
// bn_invoke / bn_free exactly as core/docs/wasm-abi.md specifies.
import (
"context"
"encoding/binary"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
abiv1 "git.dev.alexdunmow.com/block/core/abi/v1"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
"google.golang.org/protobuf/proto"
)
// buildFixture compiles testdata/fixture to a reactor-mode wasm module.
func buildFixture(t *testing.T) string {
t.Helper()
out := filepath.Join(t.TempDir(), "fixture.wasm")
cmd := exec.Command("go", "build", "-buildmode=c-shared", "-o", out, "./testdata/fixture")
cmd.Env = append(os.Environ(), "GOOS=wasip1", "GOARCH=wasm")
if b, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("build fixture: %v\n%s", err, b)
}
info, err := os.Stat(out)
if err != nil {
t.Fatalf("stat fixture: %v", err)
}
t.Logf("fixture.wasm size: %d bytes (%.1f MiB)", info.Size(), float64(info.Size())/(1<<20))
return out
}
type wasmInstance struct {
mod api.Module
ctx context.Context
}
func instantiateFixture(t *testing.T) *wasmInstance {
t.Helper()
wasmPath := buildFixture(t)
ctx := context.Background()
r := wazero.NewRuntime(ctx)
t.Cleanup(func() { _ = r.Close(ctx) })
wasi_snapshot_preview1.MustInstantiate(ctx, r)
wasmBytes, err := os.ReadFile(wasmPath)
if err != nil {
t.Fatalf("read module: %v", err)
}
// Reactor contract: no _start; run _initialize once per instance before
// any bn_invoke.
mod, err := r.InstantiateWithConfig(ctx, wasmBytes,
wazero.NewModuleConfig().WithStartFunctions("_initialize").WithName("fixture"))
if err != nil {
t.Fatalf("instantiate: %v", err)
}
for _, export := range []string{"bn_alloc", "bn_invoke", "bn_free"} {
if mod.ExportedFunction(export) == nil {
t.Fatalf("module does not export %s", export)
}
}
return &wasmInstance{mod: mod, ctx: ctx}
}
// invoke drives one bn_invoke round trip through guest memory.
func (w *wasmInstance) invoke(t *testing.T, hook abiv1.Hook, payload proto.Message) *abiv1.InvokeResponse {
t.Helper()
payloadBytes, err := proto.Marshal(payload)
if err != nil {
t.Fatalf("marshal payload: %v", err)
}
req, err := proto.Marshal(&abiv1.InvokeRequest{Hook: hook, Payload: payloadBytes})
if err != nil {
t.Fatalf("marshal envelope: %v", err)
}
alloc := w.mod.ExportedFunction("bn_alloc")
res, err := alloc.Call(w.ctx, uint64(len(req)))
if err != nil {
t.Fatalf("bn_alloc: %v", err)
}
ptr := uint32(res[0])
if ptr == 0 {
t.Fatal("bn_alloc returned 0")
}
if !w.mod.Memory().Write(ptr, req) {
t.Fatalf("write request at %d (len %d) out of range", ptr, len(req))
}
res, err = w.mod.ExportedFunction("bn_invoke").Call(w.ctx, uint64(hook), uint64(ptr), uint64(len(req)))
if err != nil {
t.Fatalf("bn_invoke: %v", err)
}
packed := res[0]
if packed == 0 {
t.Fatal("bn_invoke returned packed 0 (guest could not produce an envelope)")
}
respPtr := uint32(packed >> 32)
respLen := uint32(packed)
respBytes, ok := w.mod.Memory().Read(respPtr, respLen)
if !ok {
t.Fatalf("read response at %d (len %d) out of range", respPtr, respLen)
}
resp := &abiv1.InvokeResponse{}
if err := proto.Unmarshal(respBytes, resp); err != nil {
t.Fatalf("unmarshal InvokeResponse: %v", err)
}
// Host-driven release of the request buffer (guest also self-releases;
// bn_free must tolerate both).
if _, err := w.mod.ExportedFunction("bn_free").Call(w.ctx, uint64(ptr)); err != nil {
t.Fatalf("bn_free: %v", err)
}
return resp
}
func TestWasmFixtureDescribeRoundTrip(t *testing.T) {
if testing.Short() {
t.Skip("compiles a wasm module; skipped in -short")
}
w := instantiateFixture(t)
resp := w.invoke(t, abiv1.Hook_HOOK_DESCRIBE, &abiv1.DescribeRequest{HostAbiVersion: 1})
if resp.GetError() != nil {
t.Fatalf("DESCRIBE error: %v", resp.GetError())
}
dr := &abiv1.DescribeResponse{}
if err := proto.Unmarshal(resp.GetPayload(), dr); err != nil {
t.Fatalf("unmarshal DescribeResponse: %v", err)
}
m := dr.GetManifest()
t.Logf("manifest: name=%q version=%q abi=%d blocks=%d templates=%v admin_pages=%d",
m.GetName(), m.GetVersion(), m.GetAbiVersion(), len(m.GetBlocks()), m.GetTemplateKeys(), len(m.GetAdminPages()))
if m.GetName() != "wasmfixture" || m.GetVersion() != "0.0.1" || m.GetAbiVersion() != 1 {
t.Errorf("manifest identity = %q/%q/abi %d", m.GetName(), m.GetVersion(), m.GetAbiVersion())
}
if len(m.GetBlocks()) != 1 || m.GetBlocks()[0].GetKey() != "wasmfixture:greeting" {
t.Errorf("blocks = %v", m.GetBlocks())
}
if len(m.GetTemplateKeys()) != 1 || m.GetTemplateKeys()[0] != "wasmfixture-page" {
t.Errorf("template_keys = %v", m.GetTemplateKeys())
}
if len(m.GetAdminPages()) != 1 || m.GetAdminPages()[0].GetRoute() != "/admin/wasmfixture" {
t.Errorf("admin_pages = %v", m.GetAdminPages())
}
// Same instance renders a block after DESCRIBE.
resp = w.invoke(t, abiv1.Hook_HOOK_RENDER_BLOCK, &abiv1.RenderBlockRequest{
BlockKey: "wasmfixture:greeting",
ContentJson: []byte(`{"name":"wazero"}`),
})
if resp.GetError() != nil {
t.Fatalf("RENDER_BLOCK error: %v", resp.GetError())
}
rb := &abiv1.RenderBlockResponse{}
if err := proto.Unmarshal(resp.GetPayload(), rb); err != nil {
t.Fatalf("unmarshal RenderBlockResponse: %v", err)
}
if rb.GetHtml() != "<p>hello wazero</p>" {
t.Errorf("html = %q", rb.GetHtml())
}
// Template render through the same instance.
resp = w.invoke(t, abiv1.Hook_HOOK_RENDER_TEMPLATE, &abiv1.RenderTemplateRequest{
TemplateKey: "wasmfixture-page",
DocJson: []byte(`{"title":"Wazero"}`),
})
if resp.GetError() != nil {
t.Fatalf("RENDER_TEMPLATE error: %v", resp.GetError())
}
rt := &abiv1.RenderTemplateResponse{}
if err := proto.Unmarshal(resp.GetPayload(), rt); err != nil {
t.Fatalf("unmarshal RenderTemplateResponse: %v", err)
}
if string(rt.GetHtml()) != "<!doctype html><title>Wazero</title>" {
t.Errorf("template html = %q", rt.GetHtml())
}
}
func TestWasmFixturePanicReturnsAbiErrorAndInstanceSurvives(t *testing.T) {
if testing.Short() {
t.Skip("compiles a wasm module; skipped in -short")
}
w := instantiateFixture(t)
resp := w.invoke(t, abiv1.Hook_HOOK_RENDER_BLOCK, &abiv1.RenderBlockRequest{
BlockKey: "wasmfixture:greeting",
ContentJson: []byte(`{"boom":true}`),
})
e := resp.GetError()
if e.GetCode() != abiv1.AbiErrorCode_ABI_ERROR_CODE_INTERNAL {
t.Fatalf("error = %v, want INTERNAL", e)
}
if !strings.Contains(e.GetMessage(), "fixture kaboom") {
t.Errorf("error message %q does not carry the panic value", e.GetMessage())
}
t.Logf("panic surfaced as AbiError: code=%s message=%q", e.GetCode(), e.GetMessage())
// The instance must remain callable after the recovered panic.
resp = w.invoke(t, abiv1.Hook_HOOK_RENDER_BLOCK, &abiv1.RenderBlockRequest{
BlockKey: "wasmfixture:greeting",
ContentJson: []byte(`{"name":"survivor"}`),
})
if resp.GetError() != nil {
t.Fatalf("post-panic render error: %v", resp.GetError())
}
rb := &abiv1.RenderBlockResponse{}
if err := proto.Unmarshal(resp.GetPayload(), rb); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if rb.GetHtml() != "<p>hello survivor</p>" {
t.Errorf("post-panic html = %q", rb.GetHtml())
}
t.Log("instance still callable after panic")
}
func TestWasmFixtureUnknownRequestPointerIsDecodeError(t *testing.T) {
if testing.Short() {
t.Skip("compiles a wasm module; skipped in -short")
}
w := instantiateFixture(t)
// Bypass bn_alloc: the guest must refuse pointers it did not hand out.
req, _ := proto.Marshal(&abiv1.InvokeRequest{Hook: abiv1.Hook_HOOK_DESCRIBE})
res, err := w.mod.ExportedFunction("bn_invoke").Call(w.ctx,
uint64(abiv1.Hook_HOOK_DESCRIBE), uint64(binary.MaxVarintLen64), uint64(len(req)))
if err != nil {
t.Fatalf("bn_invoke: %v", err)
}
packed := res[0]
if packed == 0 {
t.Fatal("packed 0")
}
respBytes, ok := w.mod.Memory().Read(uint32(packed>>32), uint32(packed))
if !ok {
t.Fatal("read response out of range")
}
resp := &abiv1.InvokeResponse{}
if err := proto.Unmarshal(respBytes, resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if resp.GetError().GetCode() != abiv1.AbiErrorCode_ABI_ERROR_CODE_DECODE {
t.Fatalf("error = %v, want DECODE", resp.GetError())
}
}