Skip to content
Open
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
2 changes: 1 addition & 1 deletion apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1350,7 +1350,7 @@ export const layerPullRequestsToolkit = toolkitRegistration(
PullRequestsHandlers.layer,
).pipe(Layer.provide(PullRequestWatchService.layer));

export const layerEventsToolkit = toolkitRegistration(EventsToolkit, EventsHandlers.layer).pipe(
const layerEventsToolkit = toolkitRegistration(EventsToolkit, EventsHandlers.layer).pipe(
Layer.provide(PullRequestWatchService.layer),
);

Expand Down
104 changes: 104 additions & 0 deletions apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5211,6 +5211,110 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => {
}),
);

it.effect.each(["usage limit", "self"] as const)(
"a failed thread with no launcher wakes the watcher once, except for its %s",
(exception) =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const eventSink = yield* EventSink.EventSinkV2;
const now = yield* DateTime.now;
const key = exception === "self" ? "failure-self" : "failure-limit";
const projectId = ProjectId.make(`project:${key}`);
yield* ProjectService.ProjectService.pipe(
Effect.flatMap((projects) =>
projects.create({
commandId: CommandId.make(`command:${key}-project`),
projectId,
title: key,
workspaceRoot: `/workspace/${key}`,
}),
),
);
const createThread = (name: string) =>
orchestrator
.dispatch({
type: "thread.create",
createdBy: "user",
creationSource: "web",
commandId: CommandId.make(`command:${key}:${name}`),
threadId: ThreadId.make(`thread:${key}:${name}`),
projectId,
title: name,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
})
.pipe(Effect.as(ThreadId.make(`thread:${key}:${name}`)));
const lead = yield* createThread("lead");
const failing = exception === "self" ? [lead] : [];
const limited =
exception === "usage limit"
? [
yield* createThread("lane-1"),
yield* createThread("lane-2"),
yield* createThread("lane-3"),
]
: [];
const plain = yield* createThread("plain");
const { reactor } = yield* makeModelAlertReactor({
watcher: { environmentId: hereEnvironmentId, threadId: lead },
});
for (const threadId of [...failing, ...limited, plain]) {
const runId = RunId.make(`run:${threadId}`);
const failed = runEvent({ threadId, runId, ordinal: 1, status: "failed", now });
const limitError = {
id: EventId.make(`event:${threadId}:limit`),
type: "turn-item.updated" as const,
threadId,
occurredAt: now,
payload: {
id: TurnItemId.make(`turn-item:${threadId}:limit`),
type: "error" as const,
threadId,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 1,
status: "failed" as const,
title: "Usage limit reached",
startedAt: now,
completedAt: now,
updatedAt: now,
failure: {
class: "usage_limit" as const,
message: "Plan limit reached.",
code: "usageLimitExceeded",
retryable: null,
resetAt: null,
},
},
};
yield* eventSink.write({
commandId: CommandId.make(`command:${threadId}:failed`),
events: limited.includes(threadId) ? [failed, limitError] : [failed],
});
yield* reactor.handle(failed);
}
yield* reactor.flush;
yield* TestClock.adjust("11 minutes");
yield* reactor.flush;
const messages = (yield* orchestrator.getThreadProjection(lead)).messages;
const wakes = messages.filter((message) => message.text.startsWith("Thread event from"));
assert.equal(wakes.length, 1);
assert.include(wakes[0]?.text, `/${plain})`);
const incidents = messages.filter((message) =>
message.text.includes("Usage limit incident"),
);
assert.equal(incidents.length, limited.length === 0 ? 0 : 1);
for (const lane of limited) assert.include(incidents[0]?.text, `/${lane})`);
}),
);

