Skip to content

Pi provider: stale model catalog after models.json change; plugin reload never retires superseded bridge workers #2289

Closed

Description

@dhiyaancnirmal

Summary

The Pi provider's bridge worker loads ~/.pi/agent/models.json once at process boot. The bridge process identity does not include the contents of that file, so editing it is invisible to both stale-bridge retirement paths. bb plugin reload provider-pi reports success but only reloads server-side plugin registration; the host daemon keeps serving model/list from the old worker. The catalog stays stale until the tracked worker dies by hand, and superseded workers are leaked as duplicates.

Verified live against bb 0.39.0 (macOS, packaged app; embedded Pi 0.84.0 vs standalone pi 0.84.2).

Reproduction

  1. Start bb with the Pi provider running.
  2. Add a new model to ~/.pi/agent/models.json (e.g. a custom provider entry). Standalone pi resolves it immediately; bb's embedded runtime would too on a fresh boot.
  3. bb provider models pi still omits it.
  4. bb plugin reload provider-pi prints success. No worker restart happens.
  5. Repeated reloads leak duplicate bb-provider-bridge-worker.mjs … bb-pi-bridge.mjs provider-pi … processes.
  6. SIGTERM to the tracked worker → the next model/list spawns a fresh worker, which re-reads models.json, and the picker updates. Any other surviving superseded worker keeps running idle until manually killed.

I verified steps 3–6 live today with a probe model: probe invisible while two workers were alive; after killing one, the query respawned a fresh worker and the probe appeared, with the older superseded worker still leaking.

Root cause

In the host-daemon bundle:

  • A bridge worker's processKey is <base>#<hash> where the hash covers only the bridge launch source digest (for bundled Pi: bundled:<id>) plus a hash of the declared capabilities (yB(bridgeLaunch)).
  • retireStaleBridgeProcesses (runs on each provider spawn) retires same-base/same-suffix workers only when their hash differs from the newly current one.
  • retireSupersededBridgeProcessIfIdle likewise compares hashes only.

Since models.json is external to the launch config, its contents can never change the hash, so neither path ever has a reason to retire the pre-edit worker. Plugin reload does not reach into host-daemon bridge lifecycle at all.

Suggested fix directions

  • Include a digest of the provider's external config inputs (for Pi, ~/.pi/agent/models.json) in the bridge processKey hash, so an edit makes the next spawn retire the old idle worker naturally; or
  • Give plugin reload a way to ask the host daemon to retire idle same-hash bridge workers for that provider id; or
  • Have the Pi bridge re-read models.json per model/list instead of caching at boot.

Any of these should keep the existing safety property: retirement only when identity.threadIds.size === 0.

Regression test

A test where models.json gains a custom model entry after provider startup: assert provider models pi picks it up after a supported refresh path (config edit + reload or watcher), and that exactly one bridge worker remains afterwards.

Activity

  1. added
    host
    providers
    provider-pi
    on Aug 23, 2026
  2. added theissue type on Aug 23, 2026
  3. SawyerHood commented on Aug 24, 2026

    @SawyerHood
    Collaborator

    ---Auto-Generated---

    Reproduction & root-cause report: https://get-bb.github.io/reports/issues/2289.html

    • Verdict: REPRODUCED · root-cause confidence: high
    • Root cause (short): pi's RPC get_available_models returns a boot-time snapshot (models.json is only re-read in ModelRuntime.refresh(), which bb never triggers), the pi bridge memoizes one long-lived pi --mode rpc --no-session catalog child per cwd, the daemon keeps that bridge worker across plugin reloads because its process key (artifact digest + declaration fingerprint) never changes, and the server additionally memoizes provider.list_models for 10 minutes keyed by registration revision.
    • Proposed fix: In plugins/provider-pi/src/bridge/catalog.ts, fingerprint pi's models.json (resolve the agent dir as pi does: PI_CODING_AGENT_DIR else ~/.pi/agent; hash content or mtimeMs+size) when the catalog child is spawned, compare on every fetchRaw()/probe(), and on change kill the child so spawnChild() respawns it (it already handles child.exited); this fixes the data staleness at the plugin layer without touching the daemon process key. Separately, shorten or fingerprint-key the server's 10-minute providerModelList memo (apps/server/src/lifecycle-dedupers.ts) or document bb plugin reload provider-pi…
    • Caveats: The "repeated reloads leak duplicate bridge workers" claim does not reproduce at 494f665: three reloads left exactly one provider-pi worker under the dev daemon; extra workers are per-environment thread runtime processes (by design) or other dev daemons on this machine. The reporter's 0.39.0 build predates the 60 s provider-maintenance-runtime idle shutdown (d749741/Move provider state into provider bridge contract #1879) and the server memo …

    The report is self-contained: copy-paste repro steps with the test or script inline, expected vs actual output, screenshots where the bug is visual, and code permalinks at the base commit. It was independently re-executed by a second agent (see its Verification section).

    AGENT GENERATED: by Claude Code

  4. added
    confirmed-repro
    on Aug 24, 2026
  5. dandaka commented on Oct 2, 2026

    @dandaka
    Contributor

    Additional evidence for the stale-catalog part of this issue, plus a smaller fix for the bridge layer. Verified against main at 1b973d5584e10963018f4ae7d9c001e8ec09b99b.

    Environment: bb 0.44.0 (npx bb-app), macOS 15.6, Node 26.3.0, Pi 1.0.0 (npm install -g @earendil-works/pi-coding-agent), one connected persistent host. I also ran the bridge repro against Pi 0.84.0 (the pinned devDependency and PI_MINIMUM_SUPPORTED_VERSION).

    Observation 1: a live catalog child also misses credential changes

    This repro runs at the bridge layer with the real pi binary and an isolated PI_CODING_AGENT_DIR. No bb server is involved. Save the file below as plugins/provider-pi/src/bridge/real-pi.repro.test.ts, then run:

    pnpm exec turbo run test --filter=bb-plugin-provider-pi -- src/bridge/real-pi.repro.test.ts
    real-pi.repro.test.ts
    import { execFileSync } from "node:child_process";
    import { mkdtempSync, writeFileSync } from "node:fs";
    import { tmpdir } from "node:os";
    import { join } from "node:path";
    import { afterAll, expect, it } from "vitest";
    import { BB_PI_EXTENSION_SOURCE } from "./bb-pi-extension.js";
    import { closeAllPiCatalogs, getPiCatalog } from "./catalog.js";
    
    afterAll(() => closeAllPiCatalogs());
    
    const probeModels = (ids: string[]): string =>
      JSON.stringify({
        providers: {
          probe: {
            baseUrl: "http://127.0.0.1:9/v1",
            api: "openai-completions",
            apiKey: "x",
            models: ids.map((id) => ({ id })),
          },
        },
      });
    
    const piChildren = (): string[] =>
      execFileSync("ps", ["-axo", "pid=,ppid=,comm="])
        .toString()
        .split("\n")
        .map((line) => line.trim().split(/\s+/))
        .filter(([, ppid, comm]) => ppid === String(process.pid) && comm === "pi")
        .map(([pid]) => pid ?? "");
    
    it("a live Pi catalog child sees models.json and auth.json edits", async () => {
      const agentDir = mkdtempSync(join(tmpdir(), "pi-agent-"));
      const cwd = mkdtempSync(join(tmpdir(), "pi-cwd-"));
      const extensionPath = join(cwd, "bb-pi-extension.mjs");
      writeFileSync(extensionPath, BB_PI_EXTENSION_SOURCE);
      writeFileSync(join(agentDir, "models.json"), probeModels(["alpha"]));
      process.env.PI_CODING_AGENT_DIR = agentDir;
      const catalog = await getPiCatalog(cwd, extensionPath);
      const read = async (prefix: string): Promise<string[]> =>
        (await catalog.rawModels())
          .map((model) => `${model.provider}/${model.id}`)
          .filter((id) => id.startsWith(prefix))
          .sort();
    
      expect(await read("probe/")).toEqual(["probe/alpha"]);
      const children = piChildren();
      expect(children).toHaveLength(1);
    
      writeFileSync(join(agentDir, "models.json"), probeModels(["alpha", "beta"]));
      expect(await read("probe/")).toEqual(["probe/alpha", "probe/beta"]);
    
      writeFileSync(
        join(agentDir, "auth.json"),
        JSON.stringify({ deepseek: { type: "api_key", key: "sk-not-a-real-key" } }),
      );
      expect(await read("deepseek/")).not.toEqual([]);
    
      expect(piChildren()).toEqual(children);
    }, 120_000);

    Actual output on 1b973d5 with Pi 1.0.0:

    AssertionError: expected [ 'probe/alpha' ] to deeply equal [ 'probe/alpha', 'probe/beta' ]
    

    I also ran a variant that logs each read instead of asserting. All three reads returned ['probe/alpha'] from the same pi PID, so no deepseek/* model appeared after a DeepSeek key was written to auth.json either. Pi 0.84.0 behaves the same way in the asserting version.

    The cause is on Pi's side of the RPC. case "get_available_models" in dist/modes/rpc/rpc-mode.js returns session.modelRuntime.getAvailableSnapshot() in both 0.84.0 and 1.0.0, and the RPC command list has no refresh verb. The child stays alive for up to BB_PI_CATALOG_IDLE_MS (5 minutes) after its last fetch, and fetchRawFrom() asks it for that snapshot each time.

    Observation 2: the host row and the workspace row disagreed

    I captured this earlier today on the same machine. DeepSeek had been configured in Pi through auth.json only, with no models.json change.

    sqlite3 -readonly ~/.bb/bb.db "select scope_key, json_array_length(models_json), datetime(fetched_at/1000,'unixepoch','localtime') from provider_model_catalogs where provider_id='pi';"
    scope_key models composition fetched (local)
    '' (host) 73 44 openai + 29 opencode-go, 0 deepseek 10:33:44
    <workspace> 46 44 openai + 2 deepseek 10:39:09

    Pi recorded its DeepSeek check at 10:35:08 (checkedAt in models-store.json), after the host row was written. A read without an environment at 10:47 served the stale 73-model host row. Twelve seconds later the row held the 46-model list, which is the serve-stale-then-revalidate path in evaluate(). After that, Pi and bb agreed exactly (46 IDs each):

    pi --list-models | awk 'NR>1{print $1"/"$2}' | sort > /tmp/pi-models.txt
    bb provider models pi --environment <env> --json | jq -r '.[].id' | sort > /tmp/bb-models.txt
    comm -3 /tmp/pi-models.txt /tmp/bb-models.txt   # empty

    My reading of this: by 10:47 the host-scope child had been idle longer than 5 minutes and was respawned, so this case was not caused by a live child. It came from the server memo (FRESH_MS, and catalogFingerprint has no Pi config input), and from the host and workspace scopes keeping separate rows with separate TTLs.

    Proposed fix for the bridge layer

    Pi already exposes a reload to extensions. ExtensionContext.modelRegistry.refresh(options?) ("Reload models.json asynchronously") exists in both 0.84.0 and 1.0.0. In 1.0.0, refresh({ allowNetwork: false }) reloads models.json, rebuilds providers, and reruns the availability pass, which re-reads auth.json (AuthStorage.list → readLatestData). Pi calls it itself after provider registration changes. The bb extension already answers bridge-channel requests (fork, leaf, model-scope in runBridgeRequest). So a refresh-models request handled there, and sent before get_available_models, keeps the child alive and current.

    This also covers the credential case, which fingerprinting models.json (the report's proposal) would miss.

    Proposed split:

    1. Bridge (this layer). Add a refresh-models channel request. If the refresh is unsupported, rejects, or times out, replace the child as a fallback. Tests use the existing fake-Pi harness. I have this ready on a branch. With it, the repro above passes against real Pi 1.0.0 and 0.84.0 with a single PID across all three reads, at 2–4 ms per read, and the package suite passes (170 tests). I'll open the PR once I'm approved as a contributor.
    2. Server memo. read() serves stale data and revalidates in the background; only access.kind === "validation" waits. The design question: an explicit picker refresh (for example ?refresh=1 with a bounded wait that falls back to stale), or a shorter or revision-keyed memo? Blocking on every picker open would cost seconds when the child is cold.
    3. Scope split. The host row and the workspace row can disagree (Observation 2). This is probably its own issue.

    Ruled out

    • Duplicate bridge workers. I agree with the report that this does not reproduce, and I saw nothing that contradicts it.
    • Pi credentials. pi --list-models lists deepseek/deepseek-flash and deepseek/deepseek-v4-pro, and the bb workspace row matched Pi exactly.
    • A server-only cause. Observation 1 reproduces with no bb server at all, so the bridge child is a cause by itself.

    Separately, Pi has no RPC command for refreshing models. A refresh_models RPC command would spare every RPC client this extension hop. That belongs in the Pi repository, not here.

    AGENT GENERATED

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

    confirmed-reprohostperfprovider-piproviders

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions