From 31ab6bef068c4c76c8e4f14f187c927105d83da6 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 04:26:05 +1100 Subject: [PATCH 01/12] fix(golang): compile the encrypttest engine once per test binary wazero's in-memory compilation cache counts the compiled modules that use an entry. It deletes the entry when the last of them closes. newInstance instantiates the guest from bytes. wazero closes a module compiled that way when the module closes. So a client that closed at the end of its test took the compiled guest out of the cache. The next test's client compiled it again. Under go test -race that took about 11 seconds a client, and about 1 second without it. Parallel tests that started clients at once each compiled the guest too. seededClient now pins each test build before it builds a client. The pin compiles the build once, on a runtime that is never closed. So the cache entry stays for the life of the test binary. That copy is never instantiated: each client still compiles on its own runtime and reads the compiled code from the cache. Callers that pin at once wait for one compile. The pinned compile runs one wazero compilation worker for each core. Under -race the first compile drops from about 11 seconds to between 2 and 7 seconds, depending on the core count. Only the test client path changes. Production clients and the deterministic test builds of the guest are unchanged. Refs #1900 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- languages/golang/CHANGELOG.md | 10 ++ .../golang/encrypt/encrypttest/client.go | 9 ++ .../golang/encrypt/pinned_builds_test.go | 151 ++++++++++++++++++ languages/golang/encrypt/testclient.go | 74 +++++++++ 4 files changed, 244 insertions(+) create mode 100644 languages/golang/encrypt/pinned_builds_test.go diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index bd7ebcd199..6c5932488d 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -13,6 +13,16 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ## [Unreleased] +### Fixed + +- `encrypttest.NewClient` compiles the engine once per test binary, not + once per client. A suite that started a client in each test compiled the + engine again in every test. Under `go test -race` that took about 11 + seconds a test. Now the first client compiles it, on every core. Every + later client starts in about 0.25 seconds under `-race`, and about 30 + milliseconds without it. Parallel tests that start clients at once wait + for one compile, where before each compiled the engine itself. + ## [0.1.0-rc.7] - 2026-11-25 ### Upgrading from rc.6 diff --git a/languages/golang/encrypt/encrypttest/client.go b/languages/golang/encrypt/encrypttest/client.go index 2b116e75d8..3f7a178371 100644 --- a/languages/golang/encrypt/encrypttest/client.go +++ b/languages/golang/encrypt/encrypttest/client.go @@ -88,6 +88,15 @@ func WithSeed(seed [32]byte) ClientOption { // or [encrypt.ErrForbidden] for a keyset the client has no grant for. The // client has no token, so it never returns [encrypt.ErrUnauthorized]. // +// # Start-up time +// +// The first client in a test binary compiles the engine, on every core. +// That takes under a second, or a few seconds under the race detector. The +// compiled engine is kept until the test binary exits, so every later +// client starts in tens of milliseconds, or a few hundred under the race +// detector. A client per test is fine. A client is also safe for +// concurrent use, so parallel tests may share one. +// // # Seeds // // Every client with the default seed opens what any other client with it diff --git a/languages/golang/encrypt/pinned_builds_test.go b/languages/golang/encrypt/pinned_builds_test.go new file mode 100644 index 0000000000..195867f407 --- /dev/null +++ b/languages/golang/encrypt/pinned_builds_test.go @@ -0,0 +1,151 @@ +package encrypt + +import ( + "context" + "errors" + goruntime "runtime" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/tetratelabs/wazero" + "github.com/tetratelabs/wazero/experimental" +) + +// countingBuilds is a pinnedBuilds whose compile counts its calls, waits +// a moment so that concurrent callers overlap, and fails while fail is set. +func countingBuilds() (*pinnedBuilds, *atomic.Int32, *atomic.Bool) { + var calls atomic.Int32 + var fail atomic.Bool + p := &pinnedBuilds{compile: func(context.Context, []byte) (any, error) { + calls.Add(1) + time.Sleep(20 * time.Millisecond) + if fail.Load() { + return nil, errCompile + } + return struct{}{}, nil + }} + return p, &calls, &fail +} + +var errCompile = errors.New("compile failed") + +// A test build compiles once in a process, however many clients start and +// close, one after another or at once. wazero drops a compiled module from +// its in-memory cache when the last runtime using it closes, so without the +// pin every client in a suite that starts one per test compiled the guest +// again: about ten seconds each under the race detector. +func TestPinnedBuilds(t *testing.T) { + for _, tt := range []struct { + name string + run func(t *testing.T, p *pinnedBuilds, fail *atomic.Bool) + want int32 + }{ + { + name: "one build pinned twice compiles once", + run: func(t *testing.T, p *pinnedBuilds, _ *atomic.Bool) { + pin(t, p, "a") + pin(t, p, "a") + }, + want: 1, + }, + { + name: "one build pinned at once by many callers compiles once", + run: func(t *testing.T, p *pinnedBuilds, _ *atomic.Bool) { + var wg sync.WaitGroup + for range 8 { + wg.Go(func() { pin(t, p, "a") }) + } + wg.Wait() + }, + want: 1, + }, + { + name: "each build compiles once", + run: func(t *testing.T, p *pinnedBuilds, _ *atomic.Bool) { + pin(t, p, "a") + pin(t, p, "b") + pin(t, p, "a") + }, + want: 2, + }, + { + name: "a failed compile is not pinned", + run: func(t *testing.T, p *pinnedBuilds, fail *atomic.Bool) { + fail.Store(true) + if err := p.pin(context.Background(), []byte("a")); !errors.Is(err, errCompile) { + t.Fatalf("%v, want the compile's error", err) + } + fail.Store(false) + pin(t, p, "a") + pin(t, p, "a") + }, + want: 2, + }, + } { + t.Run(tt.name, func(t *testing.T) { + p, calls, fail := countingBuilds() + tt.run(t, p, fail) + if got := calls.Load(); got != tt.want { + t.Fatalf("compiled %d times, want %d", got, tt.want) + } + }) + } +} + +func pin(t *testing.T, p *pinnedBuilds, wasm string) { + t.Helper() + if err := p.pin(context.Background(), []byte(wasm)); err != nil { + t.Error(err) + } +} + +// The real compile, over the guest this package embeds: once a build is +// pinned, a runtime that compiles it reads the cache, even after every +// other runtime that used the build has closed. Without the pin, wazero +// drops the build from the cache when the first runtime closes, and the +// last compile below takes as long as a cold one. +func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { + wasm, err := plainGuest() + if errors.Is(err, ErrGuestNotBuilt) { + t.Skip(err) + } + if err != nil { + t.Fatal(err) + } + ctx := experimental.WithCompilationWorkers(context.Background(), goruntime.GOMAXPROCS(0)) + // compile compiles wasm on a new runtime, closes the compiled module + // and the runtime, and returns how long the compile took. Closing the + // compiled module is what closing a client does: newInstance + // instantiates from bytes, and wazero closes a module compiled that way + // with the module. + compile := func(config wazero.RuntimeConfig) time.Duration { + t.Helper() + runtime := wazero.NewRuntimeWithConfig(ctx, config) + defer func() { _ = runtime.Close(ctx) }() + start := time.Now() + compiled, err := runtime.CompileModule(ctx, wasm) + if err != nil { + t.Fatal(err) + } + elapsed := time.Since(start) + _ = compiled.Close(ctx) + return elapsed + } + cold := compile(wazero.NewRuntimeConfig().WithCompilationCache(wazero.NewCompilationCache())) + + var p pinnedBuilds + if err := p.pin(context.Background(), wasm); err != nil { + t.Fatal(err) + } + shared := wazero.NewRuntimeConfig().WithCompilationCache(compilationCache()) + compile(shared) + if again := compile(shared); again > cold/4 { + t.Fatalf("a compile after the pin took %v and a cold compile %v: the pinned build left the cache", again, cold) + } + + if err := p.pin(context.Background(), []byte("not wasm")); err == nil { + t.Fatal("pinned bytes that are not a WebAssembly module") + } +} diff --git a/languages/golang/encrypt/testclient.go b/languages/golang/encrypt/testclient.go index 7fa3a36965..6bba844383 100644 --- a/languages/golang/encrypt/testclient.go +++ b/languages/golang/encrypt/testclient.go @@ -2,11 +2,16 @@ package encrypt import ( "context" + "crypto/sha256" "fmt" + goruntime "runtime" + "sync" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testclient" "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/vitaminc/bindings/go/vcffi" + "github.com/tetratelabs/wazero" + "github.com/tetratelabs/wazero/experimental" ) // Package encrypttest builds its clients through this constructor. It is @@ -30,6 +35,9 @@ func init() { // token and a transport that refuses every request, so nothing it does can // reach the network. func seededClient(ctx context.Context, wasm []byte, seed [32]byte) (*Client, error) { + if err := testBuilds.pin(ctx, wasm); err != nil { + return nil, err + } tr := &transport{rt: refusingTransport{}, token: noToken{}} inst, err := newInstance(ctx, wasm, tr, guest.BestEffort) if err != nil { @@ -55,3 +63,69 @@ func seededClient(ctx context.Context, wasm []byte, seed [32]byte) (*Client, err copy(c.def[:], out) return c, nil } + +// testBuilds holds every test build a test client has run, compiled. +var testBuilds pinnedBuilds + +// pinnedBuilds keeps each guest build it is given compiled in the shared +// compilation cache for the life of the process, so that test clients +// compile the guest once per test binary. +// +// wazero counts the runtimes that use a compiled module in its in-memory +// cache, and deletes the module when the last of them closes. A suite that +// starts a client in each test, and closes it when the test ends, would +// compile the guest again in every test: about one second each, and about +// ten under the race detector. Parallel tests that start clients at once +// would each compile it too. pin compiles each build once, on a runtime it +// never closes, so the count never reaches zero. That copy is never +// instantiated: every client still compiles on its own runtime, and reads +// the compiled code from the cache. +type pinnedBuilds struct { + mu sync.Mutex + pinned map[[sha256.Size]byte]any + // compile compiles wasm into the shared cache and returns what keeps + // it there. nil is compileForever; tests replace it. + compile func(ctx context.Context, wasm []byte) (any, error) +} + +// pin compiles wasm into the shared cache the first time it is given, and +// keeps it there. Callers given the same build at once wait for one +// compile. A compile that fails is not kept, so the next caller tries again. +func (p *pinnedBuilds) pin(ctx context.Context, wasm []byte) error { + key := sha256.Sum256(wasm) + p.mu.Lock() + defer p.mu.Unlock() + if _, ok := p.pinned[key]; ok { + return nil + } + compile := p.compile + if compile == nil { + compile = compileForever + } + kept, err := compile(ctx, wasm) + if err != nil { + return err + } + if p.pinned == nil { + p.pinned = map[[sha256.Size]byte]any{} + } + p.pinned[key] = kept + return nil +} + +// compileForever compiles wasm on a runtime that is never closed, with the +// configuration newInstance uses, so the module has the cache entry a +// client looks up. It compiles the guest's functions on every core: the +// compiled code is the same, and under the race detector the compile takes +// about ten seconds on one core. +func compileForever(ctx context.Context, wasm []byte) (any, error) { + config := wazero.NewRuntimeConfig(). + WithCompilationCache(compilationCache()) + runtime := wazero.NewRuntimeWithConfig(ctx, config) + compiled, err := runtime.CompileModule(experimental.WithCompilationWorkers(ctx, goruntime.GOMAXPROCS(0)), wasm) + if err != nil { + _ = runtime.Close(ctx) + return nil, fmt.Errorf("encrypt: compiling the test build: %w", err) + } + return compiled, nil +} From cf52248531fd1cd2d4352178b26cd351aae13867 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 04:40:14 +1100 Subject: [PATCH 02/12] test(golang): time the pinned-build check against a one-worker compile TestPinnedBuildsKeepTheGuestCompiled failed on CI. It compared a compile that reads the cache with a cold compile that ran one worker for each core. On a machine with many cores the cold compile took 133 milliseconds, and the cached one 46 milliseconds. The check fails when the cached one takes more than a quarter of the cold one. The compiles in the test now run on one worker. A cold compile then takes about 20 times as long as one that reads the cache, whatever the core count. The test still fails when the pinned module is closed. Refs #1900 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- languages/golang/encrypt/pinned_builds_test.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/languages/golang/encrypt/pinned_builds_test.go b/languages/golang/encrypt/pinned_builds_test.go index 195867f407..1620236f4a 100644 --- a/languages/golang/encrypt/pinned_builds_test.go +++ b/languages/golang/encrypt/pinned_builds_test.go @@ -3,14 +3,12 @@ package encrypt import ( "context" "errors" - goruntime "runtime" "sync" "sync/atomic" "testing" "time" "github.com/tetratelabs/wazero" - "github.com/tetratelabs/wazero/experimental" ) // countingBuilds is a pinnedBuilds whose compile counts its calls, waits @@ -114,7 +112,12 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { if err != nil { t.Fatal(err) } - ctx := experimental.WithCompilationWorkers(context.Background(), goruntime.GOMAXPROCS(0)) + // The compiles below run on one worker, so a compile that misses the + // cache takes about 20 times as long as one that reads it, on any + // number of cores. With a worker for each core, a machine with many + // cores compiles the guest only about 3 times slower than it reads it + // from the cache, which is too close to tell apart. + ctx := context.Background() // compile compiles wasm on a new runtime, closes the compiled module // and the runtime, and returns how long the compile took. Closing the // compiled module is what closing a client does: newInstance From bdb761084fe28906269382f1c895946da2d962ba Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 04:58:02 +1100 Subject: [PATCH 03/12] test(golang): skip the pinned-build timing check where wazero interprets TestPinnedBuildsKeepTheGuestCompiled failed in the GOARCH=386 run of the Go job. The previous commit read that failure wrongly, as a cold compile on many cores. On 386 wazero has no compiler and runs its interpreter. Its compile is cheap, so a cache hit was only about 3 times faster than a miss. The check fails when a hit takes more than a quarter of a miss. The timing check now runs only on amd64 and arm64, where wazero compiles to machine code. The check that bytes which are not WebAssembly are refused runs everywhere, before the skip. Refs #1900 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- .../golang/encrypt/pinned_builds_test.go | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/languages/golang/encrypt/pinned_builds_test.go b/languages/golang/encrypt/pinned_builds_test.go index 1620236f4a..233cb33de7 100644 --- a/languages/golang/encrypt/pinned_builds_test.go +++ b/languages/golang/encrypt/pinned_builds_test.go @@ -3,6 +3,7 @@ package encrypt import ( "context" "errors" + goruntime "runtime" "sync" "sync/atomic" "testing" @@ -112,11 +113,21 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { if err != nil { t.Fatal(err) } + var p pinnedBuilds + if err := p.pin(context.Background(), []byte("not wasm")); err == nil { + t.Fatal("pinned bytes that are not a WebAssembly module") + } + // wazero compiles to machine code on amd64 and arm64 only. Elsewhere, + // such as the 386 run in CI, it runs an interpreter, whose compile is + // cheap. There a compile that reads the cache is only about 3 times + // faster than one that misses it, which is too close to tell apart. + if goruntime.GOARCH != "amd64" && goruntime.GOARCH != "arm64" { + t.Skipf("wazero has no compiler on %s, so a cache hit cannot be told from a miss by time", goruntime.GOARCH) + } // The compiles below run on one worker, so a compile that misses the // cache takes about 20 times as long as one that reads it, on any - // number of cores. With a worker for each core, a machine with many - // cores compiles the guest only about 3 times slower than it reads it - // from the cache, which is too close to tell apart. + // number of cores. With a worker for each core, on 20 cores, it takes + // only about 5 times as long. ctx := context.Background() // compile compiles wasm on a new runtime, closes the compiled module // and the runtime, and returns how long the compile took. Closing the @@ -138,7 +149,6 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { } cold := compile(wazero.NewRuntimeConfig().WithCompilationCache(wazero.NewCompilationCache())) - var p pinnedBuilds if err := p.pin(context.Background(), wasm); err != nil { t.Fatal(err) } @@ -147,8 +157,4 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { if again := compile(shared); again > cold/4 { t.Fatalf("a compile after the pin took %v and a cold compile %v: the pinned build left the cache", again, cold) } - - if err := p.pin(context.Background(), []byte("not wasm")); err == nil { - t.Fatal("pinned bytes that are not a WebAssembly module") - } } From 5d8cbbc75b81c826d7e6dc617f0b6dc3df6c13ef Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 04:26:05 +1100 Subject: [PATCH 04/12] fix(golang): compile the encrypttest engine once per test binary wazero's in-memory compilation cache counts the compiled modules that use an entry. It deletes the entry when the last of them closes. newInstance instantiates the guest from bytes. wazero closes a module compiled that way when the module closes. So a client that closed at the end of its test took the compiled guest out of the cache. The next test's client compiled it again. Under go test -race that took about 11 seconds a client, and about 1 second without it. Parallel tests that started clients at once each compiled the guest too. seededClient now pins each test build before it builds a client. The pin compiles the build once, on a runtime that is never closed. So the cache entry stays for the life of the test binary. That copy is never instantiated: each client still compiles on its own runtime and reads the compiled code from the cache. Callers that pin at once wait for one compile. The pinned compile runs one wazero compilation worker for each core. Under -race the first compile drops from about 11 seconds to between 2 and 7 seconds, depending on the core count. Only the test client path changes. Production clients and the deterministic test builds of the guest are unchanged. Refs #1900 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- languages/golang/CHANGELOG.md | 10 ++ .../golang/encrypt/encrypttest/client.go | 9 ++ .../golang/encrypt/pinned_builds_test.go | 151 ++++++++++++++++++ languages/golang/encrypt/testclient.go | 74 +++++++++ 4 files changed, 244 insertions(+) create mode 100644 languages/golang/encrypt/pinned_builds_test.go diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 6833efd306..ad1d6d46e5 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -22,6 +22,16 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. `[16]byte` (`github.com/google/uuid.UUID`, say), which is converted to one. `stashgen` does not yet map a Go type to it. +### Fixed + +- `encrypttest.NewClient` compiles the engine once per test binary, not + once per client. A suite that started a client in each test compiled the + engine again in every test. Under `go test -race` that took about 11 + seconds a test. Now the first client compiles it, on every core. Every + later client starts in about 0.25 seconds under `-race`, and about 30 + milliseconds without it. Parallel tests that start clients at once wait + for one compile, where before each compiled the engine itself. + ## [0.1.0-rc.7] - 2026-11-25 ### Upgrading from rc.6 diff --git a/languages/golang/encrypt/encrypttest/client.go b/languages/golang/encrypt/encrypttest/client.go index 2b116e75d8..3f7a178371 100644 --- a/languages/golang/encrypt/encrypttest/client.go +++ b/languages/golang/encrypt/encrypttest/client.go @@ -88,6 +88,15 @@ func WithSeed(seed [32]byte) ClientOption { // or [encrypt.ErrForbidden] for a keyset the client has no grant for. The // client has no token, so it never returns [encrypt.ErrUnauthorized]. // +// # Start-up time +// +// The first client in a test binary compiles the engine, on every core. +// That takes under a second, or a few seconds under the race detector. The +// compiled engine is kept until the test binary exits, so every later +// client starts in tens of milliseconds, or a few hundred under the race +// detector. A client per test is fine. A client is also safe for +// concurrent use, so parallel tests may share one. +// // # Seeds // // Every client with the default seed opens what any other client with it diff --git a/languages/golang/encrypt/pinned_builds_test.go b/languages/golang/encrypt/pinned_builds_test.go new file mode 100644 index 0000000000..195867f407 --- /dev/null +++ b/languages/golang/encrypt/pinned_builds_test.go @@ -0,0 +1,151 @@ +package encrypt + +import ( + "context" + "errors" + goruntime "runtime" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/tetratelabs/wazero" + "github.com/tetratelabs/wazero/experimental" +) + +// countingBuilds is a pinnedBuilds whose compile counts its calls, waits +// a moment so that concurrent callers overlap, and fails while fail is set. +func countingBuilds() (*pinnedBuilds, *atomic.Int32, *atomic.Bool) { + var calls atomic.Int32 + var fail atomic.Bool + p := &pinnedBuilds{compile: func(context.Context, []byte) (any, error) { + calls.Add(1) + time.Sleep(20 * time.Millisecond) + if fail.Load() { + return nil, errCompile + } + return struct{}{}, nil + }} + return p, &calls, &fail +} + +var errCompile = errors.New("compile failed") + +// A test build compiles once in a process, however many clients start and +// close, one after another or at once. wazero drops a compiled module from +// its in-memory cache when the last runtime using it closes, so without the +// pin every client in a suite that starts one per test compiled the guest +// again: about ten seconds each under the race detector. +func TestPinnedBuilds(t *testing.T) { + for _, tt := range []struct { + name string + run func(t *testing.T, p *pinnedBuilds, fail *atomic.Bool) + want int32 + }{ + { + name: "one build pinned twice compiles once", + run: func(t *testing.T, p *pinnedBuilds, _ *atomic.Bool) { + pin(t, p, "a") + pin(t, p, "a") + }, + want: 1, + }, + { + name: "one build pinned at once by many callers compiles once", + run: func(t *testing.T, p *pinnedBuilds, _ *atomic.Bool) { + var wg sync.WaitGroup + for range 8 { + wg.Go(func() { pin(t, p, "a") }) + } + wg.Wait() + }, + want: 1, + }, + { + name: "each build compiles once", + run: func(t *testing.T, p *pinnedBuilds, _ *atomic.Bool) { + pin(t, p, "a") + pin(t, p, "b") + pin(t, p, "a") + }, + want: 2, + }, + { + name: "a failed compile is not pinned", + run: func(t *testing.T, p *pinnedBuilds, fail *atomic.Bool) { + fail.Store(true) + if err := p.pin(context.Background(), []byte("a")); !errors.Is(err, errCompile) { + t.Fatalf("%v, want the compile's error", err) + } + fail.Store(false) + pin(t, p, "a") + pin(t, p, "a") + }, + want: 2, + }, + } { + t.Run(tt.name, func(t *testing.T) { + p, calls, fail := countingBuilds() + tt.run(t, p, fail) + if got := calls.Load(); got != tt.want { + t.Fatalf("compiled %d times, want %d", got, tt.want) + } + }) + } +} + +func pin(t *testing.T, p *pinnedBuilds, wasm string) { + t.Helper() + if err := p.pin(context.Background(), []byte(wasm)); err != nil { + t.Error(err) + } +} + +// The real compile, over the guest this package embeds: once a build is +// pinned, a runtime that compiles it reads the cache, even after every +// other runtime that used the build has closed. Without the pin, wazero +// drops the build from the cache when the first runtime closes, and the +// last compile below takes as long as a cold one. +func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { + wasm, err := plainGuest() + if errors.Is(err, ErrGuestNotBuilt) { + t.Skip(err) + } + if err != nil { + t.Fatal(err) + } + ctx := experimental.WithCompilationWorkers(context.Background(), goruntime.GOMAXPROCS(0)) + // compile compiles wasm on a new runtime, closes the compiled module + // and the runtime, and returns how long the compile took. Closing the + // compiled module is what closing a client does: newInstance + // instantiates from bytes, and wazero closes a module compiled that way + // with the module. + compile := func(config wazero.RuntimeConfig) time.Duration { + t.Helper() + runtime := wazero.NewRuntimeWithConfig(ctx, config) + defer func() { _ = runtime.Close(ctx) }() + start := time.Now() + compiled, err := runtime.CompileModule(ctx, wasm) + if err != nil { + t.Fatal(err) + } + elapsed := time.Since(start) + _ = compiled.Close(ctx) + return elapsed + } + cold := compile(wazero.NewRuntimeConfig().WithCompilationCache(wazero.NewCompilationCache())) + + var p pinnedBuilds + if err := p.pin(context.Background(), wasm); err != nil { + t.Fatal(err) + } + shared := wazero.NewRuntimeConfig().WithCompilationCache(compilationCache()) + compile(shared) + if again := compile(shared); again > cold/4 { + t.Fatalf("a compile after the pin took %v and a cold compile %v: the pinned build left the cache", again, cold) + } + + if err := p.pin(context.Background(), []byte("not wasm")); err == nil { + t.Fatal("pinned bytes that are not a WebAssembly module") + } +} diff --git a/languages/golang/encrypt/testclient.go b/languages/golang/encrypt/testclient.go index 7fa3a36965..6bba844383 100644 --- a/languages/golang/encrypt/testclient.go +++ b/languages/golang/encrypt/testclient.go @@ -2,11 +2,16 @@ package encrypt import ( "context" + "crypto/sha256" "fmt" + goruntime "runtime" + "sync" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testclient" "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/vitaminc/bindings/go/vcffi" + "github.com/tetratelabs/wazero" + "github.com/tetratelabs/wazero/experimental" ) // Package encrypttest builds its clients through this constructor. It is @@ -30,6 +35,9 @@ func init() { // token and a transport that refuses every request, so nothing it does can // reach the network. func seededClient(ctx context.Context, wasm []byte, seed [32]byte) (*Client, error) { + if err := testBuilds.pin(ctx, wasm); err != nil { + return nil, err + } tr := &transport{rt: refusingTransport{}, token: noToken{}} inst, err := newInstance(ctx, wasm, tr, guest.BestEffort) if err != nil { @@ -55,3 +63,69 @@ func seededClient(ctx context.Context, wasm []byte, seed [32]byte) (*Client, err copy(c.def[:], out) return c, nil } + +// testBuilds holds every test build a test client has run, compiled. +var testBuilds pinnedBuilds + +// pinnedBuilds keeps each guest build it is given compiled in the shared +// compilation cache for the life of the process, so that test clients +// compile the guest once per test binary. +// +// wazero counts the runtimes that use a compiled module in its in-memory +// cache, and deletes the module when the last of them closes. A suite that +// starts a client in each test, and closes it when the test ends, would +// compile the guest again in every test: about one second each, and about +// ten under the race detector. Parallel tests that start clients at once +// would each compile it too. pin compiles each build once, on a runtime it +// never closes, so the count never reaches zero. That copy is never +// instantiated: every client still compiles on its own runtime, and reads +// the compiled code from the cache. +type pinnedBuilds struct { + mu sync.Mutex + pinned map[[sha256.Size]byte]any + // compile compiles wasm into the shared cache and returns what keeps + // it there. nil is compileForever; tests replace it. + compile func(ctx context.Context, wasm []byte) (any, error) +} + +// pin compiles wasm into the shared cache the first time it is given, and +// keeps it there. Callers given the same build at once wait for one +// compile. A compile that fails is not kept, so the next caller tries again. +func (p *pinnedBuilds) pin(ctx context.Context, wasm []byte) error { + key := sha256.Sum256(wasm) + p.mu.Lock() + defer p.mu.Unlock() + if _, ok := p.pinned[key]; ok { + return nil + } + compile := p.compile + if compile == nil { + compile = compileForever + } + kept, err := compile(ctx, wasm) + if err != nil { + return err + } + if p.pinned == nil { + p.pinned = map[[sha256.Size]byte]any{} + } + p.pinned[key] = kept + return nil +} + +// compileForever compiles wasm on a runtime that is never closed, with the +// configuration newInstance uses, so the module has the cache entry a +// client looks up. It compiles the guest's functions on every core: the +// compiled code is the same, and under the race detector the compile takes +// about ten seconds on one core. +func compileForever(ctx context.Context, wasm []byte) (any, error) { + config := wazero.NewRuntimeConfig(). + WithCompilationCache(compilationCache()) + runtime := wazero.NewRuntimeWithConfig(ctx, config) + compiled, err := runtime.CompileModule(experimental.WithCompilationWorkers(ctx, goruntime.GOMAXPROCS(0)), wasm) + if err != nil { + _ = runtime.Close(ctx) + return nil, fmt.Errorf("encrypt: compiling the test build: %w", err) + } + return compiled, nil +} From 9303fc37d9a2dcc44e592520180486a30290937a Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 04:40:14 +1100 Subject: [PATCH 05/12] test(golang): time the pinned-build check against a one-worker compile TestPinnedBuildsKeepTheGuestCompiled failed on CI. It compared a compile that reads the cache with a cold compile that ran one worker for each core. On a machine with many cores the cold compile took 133 milliseconds, and the cached one 46 milliseconds. The check fails when the cached one takes more than a quarter of the cold one. The compiles in the test now run on one worker. A cold compile then takes about 20 times as long as one that reads the cache, whatever the core count. The test still fails when the pinned module is closed. Refs #1900 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- languages/golang/encrypt/pinned_builds_test.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/languages/golang/encrypt/pinned_builds_test.go b/languages/golang/encrypt/pinned_builds_test.go index 195867f407..1620236f4a 100644 --- a/languages/golang/encrypt/pinned_builds_test.go +++ b/languages/golang/encrypt/pinned_builds_test.go @@ -3,14 +3,12 @@ package encrypt import ( "context" "errors" - goruntime "runtime" "sync" "sync/atomic" "testing" "time" "github.com/tetratelabs/wazero" - "github.com/tetratelabs/wazero/experimental" ) // countingBuilds is a pinnedBuilds whose compile counts its calls, waits @@ -114,7 +112,12 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { if err != nil { t.Fatal(err) } - ctx := experimental.WithCompilationWorkers(context.Background(), goruntime.GOMAXPROCS(0)) + // The compiles below run on one worker, so a compile that misses the + // cache takes about 20 times as long as one that reads it, on any + // number of cores. With a worker for each core, a machine with many + // cores compiles the guest only about 3 times slower than it reads it + // from the cache, which is too close to tell apart. + ctx := context.Background() // compile compiles wasm on a new runtime, closes the compiled module // and the runtime, and returns how long the compile took. Closing the // compiled module is what closing a client does: newInstance From 4e9abb933999c7a5e891e92bbb382419e2867715 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 04:58:02 +1100 Subject: [PATCH 06/12] test(golang): skip the pinned-build timing check where wazero interprets TestPinnedBuildsKeepTheGuestCompiled failed in the GOARCH=386 run of the Go job. The previous commit read that failure wrongly, as a cold compile on many cores. On 386 wazero has no compiler and runs its interpreter. Its compile is cheap, so a cache hit was only about 3 times faster than a miss. The check fails when a hit takes more than a quarter of a miss. The timing check now runs only on amd64 and arm64, where wazero compiles to machine code. The check that bytes which are not WebAssembly are refused runs everywhere, before the skip. Refs #1900 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- .../golang/encrypt/pinned_builds_test.go | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/languages/golang/encrypt/pinned_builds_test.go b/languages/golang/encrypt/pinned_builds_test.go index 1620236f4a..233cb33de7 100644 --- a/languages/golang/encrypt/pinned_builds_test.go +++ b/languages/golang/encrypt/pinned_builds_test.go @@ -3,6 +3,7 @@ package encrypt import ( "context" "errors" + goruntime "runtime" "sync" "sync/atomic" "testing" @@ -112,11 +113,21 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { if err != nil { t.Fatal(err) } + var p pinnedBuilds + if err := p.pin(context.Background(), []byte("not wasm")); err == nil { + t.Fatal("pinned bytes that are not a WebAssembly module") + } + // wazero compiles to machine code on amd64 and arm64 only. Elsewhere, + // such as the 386 run in CI, it runs an interpreter, whose compile is + // cheap. There a compile that reads the cache is only about 3 times + // faster than one that misses it, which is too close to tell apart. + if goruntime.GOARCH != "amd64" && goruntime.GOARCH != "arm64" { + t.Skipf("wazero has no compiler on %s, so a cache hit cannot be told from a miss by time", goruntime.GOARCH) + } // The compiles below run on one worker, so a compile that misses the // cache takes about 20 times as long as one that reads it, on any - // number of cores. With a worker for each core, a machine with many - // cores compiles the guest only about 3 times slower than it reads it - // from the cache, which is too close to tell apart. + // number of cores. With a worker for each core, on 20 cores, it takes + // only about 5 times as long. ctx := context.Background() // compile compiles wasm on a new runtime, closes the compiled module // and the runtime, and returns how long the compile took. Closing the @@ -138,7 +149,6 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { } cold := compile(wazero.NewRuntimeConfig().WithCompilationCache(wazero.NewCompilationCache())) - var p pinnedBuilds if err := p.pin(context.Background(), wasm); err != nil { t.Fatal(err) } @@ -147,8 +157,4 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { if again := compile(shared); again > cold/4 { t.Fatalf("a compile after the pin took %v and a cold compile %v: the pinned build left the cache", again, cold) } - - if err := p.pin(context.Background(), []byte("not wasm")); err == nil { - t.Fatal("pinned bytes that are not a WebAssembly module") - } } From 17e9fe2c5b9551fe5bc66b897421609c4c38c937 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 17:09:23 +1100 Subject: [PATCH 07/12] test(golang): check that a test client pins the build it runs seededClient pins its build before it starts a client, but no test checked it: with the pin removed, every encrypt and encrypttest test still passed. The new test builds a client over each deterministic build and checks that the build's SHA-256 is in testBuilds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- .../golang/encrypt/pinned_builds_test.go | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/languages/golang/encrypt/pinned_builds_test.go b/languages/golang/encrypt/pinned_builds_test.go index 233cb33de7..65a829f6f4 100644 --- a/languages/golang/encrypt/pinned_builds_test.go +++ b/languages/golang/encrypt/pinned_builds_test.go @@ -2,7 +2,9 @@ package encrypt import ( "context" + "crypto/sha256" "errors" + "os" goruntime "runtime" "sync" "sync/atomic" @@ -93,6 +95,51 @@ func TestPinnedBuilds(t *testing.T) { } } +// A test client pins the build it runs, so that the next client over the +// same build reads the compiled code from the cache. Every test client is +// built by seededClient, package encrypttest's included. Each build is its +// own subtest, so a build that is absent shows as a skip. +func TestSeededClientPinsItsBuild(t *testing.T) { + eqlBuild := func() ([]byte, error) { + wasm, err := os.ReadFile(deterministicEQLGuestPath) + if errors.Is(err, os.ErrNotExist) { + return nil, ErrDeterministicEQLGuestNotBuilt + } + return wasm, err + } + for _, build := range []struct { + name string + load func() ([]byte, error) + absent error + }{ + {"without the EQL types", DeterministicGuest, ErrDeterministicGuestNotBuilt}, + {"with the EQL types", eqlBuild, ErrDeterministicEQLGuestNotBuilt}, + } { + t.Run(build.name, func(t *testing.T) { + wasm, err := build.load() + if errors.Is(err, build.absent) { + t.Skip(err) + } + if err != nil { + t.Fatal(err) + } + c, err := seededClient(context.Background(), wasm, [32]byte{7}) + if err != nil { + t.Fatal(err) + } + if err := c.Close(); err != nil { + t.Error(err) + } + testBuilds.mu.Lock() + _, ok := testBuilds.pinned[sha256.Sum256(wasm)] + testBuilds.mu.Unlock() + if !ok { + t.Fatal("seededClient did not pin the build it ran") + } + }) + } +} + func pin(t *testing.T, p *pinnedBuilds, wasm string) { t.Helper() if err := p.pin(context.Background(), []byte(wasm)); err != nil { From f2c90455a40211c91c957b5a9bdd5ef527647721 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 17:10:21 +1100 Subject: [PATCH 08/12] perf(golang): compile the AssertContexts engine once per test binary Each call to encrypttest.AssertContexts or encrypttest.Contexts made a checker over the production build, and then closed it. wazero drops a compiled module when the last runtime using it closes. So each call compiled the engine again. That took about 1 second, or 10 to 50 seconds under the race detector. Contexts now gets its checker through internal/testclient, over the test build that encrypttest.NewClient runs. Package encrypt keeps that build compiled with the pinnedBuilds from #1942, so clients and checkers in one test binary share one compile. Under -race, the three AssertContexts tests in encrypttest went from 138 seconds to 5. Refs #1976 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- languages/golang/CHANGELOG.md | 11 +++- languages/golang/encrypt/checker.go | 5 ++ .../golang/encrypt/encrypttest/encrypttest.go | 16 +++++- .../encrypt/encrypttest/encrypttest_test.go | 11 ---- languages/golang/encrypt/export_test.go | 7 +-- .../encrypt/internal/testclient/testclient.go | 32 ++++++++--- .../golang/encrypt/pinned_builds_test.go | 53 +++++++++++++++++++ languages/golang/encrypt/testclient.go | 24 +++++++-- 8 files changed, 129 insertions(+), 30 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 14bb7549be..7fccaa69af 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -22,9 +22,18 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. `[16]byte` (`github.com/google/uuid.UUID`, say), which is converted to one. `stashgen` does not yet map a Go type to it. - ### Fixed +- `encrypttest.AssertContexts` and `encrypttest.Contexts` compile the + engine once per test binary, not once per call. Before, each call + compiled it: about 1 second, or 10 to 50 seconds under the race + detector. They now ask the test build that `encrypttest.NewClient` runs, + so a test binary that uses both compiles one build. In this module's own + tests, the three `AssertContexts` tests took 138 seconds under `-race`, + and now take 5. A checkout of the repository now needs the test build + for them (`mise run wasm:guest:build:deterministic`), as `NewClient` + already does. A released module includes it. + - `encrypttest.NewClient` compiles the engine once per test binary, not once per client. A suite that started a client in each test compiled the engine again in every test. Under `go test -race` that took about 11 diff --git a/languages/golang/encrypt/checker.go b/languages/golang/encrypt/checker.go index ca448fbc3b..3ee4bcc262 100644 --- a/languages/golang/encrypt/checker.go +++ b/languages/golang/encrypt/checker.go @@ -27,6 +27,11 @@ func NewChecker(ctx context.Context) (*Checker, error) { if err != nil { return nil, err } + return newCheckerOver(ctx, wasm) +} + +// newCheckerOver is a checker over wasm, a build of the guest. +func newCheckerOver(ctx context.Context, wasm []byte) (*Checker, error) { t := &transport{rt: refusingTransport{}, token: noToken{}} inst, err := newInstance(ctx, wasm, t, guest.BestEffort) if err != nil { diff --git a/languages/golang/encrypt/encrypttest/encrypttest.go b/languages/golang/encrypt/encrypttest/encrypttest.go index d72919d43e..9473ab7a7d 100644 --- a/languages/golang/encrypt/encrypttest/encrypttest.go +++ b/languages/golang/encrypt/encrypttest/encrypttest.go @@ -26,6 +26,7 @@ import ( "github.com/cipherstash/stack/languages/golang/encrypt" "github.com/cipherstash/stack/languages/golang/encrypt/gensupport" + "github.com/cipherstash/stack/languages/golang/encrypt/internal/testclient" "github.com/cipherstash/stack/languages/golang/internal/record" ) @@ -34,13 +35,24 @@ import ( // context: "email\n context: users / email\n". It needs no credentials // and no network. [AssertContexts] reads this text; a test that wants the // text itself, to print or to compare whole, calls this. +// +// It asks the test build of the engine that [NewClient] runs. The first +// call, or the first client, in a test binary compiles that build, and +// every later call reuses it. func Contexts(ctx context.Context, d gensupport.Declaration) (string, error) { if err := versionSkew(); err != nil { return "", err } - checker, err := encrypt.NewChecker(ctx) + built, err := testclient.NewChecker(ctx, plainTestBuild, eqlTestBuild) if err != nil { - return "", err + return "", fmt.Errorf("encrypttest: %w", err) + } + checker, ok := built.(*encrypt.Checker) + if !ok { + if closer, ok := built.(interface{ Close() error }); ok { + _ = closer.Close() + } + return "", fmt.Errorf("encrypttest: the checker constructor returned %T, not *encrypt.Checker", built) } defer func() { _ = checker.Close() }() return d.Contexts(ctx, checker) diff --git a/languages/golang/encrypt/encrypttest/encrypttest_test.go b/languages/golang/encrypt/encrypttest/encrypttest_test.go index 986c0805c7..8a406a7e92 100644 --- a/languages/golang/encrypt/encrypttest/encrypttest_test.go +++ b/languages/golang/encrypt/encrypttest/encrypttest_test.go @@ -2,7 +2,6 @@ package encrypttest_test import ( "context" - "errors" "fmt" "strings" "testing" @@ -30,15 +29,7 @@ func users() gensupport.Declaration { Encrypt("notes", gensupport.String) } -func skipWithoutGuest(t *testing.T) { - t.Helper() - if _, err := encrypttest.Contexts(context.Background(), users()); errors.Is(err, encrypt.ErrGuestNotBuilt) { - t.Skip(err) - } -} - func TestAssertContextsPassesOnTheEnginesContexts(t *testing.T) { - skipWithoutGuest(t) encrypttest.AssertContexts(t, users(), encrypttest.Field("email", "users", "email"), encrypttest.Field("notes", "users", "notes"), @@ -54,7 +45,6 @@ func TestAssertContextsPassesOnTheEnginesContexts(t *testing.T) { } func TestAssertContextsNamesTheFirstFieldThatDiffers(t *testing.T) { - skipWithoutGuest(t) r := &recorder{TB: t} encrypttest.AssertContexts(r, users(), encrypttest.Field("email", "users", "email"), @@ -101,7 +91,6 @@ func TestAssertContextsNamesTheFirstFieldThatDiffers(t *testing.T) { } func TestAssertContextsReportsARefusedDeclaration(t *testing.T) { - skipWithoutGuest(t) bad := gensupport.Declare("users").EncryptIndex("age", gensupport.Uint32, encrypt.Match()) r := &recorder{TB: t} encrypttest.AssertContexts(r, bad) diff --git a/languages/golang/encrypt/export_test.go b/languages/golang/encrypt/export_test.go index c5930af7e5..a44bcba5a3 100644 --- a/languages/golang/encrypt/export_test.go +++ b/languages/golang/encrypt/export_test.go @@ -159,12 +159,7 @@ func PlainGuest() ([]byte, error) { // NewCheckerOver is NewChecker over the given guest bytes, so a test asks a // named build its questions. func NewCheckerOver(ctx context.Context, wasm []byte) (*Checker, error) { - t := &transport{rt: refusingTransport{}, token: noToken{}} - inst, err := newInstance(ctx, wasm, t, guest.BestEffort) - if err != nil { - return nil, err - } - return &Checker{c: newClient(inst, t)}, nil + return newCheckerOver(ctx, wasm) } // LiveClient is liveClient for the external tests: a client against real diff --git a/languages/golang/encrypt/internal/testclient/testclient.go b/languages/golang/encrypt/internal/testclient/testclient.go index 38fcc0b88d..cd0b7abaad 100644 --- a/languages/golang/encrypt/internal/testclient/testclient.go +++ b/languages/golang/encrypt/internal/testclient/testclient.go @@ -1,9 +1,9 @@ // Package testclient is where package encrypt hands package encrypttest the -// one constructor it needs: a client over a given guest build, initialised -// with a seed in place of a client key. The constructor reaches encrypt's -// unexported instance and client, and encrypttest imports encrypt, so encrypt -// registers it here on init. Nothing outside the encrypt tree can import this -// package, so the constructor is in no public API. +// two constructors it needs: a client over a given guest build, initialised +// with a seed in place of a client key, and a checker over a given guest +// build. The constructors reach encrypt's unexported instance and client, +// and encrypttest imports encrypt, so encrypt registers them here on init. Nothing outside the encrypt tree can import this +// package, so the constructors are in no public API. package testclient import ( @@ -21,8 +21,18 @@ type Constructor func(ctx context.Context, plain, withEQL func() ([]byte, error) var constructor Constructor -// Register installs encrypt's constructor. Called once, by encrypt's init. -func Register(c Constructor) { constructor = c } +// CheckerConstructor builds a checker over a test build of the guest, +// the one a production client in this program would match, as Constructor +// picks it. It returns the *encrypt.Checker as any. +type CheckerConstructor func(ctx context.Context, plain, withEQL func() ([]byte, error)) (any, error) + +var checkerConstructor CheckerConstructor + +// Register installs encrypt's constructors. Called once, by encrypt's init. +func Register(c Constructor, k CheckerConstructor) { + constructor = c + checkerConstructor = k +} // errNotRegistered is a program that reached New without package encrypt // initialised, which the import graph rules out. @@ -35,3 +45,11 @@ func New(ctx context.Context, plain, withEQL func() ([]byte, error), seed [32]by } return constructor(ctx, plain, withEQL, seed) } + +// NewChecker calls the registered checker constructor. +func NewChecker(ctx context.Context, plain, withEQL func() ([]byte, error)) (any, error) { + if checkerConstructor == nil { + return nil, errNotRegistered + } + return checkerConstructor(ctx, plain, withEQL) +} diff --git a/languages/golang/encrypt/pinned_builds_test.go b/languages/golang/encrypt/pinned_builds_test.go index 233cb33de7..0c6261ee83 100644 --- a/languages/golang/encrypt/pinned_builds_test.go +++ b/languages/golang/encrypt/pinned_builds_test.go @@ -10,6 +10,8 @@ import ( "time" "github.com/tetratelabs/wazero" + + "github.com/cipherstash/stack/languages/golang/internal/record" ) // countingBuilds is a pinnedBuilds whose compile counts its calls, waits @@ -158,3 +160,54 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { t.Fatalf("a compile after the pin took %v and a cold compile %v: the pinned build left the cache", again, cold) } } + +// encrypttest.AssertContexts and encrypttest.Contexts make a new checker +// on every call, and close it before they return. A checker over a test +// build compiles that build once in a process, however many are made and +// closed. Before, each call compiled the guest again: under the race +// detector, 10 to 50 seconds a call. +func TestTestCheckersCompileTheirBuildOnce(t *testing.T) { + if _, err := plainGuest(); errors.Is(err, ErrGuestNotBuilt) { + t.Skip(err) + } + var calls atomic.Int32 + builds := &pinnedBuilds{compile: func(ctx context.Context, wasm []byte) (any, error) { + calls.Add(1) + return compileForever(ctx, wasm) + }} + ctx := context.Background() + plan := &record.Plan{ + Context: []string{"users"}, + Fields: []record.Field{{Name: "email", Kind: record.String, Outputs: []record.Output{record.Ciphertext}}}, + } + for range 3 { + // The same loader for both builds: whichever one selectBuild picks + // in this binary, it is this build. + checker, err := testChecker(ctx, builds, plainGuest, plainGuest) + if err != nil { + t.Fatal(err) + } + if _, err := checker.Contexts(ctx, plan); err != nil { + t.Fatal(err) + } + if err := checker.Close(); err != nil { + t.Fatal(err) + } + } + if got := calls.Load(); got != 1 { + t.Fatalf("compiled %d times, want 1", got) + } +} + +// A test build that is not there is the loader's error, and nothing is +// compiled or kept. +func TestATestCheckerWithoutItsBuildIsTheLoadersError(t *testing.T) { + builds, calls, _ := countingBuilds() + missing := func() ([]byte, error) { return nil, errCompile } + if _, err := testChecker(context.Background(), builds, missing, missing); !errors.Is(err, errCompile) { + t.Fatalf("%v, want the loader's error", err) + } + if got := calls.Load(); got != 0 { + t.Fatalf("compiled %d times, want 0", got) + } +} diff --git a/languages/golang/encrypt/testclient.go b/languages/golang/encrypt/testclient.go index 6bba844383..bfeedf524b 100644 --- a/languages/golang/encrypt/testclient.go +++ b/languages/golang/encrypt/testclient.go @@ -27,9 +27,26 @@ func init() { return nil, err } return seededClient(ctx, wasm, seed) + }, func(ctx context.Context, plain, withEQL func() ([]byte, error)) (any, error) { + return testChecker(ctx, &testBuilds, plain, withEQL) }) } +// testChecker is a checker over the test build selectBuild picks, the one +// a test client in this program runs. builds keeps that build compiled, so +// that encrypttest.AssertContexts, which makes a checker on every call, +// compiles the guest once per test binary, and not on every call. +func testChecker(ctx context.Context, builds *pinnedBuilds, plain, withEQL func() ([]byte, error)) (*Checker, error) { + wasm, err := selectBuild(plain, withEQL) + if err != nil { + return nil, err + } + if err := builds.pin(ctx, wasm); err != nil { + return nil, err + } + return newCheckerOver(ctx, wasm) +} + // seededClient is a client over wasm, a deterministic-kms build of the // guest. Its config is the 32-byte seed every key derives from. It has no // token and a transport that refuses every request, so nothing it does can @@ -64,12 +81,13 @@ func seededClient(ctx context.Context, wasm []byte, seed [32]byte) (*Client, err return c, nil } -// testBuilds holds every test build a test client has run, compiled. +// testBuilds holds every test build a test client or checker has run, +// compiled. var testBuilds pinnedBuilds // pinnedBuilds keeps each guest build it is given compiled in the shared -// compilation cache for the life of the process, so that test clients -// compile the guest once per test binary. +// compilation cache for the life of the process, so that test clients and +// checkers compile the guest once per test binary. // // wazero counts the runtimes that use a compiled module in its in-memory // cache, and deletes the module when the last of them closes. A suite that From 2102a008584133c7c0bc96738df6cbcab0fb74e4 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 18:00:16 +1100 Subject: [PATCH 09/12] test(golang): check that encrypttest's checker pins the build it runs Review follow-up. A new test calls the registered checker constructor through internal/testclient, and checks that the package's testBuilds contains the build it ran. The earlier test passed its own pinnedBuilds, so it would still pass if the registration stopped pinning. newInstance and compileForever now share one runtime configuration, from guestRuntimeConfig. The cache finds a compiled module by parts of that configuration, so the two must not drift apart. encrypttest narrows what its two constructors return with one generic helper, in place of two copies of the same steps. The example's contexts test no longer skips when the production build is missing. Contexts now runs the test build, so that skip could never match. The test needs the test build, as encrypttest's own tests do. The Contexts doc comment says it asks the test build, and that the test build gives the same contexts as the production build. The deterministic-kms feature changes only the key source, its config, and cipher_init (encrypt/guest/src/abi.rs). se_contexts calls the shared ops::contexts. Refs #1976 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- .../golang/encrypt/encrypttest/client.go | 9 +--- .../encrypttest/client_internal_test.go | 36 ++++++++++++++++ .../golang/encrypt/encrypttest/encrypttest.go | 34 ++++++++++----- .../encrypt/example/user_contexts_test.go | 6 --- languages/golang/encrypt/guest.go | 15 +++++-- .../encrypt/internal/testclient/testclient.go | 5 ++- .../golang/encrypt/pinned_builds_test.go | 41 ++++++++++++++++++- languages/golang/encrypt/testclient.go | 14 +++---- 8 files changed, 122 insertions(+), 38 deletions(-) diff --git a/languages/golang/encrypt/encrypttest/client.go b/languages/golang/encrypt/encrypttest/client.go index 3f7a178371..2866c2dfe3 100644 --- a/languages/golang/encrypt/encrypttest/client.go +++ b/languages/golang/encrypt/encrypttest/client.go @@ -157,17 +157,10 @@ func NewClient(tb testing.TB, opts ...ClientOption) *encrypt.Client { for _, opt := range opts { opt(&o) } - built, err := testclient.New(context.Background(), plainTestBuild, eqlTestBuild, o.seed) + client, err := narrow[*encrypt.Client](testclient.New(context.Background(), plainTestBuild, eqlTestBuild, o.seed)) if err != nil { tb.Fatalf("encrypttest: %v", err) } - client, ok := built.(*encrypt.Client) - if !ok { - if closer, ok := built.(interface{ Close() error }); ok { - _ = closer.Close() - } - tb.Fatalf("encrypttest: the constructor returned %T, not *encrypt.Client", built) - } tb.Cleanup(func() { if err := client.Close(); err != nil { tb.Errorf("encrypttest: closing the client: %v", err) diff --git a/languages/golang/encrypt/encrypttest/client_internal_test.go b/languages/golang/encrypt/encrypttest/client_internal_test.go index 55e288b995..59f87bb92b 100644 --- a/languages/golang/encrypt/encrypttest/client_internal_test.go +++ b/languages/golang/encrypt/encrypttest/client_internal_test.go @@ -2,10 +2,46 @@ package encrypttest import ( "encoding/hex" + "errors" "strings" "testing" ) +// closer counts its Close calls. +type closer struct{ closed int } + +func (c *closer) Close() error { + c.closed++ + return nil +} + +// narrow gives back what a constructor built when it is the type asked +// for. A constructor's error comes back unchanged. A value of another type +// is an error, and is closed so that it does not leak. +func TestNarrow(t *testing.T) { + built := &closer{} + if got, err := narrow[*closer](built, nil); err != nil || got != built { + t.Fatalf("narrow = %v, %v; want the value built", got, err) + } + if built.closed != 0 { + t.Fatal("narrow closed the value it gave back") + } + + failed := errors.New("constructor failed") + if _, err := narrow[*closer](nil, failed); !errors.Is(err, failed) { + t.Fatalf("%v, want the constructor's error", err) + } + + wrong := &closer{} + _, err := narrow[*strings.Builder](wrong, nil) + if err == nil || !strings.Contains(err.Error(), "*encrypttest.closer, not *strings.Builder") { + t.Fatalf("%v, want an error naming both types", err) + } + if wrong.closed != 1 { + t.Fatalf("the value of the wrong type was closed %d times, want 1", wrong.closed) + } +} + // The default seed is a promise: values an application's fixtures sealed // under it in one release open under the next. Comparing two clients cannot // show it changed, because both read the changed value, so it is pinned here diff --git a/languages/golang/encrypt/encrypttest/encrypttest.go b/languages/golang/encrypt/encrypttest/encrypttest.go index 9473ab7a7d..2ff51c4097 100644 --- a/languages/golang/encrypt/encrypttest/encrypttest.go +++ b/languages/golang/encrypt/encrypttest/encrypttest.go @@ -30,32 +30,46 @@ import ( "github.com/cipherstash/stack/languages/golang/internal/record" ) -// Contexts asks the embedded engine for the contexts of the declaration's -// fields. The text has one line per field, then one indented line with its +// Contexts asks the engine for the contexts of the declaration's fields. +// The text has one line per field, then one indented line with its // context: "email\n context: users / email\n". It needs no credentials // and no network. [AssertContexts] reads this text; a test that wants the // text itself, to print or to compare whole, calls this. // -// It asks the test build of the engine that [NewClient] runs. The first -// call, or the first client, in a test binary compiles that build, and -// every later call reuses it. +// It asks the test build of the engine, the one [NewClient] runs. The test +// build gives the same contexts as the production build: the two differ +// only in where their keys come from. The first call, or the first client, +// in a test binary compiles the test build, and every later call reuses +// it. func Contexts(ctx context.Context, d gensupport.Declaration) (string, error) { if err := versionSkew(); err != nil { return "", err } - built, err := testclient.NewChecker(ctx, plainTestBuild, eqlTestBuild) + checker, err := narrow[*encrypt.Checker](testclient.NewChecker(ctx, plainTestBuild, eqlTestBuild)) if err != nil { return "", fmt.Errorf("encrypttest: %w", err) } - checker, ok := built.(*encrypt.Checker) + defer func() { _ = checker.Close() }() + return d.Contexts(ctx, checker) +} + +// narrow is what a testclient constructor returned, as the type T it +// builds. The constructors return any, because package testclient cannot +// import package encrypt to name the type. A value of another type is +// closed, if it can be, and is an error. +func narrow[T any](built any, err error) (T, error) { + var zero T + if err != nil { + return zero, err + } + v, ok := built.(T) if !ok { if closer, ok := built.(interface{ Close() error }); ok { _ = closer.Close() } - return "", fmt.Errorf("encrypttest: the checker constructor returned %T, not *encrypt.Checker", built) + return zero, fmt.Errorf("the constructor returned %T, not %T", built, zero) } - defer func() { _ = checker.Close() }() - return d.Contexts(ctx, checker) + return v, nil } // A FieldContext is the context of one field, as a test states it: the diff --git a/languages/golang/encrypt/example/user_contexts_test.go b/languages/golang/encrypt/example/user_contexts_test.go index c526b5b332..a070b7f618 100644 --- a/languages/golang/encrypt/example/user_contexts_test.go +++ b/languages/golang/encrypt/example/user_contexts_test.go @@ -1,11 +1,8 @@ package main import ( - "context" - "errors" "testing" - "github.com/cipherstash/stack/languages/golang/encrypt" "github.com/cipherstash/stack/languages/golang/encrypt/encrypttest" ) @@ -14,9 +11,6 @@ import ( // parts are the ones a Rust test states for an `EncryptedUser` with the // same fields. func TestUserContextsArePinned(t *testing.T) { - if _, err := encrypttest.Contexts(context.Background(), declaration); errors.Is(err, encrypt.ErrGuestNotBuilt) { - t.Skip(err) - } encrypttest.AssertContexts(t, declaration, encrypttest.Field("email", "users", "email"), encrypttest.Field("age", "users", "age"), diff --git a/languages/golang/encrypt/guest.go b/languages/golang/encrypt/guest.go index 9c0c6a2b02..400e4690b6 100644 --- a/languages/golang/encrypt/guest.go +++ b/languages/golang/encrypt/guest.go @@ -92,6 +92,17 @@ func compilationCache() wazero.CompilationCache { return sharedCache } +// guestRuntimeConfig is the runtime configuration every guest runtime +// uses. wazero finds a compiled module in the cache by its bytes and by +// parts of this configuration: the engine, and WithCloseOnContextDone. So +// compileForever, which compiles a build ahead of any client, uses this +// one too. With another, a client would miss the entry and compile the +// build again. +func guestRuntimeConfig() wazero.RuntimeConfig { + return wazero.NewRuntimeConfig(). + WithCompilationCache(compilationCache()) +} + // instance is one instantiated guest with its exports resolved. It is // the unsynchronised half of a Client; the Client serialises access. type instance struct { @@ -157,9 +168,7 @@ func newInstance(ctx context.Context, wasm []byte, t *transport, policy guest.Lo // keys while it builds, seals or opens a batch, and the host // resumes it at once (see step.go). A pause then waits for one chunk, // not a whole batch. - config := wazero.NewRuntimeConfig(). - WithCompilationCache(compilationCache()) - runtime := wazero.NewRuntimeWithConfig(ctx, config) + runtime := wazero.NewRuntimeWithConfig(ctx, guestRuntimeConfig()) // The Must* form of this panics on any error, which is the wrong // failure mode for a constructor in a library and would strand the // runtime it was instantiating into. No error is reachable here today — diff --git a/languages/golang/encrypt/internal/testclient/testclient.go b/languages/golang/encrypt/internal/testclient/testclient.go index cd0b7abaad..57b40c6bcd 100644 --- a/languages/golang/encrypt/internal/testclient/testclient.go +++ b/languages/golang/encrypt/internal/testclient/testclient.go @@ -2,8 +2,9 @@ // two constructors it needs: a client over a given guest build, initialised // with a seed in place of a client key, and a checker over a given guest // build. The constructors reach encrypt's unexported instance and client, -// and encrypttest imports encrypt, so encrypt registers them here on init. Nothing outside the encrypt tree can import this -// package, so the constructors are in no public API. +// and encrypttest imports encrypt, so encrypt registers them here on +// init. Nothing outside the encrypt tree can import this package, so the +// constructors are in no public API. package testclient import ( diff --git a/languages/golang/encrypt/pinned_builds_test.go b/languages/golang/encrypt/pinned_builds_test.go index aded8c1959..17ab0dd372 100644 --- a/languages/golang/encrypt/pinned_builds_test.go +++ b/languages/golang/encrypt/pinned_builds_test.go @@ -13,6 +13,7 @@ import ( "github.com/tetratelabs/wazero" + "github.com/cipherstash/stack/languages/golang/encrypt/internal/testclient" "github.com/cipherstash/stack/languages/golang/internal/record" ) @@ -201,7 +202,7 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { if err := p.pin(context.Background(), wasm); err != nil { t.Fatal(err) } - shared := wazero.NewRuntimeConfig().WithCompilationCache(compilationCache()) + shared := guestRuntimeConfig() compile(shared) if again := compile(shared); again > cold/4 { t.Fatalf("a compile after the pin took %v and a cold compile %v: the pinned build left the cache", again, cold) @@ -246,6 +247,44 @@ func TestTestCheckersCompileTheirBuildOnce(t *testing.T) { } } +// The checker package encrypttest gets, through internal/testclient, pins +// the test build that selectBuild picks, in the testBuilds that test +// clients pin theirs in. So encrypttest.Contexts compiles that build at +// most once in a test binary, and none at all after NewClient. +func TestTheRegisteredTestCheckerPinsItsBuild(t *testing.T) { + eqlBuild := func() ([]byte, error) { + wasm, err := os.ReadFile(deterministicEQLGuestPath) + if errors.Is(err, os.ErrNotExist) { + return nil, ErrDeterministicEQLGuestNotBuilt + } + return wasm, err + } + wasm, err := selectBuild(DeterministicGuest, eqlBuild) + if errors.Is(err, ErrDeterministicGuestNotBuilt) || errors.Is(err, ErrDeterministicEQLGuestNotBuilt) { + t.Skip(err) + } + if err != nil { + t.Fatal(err) + } + built, err := testclient.NewChecker(context.Background(), DeterministicGuest, eqlBuild) + if err != nil { + t.Fatal(err) + } + checker, ok := built.(*Checker) + if !ok { + t.Fatalf("the checker constructor returned %T, not *Checker", built) + } + if err := checker.Close(); err != nil { + t.Error(err) + } + testBuilds.mu.Lock() + _, ok = testBuilds.pinned[sha256.Sum256(wasm)] + testBuilds.mu.Unlock() + if !ok { + t.Fatal("the registered checker constructor did not pin the build it ran") + } +} + // A test build that is not there is the loader's error, and nothing is // compiled or kept. func TestATestCheckerWithoutItsBuildIsTheLoadersError(t *testing.T) { diff --git a/languages/golang/encrypt/testclient.go b/languages/golang/encrypt/testclient.go index bfeedf524b..9587dc37b0 100644 --- a/languages/golang/encrypt/testclient.go +++ b/languages/golang/encrypt/testclient.go @@ -131,15 +131,13 @@ func (p *pinnedBuilds) pin(ctx context.Context, wasm []byte) error { return nil } -// compileForever compiles wasm on a runtime that is never closed, with the -// configuration newInstance uses, so the module has the cache entry a -// client looks up. It compiles the guest's functions on every core: the -// compiled code is the same, and under the race detector the compile takes -// about ten seconds on one core. +// compileForever compiles wasm on a runtime that is never closed, with +// guestRuntimeConfig, the configuration newInstance uses, so the module +// has the cache entry a client looks up. It compiles the guest's +// functions on every core: the compiled code is the same, and under the +// race detector the compile takes about ten seconds on one core. func compileForever(ctx context.Context, wasm []byte) (any, error) { - config := wazero.NewRuntimeConfig(). - WithCompilationCache(compilationCache()) - runtime := wazero.NewRuntimeWithConfig(ctx, config) + runtime := wazero.NewRuntimeWithConfig(ctx, guestRuntimeConfig()) compiled, err := runtime.CompileModule(experimental.WithCompilationWorkers(ctx, goruntime.GOMAXPROCS(0)), wasm) if err != nil { _ = runtime.Close(ctx) From 865bef1b3b2ebf0cdea7370acdb12d086ca1e99f Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Sat, 28 Nov 2026 00:37:03 +1100 Subject: [PATCH 10/12] perf(golang): keep the compiled engine for a minute after the last client wazero deletes a compiled module from the shared compilation cache when the last runtime using it closes. So a program that opened and closed clients one after another compiled the engine again for each client, at about a second each. The package now holds one extra user of each compiled build: a module compiled on a runtime it keeps. That module is never instantiated. Every instance takes a lease on it and gives the lease back when it is released. When the last lease goes, a timer frees the build after one minute. A client opened before then stops the timer and reads the compiled code from the cache. ReleaseEngine frees every build at once. A client that is still open keeps working, because its own runtime still uses the cache entry. wazero frees the code when that client closes. The first compile also uses every core, as the test builds already do. Refs #1976 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- languages/golang/CHANGELOG.md | 14 + languages/golang/encrypt/README.md | 13 + languages/golang/encrypt/client.go | 5 + languages/golang/encrypt/engine.go | 227 ++++++++++++++++ languages/golang/encrypt/engine_test.go | 339 ++++++++++++++++++++++++ languages/golang/encrypt/guest.go | 22 +- languages/golang/encrypt/testclient.go | 18 +- 7 files changed, 624 insertions(+), 14 deletions(-) create mode 100644 languages/golang/encrypt/engine.go create mode 100644 languages/golang/encrypt/engine_test.go diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 7fccaa69af..bd5fb59a8b 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -22,8 +22,22 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. `[16]byte` (`github.com/google/uuid.UUID`, say), which is converted to one. `stashgen` does not yet map a Go type to it. +- `encrypt.ReleaseEngine` frees the compiled engine at once. Without it, + the compiled engine is freed one minute after the last client closes. + `ReleaseEngine` is safe to call more than once. A client or checker that + is open when it is called keeps working. The compiled engine is then + freed when the last of them closes. + ### Fixed +- A program that opens and closes clients one after another compiles the + engine once, not once per client. Before, the compiled engine was freed + when the last open client closed. So the next `NewClient` or + `NewChecker` compiled it again, for about 1 second each. Now the + compiled engine is kept for one minute after the last client or checker + closes. The first compile also uses every core. `encrypt.ReleaseEngine` + frees the compiled engine sooner. + - `encrypttest.AssertContexts` and `encrypttest.Contexts` compile the engine once per test binary, not once per call. Before, each call compiled it: about 1 second, or 10 to 50 seconds under the race diff --git a/languages/golang/encrypt/README.md b/languages/golang/encrypt/README.md index 6e67a1e8a8..9f2f92aa08 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -120,6 +120,19 @@ if err != nil { defer client.Close() ``` +The first `NewClient` in a process compiles the engine to machine code. +That takes about a second. The engine is a WebAssembly module. Every later +client reuses the compiled engine and skips that second. + +The compiled engine is kept while any client is open, and for one minute +after the last client closes. So a program that opens and closes clients +one after another compiles the engine once. After that minute, the +compiled engine is freed. The next client compiles it again. + +To free the compiled engine at once, call `encrypt.ReleaseEngine()`. A +client that is still open keeps working. The compiled engine is then freed +when the last open client closes. + `ctx` is Go's `context.Context`: the deadline and cancellation for the one ZeroKMS round trip `NewClient` makes. It has nothing to do with an *encryption* context, which is what a field is sealed under; that is the diff --git a/languages/golang/encrypt/client.go b/languages/golang/encrypt/client.go index 0d17c1527b..8e2c1ca210 100644 --- a/languages/golang/encrypt/client.go +++ b/languages/golang/encrypt/client.go @@ -24,6 +24,11 @@ import ( // a ZeroKMS request is performed between steps, with the client free for // other callers (see step.go). Close it when done, as with any resource. // +// Clients share the compiled engine. The first client in a process +// compiles it, in about a second, and it is kept for a minute after the +// last client closes, so the next client does not compile it again. +// [ReleaseEngine] frees it at once. +// // A call whose context ends fails with the context's error, and only that // call: one request's cancellation or deadline never closes the client for // the others sharing it. A call waiting its turn leaves the queue when its diff --git a/languages/golang/encrypt/engine.go b/languages/golang/encrypt/engine.go new file mode 100644 index 0000000000..b3d6659da0 --- /dev/null +++ b/languages/golang/encrypt/engine.go @@ -0,0 +1,227 @@ +package encrypt + +import ( + "context" + "crypto/sha256" + goruntime "runtime" + "sync" + "sync/atomic" + "time" + + "github.com/tetratelabs/wazero" + "github.com/tetratelabs/wazero/experimental" +) + +// engineIdle is how long the compiled engine is kept after the last client +// or checker over it closes. One minute is far longer than the gap between +// clients in a program that opens and closes them one after another, such +// as a job that makes a client per task, so that program compiles once. It +// is short enough that a program that stops using clients gets the memory +// back soon. A program that opens a client just after each free compiles +// for about a second once a minute at most. +const engineIdle = time.Minute + +// ReleaseEngine frees the compiled engine now, rather than when it has been +// idle for a minute. +// +// The first [NewClient] or [NewChecker] in a process compiles the engine, +// a WebAssembly module, to machine code. That takes about a second. The +// compiled engine is shared: every later client and checker reuses it +// and skips that second. It is kept while any client or checker is open, and +// for one minute after the last one closes, so a program that opens and +// closes clients one after another compiles the engine once. After that +// minute it is freed, and the next client compiles it again. +// +// ReleaseEngine is for a program that knows it has finished with clients +// and wants the memory back at once. It is safe to call more than once, +// and from any goroutine. It never breaks an open client or checker: each +// one goes on working, and the compiled engine is freed when the last of +// them closes. A client opened after ReleaseEngine compiles the engine +// again, unless a client opened before is still open, in which case it +// starts from the compiled engine that client is using. +func ReleaseEngine() { engines.releaseAll() } + +// engines is the process's compiled engines, one for each build of the +// guest a client or checker has run. +var engines = &engineCache{idle: engineIdle} + +// engineCache keeps each guest build compiled in the shared compilation +// cache while any instance over it is open, and for idle after the last +// one closes. +// +// wazero counts the users of a compiled module in its in-memory cache, and +// deletes the module when the count reaches zero. Each instance's runtime +// is one user while it is open. So when every client has closed, the next +// client would compile the guest again. engineCache adds one user of its +// own: a module compiled on a runtime it keeps, which it closes once the +// build has been idle for idle, or at once on releaseAll. That module is +// never instantiated: every instance still has its own runtime, and reads +// the compiled code from the cache. +type engineCache struct { + // compileMu makes callers given a build that is not compiled wait for + // one compile, rather than each compiling it. + compileMu sync.Mutex + + mu sync.Mutex + builds map[[sha256.Size]byte]*sharedEngine + idle time.Duration + // afterFunc runs f once d has passed. Nil is time.AfterFunc; tests + // replace it to fire the timer themselves. + afterFunc func(d time.Duration, f func()) stopper + // compile compiles wasm into the shared cache and returns what frees + // it. Nil is compileShared; tests replace it to count compiles. + compile func(ctx context.Context, wasm []byte) (free func(), err error) +} + +// stopper is the part of *time.Timer that engineCache uses. +type stopper interface{ Stop() bool } + +// sharedEngine is one compiled build and the instances open over it. +type sharedEngine struct { + key [sha256.Size]byte + free func() + open int + // idle is the timer that frees the build, while no instance is open. + idle stopper + // armed counts the idle timers started, so that a timer that fires + // after a later acquire has stopped it does nothing. + armed int +} + +// engineLease is one instance's use of a compiled build. A nil lease is +// valid, and its release does nothing. +type engineLease struct { + cache *engineCache + engine *sharedEngine + released atomic.Bool +} + +// acquire keeps the compiled form of wasm in the shared cache until the +// lease is released, compiling it first if no open instance or idle timer +// keeps it. A compile that fails gives a nil lease: the instance that asked +// then compiles wasm itself, and reports the failure as it always has. +func (c *engineCache) acquire(ctx context.Context, wasm []byte) *engineLease { + key := sha256.Sum256(wasm) + if l := c.lease(key); l != nil { + return l + } + c.compileMu.Lock() + defer c.compileMu.Unlock() + if l := c.lease(key); l != nil { + return l + } + compile := c.compile + if compile == nil { + compile = compileShared + } + free, err := compile(ctx, wasm) + if err != nil { + return nil + } + e := &sharedEngine{key: key, free: free, open: 1} + c.mu.Lock() + defer c.mu.Unlock() + if c.builds == nil { + c.builds = map[[sha256.Size]byte]*sharedEngine{} + } + c.builds[key] = e + return &engineLease{cache: c, engine: e} +} + +// lease is a lease on the build with key, if it is compiled. +func (c *engineCache) lease(key [sha256.Size]byte) *engineLease { + c.mu.Lock() + defer c.mu.Unlock() + e, ok := c.builds[key] + if !ok { + return nil + } + e.open++ + if e.idle != nil { + e.idle.Stop() + e.idle = nil + } + return &engineLease{cache: c, engine: e} +} + +// release ends the lease. When it was the last open one on its build, the +// build is freed once it has been idle for the cache's idle period. A +// second release does nothing. +func (l *engineLease) release() { + if l == nil || !l.released.CompareAndSwap(false, true) { + return + } + c, e := l.cache, l.engine + c.mu.Lock() + defer c.mu.Unlock() + e.open-- + // A build releaseAll has already dropped is freed: its lease has + // nothing left to keep. + if e.open > 0 || c.builds[e.key] != e { + return + } + e.armed++ + armed := e.armed + afterFunc := c.afterFunc + if afterFunc == nil { + afterFunc = func(d time.Duration, f func()) stopper { return time.AfterFunc(d, f) } + } + e.idle = afterFunc(c.idle, func() { c.expire(e, armed) }) +} + +// expire frees e, if no instance has opened over it since the timer armed +// was started. +func (c *engineCache) expire(e *sharedEngine, armed int) { + c.mu.Lock() + if c.builds[e.key] != e || e.open > 0 || e.armed != armed { + c.mu.Unlock() + return + } + delete(c.builds, e.key) + e.idle = nil + c.mu.Unlock() + e.free() +} + +// releaseAll frees every compiled build now. An instance still open over +// one keeps its compiled code, through its own runtime, until it closes. +func (c *engineCache) releaseAll() { + c.mu.Lock() + dropped := make([]*sharedEngine, 0, len(c.builds)) + for key, e := range c.builds { + if e.idle != nil { + e.idle.Stop() + e.idle = nil + } + delete(c.builds, key) + dropped = append(dropped, e) + } + c.mu.Unlock() + for _, e := range dropped { + e.free() + } +} + +// compileShared compiles wasm into the shared compilation cache, on a +// runtime of its own with guestRuntimeConfig, the configuration +// newInstance uses, so the module has the cache entry an instance looks +// up. It compiles the guest's functions on every core: the compiled code +// is the same, and under the race detector the compile takes about ten +// seconds on one core. free closes the module and the runtime, which ends +// this runtime's use of the cache entry. +func compileShared(ctx context.Context, wasm []byte) (free func(), err error) { + runtime := wazero.NewRuntimeWithConfig(ctx, guestRuntimeConfig()) + compiled, err := runtime.CompileModule(experimental.WithCompilationWorkers(ctx, goruntime.GOMAXPROCS(0)), wasm) + if err != nil { + _ = runtime.Close(ctx) + return nil, err + } + return func() { + // Neither close can fail here. A compiled module's Close always + // returns nil, and the runtime has no module instantiated in it, + // which is the only thing its Close reports on. Close takes the + // background context because the caller's may have ended by now. + _ = compiled.Close(context.Background()) + _ = runtime.Close(context.Background()) + }, nil +} diff --git a/languages/golang/encrypt/engine_test.go b/languages/golang/encrypt/engine_test.go new file mode 100644 index 0000000000..d31b4c09d0 --- /dev/null +++ b/languages/golang/encrypt/engine_test.go @@ -0,0 +1,339 @@ +package encrypt + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/cipherstash/stack/languages/golang/internal/guest" +) + +// fakeTimer is a timer the test fires itself. +type fakeTimer struct { + d time.Duration + f func() + stopped bool +} + +func (t *fakeTimer) Stop() bool { + was := !t.stopped + t.stopped = true + return was +} + +// fakeEngines is an engineCache whose compiles are counted, whose frees +// are counted, and whose idle timers are recorded for the test to fire. +type fakeEngines struct { + cache *engineCache + compiles atomic.Int32 + frees atomic.Int32 + fail atomic.Bool + mu sync.Mutex + timers []*fakeTimer +} + +const fakeIdle = 7 * time.Minute + +func newFakeEngines() *fakeEngines { + f := &fakeEngines{} + f.cache = &engineCache{ + idle: fakeIdle, + afterFunc: func(d time.Duration, fn func()) stopper { + f.mu.Lock() + defer f.mu.Unlock() + t := &fakeTimer{d: d, f: fn} + f.timers = append(f.timers, t) + return t + }, + compile: func(context.Context, []byte) (func(), error) { + f.compiles.Add(1) + // Long enough for concurrent callers to overlap. + time.Sleep(10 * time.Millisecond) + if f.fail.Load() { + return nil, errCompile + } + return func() { f.frees.Add(1) }, nil + }, + } + return f +} + +// lastTimer is the timer started last, which must exist. +func (f *fakeEngines) lastTimer(t *testing.T) *fakeTimer { + t.Helper() + f.mu.Lock() + defer f.mu.Unlock() + if len(f.timers) == 0 { + t.Fatal("no idle timer was started") + } + return f.timers[len(f.timers)-1] +} + +func (f *fakeEngines) timerCount() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.timers) +} + +func (f *fakeEngines) want(t *testing.T, compiles, frees int32) { + t.Helper() + if got := f.compiles.Load(); got != compiles { + t.Errorf("compiled %d times, want %d", got, compiles) + } + if got := f.frees.Load(); got != frees { + t.Errorf("freed %d times, want %d", got, frees) + } +} + +// The compiled engine is shared by every open instance, kept while one is +// open, freed by the idle timer once the last has closed, and compiled +// again by the next instance after that. +func TestEngineCacheFreesTheEngineWhenIdle(t *testing.T) { + f := newFakeEngines() + ctx := context.Background() + a := f.cache.acquire(ctx, []byte("a")) + b := f.cache.acquire(ctx, []byte("a")) + f.want(t, 1, 0) + + a.release() + if n := f.timerCount(); n != 0 { + t.Fatalf("%d idle timers started with an instance still open, want 0", n) + } + b.release() + timer := f.lastTimer(t) + if timer.d != fakeIdle { + t.Fatalf("idle timer of %v, want the cache's %v", timer.d, fakeIdle) + } + f.want(t, 1, 0) + + timer.f() + f.want(t, 1, 1) + + c := f.cache.acquire(ctx, []byte("a")) + f.want(t, 2, 1) + c.release() +} + +// An instance opened while the idle timer runs stops it and uses the +// compiled engine. The timer firing late, after Stop lost the race, frees +// nothing. +func TestEngineCacheReuseStopsTheIdleTimer(t *testing.T) { + f := newFakeEngines() + ctx := context.Background() + f.cache.acquire(ctx, []byte("a")).release() + first := f.lastTimer(t) + + again := f.cache.acquire(ctx, []byte("a")) + if !first.stopped { + t.Fatal("the idle timer was not stopped when an instance opened") + } + first.f() + f.want(t, 1, 0) + + again.release() + second := f.lastTimer(t) + first.f() + f.want(t, 1, 0) + second.f() + f.want(t, 1, 1) +} + +// ReleaseEngine frees the engine at once, stops its idle timer, and is +// safe to call again. +func TestEngineCacheReleaseAllFreesAtOnce(t *testing.T) { + f := newFakeEngines() + ctx := context.Background() + f.cache.acquire(ctx, []byte("a")).release() + f.cache.acquire(ctx, []byte("b")).release() + f.want(t, 2, 0) + + f.cache.releaseAll() + f.want(t, 2, 2) + for i, timer := range f.timers { + if !timer.stopped { + t.Errorf("idle timer %d is still running", i) + } + // A timer that fired anyway frees nothing a second time. + timer.f() + } + f.cache.releaseAll() + f.want(t, 2, 2) + + f.cache.acquire(ctx, []byte("a")).release() + f.want(t, 3, 2) +} + +// ReleaseEngine with an instance open drops the cache's own hold at once, +// and leaves the instance's alone: wazero keeps the compiled code for the +// instance's runtime until it closes. The instance's later release starts +// no timer, and a new instance compiles again. +func TestEngineCacheReleaseAllWithAnInstanceOpen(t *testing.T) { + f := newFakeEngines() + ctx := context.Background() + open := f.cache.acquire(ctx, []byte("a")) + f.cache.releaseAll() + f.want(t, 1, 1) + + next := f.cache.acquire(ctx, []byte("a")) + f.want(t, 2, 1) + + open.release() + if n := f.timerCount(); n != 0 { + t.Fatalf("%d idle timers started for a build already released, want 0", n) + } + next.release() + f.lastTimer(t).f() + f.want(t, 2, 2) +} + +// A release counts once, however often it runs, and a nil lease, from a +// compile that failed, releases nothing. +func TestEngineLeaseReleaseIsIdempotent(t *testing.T) { + f := newFakeEngines() + ctx := context.Background() + a := f.cache.acquire(ctx, []byte("a")) + b := f.cache.acquire(ctx, []byte("a")) + a.release() + a.release() + if n := f.timerCount(); n != 0 { + t.Fatalf("a second release of one lease started %d idle timers, want 0", n) + } + b.release() + f.lastTimer(t).f() + f.want(t, 1, 1) + + var none *engineLease + none.release() +} + +// A compile that fails is not kept: the lease is nil, and the next +// instance tries again. +func TestEngineCacheDoesNotKeepAFailedCompile(t *testing.T) { + f := newFakeEngines() + ctx := context.Background() + f.fail.Store(true) + if l := f.cache.acquire(ctx, []byte("a")); l != nil { + t.Fatal("a failed compile gave a lease") + } + f.fail.Store(false) + l := f.cache.acquire(ctx, []byte("a")) + if l == nil { + t.Fatal("no lease after a compile that worked") + } + f.want(t, 2, 0) + l.release() +} + +// Instances that open at once over a build that is not compiled wait for +// one compile. +func TestEngineCacheCompilesOnceForConcurrentInstances(t *testing.T) { + f := newFakeEngines() + ctx := context.Background() + leases := make([]*engineLease, 8) + var wg sync.WaitGroup + for i := range leases { + wg.Go(func() { leases[i] = f.cache.acquire(ctx, []byte("a")) }) + } + wg.Wait() + f.want(t, 1, 0) + for _, l := range leases { + wg.Go(l.release) + } + wg.Wait() + f.lastTimer(t).f() + f.want(t, 1, 1) +} + +// The real timer frees the engine once the idle period has passed, and the +// goroutine that runs it ends. +func TestEngineCacheRealTimerFreesTheEngine(t *testing.T) { + freed := make(chan struct{}) + c := &engineCache{ + idle: time.Millisecond, + compile: func(context.Context, []byte) (func(), error) { + return func() { close(freed) }, nil + }, + } + c.acquire(context.Background(), []byte("a")).release() + select { + case <-freed: + case <-time.After(10 * time.Second): + t.Fatal("the idle timer did not free the engine") + } + c.mu.Lock() + defer c.mu.Unlock() + if len(c.builds) != 0 { + t.Fatalf("%d builds kept after the idle timer fired, want 0", len(c.builds)) + } +} + +// The package's engines, over the real guest: checkers share one compile, +// ReleaseEngine called while one is open leaves it working, and a checker +// made once every earlier one has closed compiles again. +func TestReleaseEngineOverTheGuest(t *testing.T) { + wasm := guestOrSkip(t) + saved := engines + t.Cleanup(func() { engines = saved }) + var compiles atomic.Int32 + engines = &engineCache{ + idle: time.Hour, + compile: func(ctx context.Context, wasm []byte) (func(), error) { + compiles.Add(1) + return compileShared(ctx, wasm) + }, + } + ctx := context.Background() + checker := func() *Checker { + t.Helper() + k, err := newCheckerOver(ctx, wasm) + if err != nil { + t.Fatal(err) + } + return k + } + first := checker() + second := checker() + if got := compiles.Load(); got != 1 { + t.Fatalf("two checkers compiled %d times, want 1", got) + } + if err := second.Close(); err != nil { + t.Fatal(err) + } + + ReleaseEngine() + ReleaseEngine() + if _, err := first.Contexts(ctx, usersPlan()); err != nil { + t.Fatalf("a checker open across ReleaseEngine: %v", err) + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + + third := checker() + defer func() { _ = third.Close() }() + if got := compiles.Load(); got != 2 { + t.Fatalf("compiled %d times, want 2: the checker after ReleaseEngine compiles again", got) + } + if _, err := third.Contexts(ctx, usersPlan()); err != nil { + t.Fatal(err) + } +} + +// A compile that fails in the engine cache leaves the instance to fail on +// its own, with the error it always gave. +func TestNewInstanceReportsABadModuleItself(t *testing.T) { + saved := engines + t.Cleanup(func() { engines = saved }) + engines = &engineCache{idle: time.Hour} + tr := &transport{rt: refusingTransport{}, token: noToken{}} + if _, err := newInstance(context.Background(), []byte("not wasm"), tr, guest.BestEffort); err == nil { + t.Fatal("instantiated bytes that are not a WebAssembly module") + } + engines.mu.Lock() + defer engines.mu.Unlock() + if len(engines.builds) != 0 { + t.Fatal("kept a build that did not compile") + } +} diff --git a/languages/golang/encrypt/guest.go b/languages/golang/encrypt/guest.go index 400e4690b6..358b63357e 100644 --- a/languages/golang/encrypt/guest.go +++ b/languages/golang/encrypt/guest.go @@ -111,6 +111,9 @@ type instance struct { // mem supplied the module's linear memory (internal/guest) and reports // on it. mem *guest.Allocator + // engine keeps the compiled guest in the shared cache while this + // instance is open (see engineCache). Nil when that compile failed. + engine *engineLease exports guest.Exports cipherInit, shutdown, keyset api.Function @@ -146,8 +149,21 @@ func guestModuleConfig() wazero.ModuleConfig { // newInstance instantiates wasm with the transport as its host module and // its linear memory from the guest packages' shared allocator. Under the // strict policy, memory that cannot be locked fails instantiation with -// ErrMemoryLock. +// ErrMemoryLock. The compiled guest is shared with every other instance of +// the same build, and kept after the last one closes: see ReleaseEngine. func newInstance(ctx context.Context, wasm []byte, t *transport, policy guest.LockPolicy) (*instance, error) { + lease := engines.acquire(ctx, wasm) + inst, err := instantiate(ctx, wasm, t, policy) + if err != nil { + lease.release() + return nil, err + } + inst.engine = lease + return inst, nil +} + +// instantiate is newInstance's work, on a runtime of the instance's own. +func instantiate(ctx context.Context, wasm []byte, t *transport, policy guest.LockPolicy) (*instance, error) { // No WithCloseOnContextDone. That option makes wazero compile a call // back into Go at the top of every loop the guest runs, so that a call // whose context ends can be interrupted. The guest is cryptography, @@ -260,7 +276,9 @@ func (inst *instance) release() error { _, _ = inst.shutdown.Call(ctx) inst.mem.Exit() } - return inst.runtime.Close(ctx) + err := inst.runtime.Close(ctx) + inst.engine.release() + return err } // The call plumbing — stage each buffer argument through se_alloc, call, diff --git a/languages/golang/encrypt/testclient.go b/languages/golang/encrypt/testclient.go index 9587dc37b0..1c8a01a960 100644 --- a/languages/golang/encrypt/testclient.go +++ b/languages/golang/encrypt/testclient.go @@ -4,14 +4,11 @@ import ( "context" "crypto/sha256" "fmt" - goruntime "runtime" "sync" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testclient" "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/tetratelabs/wazero" - "github.com/tetratelabs/wazero/experimental" ) // Package encrypttest builds its clients through this constructor. It is @@ -131,17 +128,14 @@ func (p *pinnedBuilds) pin(ctx context.Context, wasm []byte) error { return nil } -// compileForever compiles wasm on a runtime that is never closed, with -// guestRuntimeConfig, the configuration newInstance uses, so the module -// has the cache entry a client looks up. It compiles the guest's -// functions on every core: the compiled code is the same, and under the -// race detector the compile takes about ten seconds on one core. +// compileForever compiles wasm into the shared cache, as compileShared +// does, and never frees it. func compileForever(ctx context.Context, wasm []byte) (any, error) { - runtime := wazero.NewRuntimeWithConfig(ctx, guestRuntimeConfig()) - compiled, err := runtime.CompileModule(experimental.WithCompilationWorkers(ctx, goruntime.GOMAXPROCS(0)), wasm) + free, err := compileShared(ctx, wasm) if err != nil { - _ = runtime.Close(ctx) return nil, fmt.Errorf("encrypt: compiling the test build: %w", err) } - return compiled, nil + // What keeps the build compiled is the runtime free would close, which + // free holds. + return free, nil } From 33cfd3f0d7a9c97f1ef069497d02d86b6153383c Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Sat, 28 Nov 2026 01:32:03 +1100 Subject: [PATCH 11/12] refactor(golang): pin the test builds in the engine cache Test clients and checkers kept their build compiled through a second cache, pinnedBuilds. It copied most of engineCache, and held each test build on a second runtime. They now pin the build in engines itself. A pinned build holds a lease that is never released, so no idle timer frees it, and ReleaseEngine leaves it. ReleaseEngine's doc comment and the CHANGELOG now say so. A compile that fails pins nothing, as with acquire. So a corrupt test build fails with the instance's error, as a production build does. It no longer fails with a separate "compiling the test build" error. Both seededClient and testChecker pin in engines, so tests reach both the same way. Also: - testclient.Builds carries the two test build loaders as one value, and Register names its parameters client and checker. - sharedEngine's timer field is now idleTimer, apart from the cache's idle period. - guestRuntimeConfig's comment names compileShared and instantiate, the two that must agree, and TestInstantiateReadsTheSharedCompile checks that an instance reads the entry compileShared made. It fails when instantiate's configuration adds WithCloseOnContextDone(true). - Tests that swap engines free its builds and stop its timers before putting it back. Otherwise a lease that a deferred Close ends late leaves a one-hour timer holding a build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- languages/golang/CHANGELOG.md | 4 +- .../golang/encrypt/encrypttest/client.go | 3 +- .../golang/encrypt/encrypttest/encrypttest.go | 2 +- languages/golang/encrypt/engine.go | 63 ++++-- languages/golang/encrypt/engine_test.go | 87 +++++++- languages/golang/encrypt/guest.go | 8 +- .../encrypt/internal/testclient/testclient.go | 33 +-- .../golang/encrypt/pinned_builds_test.go | 194 ++++++++++-------- languages/golang/encrypt/testclient.go | 94 ++------- 9 files changed, 283 insertions(+), 205 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 49ec9f009c..ae5733547e 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -26,7 +26,9 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. the compiled engine is freed one minute after the last client closes. `ReleaseEngine` is safe to call more than once. A client or checker that is open when it is called keeps working. The compiled engine is then - freed when the last of them closes. + freed when the last of them closes. In a test binary, `ReleaseEngine` + does not free the test builds that `encrypttest` clients and checkers + run: those are kept until the test binary exits. ### Changed diff --git a/languages/golang/encrypt/encrypttest/client.go b/languages/golang/encrypt/encrypttest/client.go index 2866c2dfe3..313dcd50ab 100644 --- a/languages/golang/encrypt/encrypttest/client.go +++ b/languages/golang/encrypt/encrypttest/client.go @@ -157,7 +157,7 @@ func NewClient(tb testing.TB, opts ...ClientOption) *encrypt.Client { for _, opt := range opts { opt(&o) } - client, err := narrow[*encrypt.Client](testclient.New(context.Background(), plainTestBuild, eqlTestBuild, o.seed)) + client, err := narrow[*encrypt.Client](testclient.New(context.Background(), testBuilds, o.seed)) if err != nil { tb.Fatalf("encrypttest: %v", err) } @@ -227,6 +227,7 @@ var ( eqlTestBuild = sync.OnceValues(func() ([]byte, error) { return readTestBuild(eqlGuestPath, "wasm:guest:build:eql:deterministic") }) + testBuilds = testclient.Builds{Plain: plainTestBuild, WithEQL: eqlTestBuild} ) func readTestBuild(path, task string) ([]byte, error) { diff --git a/languages/golang/encrypt/encrypttest/encrypttest.go b/languages/golang/encrypt/encrypttest/encrypttest.go index 2ff51c4097..be89ddc420 100644 --- a/languages/golang/encrypt/encrypttest/encrypttest.go +++ b/languages/golang/encrypt/encrypttest/encrypttest.go @@ -45,7 +45,7 @@ func Contexts(ctx context.Context, d gensupport.Declaration) (string, error) { if err := versionSkew(); err != nil { return "", err } - checker, err := narrow[*encrypt.Checker](testclient.NewChecker(ctx, plainTestBuild, eqlTestBuild)) + checker, err := narrow[*encrypt.Checker](testclient.NewChecker(ctx, testBuilds)) if err != nil { return "", fmt.Errorf("encrypttest: %w", err) } diff --git a/languages/golang/encrypt/engine.go b/languages/golang/encrypt/engine.go index b3d6659da0..e937083d04 100644 --- a/languages/golang/encrypt/engine.go +++ b/languages/golang/encrypt/engine.go @@ -39,6 +39,11 @@ const engineIdle = time.Minute // them closes. A client opened after ReleaseEngine compiles the engine // again, unless a client opened before is still open, in which case it // starts from the compiled engine that client is using. +// +// In a test binary, ReleaseEngine leaves the test builds of the engine +// that package encrypttest's clients and checkers run. Each of those is +// kept until the test binary exits, so a suite that starts a client in +// every test compiles it once. func ReleaseEngine() { engines.releaseAll() } // engines is the process's compiled engines, one for each build of the @@ -56,7 +61,8 @@ var engines = &engineCache{idle: engineIdle} // own: a module compiled on a runtime it keeps, which it closes once the // build has been idle for idle, or at once on releaseAll. That module is // never instantiated: every instance still has its own runtime, and reads -// the compiled code from the cache. +// the compiled code from the cache. A build that pin is given is kept for +// the life of the process. type engineCache struct { // compileMu makes callers given a build that is not compiled wait for // one compile, rather than each compiling it. @@ -81,8 +87,12 @@ type sharedEngine struct { key [sha256.Size]byte free func() open int - // idle is the timer that frees the build, while no instance is open. - idle stopper + // pinned is a build that pin keeps for the life of the process. It + // holds a lease that is never released, so open never reaches zero. + pinned bool + // idleTimer is the timer that frees the build, while no instance is + // open. + idleTimer stopper // armed counts the idle timers started, so that a timer that fires // after a later acquire has stopped it does nothing. armed int @@ -128,6 +138,29 @@ func (c *engineCache) acquire(ctx context.Context, wasm []byte) *engineLease { return &engineLease{cache: c, engine: e} } +// pin keeps the compiled form of wasm in the shared cache for the life of +// the process: the idle timer never frees it, and releaseAll leaves it. +// Package encrypttest's clients and checkers pin the test build they run, +// so a test binary compiles each build once, however many tests start and +// close a client, and whatever they do with ReleaseEngine. A compile that +// fails pins nothing: the instance that follows compiles wasm itself, and +// reports the failure as it always has. +func (c *engineCache) pin(ctx context.Context, wasm []byte) { + l := c.acquire(ctx, wasm) + if l == nil { + return + } + c.mu.Lock() + already := l.engine.pinned + l.engine.pinned = true + c.mu.Unlock() + // The first pin keeps its lease, and never releases it. Any later pin + // of the same build has nothing to add. + if already { + l.release() + } +} + // lease is a lease on the build with key, if it is compiled. func (c *engineCache) lease(key [sha256.Size]byte) *engineLease { c.mu.Lock() @@ -137,9 +170,9 @@ func (c *engineCache) lease(key [sha256.Size]byte) *engineLease { return nil } e.open++ - if e.idle != nil { - e.idle.Stop() - e.idle = nil + if e.idleTimer != nil { + e.idleTimer.Stop() + e.idleTimer = nil } return &engineLease{cache: c, engine: e} } @@ -166,7 +199,7 @@ func (l *engineLease) release() { if afterFunc == nil { afterFunc = func(d time.Duration, f func()) stopper { return time.AfterFunc(d, f) } } - e.idle = afterFunc(c.idle, func() { c.expire(e, armed) }) + e.idleTimer = afterFunc(c.idle, func() { c.expire(e, armed) }) } // expire frees e, if no instance has opened over it since the timer armed @@ -178,20 +211,24 @@ func (c *engineCache) expire(e *sharedEngine, armed int) { return } delete(c.builds, e.key) - e.idle = nil + e.idleTimer = nil c.mu.Unlock() e.free() } -// releaseAll frees every compiled build now. An instance still open over -// one keeps its compiled code, through its own runtime, until it closes. +// releaseAll frees every compiled build now, except the pinned ones. An +// instance still open over one keeps its compiled code, through its own +// runtime, until it closes. func (c *engineCache) releaseAll() { c.mu.Lock() dropped := make([]*sharedEngine, 0, len(c.builds)) for key, e := range c.builds { - if e.idle != nil { - e.idle.Stop() - e.idle = nil + if e.pinned { + continue + } + if e.idleTimer != nil { + e.idleTimer.Stop() + e.idleTimer = nil } delete(c.builds, key) dropped = append(dropped, e) diff --git a/languages/golang/encrypt/engine_test.go b/languages/golang/encrypt/engine_test.go index d31b4c09d0..92ad92ffc6 100644 --- a/languages/golang/encrypt/engine_test.go +++ b/languages/golang/encrypt/engine_test.go @@ -2,11 +2,14 @@ package encrypt import ( "context" + goruntime "runtime" "sync" "sync/atomic" "testing" "time" + "github.com/tetratelabs/wazero" + "github.com/cipherstash/stack/languages/golang/internal/guest" ) @@ -87,6 +90,32 @@ func (f *fakeEngines) want(t *testing.T, compiles, frees int32) { } } +// swapEngines makes c the package's engines until the test ends. The +// cleanup frees every build c holds, pinned ones too, and stops its idle +// timers, before engines goes back: a lease a test releases late, such as +// one a deferred Close ends, would otherwise start a timer that keeps its +// build compiled after the test, for as long as c's idle period. +func swapEngines(t *testing.T, c *engineCache) { + t.Helper() + saved := engines + engines = c + t.Cleanup(func() { + freeEverything(c) + engines = saved + }) +} + +// freeEverything frees every build c holds, the pinned ones included, +// which releaseAll leaves, and stops their idle timers. +func freeEverything(c *engineCache) { + c.mu.Lock() + for _, e := range c.builds { + e.pinned = false + } + c.mu.Unlock() + c.releaseAll() +} + // The compiled engine is shared by every open instance, kept while one is // open, freed by the idle timer once the last has closed, and compiled // again by the next instance after that. @@ -274,16 +303,14 @@ func TestEngineCacheRealTimerFreesTheEngine(t *testing.T) { // made once every earlier one has closed compiles again. func TestReleaseEngineOverTheGuest(t *testing.T) { wasm := guestOrSkip(t) - saved := engines - t.Cleanup(func() { engines = saved }) var compiles atomic.Int32 - engines = &engineCache{ + swapEngines(t, &engineCache{ idle: time.Hour, compile: func(ctx context.Context, wasm []byte) (func(), error) { compiles.Add(1) return compileShared(ctx, wasm) }, - } + }) ctx := context.Background() checker := func() *Checker { t.Helper() @@ -324,9 +351,7 @@ func TestReleaseEngineOverTheGuest(t *testing.T) { // A compile that fails in the engine cache leaves the instance to fail on // its own, with the error it always gave. func TestNewInstanceReportsABadModuleItself(t *testing.T) { - saved := engines - t.Cleanup(func() { engines = saved }) - engines = &engineCache{idle: time.Hour} + swapEngines(t, &engineCache{idle: time.Hour}) tr := &transport{rt: refusingTransport{}, token: noToken{}} if _, err := newInstance(context.Background(), []byte("not wasm"), tr, guest.BestEffort); err == nil { t.Fatal("instantiated bytes that are not a WebAssembly module") @@ -337,3 +362,51 @@ func TestNewInstanceReportsABadModuleItself(t *testing.T) { t.Fatal("kept a build that did not compile") } } + +// An instance reads the compiled code that compileShared put in the cache, +// so a client or checker opened while engines keeps a build compiles +// nothing. wazero finds a cache entry by the runtime configuration as well +// as the bytes: if instantiate's configuration differed from +// compileShared's, every client would compile the guest again, and the +// cache's own tests, which count calls to its compile hook, would still +// pass. +func TestInstantiateReadsTheSharedCompile(t *testing.T) { + wasm := guestOrSkip(t) + // wazero compiles to machine code on amd64 and arm64 only. Elsewhere + // it runs an interpreter, whose compile is too cheap to tell a cache + // hit from a miss by time. + if goruntime.GOARCH != "amd64" && goruntime.GOARCH != "arm64" { + t.Skipf("wazero has no compiler on %s, so a cache hit cannot be told from a miss by time", goruntime.GOARCH) + } + ctx := context.Background() + // A compile that misses the cache, on one worker, as instantiate's + // would. + runtime := wazero.NewRuntimeWithConfig(ctx, wazero.NewRuntimeConfig().WithCompilationCache(wazero.NewCompilationCache())) + start := time.Now() + compiled, err := runtime.CompileModule(ctx, wasm) + if err != nil { + t.Fatal(err) + } + cold := time.Since(start) + _ = compiled.Close(ctx) + _ = runtime.Close(ctx) + + free, err := compileShared(ctx, wasm) + if err != nil { + t.Fatal(err) + } + defer free() + start = time.Now() + inst, err := instantiate(ctx, wasm, &transport{rt: refusingTransport{}, token: noToken{}}, guest.BestEffort) + if err != nil { + t.Fatal(err) + } + warm := time.Since(start) + if err := inst.release(); err != nil { + t.Error(err) + } + t.Logf("cold compile %v, instantiate after compileShared %v", cold, warm) + if warm > cold/4 { + t.Fatalf("instantiate took %v after compileShared, and a cold compile %v: instantiate missed the shared compile", warm, cold) + } +} diff --git a/languages/golang/encrypt/guest.go b/languages/golang/encrypt/guest.go index 358b63357e..0b564a7350 100644 --- a/languages/golang/encrypt/guest.go +++ b/languages/golang/encrypt/guest.go @@ -95,9 +95,11 @@ func compilationCache() wazero.CompilationCache { // guestRuntimeConfig is the runtime configuration every guest runtime // uses. wazero finds a compiled module in the cache by its bytes and by // parts of this configuration: the engine, and WithCloseOnContextDone. So -// compileForever, which compiles a build ahead of any client, uses this -// one too. With another, a client would miss the entry and compile the -// build again. +// compileShared, which compiles a build ahead of any client for engines, +// and instantiate, which every client and checker runs, both use this one. +// If they used different ones, every client would miss the entry and +// compile the build again: TestInstantiateReadsTheSharedCompile checks +// that it does not. func guestRuntimeConfig() wazero.RuntimeConfig { return wazero.NewRuntimeConfig(). WithCompilationCache(compilationCache()) diff --git a/languages/golang/encrypt/internal/testclient/testclient.go b/languages/golang/encrypt/internal/testclient/testclient.go index 57b40c6bcd..b7138a3d60 100644 --- a/languages/golang/encrypt/internal/testclient/testclient.go +++ b/languages/golang/encrypt/internal/testclient/testclient.go @@ -12,27 +12,32 @@ import ( "errors" ) +// Builds loads the two deterministic-kms builds of the guest: Plain +// without the EQL types, and WithEQL with them. A constructor calls the +// one a production client in this program would match. +type Builds struct { + Plain, WithEQL func() ([]byte, error) +} + // Constructor builds a client over a deterministic-kms build of the guest, -// with every key derived from seed. plain and withEQL load the test builds -// without and with the EQL types; the constructor calls the one a -// production client in this program would match. It returns the -// *encrypt.Client as any, because this package cannot import encrypt to -// name the type. -type Constructor func(ctx context.Context, plain, withEQL func() ([]byte, error), seed [32]byte) (any, error) +// the one of builds a production client in this program would match, with +// every key derived from seed. It returns the *encrypt.Client as any, +// because this package cannot import encrypt to name the type. +type Constructor func(ctx context.Context, builds Builds, seed [32]byte) (any, error) var constructor Constructor // CheckerConstructor builds a checker over a test build of the guest, // the one a production client in this program would match, as Constructor // picks it. It returns the *encrypt.Checker as any. -type CheckerConstructor func(ctx context.Context, plain, withEQL func() ([]byte, error)) (any, error) +type CheckerConstructor func(ctx context.Context, builds Builds) (any, error) var checkerConstructor CheckerConstructor // Register installs encrypt's constructors. Called once, by encrypt's init. -func Register(c Constructor, k CheckerConstructor) { - constructor = c - checkerConstructor = k +func Register(client Constructor, checker CheckerConstructor) { + constructor = client + checkerConstructor = checker } // errNotRegistered is a program that reached New without package encrypt @@ -40,17 +45,17 @@ func Register(c Constructor, k CheckerConstructor) { var errNotRegistered = errors.New("encrypt: test client constructor not registered") // New calls the registered constructor. -func New(ctx context.Context, plain, withEQL func() ([]byte, error), seed [32]byte) (any, error) { +func New(ctx context.Context, builds Builds, seed [32]byte) (any, error) { if constructor == nil { return nil, errNotRegistered } - return constructor(ctx, plain, withEQL, seed) + return constructor(ctx, builds, seed) } // NewChecker calls the registered checker constructor. -func NewChecker(ctx context.Context, plain, withEQL func() ([]byte, error)) (any, error) { +func NewChecker(ctx context.Context, builds Builds) (any, error) { if checkerConstructor == nil { return nil, errNotRegistered } - return checkerConstructor(ctx, plain, withEQL) + return checkerConstructor(ctx, builds) } diff --git a/languages/golang/encrypt/pinned_builds_test.go b/languages/golang/encrypt/pinned_builds_test.go index 17ab0dd372..6f5f9f33f9 100644 --- a/languages/golang/encrypt/pinned_builds_test.go +++ b/languages/golang/encrypt/pinned_builds_test.go @@ -6,6 +6,7 @@ import ( "errors" "os" goruntime "runtime" + "strings" "sync" "sync/atomic" "testing" @@ -17,49 +18,43 @@ import ( "github.com/cipherstash/stack/languages/golang/internal/record" ) -// countingBuilds is a pinnedBuilds whose compile counts its calls, waits -// a moment so that concurrent callers overlap, and fails while fail is set. -func countingBuilds() (*pinnedBuilds, *atomic.Int32, *atomic.Bool) { - var calls atomic.Int32 - var fail atomic.Bool - p := &pinnedBuilds{compile: func(context.Context, []byte) (any, error) { - calls.Add(1) - time.Sleep(20 * time.Millisecond) - if fail.Load() { - return nil, errCompile - } - return struct{}{}, nil - }} - return p, &calls, &fail -} - var errCompile = errors.New("compile failed") +// isPinned reports whether c keeps wasm pinned. +func isPinned(c *engineCache, wasm []byte) bool { + c.mu.Lock() + defer c.mu.Unlock() + e, ok := c.builds[sha256.Sum256(wasm)] + return ok && e.pinned +} + // A test build compiles once in a process, however many clients start and -// close, one after another or at once. wazero drops a compiled module from -// its in-memory cache when the last runtime using it closes, so without the -// pin every client in a suite that starts one per test compiled the guest -// again: about ten seconds each under the race detector. -func TestPinnedBuilds(t *testing.T) { +// close, one after another or at once, and whatever ReleaseEngine does. +// wazero drops a compiled module from its in-memory cache when the last +// runtime using it closes, so without the pin every client in a suite that +// starts one per test compiled the guest again: about ten seconds each +// under the race detector. +func TestEngineCachePin(t *testing.T) { + ctx := context.Background() for _, tt := range []struct { name string - run func(t *testing.T, p *pinnedBuilds, fail *atomic.Bool) + run func(t *testing.T, f *fakeEngines) want int32 }{ { name: "one build pinned twice compiles once", - run: func(t *testing.T, p *pinnedBuilds, _ *atomic.Bool) { - pin(t, p, "a") - pin(t, p, "a") + run: func(t *testing.T, f *fakeEngines) { + f.cache.pin(ctx, []byte("a")) + f.cache.pin(ctx, []byte("a")) }, want: 1, }, { name: "one build pinned at once by many callers compiles once", - run: func(t *testing.T, p *pinnedBuilds, _ *atomic.Bool) { + run: func(t *testing.T, f *fakeEngines) { var wg sync.WaitGroup for range 8 { - wg.Go(func() { pin(t, p, "a") }) + wg.Go(func() { f.cache.pin(ctx, []byte("a")) }) } wg.Wait() }, @@ -67,33 +62,49 @@ func TestPinnedBuilds(t *testing.T) { }, { name: "each build compiles once", - run: func(t *testing.T, p *pinnedBuilds, _ *atomic.Bool) { - pin(t, p, "a") - pin(t, p, "b") - pin(t, p, "a") + run: func(t *testing.T, f *fakeEngines) { + f.cache.pin(ctx, []byte("a")) + f.cache.pin(ctx, []byte("b")) + f.cache.pin(ctx, []byte("a")) }, want: 2, }, { name: "a failed compile is not pinned", - run: func(t *testing.T, p *pinnedBuilds, fail *atomic.Bool) { - fail.Store(true) - if err := p.pin(context.Background(), []byte("a")); !errors.Is(err, errCompile) { - t.Fatalf("%v, want the compile's error", err) + run: func(t *testing.T, f *fakeEngines) { + f.fail.Store(true) + f.cache.pin(ctx, []byte("a")) + if isPinned(f.cache, []byte("a")) { + t.Fatal("pinned a build that did not compile") } - fail.Store(false) - pin(t, p, "a") - pin(t, p, "a") + f.fail.Store(false) + f.cache.pin(ctx, []byte("a")) + f.cache.pin(ctx, []byte("a")) }, want: 2, }, + { + name: "a pinned build outlives its instances and releaseAll", + run: func(t *testing.T, f *fakeEngines) { + f.cache.pin(ctx, []byte("a")) + f.cache.acquire(ctx, []byte("a")).release() + if n := f.timerCount(); n != 0 { + t.Fatalf("started %d idle timers on a pinned build, want 0", n) + } + f.cache.releaseAll() + f.cache.releaseAll() + f.cache.acquire(ctx, []byte("a")).release() + if !isPinned(f.cache, []byte("a")) { + t.Fatal("releaseAll dropped a pinned build") + } + }, + want: 1, + }, } { t.Run(tt.name, func(t *testing.T) { - p, calls, fail := countingBuilds() - tt.run(t, p, fail) - if got := calls.Load(); got != tt.want { - t.Fatalf("compiled %d times, want %d", got, tt.want) - } + f := newFakeEngines() + tt.run(t, f) + f.want(t, tt.want, 0) }) } } @@ -133,29 +144,19 @@ func TestSeededClientPinsItsBuild(t *testing.T) { if err := c.Close(); err != nil { t.Error(err) } - testBuilds.mu.Lock() - _, ok := testBuilds.pinned[sha256.Sum256(wasm)] - testBuilds.mu.Unlock() - if !ok { + if !isPinned(engines, wasm) { t.Fatal("seededClient did not pin the build it ran") } }) } } -func pin(t *testing.T, p *pinnedBuilds, wasm string) { - t.Helper() - if err := p.pin(context.Background(), []byte(wasm)); err != nil { - t.Error(err) - } -} - // The real compile, over the guest this package embeds: once a build is // pinned, a runtime that compiles it reads the cache, even after every -// other runtime that used the build has closed. Without the pin, wazero -// drops the build from the cache when the first runtime closes, and the -// last compile below takes as long as a cold one. -func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { +// other runtime that used the build has closed, and after releaseAll. +// Without the pin, wazero drops the build from the cache when the first +// runtime closes, and the last compile below takes as long as a cold one. +func TestAPinnedBuildStaysCompiled(t *testing.T) { wasm, err := plainGuest() if errors.Is(err, ErrGuestNotBuilt) { t.Skip(err) @@ -163,8 +164,11 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { if err != nil { t.Fatal(err) } - var p pinnedBuilds - if err := p.pin(context.Background(), []byte("not wasm")); err == nil { + ctx := context.Background() + c := &engineCache{idle: time.Hour} + t.Cleanup(func() { freeEverything(c) }) + c.pin(ctx, []byte("not wasm")) + if isPinned(c, []byte("not wasm")) { t.Fatal("pinned bytes that are not a WebAssembly module") } // wazero compiles to machine code on amd64 and arm64 only. Elsewhere, @@ -178,7 +182,7 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { // cache takes about 20 times as long as one that reads it, on any // number of cores. With a worker for each core, on 20 cores, it takes // only about 5 times as long. - ctx := context.Background() + // // compile compiles wasm on a new runtime, closes the compiled module // and the runtime, and returns how long the compile took. Closing the // compiled module is what closing a client does: newInstance @@ -199,9 +203,8 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { } cold := compile(wazero.NewRuntimeConfig().WithCompilationCache(wazero.NewCompilationCache())) - if err := p.pin(context.Background(), wasm); err != nil { - t.Fatal(err) - } + c.pin(ctx, wasm) + c.releaseAll() shared := guestRuntimeConfig() compile(shared) if again := compile(shared); again > cold/4 { @@ -212,26 +215,30 @@ func TestPinnedBuildsKeepTheGuestCompiled(t *testing.T) { // encrypttest.AssertContexts and encrypttest.Contexts make a new checker // on every call, and close it before they return. A checker over a test // build compiles that build once in a process, however many are made and -// closed. Before, each call compiled the guest again: under the race -// detector, 10 to 50 seconds a call. +// closed, and whatever ReleaseEngine does. Before, each call compiled the +// guest again: under the race detector, 10 to 50 seconds a call. func TestTestCheckersCompileTheirBuildOnce(t *testing.T) { if _, err := plainGuest(); errors.Is(err, ErrGuestNotBuilt) { t.Skip(err) } var calls atomic.Int32 - builds := &pinnedBuilds{compile: func(ctx context.Context, wasm []byte) (any, error) { - calls.Add(1) - return compileForever(ctx, wasm) - }} + swapEngines(t, &engineCache{ + idle: time.Hour, + compile: func(ctx context.Context, wasm []byte) (func(), error) { + calls.Add(1) + return compileShared(ctx, wasm) + }, + }) ctx := context.Background() plan := &record.Plan{ Context: []string{"users"}, Fields: []record.Field{{Name: "email", Kind: record.String, Outputs: []record.Output{record.Ciphertext}}}, } + // The same loader for both builds: whichever one selectBuild picks in + // this binary, it is this build. + builds := testclient.Builds{Plain: plainGuest, WithEQL: plainGuest} for range 3 { - // The same loader for both builds: whichever one selectBuild picks - // in this binary, it is this build. - checker, err := testChecker(ctx, builds, plainGuest, plainGuest) + checker, err := testChecker(ctx, builds) if err != nil { t.Fatal(err) } @@ -241,6 +248,7 @@ func TestTestCheckersCompileTheirBuildOnce(t *testing.T) { if err := checker.Close(); err != nil { t.Fatal(err) } + ReleaseEngine() } if got := calls.Load(); got != 1 { t.Fatalf("compiled %d times, want 1", got) @@ -248,9 +256,9 @@ func TestTestCheckersCompileTheirBuildOnce(t *testing.T) { } // The checker package encrypttest gets, through internal/testclient, pins -// the test build that selectBuild picks, in the testBuilds that test -// clients pin theirs in. So encrypttest.Contexts compiles that build at -// most once in a test binary, and none at all after NewClient. +// the test build that selectBuild picks, in engines, where test clients +// pin theirs. So encrypttest.Contexts compiles that build at most once in +// a test binary, and none at all after NewClient. func TestTheRegisteredTestCheckerPinsItsBuild(t *testing.T) { eqlBuild := func() ([]byte, error) { wasm, err := os.ReadFile(deterministicEQLGuestPath) @@ -266,7 +274,7 @@ func TestTheRegisteredTestCheckerPinsItsBuild(t *testing.T) { if err != nil { t.Fatal(err) } - built, err := testclient.NewChecker(context.Background(), DeterministicGuest, eqlBuild) + built, err := testclient.NewChecker(context.Background(), testclient.Builds{Plain: DeterministicGuest, WithEQL: eqlBuild}) if err != nil { t.Fatal(err) } @@ -277,10 +285,7 @@ func TestTheRegisteredTestCheckerPinsItsBuild(t *testing.T) { if err := checker.Close(); err != nil { t.Error(err) } - testBuilds.mu.Lock() - _, ok = testBuilds.pinned[sha256.Sum256(wasm)] - testBuilds.mu.Unlock() - if !ok { + if !isPinned(engines, wasm) { t.Fatal("the registered checker constructor did not pin the build it ran") } } @@ -288,12 +293,31 @@ func TestTheRegisteredTestCheckerPinsItsBuild(t *testing.T) { // A test build that is not there is the loader's error, and nothing is // compiled or kept. func TestATestCheckerWithoutItsBuildIsTheLoadersError(t *testing.T) { - builds, calls, _ := countingBuilds() + f := newFakeEngines() + swapEngines(t, f.cache) missing := func() ([]byte, error) { return nil, errCompile } - if _, err := testChecker(context.Background(), builds, missing, missing); !errors.Is(err, errCompile) { + if _, err := testChecker(context.Background(), testclient.Builds{Plain: missing, WithEQL: missing}); !errors.Is(err, errCompile) { t.Fatalf("%v, want the loader's error", err) } - if got := calls.Load(); got != 0 { - t.Fatalf("compiled %d times, want 0", got) + f.want(t, 0, 0) +} + +// A test build that does not compile fails as a production build does: +// the instance reports it, so there is one error for a bad module, from +// test clients and checkers as from NewClient and NewChecker. +func TestABadTestBuildIsTheInstancesError(t *testing.T) { + c := &engineCache{idle: time.Hour} + swapEngines(t, c) + bad := func() ([]byte, error) { return []byte("not wasm"), nil } + builds := testclient.Builds{Plain: bad, WithEQL: bad} + ctx := context.Background() + if _, err := testChecker(ctx, builds); err == nil || !strings.HasPrefix(err.Error(), "encrypt: instantiating guest: ") { + t.Errorf("testChecker over a bad build: %v, want the instance's error", err) + } + if _, err := seededClient(ctx, []byte("not wasm"), [32]byte{}); err == nil || !strings.HasPrefix(err.Error(), "encrypt: instantiating guest: ") { + t.Errorf("seededClient over a bad build: %v, want the instance's error", err) + } + if isPinned(c, []byte("not wasm")) { + t.Error("pinned a build that did not compile") } } diff --git a/languages/golang/encrypt/testclient.go b/languages/golang/encrypt/testclient.go index 1c8a01a960..0d55c8909e 100644 --- a/languages/golang/encrypt/testclient.go +++ b/languages/golang/encrypt/testclient.go @@ -2,9 +2,7 @@ package encrypt import ( "context" - "crypto/sha256" "fmt" - "sync" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testclient" "github.com/cipherstash/stack/languages/golang/internal/guest" @@ -18,40 +16,38 @@ import ( // embedded for production refuse a bare seed as their config. It picks // between the two test builds by selectBuild, the rule embeddedGuest uses. func init() { - testclient.Register(func(ctx context.Context, plain, withEQL func() ([]byte, error), seed [32]byte) (any, error) { - wasm, err := selectBuild(plain, withEQL) + testclient.Register(func(ctx context.Context, builds testclient.Builds, seed [32]byte) (any, error) { + wasm, err := selectBuild(builds.Plain, builds.WithEQL) if err != nil { return nil, err } return seededClient(ctx, wasm, seed) - }, func(ctx context.Context, plain, withEQL func() ([]byte, error)) (any, error) { - return testChecker(ctx, &testBuilds, plain, withEQL) + }, func(ctx context.Context, builds testclient.Builds) (any, error) { + return testChecker(ctx, builds) }) } // testChecker is a checker over the test build selectBuild picks, the one -// a test client in this program runs. builds keeps that build compiled, so -// that encrypttest.AssertContexts, which makes a checker on every call, -// compiles the guest once per test binary, and not on every call. -func testChecker(ctx context.Context, builds *pinnedBuilds, plain, withEQL func() ([]byte, error)) (*Checker, error) { - wasm, err := selectBuild(plain, withEQL) +// a test client in this program runs. It pins that build in engines, as +// seededClient does, so that encrypttest.AssertContexts, which makes a +// checker on every call, compiles the guest once per test binary, and not +// on every call. +func testChecker(ctx context.Context, builds testclient.Builds) (*Checker, error) { + wasm, err := selectBuild(builds.Plain, builds.WithEQL) if err != nil { return nil, err } - if err := builds.pin(ctx, wasm); err != nil { - return nil, err - } + engines.pin(ctx, wasm) return newCheckerOver(ctx, wasm) } // seededClient is a client over wasm, a deterministic-kms build of the // guest. Its config is the 32-byte seed every key derives from. It has no // token and a transport that refuses every request, so nothing it does can -// reach the network. +// reach the network. It pins wasm in engines, so the test binary compiles +// it once, however many test clients start and close. func seededClient(ctx context.Context, wasm []byte, seed [32]byte) (*Client, error) { - if err := testBuilds.pin(ctx, wasm); err != nil { - return nil, err - } + engines.pin(ctx, wasm) tr := &transport{rt: refusingTransport{}, token: noToken{}} inst, err := newInstance(ctx, wasm, tr, guest.BestEffort) if err != nil { @@ -77,65 +73,3 @@ func seededClient(ctx context.Context, wasm []byte, seed [32]byte) (*Client, err copy(c.def[:], out) return c, nil } - -// testBuilds holds every test build a test client or checker has run, -// compiled. -var testBuilds pinnedBuilds - -// pinnedBuilds keeps each guest build it is given compiled in the shared -// compilation cache for the life of the process, so that test clients and -// checkers compile the guest once per test binary. -// -// wazero counts the runtimes that use a compiled module in its in-memory -// cache, and deletes the module when the last of them closes. A suite that -// starts a client in each test, and closes it when the test ends, would -// compile the guest again in every test: about one second each, and about -// ten under the race detector. Parallel tests that start clients at once -// would each compile it too. pin compiles each build once, on a runtime it -// never closes, so the count never reaches zero. That copy is never -// instantiated: every client still compiles on its own runtime, and reads -// the compiled code from the cache. -type pinnedBuilds struct { - mu sync.Mutex - pinned map[[sha256.Size]byte]any - // compile compiles wasm into the shared cache and returns what keeps - // it there. nil is compileForever; tests replace it. - compile func(ctx context.Context, wasm []byte) (any, error) -} - -// pin compiles wasm into the shared cache the first time it is given, and -// keeps it there. Callers given the same build at once wait for one -// compile. A compile that fails is not kept, so the next caller tries again. -func (p *pinnedBuilds) pin(ctx context.Context, wasm []byte) error { - key := sha256.Sum256(wasm) - p.mu.Lock() - defer p.mu.Unlock() - if _, ok := p.pinned[key]; ok { - return nil - } - compile := p.compile - if compile == nil { - compile = compileForever - } - kept, err := compile(ctx, wasm) - if err != nil { - return err - } - if p.pinned == nil { - p.pinned = map[[sha256.Size]byte]any{} - } - p.pinned[key] = kept - return nil -} - -// compileForever compiles wasm into the shared cache, as compileShared -// does, and never frees it. -func compileForever(ctx context.Context, wasm []byte) (any, error) { - free, err := compileShared(ctx, wasm) - if err != nil { - return nil, fmt.Errorf("encrypt: compiling the test build: %w", err) - } - // What keeps the build compiled is the runtime free would close, which - // free holds. - return free, nil -} From 7e33bc0279751a426f73dbfe0f69b4c8bb38b011 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Sat, 28 Nov 2026 02:13:22 +1100 Subject: [PATCH 12/12] fix(golang): mark a pinned build in the section that finds it pin took a lease through acquire, then marked the build pinned under a second lock. A releaseAll between the two could drop the build. Then the pin marked a build the cache no longer held. The next client compiled the build again. pin and acquire now share take. It marks the build pinned in the same critical section that finds the build or adds it, so releaseAll never sees a pinned build unmarked. A pin of a build that is already pinned takes no lease. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- languages/golang/encrypt/engine.go | 69 ++++++++++++++++-------------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/languages/golang/encrypt/engine.go b/languages/golang/encrypt/engine.go index e937083d04..4c884f6e99 100644 --- a/languages/golang/encrypt/engine.go +++ b/languages/golang/encrypt/engine.go @@ -107,17 +107,37 @@ type engineLease struct { } // acquire keeps the compiled form of wasm in the shared cache until the -// lease is released, compiling it first if no open instance or idle timer -// keeps it. A compile that fails gives a nil lease: the instance that asked -// then compiles wasm itself, and reports the failure as it always has. +// lease is released. It compiles wasm first if nothing keeps it. A compile +// that fails gives a nil lease. The instance that asked then compiles wasm +// itself, and reports the failure as it always has. func (c *engineCache) acquire(ctx context.Context, wasm []byte) *engineLease { + return c.take(ctx, wasm, false) +} + +// pin keeps the compiled form of wasm in the shared cache for the life of +// the process. The idle timer never frees it, and releaseAll leaves it. +// Package encrypttest's clients and checkers pin the test build they run. +// So a test binary compiles each build once, whatever its tests do. +// +// A compile that fails pins nothing. The instance that follows compiles wasm +// itself, and reports the failure as it always has. +func (c *engineCache) pin(ctx context.Context, wasm []byte) { + // The first pin of a build takes a lease and never releases it. So + // open never reaches zero. A later pin takes no lease. + _ = c.take(ctx, wasm, true) +} + +// take is acquire. With pin set, it is pin. It marks the build pinned in +// the same critical section that finds the build or adds it. So releaseAll +// cannot drop the build between the two. +func (c *engineCache) take(ctx context.Context, wasm []byte, pin bool) *engineLease { key := sha256.Sum256(wasm) - if l := c.lease(key); l != nil { + if l, ok := c.lease(key, pin); ok { return l } c.compileMu.Lock() defer c.compileMu.Unlock() - if l := c.lease(key); l != nil { + if l, ok := c.lease(key, pin); ok { return l } compile := c.compile @@ -128,7 +148,7 @@ func (c *engineCache) acquire(ctx context.Context, wasm []byte) *engineLease { if err != nil { return nil } - e := &sharedEngine{key: key, free: free, open: 1} + e := &sharedEngine{key: key, free: free, open: 1, pinned: pin} c.mu.Lock() defer c.mu.Unlock() if c.builds == nil { @@ -138,43 +158,26 @@ func (c *engineCache) acquire(ctx context.Context, wasm []byte) *engineLease { return &engineLease{cache: c, engine: e} } -// pin keeps the compiled form of wasm in the shared cache for the life of -// the process: the idle timer never frees it, and releaseAll leaves it. -// Package encrypttest's clients and checkers pin the test build they run, -// so a test binary compiles each build once, however many tests start and -// close a client, and whatever they do with ReleaseEngine. A compile that -// fails pins nothing: the instance that follows compiles wasm itself, and -// reports the failure as it always has. -func (c *engineCache) pin(ctx context.Context, wasm []byte) { - l := c.acquire(ctx, wasm) - if l == nil { - return - } - c.mu.Lock() - already := l.engine.pinned - l.engine.pinned = true - c.mu.Unlock() - // The first pin keeps its lease, and never releases it. Any later pin - // of the same build has nothing to add. - if already { - l.release() - } -} - -// lease is a lease on the build with key, if it is compiled. -func (c *engineCache) lease(key [sha256.Size]byte) *engineLease { +// lease returns a lease on the build with key. It also reports whether the +// build is compiled. With pin set, it marks the build pinned. A build that +// is already pinned gives a nil lease, because its first pin holds one. +func (c *engineCache) lease(key [sha256.Size]byte, pin bool) (*engineLease, bool) { c.mu.Lock() defer c.mu.Unlock() e, ok := c.builds[key] if !ok { - return nil + return nil, false } + if pin && e.pinned { + return nil, true + } + e.pinned = e.pinned || pin e.open++ if e.idleTimer != nil { e.idleTimer.Stop() e.idleTimer = nil } - return &engineLease{cache: c, engine: e} + return &engineLease{cache: c, engine: e}, true } // release ends the lease. When it was the last open one on its build, the