Skip to content

fix(codex): discover on demand and retire unowned clients - #168387

Merged
steipete merged 6 commits into
mainfrom
codex/stab-codex-boot-appserver-fanout
Oct 10, 2026
Merged

steipete merged 6 commits into
mainfrom
codex/stab-codex-boot-appserver-fanout

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Every agent on the Codex harness got its own Codex app-server at Gateway boot, even if nobody used that agent, and the process stayed resident forever. On a dev Gateway with 18 agents (15 of them on the Codex runtime):

  • boot spawned the app-servers concurrently, and 9 to 12 acquisitions timed out after 10 s on a loaded host (codex app-server scope timed out phase=acquire-client ... requestStartedCount=0), about a minute after ready, with no client request in flight;
  • 19 minutes later, with no traffic, 9 Codex app-servers were still children of the Gateway, about 1.3 GB RSS together (about 105 MiB each, launcher included);
  • the count scales with the number of Codex agents.

The cause: startup's changed-only model catalog refresh acquired native inventory (model/list, account/read) for every configured agent, after the provider concurrency limit. Releasing that discovery request left the client resident, and nothing retired idle shared clients.

Why This Change Was Made

Maintainer decision (Peter, 2026-10-09): demand-driven Codex discovery. No boot spawns for unused agents, lazy discovery on first real use, and retirement of clients that own no work. The first use of an idle agent pays the cold start.

  • Startup stays provider-only. Lifecycle refreshes no longer acquire native inventory (src/agents/prepared-model-runtime.catalog-access.ts). The real picker handler (models.list) and catalog reader trigger native discovery for the requested agent only, coalesce concurrent requests, and reacquire after retirement. Until discovery runs, native readiness reports unknown instead of a false negative.
  • Ownership-aware retirement. extensions/codex/src/app-server/shared-client-lifecycle.ts retires a shared client after a 30 s grace (about 6× the measured worst cold start of 5.4 s) once it holds no leases or pending acquisitions and owns no live thread, turn, native child, background terminal, or ephemeral history (client-runtime.ts).
  • Unchanged: per-agent and per-account isolation, explicit recovery retirement, the warm session-create executor LRU, and thread retention policies.
  • Docs (docs/concepts/models.md, Codex harness model-discovery reference) describe the new lifecycle.

User Impact

A Gateway with many Codex agents boots without spawning an app-server per agent, so boot-time load drops and the acquisition timeouts are gone. Idle agents stop holding about 100 MiB each. The first picker read or turn for an idle agent pays a cold start of about 1 to 5 s.

Evidence

  • Negative controls with the original production bytes restored: the boot regression saw 3 native acquisitions instead of 0, all 8 idle-retirement cases kept clients open past the grace, and initial readiness was false instead of unknown. With the fix, these pass.
  • 472 distinct tests passed across scoped runs: six Codex owner and sibling suites (294), core discovery, reload and publication siblings (57), Gateway picker, provider lifecycle and startup sidecars (88), the Gateway catalog boundary (16), plus the multi-agent demand cases. Core types, lint, formatting, docs, mock-export pruning and cycles pass. Autoreview is scoped-clean.
  • Not claimed green locally: broad extension types (QA Lab's unavailable Crabbox dependency), the Codex boundary project (missing SDK declarations), and extension lint prerequisite generation (timed out on a loaded host). CI covers these.
  • Live A/B on dev Gateways, real OpenAI provider, same 17 to 18 agents (15 on the Codex runtime), no traffic after boot:
    • main plus an unrelated fix: 9 to 12 acquire-client timeouts per boot; 9 resident app-servers about 1.3 GB RSS after 19 idle minutes.
    • this branch, fresh state dir: 0 acquisition timeouts and 0 app-servers 2 minutes after boot.
    • first models.list for an idle agent: 5.5 s and 37 models, which spawned 1 app-server. A first turn on another idle agent replied ok (app-server cold start 10.4 s; first output 19 s into the turn on a host at load about 60); resume in the same session replied again in 10 s; a repeat models.list took 74 ms.
    • after idle: the picker-only client and a later transient client retired after the grace; the one client that still owns the resumed session's Codex thread stays, following the existing thread-retention policy (unchanged).

Follow-up after review (head 8917a77)

The first landing attempt stopped on a ClawSweeper P2: models.list awaited native discovery, so an immediate Codex startup or model/list failure rejected an ordinary picker read even when provider rows were already published. The branch also conflicted with main.

  • origin/main is merged in, keeping main's listChangedProviders-based reacquisition of discovery-only providers.
  • f186a7d413ee: an ordinary picker read returns the saved rows with refreshFailed when optional native discovery rejects. Selected execution, explicit refresh, superseded-owner and authorization errors still reject. A handler-boundary regression covers published provider rows with a native hook that rejects before 5 s.
  • d66abd017595 and 8917a773f7c4 fix three readiness defects found in review: native discovery failures are now scoped to their own runtime, partial discovery no longer marks the whole inventory complete, and runtime-key lookups are preserved.
  • 510 tests pass: six Codex suites (294), catalog and harness suites (111), Gateway suites (105). Each new regression fails before its fix. Autoreview is scoped-clean.
  • Live re-proof on this head (17 agents, fresh state): 0 acquisition timeouts and 0 app-servers 2 minutes after boot; first picker read 1.3 s with 37 models; first turn 12 s; resume 4 s; repeat picker 13 ms; after idle, only the client that owns the resumed session's thread remains.

CI fixture follow-up (head a5fa979)

ClawSweeper's review of 8917a773f7c4 confirmed the optional-discovery failure repair and identified two stale sibling test contracts in CI run 38050401013. This follow-up changes tests only: the metadata lifecycle fixture explicitly acquires native inventory before testing retained observations and after generation replacement; the registered Codex runtime-choice test distinguishes unknown readiness from an observed native row that is unavailable. Pin authority, revocation, full discovered metadata, and passive repeated-read checks remain covered.

Both files passed on captured main e3415ea8c554 and reproduced the reviewed-head failures locally before correction. The final focused runs pass all 20 cases: Gateway lifecycle (18 tests, 28.33 s wall) and registered runtime choices (2 tests, 19.25 s wall). Targeted lint, Gateway test types, formatting, and git diff --check pass. Independent review of the production diff and the final test changes found no actionable P0–P2 findings. Exact-head CI run 38051919906 passed on attempt 1 (62 successful jobs, 23 skipped, no failures). ClawSweeper completed its exact-head review on October 10 at 12:33 UTC with no findings or before-merge items. Telegram Test Server menu E2E remains an optional proof improvement; the supplied real-provider Gateway proof is sufficient. No rerun or admin exception was used.

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling extensions: codex size: L labels Oct 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR defers native model discovery until demand and retires Codex clients after 30 seconds without owned work.

Example: A Gateway has 17 agents, including 15 using Codex.

  • Before: Unused agents start app-servers at boot and leave idle processes resident.
  • After: The reported live run has no app-servers after idle boot; a picker request starts one, while a resumed session retains its owned client.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful owner-approved repair with scoped live evidence, meaningful regressions, and both prior findings resolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied live Gateway A/B results exercise provider-only boot, first models.list demand, first Codex turn, same-session resume, repeated reads, and retirement of clients without owned threads; the final commit changes tests only.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Unused Codex agents create persistent app-server processes, increasing memory pressure and loaded-host acquisition failures.
Reason: The recorded maintainer direction accepts demand-driven discovery and its cold-start cost, and the supplied live results show meaningful resource savings.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: both prior findings are addressed, the resource-retention fix remains necessary, and no new actionable defect was found; current-head CI is still pending.

Priority: P2
Reviewed head: a5fa97956e345efedf841da2a2947ee9c5b09951

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Telegram Test Server evidence for first-use model-menu readiness and catalogue publication was not supplied.
Agent review details

How this fits together

Gateway catalogue requests enter the prepared model owner, which combines provider inventory with native harness observations and uses the Codex shared-client owner to acquire and retire physical clients.

flowchart TD
A[Gateway startup] --> B[Provider inventory]
C[Picker or native execution] --> D[Prepared model owner]
B --> D
D --> E[Codex shared client]
E --> F[Native model and account observations]
F --> D
E --> G[Ownership aware idle retirement]
Loading

Technical review

Best possible solution:

Land the existing demand-driven discovery and ownership-aware retirement implementation once the normal merge gates pass.

Do we have a high-confidence way to reproduce the issue?

Current-main source contains startup native acquisition and no general idle-retirement timer, consistent with the reported multi-agent Gateway observations; this read-only review ran no target code.

Is this the best way to solve the issue?

The patch repairs discovery demand and client lifetime in their existing owners while retaining provider publication, warm subscriptions, and execution error contracts.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against e09de50421ef.

Provenance checked

  • Startup and lifecycle native discovery changes intended behavior with a stated reason (fix(models): discover account models after sign-in #145190: Publish account models after sign-in while keeping ordinary reads passive.)
  • Cold-start catalogue completeness changes intended behavior with a stated reason (b05104a: Restore models that only full discovery finds after a Gateway restart.)
  • Independent warm-thread retention keeps the original intent (5a79d19: Preserve warm conversations and approvals while bounding unprotected idle subscriptions.)
  • Independent provider and native publication keeps the original intent (11d36eb: Prevent catalogue renewal from stalling selected native execution or discarding healthy provider results.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 5a79d19 adds extensions/codex/src/app-server/client-runtime.ts:35 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5a79d19ba179; files: extensions/codex/src/app-server/client-runtime.ts)
  • Ayaan Zaidi: Raw commit eea11f9 adds src/agents/prepared-model-runtime.discovery-retry.ts:12 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: eea11f9739d9; files: src/agents/prepared-model-runtime.discovery-retry.ts)
  • JC: Raw commit 7f60f5f adds extensions/codex/src/app-server/client-runtime.ts:51 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 7f60f5f7e51d; files: extensions/codex/src/app-server/client-runtime.ts)

PR surface

Source +161, Tests +642, Docs +21, Other -2. Total +822 across 36 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 17 290 129 +161
Tests 16 699 57 +642
Docs 2 35 14 +21
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 2 -2
Total 36 1024 202 +822

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Unnecessary native processes consume substantial memory on multi-agent Gateways, with a bounded lifecycle repair.
  • merge-risk: 🚨 compatibility: Startup discovery and pre-discovery availability change intentionally; the recorded maintainer direction accepts cold first use and unknown native readiness.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. Shared catalogue acquisition and unknown native readiness affect Telegram model-menu rows and runtime choices before and after first discovery.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Exercise first-use native model discovery and menu readiness through Telegram's Test Server userbot.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-10T10:32:11.170Z sha e74a91a :: needs changes before merge. :: [P2] Preserve saved picker rows when native discovery rejects
  • reviewed 2026-10-10T12:13:09.906Z sha 8917a77 :: needs changes before merge. :: [P2] Update metadata lifecycle fixtures for demand-driven discovery | [P2] Preserve unknown readiness in the runtime-choice test

Reviewed October 10, 2026, 8:33 AM ET / 12:33 UTC (Revision 3).

Merge main while retaining discovery-only provider reacquisition and demand-driven native catalogs. Ordinary inventory reads retain published rows and refreshFailed when optional native hooks reject; selected execution and explicit refresh still reject. Add handler-boundary coverage for saved rows, owner supersession, and authorization invalidation.
Main now reacquires discovery-only providers after credential invalidation. Serve current empty discovery auth, join that acquisition, and assert one additional request while retaining the no-rediscovery checks for compatible reloads. The prior expectation fails with exact merged-main production as well.
Record rejected native observations in the existing runtime outcome map. Preserve healthy runtime readiness checks after unrelated failures, including runtimes sharing a provider. Publish failed observations before retaining selected and explicit-refresh rejection. Add failing-before handler regressions for unscoped and shared-provider failures.
Only unscoped native acquisition completes global inventory readiness. Check outcome ownership before indexing arbitrary runtime IDs. Handler regressions prove an initial provider-scoped refresh still acquires the remaining runtime and inherited property names cannot break picker reads.
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. labels Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Both findings from the review of 8917a773f7c4 are addressed in a5fa97956e345efedf841da2a2947ee9c5b09951. The test-only follow-up explicitly acquires native inventory in retained-metadata fixtures and distinguishes unknown runtime readiness from an observed unavailable native row. All 20 focused cases, targeted lint, Gateway test types, formatting, and independent review pass. The PR body records the CI failures and measured proof.

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper approve

Maintainer decision (Peter, 2026-10-09, in chat): Demand-driven Codex discovery - no boot spawns for unused agents, lazy discovery on first use, retire clients that own no work after a short grace; first use pays the cold start.

The completed review of a5fa97956e345efedf841da2a2947ee9c5b09951 has no findings or before-merge items. CI run 38051919906 has since completed successfully on that exact head.

@clawsweeper

clawsweeper Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@steipete
steipete merged commit a825abb into main Oct 10, 2026
163 of 164 checks passed
steipete added a commit that referenced this pull request Oct 10, 2026
Demand-driven discovery in #168387 leaves configured model hints with
unknown native readiness until discovery supplies an observation. Check
that this state does not renew, then supply the observed native variant
before exercising the existing exact renewal and revocation assertions.

Preserve every original case and assertion. Production discovery behavior
is unchanged.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…68387)

* fix(codex): discover on demand and retire unowned clients

* test(models): align reload proof with provider reacquisition

Main now reacquires discovery-only providers after credential invalidation. Serve current empty discovery auth, join that acquisition, and assert one additional request while retaining the no-rediscovery checks for compatible reloads. The prior expectation fails with exact merged-main production as well.

* fix(models): scope native discovery failures to their runtime

Record rejected native observations in the existing runtime outcome map. Preserve healthy runtime readiness checks after unrelated failures, including runtimes sharing a provider. Publish failed observations before retaining selected and explicit-refresh rejection. Add failing-before handler regressions for unscoped and shared-provider failures.

* fix(models): preserve native inventory scope and runtime keys

Only unscoped native acquisition completes global inventory readiness. Check outcome ownership before indexing arbitrary runtime IDs. Handler regressions prove an initial provider-scoped refresh still acquires the remaining runtime and inherited property names cannot break picker reads.

* test(codex): align catalog fixtures with demand discovery
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
Demand-driven discovery in openclaw#168387 leaves configured model hints with
unknown native readiness until discovery supplies an observation. Check
that this state does not renew, then supply the observed native variant
before exercising the existing exact renewal and revocation assertions.

Preserve every original case and assertion. Production discovery behavior
is unchanged.
RomneyDa added a commit that referenced this pull request Oct 12, 2026
… refresh

Align the scoped-refresh case with the #168315 backport, which reacquires
discovered providers a config rebuild cannot retain. Main carries the same
case as "retains compatible discovery and reacquires it after credentials
change" (from a825abb); this ports only that test case, not #168387's
Codex discovery changes.
steipete added a commit that referenced this pull request Oct 20, 2026
The metadata fixture asserted complete plugin discovery after a bounded foreground catalog read, which can legitimately return seeded rows while acquisition remains pending. Use the existing explicit refresh wait contract and retain all metadata, catalog-row, native-auth and single-acquisition assertions. The five-second foreground behavior introduced in #168387 remains unchanged.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
The metadata fixture asserted complete plugin discovery after a bounded foreground catalog read, which can legitimately return seeded rows while acquisition remains pending. Use the existing explicit refresh wait contract and retain all metadata, catalog-row, native-auth and single-acquisition assertions. The five-second foreground behavior introduced in openclaw#168387 remains unchanged.
RomneyDa added a commit that referenced this pull request Oct 26, 2026
Shared Codex app-server clients stayed resident until Gateway restart once
their last lease released, so per-agent discovery and status requests left
idle app-server process pairs behind (#165663).

A shared client with no active leases, no pending acquires, and no native
thread ownership (retained, claimed, releasing, or protected subscriptions)
now retires 30 seconds after it goes idle. Lease acquisition and thread
ownership changes cancel or reschedule the timer, closing the client clears
it, and the next request starts a fresh client through the normal
acquisition path.

(cherry picked from commit a825abb)

Adapted for 2026.9.x: ported only the idle-retirement slice of a825abb
(shared-client-lifecycle.ts idle timer, shared-client.ts hasOwnedThreads
and ownership-change wiring, client-runtime.ts ownership hook and
hasCodexAppServerThreadOwnership, shared-client-idle.test-support.ts). Left
out on-demand discovery, the model catalog and prepared-runtime changes,
and the harness/gateway changes. 9.x has no closeSharedClientEntryIfUnclaimed,
so that cancel site is skipped; closeRetiredSharedClientEntry and the
client close handler still clear the timer. The grace stays at a825's 30
seconds instead of main's later 5 minutes (b39a055). The eviction-timer
clear in client-runtime.ts uses main's two-line form so the file stays
within the 700-line lint limit.
@obviyus obviyus mentioned this pull request Nov 18, 2026
5 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: codex gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant