diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 2396d56661..ae5733547e 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -22,6 +22,14 @@ 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. 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 - **A record field converts a number of another width or kind, as a @@ -40,6 +48,32 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ### 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 + 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 + 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. + - **Other calls no longer wait behind a token refresh** (#1958). An `auth.Strategy` is shared by every encrypt and decrypt in a process, and about once every 15 minutes its token is refreshed with the token 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/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/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/encrypttest/client.go b/languages/golang/encrypt/encrypttest/client.go index 2b116e75d8..313dcd50ab 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 @@ -148,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(), testBuilds, 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) @@ -225,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/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 d72919d43e..be89ddc420 100644 --- a/languages/golang/encrypt/encrypttest/encrypttest.go +++ b/languages/golang/encrypt/encrypttest/encrypttest.go @@ -26,26 +26,52 @@ 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" ) -// 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, 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 } - checker, err := encrypt.NewChecker(ctx) + checker, err := narrow[*encrypt.Checker](testclient.NewChecker(ctx, testBuilds)) if err != nil { - return "", err + return "", fmt.Errorf("encrypttest: %w", err) } 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 zero, fmt.Errorf("the constructor returned %T, not %T", built, zero) + } + return v, nil +} + // A FieldContext is the context of one field, as a test states it: the // field's name and the parts of its context, in order. Build one with // [Field]. 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/engine.go b/languages/golang/encrypt/engine.go new file mode 100644 index 0000000000..4c884f6e99 --- /dev/null +++ b/languages/golang/encrypt/engine.go @@ -0,0 +1,267 @@ +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. +// +// 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 +// 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. 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. + 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 + // 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 +} + +// 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. 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, ok := c.lease(key, pin); ok { + return l + } + c.compileMu.Lock() + defer c.compileMu.Unlock() + if l, ok := c.lease(key, pin); ok { + 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, pinned: pin} + 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 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, 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}, true +} + +// 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.idleTimer = 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.idleTimer = nil + c.mu.Unlock() + e.free() +} + +// 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.pinned { + continue + } + if e.idleTimer != nil { + e.idleTimer.Stop() + e.idleTimer = 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..92ad92ffc6 --- /dev/null +++ b/languages/golang/encrypt/engine_test.go @@ -0,0 +1,412 @@ +package encrypt + +import ( + "context" + goruntime "runtime" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/tetratelabs/wazero" + + "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) + } +} + +// 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. +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) + var compiles atomic.Int32 + 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() + 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) { + 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") + } + engines.mu.Lock() + defer engines.mu.Unlock() + if len(engines.builds) != 0 { + 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/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/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/guest.go b/languages/golang/encrypt/guest.go index 9c0c6a2b02..0b564a7350 100644 --- a/languages/golang/encrypt/guest.go +++ b/languages/golang/encrypt/guest.go @@ -92,6 +92,19 @@ 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 +// 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()) +} + // instance is one instantiated guest with its exports resolved. It is // the unsynchronised half of a Client; the Client serialises access. type instance struct { @@ -100,6 +113,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 @@ -135,8 +151,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, @@ -157,9 +186,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 — @@ -251,7 +278,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/internal/testclient/testclient.go b/languages/golang/encrypt/internal/testclient/testclient.go index 38fcc0b88d..b7138a3d60 100644 --- a/languages/golang/encrypt/internal/testclient/testclient.go +++ b/languages/golang/encrypt/internal/testclient/testclient.go @@ -1,9 +1,10 @@ // 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 ( @@ -11,27 +12,50 @@ 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 -// 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, builds Builds) (any, error) + +var checkerConstructor CheckerConstructor + +// Register installs encrypt's constructors. Called once, by encrypt's init. +func Register(client Constructor, checker CheckerConstructor) { + constructor = client + checkerConstructor = checker +} // errNotRegistered is a program that reached New without package encrypt // initialised, which the import graph rules out. 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, builds Builds) (any, error) { + if checkerConstructor == nil { + return nil, errNotRegistered + } + return checkerConstructor(ctx, builds) } diff --git a/languages/golang/encrypt/pinned_builds_test.go b/languages/golang/encrypt/pinned_builds_test.go new file mode 100644 index 0000000000..6f5f9f33f9 --- /dev/null +++ b/languages/golang/encrypt/pinned_builds_test.go @@ -0,0 +1,323 @@ +package encrypt + +import ( + "context" + "crypto/sha256" + "errors" + "os" + goruntime "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/tetratelabs/wazero" + + "github.com/cipherstash/stack/languages/golang/encrypt/internal/testclient" + "github.com/cipherstash/stack/languages/golang/internal/record" +) + +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, 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, f *fakeEngines) + want int32 + }{ + { + name: "one build pinned twice compiles once", + 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, f *fakeEngines) { + var wg sync.WaitGroup + for range 8 { + wg.Go(func() { f.cache.pin(ctx, []byte("a")) }) + } + wg.Wait() + }, + want: 1, + }, + { + name: "each build compiles once", + 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, 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") + } + 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) { + f := newFakeEngines() + tt.run(t, f) + f.want(t, tt.want, 0) + }) + } +} + +// 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) + } + if !isPinned(engines, wasm) { + t.Fatal("seededClient did not pin the build it ran") + } + }) + } +} + +// 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, 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) + } + if err != nil { + t.Fatal(err) + } + 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, + // 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, on 20 cores, it takes + // only about 5 times as long. + // + // 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())) + + c.pin(ctx, wasm) + c.releaseAll() + 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) + } +} + +// 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, 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 + 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 { + checker, err := testChecker(ctx, builds) + 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) + } + ReleaseEngine() + } + if got := calls.Load(); got != 1 { + t.Fatalf("compiled %d times, want 1", got) + } +} + +// The checker package encrypttest gets, through internal/testclient, pins +// 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) + 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(), testclient.Builds{Plain: DeterministicGuest, WithEQL: 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) + } + if !isPinned(engines, wasm) { + 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) { + f := newFakeEngines() + swapEngines(t, f.cache) + missing := func() ([]byte, error) { return nil, 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) + } + 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 7fa3a36965..0d55c8909e 100644 --- a/languages/golang/encrypt/testclient.go +++ b/languages/golang/encrypt/testclient.go @@ -16,20 +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, 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. 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 + } + 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) { + engines.pin(ctx, wasm) tr := &transport{rt: refusingTransport{}, token: noToken{}} inst, err := newInstance(ctx, wasm, tr, guest.BestEffort) if err != nil {