Skip to content

Commit 1de3c3c

Browse files
fix(server): a pass that changes several watched pull requests wakes their thread once (#35109)
1 parent 8ef649f commit 1de3c3c

5 files changed

Lines changed: 481 additions & 78 deletions

File tree

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 149 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
OrchestrationV2Command,
3535
type OrchestrationV2InternalCommand,
3636
type OrchestrationV2LimitRecoveryUpdate,
37+
type OrchestrationV2Notification,
3738
type OrchestrationV2ServerCommand,
3839
type ThreadPullRequestLink,
3940
type ThreadPullRequestWatch,
@@ -80,6 +81,7 @@ import {
8081
import * as KeyedLock from "@t3tools/shared/KeyedLock";
8182
import { modelSelectionsEqual } from "@t3tools/shared/model";
8283
import { modelSwitchSince } from "./modelSwitch.ts";
84+
import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts";
8385
import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
8486
import {
8587
backgroundWorkHoldsCompletion,
@@ -964,14 +966,21 @@ function pullRequestSnapshotEndsWatch(
964966
);
965967
}
966968

967-
function isStalePullRequestWatchWake(
969+
type MonitorPullRequestStamp = NonNullable<
970+
Extract<OrchestrationV2Notification["source"], { readonly kind: "monitor" }>["pullRequest"]
971+
>;
972+
973+
function monitorPullRequestStamps(
974+
source: OrchestrationV2Notification["source"] | undefined,
975+
): ReadonlyArray<MonitorPullRequestStamp> {
976+
if (source?.kind !== "monitor" || source.pullRequest === undefined) return [];
977+
return [source.pullRequest, ...(source.otherPullRequests ?? [])];
978+
}
979+
980+
function isStalePullRequestWatchStamp(
968981
projection: Pick<OrchestrationV2ThreadProjection, "thread" | "messages">,
969-
run: OrchestrationV2Run,
982+
stamp: MonitorPullRequestStamp,
970983
): boolean {
971-
const source = projection.messages.find((message) => message.id === run.userMessageId)
972-
?.notification?.source;
973-
if (source?.kind !== "monitor" || source.pullRequest === undefined) return false;
974-
const stamp = source.pullRequest;
975984
const link = threadPullRequestsOf(projection.thread).find(
976985
(candidate) =>
977986
candidate.source !== "stack-dismissed" && threadPullRequestKeysEqual(candidate, stamp),
@@ -984,15 +993,14 @@ function isStalePullRequestWatchWake(
984993
}
985994
if (link.watch === undefined) {
986995
// A watch the server ended with a final notice still owes the wakes it queued before it.
987-
const endedWithNotice = projection.messages.some((message) => {
988-
const ending = message.notification?.source;
989-
return (
990-
ending?.kind === "monitor" &&
991-
ending.pullRequest?.watchEnded === true &&
992-
ending.pullRequest.watchStartedAt === stamp.watchStartedAt &&
993-
threadPullRequestKeysEqual(ending.pullRequest, stamp)
994-
);
995-
});
996+
const endedWithNotice = projection.messages.some((message) =>
997+
monitorPullRequestStamps(message.notification?.source).some(
998+
(ending) =>
999+
ending.watchEnded === true &&
1000+
ending.watchStartedAt === stamp.watchStartedAt &&
1001+
threadPullRequestKeysEqual(ending, stamp),
1002+
),
1003+
);
9961004
return (
9971005
!endedWithNotice ||
9981006
link.endedWatch?.startedAt !== stamp.watchStartedAt ||
@@ -1006,6 +1014,58 @@ function isStalePullRequestWatchWake(
10061014
);
10071015
}
10081016

1017+
function isStalePullRequestWatchWake(
1018+
projection: Pick<OrchestrationV2ThreadProjection, "thread" | "messages">,
1019+
run: OrchestrationV2Run,
1020+
): boolean {
1021+
const stamps = monitorPullRequestStamps(
1022+
projection.messages.find((message) => message.id === run.userMessageId)?.notification?.source,
1023+
);
1024+
return (
1025+
stamps.length > 0 && stamps.every((stamp) => isStalePullRequestWatchStamp(projection, stamp))
1026+
);
1027+
}
1028+
1029+
/**
1030+
* A queued wake covering several pull requests, rebuilt from the ones still current, or
1031+
* undefined when it needs no change.
1032+
*/
1033+
function currentPullRequestWatchWake(
1034+
projection: Pick<OrchestrationV2ThreadProjection, "thread" | "messages">,
1035+
run: OrchestrationV2Run,
1036+
): OrchestrationV2ConversationMessage | undefined {
1037+
const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
1038+
const stamps = monitorPullRequestStamps(message?.notification?.source);
1039+
if (message === undefined || stamps.length < 2) return undefined;
1040+
const current = stamps.filter((stamp) => !isStalePullRequestWatchStamp(projection, stamp));
1041+
const [first, ...rest] = current;
1042+
if (first === undefined || rest.length === stamps.length - 1) return undefined;
1043+
const sections = current.flatMap(({ section }) => (section === undefined ? [] : [section]));
1044+
if (sections.length !== current.length) return undefined;
1045+
const wake = combinePullRequestWatchWakes(
1046+
sections.map(({ text, outcome, summary }) => ({
1047+
text,
1048+
notification: { source: { kind: "monitor" }, outcome, summary },
1049+
})) as [PullRequestWatchWake, ...Array<PullRequestWatchWake>],
1050+
);
1051+
return {
1052+
...message,
1053+
text: wake.text,
1054+
notification: {
1055+
...wake.notification,
1056+
source: {
1057+
kind: "monitor",
1058+
pullRequest: rest.length === 0 ? withoutSection(first) : first,
1059+
...(rest.length === 0 ? {} : { otherPullRequests: rest }),
1060+
},
1061+
},
1062+
};
1063+
}
1064+
1065+
function withoutSection({ section: _, ...stamp }: MonitorPullRequestStamp) {
1066+
return stamp;
1067+
}
1068+
10091069
function queuedRunCancellationEvents(
10101070
projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "attempts">,
10111071
run: OrchestrationV2Run,
@@ -2117,6 +2177,28 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
21172177
projection = yield* readCommandProjection(threadId);
21182178
storedQueuedRun = nextQueuedRun(projection);
21192179
}
2180+
// A wake that outlived some of its pull requests tells only the current ones.
2181+
const currentWake =
2182+
storedQueuedRun === undefined
2183+
? undefined
2184+
: currentPullRequestWatchWake(projection, storedQueuedRun);
2185+
if (storedQueuedRun !== undefined && currentWake !== undefined) {
2186+
const now = yield* DateTime.now;
2187+
yield* writeSystemEvents([
2188+
{
2189+
type: "message.updated",
2190+
threadId,
2191+
runId: storedQueuedRun.id,
2192+
...(storedQueuedRun.rootNodeId === null ? {} : { nodeId: storedQueuedRun.rootNodeId }),
2193+
providerInstanceId: storedQueuedRun.providerInstanceId,
2194+
occurredAt: now,
2195+
payload: { ...currentWake, updatedAt: now },
2196+
},
2197+
]);
2198+
const runId = storedQueuedRun.id;
2199+
projection = yield* readCommandProjection(threadId);
2200+
storedQueuedRun = projection.runs.find((run) => run.id === runId);
2201+
}
21202202
if (storedQueuedRun === undefined) {
21212203
return;
21222204
}
@@ -3554,57 +3636,79 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
35543636
(cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
35553637
),
35563638
);
3557-
const key = normalizeThreadPullRequestKey(command);
3558-
const link = threadPullRequestsOf(thread).find(
3559-
(candidate) =>
3560-
candidate.source !== "stack-dismissed" && threadPullRequestKeysEqual(candidate, key),
3561-
);
3639+
const { others = [], wake, ...primary } = command;
3640+
const entries = [
3641+
{ ...primary, includesRemarks: wake?.includesRemarks },
3642+
...others.map((other) => ({
3643+
type: primary.type,
3644+
commandId: primary.commandId,
3645+
threadId: primary.threadId,
3646+
...other,
3647+
})),
3648+
].map((entry) => {
3649+
const key = normalizeThreadPullRequestKey(entry);
3650+
const link = threadPullRequestsOf(thread).find(
3651+
(candidate) =>
3652+
candidate.source !== "stack-dismissed" && threadPullRequestKeysEqual(candidate, key),
3653+
);
3654+
return { entry, key, link };
3655+
});
35623656
const inactive =
35633657
thread.archivedAt !== null ||
35643658
thread.settledOverride === "settled" ||
35653659
thread.settledAt !== null ||
35663660
isProviderNativeSubagentThread(thread);
3567-
if (link?.watch?.startedAt !== command.startedAt || (command.wake && inactive)) {
3661+
// An idle thread dispatches immediately, bypassing queued-wake validation.
3662+
const outdated = entries.map(
3663+
({ entry, link }) =>
3664+
wake?.notification.source.kind === "monitor" &&
3665+
entry.watch !== null &&
3666+
pullRequestSnapshotEndsWatch(link?.snapshot ?? null, entry.startedAt),
3667+
);
3668+
if (
3669+
entries.some(({ entry, link }) => link?.watch?.startedAt !== entry.startedAt) ||
3670+
(wake && inactive) ||
3671+
// One wake cannot drop the news of just some of its pull requests; the sender splits it.
3672+
(entries.length > 1 && outdated.some(Boolean))
3673+
) {
35683674
return yield* new OrchestratorDispatchError({
35693675
commandId: command.commandId,
35703676
commandType: command.type,
35713677
cause: "The pull request watch ended or its thread settled while it was read.",
35723678
});
35733679
}
3574-
yield* dispatchThreadMutation(command, events, effects);
3575-
if (command.wake === undefined) return;
3576-
// An idle thread dispatches immediately, bypassing queued-wake validation.
3577-
if (
3578-
command.wake.notification.source.kind === "monitor" &&
3579-
command.watch !== null &&
3580-
pullRequestSnapshotEndsWatch(link.snapshot, command.startedAt)
3581-
) {
3582-
return;
3583-
}
3680+
for (const { entry } of entries) {
3681+
const { includesRemarks: _, ...mutation } = entry;
3682+
yield* dispatchThreadMutation(mutation, events, effects);
3683+
}
3684+
if (wake === undefined || outdated[0]) return;
3685+
const { sections, ...wakeMessage } = wake;
3686+
const stamps = entries.map(({ entry, key }, index) => ({
3687+
...key,
3688+
watchStartedAt: entry.startedAt,
3689+
headSha: entry.includesRemarks === true ? null : (entry.watch?.headSha ?? null),
3690+
...(entry.watch === null ? { watchEnded: true } : {}),
3691+
...(entries.length > 1 && sections?.[index] !== undefined
3692+
? { section: sections[index] }
3693+
: {}),
3694+
}));
35843695
yield* dispatchMessage(
35853696
{
35863697
type: "message.dispatch",
35873698
commandId: command.commandId,
35883699
threadId: command.threadId,
3589-
messageId: command.wake.messageId,
3590-
text: command.wake.text,
3700+
messageId: wakeMessage.messageId,
3701+
text: wakeMessage.text,
35913702
notification: {
3592-
...command.wake.notification,
3703+
...wakeMessage.notification,
35933704
source:
3594-
command.wake.notification.source.kind === "monitor"
3705+
wake.notification.source.kind === "monitor"
35953706
? {
35963707
kind: "monitor",
3597-
pullRequest: {
3598-
...key,
3599-
watchStartedAt: command.startedAt,
3600-
headSha:
3601-
command.wake.includesRemarks === true
3602-
? null
3603-
: (command.watch?.headSha ?? null),
3604-
...(command.watch === null ? { watchEnded: true } : {}),
3605-
},
3708+
pullRequest: stamps[0]!,
3709+
...(stamps.length > 1 ? { otherPullRequests: stamps.slice(1) } : {}),
36063710
}
3607-
: command.wake.notification.source,
3711+
: wake.notification.source,
36083712
},
36093713
attachments: [],
36103714
dispatchMode: { type: "queue_after_active" },

0 commit comments

Comments
 (0)