Skip to content

fix(openai): a stateless stream refused a permit ends its conversation; mapping deletes match - #1355

Merged
ginccc merged 2 commits into
mainfrom
fix/v1-bridge
Nov 12, 2026
Merged

ginccc merged 2 commits into
mainfrom
fix/v1-bridge

Conversation

@ginccc

@ginccc ginccc commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Three small defects in the OpenAI-compatible /v1 adapter, found in the whole-codebase review (MOD-16, NEW-channels-2, NEW-gap-modules-integrations-5).

A stateless stream refused a permit left its conversation open

chatCompletions calls bridge.prepare, which for a stateless model (…:stateless or "stateless": true) starts the throwaway conversation immediately, and then releases its permit. The SSE body re-acquires a permit when it runs. If that fails, it writes the in-band 429 error event and returns without calling bridge.stream — and stream()'s finally was the only place a streamed stateless conversation was ended.

Failure scenario: max-concurrent-requests=64, a burst of 100 Open WebUI title requests pointed at a :stateless model with stream: true. Every body that loses the permit race answers "Too many concurrent requests" and leaves one READY conversation behind, which nothing ever ends. The sync path was fine (say() ends it in finally).

Fix: a new OpenAiConversationBridge.abandon(PreparedTurn) ends a stateless turn's conversation and does nothing for a stateful one (that conversation belongs to the chat). The refused body calls it before writing the error. The stream() Javadoc now says every exit ends a stateless turn and that a never-streamed turn goes to abandon.

Unconditional mapping deletes split a chat across two conversations

When a chat's mapped conversation has ended (idle sweep, rollover), the bridge deletes the mapping and starts a new conversation. Open WebUI sends a chat's completion and its title request together, with the same chat id — the bridge's own comment calls this routine. Both read the ended mapping. A deletes it, starts a, writes the mapping. B, which read the old mapping earlier, then runs deleteUserConversation(intent, userId) — unconditional — removing A's fresh mapping, starts b and writes that. Conversation a stays open and orphaned, and the chat continues in b without A's turn.

Fix: every mapping delete in the bridge (stale mapping, new-chat supersede, ended legacy mapping, legacy re-key, mid-turn self-heal) goes through IUserConversationStore.deleteUserConversationIfMatches with the conversation id the request read. That primitive exists for exactly this race and Slack and the webhook handler already use it. B's delete now matches nothing, its create collides with A's mapping, and the existing insert-conflict re-read adopts a and ends B's own fresh conversation.

Model resolution probed access by exception, and cached a failed catalogue

AgentModelResolver.mayUse called requireAgentUseAccess and caught the exception. For every agent the caller may not use, that logs WARN Use check failed… and builds a ForbiddenException. GET /v1/models runs it per catalogue entry and Open WebUI polls it, so a deployment with 150 private agents wrote 150 WARN lines per listing (and resolve() did the same). It now asks ResourceAccessGuard.hasAccess(agentId, AccessLevel.USE), which is documented to be true exactly when requireUseAccess would pass, including the legacy fallback for a missing descriptor.

Separately, when getAllLatestAgents threw, buildCatalogue returned an empty catalogue that Caffeine cached for model-cache-seconds (30 s), so a one-off store error made every model "unknown" for 30 s. The loader now returns null on failure (Caffeine does not store it) and that one call gets an empty view.

Decisions

Choice Rejected Why
bridge.abandon(turn) Calling endConversation from the adapter The bridge owns the stateless-turn lifecycle (say/stream end it in finally); the adapter should not need to know which turns own a throwaway conversation.
Keep the prepare-time start and the X-EDDI-Conversation-Id header Start the stateless conversation lazily inside the body The header must name the conversation before the body runs; a lazy start would drop it or need a second mechanism.
No hook for "body never runs" (yet) A response-close callback That case is real (see below), but closing it needs a hook on the Vert.x response that cannot be checked without a live server. It is a follow-up, and it does not change abandon.
Loader returns null on failure Throwing from the loader Same effect in Caffeine (not stored), but null keeps the failure log in one place and avoids an exception round-trip through cache.get.

What this changes for users and operators

  • /v1 request and response shapes, REST paths, config keys and defaults are unchanged.
  • A stateless stream refused by the concurrency cap no longer leaves a conversation open.
  • Two concurrent requests for a chat whose conversation has ended now land in one new conversation (the second may still get the usual 429 from ConversationCoordinator if both hit it at the same instant; clients retry).
  • GET /v1/models no longer logs a WARN per hidden agent.
  • A transient agent-listing failure affects only the request that saw it, not the next 30 s.
  • docs/open-webui-integration.md: the model-cache-seconds row and the "two requests in one chat" row say so.

Where to look hardest

  • Scope, checked against every streaming entry point: this PR covers one way a /v1 stream body gives up before stream(), a body that runs but is refused a permit. A body the server never invokes still leaves a stateless conversation open until the idle sweep; that gap has no owner yet, and fix(openai): cancel a /v1 stream's turn when its client leaves or times out #1404 does not close it because its checks sit inside stream(). No other streaming entry point creates something before a deferred body: native and group SSE do their work in the resource method, the A2A body only drains a queue whose turn settles on its own, and the ratings export creates nothing before its body.

  • The "body never runs" case, which this PR does not cover. In RESTEasy Reactive 3.40.1 a closed connection sets connectionClosed, and ResteasyReactiveRequestContext.isHandlerCanceled then skips every remaining cancellable handler. ResponseWriterHandler, which invokes the StreamingOutput, keeps the default isCancellable() == true. So a client that disconnects after prepare() has started a stateless conversation, but before the response is written, leaves that conversation open until the idle sweep (maximumLifeTimeOfIdleConversationsInDays, 90 days by default) ends it. This was read from the library source, not reproduced against a live server. It is the same window the adapter's existing permit comment guards against. The window is much narrower than the permit-refused case fixed here, and is listed as a follow-up.

  • OpenAiConversationBridge.getOrCreateConversation, the newChat branch: the supersede delete is now conditional too. Two requests that open a history-keyed chat with the same words at the same instant now converge on one conversation instead of B silently deleting A's mapping. Since history-keyed chats share the intent from their second turn on anyway, this matches what happens one turn later.

  • AgentModelResolver.mayUse: hasAccess answers false for a blank id where requireUseAccess returned (passed). Catalogue entries always carry the deployed agent's id, so this does not change who sees what.

Verification

  • ./mvnw -o -q -DskipUi=true compile — exit 0.

  • Red run before the fix (abandon as an empty stub, everything else unchanged), ./mvnw -o -DskipUi=true test -Dtest='RestOpenAiAdapterTest,OpenAiConversationBridgeTest,OpenAiBridgeSessionAndErrorTest,AgentModelResolverTest': 137 tests, 15 failures and 1 error, each for the item's reason: the adapter test "Wanted but not invoked: abandon(conv-2)"; the race test "expected …03 but was …01" (the chat split); the cache test "expected 2 but was 0"; useGate_asksWithoutThrowing listed the private agent; the conditional-delete verifies were not met.

  • Green run, same command: 137 tests, 0 failures.

  • Final run with the guard classes: ./mvnw -o -DskipUi=true test -Dtest='RestOpenAiAdapterTest,OpenAiConversationBridgeTest,OpenAiBridgeSessionAndErrorTest,AgentModelResolverTest,ImportStyleTest,BuildQualityGatesTest,ChangelogRotationTest,ChangelogFragmentTest,DocumentationLinksTest,DocumentationAccuracyTest,DocumentedRestPathsTest,DeploymentManifestsTest' — BUILD SUCCESS, 325 tests, 0 failures, 1 skipped (a pre-existing skip in DeploymentManifestsTest); a surefire report exists for all 12 named classes.

  • Mutation check: the red run above is the pre-fix code for every key line (no abandon call, an empty abandon, unconditional deletes, the catching mayUse, the cached empty catalogue), and each new or changed test failed against it.

  • Independent review mutation check: three mutants together (the plain delete back in deleteMappingIfMatches, no abandon call in the adapter, and a cached empty catalogue on a listing failure). -Dtest='RestOpenAiAdapterTest,OpenAiConversationBridgeTest,AgentModelResolverTest' gave 107 tests and 8 failures, each for its own item. After restoring them, the 12-class run above was repeated: 325 tests, 0 failures, 1 pre-existing skip, and 12/12 reports.

Not run locally: the full unit suite, integration tests (*IT) and the UI suites, left to CI.

Follow-ups

  • MOD-17 (D39) builds on the conditional delete introduced here.
  • End a stateless streamed turn's conversation when its response is disposed without the body having run (the client-disconnect window described above).

Summary by CodeRabbit

  • Bug Fixes
    • Fixed recovery when a chat’s conversation has ended, so concurrent requests can use the same replacement conversation without losing its mapping.
    • Refused stateless streaming requests now clean up their temporary conversations.
    • Model access checks no longer rely on exceptions. Failed agent listings are retried on the next request instead of being cached as empty.
  • Documentation
    • Clarified model-listing retry behavior and how concurrent requests handle ended conversations.

…ing deletes match

- A streaming body refused a concurrency permit returned without calling
  bridge.stream(), so the stateless conversation prepare() had started was
  never ended. New OpenAiConversationBridge.abandon(turn) ends a stateless
  turn's conversation; the refused body calls it.
- Every mapping delete in the bridge now uses
  deleteUserConversationIfMatches with the conversation the request read, so
  concurrent requests for a chat whose conversation ended (Open WebUI's
  completion and title request) converge on one new conversation instead of
  the slower one deleting the faster one's fresh mapping.
- AgentModelResolver asks ResourceAccessGuard.hasAccess(id, USE) instead of
  catching requireAgentUseAccess (a WARN and an exception per hidden agent on
  every polled GET /v1/models), and no longer caches the empty catalogue a
  failed agent listing produced for model-cache-seconds.
… the changelog

The fragment said a StreamingOutput body that never runs is unreachable.
RESTEasy Reactive skips every cancellable handler once the connection
closes, and ResponseWriterHandler is cancellable, so a client that
disconnects after prepare() started a stateless conversation still
leaves it open. Say so, and list the completion hook as a follow-up.
@ginccc
ginccc requested a review from rolandpickl as a code owner November 7, 2026 21:43
@vercel

