fix: run queued messages on the chat's model when theirs is unavailable (#31632)

A queued message whose model was disabled, had its provider disabled,
or was deleted ran on the organization default, even when the chat was
on another available model, and the chat then moved to the default.

Promotion now tries the queued message's model, then the chat's last
model, then the organization default, the order a message sent without
a model already uses. Saving a queued edit without picking a model now
sends the picker's model when the row's model is no longer selectable,
as a history edit does.

Refs CODAGT-971
This commit is contained in:
Mathias Fredriksson authored and GitHub committed 2026-11-12 12:48:35 +00:00
1 parent a48a8c0cd7
commit 3086d4f4c0
6 files changed
+149 -59

No files matched your search

+1 -1
View File
@@ -862,7 +862,7 @@ A chat worker is identified by a **worker ID**, which is regenerated on worker s
A chat may use model configs only from its own organization. Chat creation, message sends, and message edits reject an explicit config that is disabled, unavailable to the caller, or belongs to another organization.
Queued-message promotion revalidates the stored model with daemon authorization. It keeps the model when the model and its provider are enabled and the model belongs to the chat's organization. Worker generation preparation revalidates with the chat owner's authorization context, so it also requires the model to remain readable by the owner. When those checks make the stored model unavailable, the path selects that organization's enabled default. If no local default is available, processing fails with `ErrNoDefaultChatModelConfig`; it never falls back to another organization's model.
Queued-message promotion revalidates the stored model with daemon authorization. It keeps the model when the model and its provider are enabled and the model belongs to the chat's organization. Worker generation preparation revalidates with the chat owner's authorization context, so it also requires the model to remain readable by the owner. When the queued row's model fails promotion's checks, promotion uses the chat's last model if that model passes the same checks, and otherwise the organization's enabled default. When the chat's last model fails generation preparation's checks, generation preparation selects the organization's enabled default. If no local default is available, processing fails with `ErrNoDefaultChatModelConfig`; it never falls back to another organization's model.
## Acquisition loop
+30 -4
View File
@@ -13614,9 +13614,14 @@ func TestQueuedCompletionResolvesOrganizationModel(t *testing.T) {
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
})
user, org, localDefault := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
chatModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
AIProviderID: localDefault.AIProviderID,
OrganizationID: org.ID,
})
foreignModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{})
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, localDefault.ID, "first")
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, chatModel.ID, "first")
testutil.TryReceive(ctx, t, firstRunStarted)
disableChatModelConfig(t, db, chatModel)
insertQueuedMessage(ctx, t, db, chat.ID, user.ID, foreignModel.ID, "queued")
close(allowFirstRunFinish)
waitForChatStatus(ctx, t, db, chat.ID, database.ChatStatusWaiting)
@@ -13667,9 +13672,14 @@ func TestQueuedCompletionResolvesOrganizationModel(t *testing.T) {
cfg.AIBridgeTransportFactory = chatAIGatewayTransportFactoryPointer(chattest.NewMockAIBridgeTransport(t, openAIURL))
})
user, org, localDefault := seedChatDependenciesWithProvider(t, db, "openai-compat", openAIURL)
chatModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
AIProviderID: localDefault.AIProviderID,
OrganizationID: org.ID,
})
foreignModel := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{})
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, localDefault.ID, "first")
chat := createChatThroughServer(ctx, t, db, server, org.ID, user.ID, chatModel.ID, "first")
testutil.TryReceive(ctx, t, streamStarted)
disableChatModelConfig(t, db, chatModel)
insertQueuedMessage(ctx, t, db, chat.ID, user.ID, foreignModel.ID, "queued")
current, err := db.GetChatByID(ctx, chat.ID)
require.NoError(t, err)
@@ -13708,7 +13718,7 @@ func TestQueuedPromotionResolvesOrganizationModel(t *testing.T) {
chat := dbgen.Chat(t, db, database.Chat{
OrganizationID: org.ID,
OwnerID: user.ID,
LastModelConfigID: localDefault.ID,
LastModelConfigID: foreignModel.ID,
Title: "resolve explicit queued promotion",
Status: database.ChatStatusError,
})
@@ -13734,7 +13744,7 @@ func TestQueuedPromotionResolvesOrganizationModel(t *testing.T) {
chat := dbgen.Chat(t, db, database.Chat{
OrganizationID: org.ID,
OwnerID: user.ID,
LastModelConfigID: localDefault.ID,
LastModelConfigID: foreignModel.ID,
Title: "resolve error send promotion",
Status: database.ChatStatusError,
})
@@ -13785,6 +13795,22 @@ func TestQueuedPromotionResolvesOrganizationModel(t *testing.T) {
})
}
func disableChatModelConfig(t *testing.T, db database.Store, model database.ChatModelConfig) {
t.Helper()
_, err := db.UpdateChatModelConfig(context.Background(), database.UpdateChatModelConfigParams{
ID: model.ID,
DisplayName: model.DisplayName,
Model: model.Model,
Enabled: false,
IsDefault: model.IsDefault,
ContextLimit: model.ContextLimit,
CompressionThreshold: model.CompressionThreshold,
Options: model.Options,
AIProviderID: model.AIProviderID,
})
require.NoError(t, err)
}
func insertQueuedMessage(
ctx context.Context,
t *testing.T,
+16 -4
View File
@@ -429,21 +429,33 @@ func (tx *Tx) deletePromotedQueuedMessage(id int64) error {
return nil
}
// resolveQueuedMessageModelConfigID returns the first of the queued row's
// model and the chat's last model that is enabled, has an enabled
// provider, and belongs to the chat's organization, else the organization
// default. A lookup error other than sql.ErrNoRows is returned without
// trying the next candidate.
func (tx *Tx) resolveQueuedMessageModelConfigID(
chat database.Chat,
queued database.ChatQueuedMessage,
) (uuid.NullUUID, error) {
//nolint:gocritic // Queue promotion needs daemon access to deployment model configuration.
ctx := dbauthz.AsChatd(tx.ctx)
if queued.ModelConfigID.Valid {
config, err := tx.store.GetEnabledChatModelConfigByID(ctx, queued.ModelConfigID.UUID)
candidates := []uuid.NullUUID{
queued.ModelConfigID,
{UUID: chat.LastModelConfigID, Valid: true},
}
for _, candidate := range candidates {
if !candidate.Valid {
continue
}
config, err := tx.store.GetEnabledChatModelConfigByID(ctx, candidate.UUID)
if err == nil && config.OrganizationID == chat.OrganizationID {
return queued.ModelConfigID, nil
return candidate, nil
}
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return uuid.NullUUID{}, xerrors.Errorf(
"get chat model config %s: %w",
queued.ModelConfigID.UUID,
candidate.UUID,
err,
)
}
+31 -6
View File
@@ -175,7 +175,7 @@ func TestSteerQueuedMessageResolvesOrganizationModel(t *testing.T) {
localModel := dbgen.ChatModelConfig(t, f.DB, database.ChatModelConfig{
OrganizationID: f.Org.ID,
})
promoted := steerQueuedMessageWithModel(t, f, localModel.ID)
promoted := steerQueuedMessageWithModel(t, f, f.Model.ID, localModel.ID)
require.Equal(t, localModel.ID, promoted.ModelConfigID.UUID)
})
@@ -187,14 +187,19 @@ func TestSteerQueuedMessageResolvesOrganizationModel(t *testing.T) {
OrganizationID: foreignOrg.ID,
IsDefault: true,
})
promoted := steerQueuedMessageWithModel(t, f, foreignModel.ID)
promoted := steerQueuedMessageWithModel(t, f, foreignModel.ID, foreignModel.ID)
require.Equal(t, f.Model.ID, promoted.ModelConfigID.UUID)
})
t.Run("missing model falls back to local default", func(t *testing.T) {
t.Parallel()
f := newTestFixture(t)
promoted := steerQueuedMessageWithModel(t, f, uuid.New())
deleted := dbgen.ChatModelConfig(t, f.DB, database.ChatModelConfig{
OrganizationID: f.Org.ID,
})
_, err := f.DB.DeleteChatModelConfigByID(context.Background(), deleted.ID)
require.NoError(t, err)
promoted := steerQueuedMessageWithModel(t, f, deleted.ID, uuid.New())
require.Equal(t, f.Model.ID, promoted.ModelConfigID.UUID)
})
@@ -205,10 +210,24 @@ func TestSteerQueuedMessageResolvesOrganizationModel(t *testing.T) {
OrganizationID: f.Org.ID,
})
setChatModelConfigEnabled(t, f.DB, disabled, false)
promoted := steerQueuedMessageWithModel(t, f, disabled.ID)
promoted := steerQueuedMessageWithModel(t, f, disabled.ID, disabled.ID)
require.Equal(t, f.Model.ID, promoted.ModelConfigID.UUID)
})
t.Run("disabled model falls back to chat model", func(t *testing.T) {
t.Parallel()
f := newTestFixture(t)
chatModel := dbgen.ChatModelConfig(t, f.DB, database.ChatModelConfig{
OrganizationID: f.Org.ID,
})
disabled := dbgen.ChatModelConfig(t, f.DB, database.ChatModelConfig{
OrganizationID: f.Org.ID,
})
setChatModelConfigEnabled(t, f.DB, disabled, false)
promoted := steerQueuedMessageWithModel(t, f, chatModel.ID, disabled.ID)
require.Equal(t, chatModel.ID, promoted.ModelConfigID.UUID)
})
t.Run("missing local default rejects promotion", func(t *testing.T) {
t.Parallel()
f := newTestFixture(t)
@@ -390,12 +409,18 @@ func (s *modelConfigErrorStore) GetEnabledChatModelConfigByID(
func steerQueuedMessageWithModel(
t *testing.T,
f *testFixture,
modelConfigID uuid.UUID,
chatModelConfigID uuid.UUID,
queuedModelConfigID uuid.UUID,
) database.ChatMessage {
t.Helper()
ctx := testutil.Context(t, testutil.WaitShort)
created := createTestChat(t, f)
message := userTextMessage("queued model resolution", f.User.ID, modelConfigID)
_, err := f.DB.UpdateChatLastModelConfigByID(ctx, database.UpdateChatLastModelConfigByIDParams{
ID: created.Chat.ID,
LastModelConfigID: chatModelConfigID,
})
require.NoError(t, err)
message := userTextMessage("queued model resolution", f.User.ID, queuedModelConfigID)
queued, err := f.DB.InsertChatQueuedMessage(ctx, database.InsertChatQueuedMessageParams{
ChatID: created.Chat.ID,
Content: message.Content.RawMessage,
@@ -343,50 +343,71 @@ describe("AgentChatPage", () => {
// The row was queued with another model than the one the picker shows.
it.each([
["keeps the row's model when the picker is untouched", undefined],
["sends the model picked during the edit", "model-c"],
])("saving a queued edit %s", async (_name, pickedModel) => {
const page = renderQueuedChat({
queuedMessages: [{ ...row, model_config_id: "model-b" }],
models: [
{
...MockChatModel,
id: MockChat.last_model_config_id,
display_name: "Model A",
},
{ ...MockChatModel, id: "model-b", display_name: "Model B" },
{ ...MockChatModel, id: "model-c", display_name: "Model C" },
],
});
await page.rowAction("Edit");
await waitFor(() =>
expect(page.composer().textContent).toBe("queued text"),
);
if (pickedModel) {
await page.user.click(
screen.getByRole("combobox", { name: "Model A" }),
[
"keeps the row's model when the picker is untouched",
"model-b",
undefined,
undefined,
],
[
"sends the model picked during the edit",
"model-b",
"Model C",
"model-c",
],
[
"sends the picker's model when the row's model is no longer available",
"model-deleted",
undefined,
MockChat.last_model_config_id,
],
])(
"saving a queued edit %s",
async (_name, rowModel, pickModelName, wantModelConfigID) => {
const page = renderQueuedChat({
queuedMessages: [{ ...row, model_config_id: rowModel }],
models: [
{
...MockChatModel,
id: MockChat.last_model_config_id,
display_name: "Model A",
},
{ ...MockChatModel, id: "model-b", display_name: "Model B" },
{ ...MockChatModel, id: "model-c", display_name: "Model C" },
],
});
await page.rowAction("Edit");
await waitFor(() =>
expect(page.composer().textContent).toBe("queued text"),
);
if (pickModelName) {
await page.user.click(
screen.getByRole("combobox", { name: "Model A" }),
);
await page.user.click(
within(await screen.findByRole("listbox")).getByRole("option", {
name: new RegExp(pickModelName),
}),
);
}
await page.type(" edit");
await page.user.click(
within(await screen.findByRole("listbox")).getByRole("option", {
name: /Model C/,
}),
screen.getByRole("button", { name: "Save Edit" }),
);
}
await page.type(" edit");
await page.user.click(screen.getByRole("button", { name: "Save Edit" }));
await waitFor(() =>
expect(page.editChatQueuedMessage).toHaveBeenCalledWith(
MockChat.id,
row.id,
expect.objectContaining({
content: expect.anything(),
model_config_id: pickedModel,
}),
),
);
expect(localStorage.getItem(savedEditKey)).toBeNull();
});
await waitFor(() =>
expect(page.editChatQueuedMessage).toHaveBeenCalledWith(
MockChat.id,
row.id,
expect.objectContaining({
content: expect.anything(),
model_config_id: wantModelConfigID,
}),
),
);
expect(localStorage.getItem(savedEditKey)).toBeNull();
},
);
// react-query delivers the failed request's state to the page on a
// scheduler it owns, which may run before the request's own error
@@ -356,14 +356,20 @@ export async function submitChatTurn(
if (editingTarget?.kind === "queued") {
const queuedMessageID = editingTarget.id;
const queuedRow = store
.getSnapshot()
.queuedMessages.find((row) => row.id === queuedMessageID);
// A queued row keeps its model and effort unless the user changes
// them during this edit; the picker otherwise shows the chat's model,
// not the row's.
// not the row's. A row whose model is no longer selectable takes the
// picker's model, as a history edit does.
const request: TypesGen.EditChatQueuedMessageRequest = {
content,
model_config_id: isEditModelDirtyRef.current
? effectiveSelectedModel || undefined
: undefined,
model_config_id:
isEditModelDirtyRef.current ||
isUnavailableHistoricalModelID(queuedRow?.model_config_id, modelOptions)
? effectiveSelectedModel || undefined
: undefined,
reasoning_effort: isEditReasoningEffortDirtyRef.current
? effectiveReasoningEffort
: undefined,