ChatGPTClaudeGrok / X / CursorGemini

DSH plugin cleanup: what dispose removes and in what order

Plugin DevelopmentPublished 2026-11-05Author: DeepSeek Plugin Market
DSH plugincleanupctx.effectdisposehot reload
Doubled timers and lingering listeners after hot reload mean cleanup ownership or ordering is wrong. A post-mortem of one reload bug, plus a five-step check.

The first run is perfect. Change the code, save, and hot reload starts printing two heartbeats; change it again and there are three. Restart the process and everything is fine. Problems that only appear after a reload almost always come down to cleanup.

Here is one such case, in the order it was actually diagnosed: symptom, ownership, ordering, and a check you can repeat.

A DSH plugin symptom that appears only after reload

A DSH plugin resource that doubles only after reload is almost always one that never went through ctx. The setup was ordinary. The plugin started a background poll to fetch remote state and registered a tool so the model could trigger a refresh manually.

The first start looked right. After changing the poll interval and saving, HMR applied and the refresh log appeared at twice the rate. One more change, three times. dsh --version was unchanged, the code was unchanged; the only variable was how many times this process had been reloaded.

Two hypotheses fit: the old instance never unloaded, or it unloaded without releasing its resources.

Confirm whether the plugin entered the unload path before editing code. Two observations:

  1. After the reload, did the old tool disappear from the list? If yes, the ctx.tools.register part was revoked correctly;
  2. Does the log show two plugin loaded lines without matching cleanup output? Loading without cleanup points at resources not owned by ctx.

If the tool is still there and a new one appeared too, unload never happened — a different investigation about profiles and whether HMR actually recomposed the config.

This case was the first kind: one tool, doubled polling. Unload happened; setInterval was never collected.

What DSH plugin automatic cleanup covers

The framework tracks registrations made through ctx, not everything the plugin creates. The documented set falls into four groups:

RegistrationTypical useOn unload
ctx.on(event, handler)Listen to framework or plugin eventsRemoved
ctx.tools.register(tool)Expose a tool to the modelRevoked
ctx.llm.registerAdapter(names, adapter)Add a model providerRevoked
ctx.effect(() => cleanup)Custom resourcesDisposer called

Treat this as a whitelist, not a safety net. Anything not created through these four is outside automatic cleanup.

Three things that survive a DSH plugin unload

Only three kinds of DSH plugin resources survive unload: bare timers, references inside libraries, and module-level state. Check against these three and most "stuff left behind" reports resolve:

First, native timers and polling. setInterval, setTimeout, and requestAnimationFrame are bare resources with no ctx involvement.

Second, references held inside third-party libraries. A client SDK may register internal listeners from your callback; it does not know to unregister them on unload, so calling its close() inside ctx.effect is what closes the loop.

Third, module-level or global state. Connection pools created at module top level, caches attached to globalThis, singleton arrays in an outer closure — all of these outlive the instance.

A useful test: who owns this resource? If ctx owns it, the framework handles it. If you own it, write it into ctx.effect. If a library owns it, call that library's shutdown method.

DSH plugin reverse order is not serial order: one effect for ordered cleanup

DSH plugin disposers run in reverse order but concurrently, so ordered cleanup needs one ctx.effect. Ownership fixes the first problem; ordering is the second.

The documented semantics are that disposers run in reverse registration order, but multiple async disposers run concurrently, with no guarantee of one finishing before the next starts. That means:

  1. Register A then B; unload calls B before A;
  2. If B's disposer is async and unfinished, A's disposer may already be running;
  3. Cleanup that requires "B closed, then A stops" cannot rely on two separate effects.

Ask whether two cleanups running at the same time would interfere. If yes, they cannot be separate effects. The reliable shape is a single ctx.effect that owns the whole chain and awaits it:

ts
export function apply(ctx: Context) {
  ctx.effect(() => {
    const timer = setInterval(poll, 5000)
    const socket = connect()

    return async () => {
      clearInterval(timer)     // stop the producer first
      await socket.drain()     // wait for the queue to empty
      await socket.close()     // close the connection last
    }
  })
}

Inside that disposer the order is serial, because it is one async function. The framework calls it on unload and waits for it to resolve; the ordering within is yours.

Split those three calls into three effects and the framework calls all three concurrently — close may run before drain finishes.

A five-step DSH plugin cleanup check

Verify DSH plugin cleanup by comparing a resource signature after five reloads, not by checking for errors. After changing the code, do not stop at "no errors". Verify with observable results:

  1. Start once and note a resource signature, such as polling frequency or listener count;
  2. Trigger five hot reloads in a row and confirm the signature does not change;
  3. Unload the plugin (remove the patch row and restart) and confirm the signature disappears;
  4. Inspect handles with lsof -i :3080 and lsof -p <pid>; no unexpected entries;
  5. Reinstall and confirm the feature returns without "address already in use" errors.

Step 2 is the core. It verifies idempotence: however many times the plugin loads, there is exactly one copy of each resource.

Make cleanup part of the DSH plugin interface

A DSH plugin that leaks resources across reloads breaks its contract with every dependent. One last design point. Cleanup is not an afterthought; it is part of a plugin's external contract, alongside inject and Config. Anyone depending on your plugin assumes it unloads cleanly.

Before creating any resource, answer three questions: who owns it, who closes it on unload, and whether a failed close blocks other cleanup. Once those are clear, write apply.

For how ctx registrations relate to effects, read Cordis primer; for locating where a plugin stopped, read local debugging; for where this fits in the error list, read common plugin errors.

ChatGPTClaudeGrok / X / CursorGemini

FAQ

After hot reload, my DSH plugin timer fires twice as often. Did unload fail?

Usually a DSH plugin timer was never tracked by ctx. Unload did happen, but setInterval sits outside that scope, so the old instance keeps firing. Create and dispose it inside ctx.effect, returning a function that clears the interval.

Do DSH plugin ctx.effect disposers always run one after another in reverse order?

The DSH plugin order is reversed, but async disposers run concurrently, with no guarantee that one finishes before the next starts. Cleanup steps with ordering requirements must live in one ctx.effect disposer that awaits them in sequence.

Are listeners registered inside a third-party library removed automatically on DSH plugin unload?

No, it does not: DSH plugin automatic revocation covers only registrations made through ctx, such as ctx.on, ctx.tools.register, ctx.llm.registerAdapter, and ctx.effect. Callbacks stored inside libraries and global singletons need explicit teardown in your disposer.

Do resources inside a child plugin get cleaned up when the parent unloads?

It does when the child plugin was mounted through the parent ctx with ctx.plugin. DSH plugin parent dispose recursively unloads children and their registrations follow; a child attached to a separately created context is not on that chain.

Related Terms

unload
Unload is the process of ending a plugin instance, moving it to UNLOADING, releasing its registrations, and finishing in DISPOSED.— DeepSeek Harness docs
tracked registration
A tracked registration is one made through ctx and recorded in the plugin's scope, then revoked automatically on unload.— DeepSeek Harness docs
disposer
A disposer is a cleanup function returned by a ctx.effect callback and invoked when the plugin unloads.— DeepSeek Harness docs
reverse cleanup
Reverse cleanup is the DSH plugin behavior of calling disposers in the opposite order of registration, so later registrations are undone before earlier ones.— DeepSeek Harness docs

Sources