Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

fix(plugins): free unused plugin memory and fix admin update flow

Gabe Kangas5091681ba28f
diff --git a/services/plugins/engine_cache.go b/services/plugins/engine_cache.go
index e1e318ab3f..0ac1f0b49e 100644
--- a/services/plugins/engine_cache.go
+++ b/services/plugins/engine_cache.go
@@ -3,6 +3,7 @@ package plugins
import (
"context"
"fmt"
+ "runtime/debug"
"sync"
extism "github.com/extism/go-sdk"
@@ -16,11 +17,20 @@ import (
// every plugin compiling its own copy of QuickJS/CPython, one compiled engine
// is shared across all plugins of that language.
//
+// Engines are reference-counted: every live plugin instance holds one
+// reference (taken by acquire, dropped by the release func it returns). When
+// the last plugin of a language unloads, the engine's runtime is closed and
+// its compiled native code is freed, so a server with all plugins disabled
+// pays no engine memory at all. The next load of that language recompiles the
+// engine from the embedded wasm.
+// ponytail: no linger on the last release — disabling then re-enabling the
+// sole plugin of a language recompiles the engine (sub-second for JS, a
+// couple of seconds for Python). Add a delayed close if that churn ever
+// matters.
+//
// It is package-level (not Manager-owned) for the same reason the plugin
-// registry and the compilation cache are: the load path (loadFromBytes,
-// LoadPlugin) runs without a Manager in the test runner and package preflight.
-// In production there is exactly one *HostEnv; the engine's host functions are
-// built once against the env captured on first compile.
+// registry is: the load path (loadFromBytes, LoadPlugin) runs without a
+// Manager in the test runner and package preflight.
// engineKey identifies a compiled engine. It includes the *HostEnv because the
// engine's host functions close over it: in production there is exactly one
// HostEnv (one Manager), so all plugins of a language share one engine and the
@@ -32,24 +42,65 @@ type engineKey struct {
env *HostEnv
}
+// engineEntry pairs a compiled engine with the number of live plugin
+// instances built from it.
+type engineEntry struct {
+ cp *extism.CompiledPlugin
+ refs int
+}
+
type engineCache struct {
mu sync.Mutex
- byKey map[engineKey]*extism.CompiledPlugin
+ byKey map[engineKey]*engineEntry
}
-var compiledEngines = &engineCache{byKey: map[engineKey]*extism.CompiledPlugin{}}
+var compiledEngines = &engineCache{byKey: map[engineKey]*engineEntry{}}
-// get returns the compiled engine for a (language, env) pair, compiling and
-// memoizing it on first use. Host functions are built once per engine and
-// shared across every instance it produces; they resolve the calling plugin's
-// identity at call time (see registry.go).
-func (c *engineCache) get(ctx context.Context, env *HostEnv, lang string) (*extism.CompiledPlugin, error) {
+// acquire returns the compiled engine for a (language, env) pair, compiling
+// and memoizing it on first use, and takes a reference on it. The returned
+// release func drops that reference; the caller must invoke it exactly once
+// when the plugin instance built from the engine is closed. Host functions
+// are built once per engine and shared across every instance it produces;
+// they resolve the calling plugin's identity at call time (see registry.go).
+func (c *engineCache) acquire(ctx context.Context, env *HostEnv, lang string) (*extism.CompiledPlugin, func(), error) {
c.mu.Lock()
defer c.mu.Unlock()
key := engineKey{lang: lang, env: env}
- if cp, ok := c.byKey[key]; ok {
- return cp, nil
+ entry, ok := c.byKey[key]
+ if !ok {
+ cp, err := compileEngine(ctx, env, lang)
+ if err != nil {
+ return nil, nil, err
+ }
+ entry = &engineEntry{cp: cp}
+ c.byKey[key] = entry
}
+ entry.refs++
+ return entry.cp, func() { c.release(key, entry) }, nil
+}
+
+// release drops one reference on an engine. When the last reference goes, the
+// engine's runtime (and with it the compiled native code) is closed and freed,
+// and the freed pages are handed back to the OS so the drop is visible to an
+// operator watching process memory.
+func (c *engineCache) release(key engineKey, entry *engineEntry) {
+ c.mu.Lock()
+ entry.refs--
+ closeIt := entry.refs == 0 && c.byKey[key] == entry
+ if closeIt {
+ delete(c.byKey, key)
+ }
+ c.mu.Unlock()
+ if closeIt {
+ _ = entry.cp.Close(context.Background())
+ debug.FreeOSMemory()
+ }
+}
+
+// compileEngine compiles the embedded engine wasm for a language. Called with
+// the cache lock held; compilation is rare (first plugin of a language after
+// none were loaded) so holding the lock through it is fine.
+func compileEngine(ctx context.Context, env *HostEnv, lang string) (*extism.CompiledPlugin, error) {
wasmBytes, ok := engines.Bytes(lang)
if !ok {
return nil, fmt.Errorf("no embedded engine for runtime %q", lang)
@@ -67,16 +118,23 @@ func (c *engineCache) get(ctx context.Context, env *HostEnv, lang string) (*exti
// not per engine, so it's set on each instance (inst.AllowedHosts)
// from the plugin's manifest at load time.
}
- // Share the compilation cache and build the full host-function set once.
+ // No external compilation cache: the engine's compiled code must die with
+ // its runtime when the last plugin of the language unloads. Reuse while
+ // plugins are loaded comes from the engineCache map itself.
// ModuleConfig is set per-instance (Instance()), not here.
pc := extism.PluginConfig{
EnableWasi: true,
- RuntimeConfig: wazero.NewRuntimeConfig().WithCompilationCache(sharedCompilationCache()),
+ RuntimeConfig: wazero.NewRuntimeConfig(),
}
cp, err := extism.NewCompiledPlugin(ctx, em, pc, BuildHostFunctions(env))
if err != nil {
return nil, fmt.Errorf("compile %s engine: %w", lang, err)
}
- c.byKey[key] = cp
+ // Compilation churns through large transient buffers (parsing, IR) that
+ // the Go runtime would otherwise sit on for minutes. Hand them back now so
+ // the steady-state cost of an enabled plugin is the compiled code and its
+ // instances, not the compiler's scratch space (measured: ~90 MiB retained
+ // across the JS+Python engine compiles without this).
+ debug.FreeOSMemory()
return cp, nil
}
diff --git a/services/plugins/engine_lifecycle_test.go b/services/plugins/engine_lifecycle_test.go
new file mode 100644
index 0000000000..eaf47f4f44
--- /dev/null
+++ b/services/plugins/engine_lifecycle_test.go
@@ -0,0 +1,337 @@
+package plugins
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "testing"
+)
+
+// engineCacheState reports the number of cached engines and the total live
+// references across them, read under the cache lock.
+func engineCacheState() (entries, refs int) {
+ compiledEngines.mu.Lock()
+ defer compiledEngines.mu.Unlock()
+ for _, e := range compiledEngines.byKey {
+ refs += e.refs
+ }
+ return len(compiledEngines.byKey), refs
+}
+
+// TestEngineRefcountLifecycle defends the shared-engine refcount invariant:
+// every live plugin instance holds one reference on its language's compiled
+// engine; the engine survives while any instance lives, is closed and evicted
+// when the last one closes, and a later load recompiles it from scratch.
+func TestEngineRefcountLifecycle(t *testing.T) {
+ ctx := context.Background()
+ compiledEngines.resetForTest(ctx)
+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
+
+ env, sends, mu := captureEnv()
+ script := `
+const { definePlugin, owncast } = require("@owncast/plugin-sdk");
+module.exports = definePlugin({
+ onChatMessage(msg) { owncast.chat.send("survivor: " + msg.body); }
+});`
+ p1 := loadShared(t, ctx, env, RuntimeJavaScript, "ref-one", script, []string{PermChatSend})
+ p2 := loadShared(t, ctx, env, RuntimeJavaScript, "ref-two", script, []string{PermChatSend})
+
+ if n, refs := engineCacheState(); n != 1 || refs != 2 {
+ t.Fatalf("after two JS loads: %d engines with %d total refs, want 1 engine with 2 refs", n, refs)
+ }
+
+ p1.Close(ctx)
+ if n, refs := engineCacheState(); n != 1 || refs != 1 {
+ t.Fatalf("after closing one of two: %d engines with %d refs, want the engine to survive with 1 ref", n, refs)
+ }
+
+ // The surviving instance must still dispatch on the shared engine.
+ d := NewLiveDispatcher(func() []*Loaded { return []*Loaded{p2} })
+ d.Dispatch(ctx, EventChatMessageReceived, chatPayload("alice", "still here"))
+ mu.Lock()
+ if len(*sends) != 1 || (*sends)[0].Text != "survivor: still here" {
+ mu.Unlock()
+ t.Fatalf("surviving plugin failed to dispatch after sibling close: sends=%+v", *sends)
+ }
+ mu.Unlock()
+
+ p2.Close(ctx)
+ if n, _ := engineCacheState(); n != 0 {
+ t.Fatalf("after closing the last JS plugin the engine must be evicted; %d entries remain", n)
+ }
+
+ // A later load must recompile the engine and work again.
+ p3 := loadShared(t, ctx, env, RuntimeJavaScript, "ref-three", script, []string{PermChatSend})
+ defer p3.Close(ctx)
+ if n, refs := engineCacheState(); n != 1 || refs != 1 {
+ t.Fatalf("load after eviction: %d engines with %d refs, want a freshly compiled engine with 1 ref", n, refs)
+ }
+}
+
+// TestLoadFailureReleasesEngine defends the load-error path: a script that
+// fails after the engine reference was taken (register() evals the author
+// source, which throws) must drop its reference so the engine is not leaked.
+func TestLoadFailureReleasesEngine(t *testing.T) {
+ ctx := context.Background()
+ compiledEngines.resetForTest(ctx)
+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
+
+ env, _, _ := captureEnv()
+ manifestBytes, _ := json.Marshal(map[string]any{
+ "api": "1",
+ "name": "boom",
+ "slug": "boom",
+ "version": "0.1.0",
+ "permissions": []string{},
+ })
+ _, err := loadFromBytes(ctx, env, manifestBytes, []byte(`throw new Error("boom")`), RuntimeJavaScript, "boom", nil)
+ if err == nil {
+ t.Fatal("expected the throwing script to fail the load")
+ }
+ if n, refs := engineCacheState(); n != 0 {
+ t.Fatalf("failed load leaked an engine reference: %d entries, %d refs", n, refs)
+ }
+}
+
+// lifecycleManifest builds manifest bytes for the Install lifecycle tests:
+// fixed slug, caller-chosen version and permissions.
+func lifecycleManifest(t *testing.T, version string, perms []string) []byte {
+ t.Helper()
+ b, err := json.Marshal(map[string]any{
+ "api": "1",
+ "name": "lifecycle-bot",
+ "slug": "lifecycle-bot",
+ "version": version,
+ "permissions": perms,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+// buildJSPackageBytes builds an in-memory .ocpkg carrying a plugin.js code
+// entry (the JS twin of buildPackageBytes, which hardcodes plugin.wasm).
+func buildJSPackageBytes(t *testing.T, manifest, script []byte) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ for name, data := range map[string][]byte{
+ pkgManifestFilename: manifest,
+ pkgJSFilename: script,
+ } {
+ w, err := zw.Create(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.Write(data); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+// TestManager_Install_ReloadsRunningInstanceOnUpdate defends the Install
+// contract for updates within the approved permission set: the returned entry
+// reports Enabled/Loaded like List() does, and installing v2 over a running v1
+// swaps the live instance so the new code answers dispatches immediately.
+func TestManager_Install_ReloadsRunningInstanceOnUpdate(t *testing.T) {
+ ctx := context.Background()
+ compiledEngines.resetForTest(ctx)
+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
+
+ env, sends, mu := captureEnv()
+ mgr := NewManager(t.TempDir(), env)
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(ctx)
+
+ script := func(tag string) []byte {
+ return fmt.Appendf(nil, `
+const { definePlugin, owncast } = require("@owncast/plugin-sdk");
+module.exports = definePlugin({
+ onChatMessage(msg) { owncast.chat.send(%q + msg.body); }
+});`, tag+": ")
+ }
+ perms := []string{PermChatSend}
+
+ entry, err := mgr.Install(ctx, buildJSPackageBytes(t, lifecycleManifest(t, "0.1.0", perms), script("v1")))
+ if err != nil {
+ t.Fatalf("install v1: %v", err)
+ }
+ if entry.Enabled || entry.Loaded {
+ t.Fatalf("fresh install must be neither enabled nor loaded: Enabled=%v Loaded=%v", entry.Enabled, entry.Loaded)
+ }
+
+ if err := mgr.Enable(ctx, "lifecycle-bot"); err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+
+ entry, err = mgr.Install(ctx, buildJSPackageBytes(t, lifecycleManifest(t, "0.2.0", perms), script("v2")))
+ if err != nil {
+ t.Fatalf("install v2: %v", err)
+ }
+ if !entry.Enabled || !entry.Loaded {
+ t.Fatalf("update of an enabled+loaded plugin must stay enabled+loaded: Enabled=%v Loaded=%v LastError=%q",
+ entry.Enabled, entry.Loaded, entry.LastError)
+ }
+ if entry.Version != "0.2.0" {
+ t.Errorf("entry version after update: got %q, want 0.2.0", entry.Version)
+ }
+ if len(entry.PendingPermissions) != 0 {
+ t.Errorf("same-permission update must not report pending permissions, got %v", entry.PendingPermissions)
+ }
+
+ // The running instance must be the NEW code: v2 answers the dispatch.
+ d := NewLiveDispatcher(mgr.Snapshot)
+ d.Dispatch(ctx, EventChatMessageReceived, chatPayload("alice", "ping"))
+ mu.Lock()
+ defer mu.Unlock()
+ if len(*sends) != 1 || (*sends)[0].Text != "v2: ping" {
+ t.Fatalf("dispatch after update: sends=%+v, want exactly one %q", *sends, "v2: ping")
+ }
+}
+
+// TestManager_Install_PermissionExpansionDefersReload defends the other half
+// of the Install update contract: when the new package declares a permission
+// the admin never approved, the running v1 instance is left alone (it holds
+// only approved permissions) and the entry reports the pending set for the
+// re-approval flow.
+func TestManager_Install_PermissionExpansionDefersReload(t *testing.T) {
+ ctx := context.Background()
+ compiledEngines.resetForTest(ctx)
+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
+
+ env, _, _ := captureEnv()
+ mgr := NewManager(t.TempDir(), env)
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(ctx)
+
+ script := []byte(`
+const { definePlugin } = require("@owncast/plugin-sdk");
+module.exports = definePlugin({ onChatMessage(msg) {} });`)
+
+ if _, err := mgr.Install(ctx, buildJSPackageBytes(t, lifecycleManifest(t, "0.1.0", []string{}), script)); err != nil {
+ t.Fatalf("install v1: %v", err)
+ }
+ if err := mgr.Enable(ctx, "lifecycle-bot"); err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+
+ entry, err := mgr.Install(ctx, buildJSPackageBytes(t, lifecycleManifest(t, "0.2.0", []string{PermChatSend}), script))
+ if err != nil {
+ t.Fatalf("install v2: %v", err)
+ }
+ if !entry.Enabled {
+ t.Error("permission-expanding update must leave the plugin enabled")
+ }
+ if !entry.Loaded {
+ t.Error("permission-expanding update must leave the old instance loaded")
+ }
+ if len(entry.PendingPermissions) != 1 || entry.PendingPermissions[0] != PermChatSend {
+ t.Errorf("pending permissions: got %v, want [%s]", entry.PendingPermissions, PermChatSend)
+ }
+
+ // The old instance is still the one running: its manifest is v1.
+ snap := mgr.Snapshot()
+ if len(snap) != 1 {
+ t.Fatalf("expected exactly one loaded plugin, got %d", len(snap))
+ }
+ if got := snap[0].Manifest.Version; got != "0.1.0" {
+ t.Errorf("running instance version after deferred update: got %q, want the old 0.1.0", got)
+ }
+}
+
+// TestManager_Enable_ReApprovesPendingPermissionsAndSwapsInstance defends the
+// re-approval contract: Enable on an already-enabled, already-loaded plugin
+// with pending permissions re-captures the approval baseline, clears the
+// pending set, and swaps the running old-version instance for one built from
+// the updated package — releasing the old instance's engine reference. Enable
+// with nothing pending stays a no-op and must not restart the instance.
+func TestManager_Enable_ReApprovesPendingPermissionsAndSwapsInstance(t *testing.T) {
+ ctx := context.Background()
+ compiledEngines.resetForTest(ctx)
+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
+
+ env, _, _ := captureEnv()
+ mgr := NewManager(t.TempDir(), env)
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(ctx)
+
+ script := []byte(`
+const { definePlugin } = require("@owncast/plugin-sdk");
+module.exports = definePlugin({ onChatMessage(msg) {} });`)
+
+ // v1 with no permissions, enabled; v2 expands to chat.send → deferred.
+ if _, err := mgr.Install(ctx, buildJSPackageBytes(t, lifecycleManifest(t, "0.1.0", []string{}), script)); err != nil {
+ t.Fatalf("install v1: %v", err)
+ }
+ if err := mgr.Enable(ctx, "lifecycle-bot"); err != nil {
+ t.Fatalf("enable v1: %v", err)
+ }
+ if _, err := mgr.Install(ctx, buildJSPackageBytes(t, lifecycleManifest(t, "0.2.0", []string{PermChatSend}), script)); err != nil {
+ t.Fatalf("install v2: %v", err)
+ }
+
+ // Re-approval: the admin consents to the expanded permission set.
+ if err := mgr.Enable(ctx, "lifecycle-bot"); err != nil {
+ t.Fatalf("re-approving Enable: %v", err)
+ }
+
+ var entry *DiscoveredEntry
+ for _, e := range mgr.List() {
+ if e.Slug == "lifecycle-bot" {
+ entry = &e
+ break
+ }
+ }
+ if entry == nil {
+ t.Fatal("lifecycle-bot missing from List() after re-approval")
+ }
+ if len(entry.PendingPermissions) != 0 {
+ t.Errorf("re-approval must clear pending permissions, got %v", entry.PendingPermissions)
+ }
+ if !entry.Enabled || !entry.Loaded {
+ t.Errorf("re-approved plugin must be enabled+loaded: Enabled=%v Loaded=%v LastError=%q",
+ entry.Enabled, entry.Loaded, entry.LastError)
+ }
+
+ // The running instance is now the updated package.
+ snap := mgr.Snapshot()
+ if len(snap) != 1 {
+ t.Fatalf("expected exactly one loaded plugin after re-approval, got %d", len(snap))
+ }
+ if got := snap[0].Manifest.Version; got != "0.2.0" {
+ t.Errorf("running instance version after re-approval: got %q, want 0.2.0", got)
+ }
+
+ // One live instance → one engine holding exactly one reference; the
+ // swapped-out old instance must have released its ref.
+ if n, refs := engineCacheState(); n != 1 || refs != 1 {
+ t.Fatalf("engine cache after instance swap: %d engines with %d refs, want 1 engine with 1 ref (old ref leaked?)", n, refs)
+ }
+
+ // Enable with nothing pending stays a no-op: the same instance keeps
+ // running (a restart would produce a new *Loaded).
+ cur := snap[0]
+ if err := mgr.Enable(ctx, "lifecycle-bot"); err != nil {
+ t.Fatalf("no-op Enable: %v", err)
+ }
+ snap = mgr.Snapshot()
+ if len(snap) != 1 || snap[0] != cur {
+ t.Fatal("Enable on an enabled+loaded plugin with nothing pending must not restart the instance")
+ }
+ if n, refs := engineCacheState(); n != 1 || refs != 1 {
+ t.Fatalf("engine cache after no-op Enable: %d engines with %d refs, want unchanged 1/1", n, refs)
+ }
+}
diff --git a/services/plugins/manager.go b/services/plugins/manager.go
index cb7977af9f..2775be60a0 100644
--- a/services/plugins/manager.go
+++ b/services/plugins/manager.go
@@ -11,6 +11,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "runtime/debug"
"sort"
"strings"
"sync"
@@ -47,17 +48,21 @@ import (
// downloadable directly. Populated from an `assets/` directory in the
// .ocpkg (or a <name>-assets/ sibling for loose-files plugins).
type Loaded struct {
- Manifest *Manifest
- WasmPath string
- PublicFS fs.FS
- AssetsFS fs.FS
- adminGlobs []glob.Glob // compiled from manifest.admin.pages[].path
- adminPaths []string // original path strings, used for "page gates descendants" prefix-matching
- plugin *extism.Plugin
- mu sync.Mutex
- failureMu sync.Mutex
- filterFails int
- disabled atomic.Bool
+ Manifest *Manifest
+ WasmPath string
+ PublicFS fs.FS
+ AssetsFS fs.FS
+ adminGlobs []glob.Glob // compiled from manifest.admin.pages[].path
+ adminPaths []string // original path strings, used for "page gates descendants" prefix-matching
+ plugin *extism.Plugin
+ // releaseEngine drops this instance's reference on its shared compiled
+ // engine (nil for legacy self-contained wasm). Called exactly once by
+ // Close, after the instance itself is closed.
+ releaseEngine func()
+ mu sync.Mutex
+ failureMu sync.Mutex
+ filterFails int
+ disabled atomic.Bool
// pkgCloser holds the file-backed zip reader for .ocpkg plugins so the
// underlying file stays open for PublicFS / AssetsFS reads. nil for
// loose-files plugins. Closed by Loaded.Close.
@@ -127,30 +132,6 @@ const (
HTTPHandlerTimeout = 5 * time.Second
)
-// wasmCompilationCache is shared across every plugin instance so wazero
-// compiles a given wasm module to native code at most once for the lifetime
-// of the process. The cache is keyed on module content, so it dedupes the
-// repeated work of reloading the same plugin (dev churn, reload-on-change,
-// or running multiple instances of one plugin). It is safe for concurrent
-// use across runtimes.
-//
-// NOTE: this does NOT dedupe the interpreter engine across *different*
-// plugins — each plugin's wasm bundles the QuickJS/CPython engine together
-// with the author's code, so every plugin's bytes differ and hash to a
-// distinct cache key. Sharing the engine across distinct plugins requires
-// splitting it out of the per-plugin module; tracked separately.
-var (
- wasmCompilationCache wazero.CompilationCache
- wasmCompilationCacheOnce sync.Once
-)
-
-func sharedCompilationCache() wazero.CompilationCache {
- wasmCompilationCacheOnce.Do(func() {
- wasmCompilationCache = wazero.NewCompilationCache()
- })
- return wasmCompilationCache
-}
-
// IsDisabled reports whether the plugin has been auto-disabled by the
// strike system. Disabled plugins are omitted from Manager.Snapshot, so they
// are skipped by every dispatch and serve path (filter chain, notifications,
@@ -292,13 +273,19 @@ func (l *Loaded) Close(ctx context.Context) {
l.mu.Lock()
pl := l.plugin
l.plugin = nil
+ release := l.releaseEngine
+ l.releaseEngine = nil
l.mu.Unlock()
if pl != nil {
- // Closes this instance only. For shared-engine plugins the underlying
- // CompiledPlugin (the engine) is process-global and is never closed
- // here; for legacy wasm plugins this closes their own runtime.
+ // Closes this instance only; the shared compiled engine is
+ // reference-counted and torn down by releaseEngine below when this
+ // was the last plugin of its language. Legacy wasm plugins close
+ // their own runtime here.
_ = pl.Close(ctx)
}
+ if release != nil {
+ release()
+ }
// Drop the call-time identity so any in-flight or stale host call from this
// plugin resolves to "not found" and fails cleanly rather than acting on a
// torn-down plugin.
@@ -628,7 +615,12 @@ func (m *Manager) Snapshot() []*Loaded {
// Enable marks a discovered plugin as enabled, captures the current
// manifest's permission set as the approved baseline (so any later
// expansion triggers a re-approval flow), persists the choice, and
-// loads the plugin. No-op if already loaded.
+// loads the plugin. No-op if already loaded with nothing pending.
+//
+// Calling Enable on an already-enabled, already-loaded plugin that has
+// pending permissions is the re-approval action: the admin consents to the
+// expanded set, so the baseline is re-captured and the running (old-version)
+// instance is swapped for one built from the current package.
func (m *Manager) Enable(ctx context.Context, name string) error {
m.mu.Lock()
d, ok := m.discovered[name]
@@ -637,8 +629,10 @@ func (m *Manager) Enable(ctx context.Context, name string) error {
return fmt.Errorf("plugin %q not discovered", name)
}
if m.enabledSet[name] {
- // Already enabled in the persisted set; just make sure it's loaded.
- if _, ok := m.loaded[name]; ok {
+ // Already enabled and running with nothing awaiting approval:
+ // nothing to do. With pending permissions, fall through — this
+ // call is the admin approving them.
+ if _, ok := m.loaded[name]; ok && len(pendingPermissions(d.Permissions, m.approvedSet[name])) == 0 {
m.mu.Unlock()
return nil
}
@@ -665,8 +659,18 @@ func (m *Manager) Enable(ctx context.Context, name string) error {
if err := m.saveEnabledSet(); err != nil {
return fmt.Errorf("persist enabled set: %w", err)
}
- err := m.loadInternal(ctx, name)
- return err
+ // Swap out any still-running instance (re-approval of an updated plugin)
+ // before loading, so the old instance and its engine reference are
+ // released rather than silently overwritten in m.loaded.
+ m.mu.Lock()
+ old := m.loaded[name]
+ delete(m.loaded, name)
+ m.mu.Unlock()
+ if old != nil {
+ m.notifyUnload(old)
+ old.Close(ctx)
+ }
+ return m.loadInternal(ctx, name)
}
// validateUploadedPackage checks an uploaded .ocpkg's bytes, verifies the
@@ -815,8 +819,17 @@ const MaxUploadBytes = 50 * 1024 * 1024
// filename is derived from the manifest's name, not from the uploaded
// name, so an admin can't drop a file outside the plugins directory by
// abusing the upload filename, and a plugin update from a differently
-// named .ocpkg ends up replacing the right file. Returns the discovered
-// entry for the installed plugin.
+// named .ocpkg ends up replacing the right file.
+//
+// When the plugin is already enabled and the new manifest declares no
+// permissions beyond the approved set, the running instance is reloaded in
+// place so the update takes effect immediately. If the update expands
+// permissions, the old instance keeps running (it holds only approved
+// permissions) and the entry reports PendingPermissions so the admin UI can
+// run the re-approval flow.
+//
+// Returns the discovered entry for the installed plugin, with Enabled and
+// Loaded populated the same way List() reports them.
func (m *Manager) Install(ctx context.Context, packageBytes []byte) (*DiscoveredEntry, error) {
manifest, err := validateUploadedPackage(ctx, m.env, packageBytes)
if err != nil {
@@ -834,14 +847,36 @@ func (m *Manager) Install(ctx context.Context, packageBytes []byte) (*Discovered
m.mu.RLock()
entry, ok := m.discovered[manifest.Slug]
- var snapshot DiscoveredEntry
+ enabled := m.enabledSet[manifest.Slug]
+ _, isLoaded := m.loaded[manifest.Slug]
+ pending := 0
if ok {
- snapshot = *entry
+ pending = len(entry.PendingPermissions)
}
m.mu.RUnlock()
if !ok {
return nil, fmt.Errorf("scan did not pick up the installed plugin %q", manifest.Slug)
}
+
+ // An update of an enabled plugin whose permissions are still covered by
+ // the admin's approval takes effect now: swap the running instance for
+ // one built from the new package. A failure surfaces via LastError (set
+ // by loadInternal) rather than failing the install — the file on disk is
+ // already the new version either way.
+ if enabled && isLoaded && pending == 0 {
+ if err := m.Reload(ctx, manifest.Slug); err != nil {
+ fmt.Fprintf(os.Stderr, "plugin %s: reload after update failed: %v\n", manifest.Slug, err)
+ }
+ }
+
+ m.mu.RLock()
+ var snapshot DiscoveredEntry
+ if entry, ok := m.discovered[manifest.Slug]; ok {
+ snapshot = *entry
+ snapshot.Enabled = m.enabledSet[manifest.Slug]
+ _, snapshot.Loaded = m.loaded[manifest.Slug]
+ }
+ m.mu.RUnlock()
return &snapshot, nil
}
@@ -910,6 +945,10 @@ func (m *Manager) Disable(ctx context.Context, name string) error {
m.notifyUnload(loaded)
loaded.Close(ctx)
}
+ // Hand freed pages back to the OS promptly so an operator watching
+ // process memory sees the disable take effect (the Go scavenger would
+ // get there, but only after minutes).
+ debug.FreeOSMemory()
return nil
}
@@ -937,6 +976,7 @@ func (m *Manager) Uninstall(ctx context.Context, name string) error {
if loaded != nil {
m.notifyUnload(loaded)
loaded.Close(ctx)
+ debug.FreeOSMemory()
}
// Persist the cleared enabled + approved state before touching the
@@ -1444,11 +1484,21 @@ func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, artifactByt
}
manifest.Type = runtimeType
- p, err := instantiate(ctx, env, manifest, manifestBytes, artifactBytes, displayName)
+ p, releaseEngine, err := instantiate(ctx, env, manifest, manifestBytes, artifactBytes, displayName)
if err != nil {
return nil, err
}
+ // fail tears down the just-created instance (and its engine reference) on
+ // any load-path error below.
+ fail := func(err error) error {
+ _ = p.Close(ctx)
+ if releaseEngine != nil {
+ releaseEngine()
+ }
+ return err
+ }
+
// Register the plugin's identity so shared host functions can resolve it at
// call time (by the slug stashed in the instance's Extism config). Done
// before register() because the engine bootstrap evals author top-level
@@ -1467,30 +1517,24 @@ func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, artifactByt
})
if !p.FunctionExists("register") {
- _ = p.Close(ctx)
- return nil, fmt.Errorf("plugin does not export register()")
+ return nil, fail(fmt.Errorf("plugin does not export register()"))
}
_, regOut, err := p.Call("register", nil)
if err != nil {
- _ = p.Close(ctx)
- return nil, fmt.Errorf("call register(): %w", err)
+ return nil, fail(fmt.Errorf("call register(): %w", err))
}
if len(regOut) > MaxRegisterOutputBytes {
- _ = p.Close(ctx)
- return nil, fmt.Errorf("register() output too large: %d bytes (max %d)", len(regOut), MaxRegisterOutputBytes)
+ return nil, fail(fmt.Errorf("register() output too large: %d bytes (max %d)", len(regOut), MaxRegisterOutputBytes))
}
var runtime Manifest
if err := json.Unmarshal(regOut, &runtime); err != nil {
- _ = p.Close(ctx)
- return nil, fmt.Errorf("parse register() output: %w", err)
+ return nil, fail(fmt.Errorf("parse register() output: %w", err))
}
if err := manifest.AgreesWith(&runtime); err != nil {
- _ = p.Close(ctx)
- return nil, fmt.Errorf("manifest/runtime mismatch: %w", err)
+ return nil, fail(fmt.Errorf("manifest/runtime mismatch: %w", err))
}
if err := requireChatFilterPermission(manifest, runtime.Subscriptions); err != nil {
- _ = p.Close(ctx)
- return nil, err
+ return nil, fail(err)
}
manifest.Subscriptions = runtime.Subscriptions
// Command metadata is derived by the SDK and reported via register() (like
@@ -1506,15 +1550,14 @@ func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, artifactByt
lowered := strings.ToLower(page.Path)
g, err := glob.Compile(lowered)
if err != nil {
- _ = p.Close(ctx)
- return nil, fmt.Errorf("manifest.admin.pages: invalid path glob %q: %w", page.Path, err)
+ return nil, fail(fmt.Errorf("manifest.admin.pages: invalid path glob %q: %w", page.Path, err))
}
adminGlobs = append(adminGlobs, g)
adminPaths = append(adminPaths, lowered)
}
loaded = true
- return &Loaded{Manifest: manifest, plugin: p, adminGlobs: adminGlobs, adminPaths: adminPaths, AssetsFS: assetsFS}, nil
+ return &Loaded{Manifest: manifest, plugin: p, releaseEngine: releaseEngine, adminGlobs: adminGlobs, adminPaths: adminPaths, AssetsFS: assetsFS}, nil
}
// instantiate creates the extism plugin instance for a manifest: a per-plugin
@@ -1522,20 +1565,26 @@ func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, artifactByt
// for "wasm"/legacy. Either way the result is a *extism.Plugin with its
// identity slug stashed in Config so shared host functions can resolve the
// caller, and its per-plugin network scope applied.
-func instantiate(ctx context.Context, env *HostEnv, manifest *Manifest, manifestBytes, artifactBytes []byte, displayName string) (*extism.Plugin, error) {
+//
+// For shared-engine plugins the returned release func drops the instance's
+// reference on the compiled engine; the caller must invoke it exactly once
+// after closing the instance. nil for legacy self-contained wasm, whose
+// instance close tears down its whole runtime.
+func instantiate(ctx context.Context, env *HostEnv, manifest *Manifest, manifestBytes, artifactBytes []byte, displayName string) (*extism.Plugin, func(), error) {
// Give the guest the real host wall and monotonic clocks (wazero's default
// is a frozen 2022 clock). Nanosleep is deliberately NOT wired so a plugin
// can't block inside a call and burn its timeout budget.
moduleConfig := wazero.NewModuleConfig().WithSysWalltime().WithSysNanotime()
if manifest.usesSharedEngine() {
- engine, err := compiledEngines.get(ctx, env, manifest.Type)
+ engine, release, err := compiledEngines.acquire(ctx, env, manifest.Type)
if err != nil {
- return nil, err
+ return nil, nil, err
}
inst, err := engine.Instance(ctx, extism.PluginInstanceConfig{ModuleConfig: moduleConfig})
if err != nil {
- return nil, fmt.Errorf("instantiate %s engine: %w", manifest.Type, err)
+ release()
+ return nil, nil, fmt.Errorf("instantiate %s engine: %w", manifest.Type, err)
}
// Inject the per-plugin script + manifest the engine bootstrap reads at
// runtime, plus the slug shared host functions resolve identity by.
@@ -1545,12 +1594,14 @@ func instantiate(ctx context.Context, env *HostEnv, manifest *Manifest, manifest
configKeyManifest: string(manifestBytes),
}
applyNetworkScope(inst, manifest)
- return inst, nil
+ return inst, release, nil
}
- // Legacy self-contained wasm: each plugin compiles into its own runtime.
- // Share the compilation cache so reloads / repeated loads of the same
- // module don't recompile its embedded engine.
+ // Legacy self-contained wasm: each plugin compiles into its own runtime,
+ // deliberately without a shared compilation cache — a cache entry would
+ // pin the compiled native code for the life of the process, so disabling
+ // the plugin would never return its memory. Reloads recompile (fast
+ // relative to an explicit admin action).
extismManifest := extism.Manifest{
Wasm: []extism.Wasm{extism.WasmData{Data: artifactBytes, Name: displayName}},
Timeout: 10_000, // milliseconds; enables Wazero's WithCloseOnContextDone
@@ -1569,16 +1620,19 @@ func instantiate(ctx context.Context, env *HostEnv, manifest *Manifest, manifest
pc := extism.PluginConfig{
EnableWasi: true,
ModuleConfig: moduleConfig,
- RuntimeConfig: wazero.NewRuntimeConfig().WithCompilationCache(sharedCompilationCache()),
+ RuntimeConfig: wazero.NewRuntimeConfig(),
}
p, err := extism.NewPlugin(ctx, extismManifest, pc, BuildHostFunctions(env))
if err != nil {
- return nil, fmt.Errorf("instantiate wasm: %w", err)
+ return nil, nil, fmt.Errorf("instantiate wasm: %w", err)
}
// Even self-contained plugins now use the shared, identity-resolving host
// functions, so stash the slug for the registry lookup.
p.Config = map[string]string{configKeySlug: manifest.Slug}
- return p, nil
+ // Return the compiler's transient scratch space now rather than letting
+ // the Go runtime sit on it (same reasoning as compileEngine).
+ debug.FreeOSMemory()
+ return p, nil, nil
}
// applyNetworkScope sets a shared-engine instance's per-plugin AllowedHosts.
diff --git a/services/plugins/shared_engine_test.go b/services/plugins/shared_engine_test.go
index c39a9b13bb..afbccd0a32 100644
--- a/services/plugins/shared_engine_test.go
+++ b/services/plugins/shared_engine_test.go
@@ -394,8 +394,8 @@ def greet(msg):
// file so it isn't flagged as unused production code.
func (c *engineCache) resetForTest(ctx context.Context) {
c.mu.Lock()
- for k, cp := range c.byKey {
- _ = cp.Close(ctx)
+ for k, entry := range c.byKey {
+ _ = entry.cp.Close(ctx)
delete(c.byKey, k)
}
c.mu.Unlock()
diff --git a/web/components/admin/MainLayout.tsx b/web/components/admin/MainLayout.tsx
index 7921e516b1..32022681a0 100644
--- a/web/components/admin/MainLayout.tsx
+++ b/web/components/admin/MainLayout.tsx
@@ -342,15 +342,16 @@ export const MainLayout: FC<MainLayoutProps> = ({ children }) => {
key: '/admin/plugins',
label: <Link href="/admin/plugins">{t(Localization.Admin.Plugins.overview)}</Link>,
},
- // One entry per loaded plugin that declares at least one admin
+ // One entry per enabled plugin that declares at least one admin
// page, so the admin can jump straight to a plugin's config
- // without going through the overview + Configure button. URL is
+ // without going through the overview + Configure button. Disabled
+ // plugins are omitted — their admin pages don't serve. URL is
// a static route plus an id query param (the plugin's slug)
// because the admin UI is statically exported and can't
// enumerate plugin identifiers at build time. Sidebar labels use
// the human-readable display name.
...plugins
- .filter(p => (p.adminPages?.length ?? 0) > 0)
+ .filter(p => p.enabled && (p.adminPages?.length ?? 0) > 0)
.map(p => ({
key: `/admin/plugins/configure?id=${p.slug}`,
label: (
diff --git a/web/pages/admin/plugins.tsx b/web/pages/admin/plugins.tsx
index 3c66e94332..675fda242d 100644
--- a/web/pages/admin/plugins.tsx
+++ b/web/pages/admin/plugins.tsx
@@ -242,6 +242,24 @@ const Plugins = () => {
}
};
+ // Called when the admin declines the post-install confirmation. For a
+ // fresh install the plugin was never enabled, so there's nothing to do.
+ // For an update that expanded permissions the plugin is still enabled
+ // (running the old, previously-approved code), so declining the new
+ // permissions must actually disable it — otherwise "no" would silently
+ // leave it running.
+ const handleDeclineAfterInstall = async () => {
+ const plugin = pendingEnable;
+ setPendingEnable(null);
+ if (!plugin?.enabled) return;
+ try {
+ await fetchData(pluginActionUrl(plugin.slug, 'disable'), { method: 'POST' });
+ await loadPlugins();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ }
+ };
+
// Common path for "fetch the registry's bytes for (name, version)
// and run Manager.Install". Shared between the Browse tab's Update
// button and the Installed tab's "update available" tag so both
@@ -257,12 +275,11 @@ const Plugins = () => {
message.success(t(Localization.Admin.Plugins.uploadSuccess, { name: entry.name }));
await loadPlugins();
await loadRegistry();
- // Only prompt to enable for plugins that aren't already
- // running. Updates of enabled plugins keep their enabled state
- // unless the new manifest expanded permissions (in which case
- // the host marks them auto-disabled and the modal shows the
- // new perms).
- if (!entry.enabled) {
+ // Prompt only when there's a decision to make: a fresh install
+ // that isn't running yet, or an update that expanded permissions
+ // and needs re-approval. An update with unchanged permissions
+ // reloads in place on the host and needs no prompt.
+ if (!entry.enabled || (entry.pendingPermissions?.length ?? 0) > 0) {
setPendingEnable(entry);
}
} catch (e) {
@@ -349,7 +366,7 @@ const Plugins = () => {
<InstallConfirmModal
plugin={pendingEnable}
- onCancel={() => setPendingEnable(null)}
+ onCancel={handleDeclineAfterInstall}
onEnable={handleEnableAfterInstall}
/>
</div>