Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 47 additions & 30 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ import {
import * as ProviderFailover from "./ProviderFailover.ts";
import * as ProviderCooldown from "../provider/ProviderCooldown.ts";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
import { modelSelectionsEqual } from "@t3tools/shared/model";
import { draftModelPickMatchesThread, modelSelectionsEqual } from "@t3tools/shared/model";
import { modelSwitchSince } from "./modelSwitch.ts";
import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts";
import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
Expand Down Expand Up @@ -1050,7 +1050,11 @@ function threadAtRunStart(
): OrchestrationV2ThreadProjection["thread"] {
const scheduled = projection.thread.scheduledModelSelection;
if (scheduled == null || starting.model === "server") return projection.thread;
const cleared = { ...projection.thread, scheduledModelSelection: null };
const cleared = {
...projection.thread,
scheduledModelSelection: null,
bypassProviderCooldown: false,
};
if (starting.model === "named") {
return starting.ordinal !== null && starting.ordinal <= scheduled.queuedThroughOrdinal
? projection.thread
Expand Down Expand Up @@ -2529,6 +2533,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
(candidate) => candidate.id === storedQueuedRun.userMessageId,
);
const requestedSelection = queuedRunModelSelection(projection, storedQueuedRun);
const recoveryRun =
storedQueuedRun.failoverOfRunId !== undefined ||
storedQueuedRun.restartContinuationOfRunId !== undefined;
const consumesProviderCooldownBypass =
!recoveryRun &&
(storedQueuedRun.explicitModelSelection !== true ||
projection.thread.scheduledModelSelection == null ||
storedQueuedRun.ordinal >
projection.thread.scheduledModelSelection.queuedThroughOrdinal) &&
queuedMessage !== undefined &&
ProviderFailover.resendable(queuedMessage) &&
projection.thread.bypassProviderCooldown === true &&
draftModelPickMatchesThread(requestedSelection, nextTurnModelSelection(projection.thread));
Comment on lines +2539 to +2548

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the bypass across older explicit queued runs

If an explicitly modeled queued run predates a scheduled change but happens to name the same selection, model equality here consumes the scheduled bypass even though threadAtRunStart correctly keeps the schedule pending through that older run. The queued run already has its own explicit-pick bypass, so when the selected provider is cooling, the first default turn after the preexisting queue is incorrectly routed to the fallback. Only consume the scheduled bypass for a run that actually follows or supersedes the scheduled selection boundary.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5d8bca8. An explicit queued run at or before queuedThroughOrdinal keeps its own run bypass and cannot claim the later scheduled bypass. The scheduled-older-explicit regression verifies that the pick survives that run and is consumed once by the next default prompt; it failed before the repair and passes now.

const modelSelection =
queuedMessage === undefined
? requestedSelection
Expand All @@ -2540,13 +2557,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
run: {
...storedQueuedRun,
bypassProviderCooldown:
storedQueuedRun.bypassProviderCooldown === true ||
projection.thread.bypassProviderCooldown === true ||
(projection.thread.scheduledModelSelection != null &&
modelSelectionsEqual(
requestedSelection,
projection.thread.scheduledModelSelection.modelSelection,
)),
storedQueuedRun.bypassProviderCooldown === true || consumesProviderCooldownBypass,
},
message: queuedMessage,
});
Expand Down Expand Up @@ -2739,8 +2750,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const threadAtStart = threadAtRunStart(projection, {
runId: queuedRun.id,
ordinal: queuedRun.ordinal,
model:
queuedRun.explicitModelSelection !== true
model: recoveryRun
? "server"
: queuedRun.explicitModelSelection !== true
? "default"
: queuedMessage?.creationSource === "server"
? "server"
Expand Down Expand Up @@ -3216,7 +3228,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
[
...(selectionChanged ||
threadAtStart !== projection.thread ||
projection.thread.bypassProviderCooldown === true
consumesProviderCooldownBypass
? [
{
type: !selectionChanged
Expand All @@ -3231,7 +3243,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
...threadAtStart,
providerInstanceId: queuedRun.providerInstanceId,
modelSelection: queuedRun.modelSelection,
bypassProviderCooldown: false,
...(consumesProviderCooldownBypass ? { bypassProviderCooldown: false } : {}),
Comment on lines 3243 to +3246

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear the bypass when replacing a scheduled pick

When scheduled selection B is pending and a later explicitly named queued run on A starts after the scheduling boundary, threadAtRunStart clears scheduledModelSelection, but consumesProviderCooldownBypass is false because A does not match B. This conditional therefore preserves the now-orphaned bypassProviderCooldown: true, allowing the next ordinary A prompt to bypass a cooldown even though no explicit pick remains. Clear the associated bypass whenever the scheduled selection is cleared or superseded.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5d8bca8. threadAtRunStart clears bypassProviderCooldown whenever it clears or supersedes scheduledModelSelection, on both dispatch and queued starts. The scheduled-superseded regression proves the flag is cleared when a later explicit A replaces scheduled B; it failed before the repair and passes now.

updatedAt: now,
},
},
Expand Down Expand Up @@ -5377,6 +5389,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return {
...thread,
scheduledModelSelection: providerSwitchPlan.scheduled,
bypassProviderCooldown: true,
updatedAt: now,
};
}
Expand Down Expand Up @@ -7929,30 +7942,33 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
) {
modelSelection = queueTailModelSelection(projection);
}
const recoveryRun =
command.failoverOfRunId !== undefined || command.restartContinuationOfRunId !== undefined;
const resendablePrompt = ProviderFailover.resendable({ ...incomingMessage, role: "user" });
const consumesProviderCooldownBypass =
!recoveryRun &&
resendablePrompt &&
projection.thread.bypassProviderCooldown === true &&
draftModelPickMatchesThread(modelSelection, nextTurnModelSelection(projection.thread));
Comment on lines +7948 to +7952

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude recovery runs from consuming the pending pick

When an automatic failover or restart continuation targets the same model as a pending scheduled pick, its copied user prompt passes resendable and this predicate consumes the thread bypass before the later guards exempt the recovery run from cooldown routing. These runs continue an earlier turn rather than taking the scheduled next turn, so the user's subsequent prompt can be redirected away from the cooling model. Exclude failover and restart continuations from bypass consumption, as resolveProviderCooldownTarget already does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5d8bca8. Failover and restart continuations cannot consume a pending bypass on dispatch or queued start, and schedule cleanup treats them as continuations too. The two failover and two restart cases assert an armed pick before recovery and its preservation afterward; all four failed before the repair and pass now.

Comment on lines +7948 to +7952

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear the inherited bypass when an explicit pick replaces it

When an idle thread already has a one-shot bypass for selection B and the user sends a resendable prompt explicitly selecting C, this match is false, so consumesProviderCooldownBypass remains false while the following expression correctly gives the C run its own bypass. Because there is no scheduled selection, threadAtRunStart then preserves the thread-level bypass; after C becomes the thread default, the next ordinary C prompt consumes that stale flag and skips cooldown fallback. Clear the inherited thread flag when an explicit pick supersedes the effective selection while retaining the new run's local bypass.

Useful? React with 👍 / 👎.

const bypassProviderCooldown =
(command.modelSelection !== undefined &&
!modelSelectionsEqual(command.modelSelection, projection.thread.modelSelection)) ||
projection.thread.bypassProviderCooldown === true ||
(projection.thread.scheduledModelSelection != null &&
modelSelectionsEqual(
modelSelection,
projection.thread.scheduledModelSelection.modelSelection,
));
if (
command.failoverOfRunId === undefined &&
command.restartContinuationOfRunId === undefined &&
startsOrQueuesRun
) {
(resendablePrompt &&
command.modelSelection !== undefined &&
!draftModelPickMatchesThread(
command.modelSelection,
nextTurnModelSelection(projection.thread),
)) ||
consumesProviderCooldownBypass;
if (!recoveryRun && startsOrQueuesRun) {
modelSelection = yield* ProviderFailover.resolveProviderCooldownTarget({
cooldown: providerCooldown,
settings: serverSettings,
projectId: projection.thread.projectId,
modelSelection,
run: { bypassProviderCooldown },
message: { ...command, role: "user" },
message: { ...incomingMessage, role: "user" },
});
}
if (projection.thread.bypassProviderCooldown === true && startsOrQueuesRun) {
if (consumesProviderCooldownBypass && startsOrQueuesRun) {
const now = yield* DateTime.now;
const event = yield* emit(
events,
Expand Down Expand Up @@ -8383,8 +8399,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const threadAtStart = threadAtRunStart(projection, {
runId: null,
ordinal: null,
model:
command.modelSelection === undefined
model: recoveryRun
? "server"
: command.modelSelection === undefined
? "default"
: command.creationSource === "server"
? "server"
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/orchestration-v2/ProviderFailover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export interface ProviderFailoverTargets {
* Only a prompt someone sent is re-sent. Wakes, delegated results, compaction and slash
* commands are provider-specific or have their own recovery.
*/
function resendable(
export function resendable(
message: Pick<
OrchestrationV2ConversationMessage,
"role" | "notification" | "delegatedCompletion" | "idleCompaction" | "workflowScript" | "text"
Expand Down
88 changes: 80 additions & 8 deletions apps/server/src/orchestration-v2/runtimeLayer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8449,7 +8449,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
worktreePath: process.cwd(),
});
// A restart continuation names the run's own model and comes from the server.
const send = (key: string, kind: "agent" | "server", queue: boolean) =>
const send = (key: string, kind: "agent" | "server" | "notification", queue: boolean) =>
orchestrator.dispatch({
type: "message.dispatch",
commandId: CommandId.make(`${threadId}:${key}`),
Expand All @@ -8458,9 +8458,19 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
text: key,
attachments: [],
...(kind === "server" ? { modelSelection } : {}),
...(kind === "notification"
? {
modelSelection: scheduledSelection,
notification: {
source: { kind: "monitor" as const },
outcome: "updated" as const,
summary: key,
},
}
: {}),
dispatchMode: { type: queue ? "queue_after_active" : "start_immediately" },
createdBy: "agent",
creationSource: kind === "server" ? "server" : "mcp",
creationSource: kind === "agent" ? "mcp" : "server",
});
const run = (key: string) =>
orchestrator
Expand Down Expand Up @@ -8494,19 +8504,29 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
.getThreadProjection(threadId)
.pipe(Effect.map(({ thread }) => thread.scheduledModelSelection ?? null));
yield* send("active", "agent", false);
yield* orchestrator.dispatch({
type: "thread.model-selection.set",
commandId: CommandId.make(`${threadId}:pick`),
threadId,
modelSelection,
});
yield* orchestrator.dispatch({
type: "thread.model-selection.set",
commandId: CommandId.make(`${threadId}:schedule`),
threadId,
modelSelection: scheduledSelection,
applyAt: "next_turn",
});
return { threadId, send, run, complete, scheduledNow };
const bypassNow = orchestrator
.getThreadProjection(threadId)
.pipe(Effect.map(({ thread }) => thread.bypassProviderCooldown === true));
return { threadId, send, run, complete, scheduledNow, bypassNow };
});

// Queued behind the busy run.
const queued = yield* scenario("queued");
yield* queued.send("continuation", "server", true);
assert.isTrue(yield* queued.bypassNow);
yield* queued.send("after", "agent", true);
assert.deepEqual((yield* queued.run("after")).modelSelection, scheduledSelection);
yield* queued.complete("active");
Expand All @@ -8523,13 +8543,33 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
// Started at once on the idle thread, after the busy run ended.
const immediate = yield* scenario("immediate");
yield* immediate.complete("active");
yield* immediate.send("continuation", "server", false);
assert.deepEqual((yield* immediate.run("continuation")).modelSelection, modelSelection);
assert.isNotNull(yield* immediate.scheduledNow());
yield* immediate.complete("continuation");
for (const key of ["continuation", "another-continuation"]) {
yield* immediate.send(key, "server", false);
assert.deepEqual((yield* immediate.run(key)).modelSelection, modelSelection);
assert.isNotNull(yield* immediate.scheduledNow());
assert.isTrue(yield* immediate.bypassNow);
yield* immediate.complete(key);
assert.isTrue(yield* immediate.bypassNow);
}
yield* immediate.send("next", "agent", false);
assert.deepEqual((yield* immediate.run("next")).modelSelection, scheduledSelection);
assert.isNull(yield* immediate.scheduledNow());
assert.isFalse(yield* immediate.bypassNow);

const notifications = yield* scenario("notifications");
yield* notifications.complete("active");
for (const key of ["wake", "another-wake"]) {
yield* notifications.send(key, "notification", true);
assert.deepEqual((yield* notifications.run(key)).modelSelection, scheduledSelection);
assert.isNotNull(yield* notifications.scheduledNow());
assert.isTrue(yield* notifications.bypassNow);
yield* notifications.complete(key);
assert.isTrue(yield* notifications.bypassNow);
}
yield* notifications.send("next", "agent", false);
assert.deepEqual((yield* notifications.run("next")).modelSelection, scheduledSelection);
assert.isNull(yield* notifications.scheduledNow());
assert.isFalse(yield* notifications.bypassNow);
}),
);

Expand Down Expand Up @@ -9163,6 +9203,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
modelSelection: newerSelection,
});
const waiting = yield* orchestrator.getThreadProjection(threadId);
assert.isTrue(waiting.thread.bypassProviderCooldown);
yield* eventSink.write({
events: [
{
Expand Down Expand Up @@ -9190,6 +9231,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
newerSelection.instanceId,
);
assert.deepEqual(after.thread.modelSelection, newerSelection);
assert.isTrue(after.thread.bypassProviderCooldown);
}),
);

Expand Down Expand Up @@ -10160,6 +10202,17 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
dispatchMode: { type: "start_immediately" },
});
const cut = (yield* runFor("cut"))!;
const scheduledSelection = { ...modelSelection, model: "gpt-5.5" };
yield* orchestrator.dispatch({
type: "thread.model-selection.set",
commandId: CommandId.make(`${threadId}:schedule`),
threadId,
modelSelection: scheduledSelection,
applyAt: "next_turn",
});
const beforeRecovery = yield* orchestrator.getThreadProjection(threadId);
assert.isNotNull(beforeRecovery.thread.scheduledModelSelection);
assert.isTrue(beforeRecovery.thread.bypassProviderCooldown);
yield* write("cut:cancelled", { ...cut, status: "cancelled" });
yield* orchestrator.dispatch({
type: "message.dispatch",
Expand All @@ -10170,10 +10223,13 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
messageId: messageId("continuation"),
text: "Continue where you left off.",
attachments: [],
modelSelection,
modelSelection: scheduledSelection,
dispatchMode: { type: "start_immediately" },
restartContinuationOfRunId: cut.id,
});
const afterRecovery = yield* orchestrator.getThreadProjection(threadId);
assert.isNotNull(afterRecovery.thread.scheduledModelSelection);
assert.isTrue(afterRecovery.thread.bypassProviderCooldown);
yield* orchestrator.dispatch({
type: "message.dispatch",
createdBy: "user",
Expand Down Expand Up @@ -12931,6 +12987,7 @@ it.layer(
key: string,
options?: {
readonly freshContext?: boolean;
readonly scheduledFallback?: boolean;
readonly fallbackInstanceId?: ProviderInstanceId;
/** The failed message opens the thread; there is no earlier role. */
readonly sourceFirst?: boolean;
Expand Down Expand Up @@ -13020,6 +13077,15 @@ it.layer(
const source = yield* latest;
yield* send("queued", "Queue: a later note.", "queue_after_active");
const queued = yield* latest;
if (options?.scheduledFallback === true) {
yield* orchestrator.dispatch({
type: "thread.model-selection.set",
commandId: CommandId.make(`failover:schedule:${key}`),
threadId,
modelSelection: fallback,
applyAt: "next_turn",
});
}
yield* finish(source, {
status: "failed",
startedAt: now,
Expand Down Expand Up @@ -13052,7 +13118,11 @@ it.layer(
const orchestrator = yield* Orchestrator.OrchestratorV2;
const { threadId, source, queued } = yield* failedRunWithClaim(`dispatch:${freshContext}`, {
freshContext,
scheduledFallback: true,
});
const beforeRecovery = yield* orchestrator.getThreadProjection(threadId);
assert.isNotNull(beforeRecovery.thread.scheduledModelSelection);
assert.isTrue(beforeRecovery.thread.bypassProviderCooldown);
// Startup queue recovery and the parent wait both treat the claim as unfinished work.
yield* orchestrator.resumeQueuedRuns;
const pending = yield* orchestrator.getThreadProjection(threadId);
Expand All @@ -13068,6 +13138,8 @@ it.layer(
yield* runFailover(threadId, source.id, 2);

const after = yield* orchestrator.getThreadProjection(threadId);
assert.isNotNull(after.thread.scheduledModelSelection);
assert.isTrue(after.thread.bypassProviderCooldown);
const failedOver = after.runs.filter((run) => run.failoverOfRunId === source.id);
assert.lengthOf(failedOver, 1);
const run = failedOver[0]!;
Expand Down
Loading
Loading