Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadSettlementService.ts

515 lines19.9 KB

1import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
2import {
3 CommandId,
4 type ThreadId,
5 type OrchestrationV2DomainEvent,
6 type OrchestrationV2ThreadShell,
7} from "@t3tools/contracts";
8import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
9import * as Cause from "effect/Cause";
10import * as Context from "effect/Context";
11import * as Crypto from "effect/Crypto";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Schedule from "effect/Schedule";
17import type * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19​
20import * as GitManager from "../git/GitManager.ts";
21import * as PullRequestService from "../pullRequest/PullRequestService.ts";
22import * as ServerSettings from "../serverSettings.ts";
23import { forkParked } from "../serverActivation.ts";
24import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
25import { OrchestratorV2 } from "./Orchestrator.ts";
26import { ProjectionStoreV2, type ProjectionSettlementCandidate } from "./ProjectionStore.ts";
27​
28export interface SettlementPullRequest {
29 readonly state: "open" | "closed" | "merged";
30 readonly closedAt?: string | null;
31 readonly mergedAt?: string | null;
33​
34const DAY_MS = 24 * 60 * 60 * 1_000;
35export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
36​
37function toMillis(value: DateTime.Utc | null | undefined): number | null {
38 return value == null ? null : DateTime.toEpochMillis(value);
40​
41function latestMillis(values: ReadonlyArray<number | null>): number | null {
42 let latest: number | null = null;
43 for (const value of values) {
44 if (value === null) continue;
45 if (latest === null || value > latest) latest = value;
46 }
47 return latest;
49​
50function canonicalRepositoryKey(key: string): string {
51 return key
52 .replace(
53 /^(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)\/v3\/([^/]+)\/([^/]+)\/([^/]+)$/u,
54 "dev.azure.com/$1/$2/_git/$3",
55 )
56 .replace(
57 /^([^.]+)\.visualstudio\.com\/(?:defaultcollection\/)?([^/]+)\/_git\/([^/]+)$/u,
58 "dev.azure.com/$1/$2/_git/$3",
59 );
61​
62function pullRequestMatchesProject(
63 pullRequest: GitManager.GitBranchPullRequest,
64 project: {
65 readonly repositoryIdentity?: { readonly canonicalKey: string } | null | undefined;
66 },
67): boolean {
68 return (
69 pullRequest.repositoryKey !== null &&
70 project.repositoryIdentity != null &&
71 canonicalRepositoryKey(pullRequest.repositoryKey) ===
72 canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
73 );
75​
76/**
77 * A recent user message stays queued until a run adopts its timestamp.
78 * Absolute age bounds client clock skew in both directions and stops stale
79 * pre-adoption data from blocking the thread forever. A failed run start
80 * clears the block immediately (mirrors the v1 session "error" rule).
81 */
82export function threadHasQueuedTurnStart(
83 thread: Pick<
84 OrchestrationV2ThreadShell,
85 | "latestUserMessageAt"
86 | "latestRunRequestedAt"
87 | "latestRunStartedAt"
88 | "latestRunCompletedAt"
89 | "latestRunId"
90 | "status"
91 >,
92 nowMs: number,
93): boolean {
94 const messageAtMs = toMillis(thread.latestUserMessageAt);
95 if (messageAtMs === null || thread.status === "failed") return false;
96 const age = nowMs - messageAtMs;
97 if (Number.isNaN(age) || Math.abs(age) > QUEUED_TURN_START_GRACE_MS) return false;
98 if (thread.latestRunId === null) return true;
99 return [
100 toMillis(thread.latestRunRequestedAt),
101 toMillis(thread.latestRunStartedAt),
102 toMillis(thread.latestRunCompletedAt),
103 ].every((value) => value === null || value < messageAtMs);
105​
106function pullRequestSettles(
107 thread: Pick<
108 OrchestrationV2ThreadShell,
109 "createdAt" | "latestUserMessageAt" | "latestRunRequestedAt"
110 >,
111 pullRequest: SettlementPullRequest,
112 autoSettleOnMerge: boolean,
113): boolean {
114 if (pullRequest.state !== "closed" && (pullRequest.state !== "merged" || !autoSettleOnMerge)) {
115 return false;
116 }
117 const terminalAt = pullRequest.state === "merged" ? pullRequest.mergedAt : pullRequest.closedAt;
118 if (terminalAt == null) return false;
119 const userAnchorMs = latestMillis([
120 toMillis(thread.createdAt),
121 toMillis(thread.latestUserMessageAt),
122 toMillis(thread.latestRunRequestedAt),
123 ]);
124 if (userAnchorMs === null) return false;
125 const pullRequestAtMs = Date.parse(terminalAt);
126 if (Number.isNaN(pullRequestAtMs)) return false;
127 return pullRequestAtMs >= userAnchorMs;
129​
130/** Cheap checks that run before any source control lookup. */
131export function isAutoSettlementCandidate(
132 thread: ProjectionSettlementCandidate,
133 nowMs: number,
134): boolean {
135 if (thread.archivedAt !== null || thread.settledOverride !== null) return false;
136 if (thread.pinnedAt != null) return false;
137 // Blocked-on-you work must never park behind a settled override.
138 if (thread.pendingRuntimeRequest !== null) return false;
139 // A live run — or post-settlement background work — is not staleness.
140 if (thread.activityRunStatus != null) return false;
141 if ((thread.pendingBackgroundTasks?.length ?? 0) > 0) return false;
142 if (threadHasQueuedTurnStart(thread, nowMs)) return false;
143 const snoozedUntilMs = toMillis(thread.snoozedUntil);
144 if (snoozedUntilMs === null || snoozedUntilMs <= nowMs) return true;
145 // A snoozed thread that woke early (error or completed work) can settle;
146 // one still parked on its wake time keeps its stronger statement.
147 const snoozedAtMs = toMillis(thread.snoozedAt);
148 const completedAtMs = toMillis(thread.latestRunCompletedAt);
149 const wokeOnError =
150 thread.status === "failed" &&
151 (snoozedAtMs === null || (completedAtMs !== null && completedAtMs > snoozedAtMs));
152 const wokeOnCompletion =
153 snoozedAtMs !== null && completedAtMs !== null && completedAtMs > snoozedAtMs;
154 return wokeOnError || wokeOnCompletion;
156​
157export function resolveAutoSettlementAt(input: {
158 readonly thread: ProjectionSettlementCandidate;
159 readonly pullRequest: SettlementPullRequest | null;
160 readonly nowMs: number;
161 readonly autoSettleAfterDays: number | null;
162 readonly autoSettleOnMerge: boolean;
163}): DateTime.Utc | null {
164 const { thread, pullRequest } = input;
165 if (!isAutoSettlementCandidate(thread, input.nowMs)) return null;
166 const activityAtMs = latestMillis([
167 toMillis(thread.latestUserMessageAt),
168 toMillis(thread.latestRunRequestedAt),
169 toMillis(thread.latestRunStartedAt),
170 toMillis(thread.latestRunCompletedAt),
171 ]);
172 if (pullRequest !== null && pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) {
173 return activityAtMs === null ? thread.createdAt : DateTime.makeUnsafe(activityAtMs);
174 }
175 if (input.autoSettleAfterDays === null || activityAtMs === null) return null;
176 return activityAtMs < input.nowMs - input.autoSettleAfterDays * DAY_MS
177 ? DateTime.makeUnsafe(activityAtMs)
178 : null;
180​
181export class ThreadSettlementServiceV2 extends Context.Service<
182 ThreadSettlementServiceV2,
183 {
184 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
185 readonly drain: Effect.Effect<void>;
186 }
187>()("t3/orchestration-v2/ThreadSettlementService/ThreadSettlementServiceV2") {}
188​
189function autoSettlementConfigured(settings: import("@t3tools/contracts").ServerSettings): boolean {
190 if (settings.sidebarAutoSettleOnMerge || settings.sidebarAutoSettleAfterDays !== null) {
191 return true;
192 }
193 return Object.values(settings.projectSettingsOverrides).some(
194 (entry) =>
195 entry.sidebarAutoSettleOnMerge === true ||
196 (entry.sidebarAutoSettleAfterDays !== undefined && entry.sidebarAutoSettleAfterDays !== null),
197 );
199​
200/** Identity of every settlement input, so unrelated settings edits do not trigger a sweep. */
201/** @internal Exported for tests. */
202export function autoSettlementSettingsKey(
203 settings: import("@t3tools/contracts").ServerSettings,
204): string {
205 return JSON.stringify([
206 settings.sidebarAutoSettleOnMerge,
207 settings.sidebarAutoSettleAfterDays,
208 // Only entries that touch settlement, in a stable order, so a project
209 // override on an unrelated key does not queue a sweep. JSON drops
210 // undefined, so inherit (absent) and never (null) need distinct marks.
211 Object.entries(settings.projectSettingsOverrides)
212 .filter(
213 ([, entry]) =>
214 entry.sidebarAutoSettleOnMerge !== undefined ||
215 entry.sidebarAutoSettleAfterDays !== undefined,
216 )
217 .sort(([left], [right]) => left.localeCompare(right))
218 .map(([projectId, entry]) => [
219 projectId,
220 entry.sidebarAutoSettleOnMerge ?? "inherit",
221 entry.sidebarAutoSettleAfterDays === undefined
222 ? "inherit"
223 : entry.sidebarAutoSettleAfterDays,
224 ]),
225 ]);
227​
228export const make = Effect.gen(function* () {
229 const orchestrator = yield* OrchestratorV2;
230 const projections = yield* ProjectionStoreV2;
231 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
232 const settingsService = yield* ServerSettings.ServerSettingsService;
233 const git = yield* GitManager.GitManager;
234 const pullRequests = yield* PullRequestService.PullRequestService;
235 const crypto = yield* Crypto.Crypto;
236 const fileSystem = yield* FileSystem.FileSystem;
237​
238 const sweep = Effect.fn("ThreadSettlementServiceV2.sweep")(function* (
239 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
240 threadId?: ThreadId,
241 ) {
242 const settings = yield* settingsService.getSettings;
243 if (!autoSettlementConfigured(settings)) {
244 return;
245 }
246 const threads = yield* projections.getSettlementCandidates();
247 const projectShells = yield* snapshots.getProjectShellsWithoutEnrichment();
248 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
249 const projects = new Map(projectShells.map((project) => [project.id, project]));
250 // A merge event re-sweeps every candidate, not just the threads linked to
251 // the merged pull request: most threads carry no link and settle from
252 // their branch lookup, which would otherwise wait for the next minute's
253 // sweep on a possibly stale cached answer.
254 const candidates = threads.filter(
255 (thread) =>
256 (threadId === undefined || thread.id === threadId) &&
257 isAutoSettlementCandidate(thread, nowMs),
258 );
259​
260 const settleThread = Effect.fn("ThreadSettlementServiceV2.settleThread")(
261 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
262 const currentSettings = resolveProjectSettings(
263 yield* settingsService.getSettings,
264 thread.projectId,
265 ).settings;
266 const decisionNow = yield* DateTime.now;
267 const settledAt = resolveAutoSettlementAt({
268 thread,
269 pullRequest,
270 nowMs: DateTime.toEpochMillis(decisionNow),
271 autoSettleAfterDays: currentSettings.sidebarAutoSettleAfterDays,
272 autoSettleOnMerge: currentSettings.sidebarAutoSettleOnMerge,
273 });
274 if (settledAt === null) return thread;
275 const uuid = yield* crypto.randomUUIDv4;
276 yield* orchestrator.dispatch({
277 type: "thread.auto-settle",
278 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
279 threadId: thread.id,
280 snapshotAt: thread.updatedAt,
281 settledAt,
282 });
283 return null;
284 },
285 (effect, thread) =>
286 effect.pipe(
287 Effect.catchCause((cause) =>
288 Cause.hasInterruptsOnly(cause)
289 ? Effect.failCause(cause)
290 : Effect.logWarning("automatic thread settlement skipped", {
291 threadId: thread.id,
292 cause: Cause.pretty(cause),
293 }).pipe(Effect.as(null)),
294 ),
295 ),
296 );
297​
298 // Inactivity is entirely projection-backed. Complete those decisions before
299 // a source-control lookup can delay or fail an otherwise eligible thread.
300 const lookupCandidates = (yield* Effect.forEach(
301 candidates,
302 (thread) => settleThread(thread, null),
303 { concurrency: 8 },
304 )).filter((thread) => thread !== null);
305 // Use the same cwd as the sidebar so both paths share GitManager's PR cache.
306 const lookupCwdByThreadId = new Map<string, string>();
307 yield* Effect.forEach(
308 lookupCandidates,
309 (thread) =>
310 Effect.gen(function* () {
311 const project = projects.get(thread.projectId);
312 if (project === undefined || thread.branch === null) return;
313 const worktreeExists =
314 thread.worktreePath !== null &&
315 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
316 lookupCwdByThreadId.set(
317 thread.id,
318 worktreeExists && thread.worktreePath !== null
319 ? thread.worktreePath
320 : project.workspaceRoot,
321 );
322 }),
323 { concurrency: 8, discard: true },
324 );
325 if (mergedPullRequest !== null) {
326 // The merge just confirmed a terminal state the lookup caches can still
327 // call open (branch answers live two minutes, the sweep runs every
328 // minute). Drop the swept checkouts' cached answers so the merge settles
329 // its branch threads now instead of on a later sweep. Threads linked to
330 // the merged pull request settle from the event itself below and need no
331 // lookup, so they are absent from this map by construction.
332 const cwds = [...new Set(lookupCwdByThreadId.values())];
333 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
334 concurrency: 8,
335 discard: true,
336 });
337 }
338 const lookupKey = (thread: (typeof lookupCandidates)[number]) => {
339 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
340 if (reference != null) {
341 return JSON.stringify([
342 "linked",
343 reference.projectId,
344 reference.repository,
345 reference.number,
346 lookupCwdByThreadId.get(thread.id),
347 thread.branch,
348 ]);
349 }
350 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
351 const cwd = lookupCwdByThreadId.get(thread.id);
352 return JSON.stringify(
353 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
354 );
355 };
356 const groups = Map.groupBy(lookupCandidates, lookupKey);
357​
358 const pullRequestFor = Effect.fn("ThreadSettlementServiceV2.pullRequestFor")(function* (
359 thread: (typeof lookupCandidates)[number],
360 ) {
361 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
362 if (reference != null) {
363 // The event carries the merged state, so only the threads linked to
364 // that exact pull request settle from it. Every other linked thread
365 // falls through to a fresh summary lookup below: the merge sweep
366 // covers all candidates, and an unrelated merge must never settle
367 // them.
368 const matchesMerge =
369 mergedPullRequest !== null &&
370 reference.projectId === mergedPullRequest.projectId &&
371 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
372 reference.number === mergedPullRequest.number;
373 if (!matchesMerge && !projects.has(reference.projectId)) {
374 return yield* Effect.die(new Error("linked pull request project not found"));
375 }
376 const summary = matchesMerge
377 ? ({
378 state: "merged",
379 closedAt: null,
380 mergedAt: mergedPullRequest.mergedAt,
381 } satisfies SettlementPullRequest)
382 : yield* pullRequests.summary(
383 {
384 projectId: reference.projectId,
385 repository: reference.repository,
386 number: reference.number,
387 },
388 { recoverTransientFailure: false },
389 );
390 const cwd = lookupCwdByThreadId.get(thread.id);
391 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
392 const current = yield* git.branchPullRequest(
393 { cwd, branch: thread.branch },
394 { refresh: true },
395 );
396 const project = projects.get(thread.projectId);
397 if (
398 current?.state === "open" &&
399 project !== undefined &&
400 pullRequestMatchesProject(current, project)
401 ) {
402 return current;
403 }
404 }
405 return {
406 state: summary.state,
407 closedAt: summary.closedAt ?? null,
408 mergedAt: summary.mergedAt ?? null,
409 } satisfies SettlementPullRequest;
410 }
411 if (thread.branch === null) return null;
412 const cwd = lookupCwdByThreadId.get(thread.id);
413 if (cwd === undefined) {
414 return yield* Effect.die(new Error("thread project not found"));
415 }
416 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
417 });
418​
419 yield* Effect.forEach(
420 groups.values(),
421 (group) =>
422 Effect.gen(function* () {
423 const pullRequest = yield* pullRequestFor(group[0]!);
424 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
425 discard: true,
426 });
427 }).pipe(
428 Effect.catchCause((cause) =>
429 Cause.hasInterruptsOnly(cause)
430 ? Effect.failCause(cause)
431 : Effect.logWarning("automatic thread settlement skipped", {
432 threadIds: group.map((thread) => thread.id),
433 cause: Cause.pretty(cause),
434 }),
435 ),
436 ),
437 { concurrency: 8, discard: true },
438 );
439 });
440​
441 const runSweep = (
442 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
443 threadId?: ThreadId,
444 ) =>
445 sweep(mergedPullRequest, threadId).pipe(
446 Effect.catchCause((cause) =>
447 Cause.hasInterruptsOnly(cause)
448 ? Effect.failCause(cause)
449 : Effect.logWarning("automatic thread settlement sweep failed", {
450 cause: Cause.pretty(cause),
451 }),
452 ),
453 );
454 const worker = yield* makeDrainableWorker((threadId: ThreadId | undefined) =>
455 runSweep(null, threadId),
456 );
457​
458 const processEvent = (event: OrchestrationV2DomainEvent) => {
459 switch (event.type) {
460 case "thread.pull-request-synced":
461 case "provider-session.detached":
462 return worker.enqueue(event.threadId);
463 case "provider-session.updated":
464 return event.payload.status !== "starting" && event.payload.status !== "running"
465 ? worker.enqueue(event.threadId)
466 : Effect.void;
467 case "run.updated":
468 return ["completed", "interrupted", "failed", "cancelled", "rolled_back"].includes(
469 event.payload.status,
470 )
471 ? worker.enqueue(event.threadId)
472 : Effect.void;
473 default:
474 return Effect.void;
475 }
476 };
477​
478 const start: ThreadSettlementServiceV2["Service"]["start"] = Effect.fn(
479 "ThreadSettlementServiceV2.start",
480 )(function* () {
481 const settingsChanges = yield* settingsService.subscribeChanges;
482 const mergedPullRequests = yield* pullRequests.subscribeMerges;
483 const events = orchestrator.streamDomainEvents;
484 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
485 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
486 yield* forkParked(
487 Effect.gen(function* () {
488 yield* worker.enqueue(undefined);
489 yield* worker.drain;
490 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
491 );
492 yield* forkParked(
493 Stream.runForEach(settingsChanges, (settings) => {
494 const key = autoSettlementSettingsKey(settings);
495 if (key === lastSettlementSettings) {
496 return Effect.void;
497 }
498 lastSettlementSettings = key;
499 return worker.enqueue(undefined);
500 }),
501 );
502 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
503 yield* forkParked(
504 Stream.runForEach(events, processEvent).pipe(
505 Effect.catchCause((cause) =>
506 Effect.logWarning("Thread settlement event stream failed", { cause }),
507 ),
508 ),
509 );
510 });
511​
512 return { start, drain: worker.drain } satisfies ThreadSettlementServiceV2["Service"];
513});
514​
515export const layer = Layer.effect(ThreadSettlementServiceV2, make);