vercel Bot commented Nov 7, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
eddi-docs Ignored Ignored Nov 7, 2026 9:43pm UTC

Request Review

@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

⚠️ Deprecation Warning: The deny-licenses option is deprecated for possible removal in the next major release. For more information, see issue 997.

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

@coderabbitai

coderabbitai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The /v1 adapter now checks agent USE access without a throwing access check, avoids caching failed agent listings, and conditionally removes conversation mappings. It can also abandon unrun stateless turns, including when a streaming request cannot acquire a concurrency permit.

Changes: OpenAI-compatible adapter fixes

Layer / File(s) Summary
Agent model resolution
src/main/java/ai/labs/eddi/integrations/openai/AgentModelResolver.java, src/test/java/ai/labs/eddi/integrations/openai/AgentModelResolverTest.java, docs/open-webui-integration.md
USE access checks now use hasAccess. A failed agent listing returns an empty catalogue for that call and is not cached, allowing a later request to retry. Tests cover access denial and listing recovery.
Conversation mapping and stateless-turn cleanup
src/main/java/ai/labs/eddi/integrations/openai/OpenAiConversationBridge.java, src/main/java/ai/labs/eddi/integrations/openai/RestOpenAiAdapter.java, src/test/java/ai/labs/eddi/integrations/openai/OpenAi*Test.java, docs/open-webui-integration.md, docs/changelog.d/2026-11-07-v1-bridge.md
Mapping cleanup now removes a mapping only if it still identifies the conversation being replaced. abandon ends an unrun stateless turn but leaves stateful conversations open. The adapter abandons a turn when it cannot acquire a streaming permit. Tests cover mapping races and abandonment. The changelog notes a remaining disconnect-before-body cleanup gap.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Merge Risk: Minimal · up to ac882

No merge-blocking issue was established in the adapter changes. The documented disconnect-before-streaming-body cleanup gap remains follow-up work.

Security architecture risk: Low · up to ac882

The changes improve cleanup and prevent concurrent requests from replacing each other’s conversation mappings. No broader access was demonstrated, but early-disconnect cleanup and some failure-recovery behavior remain incompletely verified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — The changed deletion path is scoped to the existing user-and-intent mapping plus the observed conversation identifier. Abandonment targets only the conversation carried by a stateless prepared turn, rather than ending a stateful conversation owned by the chat.

Trust Boundaries and Controls

  • observed — The non-throwing access check still derives effective permissions from the current security context and stored descriptor. A descriptor-store failure denies access rather than granting it, preserving the former fail-closed outcome for that failure class.

Resilience and Maintainability Implications

  • inferred — A stateless conversation can remain open if response processing stops after preparation but before the streaming body executes: both abandonment and streaming cleanup require body invocation. This window already exists in the comparison base and is explicitly documented as outside this fix; framework cancellation and eventual idle-sweep recovery were not independently verified.

Hardening Proposals

  • proposed — Validate response cancellation against a live server, then provide a response-lifecycle cleanup mechanism for prepared stateless turns whose body never executes. Cleanup should coordinate with normal streaming termination to avoid ending an active turn twice and must preserve stateful chat ownership.
Pre-merge checks: Passed 5

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names two of the three fixes in the PR: abandoned stateless streams now end their conversation, and mapping deletes now match the expected conversation. It omits the third change, the AgentM…
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names two of the three fixes in the PR: abandoned stateless streams now end their conversation, and mapping deletes now match the expected conversation. It omits the third change, the AgentModelResolver access check and empty-catalogue caching fix. The title is specific and accurate for the main bridge change, and it does not describe anything absent from the changeset. Its phrasing is dense, and the 86-character length is slightly long for a scanning reader.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 8 functions across 7 files. (2 skipped: 2 unsupported.)

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
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 7941944 and ac88247.

Files selected for processing: 9

  • docs/changelog.d/2026-11-07-v1-bridge.md
  • docs/open-webui-integration.md
  • src/main/java/ai/labs/eddi/integrations/openai/AgentModelResolver.java
  • src/main/java/ai/labs/eddi/integrations/openai/OpenAiConversationBridge.java
  • src/main/java/ai/labs/eddi/integrations/openai/RestOpenAiAdapter.java
  • src/test/java/ai/labs/eddi/integrations/openai/AgentModelResolverTest.java
  • src/test/java/ai/labs/eddi/integrations/openai/OpenAiBridgeSessionAndErrorTest.java
  • src/test/java/ai/labs/eddi/integrations/openai/OpenAiConversationBridgeTest.java
  • src/test/java/ai/labs/eddi/integrations/openai/RestOpenAiAdapterTest.java

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

@ginccc
ginccc merged commit 90466e1 into main Nov 12, 2026
46 checks passed
@ginccc ginccc changed the title fix(openai): abandoned stateless streams end their conversation; mapping deletes match fix(openai): a stateless stream refused a permit ends its conversation; mapping deletes match Nov 12, 2026
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