Skip to content

fix(gmi): manager shutdown waits for creations in flight, bounds each GMI and runs once - #222

Merged
jddunn merged 11 commits into
masterfrom
fix/gmimanager-shutdown-2
Oct 10, 2026
Merged

jddunn merged 11 commits into
masterfrom
fix/gmimanager-shutdown-2

Conversation

@jddunn

@jddunn jddunn commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

Summary

Follow-ups from the review of #210, which made GMIManager.shutdown() reach every GMI in the session map. Five paths still leave a GMI running after the manager shuts down, or let one GMI hold AgentOS.shutdown() open. Each fix lands after a regression test that CI ran red; every case drives a real GMIManager with real GMIs and a recorder in place of the cognitive memory (src/cognition/substrate/__tests__/GMIManager.shutdown.test.ts).

  1. A creation in flight when shutdown begins: getOrCreateGMIForSession() checks the manager's initialization again after every wait. A GMI it built and has not registered once shutdown has begun is shut down and the call fails with NOT_INITIALIZED; shutdown() waits for the calls in flight before it clears the maps. Done.
  2. Each GMI's shutdown runs in parallel under a time limit: shutdown() shuts every GMI down at the same time, and a new GMIManagerConfig.shutdownTimeoutMs (default 8000) bounds each one wherever the manager shuts a GMI down. A GMI that has not finished by then is logged at warn with its session and finishes on its own; the maps are cleared either way, so AgentOS.shutdown() takes about one bound, not a sum. Done.
  3. GMIs in the active map with no session entry (two creations for one new session that raced) are shut down in the same pass, before both maps are cleared. Done.
  4. GMI.shutdown() stops the running turn and keeps the SHUTDOWN state: each turn's model call runs under a stop signal that the caller's abort signal (a session's close()) and shutdown() both abort, so the call ends with the provider's or the gateway's abort chunk and the turn ends with the abort error. shutdown() takes the lifecycle state back first, so a turn that ends afterwards writes neither READY nor ERRORED, and it waits for the stopped turns within the shutdown bound before it closes the memories. GMIBaseConfig takes an optional shutdownTimeoutMs (default 8000), which the manager sets to its own. Done.
  5. A GMI's shutdown runs once when calls overlap: GMI.shutdown() returns the running shutdown's promise to a call made while it runs, so a second manager shutdown (SIGINT, then SIGTERM), a deactivation or a cleanup that overlaps it waits for the same work, and the memories are closed once. A call after the shutdown has finished returns at once, as before. Done.

Linked issues

None.

Type of change

  • Bug fix
  • Feature
  • Performance
  • Documentation
  • Refactor
  • Tests
  • Build or CI

How this was verified

CI only. Each regression test was pushed alone and read red with only its own case failing, then the fix was pushed and read green:

Item Test commit, red run Fix commit, green run
1 3241ef1, run 38007301291 6607463, run 38007596691
2 37413a4, run 38007845911 7e98277, run 38008187439
3 af14caa, run 38008511236 3d5ebc6, run 38008780337
4 4e6e898, run 38011582982 dcea615, run 38011909936
5 c6253e9, run 38012204520 52f56cd, run 38012462596

The branch then merged master (2c41dac); the CI run on that head is the one this pull request merges on.

Migration notes

None. No signature changes; the new options have defaults.

Checklist

  • Tests cover the changed behavior.
  • Docs are updated.
  • The title follows Conventional Commits, with ! before the colon for a change that breaks users (feat!: or feat(api)!:).
  • No secrets or private data are included.
  • Every automated review thread is settled (how).
  • I have read this change and can explain every line.

Summary by Sourcery

Make GMI shutdown bounded, concurrent, and idempotent while reliably cleaning up creations, active turns, and orphaned instances.

Bug Fixes:

  • Ensure GMI manager shutdown handles in-flight creations, orphaned GMIs, overlapping shutdown calls, and active turns without leaving resources running.
  • Bound each GMI shutdown and run shutdown operations concurrently so one slow GMI cannot block runtime shutdown indefinitely.

Enhancements:

  • Add configurable shutdown timeouts with an 8-second default and propagate the manager setting to individual GMIs.
  • Document GMI and manager shutdown behavior, including cancellation of active turns and cleanup guarantees.

Documentation:

  • Document the shutdown lifecycle, timeout behavior, cancellation of active turns, and overlapping shutdown handling.

Tests:

  • Add regression coverage for in-flight creation cleanup, concurrent bounded shutdown, orphaned GMIs, active-turn cancellation, and idempotent overlapping shutdowns.

Summary by CodeRabbit

  • New Features
    • Added configurable shutdown timeouts, defaulting to 8 seconds, so runtime shutdown can continue when a GMI takes too long to stop.
    • Shutdown now stops active turns, closes GMI memories, and safely handles GMIs being created at the same time. Calls made after manager shutdown begins are rejected.
    • Overlapping shutdown requests share the same operation.

getOrCreateGMIForSession() checks the manager's initialization only when
it starts. A call still waiting on the tier check, the cognitive memory
factory or GMI.initialize() when shutdown() runs registers its new GMI
afterwards, so the manager holds a READY GMI after shutdown and that
GMI's memory is never closed.

The case holds the creation for session-3 in the cognitive memory
factory, starts shutdown(), then releases the factory. The call must
fail with NOT_INITIALIZED, the GMI it built must be shut down, and both
maps must end empty.
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 10, 2026 00:02
@sourcery-ai

sourcery-ai Bot commented Oct 10, 2026

Copy link
Copy Markdown

Sorry @jddunn, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 3 hours and 58 minutes by commenting @sourcery-ai review. Upgrade to get a review now.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@sourcery-ai

sourcery-ai Bot commented Oct 10, 2026

Copy link
Copy Markdown

Reviewer's Guide

Adds a deterministic real-manager regression test for a GMI created while shutdown starts, verifying the late-created GMI is rejected, shut down, and removed along with all existing GMIs.

File-Level Changes

Change Details Files
Make the test harness able to pause GMI creation before cognitive memory initialization completes.
  • Add an optional per-session async hook to hold cognitive memory creation.
  • Preserve real GMI and manager construction while injecting deterministic creation timing.
src/cognition/substrate/__tests__/GMIManager.shutdown.test.ts
Add regression coverage for shutdown racing with an in-flight GMI creation.
  • Start creation for a third session and block it after initialization begins.
  • Begin manager shutdown, release creation, and verify the creation fails as uninitialized.
  • Verify all three cognitive memories close and both manager registries are empty.
src/cognition/substrate/__tests__/GMIManager.shutdown.test.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: Repository: framerslab/agentos/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Team
  • Run ID: a80edbfd-1248-480c-b9d2-890004f24f15

📥 Commits

Reviewing files that changed from the base of the PR and between b9931bf and 2c41dac.


📒 Files selected for processing (6)
  • docs/GMI.md
  • src/cognition/substrate/GMI.ts
  • src/cognition/substrate/GMIManager.ts
  • src/cognition/substrate/IGMI.ts
  • src/cognition/substrate/__tests__/GMIManager.shutdown.test.ts
  • src/cognition/substrate/shutdownBound.ts

 _______________________________________________________
< Veni, Vidi, VCS: I came, I saw, I version-controlled. >
 -------------------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR

🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR


  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

test(gmi): cover shutdown during in-flight GMI creation

🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Add a controllable memory factory to hold GMI creation while manager shutdown begins.
• Assert the pending call fails, its memory closes, and both manager maps are empty.
Diagram

sequenceDiagram
    participant Test as Regression test
    participant Manager as GMI manager
    participant Factory as Memory factory
    participant GMI as New GMI
    participant Maps as Manager maps
    Test->>Manager: Request session creation
    Manager->>Factory: Build cognitive memory
    Factory-->>Test: Signal creation held
    Test->>Manager: Start shutdown
    Test->>Factory: Release memory
    Factory-->>Manager: Return memory
    Manager->>GMI: Initialize GMI
    Manager->>Maps: Register GMI
    Test->>Manager: Assert rejection and cleanup
Loading
High-Level Assessment

A controlled factory pause is appropriate for reproducing this race with real manager and GMI instances. This diff adds the regression test only; it does not change shutdown behavior, so the creation–shutdown coordination fix is still needed.

Files changed (1) +51 / -4

Tests (1) +51 / -4
GMIManager.shutdown.test.tsTest shutdown against a paused GMI creation +51/-4

Test shutdown against a paused GMI creation

• Makes the harness's cognitive memory factory optionally wait for a selected session. Adds a test that starts shutdown while session-3 creation is paused, then expects the pending call to reject with NOT_INITIALIZED, all three memories to close, and both maps to be empty.

src/cognition/substrate/tests/GMIManager.shutdown.test.ts

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Shutdown regression test fails every run ✓ Resolved
Description
shutdown() snapshots the session map before waiting for getOrCreateGMIForSession() to finish, so
this test's released creation can register after the snapshot and resolve successfully. The
assertions then expect NOT_INITIALIZED and three memory closes, causing the suite to fail while
the late GMI remains unshutdown until its map reference is cleared.
Code

src/cognition/substrate/tests/GMIManager.shutdown.test.ts[R164-166]

+    const shutdown = manager.shutdown();
+    releaseMemory();
+    await shutdown;
Evidence
The test deliberately pauses creation inside the cognitive-memory factory, starts shutdown, and then
releases creation. The manager checks initialization only at method entry, snapshots existing
sessions before awaiting shutdown, and later inserts the newly initialized GMI into both maps;
clearing those maps does not invoke the GMI's shutdown, so the test's rejection and memory-close
assertions fail.

src/cognition/substrate/tests/GMIManager.shutdown.test.ts[145-166]
src/cognition/substrate/GMIManager.ts[505-511]
src/cognition/substrate/GMIManager.ts[464-479]
src/cognition/substrate/GMIManager.ts[575-580]
src/cognition/substrate/GMIManager.ts[716-737]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An in-flight GMI creation can resume after `GMIManager.shutdown()` snapshots the session map, register a new GMI, and resolve successfully. The added regression test exposes this because the manager does not track creation promises or recheck shutdown state before registration, leaving the late GMI's cognitive memory open.
## Fix Focus Areas
- src/cognition/substrate/GMIManager.ts[505-511]
- src/cognition/substrate/GMIManager.ts[464-479]
- src/cognition/substrate/GMIManager.ts[575-580]
- src/cognition/substrate/GMIManager.ts[716-737]
## Recommended Fix
Track active `getOrCreateGMIForSession()` operations, have shutdown wait for them to reach a safe checkpoint, and recheck `isInitialized` after asynchronous creation completes before inserting the GMI into either map. If shutdown has started, shut down the newly built GMI immediately and reject with `GMIErrorCode.NOT_INITIALIZED`; ensure shutdown also drains or otherwise handles all tracked creations before clearing the maps.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can copy the agent prompt from any finding and feed it to your IDE agent

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

jddunn added 10 commits October 9, 2026 17:06
…registered

getOrCreateGMIForSession() checked the manager's initialization only when
it started. A call still waiting on the tier check, the cognitive memory
factory or GMI.initialize() when shutdown() ran registered its GMI after
the maps were cleared, and that GMI stayed READY with its memory open.

The call now checks again after every wait. A GMI it built and has not
registered when shutdown has begun is shut down through the manager's
per-GMI shutdown, and the call fails with NOT_INITIALIZED. A call that
registered its GMI before shutdown began also fails once it resumes, and
shutdown() shuts that GMI down with the others. shutdown() waits for every
call still in flight before it clears the maps.
GMIManager.shutdown() waits for each GMI's shutdown in turn with no time
limit. A GMI whose cognitive memory is still closing (a consolidation
cycle waiting on its model call) holds the loop, as does one whose
metaprompt drain runs its full 5 seconds, so AgentOS.shutdown() takes
the sum over all GMIs, or never returns, before its later steps run.

The case keeps the cognitive memory of three GMIs open and sets
shutdownTimeoutMs to 50. Under fake timers every GMI must begin closing
at once, shutdown() must resolve after one bound, one warning per session
must be logged, and both maps must end empty.
…limit

GMIManager.shutdown() waited for each GMI's shutdown in turn with no time
limit. AgentOS.shutdown() therefore took the sum over all GMIs (a
metaprompt drain alone can take 5 seconds), or never returned when a
GMI's cognitive memory never finished closing, and its later steps never
ran.

shutdown() now shuts every GMI down at the same time. A new
GMIManagerConfig option, shutdownTimeoutMs (default 8000: inside the 10
seconds docker stop waits, above the 5-second metaprompt drain), bounds
each GMI's shutdown wherever the manager shuts one down. A GMI that has
not finished by then is logged at warn with its session and finishes on
its own; the maps are cleared either way. The wait for creations in
flight has the same bound. docs/GMI.md describes the manager's shutdown.
shutdown() finds GMIs only through the session map. Two
getOrCreateGMIForSession() calls for one new session that run at the
same time both build a GMI, and the later registration takes the session
entry from the earlier one, which then sits in the active map alone.
shutdown() clears it from the map without shutting it down, so its
metaprompt queue and memories stay open.

The case races two creations for session-9 and checks that shutdown()
shuts the GMI left without a session entry down once and waits for it.
shutdown() found GMIs only through the session map and then cleared the
active map, so a GMI left there without a session entry (two creations
for one new session raced, and the later registration took the entry)
was dropped while still READY, with its metaprompt queue and memories
open.

shutdown() now also shuts down every GMI in the active map that no
session maps to, in the same pass and within the same bound as the
sessions, before it clears both maps.
GMI.shutdown() does not stop a turn that is running, and the turn keeps
its hold on the lifecycle state. A turn waiting on its model call when
the manager shuts down goes on once the call answers, and its finally
block writes READY over SHUTDOWN, so a GMI that has been shut down
reports READY.

The case runs a turn against a provider that holds the call open until
it is aborted or answered, shuts the manager down while the call is open,
then lets the provider answer. The turn must end with the abort error and
an ERROR chunk, and the GMI must read SHUTDOWN afterwards.
GMI.shutdown() did not stop a turn that was running, and the turn kept
its hold on the lifecycle state. A turn waiting on its model call when
the GMI shut down went on once the call answered, wrote to memories
that were closed, and its finally block wrote READY over SHUTDOWN.

Each turn now runs under a stop signal of its own, which is what the
model call receives. The caller's abort signal (a session's close())
aborts it as before, and shutdown() aborts it too, so the model call in
progress ends with the provider's abort chunk, or the gateway's, and the
turn ends with the abort error. shutdown() takes the lifecycle state
back before it stops the turns, so a turn that ends afterwards writes
neither READY nor ERRORED, and it waits for the stopped turns at most
the shutdown bound before it closes the memories. GMIBaseConfig takes
an optional shutdownTimeoutMs (default 8000); GMIManager passes its own.
docs/GMI.md describes the behaviour.
GMI.shutdown() returns early only once the state is SHUTDOWN, so a call
made while another is running starts the drain and the memory close
again. The manager reaches this whenever two shutdowns overlap: a second
manager shutdown (SIGINT, then SIGTERM), or a shutdown during a session's
deactivation, sees the session still mapped and shuts its GMI down a
second time, and a cognitive memory from a factory that is not
idempotent is closed twice.

The case calls shutdown() twice at once on one GMI, then runs two manager
shutdowns at once. Each GMI's memory must close once, every call must
resolve, and both maps must end empty.
GMI.shutdown() returned early only once the state was SHUTDOWN, so a
call made while another was running drained the metaprompt queue and
closed the memories a second time. The manager reached this whenever
two shutdowns overlapped: a second manager shutdown (SIGINT, then
SIGTERM), or a shutdown during a session's deactivation, saw the
session still mapped and shut its GMI down again, and a cognitive
memory from a factory that is not idempotent was closed twice.

One shutdown now runs at a time: a call made while one runs returns the
same promise, so every caller waits for the same work and the memories
are closed once. A call after the shutdown has finished returns at once,
as before. The manager's deactivations, cleanup and shutdown all go
through GMI.shutdown(), so they share it too. docs/GMI.md says so.
@jddunn
jddunn merged commit d99b126 into master Oct 10, 2026
9 of 10 checks passed
github-actions Bot pushed a commit that referenced this pull request Oct 10, 2026
## [0.13.23](v0.13.22...v0.13.23) (2026-10-10)

### fix

* **gmi:** follow-ups from the reviews of #193 and #199 (#217) ([2bacb69](2bacb69))
* **gmi:** manager shutdown waits for creations in flight, bounds each GMI and runs once (#222) ([d99b126](d99b126))
* **images:** the untrusted fetch settles on a protocol upgrade, and four review follow-ups (#227) ([9efb4b5](9efb4b5))
* **vision:** the TrOCR and Florence-2 tiers get a Buffer image as a Blob (#229) ([7fe444a](7fe444a))
@jddunn
jddunn deleted the fix/gmimanager-shutdown-2 branch October 10, 2026 18:59
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.

1 participant