it.effect("sends a model alert over the link to the watcher's machine and retries it", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
Expand Down
63 changes: 63 additions & 0 deletions apps/server/src/orchestration-v2/ModelAlertReactor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ import {
BUSY_WATCHER_RECHECK_MS,
busyWatcherHold,
deliverAlertToWatcher,
failureWakeHold,
INCIDENT_GROUP_INTERVAL_MS,
INCIDENT_GROUP_WAIT_MS,
EMPTY_MODEL_ALERT_STATE,
type ModelAlert,
type ModelAlertState,
modelAlertDestinations,
modelAlertFor,
overdueResumes,
Expand All @@ -26,6 +28,7 @@ import {
recordThreadEvents,
threadEventDestinations,
watcherAlertMessage,
watcherLimitHold,
} from "./ModelAlertReactor.ts";
import { ProviderExhaustion } from "./ProviderExhaustion.ts";
import { alertIsStale, expectsAutoResume, replacedBySibling } from "./UsageLimitIncidents.ts";
Expand Down Expand Up @@ -199,6 +202,59 @@ const finding = (kind: ThreadEventKind, signature: string): ThreadFinding => ({
detail: `${kind} detail`,
});

it("rate-limits subsequent failure wakes per thread after successful delivery", () => {
const threadId = "thread:fleet";
const { state } = recordThreadEvents(
EMPTY_MODEL_ALERT_STATE,
{
threadId,
evaluated: ["thread-failed"],
findings: [finding("thread-failed", "run:1")],
},
eventAlert,
["watcher"],
0,
);
const entry = state.outbox[0]!;
const failed = afterDeliveryAttempt(state, entry, false, 10);
assert.isNull(failureWakeHold(failed.failureWakeSentAt[threadId], 100));
const sent = afterDeliveryAttempt(failed, entry, true, 100);
assert.equal(failureWakeHold(sent.failureWakeSentAt[threadId], 101), 300100);
assert.isNull(failureWakeHold(sent.failureWakeSentAt[threadId], 300100));
assert.isNull(failureWakeHold(sent.failureWakeSentAt["other"], 101));

const rerun = (state: ModelAlertState, runId: string) =>
recordThreadEvents(
state,
{ threadId, evaluated: ["thread-failed"], findings: [finding("thread-failed", runId)] },
eventAlert,
["watcher"],
200,
);
assert.isFalse(rerun(sent, "run:1").enqueued);
assert.isTrue(rerun(sent, "run:2").enqueued);
});

it("holds a failure wake while the watcher is stopped at its own usage limit", () => {
const wake = eventAlert(finding("thread-failed", "run:1"));
const nowMs = Date.parse("2026-11-19T04:00:00.000Z");
const limited = {
status: "failed",
providerInstanceId: "codex",
usageLimited: true,
resetAt: "2026-11-19T04:02:00.000Z",
};
assert.equal(watcherLimitHold(limited, wake, nowMs), Date.parse(limited.resetAt));
assert.isNull(watcherLimitHold(limited, wake, Date.parse(limited.resetAt)));
assert.isNull(watcherLimitHold({ ...limited, usageLimited: false }, wake, nowMs));
assert.isNull(watcherLimitHold({ ...limited, status: "idle" }, wake, nowMs));
assert.isNull(watcherLimitHold({ ...limited, usageLimited: null, resetAt: null }, wake, nowMs));
assert.isNull(watcherLimitHold(null, wake, nowMs));
assert.isNull(
watcherLimitHold(limited, eventAlert(finding("promise-without-wake", "message:1")), nowMs),
);
});

it("reports a thread event once per kind and signature until its state changes", () => {
let state = EMPTY_MODEL_ALERT_STATE;
const enqueued: Array<boolean> = [];
Expand Down Expand Up @@ -394,6 +450,8 @@ it.effect("forwards a thread event to a watcher on another environment with one
assert.match(String(called[0]!.arguments?.clientRequestId), /^thread-event:/);
assert.equal(called[0]!.arguments?.clientRequestId, called[1]!.arguments?.clientRequestId);

assert.equal(called[0]!.arguments?.deliveryClass, "digest");

// The same alert on the watcher's own machine queues into the thread directly.
yield* deliverAlertToWatcher(deps, alert, laptop, EnvironmentId.make("laptop"));
assert.equal(called.length, 2);
Expand All @@ -402,6 +460,11 @@ it.effect("forwards a thread event to a watcher on another environment with one
assert.deepEqual((dispatched[0] as { dispatchMode: unknown }).dispatchMode, {
type: "queue_after_active",
});
const failure = eventAlert(finding("thread-failed", "run:1"));
yield* deliverAlertToWatcher(deps, failure, laptop, EnvironmentId.make("laptop"));
yield* deliverAlertToWatcher(deps, failure, laptop, EnvironmentId.make("r720"));
assert.equal((dispatched[1] as { delivery: { class: string } }).delivery.class, "next_turn");
assert.equal(called[2]?.arguments?.deliveryClass, "next_turn");
}),
);

Expand Down
Loading
Loading