fix(server): working timers no longer reset on every background wake (#15029)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
9333509c91
commit
736130c2fd
9 files changed
+245
-11
No files matched your search
@@ -39,6 +39,7 @@ import {
|
||||
type OrchestrationV2Subagent,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type OrchestrationV2TurnItem,
|
||||
orchestrationV2RunWorkStartedAt,
|
||||
ProviderInstanceId,
|
||||
type ProviderSessionId,
|
||||
RunId,
|
||||
@@ -304,6 +305,37 @@ function nextRunOrdinal(projection: Pick<OrchestrationV2ThreadProjection, "runs"
|
||||
return projection.runs.length + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* A wake (background notification, delegated task result, restart
|
||||
* continuation) carries on the work of the run that started last, so it keeps
|
||||
* that work's start. Stamp it when the wake run starts, not when it queues:
|
||||
* a queued prompt ahead of it has no start yet, and delegated results jump
|
||||
* the queue. Other runs start new work.
|
||||
*/
|
||||
function wakeWorkStartedAt(
|
||||
runs: ReadonlyArray<OrchestrationV2Run>,
|
||||
trigger: {
|
||||
readonly notification?: unknown;
|
||||
readonly delegatedCompletion?: unknown;
|
||||
readonly restartContinuationOfRunId?: RunId | undefined;
|
||||
},
|
||||
): Pick<OrchestrationV2Run, "workStartedAt"> {
|
||||
if (
|
||||
trigger.notification === undefined &&
|
||||
trigger.delegatedCompletion === undefined &&
|
||||
trigger.restartContinuationOfRunId === undefined
|
||||
) {
|
||||
return {};
|
||||
}
|
||||
const previous = runs
|
||||
.flatMap((run) => (run.startedAt === null ? [] : [{ run, startedAt: run.startedAt }]))
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.Order(right.startedAt, left.startedAt) || right.run.ordinal - left.run.ordinal,
|
||||
)[0]?.run;
|
||||
return previous === undefined ? {} : { workStartedAt: orchestrationV2RunWorkStartedAt(previous) };
|
||||
}
|
||||
|
||||
function isNativeMaintenanceCommand(message: {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
@@ -1459,6 +1491,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
queuePosition: null,
|
||||
startedAt: null,
|
||||
contextHandoffId: activeHandoff?.id ?? null,
|
||||
...wakeWorkStartedAt(projection.runs, {
|
||||
notification: queuedMessage.notification,
|
||||
delegatedCompletion: queuedMessage.delegatedCompletion,
|
||||
restartContinuationOfRunId: queuedRun.restartContinuationOfRunId,
|
||||
}),
|
||||
};
|
||||
const userTurnItem: OrchestrationV2TurnItem = {
|
||||
...(legacyQueuedTurnItem ?? {
|
||||
@@ -4949,6 +4986,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
...(command.restartContinuationOfRunId === undefined
|
||||
? {}
|
||||
: { restartContinuationOfRunId: command.restartContinuationOfRunId }),
|
||||
...wakeWorkStartedAt(projection.runs, command),
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
id: attemptId,
|
||||
@@ -5642,6 +5680,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
...(command.restartContinuationOfRunId === undefined
|
||||
? {}
|
||||
: { restartContinuationOfRunId: command.restartContinuationOfRunId }),
|
||||
...wakeWorkStartedAt(projection.runs, command),
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
id: attemptId,
|
||||
|
||||
@@ -1982,6 +1982,37 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
assert.isNull(onlyHeldShell.latestRunId);
|
||||
assert.equal(onlyHeldShell.status, "idle");
|
||||
}
|
||||
|
||||
// A wake run counts from the start of the work it continues.
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-shell-interruptible:wake"),
|
||||
type: "run.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
driver,
|
||||
occurredAt: later,
|
||||
payload: {
|
||||
...run,
|
||||
status: "running",
|
||||
requestedAt: later,
|
||||
startedAt: later,
|
||||
workStartedAt: now,
|
||||
},
|
||||
});
|
||||
const wakeProjection = yield* projectionStore.getThreadProjection(threadId);
|
||||
const wakeSqlShell = (yield* projectionStore.getShellSnapshot()).threads.find(
|
||||
(row) => row.id === threadId,
|
||||
)!;
|
||||
for (const wakeShell of [
|
||||
wakeSqlShell,
|
||||
ProjectionStore.threadShellFromProjection(wakeProjection),
|
||||
]) {
|
||||
assert.equal(
|
||||
wakeShell.activityRunStartedAt && DateTime.toEpochMillis(wakeShell.activityRunStartedAt),
|
||||
DateTime.toEpochMillis(now),
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
OrchestrationV2RuntimeRequestJson as OrchestrationV2RuntimeRequestJsonSchema,
|
||||
OrchestrationV2SubagentJson as OrchestrationV2SubagentJsonSchema,
|
||||
OrchestrationV2TurnItemJson as OrchestrationV2TurnItemJsonSchema,
|
||||
orchestrationV2RunWorkStartedAt,
|
||||
RunId,
|
||||
CheckpointScopeId,
|
||||
ThreadId,
|
||||
@@ -1368,7 +1369,8 @@ export function threadShellFromProjection(
|
||||
latestRunCompletedAt: latestRun?.completedAt ?? null,
|
||||
activeRunId: activeRun?.id ?? null,
|
||||
activityRunStatus: activityRun?.status ?? null,
|
||||
activityRunStartedAt: activityRun?.startedAt ?? activityRun?.requestedAt ?? null,
|
||||
activityRunStartedAt:
|
||||
activityRun === null ? null : orchestrationV2RunWorkStartedAt(activityRun),
|
||||
status: latestRun?.status ?? "idle",
|
||||
...threadErrorSummary(
|
||||
latestRootProviderFailure(latestRun, projection.turnItems),
|
||||
@@ -4782,7 +4784,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
LIMIT 1
|
||||
) AS activity_run_status,
|
||||
(
|
||||
SELECT COALESCE(json_extract(r.payload_json, '$.startedAt'), r.requested_at)
|
||||
-- Mirrors orchestrationV2RunWorkStartedAt.
|
||||
SELECT COALESCE(
|
||||
json_extract(r.payload_json, '$.workStartedAt'),
|
||||
json_extract(r.payload_json, '$.startedAt'),
|
||||
r.requested_at
|
||||
)
|
||||
FROM orchestration_v2_projection_runs r
|
||||
WHERE r.thread_id = t.thread_id
|
||||
AND r.status IN ('preparing', 'starting', 'running', 'waiting')
|
||||
|
||||
@@ -2800,6 +2800,124 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("starts a wake's work clock from the run that ran before it", () =>
|
||||
Effect.gen(function* () {
|
||||
const orchestrator = yield* Orchestrator.OrchestratorV2;
|
||||
const eventSink = yield* EventSink.EventSinkV2;
|
||||
const threadId = ThreadId.make("runtime-layer-wake-work-start-thread");
|
||||
const messageId = (key: string) => MessageId.make(`runtime-layer-wake-work-start-${key}`);
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("runtime-layer-wake-work-start-create"),
|
||||
threadId,
|
||||
projectId: ProjectId.make("runtime-layer-wake-work-start-project"),
|
||||
title: "Wake work start",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: process.cwd(),
|
||||
});
|
||||
const dispatch = (key: string, wake: boolean) =>
|
||||
orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
createdBy: wake ? "agent" : "user",
|
||||
creationSource: wake ? "provider" : "web",
|
||||
...(wake
|
||||
? {
|
||||
notification: {
|
||||
source: { kind: "background_task" as const },
|
||||
outcome: "updated" as const,
|
||||
summary: "Background activity updated",
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
commandId: CommandId.make(`runtime-layer-wake-work-start-${key}`),
|
||||
threadId,
|
||||
messageId: messageId(key),
|
||||
text: key,
|
||||
attachments: [],
|
||||
modelSelection,
|
||||
dispatchMode:
|
||||
key === "prompt" ? { type: "start_immediately" } : { type: "queue_after_active" },
|
||||
});
|
||||
const runFor = (key: string) =>
|
||||
Effect.map(orchestrator.getThreadProjection(threadId), ({ runs }) => {
|
||||
const run = runs.find((candidate) => candidate.userMessageId === messageId(key));
|
||||
assert.isDefined(run);
|
||||
return run;
|
||||
});
|
||||
yield* dispatch("prompt", false);
|
||||
yield* dispatch("queued", false);
|
||||
yield* dispatch("early-wake", true);
|
||||
// The early wake now runs ahead of the older queued prompt, as a
|
||||
// delegated result does when it jumps the queue.
|
||||
yield* orchestrator.dispatch({
|
||||
type: "queued-run.reorder",
|
||||
commandId: CommandId.make("runtime-layer-wake-work-start-reorder"),
|
||||
threadId,
|
||||
runId: (yield* runFor("queued")).id,
|
||||
beforeRunId: null,
|
||||
});
|
||||
yield* dispatch("late-wake", true);
|
||||
// A queued wake has no clock yet: what runs before it is still unknown.
|
||||
assert.isUndefined((yield* runFor("early-wake")).workStartedAt);
|
||||
|
||||
const startedRunIds = yield* Queue.unbounded<RunId>();
|
||||
const afterSequence = yield* orchestrator.getThreadEventSequence(threadId);
|
||||
yield* eventSink.stream({ threadId, afterSequence }).pipe(
|
||||
Stream.runForEach((stored) =>
|
||||
stored.event.type === "run.updated" && stored.event.payload.status === "starting"
|
||||
? Queue.offer(startedRunIds, stored.event.payload.id)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
// Runs start and settle the way the provider would report them.
|
||||
const settle = (key: string, startedAt: DateTime.Utc) =>
|
||||
Effect.gen(function* () {
|
||||
const run = yield* runFor(key);
|
||||
yield* eventSink.write({
|
||||
events: [
|
||||
{
|
||||
id: EventId.make(`runtime-layer-wake-work-start-${key}-completed`),
|
||||
type: "run.updated",
|
||||
threadId,
|
||||
runId: run.id,
|
||||
...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }),
|
||||
providerInstanceId: run.providerInstanceId,
|
||||
occurredAt: startedAt,
|
||||
payload: { ...run, status: "completed", startedAt, completedAt: startedAt },
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
const millis = (value: DateTime.Utc | undefined) =>
|
||||
value === undefined ? undefined : DateTime.toEpochMillis(value);
|
||||
|
||||
yield* settle("prompt", now);
|
||||
assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("early-wake")).id);
|
||||
assert.equal(millis((yield* runFor("early-wake")).workStartedAt), millis(now));
|
||||
|
||||
yield* settle("early-wake", DateTime.add(now, { seconds: 1 }));
|
||||
assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("queued")).id);
|
||||
assert.isUndefined((yield* runFor("queued")).workStartedAt);
|
||||
|
||||
// The queued prompt starts long after it was requested; the wake after it
|
||||
// counts from that start, not from the request.
|
||||
const queuedStartedAt = DateTime.add(now, { minutes: 10 });
|
||||
yield* settle("queued", queuedStartedAt);
|
||||
assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("late-wake")).id);
|
||||
assert.equal(millis((yield* runFor("late-wake")).workStartedAt), millis(queuedStartedAt));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect.each(["usage_limit", "provider_error"] as const)(
|
||||
"handles a queued message after a %s failure",
|
||||
(failureClass) =>
|
||||
|
||||
Reference in new issue
Block a user