[GH-ISSUE #3038] [Issue]: Changing a connection's provider via PATCH can leave two connections marked defaultForAgents, making agent selection ambiguous #1606

Closed
opened 2026-10-21 05:40:35 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @kolacheee on GitHub (Jun 29, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3038

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong

The "at most one non-image connection is the default for agents" invariant is only enforced when a PATCH body includes defaultForAgents. If a raw API call changes only a connection's provider (moving it between the image-generation and non-image categories) without re-sending defaultForAgents, the dedupe block is skipped. A connection that was the image-generation default can become a non-image default while a legitimate text default already exists — so getDefaultForAgents() now finds two candidates and returns whichever its unordered query yields first. Agents may resolve to the wrong connection. (The ConnectionEditor UI always sends defaultForAgents, so this is reachable only via the raw API.)

How to reproduce (try it yourself)

  1. Have a non-image connection A with defaultForAgents='true'.
  2. Have an image_generation connection B with defaultForAgents='true' (allowed — separate category).
  3. PATCH /api/connections/{B.id} with body {"provider":"openai"} only (no defaultForAgents).

You'll see: B's effectiveProvider becomes openai but the unset-others block is skipped (because data.defaultForAgents is undefined), so B keeps defaultForAgents='true'. Now both A and B are non-image defaults; getDefaultForAgents() returns whichever the unordered query yields first.

Expected: after the provider change, exactly one non-image connection remains the default for agents.

Where it is

packages/server/src/services/storage/connections.storage.ts: the update() dedupe block gated on if (data.defaultForAgents !== undefined) (lines 136-156; effectiveProvider at line 118), and getDefaultForAgents()'s unordered select + .find (lines 37-42). Reachable via connections.routes.ts:260-265 (createConnectionSchema.partial().parse). The UI always sends defaultForAgents at packages/client/src/components/connections/ConnectionEditor.tsx:462.

What's happening

The category-uniqueness enforcement is gated on data.defaultForAgents being supplied, but a provider change alone moves a row between the image/non-image categories, invalidating the previously-maintained invariant without triggering re-enforcement. getDefaultForAgents() then resolves the ambiguity with an unordered .find(), so the chosen row is non-deterministic.

Suggested fix

Enforce the invariant on a provider change too. In connections.storage.ts:

  1. Add ne to the drizzle import (line 4): import { eq, desc, and, ne } from "drizzle-orm";
  2. Immediately AFTER the existing if (data.defaultForAgents !== undefined) { ... } block, add an else if that runs only when defaultForAgents was NOT sent and the edited row is already a default, and which excludes the edited row's own id so it stays the sole default in its new category:
} else if (data.provider !== undefined && existing.defaultForAgents === "true") {
  if (effectiveProvider === "image_generation") {
    await db.update(apiConnections).set({ defaultForAgents: "false" }).where(
      and(
        eq(apiConnections.defaultForAgents, "true"),
        eq(apiConnections.provider, "image_generation"),
        ne(apiConnections.id, id),
      ),
    );
  } else {
    const existingDefaults = await db.select().from(apiConnections).where(eq(apiConnections.defaultForAgents, "true"));
    for (const row of existingDefaults) {
      if (row.id !== id && row.provider !== "image_generation") {
        await db.update(apiConnections).set({ defaultForAgents: "false" }).where(eq(apiConnections.id, row.id));
      }
    }
  }
}

This keeps the edited row's defaultForAgents='true' and demotes any conflicting default in the category it just moved into, in both directions (covered by branching on effectiveProvider).

Regression avoided: do NOT just reuse the existing dedupe blocks for the provider-change case. Those blocks unset every default in the target category without excluding the edited row, and rely on the subsequent updateFields.defaultForAgents = "true" write to re-set it — which does not run when defaultForAgents isn't in the body. Reusing them as-is would demote the edited row itself, leaving ZERO defaults (a different but equally wrong bug). The new block excludes the edited row's own id and runs only when defaultForAgents is absent, so it never double-runs with the existing block. Optionally add .orderBy(desc(apiConnections.updatedAt)) to getDefaultForAgents()/getDefaultForImageGeneration() for deterministic resolution of any pre-existing duplicate state — but that alone is insufficient, since it leaves two defaultForAgents='true' rows persisted.


AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.

Originally created by @kolacheee on GitHub (Jun 29, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3038 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** The "at most one non-image connection is the default for agents" invariant is only enforced when a PATCH body includes `defaultForAgents`. If a raw API call changes only a connection's `provider` (moving it between the image-generation and non-image categories) without re-sending `defaultForAgents`, the dedupe block is skipped. A connection that was the image-generation default can become a *non-image* default while a legitimate text default already exists — so `getDefaultForAgents()` now finds two candidates and returns whichever its unordered query yields first. Agents may resolve to the wrong connection. (The ConnectionEditor UI always sends `defaultForAgents`, so this is reachable only via the raw API.) **How to reproduce (try it yourself)** 1. Have a non-image connection A with `defaultForAgents='true'`. 2. Have an `image_generation` connection B with `defaultForAgents='true'` (allowed — separate category). 3. `PATCH /api/connections/{B.id}` with body `{"provider":"openai"}` only (no `defaultForAgents`). You'll see: B's `effectiveProvider` becomes `openai` but the unset-others block is skipped (because `data.defaultForAgents` is undefined), so B keeps `defaultForAgents='true'`. Now both A and B are non-image defaults; `getDefaultForAgents()` returns whichever the unordered query yields first. Expected: after the provider change, exactly one non-image connection remains the default for agents. **Where it is** `packages/server/src/services/storage/connections.storage.ts`: the `update()` dedupe block gated on `if (data.defaultForAgents !== undefined)` (lines 136-156; `effectiveProvider` at line 118), and `getDefaultForAgents()`'s unordered `select` + `.find` (lines 37-42). Reachable via `connections.routes.ts:260-265` (`createConnectionSchema.partial().parse`). The UI always sends `defaultForAgents` at `packages/client/src/components/connections/ConnectionEditor.tsx:462`. **What's happening** The category-uniqueness enforcement is gated on `data.defaultForAgents` being supplied, but a provider change alone moves a row between the image/non-image categories, invalidating the previously-maintained invariant without triggering re-enforcement. `getDefaultForAgents()` then resolves the ambiguity with an unordered `.find()`, so the chosen row is non-deterministic. **Suggested fix** Enforce the invariant on a provider change too. In `connections.storage.ts`: 1. Add `ne` to the drizzle import (line 4): `import { eq, desc, and, ne } from "drizzle-orm";` 2. Immediately AFTER the existing `if (data.defaultForAgents !== undefined) { ... }` block, add an `else if` that runs only when `defaultForAgents` was NOT sent and the edited row is already a default, and which **excludes the edited row's own id** so it stays the sole default in its new category: ```ts } else if (data.provider !== undefined && existing.defaultForAgents === "true") { if (effectiveProvider === "image_generation") { await db.update(apiConnections).set({ defaultForAgents: "false" }).where( and( eq(apiConnections.defaultForAgents, "true"), eq(apiConnections.provider, "image_generation"), ne(apiConnections.id, id), ), ); } else { const existingDefaults = await db.select().from(apiConnections).where(eq(apiConnections.defaultForAgents, "true")); for (const row of existingDefaults) { if (row.id !== id && row.provider !== "image_generation") { await db.update(apiConnections).set({ defaultForAgents: "false" }).where(eq(apiConnections.id, row.id)); } } } } ``` This keeps the edited row's `defaultForAgents='true'` and demotes any conflicting default in the category it just moved into, in both directions (covered by branching on `effectiveProvider`). **Regression avoided:** do NOT just reuse the existing dedupe blocks for the provider-change case. Those blocks unset every default in the target category *without excluding the edited row*, and rely on the subsequent `updateFields.defaultForAgents = "true"` write to re-set it — which does not run when `defaultForAgents` isn't in the body. Reusing them as-is would demote the edited row itself, leaving ZERO defaults (a different but equally wrong bug). The new block excludes the edited row's own id and runs only when `defaultForAgents` is absent, so it never double-runs with the existing block. Optionally add `.orderBy(desc(apiConnections.updatedAt))` to `getDefaultForAgents()`/`getDefaultForImageGeneration()` for deterministic resolution of any pre-existing duplicate state — but that alone is insufficient, since it leaves two `defaultForAgents='true'` rows persisted. --- *AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.*
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Claiming this for the current staging sweep in draft PR #3053 (branch codex/issue-sweep-3033-3052).

<!-- gh-comment-id:4834987662 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Claiming this for the current staging sweep in draft PR #3053 (branch `codex/issue-sweep-3033-3052`).
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Fixed in PR #3053 on branch codex/issue-sweep-3033-3052 (commit bfb1bc76). Closing this issue as addressed; the PR remains open for staging review/merge.

<!-- gh-comment-id:4835087328 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Fixed in PR #3053 on branch `codex/issue-sweep-3033-3052` (commit bfb1bc76). Closing this issue as addressed; the PR remains open for staging review/merge.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1606
No description provided.