Skip to content

plugin: a reloading plugin's tools leave ctx.tool.list() while ctx.plugin.list() says active (2.3.0) #64464

In review

Description

@iceteaSA

Summary

On 2.3.0, when a server plugin is reloaded in place (for example after a change of its options in opencode.json), the tools that the plugin registers are absent from the tool list for a short time, as a reader inside the server sees it (ctx.tool.list() from another plugin). During the same time ctx.plugin.list() reports the reloading plugin as active. The tools return by themselves. The same test on 2.2.6 does not show the gap.

This is a consistency report, not a report of lost work: in a second measurement, model requests that were sent during the reload were held and arrived after it with the complete tool list.

Environment

  • opencode 2.3.0 (release binary), Linux x64, one shared server, three loaded locations.
  • Comparison: opencode 2.2.6, same machine, same test.

What was measured

Plugin A registers tools; the test watches one of them. A second plugin registers one test tool. A fixture plugin reads ctx.tool.list() and ctx.plugin.list() for an open session of each location. The test changes one option value of plugin A in the global opencode.json one time and then samples both lists every 20 ms for 15 s.

On 2.3.0, in three runs with two reloads each and three locations (18 location reloads):

Result
First sample without plugin A's tool 301 to 366 ms after the configuration write
First sample with the tool again 339 to 454 ms after the write
Length of the gap by the samples 36 to 88 ms, in each of the 18 reloads
ctx.plugin.list() state of plugin A in the gap active in every sample
After the return the tool is present in every sample to the end (more than 14 s)

The test tool of the second plugin is absent in the same samples and returns in the same sample or one sample later.

On 2.2.6 the same test with the same sampler has no sample without the tool.

A second measurement on a full plugin set read the tool names that a model request carries (arrival times at a stand-in provider). A prompt that was sent during the reload arrived after the reload with the complete tool list. Where the server holds such a prompt was not read.

Expected

A reader of the tool list and the plugin list inside the server sees a consistent pair: either the old registrations until the swap is complete, or a plugin state that says the plugin is not ready. A plugin that checks "is tool X present" after a reload cannot tell this gap from a tool that is truly missing, because the plugin list says active.

Possible cause (read in the source, not proven)

packages/core/src/plugin.ts:137-193 at v2.3.0 (the file is identical on the current dev): the reload runs inside State.batch(...). It first closes the activation scope of every plugin after the unchanged prefix (:141-156), which removes their registrations, and then loads the replacements one after the other (:157-188). The inventory snapshot is taken at the end of the batch (:190) and published after it (:193), so the plugin list keeps the old active rows during the batch. State.batch (packages/core/src/state.ts:87-105) holds back the change notifications until the batch ends, but a direct read of the tool registry during the batch sees the closed registrations.

The order "close, then load" is the same at v2.2.6. Why 2.2.6 does not show the gap to the same reader is not known to me.

Related

Notes

I can supply a minimal reproduction (two plugins and a sampler) if that helps.

Activity

  1. added
    area/plugins
    type/bug
    version/v2
    on Nov 17, 2026
  2. opencodejr commented on Nov 17, 2026

    @opencodejr
    Contributor

    Thanks for the detailed report. I reproduced this on the released 2.3.0, and it still happens on the latest dev (00016308).

    Setup (the script below does all of this):

    • One opencode serve with three local plugins in the global opencode.json.
    • A sampler loads first and reads ctx.tool.list() and ctx.plugin.list() every 20 ms.
    • alpha takes options and registers alpha_probe.
    • beta loads after alpha and registers beta_probe.
    • The script changes alpha's option value four times, 6 s apart.

    What I saw:

    • After each change, alpha's setup runs again about 330 ms after the write.
    • For about 55–100 ms after that, alpha_probe, beta_probe and all the browser_* tools of the built-in browser plugin (which loads after alpha) are missing from ctx.tool.list(). The list drops from 68 tools to 21.
    • During that time, ctx.plugin.list() keeps reporting alpha as active.
    • The tools then come back by themselves, as you describe.

    One difference from your report: to see the gap, alpha's setup waits 60 ms before registering, like a plugin that loads data first. With an instant setup, the window was shorter than one 20 ms sample. With that delay, the same script also shows the gap on 2.2.6, so in my setup I could not confirm that it is new in 2.3.0.

    Your reading of packages/core/src/plugin.ts fits what I saw. The reload closes the activations after the unchanged prefix, then loads the replacements one by one, and only takes the plugin inventory snapshot at the end. State.batch only holds back notifications, so reads in between see the closed registrations.

    Related: #59993, where a location reload leaves an empty tool catalog. It takes a different path but has a similar symptom.

    Reproduction script (repro.sh)
    #!/usr/bin/env bash
    # Repro for #64464: tools of a reloading plugin vanish from ctx.tool.list() while ctx.plugin.list() says "active".
    # Usage: ./repro.sh            (uses `opencode` on PATH)
    #        OC_CMD="bun ... /path/packages/cli/src/index.ts" ./repro.sh   (run from source)
    set -u
    # Writes three local plugins (sampler first, then alpha with options, then beta) and a global opencode.json,
    # starts `opencode serve`, changes alpha's option four times and samples ctx.tool.list()/ctx.plugin.list() every 20 ms.
    # alpha waits ALPHA_SETUP_DELAY_MS (default 60) in setup before registering, like a plugin that loads data first.
    mkdir -p /tmp/opencode
    R=${REPRO_DIR:-/tmp/opencode/repro-64464}
    OC_CMD=${OC_CMD:-opencode}
    export HOME=$R/home XDG_CONFIG_HOME=$R/xdg/config XDG_DATA_HOME=$R/xdg/data XDG_STATE_HOME=$R/xdg/state XDG_CACHE_HOME=$R/xdg/cache
    export SAMPLER_OUT=/tmp/opencode/samples.jsonl
    rm -rf "$R/home" "$R/xdg"; mkdir -p "$HOME" "$XDG_CONFIG_HOME/opencode" "$R/project"
    : > "$SAMPLER_OUT"
    mkdir -p "$R/plugins/sampler" "$R/plugins/alpha" "$R/plugins/beta"
    cat > "$R/plugins/sampler/index.ts" <<'TS'
    // Sampler: loaded first, polls ctx.tool.list() and ctx.plugin.list() every 20 ms
    import { appendFileSync } from "node:fs"
    const OUT = process.env.SAMPLER_OUT ?? "/tmp/opencode/samples.jsonl"
    export default {
      id: "sampler",
      async setup(ctx: any) {
        let busy = false
        const timer = setInterval(async () => {
          if (busy) return
          busy = true
          try {
            const [tools, plugins] = await Promise.all([ctx.tool.list(), ctx.plugin.list()])
            const toolArr = Array.isArray(tools) ? tools : (tools?.data ?? [])
            const plugArr = Array.isArray(plugins) ? plugins : (plugins?.data ?? [])
            const ids = toolArr.map((t: any) => t.id)
            const alphaPlugin = plugArr.find((p: any) => p.id === "alpha")
            appendFileSync(OUT, JSON.stringify({
              t: Date.now(),
              alphaTool: ids.some((i: string) => i.includes("alpha_probe")),
              betaTool: ids.some((i: string) => i.includes("beta_probe")),
              alphaState: alphaPlugin?.state?.status ?? null,
              alphaOptions: alphaPlugin?.options ?? alphaPlugin?.source?.options ?? undefined,
              ntools: ids.length,
              ids: process.env.SAMPLER_IDS ? ids : undefined,
            }) + "\n")
          } catch (e) {
            appendFileSync(OUT, JSON.stringify({ t: Date.now(), error: String(e) }) + "\n")
          } finally { busy = false }
        }, 20)
        ;(timer as any).unref?.()
      },
    }
    TS
    cat > "$R/plugins/alpha/index.ts" <<'TS'
    // Plugin A: registers a tool and takes options from opencode.json
    import { appendFileSync } from "node:fs"
    export default {
      id: "alpha",
      async setup(ctx: any) {
        appendFileSync("/tmp/opencode/samples.jsonl", JSON.stringify({ t: Date.now(), alphaSetup: ctx.options }) + "\n")
        // simulate a plugin that loads something before registering (e.g. reads a file or a remote list)
        await new Promise((r) => setTimeout(r, Number(process.env.ALPHA_SETUP_DELAY_MS ?? 60)))
        await ctx.tool.transform((editor: any) => {
          editor.add({
            name: "alpha_probe",
            description: "alpha probe tool (option " + JSON.stringify(ctx.options) + ")",
            input: { type: "object", properties: {}, additionalProperties: false },
            execute: async () => ({ content: "alpha" }),
          })
        })
      },
    }
    TS
    cat > "$R/plugins/beta/index.ts" <<'TS'
    // Plugin B: registers one test tool, loaded after alpha
    export default {
      id: "beta",
      async setup(ctx: any) {
        await ctx.tool.transform((editor: any) => {
          editor.add({
            name: "beta_probe",
            description: "beta probe tool",
            input: { type: "object", properties: {}, additionalProperties: false },
            execute: async () => ({ content: "beta" }),
          })
        })
      },
    }
    TS
    CFG=$XDG_CONFIG_HOME/opencode/opencode.json
    write_cfg() {
    cat > "$CFG" <<JSON
    {
      "plugins": [
        "$R/plugins/sampler",
        { "package": "$R/plugins/alpha", "options": { "value": $1 } },
        "$R/plugins/beta"
      ]
    }
    JSON
    }
    write_cfg 1
    PORT=4599
    export OPENCODE_SERVER_PASSWORD=repro-pass
    (cd "$R/project" && exec $OC_CMD serve --port $PORT --hostname 127.0.0.1 > /tmp/opencode/serve.log 2>&1) &
    SPID=$!
    trap 'kill $SPID 2>/dev/null; pkill -P $SPID 2>/dev/null' EXIT
    for i in $(seq 1 60); do curl -sf "http://127.0.0.1:$PORT/" >/dev/null 2>&1 && break; sleep 0.5; done
    # load the project location by listing plugins there
    curl -s -u "opencode:repro-pass" "http://127.0.0.1:$PORT/api/plugin?location%5Bdirectory%5D=$R/project" -o /tmp/opencode/plugins.json -w "plugin list HTTP %{http_code}\n"
    sleep 5
    for v in 2 3 4 5; do
      W=$(date +%s%3N); echo "write value=$v at $W"; write_cfg $v; sleep 6
      echo "$W" >> /tmp/opencode/writes.txt
    done
    python3 - "$SAMPLER_OUT" <<'PY'
    import json,sys
    s=[json.loads(l) for l in open(sys.argv[1]) if l.strip()]
    print("samples:",len(s))
    prev=None
    for x in s:
        k=(x.get("alphaSetup") and x['t'],x.get("alphaTool"),x.get("betaTool"),x.get("alphaState"),x.get("error"))
        if k!=prev: print(x); prev=k
    gap=[x for x in s if x.get("alphaTool") is False and x.get("alphaState")=="active"]
    print("samples with alpha tool missing while alpha state == active:",len(gap))
    PY

    Run it: bash repro.sh

  3. argszero commented on Nov 17, 2026

    @argszero
    Contributor

    I'd like to work on this.

    I read the reload path on dev (2b5ea4977f) and the gap you measured has a mechanism, not a timing accident:

    • Plugin.list returns the stored inventory snapshot (packages/core/src/plugin.ts:51), which is only rebuilt at :132 when nothing changed and at :190 after the whole swap finishes.
    • The swap closes the old generation's scope first (:145 deletes the slot, :149 closes its scope), so its tool registrations are gone the moment that runs.
    • Between those two points the inventory still describes the previous generation — your fixture reads "active" from a list that was built before the close, while ctx.tool.list() reads a registry the close has already emptied. Both readings are correct about their own source; nothing makes them agree.

    awaitActivation (packages/core/src/plugin/service.ts:42) gates model requests, which is why your second measurement saw the held requests arrive with the complete tool list — the requests wait for the swap, the two list readers do not.

    Two directions I can see, and I would rather take the one you prefer:

    1. Keep the previous generation's registrations alive until the replacement finishes registering, and close the old scope after the new one is published — the tool list never dips.
    2. Leave the ordering alone and make the two readers agree by construction: either the inventory stops reporting a plugin as active while its registrations are closed, or ctx.tool.list() observes the same latch the requests do.

    (1) is the stronger guarantee and touches only the swap ordering in plugin.ts; (2) is smaller but makes one of the two views wait, which changes what a reader can observe rather than removing the inconsistency.

    I cannot measure your 301–366 ms window here — I have no 2.3.0 build and no multi-location server — so a test I add will assert the invariant ("no sample where a plugin reads as active while its tool is missing") over a reload rather than reproduce your timings. Tell me if you would rather have this as a written analysis on the issue only, with no patch.

  4. argszero commented on Nov 18, 2026

    @argszero
    Contributor

    Follow-up on the direction question from my claim, with measurements rather than a proposal.

    I first tried moving the outgoing generation's Scope.close to after the new inventory is published, so both views would flip together. That breaks two existing tests — restarts the suffix after an insertion and restarts the suffix after a revision changes both assert stop:c → stop:b → start:b → start:c, i.e. the outgoing generation must be fully stopped before the replacement starts. That contract looks deliberate (a plugin may hold a port or a file lock), so I dropped that approach rather than adjusting the tests.

    What I did instead: Plugin.list was the only view returning a cached snapshot (inventory, captured at the last publish) while the others read live state. It now reads the live snapshot at call time like the rest.

    Measured inside the reload window, sampling both views from the replacement's own setup — after the outgoing scope closed, before the replacement registers:

    • before: plugin.list() reports the plugin active, tool.list() no longer holds its tool — true:false, the symptom in the report
    • after: false:false, and once the reload completes both views agree again (alpha-plugin / alpha)

    bun test test/plugin.test.ts → 22 pass, 2 fail; the two failures fail with the same names on a clean upstream/dev worktree here, so they are pre-existing and not from this change. tsc reports the three errors already on dev and adds none; oxlint is clean on both files.

    The change is 6 lines in packages/core/src/plugin.ts plus one test. It is pushed to my fork as plugin-reload-tool-gap; I am at the 3-open-PR limit, so the pull request goes up as soon as a slot frees.

  5. iceteaSA commented on Nov 26, 2026

    @iceteaSA
    Author

    Thanks for the analysis and the patch, and sorry for the late answer. A patch is welcome. The invariant test you describe (over a reload, no sample in which a plugin reads as active while its tool is missing) is the right check: the window we measured depends on load and on the number of locations, so a timing assertion would be fragile.

    When the pull request is up, we will run it against our reload case on a multi-location server and report the result here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/pluginsplatform/linuxreproducedtype/bugversion/v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions