Skip to content

fix(plugins): don't retire a registry mid-schedule just because a different one became active - #233

Merged
convyusboy merged 13 commits into
boonfrom
ridho/plugin-registry-retirement-race-fix
Sep 22, 2026
Merged

convyusboy merged 13 commits into
boonfrom
ridho/plugin-registry-retirement-race-fix

Conversation

@convyusboy

@convyusboy convyusboy commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Live-diagnosed via a real gateway's own logs (not a guess): a plugin's scheduleSessionTurn call was silently rolled back on its very first attempt in a conversation, every single time, with zero warning anywhere in the logs. browser_handoff's own recently-added scheduling warnings (a separate change) were the only line that ever fired — the core scheduler itself stayed completely silent.

Reproduced and localized precisely: schedulePluginSessionTurn (src/plugins/host-hook-scheduled-turns.ts) re-checks shouldCommit (in production, isLoadedRecordInActiveRegistry in registry.ts) after the async cron.add() call resolves, specifically to catch a plugin that genuinely got unloaded mid-flight. That rollback path is deliberate and already covered by an existing test ("removes a stale cron job when the plugin unloads after cron.add") — it is correct and untouched by this PR.

The actual bug is the signal feeding that check: isPluginRegistryActivated/isPluginRegistryRetired are per-registry flags, but setActivePluginRegistry unconditionally retires whatever registry was previously active the instant any different registry takes over the single global active pointer — including a completely unrelated, concurrently-running standalone (cron-triggered or isolated-agent) load on a busy multi-tenant gateway process. The calling turn's own plugin was never unloaded; its registry just stopped being the global "active" one for a moment, for a reason that has nothing to do with it, and by the time the post-cron.add() check ran, that transient dip had already been recorded as permanent retirement.

Why This Change Was Made

Added beginPendingRegistryOperation/hasPendingRegistryOperation (registry-lifecycle.ts), mirroring the existing pin mechanism the channel/http-route surfaces already use, so a registry is treated as still "live" while it has an in-flight async scheduling operation — surviving a purely transient, unrelated active-pointer swap during that exact window. schedulePluginSessionTurn now holds this pin for the duration of cron.add() and the shouldCommit re-check, and releases it via retirePluginRegistryIfNowUnused right after — the same re-check-on-release pattern every existing pin-release function (releasePinnedPluginChannelRegistry, etc.) already follows, so a registry that's genuinely done for is still retired and cleaned up promptly, not leaked.

User Impact

Any bundled plugin's scheduleSessionTurn call (durable cron-scheduled follow-up turns) on a busy gateway process serving multiple concurrent registries no longer silently fails to schedule just because unrelated concurrent activity happened to swap the global active-registry pointer during the async gap. For browser_handoff specifically: automatic resume after a customer signs in should now actually fire on the first attempt instead of requiring a manual nudge.

Evidence

  • Live production log evidence: the exact silent-failure timing and absence of any core-scheduler warning, isolating the fault to this one un-covered branch.
  • New regression test in scheduled-turns.contract.test.ts proves both directions:
    • The existing "removes a stale cron job when the plugin unloads after cron.add" test still passes unmodified — genuine unload still rolls back correctly.
    • A new test confirms a job survives when an unrelated registry becomes active mid-flight — confirmed to fail without the fix by temporarily reverting just the fix files and re-running the same test (got the expected undefined handle), then restoring the fix and confirming it passes.
  • node scripts/run-vitest.mjs src/plugins/runtime.test.ts src/plugins/contracts/scheduled-turns.contract.test.ts src/plugins/host-hook-scheduled-turns-diagnostics.test.ts — 27 + 27 examples (1 new), 0 failures.
  • pnpm tsgo:core — clean.
  • pnpm check:import-cycles — 0 runtime value cycles.
  • oxlint + oxfmt --check on all changed files — clean.

🤖 Generated with Claude Code


Summary by cubic

Fixes a race where a plugin's scheduleSessionTurn call was silently rolled back on its first attempt whenever an unrelated registry briefly became the global active pointer while cron.add() was in flight.

  • Tracks in-flight async scheduling per registry (beginPendingRegistryOperation/hasPendingRegistryOperation) so a transient, unrelated active-pointer swap doesn't retire a still-loaded registry mid-schedule.
  • Retirement is re-checked in finally on every path; successful commits preserve the job by passing it through a per-registry, per-pluginId accumulator, so the cleanup pass keeps it.
  • isPluginRegistrySuperseded detects genuine same-context reloads by comparing recorded cache keys directly, surviving interposed unrelated swaps and later pointer changes; explicit retirement clears the latest-by-cache-key index to avoid unbounded growth.
  • Restores automatic resume in browser_handoff after sign-in on busy multi-tenant gateways.
  • Adds regression tests for job survival across unrelated swaps, same-context reload rollback (direct, interposed, later-swap), overlapping calls preserving both jobs, plugin-scoped job id preservation, and sweeping stale jobs from closed pending windows.

Written for commit 8cc32c4. Summary will update on new commits.

Review in cubic

…ferent one became active

Live-diagnosed via a real gateway's own logs: a plugin's scheduleSessionTurn
call was silently rolled back on its very first attempt in a conversation,
every time, with zero warning anywhere -- browser_handoff's own scheduling
warnings (added separately) were the only line that ever fired.

Root cause: schedulePluginSessionTurn re-checks shouldCommit (in production,
isLoadedRecordInActiveRegistry) after the async cron.add() call resolves,
to catch a plugin that genuinely unloaded mid-flight -- that rollback path
is deliberate and already covered by an existing test. The bug is the
SIGNAL feeding it: isPluginRegistryActivated/isPluginRegistryRetired are
per-registry flags, but setActivePluginRegistry unconditionally retires
whatever registry was PREVIOUSLY active the instant ANY different registry
takes over the single global active pointer -- including a completely
unrelated, concurrently-running standalone (cron-triggered or
isolated-agent) load on a busy multi-tenant gateway process. The calling
turn's own plugin was never unloaded; its registry just stopped being the
global "active" one for a moment, for a reason that has nothing to do with
it, and by the time the post-cron.add() check ran, that transient dip had
already been recorded as permanent retirement.

Fix: track in-flight async scheduling operations per-registry
(beginPendingRegistryOperation, mirroring the existing pin mechanism
channel/http-route surfaces already use) and treat a registry as still
"live" while one is pending -- so a same-generation registry survives a
purely transient, unrelated active-pointer swap during that window. When
the operation ends, retirePluginRegistryIfNowUnused re-checks retirement
immediately (same pattern every existing pin-release function already
follows), so a registry that's genuinely done for is still retired and
cleaned up promptly, not leaked.

New regression test proves both directions: the existing "removes a stale
cron job when the plugin unloads after cron.add" test still passes
unmodified (genuine unload still rolls back correctly), and a new test
confirms a job survives when an unrelated registry becomes active mid-flight
(confirmed to fail without the fix, by temporarily reverting it and
re-running the same test).

Tests: 27/27 in scheduled-turns.contract.test.ts (1 new), 27/27 across
runtime.test.ts + host-hook-scheduled-turns-diagnostics.test.ts. tsgo:core
and check:import-cycles both clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@convyusboy
convyusboy requested a review from a team September 21, 2026 10:23
@claude

claude Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Claude encountered an error —— View job


I'll analyze this and get back to you.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 4 files

Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.

Fix all with cubic | Re-trigger cubic

Comment thread src/plugins/runtime.ts Resolved
… on failure (PR review)

P1 (confirmed valid, and my own regression test's original pass was a
false negative): the finally block called retirePluginRegistryIfNowUnused
unconditionally, including on the SUCCESS path right after the job was
registered. cleanupReplacedPluginHostRegistry's "disable" branch
unconditionally sweeps the global scheduler-jobs map for the retiring
registry's own pluginId, with no preserve exception for a job that was
just committed a moment earlier -- so this immediately cancelled the exact
job schedulePluginSessionTurn had just successfully created.

My first regression test used createEmptyPluginRegistry() for
ownerRegistry, which has zero loaded plugins -- previousPluginIds ends up
empty, so cleanupReplacedPluginHostRegistry's whole per-plugin loop never
iterates, and the test passed even with the bug present. Rewrote it with a
real loaded plugin record (matching the sibling "preserves
replacement-generation runtime scheduled turns" test's own construction),
which correctly reproduces the bug when reverted and confirms the fix.

Fix: only call retirePluginRegistryIfNowUnused on the three failure
return paths (cron.add threw, no job id, shouldCommit rolled back), never
on success. A registry that's genuinely retirable after a success path is
picked up by whatever future event naturally re-checks it, same as any
other registry that stops being live between checks -- the alternative
(destroying the job we just created) is strictly worse.

Also fixes P3 (test comment overclaiming exact parity with the real
isLoadedRecordInActiveRegistry check -- now states plainly which condition
it deliberately omits and why).

Tests: 27/27 in scheduled-turns.contract.test.ts, 27/27 across
runtime.test.ts + host-hook-scheduled-turns-diagnostics.test.ts. Confirmed
the new/strengthened test fails for the right reason when the fix is
temporarily reverted (cronRemove called with "job-survives"), and passes
once restored. tsgo:core, check:import-cycles, oxlint, oxfmt all clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

…t reload (PR review)

P2 (confirmed valid): hasPendingRegistryOperation kept a registry live
unconditionally while its cron.add()/shouldCommit re-check was in flight --
correct for the unrelated-tenant-swap race #1 targets, but it also
suppressed retirement when the OWNER's own standalone context genuinely
reloaded into a fresh registry generation (config change, real disable)
during that exact window. shouldCommit would then read the stale registry
as still active/not-retired and commit a job for a context that had
already moved on, with no guaranteed later cleanup.

Fix: record the cache key each registry was activated under
(recordPluginRegistryCacheKey/getPluginRegistryCacheKey in
registry-lifecycle.ts, written from setActivePluginRegistry). isRegistryLive
now only lets the pending-operation pin protect a registry when the
replacement that took over the active pointer has a DIFFERENT cache key (or
neither has one, e.g. non-cache-keyed gateway-bindable registries, which
keep the prior conservative behavior). A same-cache-key replacement is by
definition the same context reloading, not an unrelated swap, so retirement
is allowed to proceed immediately and the shouldCommit re-check correctly
rolls the job back.

Tests: new regression test proves a same-cache-key reload during cron.add()
still rolls back (confirmed it fails for the right reason -- job survives
when it shouldn't -- with the isRegistryLive refinement temporarily
reverted, and passes restored). The existing unrelated-registry-swap test
stays unaffected: 28/28 in scheduled-turns.contract.test.ts, 27/27 across
runtime.test.ts + host-hook-scheduled-turns-diagnostics.test.ts. tsgo:core,
check:import-cycles, oxlint, oxfmt all clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 3 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Fix all with cubic | Re-trigger cubic

Comment thread src/plugins/registry-lifecycle.ts Resolved
convyusboy and others added 2 commits September 21, 2026 18:57
… path (PR review)

New P2 (confirmed valid, confidence 10): retireOwnerIfNowUnused() was
called from each of the 3 failure returns while
beginPendingRegistryOperation's pin was still held (only released in the
outer finally), so hasPendingRegistryOperation(ownerRegistry) still read
true and retirePluginRegistryIfUnused's isRegistryLive check no-opped --
a genuinely stale registry never actually got retired on a failure path
either, silently falling back to whatever unrelated future event happens
to re-check it.

Fix: retireOwnerIfNowUnused now calls endPendingRegistryOperation() first,
then re-checks retirement. The outer finally's own call becomes a no-op
safety net for the success path (idempotent release, already guarded by
beginPendingRegistryOperation's own released flag).

Also addresses new P3 (confidence 10): shortened the comment above it that
narrated this PR's own history instead of stating the invariant plainly.

Evaluated a third new finding (confidence 7, the 50ms wait in the existing
unrelated-registry-swap test) and determined it's incorrect: reintroduced
the on-success retirement bug this PR's first fix removed, ran that same
test with the wait deleted, and it still passed -- a false negative --
confirming the wait is load-bearing (cleanupRetiredPluginHostRegistry's
retirement cleanup is a fire-and-forget promise chain through two dynamic
imports, not something the caller awaits). The suggested vi.waitFor
replacement wouldn't help either: it stops retrying as soon as its
callback doesn't throw, and a not.toHaveBeenCalled() assertion never
throws on the very first check, so it would resolve immediately without
ever actually waiting. Replied on the thread with this evidence; left
unresolved for a second opinion given the lower confidence.

Tests: 28/28 in scheduled-turns.contract.test.ts, 27/27 across
runtime.test.ts + host-hook-scheduled-turns-diagnostics.test.ts. tsgo:core,
check:import-cycles, oxlint, oxfmt all clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…eview)

New P3 (confirmed valid, confidence 9): the cache-key tracking comment on
recordPluginRegistryCacheKey spanned nine lines narrating activation-path
details instead of stating the invariant plainly. Condensed to two lines.

Tests: 28/28 in scheduled-turns.contract.test.ts, 27/27 across
runtime.test.ts + host-hook-scheduled-turns-diagnostics.test.ts. tsgo:core,
oxlint, oxfmt all clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@augusteo augusteo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hermes review

Verdict: Changes requested

Blocking

The pending-operation pin fixes the immediate rollback race, but the successful path releases the pin without re-evaluating retirement. If the owner is displaced by an unrelated registry during cron.add(), it is intentionally left unretired. If that unrelated registry is then replaced by a same-context registry, the original owner is no longer previousRegistry, so the cache-key refinement never retires it. A captured API from the original owner still passes the lifecycle predicate and can continue committing side effects, while its cleanup state is no longer tied to an active or pinned surface.

I reproduced this sequence locally against this exact head: owner registry, unrelated registry during cron.add(), then same-key owner replacement. The original owner remained isPluginRegistryRetired === false. Please preserve the newly committed job while still retiring or otherwise reaping the displaced owner, and add a regression test for the interposed-registry sequence.

Checks

  • Focused scheduled-turn contract tests: 28 passed.
  • Runtime and scheduled-turn diagnostics tests: 27 passed.
  • Standalone registry loader tests: 6 passed.
  • Runtime registry reuse test: 1 passed.
  • Core TypeScript check: passed.
  • Runtime import-cycle check: 0 cycles.
  • oxlint and oxfmt on all changed files: passed.
  • Exact-head Actions runs: successful for the named workflows; required-check completeness is unverified because the branch-protection endpoint is forbidden for this token.

…erving the just-committed job (PR review)

Blocking review finding (confirmed valid): the finally block only released
the pending-op pin. On a successful commit, the owner registry was never
explicitly retired, so if an unrelated registry had already displaced it as
the active pointer, it would never become previousRegistry for any future
setActivePluginRegistry call again -- retirement is only ever triggered as
a side effect of that specific transition. A registry left un-retired after
success wasn't just delayed, it was leaked forever, along with any other
real cleanup work it still owned (session extensions, runtime lifecycles,
other scheduler jobs).

Fix: consolidated retirement into a single call in the finally block that
runs on every path (success or failure), after the pin releases. Threaded
an optional preserveSchedulerJobIds set through
retirePluginRegistryIfNowUnused -> cleanupRetiredPluginHostRegistry ->
cleanupPreviousPluginHostRegistry -> cleanupReplacedPluginHostRegistry ->
runPluginHostCleanup, so retirement's cleanup pass can be told to keep a
specific job even when it lands on the 'disable' branch that would
otherwise sweep it. schedulePluginSessionTurn now retires with the
just-committed job's id preserved on success, and with nothing preserved
on any failure path (removing the three now-redundant per-branch retire
calls this PR's earlier commits added).

Tests: new regression test proves the leak is fixed -- confirmed
isPluginRegistryRetired(ownerRegistry) is false without the finally-based
retire call (reverted it, test failed for the right reason) and true with
it restored. Also extended the test to cover the reviewer's exact requested
chain (owner -> unrelated -> later same-key reload of the unrelated
context), confirming ownerRegistry isn't stranded and the preserved job
still isn't touched. 29/29 in scheduled-turns.contract.test.ts, 27/27
across runtime.test.ts + host-hook-scheduled-turns-diagnostics.test.ts,
96/96 across the host-hook-cleanup and dependent contract test files whose
signatures changed. tsgo:core, check:import-cycles, oxlint, oxfmt all
clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 4 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Fix all with cubic | Re-trigger cubic

Comment thread src/plugins/runtime.ts Resolved
Comment thread src/plugins/host-hook-cleanup.ts Resolved
…ervation by plugin, make cleanup awaitable for tests (PR review)

Three new cubic findings on the previous commit, all confirmed valid:

P1 (confidence 9, runtime.ts): retirePluginRegistryIfNowUnused's preserve
set only ever contained the CURRENT call's own job. Two
schedulePluginSessionTurn calls sharing the same owner registry can
overlap (both hold the pending-op pin); only the LAST one to release its
pin is the one whose retirement check actually fires cleanup, but it only
knew about its own job -- an earlier call's already-returned, already-committed
job had no protection and got swept.

Fix: added a per-registry, per-pluginId accumulator
(recordPendingCommittedSchedulerJobId/getPendingCommittedSchedulerJobIds in
registry-lifecycle.ts) that every successful commit adds to, and
retirement now preserves the FULL accumulated set whenever it actually
fires, not just the triggering call's own job.

P2 (confidence 8, host-hook-cleanup.ts): the caller-supplied preserve set
was a flat, unscoped Set<string> applied identically to every pluginId in
cleanupReplacedPluginHostRegistry's loop -- if two different plugins ever
committed a job under the same job id string, preserving one would also
accidentally preserve the other's.

Fix: preserveSchedulerJobIds is now a ReadonlyMap<pluginId, Set<jobId>>
end to end; the loop looks up each pluginId's own preserved set instead of
applying one shared set to all of them.

P3 (confidence 6, scheduled-turns.contract.test.ts): the fixed 50ms
wall-clock waits used to observe the fire-and-forget retirement cleanup
could pass vacuously on a slow CI runner if that cleanup (two dynamic
imports deep) hadn't actually finished within the window.

Fix: retirePluginRegistryIfNowUnused now returns its cleanup promise
(never-rejecting, same as before) instead of void; production callers
still don't await it (identical fire-and-forget timing), but a new test
helper (withRetirementSettled) spies on it and awaits every real
invocation's returned promise, replacing both wall-clock waits with
deterministic synchronization.

Also added: a new regression test proving the P1 fix (two overlapping
calls, only the second call's retirement preserves both jobs -- confirmed
it fails for the right reason with a single-job preserve set restored),
and a new test proving the P2 fix (two plugins sharing a colliding job id
string, confirmed it fails for the right reason with an unscoped preserve
set restored).

Tests: 31/31 in scheduled-turns.contract.test.ts (2 new), 122+32 across
all dependent contract/cleanup test files whose signatures changed.
tsgo:core, check:import-cycles, oxlint, oxfmt all clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 5 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Fix all with cubic | Re-trigger cubic

Comment thread src/plugins/registry-lifecycle.ts Resolved
Comment thread src/plugins/runtime.ts Resolved
Comment thread src/plugins/host-hook-cleanup.ts Resolved
…ndow closes, trim two long comments (PR review)

P1 (confidence 9, confirmed valid): recordPendingCommittedSchedulerJobId's
per-registry accumulator was never cleared. A long-lived, frequently-
scheduling registry would keep every job id it ever committed forever, so
a LATER, unrelated retirement (for a totally separate pending window)
would keep preserving jobs from windows that had already closed --
unbounded growth, and stale jobs shielded from legitimate 'disable'
cleanup they should no longer be exempt from.

Fix: retirePluginRegistryIfNowUnused is now self-contained -- it reads
the accumulated set for its own preserve decision, then clears it
whenever hasPendingRegistryOperation is false (this was the last
overlapping call to release the pin, so the shared window has fully
closed). Simplified its signature to drop the now-internal
preserveSchedulerJobIds parameter; its one caller
(schedulePluginSessionTurn) no longer needs to read the accumulator
itself either.

P3 x2 (confidence 9 and 10): trimmed two comments that mixed the
invariant with PR-specific narrative/history, per the team's existing
concise-comment feedback -- one on cleanupRetiredPluginHostRegistry's
promise-return rationale, one on the per-pluginId preserve scoping in
cleanupReplacedPluginHostRegistry.

Tests: new regression test proves the accumulator-clearing fix -- an
older, separately-committed job from an already-closed window now
correctly gets swept by a LATER, unrelated retirement instead of staying
shielded forever (confirmed it fails for the right reason -- job-old
wrongly preserved -- with the clear call temporarily removed). 32/32 in
scheduled-turns.contract.test.ts (1 new), 123+32 across all dependent
contract/cleanup test files. tsgo:core, check:import-cycles, oxlint,
oxfmt all clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@augusteo augusteo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hermes re-review

Verdict: Changes requested

The follow-up commits improve cleanup preservation and add direct same-key reload coverage, but the current head still has a lifecycle race in an interposed replacement sequence.

Validation on this exact head:

  • Scheduled-turn contract/runtime/diagnostics suites: 32 + 27 passed
  • Adjacent registry-loader/runtime-reuse suites: 6 + 1 passed
  • tsgo:core, import-cycle check, oxlint, oxfmt, and build: passed
  • Exact-head Actions: relevant CI, CodeQL, OpenGrep, security, dependency, and workflow-sanity jobs successful or intentionally skipped

The blocker is described inline below. A disposable regression probe against this exact checkout reproduced it: owner -> unrelated registry -> same-cache-key replacement while cron.add() was pending returned a committed handle instead of rolling back the stale job.

Comment thread src/plugins/runtime.ts Resolved
…ated registry swap (PR review)

Blocking review finding (confirmed valid, reproduced with a dedicated
regression test): an unrelated registry swap can interpose between an
owner registry losing the active pointer and a fresh same-cache-key
generation taking it. setActivePluginRegistry only ever evaluates whoever
is the CURRENT previousRegistry at each specific swap -- once the owner
is displaced by the unrelated registry, it's never previousRegistry
again for the SECOND swap (the genuine same-key reload), so neither the
retiredRegistries flag nor isRegistryLive's own same-context check ever
fires for it. The production shouldCommit callback
(isLoadedRecordInActiveRegistry in registry.ts) only reads the raw
retired/activated flags, so it stayed true and committed a job for a
context that had already been superseded.

Fix: added isPluginRegistrySuperseded (runtime.ts), which compares a
registry's own recorded cache key directly against whatever the CURRENT
active registry's cache key is, independent of the previousRegistry
chain -- immune to however many registries interposed in between. Wired
it into both production callbacks in registry.ts
(isLoadedRecordInActiveRegistry, shouldCommitWorkflowSideEffect) in place
of the raw isPluginRegistryRetired flag, and into the same-class sibling
check in hook-runner-global-state.ts (composing the live hook registry
list) since it shared the identical blind spot.

Tests: new regression test reproduces the exact reported sequence (owner
pending schedule -> unrelated registry active -> same-cache-key reload
active, before cron.add() resolves) and confirms the job rolls back;
verified it fails for the right reason (job commits instead of rolling
back) with isPluginRegistrySuperseded temporarily reduced to the old
raw-flag check. Updated the file's other shouldCommit test closures to
call the real isPluginRegistrySuperseded instead of hand-reconstructing
the (now-changed) production check. 33/33 in
scheduled-turns.contract.test.ts (1 new), 124+32 across dependent
contract/cleanup files, 9/9 in hook-runner-global*.test.ts, 15+2 in
registry.*.test.ts. tsgo:core, check:import-cycles, oxlint, oxfmt all
clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 4 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Fix all with cubic | Re-trigger cubic

…ne parameterized case (PR review)

P3 (confidence 6, confirmed valid): the interposed-reload test duplicated
the preceding same-context-reload test almost verbatim (~85 lines);
only the extra unrelated-registry swap differed.

Fix: merged both into a single it.each covering both scenarios
(cache key, job id, and whether an unrelated registry interposes before
the reload), sharing one fixture/shouldCommit/assertion skeleton. Same
two cases, same coverage -- verified the interposed case still fails for
the right reason with isPluginRegistrySuperseded temporarily reduced to
the old raw-flag check, and the direct-reload case is unaffected.

Tests: 33/33 in scheduled-turns.contract.test.ts, 27/27 across
runtime.test.ts + host-hook-scheduled-turns-diagnostics.test.ts.
tsgo:core, check:import-cycles, oxlint, oxfmt all clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@augusteo augusteo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hermes re-review

Verdict: Approved

The prior blocking race is fixed. isPluginRegistrySuperseded now detects a same-cache-key replacement directly from current runtime state, including when an unrelated registry interposes before the replacement. Production shouldCommit and global hook dispatch use that generation-aware predicate, and the exact interposed-reload regression test is now present and passing.

Validation on this exact head:

  • Scheduled-turn contract suite: 33 passed
  • Runtime and scheduled-turn diagnostics suites: 27 passed
  • Adjacent registry-loader/runtime-reuse suites: 6 and 1 passed
  • tsgo:core, import-cycle check, oxlint, oxfmt, and build: passed
  • Exact-head Actions: CI 92 successful jobs and 8 skipped, CodeQL successful, OpenGrep successful, Security Sensitive Guard successful, Dependency Guard successful or skipped, and Workflow Sanity successful or skipped

Approval is for commit a9a769fe5f0bbb28e28880ee430b7ad932360b42. Merge and deployment are separate actions.

@augusteo augusteo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hermes re-review

Verdict: Approved

The prior lifecycle blocker remains fixed. The production code detects an interposed same-cache-key replacement through isPluginRegistrySuperseded, and the parameterized scheduled-turn regression test preserves coverage for both direct and interposed reloads.

Validation on this exact head:

  • Scheduled-turn contract suite: 33 passed
  • Runtime and scheduled-turn diagnostics suites: 27 passed
  • Adjacent registry-loader/runtime-reuse suites: 6 and 1 passed
  • tsgo:core, oxlint, and oxfmt: passed
  • Exact-head CI jobs: 92 successful, 8 skipped, 0 failed
  • Exact-head CodeQL, CodeQL Critical Quality, OpenGrep, Security Sensitive Guard, Dependency Guard, and Workflow Sanity: successful or intentionally skipped

Approval is for commit a12d4dd91974204e00fcc792a631783f9944d4a8. Merge and deployment remain separate actions.

@augusteo augusteo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review found one remaining interleaving on a12d4dd: owner cache key K starts scheduleSessionTurn -> unrelated registry becomes active -> same-key reload installs -> another unrelated registry becomes active before cron.add() resolves. Because the check compared only the current active cache key, the second unrelated swap erased the superseded signal and the stale job still committed. I reproduced it with a disposable case: it returned job-interposed-reload-then-unrelated instead of undefined.

Pushed 66570aa46 to fix it: recordPluginRegistryCacheKey now marks the older same-cache-key generation superseded when the replacement is installed, using a WeakRef/latest-by-key index so the signal survives later active-pointer swaps without retaining registries. isPluginRegistrySuperseded/isRegistryLive now consult that marker. The parameterized same-cache-key reload contract test gained the exact owner -> unrelated -> same-key reload -> unrelated case.

Validation on 66570aa46:

  • node scripts/run-vitest.mjs src/plugins/runtime.test.ts src/plugins/contracts/scheduled-turns.contract.test.ts src/plugins/host-hook-scheduled-turns-diagnostics.test.ts src/plugins/runtime/standalone-runtime-registry-loader.test.ts src/plugins/active-runtime-registry.test.ts src/plugins/runtime.channel-pin.test.ts - 34 contract tests + 53 plugin tests passed
  • node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile /home/ec2-user/.tmp/pr233-tsgo.tsbuildinfo - clean
  • node --import tsx scripts/check-import-cycles.ts - 0 runtime value cycles
  • node scripts/run-oxlint.mjs <3 changed files> and pnpm exec oxfmt --check --threads=1 <3 changed files> - clean

Full local pnpm build was not run because this host's root filesystem is at 100% (about 88MB free); build-artifacts is running in CI.

#233

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 3 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Fix all with cubic | Re-trigger cubic

Comment thread src/plugins/registry-lifecycle.ts Resolved
…xplicit retirement (PR review)

P2 (confidence 8, confirmed valid): latestCacheKeyRegistries (added in
66570aa to keep same-context supersession detection alive across later
unrelated swaps) only ever removed an entry when a newer registry took
over the same cache key, or via its FinalizationRegistry callback once
the referenced registry is actually garbage collected. Real GC timing is
non-deterministic and can lag well behind a registry's own logical
retirement, so a gateway cycling through many distinct tenant/session
cache keys could accumulate one map entry per key for registries that
are already done but not yet collected.

Fix: markPluginRegistryRetired now also drops the registry's own
latest-by-cache-key slot immediately (and unregisters its finalizer) when
it's still the current entry for its key. This is safe: retirement is
permanent and isPluginRegistrySuperseded already covers it via the
separate retired flag, so a later registry reusing the same key doesn't
need a stale 'latest' pointer to compare against.

Tests: new registry-lifecycle.test.ts proves the fix -- a later registry
reusing a retired registry's cache key doesn't mark either superseded via
the removed slot (only isPluginRegistrySuperseded's own retired-flag check
would apply, which is a separate mechanism this index doesn't need to
duplicate). Confirmed it fails for the right reason with the retirement
cleanup temporarily removed. 34/33 in scheduled-turns.contract.test.ts,
27/27 across runtime.test.ts + host-hook-scheduled-turns-diagnostics.test.ts,
2/2 new. tsgo:core, check:import-cycles, oxlint, oxfmt all clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Fix all with cubic | Re-trigger cubic

Comment thread src/plugins/registry-lifecycle.test.ts Resolved
…ry-lifecycle.test.ts (PR review)

P3 (confidence 6, confirmed valid): the test title and its inline comment
far exceeded this repo's 1-3 short-line convention, and repeated
rationale already stated in markPluginRegistryRetired's own comment.
Condensed both, using the reviewer's suggested comment wording.

Tests: 2/2 in registry-lifecycle.test.ts. tsgo:core, check:import-cycles,
oxlint, oxfmt all clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@convyusboy
convyusboy merged commit 1584bc9 into boon Sep 22, 2026
144 of 146 checks passed
@convyusboy
convyusboy deleted the ridho/plugin-registry-retirement-race-fix branch September 22, 2026 01:40
convyusboy added a commit that referenced this pull request Sep 22, 2026
…bump conflict)

Merges 3 commits from origin/boon (#233, #212, #229) into the 6.34
integration branch. Only pnpm-lock.yaml conflicted; package.json,
ui/package.json, and pnpm-workspace.yaml auto-merged clean and already
reflect boon's vitest 4.1.10 -> 4.1.11 bump. Resolved each lockfile
conflict hunk to boon's side (the newer vitest/@vitest/* version
strings and one transitive es-module-lexer bump); `pnpm install`
afterward made no further changes, confirming the resolution is
consistent.

Verified: tsgo:core clean; targeted vitest runs across the merged
surfaces (src/plugins/registry-lifecycle, plugin-registry, runtime,
host-hook-cleanup*, host-hook-scheduled-turns-diagnostics,
scheduled-turns.contract, extensions/browser-handoff/tool) all green.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
insomnius added a commit that referenced this pull request Sep 22, 2026
…238)

Root version, 135 plugin manifests synced via scripts/sync-plugin-versions.ts, changed npm-shrinkwrap.json files regenerated, CHANGELOG section for boon.46.

Shipping: #237 (diagnostics-otel owns its tracer and meter providers instead of the global ones, so it stops handing spans to a co-running SDK), #235 (model.usage stays inside the turn trace), #233 (a plugin's scheduled turn is no longer rolled back by an unrelated registry becoming active), #229 (browser-handoff recheck scheduling failure is logged), #212 (dev-only vitest bump in ui).

Base = 2026.6.11-boon.45. Gateway plus @openclaw/slack, @openclaw/msteams and @openclaw/diagnostics-prometheus bumped in lockstep; no separately published plugin source changed in this train, so a gateway roll delivers all of it.
convyusboy added a commit that referenced this pull request Sep 23, 2026
…s own execution (#236)

* fix(plugins): let scheduleSessionTurn work from inside a plugin tool's own execution

Root cause of the browser-handoff automatic-recheck failure (previously
mistaken for a plugin-registry retirement race, see #233): every plugin
tool's execute() handler resolves a fresh, narrow registry scoped to just
that one plugin, per invocation (createCachedDescriptorPluginTool in
tools.ts, activate:false, never installed via setActivePluginRegistry).
This is by design and works fine for normal tool calls, but
scheduleSessionTurn's shouldCommit check (isLoadedRecordInActiveRegistry)
required THIS specific registry to be activated -- which it never is,
even though the same plugin is genuinely loaded gateway-wide. Confirmed
live on arief-openclaw-test: a hand-patched diagnostic showed
'activateGlobalSideEffects is false on this registry' firing on every
single attempt, and a stack-trace patch on setActivePluginRegistry showed
this narrow registry was never installed as the active pointer at all --
it's simply never checked against the right thing.

Fix: isLoadedRecordInActiveRegistry now falls back to checking the real,
system-wide active registry by plugin id (new
isPluginLoadedInActiveRegistry in runtime.ts) whenever the caller's own
registry was never activated at all. Registries that WERE installed
active with side effects deliberately off (e.g. the migration-provider
registry from ensureStandaloneMigrationProviderRegistryLoaded) keep the
original, stricter rejection -- only a never-activated snapshot gets the
fallback. scheduleSessionTurn/unscheduleSessionTurnsByTag's own
activateGlobalSideEffects gates were narrowed the same way.

Tests: two new regression tests -- one proving scheduleSessionTurn now
succeeds when called through a narrow, never-activated registry while the
plugin is loaded in a separate real active one (confirmed it fails for
the right reason with the fix reverted), and one proving a registry that
WAS installed active with side effects off still correctly refuses
(confirmed cron.add gets called when THAT gate is removed). 36/36 in
scheduled-turns.contract.test.ts (2 new), 155 across every other test
file that references activateGlobalSideEffects. tsgo:core,
check:import-cycles, oxlint, oxfmt all clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(plugins): narrow the never-activated scheduleSessionTurn fallback to tool-execution snapshots

cubic-dev-ai flagged (PR #236) that the never-activated fallback in
isLoadedRecordInActiveRegistry was keyed only on isPluginRegistryActivated(registry),
so it applied to any side-effects-off registry that was never marked active -- not just
a plugin tool's own per-invocation execute() snapshot. A tool-discovery descriptor scan
or the CLI-only registry is also never-activated, and would have incorrectly bypassed
the activateGlobalSideEffects hard-reject for scheduleSessionTurn/unscheduleSessionTurnsByTag
whenever the same plugin id happened to be loaded in whatever registry is currently active.

Added an explicit toolExecutionScoped/toolExecutionSnapshot marker, set only at
createCachedDescriptorPluginTool's own load-options call site, and gated both the
fallback and the early activateGlobalSideEffects reject on it, so the loosened
by-id check only ever applies to the exact registry it was designed for.

Also trimmed two verbose comments (runtime.ts, registry.ts) and two verbose test
titles per cubic's style feedback, and added a regression test proving a
never-activated, non-tool-execution registry still gets rejected -- confirmed it
fails without the toolExecutionSnapshot marker (TypeError from cron.add being
called with no cron service).

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* fix(plugins): include toolExecutionScoped in the plugin registry loader cache key

cubic-dev-ai's re-review of PR #236 flagged a P1: the toolExecutionScoped marker
added in the previous commit is set on PluginLoadOptions but was never part of
the loader's cache identity (buildCacheKey / resolvePluginLoadCacheContext). An
ordinary tool-discovery load and a plugin tool's own execute() snapshot can
otherwise compute the identical cache key (same onlyPluginIds/toolDiscovery/
activate), so whichever one runs first gets cached and reused for the other --
silently handing back a registry whose toolExecutionSnapshot doesn't match what
the caller asked for, reintroducing the exact bug the marker exists to fix.

Added toolExecutionScoped to buildCacheKey's params and folded it into the
returned cache key string, and threaded options.toolExecutionScoped through
resolvePluginLoadCacheContext's call to it. Added a regression test asserting
the two cache keys differ for otherwise-identical options -- confirmed it fails
without the threading (the two keys were identical).

Also added the positive unscheduleSessionTurnsByTag test cubic asked for (P3):
the existing toolExecutionSnapshot coverage only exercised scheduleSessionTurn,
not the identical gate applied to unscheduleSessionTurnsByTag.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* test(plugins): extract shared toolExecutionSnapshot registry/api fixture helpers

cubic-dev-ai flagged (PR #236) that the same ~30-line registry+record+api setup
was duplicated across four tests in scheduled-turns.contract.test.ts (schedule,
unschedule, migration-provider, and non-tool-execution-snapshot rejection).

Extracted activateWorkflowPluginFixtureRegistry() (installs the real, activated
registry with the plugin loaded gateway-wide) and createWorkflowPluginRegistryApi()
(builds a separate, never-activated, side-effects-off registry + record + api,
optionally marked toolExecutionSnapshot) and switched all four tests to use them.
Net -53 LOC in the test file; behavior unchanged (all 38 tests still pass).

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants