Skip to content

fix(local-ai): stop routing to OpenAI while the endpoint restarts - #1321

Closed
larroy wants to merge 3 commits into
openclaw:mainfrom
larroy:dev/plarroy/local-ai-no-openai-fallback
Closed

larroy wants to merge 3 commits into
openclaw:mainfrom
larroy:dev/plarroy/local-ai-no-openai-fallback

Conversation

@larroy

@larroy larroy commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes the missing-provider-auth / No API key found for provider "openai" failure on the first prompt after the companion starts, on a Local AI-only install.

Refs #1293. Note that issue is filed as a gateway-side stale-reload/dispatch race; the root cause is actually in this repo, and the gateway behaved correctly throughout (detail).

Root cause

EnsureStartedCoreAsync sequenced quiesce → start → probe → publish on every launch. QuiesceAsync unsets models.providers.llamacpp and, when GatewayFallbackModel is null, unset agents.defaults.model.primary outright.

An absent primary is not "no routing" — the gateway resolves its built-in default:

parseModelRef(... ?? "gpt-5.6-sol", "openai", { allowPluginNormalization: false })

So any prompt dispatched in that window went to openai and failed on a missing credential. From ~/.openclaw/logs/config-audit.jsonl on a reproducing run:

Time (UTC) Command
01:26:12.432 config unset agents.defaults.model.primary
01:26:13.579 config unset models.providers.llamacpp
01:26:22.662 config set --batch-file /dev/stdin (republishes provider + primary)

with the failure landing at 01:26:15 — inside the ~9s hole. The window existed on every launch, not just after setup, because requestedPort is 0, so the OS assigns a new port each run and the previously published baseUrl is stale by construction.

Changes

1. Never leave the gateway without a primary model. QuiesceAsync takes a LocalAiQuiesceReason. EndpointCycle retains the managed llamacpp/<alias> primary, so a request that lands mid-cycle fails as Local AI rather than as an unrelated provider. Teardown (stop, shutdown, failed publish, uninstall) keeps the existing restore-or-unset behaviour, so a user with a real prior model still gets it back.

2. Make the normal restart a no-op. ResolvePlannedPort reuses the last verified port when free, so the published route stays valid and the quiesce is skipped entirely; PublishAsync then sees an exact match and no-ops. The common restart now performs zero config writes. A route is withdrawn only when the endpoint genuinely moves.

3. Latent bug surfaced by (2). Deciding the port before touching routing revealed that the port-conflict and ownership-unknown paths returned Conflict without withdrawing the published route, leaving the gateway aimed at a port a foreign process owns. FailStartupAsync now takes a route to withdraw, and every startup-failure path passes it when one was left standing.

4. Terminal startup outcomes withdraw retained routing (ClawSweeper P1 findings). With a retained route, a process-launch exception, immediate child exit, or cancellation previously hit the catch handlers in EnsureStartedCoreAsync, which only disposed the child — the gateway kept routing to the retained port with no listener. Both catch paths now withdraw the retained route with Teardown semantics before the child's listener disappears. HandleManagedProcessExitedAsync also always quiesced with EndpointCycle semantics even when automatic restart attempts were exhausted, leaving the managed primary selected with its provider absent; it now picks the reason from whether a restart will actually run (EndpointCycle for a pending restart, Teardown once the retry budget is spent). FailStartupAsync withdraws a retained route before disposing the child, matching the lifecycle contract that managed routing is removed before a listener can disappear.

Tests

Six new tests from the first round, each failing on the old code:

  • Quiesce_EndpointCycleRetainsManagedPrimaryWhenNoFallbackExists — asserts no unset of the primary path
  • Quiesce_EndpointCycleStillRestoresRealPriorModel
  • Publish_AcceptsPrimaryRetainedByAnEndpointCycle
  • Restart_ReusesLastVerifiedPortAndNeverWithdrawsThePublishedRoute — asserts no quiesce event at all
  • Restart_WithdrawsStaleRouteWhenTheLastVerifiedPortIsTaken
  • Restart_WithdrawsRetainedRouteWhenStartupNeverBecomesHealthy

Three new regression tests for the terminal failure paths from the ClawSweeper review:

  • Restart_LaunchExceptionWithdrawsRetainedRouteAsTeardown — process-launch exception with a retained route withdraws it as Teardown
  • Restart_ExhaustedAutomaticRestoresEndInTeardownNotEndpointCycle — first unexpected exit is EndpointCycle + restart, the next exit (retry budget spent) is Teardown
  • Restart_CancellationWithdrawsRetainedRouteBeforeDisposingChild — canceled startup withdraws the retained route before the child stops

The publish-failure and startup-timeout tests were updated for the withdraw-before-stop ordering; FakePlatform gained a yield mode and FakeProcessHost launch-exception/exit-trigger hooks so the terminal paths are exercised deterministically.

Required proof pools

  • windows-wsl-dgx-blackwell: local AI managed runtime routing/restart behavior changed (this machine's RTX-class GPU hosts the llama-server runtime; GPU-specific detection did not change).

Validation

All commands run on the current head (7a15b10), Windows 11 ARM64:

  • ./build.ps1 — all builds succeeded.
  • dotnet test ./tests/OpenClaw.Connection.Tests/OpenClaw.Connection.Tests.csproj — 724 passed, 0 failed.
  • dotnet test ./tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj — 2864 passed, 0 failed.
  • dotnet test ./tests/OpenClaw.SetupEngine.Tests/... --filter FullyQualifiedName~LocalAiGpu — 8 passed, 0 failed (focused Local AI GPU restart/endpooint policy tests).
  • dotnet test ./tests/OpenClaw.Shared.Tests/... — 3940 passed, 3 failed; all 3 are pre-existing on the PR base with the diff stashed (ReadmeValidationTests.ReadmeAllowCommandsJsonExample_IsValid fails deterministically on the base commit; BoundedProcessWaitTests, PiperVoiceExtractionTests, and MarkdownParserFuzzTests timing tests pass in isolation and only flake under full-suite parallel load). None touch this PR's subsystems.
  • MXC E2E (validate-mxc-e2e.ps1) not run: no changes to MXC, system.run, src/OpenClaw.Shared/Mxc, or setup/connect E2E paths.

Real behavior proof

Unit-level (deterministic, current head): the three new terminal-path tests fail on the parent commit and pass on this head — they assert the exact lifecycle contract ClawSweeper required: launch exception → quiesce:Teardown with the retained route withdrawn and no child started; retry exhaustion → final exit is quiesce:Teardown while the earlier restart was quiesce:EndpointCycle; cancellation → quiesce:Teardown ordered before the child's stop.

Live gateway restart diagnostics (existing-install restart path): captured on this machine against the pre-existing OpenClawGateway-Dev WSL gateway and existing Local AI install (manifest endpoint http://127.0.0.1:64133/v1, primary llamacpp/qwen3.6-27b-mtp-q4-k-m):

  • Gateway config-audit baseline before restart: 11 entries (last from 2026-09-04 setup).
  • Multiple isolated current-head tray launches exercised the existing-install restart path. After each launch, the gateway audit log stayed at 11 entries — zero configuration writes during restart, confirming the retained-route fast path (Restart_ReusesLastVerifiedPortAndNeverWithdrawsThePublishedRoute) in the live path.
  • Gateway config after restarts: primary: llamacpp/qwen3.6-27b-mtp-q4-k-m, models.providers.llamacpp.baseUrl: http://127.0.0.1:64133/v1 — the managed provider and primary remained published and untouched, so no OpenAI fallback window existed at any point.

Not verified / blocked: the UI-visible chat round trip through the restarted endpoint could not be captured on this head. Every tray launch on this host (including with this PR's diff stashed and after a clean rebuild of the base commit) crashes in Microsoft.UI.Input.dll (0xc0000602, EnableMouseInPointer) during WinUI startup before the UI surface appears — the crash reproduces identically on the PR base commit, so it is a pre-existing environment/SDK issue on this machine, not caused by this PR. The runtime path under the UI (managed llama-server lifecycle + gateway coordinator) is exercised by the isolated launches above and fully covered by the deterministic unit tests.

🤖 Generated with Claude Code

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

🦞👀
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.

@clawsweeper clawsweeper Bot added P1 Urgent regression or broken agent/channel workflow affecting real users now. merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge. Reviewed September 9, 2026, 8:19 PM ET / September 10, 2026, 00:19 UTC (Revision 6).

ClawSweeper review

What this changes

Keeps Local AI selected during endpoint cycles, reuses its previous available port, and adds terminal cleanup and regression tests.

Merge readiness

⛔ Blocked before merge - 5 items remain

This remains useful and is not implemented on current main. Earlier cleanup fixes are present, but the previously reported interrupted-withdrawal defect remains, and the maintainer-requested restart proof is outstanding.

Priority: P1
Reviewed head: 49e9106eb99a64fa823dba84aa33b00c4486485c

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, focused work with positive earlier proof, but one repeated cleanup defect and incomplete restart evidence prevent readiness.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: Earlier screenshots positively show a local-model reply after reinstall. Later 7a15b10 audit-count observations do not show LlamaServerRuntimeService reaching a healthy endpoint and LocalAiGatewayProviderCoordinator completing an existing-install restart that serves a gateway request. That current-head maintainer requirement remains unmet; a redacted terminal trace is sufficient. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: Earlier screenshots positively show a local-model reply after reinstall. Later 7a15b10 audit-count observations do not show LlamaServerRuntimeService reaching a healthy endpoint and LocalAiGatewayProviderCoordinator completing an existing-install restart that serves a gateway request. That current-head maintainer requirement remains unmet; a redacted terminal trace is sufficient. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 10 items Introduced scope: The verified merge-base-to-head diff changes three production files and two test files. The workflow difference belongs to base-branch drift, not this PR.
Current main still clears the primary: Current main restores the fallback or unsets the managed primary during quiescence without distinguishing a temporary endpoint cycle.
Latest release comparison: The supplied latest release still unconditionally quiesces before starting the local server; it does not contain the proposed retained-route startup behavior.
Findings 1 actionable finding [P2] Run terminal cleanup when endpoint withdrawal is interrupted
Security None None.

How this fits together

The Windows companion starts and monitors the local llama-server process. Its gateway coordinator updates the managed WSL gateway’s provider and model selection so agent requests reach that local endpoint.

flowchart TD
 A[Companion startup or restart] --> B[Inspect saved endpoint and listeners]
 B --> C{Previous port available?}
 C -->|Yes| D[Retain route and reuse port]
 C -->|No| E[Withdraw provider for endpoint cycle]
 D --> F[Start and verify local server]
 E --> F
 F -->|Healthy| G[Publish route for gateway requests]
 F -->|Terminal failure| H[Restore terminal routing]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: Earlier screenshots positively show a local-model reply after reinstall. Later 7a15b10 audit-count observations do not show LlamaServerRuntimeService reaching a healthy endpoint and LocalAiGatewayProviderCoordinator completing an existing-install restart that serves a gateway request. That current-head maintainer requirement remains unmet; a redacted terminal trace is sufficient. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Run terminal cleanup when endpoint withdrawal is interrupted (P2) - On an existing install with no fallback and an occupied previous port, EndpointCycle can remove the provider and then fail or throw during verification. This call is outside the cleanup catches, and the failure return occurs before terminalTeardownRequired is set, leaving llamacpp/&lt;alias> selected without a provider or pending restart. This repeats the previous review’s unresolved finding. The same partial-withdrawal outcome occurs in QuiesceOrStopAsync and the automatic-exit handler when they abandon a cycle. Attempt non-cancelable teardown on these terminal paths and assert final primary/provider state after cancellation and failed verification.
  • Resolve merge risk (P1) - An interrupted endpoint cycle can leave an existing installation selecting a managed primary whose provider has been removed, with no recovery scheduled.
  • Resolve merge risk (P1) - The supplied current-run diagnostics do not establish successful existing-install restart and inference; unchanged configuration during a crashing launch is inconclusive.
  • Complete next step (P2) - Repair interrupted-withdrawal cleanup and provide current-head proof of a healthy existing-install restart serving a gateway request. Redact private details from terminal output or diagnostic recordings before updating the PR body.

Findings

  • [P2] Run terminal cleanup when endpoint withdrawal is interrupted — src/OpenClaw.Connection/LocalAi/LlamaServerRuntimeService.cs:205-210
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production and test growth Production +186 net lines; tests +404 net lines The growth supports retained routing, terminal cleanup, and lifecycle regression coverage across five files.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #1293
Summary: This PR is a candidate repair for the companion-side configuration gap established in the related issue’s discussion.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Finish terminal cleanup and verify restart (recommended)
    Handle partial endpoint withdrawal across startup, refresh, and automatic restart, then demonstrate restored configuration and a successful existing-install gateway request.

Technical review

Best possible solution:

Preserve local selection through recoverable cycles, restore terminal routing on every abandoned cycle, and verify existing-install recovery through a real gateway request.

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

Yes, from source: interrupt or fail the verification read after EndpointCycle removes the provider on a no-fallback install; terminal cleanup is bypassed. This review did not execute that regression.

Is this the best way to solve the issue?

Yes in direction: the existing lifecycle and coordinator are the right owners, and real fallback preferences remain preserved. The implementation still needs complete handling of partially completed withdrawal.

Full review comments:

  • [P2] Run terminal cleanup when endpoint withdrawal is interrupted — src/OpenClaw.Connection/LocalAi/LlamaServerRuntimeService.cs:205-210
    On an existing install with no fallback and an occupied previous port, EndpointCycle can remove the provider and then fail or throw during verification. This call is outside the cleanup catches, and the failure return occurs before terminalTeardownRequired is set, leaving llamacpp/&lt;alias> selected without a provider or pending restart. This repeats the previous review’s unresolved finding. The same partial-withdrawal outcome occurs in QuiesceOrStopAsync and the automatic-exit handler when they abandon a cycle. Attempt non-cancelable teardown on these terminal paths and assert final primary/provider state after cancellation and failed verification.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence. Earlier screenshots positively show a local-model reply after reinstall. Later 7a15b10 audit-count observations do not show LlamaServerRuntimeService reaching a healthy endpoint and LocalAiGatewayProviderCoordinator completing an existing-install restart that serves a gateway request. That current-head maintainer requirement remains unmet; a redacted terminal trace is sufficient.

Label justifications:

  • P1: The linked reproduction shows first Local AI prompts failing through an unrelated provider during companion startup.
  • merge-risk: 🚨 auth-provider: New primary retention can survive a failed provider withdrawal and leave gateway routing without a usable provider.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Earlier screenshots positively show a local-model reply after reinstall. Later 7a15b10 audit-count observations do not show LlamaServerRuntimeService reaching a healthy endpoint and LocalAiGatewayProviderCoordinator completing an existing-install restart that serves a gateway request. That current-head maintainer requirement remains unmet; a redacted terminal trace is sufficient. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence. Earlier screenshots positively show a local-model reply after reinstall. Later 7a15b10 audit-count observations do not show LlamaServerRuntimeService reaching a healthy endpoint and LocalAiGatewayProviderCoordinator completing an existing-install restart that serves a gateway request. That current-head maintainer requirement remains unmet; a redacted terminal trace is sufficient.

Evidence

What I checked:

Likely related people:

  • joelagnel: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • karkarl: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Cover cancellation and failed verification after provider removal, asserting final primary/provider state across terminal cycle paths.
  • Provide current-head windows-wsl-dgx-blackwell evidence of a healthy existing-install restart and successful gateway request, retaining the earlier fresh-install evidence.
  • Update validation and proof in the PR body, redacting private details; this should trigger re-review, or a maintainer can comment @clawsweeper re-review.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-09-04T05:06:07.611Z sha a523555 :: needs real behavior proof before merge. :: [P1] Withdraw a retained route when native launch fails
  • reviewed 2026-09-04T07:33:48.537Z sha a523555 :: needs real behavior proof before merge. :: [P1] Withdraw a retained route when native launch fails
  • reviewed 2026-09-04T17:16:38.025Z sha a523555 :: needs real behavior proof before merge. :: [P1] Tear down retained routing on terminal startup failures | [P1] Use teardown after automatic restart attempts are exhausted
  • reviewed 2026-09-09T00:23:50.229Z sha 7a15b10 :: needs real behavior proof before merge. :: [P1] Handle cancellation during preset preparation | [P2] Tear down the retained primary when a port-change attempt fails
  • reviewed 2026-09-09T23:26:03.714Z sha 49e9106 :: needs real behavior proof before merge. :: [P2] Run terminal cleanup when endpoint withdrawal is interrupted

@larroy

larroy commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

Proof: reinstalled the windows node app using local inference, first request goes directly to the local model, no spurious openai fallback attempt. See screenshot.

Screenshot 2026-09-04 at 12 11 56 AM

@larroy

larroy commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author
Screenshot 2026-09-04 at 12 13 57 AM

@larroy

larroy commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper provided proof

@larroy
larroy marked this pull request as ready for review September 4, 2026 07:27
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 4, 2026
@larroy

larroy commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review again and provide feedback on proof status.

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 4, 2026
@shanselman

Copy link
Copy Markdown
Collaborator

@clawsweeper rereview...what's the issue dude?

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

🦞👀
ClawSweeper assist is taking a look at your question.

I queued a lightweight read-only assist pass. It will post a separate answer comment and will not edit the durable ClawSweeper review comment or trigger close, merge, repair, label, or branch changes.

Request: rereview...what's the issue dude?

@clawsweeper

clawsweeper Bot commented Sep 4, 2026

Copy link
Copy Markdown

ClawSweeper assist: The remaining issue is not the screenshot itself; it’s that the prior review identified two P1 terminal-failure paths that may still leave retained Local AI routing active:

  • native launch failure needs to withdraw the retained route
  • exhausted automatic restart attempts need teardown/route withdrawal

The supplied screenshots are evidence of a fresh install’s first request reaching Local AI, but they do not demonstrate the existing-install restart path or terminal recovery paths on the current head.

Evidence:

Suggested next action: For a full current-head correctness assessment, request @clawsweeper review; if those failure paths need changes, use the existing repair command.


Source: #1321 (comment)
Assist reasoning: high.

plarroy-nv and others added 2 commits September 8, 2026 14:44
On every companion start, EnsureStartedCoreAsync quiesced the gateway
route, started llama-server, probed it, and only then republished. With
no prior model to restore, quiesce unset agents.defaults.model.primary
outright -- and an absent primary is not "no routing", it is the
gateway's built-in default:

    parseModelRef(... ?? "gpt-5.6-sol", "openai", ...)

So any prompt sent during that window was dispatched to openai and
failed with ProviderAuthError / missing-provider-auth on a Local
AI-only install. The window was ~10s and reproduced on every launch,
because requestedPort is 0 and the OS-assigned port made the previously
published baseUrl stale by construction.

Retain the managed primary across an endpoint cycle. QuiesceAsync now
takes a LocalAiQuiesceReason: EndpointCycle keeps llamacpp/<alias> in
place so a mid-cycle request fails as Local AI rather than as an
unrelated provider, while Teardown (stop, shutdown, failed publish)
still restores whatever preceded Local AI.

Reuse the last verified port when it is free, and skip the quiesce
entirely when the published route already names the port about to be
bound. The normal restart now performs zero config writes; PublishAsync
re-verifies and no-ops. A route is only withdrawn when the endpoint
genuinely moves.

Deciding the port before touching routing exposed a latent bug: the
port-conflict and ownership-unknown paths returned Conflict without
withdrawing the published route, leaving the gateway aimed at a port a
foreign process owns. FailStartupAsync now takes a route to withdraw,
and every startup-failure path passes it when one was left standing.

Refs openclaw#1293

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
ClawSweeper review of PR openclaw#1321 identified two terminal lifecycle paths
that could leave the gateway configured for a Local AI provider nothing
would serve:

1. With a retained route (last-verified port reuse), a process-launch
   exception, immediate child exit, probe failure, or cancellation hit
   the catch handlers in EnsureStartedCoreAsync, which only disposed the
   child. The gateway kept routing to the retained port with no listener.
   Both catch paths now withdraw the retained route with teardown
   semantics before the child's listener disappears.

2. HandleManagedProcessExitedAsync always quiesced with EndpointCycle
   semantics even when automatic restart attempts were exhausted, so the
   managed primary stayed selected with its provider absent and no
   republish to follow. The exit handler now picks the quiesce reason
   from whether a restart will actually run: EndpointCycle for a pending
   restart, Teardown once the retry budget is spent.

FailStartupAsync also now withdraws a retained route before disposing
the child (previously after), matching the lifecycle contract that
managed routing is removed before a listener can disappear.

Tests: three new regression tests cover launch exception, retry
exhaustion, and cancellation with a retained route; the publish-failure
and startup-timeout tests were updated for the withdraw-before-stop
ordering.

Validation: build.ps1 clean; OpenClaw.Connection.Tests 724/724,
OpenClaw.Tray.Tests 2864/2864, OpenClaw.SetupEngine.Tests
LocalAiGpu 8/8 pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@larroy
larroy force-pushed the dev/plarroy/local-ai-no-openai-fallback branch from a523555 to 7a15b10 Compare September 9, 2026 00:20
@larroy

larroy commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

Both P1 findings from the previous review are fixed on the new head 7a15b10:

  1. Terminal startup failures now withdraw retained routing. The catch handlers in EnsureStartedCoreAsync (process-launch exception, immediate child exit, cancellation) withdraw the retained route with Teardown semantics before the child's listener disappears. Covered by Restart_LaunchExceptionWithdrawsRetainedRouteAsTeardown and Restart_CancellationWithdrawsRetainedRouteBeforeDisposingChild.

  2. Exhausted automatic restarts use teardown. HandleManagedProcessExitedAsync picks the quiesce reason from whether a restart will actually run: EndpointCycle for a pending restart, Teardown once the retry budget is spent. Covered by Restart_ExhaustedAutomaticRestoresEndInTeardownNotEndpointCycle.

FailStartupAsync also withdraws before disposing the child, matching the remove-routing-before-listener-disappears contract.

Proof status:

  • Live gateway existing-install restart diagnostics: config-audit.jsonl stayed at its 11-entry baseline across multiple isolated current-head tray launches (zero config writes, retained provider + primary untouched), confirming no OpenAI fallback window.
  • UI chat round trip is blocked by a pre-existing EnableMouseInPointer crash (0xc0000602 in Microsoft.UI.Input.dll) that reproduces identically with this PR's diff stashed and on a clean rebuild of the base commit; documented under Not verified / blocked in the PR body.
  • Validation: build clean, Connection 724/724, Tray 2864/2864, LocalAiGpu 8/8. Shared.Tests has 3 failures that reproduce on the PR base with the diff stashed; details in the PR body.

@clawsweeper

clawsweeper Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. labels Sep 9, 2026
@karkarl

karkarl commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

Maintainer verdict: HOLD_FOR_AUTHOR on current head \7a15b100\ (take confidence 40%, recommendation confidence 99%). The direction is valuable, but two terminal cleanup gaps remain: cancellation during preset preparation can leave retained routing published, and a failed port-relocation attempt can leave the managed primary selected after the provider is removed. Please repair both paths, add focused regressions, and provide current-head \windows-wsl-dgx-blackwell\ proof that an existing-install restart reaches a healthy endpoint and serves a gateway request. The current CI Gate failure is in unchanged \SystemRun_Where_ReturnsExpectedOutput\ infrastructure and is not the reason for this hold.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: d0dbb47f-7bb0-4294-bda6-60b2a8b5fc55
@clawsweeper clawsweeper Bot added merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. and removed merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. labels Sep 9, 2026
@shanselman shanselman added the status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. label Sep 10, 2026
@clawsweeper clawsweeper Bot added the proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. label Sep 10, 2026
@shanselman

Copy link
Copy Markdown
Collaborator

Superseded by #1390 (fix(local-ai): keep routing safe across endpoint restarts), rebuilt from current main with terminal cleanup, retry-exhaustion, cancellation, setup rollback, and UI recovery coverage.

@shanselman shanselman closed this Sep 10, 2026
@shanselman shanselman removed the status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. label Sep 10, 2026
shanselman added a commit that referenced this pull request Sep 10, 2026
* fix(local-ai): stop routing to OpenAI while the endpoint restarts

On every companion start, EnsureStartedCoreAsync quiesced the gateway
route, started llama-server, probed it, and only then republished. With
no prior model to restore, quiesce unset agents.defaults.model.primary
outright -- and an absent primary is not "no routing", it is the
gateway's built-in default:

    parseModelRef(... ?? "gpt-5.6-sol", "openai", ...)

So any prompt sent during that window was dispatched to openai and
failed with ProviderAuthError / missing-provider-auth on a Local
AI-only install. The window was ~10s and reproduced on every launch,
because requestedPort is 0 and the OS-assigned port made the previously
published baseUrl stale by construction.

Retain the managed primary across an endpoint cycle. QuiesceAsync now
takes a LocalAiQuiesceReason: EndpointCycle keeps llamacpp/<alias> in
place so a mid-cycle request fails as Local AI rather than as an
unrelated provider, while Teardown (stop, shutdown, failed publish)
still restores whatever preceded Local AI.

Reuse the last verified port when it is free, and skip the quiesce
entirely when the published route already names the port about to be
bound. The normal restart now performs zero config writes; PublishAsync
re-verifies and no-ops. A route is only withdrawn when the endpoint
genuinely moves.

Deciding the port before touching routing exposed a latent bug: the
port-conflict and ownership-unknown paths returned Conflict without
withdrawing the published route, leaving the gateway aimed at a port a
foreign process owns. FailStartupAsync now takes a route to withdraw,
and every startup-failure path passes it when one was left standing.

Refs #1293

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(local-ai): route terminal startup outcomes through teardown

ClawSweeper review of PR #1321 identified two terminal lifecycle paths
that could leave the gateway configured for a Local AI provider nothing
would serve:

1. With a retained route (last-verified port reuse), a process-launch
   exception, immediate child exit, probe failure, or cancellation hit
   the catch handlers in EnsureStartedCoreAsync, which only disposed the
   child. The gateway kept routing to the retained port with no listener.
   Both catch paths now withdraw the retained route with teardown
   semantics before the child's listener disappears.

2. HandleManagedProcessExitedAsync always quiesced with EndpointCycle
   semantics even when automatic restart attempts were exhausted, so the
   managed primary stayed selected with its provider absent and no
   republish to follow. The exit handler now picks the quiesce reason
   from whether a restart will actually run: EndpointCycle for a pending
   restart, Teardown once the retry budget is spent.

FailStartupAsync also now withdraws a retained route before disposing
the child (previously after), matching the lifecycle contract that
managed routing is removed before a listener can disappear.

Tests: three new regression tests cover launch exception, retry
exhaustion, and cancellation with a retained route; the publish-failure
and startup-timeout tests were updated for the withdraw-before-stop
ordering.

Validation: build.ps1 clean; OpenClaw.Connection.Tests 724/724,
OpenClaw.Tray.Tests 2864/2864, OpenClaw.SetupEngine.Tests
LocalAiGpu 8/8 pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* fix(local-ai): teardown terminal restart failures

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: d0dbb47f-7bb0-4294-bda6-60b2a8b5fc55

* fix(local-ai): teardown interrupted endpoint cycles

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): keep routing safe across restarts

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): harden terminal restart cleanup

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): complete terminal cleanup retries

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): preserve restart privacy invariants

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): close interrupted lifecycle gaps

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* test(local-ai): assert refresh teardown

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): preserve explicit stop intent

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): expose failed cleanup recovery

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): preserve runtime on refresh cancellation

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): reconcile canceled and missing restarts

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): keep failed stops quiesced

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): keep preserved listeners stop-only

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): preserve pending route recovery

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): stop untrusted listeners on cleanup failure

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): honor stop during automatic retry

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): keep failed shutdown retryable

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* test(local-ai): consolidate unsafe startup coverage

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* test(local-ai): trim review-only commentary

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): complete final process disposal

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* docs(local-ai): tighten lifecycle comments

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* docs(local-ai): remove redundant routing comments

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): surface retained shutdown failures

Bound post-cancellation route recovery, publish retryable ownership when process shutdown fails, and cover teardown failure after retry exhaustion.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

* fix(local-ai): clarify interrupted route recovery

Make endpoint-cycle recovery state explicit and drive the manifest-lock cancellation test causally.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa

---------

Co-authored-by: Pedro Larroy <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Karen Lai <[email protected]>
Copilot-Session: d0dbb47f-7bb0-4294-bda6-60b2a8b5fc55
Copilot-Session: fe99977b-465c-4796-a6ae-436b4b11f6fa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. P1 Urgent regression or broken agent/channel workflow affecting real users now. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants