@devries-cameron20 / t3code-1 / commits / 6fae3c9303
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(gitlab): MR watches check a one-query fingerprint before full reads (#34638)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Antony committed Nov 14, 2026 at 22:49 UTC 6fae3c9303315835943327434335a1f5be03295a
7 files changed +410 -11
apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
+5 -1
@@ -186,7 +186,11 @@ function planRead(
186 !last.remarksComplete ||
187 now - last.at >= FINGERPRINT_REREAD_MS;
188 return {
189 - detail: activity || checksDue || last.status !== fingerprint.status || last.inFlight,
189 + detail:
190 + activity ||
191 + checksDue ||
192 + last.status !== fingerprint.status ||
193 + (last.inFlight && fingerprint.coversDetail !== true),
194 activity,
195 };
196 }
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+103
@@ -5262,6 +5262,109 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
5262 }),
5263 );
5264
5265 + it.effect.each([true, false])(
5266 + "rereads pending checks only on a fingerprint change when it covers them (covers: %s)",
5267 + (coversDetail) =>
5268 + Effect.gen(function* () {
5269 + const orchestrator = yield* Orchestrator.OrchestratorV2;
5270 + const threadId = ThreadId.make(`runtime-pull-request-watch-covers-${coversDetail}`);
5271 + const projectId = ProjectId.make(`pr-watch-covers-project-${coversDetail}`);
5272 + yield* seedProject({
5273 + projectId,
5274 + title: "Watch pending checks",
5275 + workspaceRoot: "/workspace/watch-covers",
5276 + defaultModelSelection: null,
5277 + createdAt: "2026-10-01T00:00:00.000Z",
5278 + });
5279 + yield* orchestrator.dispatch({
5280 + type: "thread.create",
5281 + createdBy: "user",
5282 + creationSource: "web",
5283 + commandId: CommandId.make(`pr-watch-covers-create-${coversDetail}`),
5284 + threadId,
5285 + projectId,
5286 + title: "Watch pending checks",
5287 + modelSelection,
5288 + runtimeMode: "full-access",
5289 + interactionMode: "default",
5290 + branch: null,
5291 + worktreePath: null,
5292 + });
5293 + const key = { host: "gitlab.com", repository: "acme/web", number: 15 };
5294 + yield* orchestrator.dispatch({
5295 + type: "thread.pull-request.watch",
5296 + commandId: CommandId.make(`pr-watch-covers-start-${coversDetail}`),
5297 + threadId,
5298 + ...key,
5299 + watching: true,
5300 + link: { url: "https://gitlab.com/acme/web/-/merge_requests/15", source: "agent" },
5301 + });
5302 +
5303 + let reads = 0;
5304 + let status = "running";
5305 + const host = Layer.mergeAll(
5306 + NodeServices.layer,
5307 + NodeCrypto.layer,
5308 + Layer.mock(PullRequestService.PullRequestService)({
5309 + watchFingerprint: () => Effect.sync(() => ({ status, remarks: "none", coversDetail })),
5310 + invalidate: () => Effect.void,
5311 + detail: (input) =>
5312 + Effect.sync(() => {
5313 + // Watches left by earlier cases in this layer are swept too.
5314 + if (input.projectId === projectId) reads++;
5315 + return {
5316 + ...watchedPullRequestDetail({
5317 + projectId,
5318 + number: 15,
5319 + at: "2026-10-02T12:00:00.000Z",
5320 + }),
5321 + headSha: "6074dd48ff",
5322 + checks: [
5323 + {
5324 + name: "lint",
5325 + status: "pending",
5326 + description: null,
5327 + url: null,
5328 + required: true,
5329 + },
5330 + ],
5331 + };
5332 + }),
5333 + activity: () =>
5334 + Effect.succeed({
5335 + comments: [],
5336 + commentCount: 0,
5337 + commentsTruncated: false,
5338 + reviewThreads: [],
5339 + commits: [],
5340 + }),
5341 + }),
5342 + );
5343 + const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host));
5344 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
5345 + const sweep = reactor.sweep.pipe(Effect.andThen(worker.drain()));
5346 +
5347 + yield* sweep;
5348 + yield* TestClock.adjust("2 minutes");
5349 + yield* sweep;
5350 + assert.equal(reads, coversDetail ? 1 : 2);
5351 +
5352 + status = "passed";
5353 + yield* TestClock.adjust("2 minutes");
5354 + yield* sweep;
5355 + assert.equal(reads, coversDetail ? 2 : 3);
5356 +
5357 + yield* orchestrator.dispatch({
5358 + type: "thread.pull-request.watch",
5359 + commandId: CommandId.make(`pr-watch-covers-end-${coversDetail}`),
5360 + threadId,
5361 + ...key,
5362 + watching: false,
5363 + });
5364 + yield* worker.drain();
5365 + }),
5366 + );
5367 +
5368 // regression: #21155 watching a pull request again repeated news the thread already got
5369 it.effect("watching a dismissed stack layer again keeps what its last watch told", () =>
5370 Effect.gen(function* () {
packages/source-control-core/src/server/PullRequestProvider.ts
+2
@@ -75,6 +75,8 @@ export class PullRequestProviderError extends Schema.TaggedError<PullRequestProv
75 export interface ProviderChangeRequestWatchFingerprint {
76 readonly status: string;
77 readonly remarks: string;
78 + /** True when `status` changes with every check and mergeability change, so pending work needs no detail read. */
79 + readonly coversDetail?: boolean;
80 }
81
82 export interface PullRequestProviderFailure {
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+23
@@ -56,6 +56,7 @@ import {
56 decodeMergeRequestGraphqlListJson,
57 decodeMergeRequestListJson,
58 decodeMergeRequestFileStatsJson,
59 + decodeMergeRequestWatchFingerprintJson,
60 decodeMergeRequestStatsJson,
61 decodeMutationErrorsJson,
62 decodeNotesJson,
@@ -75,6 +76,7 @@ import {
76 LABEL_PERMISSION_GRAPHQL_QUERY,
77 MERGE_MESSAGES_GRAPHQL_QUERY,
78 MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY,
79 + MERGE_REQUEST_WATCH_FINGERPRINT_GRAPHQL_QUERY,
80 MERGE_REQUEST_STATS_GRAPHQL_QUERY,
81 REPOSITORY_BLOBS_GRAPHQL_QUERY,
82 LIST_ITEM_GRAPHQL_FIELDS,
@@ -89,6 +91,7 @@ import {
91 } from "./gitLabMergeRequestJson.ts";
92 import type {
93 ProviderChangeRequestSummary,
94 + ProviderChangeRequestWatchFingerprint,
95 ProviderFileStats,
96 ProviderListCursor,
97 } from "@t3tools/source-control-core/server/PullRequestProvider";
@@ -448,6 +451,13 @@ export class GitLabPullRequestCli extends Context.Service<
451 readonly number: number;
452 }) => Effect.Effect<ProviderFileStats, GitLabPullRequestCliError>;
453
454 + readonly getMergeRequestWatchFingerprint: (input: {
455 + readonly cwd: string;
456 + readonly host?: string | undefined;
457 + readonly repository: string;
458 + readonly number: number;
459 + }) => Effect.Effect<ProviderChangeRequestWatchFingerprint | null, GitLabPullRequestCliError>;
460 +
461 readonly listNotes: (input: {
462 readonly cwd: string;
463 readonly host?: string | undefined;
@@ -2306,6 +2316,19 @@ export const make = Effect.gen(function* () {
2316 }),
2317 ),
2318
2319 + getMergeRequestWatchFingerprint: Effect.fn(
2320 + "GitLabPullRequestCli.getMergeRequestWatchFingerprint",
2321 + )((input) =>
2322 + graphqlRead({
2323 + cwd: input.cwd,
2324 + host: input.host,
2325 + operation: "getMergeRequestWatchFingerprint",
2326 + query: MERGE_REQUEST_WATCH_FINGERPRINT_GRAPHQL_QUERY,
2327 + variables: { fullPath: input.repository, iid: String(input.number) },
2328 + decode: decodeMergeRequestWatchFingerprintJson,
2329 + }),
2330 + ),
2331 +
2332 listNotes: Effect.fn("GitLabPullRequestCli.listNotes")(function (input) {
2333 return notesPage({ ...input, page: 1, collected: [] });
2334 }),
packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+5
@@ -380,6 +380,11 @@ export const make = Effect.gen(function* () {
380 })),
381 ),
382
383 + getChangeRequestWatchFingerprint: (input) =>
384 + cli
385 + .getMergeRequestWatchFingerprint(input)
386 + .pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))),
387 +
388 getChangeRequestActivity: (input) =>
389 Effect.all(
390 [
packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts
+103
@@ -13,6 +13,7 @@ import {
13 decodeMergeRequestListJson,
14 decodeMergeRequestFileStatsJson,
15 decodeMergeRequestStatsJson,
16 + decodeMergeRequestWatchFingerprintJson,
17 decodeReferenceCandidatesJson,
18 decodeNotesJson,
19 decodeOwnAwardIdJson,
@@ -1232,3 +1233,105 @@ describe("decodeMergeMessagesJson", () => {
1233 expect(Result.isFailure(decoded)).toBe(true);
1234 });
1235 });
1236 +
1237 +describe("decodeMergeRequestWatchFingerprintJson", () => {
1238 + const pipeline = (status: string, downstream: string, failed = 0, moreBridges = false) => ({
1239 + id: "gid://gitlab/Ci::Pipeline/9",
1240 + status,
1241 + succeeded: { count: 3 },
1242 + failed: { count: failed },
1243 + stopped: { count: 0 },
1244 + jobs: {
1245 + pageInfo: { hasNextPage: moreBridges },
1246 + nodes: [
1247 + {
1248 + name: "deploy",
1249 + status,
1250 + downstreamPipeline: { id: "gid://gitlab/Ci::Pipeline/10", status: downstream },
1251 + },
1252 + ],
1253 + },
1254 + });
1255 + const edit = (at: string, resolved = false) => ({
1256 + lastEditedAt: at,
1257 + lastEditedBy: { username: "reviewer" },
1258 + resolved,
1259 + });
1260 + const read = (overrides: Record<string, unknown>) =>
1261 + expectSuccess(
1262 + decodeMergeRequestWatchFingerprintJson(
1263 + JSON.stringify({
1264 + data: {
1265 + project: {
1266 + mergeRequest: {
1267 + state: "opened",
1268 + mergeStatusEnum: "CAN_BE_MERGED",
1269 + conflicts: false,
1270 + diffHeadSha: "a".repeat(40),
1271 + userPermissions: { updateMergeRequest: true },
1272 + headPipeline: pipeline("RUNNING", "RUNNING"),
1273 + userNotesCount: 2,
1274 + notes: {
1275 + nodes: [
1276 + edit("2026-07-02T00:00:00Z"),
1277 + { lastEditedAt: null, lastEditedBy: null, resolved: null },
1278 + edit("2026-07-01T00:00:00Z"),
1279 + ],
1280 + },
1281 + ...overrides,
1282 + },
1283 + },
1284 + },
1285 + }),
1286 + ),
1287 + );
1288 +
1289 + // A remarks change makes the watch reread every comment, so pipeline progress must not touch it.
1290 + it("moves pipeline progress into status and comment edits into remarks", () => {
1291 + const base = read({});
1292 + const passed = read({ headPipeline: pipeline("SUCCESS", "RUNNING") });
1293 + const downstreamPassed = read({ headPipeline: pipeline("SUCCESS", "SUCCESS") });
1294 + const jobFailed = read({ headPipeline: pipeline("RUNNING", "RUNNING", 1) });
1295 + const edited = read({ notes: { nodes: [edit("2026-07-03T00:00:00Z")] } });
1296 + // Resolving a thread restamps its notes without an edit, so it must not reread comments.
1297 + const resolved = read({
1298 + notes: { nodes: [edit("2026-07-02T00:00:00Z"), edit("2026-07-03T00:00:00Z", true)] },
1299 + });
1300 +
1301 + expect(base?.remarks).toBe("2 2026-07-02T00:00:00Z");
1302 + expect(passed?.status).not.toBe(base?.status);
1303 + expect(downstreamPassed?.status).not.toBe(passed?.status);
1304 + expect(jobFailed?.status).not.toBe(base?.status);
1305 + expect(passed?.remarks).toBe(base?.remarks);
1306 + expect(edited?.status).toBe(base?.status);
1307 + expect(edited?.remarks).not.toBe(base?.remarks);
1308 + expect(resolved?.remarks).toBe(base?.remarks);
1309 + expect(read({ userNotesCount: 3 })?.remarks).not.toBe(base?.remarks);
1310 + });
1311 +
1312 + // Only the REST read asks GitLab to recheck mergeability, and only for viewers who can update.
1313 + it("covers the detail read once merge status has settled or no read could settle it", () => {
1314 + expect(read({})?.coversDetail).toBe(true);
1315 + // A capped job count or a second bridge page can hide a job settling.
1316 + expect(read({ headPipeline: pipeline("RUNNING", "RUNNING", 1001) })?.coversDetail).toBe(false);
1317 + expect(read({ headPipeline: pipeline("RUNNING", "RUNNING", 0, true) })?.coversDetail).toBe(
1318 + false,
1319 + );
1320 + expect(read({ mergeStatusEnum: "UNCHECKED" })?.coversDetail).toBe(false);
1321 + expect(read({ mergeStatusEnum: "CHECKING", conflicts: true })?.coversDetail).toBe(true);
1322 + expect(
1323 + read({ mergeStatusEnum: "UNCHECKED", userPermissions: { updateMergeRequest: false } })
1324 + ?.coversDetail,
1325 + ).toBe(true);
1326 + });
1327 +
1328 + it("answers null when GitLab returned no merge request", () => {
1329 + expect(
1330 + expectSuccess(
1331 + decodeMergeRequestWatchFingerprintJson(
1332 + JSON.stringify({ data: { project: { mergeRequest: null } } }),
1333 + ),
1334 + ),
1335 + ).toBeNull();
1336 + });
1337 +});
packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+169 -10
@@ -25,6 +25,7 @@ import type {
25 import { TrimmedNonEmptyString } from "@t3tools/contracts";
26 import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
27 import { decodeJsonResult } from "@t3tools/shared/schemaJson";
28 +import type { ProviderChangeRequestWatchFingerprint } from "@t3tools/source-control-core/server/PullRequestProvider";
29
30 /** Unknown pipeline or merge status values must not fail the whole payload. */
31 const RawUserSchema = Schema.Struct({
@@ -1214,6 +1215,25 @@ function toReactions(
1215 );
1216 }
1217
1218 +/**
1219 + * Resolving a thread moves lastEditedAt on every note in it; only lastEditedBy marks a text
1220 + * edit, and a resolved note's stamp may be the resolve rather than that edit.
1221 + */
1222 +function textEditedAt(
1223 + note: {
1224 + readonly lastEditedAt?: string | null | undefined;
1225 + readonly lastEditedBy?: { readonly username?: string | null | undefined } | null | undefined;
1226 + readonly resolved?: boolean | null | undefined;
1227 + } | null,
1228 +): string | null {
1229 + const editedAt = trimmed(note?.lastEditedAt);
1230 + return editedAt !== null &&
1231 + trimmed(note?.lastEditedBy?.username) !== null &&
1232 + note?.resolved !== true
1233 + ? editedAt
1234 + : null;
1235 +}
1236 +
1237 function noteIdOf(gid: string | null | undefined): string | null {
1238 const id = trimmed(gid)?.split("/").at(-1);
1239 return id !== undefined && /^\d+$/.test(id) ? id : null;
@@ -1247,16 +1267,8 @@ export function decodeAwardEmojiJson(
1267 if (id === null) continue;
1268 const reactions = toReactions(node?.awardEmoji, viewer);
1269 if (reactions.length > 0) reactionsByNoteId.set(id, reactions);
1250 - // Resolving a thread moves lastEditedAt on every note in it; only lastEditedBy marks a
1251 - // text edit, and a resolved note's stamp may be the resolve rather than that edit.
1252 - const editedAt = trimmed(node?.lastEditedAt);
1253 - if (
1254 - editedAt !== null &&
1255 - trimmed(node?.lastEditedBy?.username) !== null &&
1256 - node?.resolved !== true
1257 - ) {
1258 - editedAtByNoteId.set(id, editedAt);
1259 - }
1270 + const editedAt = textEditedAt(node);
1271 + if (editedAt !== null) editedAtByNoteId.set(id, editedAt);
1272 }
1273 const pageInfo = mergeRequest?.notes?.pageInfo;
1274 return Result.succeed({
@@ -2041,3 +2053,150 @@ export function decodeMergeRequestFileStatsJson(raw: string): Result.Result<
2053 const fileCount = mergeRequest?.diffStatsSummary?.fileCount;
2054 return Result.succeed({ files, truncated: fileCount === undefined || files.length < fileCount });
2055 }
2056 +
2057 +/**
2058 + * One cheap read that tells a watch whether anything it reports on changed. Edits to comments
2059 + * older than the newest 100 are missed here and left to the watch's periodic full reread.
2060 + * Finished job counts move whenever one job settles while its pipeline still runs, and bridge
2061 + * jobs are read because their downstream pipelines are checks of their own.
2062 + */
2063 +export const MERGE_REQUEST_WATCH_FINGERPRINT_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {
2064 + project(fullPath: $fullPath) {
2065 + mergeRequest(iid: $iid) {
2066 + state mergeStatusEnum conflicts diffHeadSha
2067 + userPermissions { updateMergeRequest }
2068 + headPipeline {
2069 + id status
2070 + succeeded: jobs(retried: false, statuses: [SUCCESS]) { count }
2071 + failed: jobs(retried: false, statuses: [FAILED]) { count }
2072 + stopped: jobs(retried: false, statuses: [CANCELED, SKIPPED]) { count }
2073 + jobs(jobKind: BRIDGE, retried: false, first: 100) {
2074 + pageInfo { hasNextPage }
2075 + nodes { name status downstreamPipeline { id status } }
2076 + }
2077 + }
2078 + userNotesCount
2079 + notes(filter: ONLY_COMMENTS, last: 100) {
2080 + nodes { lastEditedAt lastEditedBy { username } resolved }
2081 + }
2082 + }
2083 + }
2084 +}`;
2085 +
2086 +const PipelineIdentitySchema = Schema.Struct({ id: Schema.String, status: Schema.String });
2087 +const JobCountSchema = Schema.NullOr(Schema.Struct({ count: Schema.Int }));
2088 +// GitLab's connection `count` stops at its default limit and answers `limit + 1` above it.
2089 +const JOB_COUNT_LIMIT = 1000;
2090 +
2091 +const decodeMergeRequestWatchFingerprint = decodeJsonResult(
2092 + Schema.Struct({
2093 + data: Schema.Struct({
2094 + project: Schema.NullOr(
2095 + Schema.Struct({
2096 + mergeRequest: Schema.NullOr(
2097 + Schema.Struct({
2098 + state: Schema.String,
2099 + mergeStatusEnum: Schema.NullOr(Schema.String),
2100 + conflicts: Schema.Boolean,
2101 + diffHeadSha: Schema.NullOr(Schema.String),
2102 + userPermissions: Schema.Struct({ updateMergeRequest: Schema.Boolean }),
2103 + headPipeline: Schema.NullOr(
2104 + Schema.Struct({
2105 + ...PipelineIdentitySchema.fields,
2106 + succeeded: JobCountSchema,
2107 + failed: JobCountSchema,
2108 + stopped: JobCountSchema,
2109 + jobs: Schema.NullOr(
2110 + Schema.Struct({
2111 + pageInfo: Schema.Struct({ hasNextPage: Schema.Boolean }),
2112 + nodes: Schema.Array(
2113 + Schema.NullOr(
2114 + Schema.Struct({
2115 + name: Schema.NullOr(Schema.String),
2116 + status: Schema.NullOr(Schema.String),
2117 + downstreamPipeline: Schema.NullOr(PipelineIdentitySchema),
2118 + }),
2119 + ),
2120 + ),
2121 + }),
2122 + ),
2123 + }),
2124 + ),
2125 + userNotesCount: Schema.NullOr(Schema.Int),
2126 + notes: Schema.Struct({
2127 + nodes: Schema.Array(
2128 + Schema.NullOr(
2129 + Schema.Struct({
2130 + lastEditedAt: Schema.NullOr(Schema.String),
2131 + lastEditedBy: Schema.NullOr(
2132 + Schema.Struct({ username: Schema.NullOr(Schema.String) }),
2133 + ),
2134 + resolved: Schema.NullOr(Schema.Boolean),
2135 + }),
2136 + ),
2137 + ),
2138 + }),
2139 + }),
2140 + ),
2141 + }),
2142 + ),
2143 + }),
2144 + }),
2145 +);
2146 +
2147 +/** Null when GitLab returned no merge request, so the watch falls back to full reads. */
2148 +export function decodeMergeRequestWatchFingerprintJson(
2149 + raw: string,
2150 +): Result.Result<ProviderChangeRequestWatchFingerprint | null, DecodeFailure> {
2151 + const decoded = decodeMergeRequestWatchFingerprint(raw);
2152 + if (!Result.isSuccess(decoded)) {
2153 + return Result.fail(decoded.failure);
2154 + }
2155 + const mr = decoded.success.data.project?.mergeRequest;
2156 + if (mr == null) return Result.succeed(null);
2157 + const newestEdit = mr.notes.nodes.reduce((newest, note) => {
2158 + const editedAt = textEditedAt(note);
2159 + return editedAt !== null && editedAt > newest ? editedAt : newest;
2160 + }, "");
2161 + const pipeline = mr.headPipeline;
2162 + const jobCounts = [pipeline?.succeeded, pipeline?.failed, pipeline?.stopped].map(
2163 + (jobs) => jobs?.count ?? null,
2164 + );
2165 + // Past a capped count or the first bridge page, a job can settle without moving the status.
2166 + const seesEveryJob =
2167 + pipeline?.jobs?.pageInfo.hasNextPage !== true &&
2168 + jobCounts.every((count) => count === null || count <= JOB_COUNT_LIMIT);
2169 + const bridges = (pipeline?.jobs?.nodes ?? [])
2170 + .flatMap((job) =>
2171 + job === null
2172 + ? []
2173 + : [
2174 + [job.name, job.status, job.downstreamPipeline?.id, job.downstreamPipeline?.status]
2175 + .map((part) => part ?? "")
2176 + .join(":"),
2177 + ],
2178 + )
2179 + .toSorted()
2180 + .join(",");
2181 + return Result.succeed({
2182 + status: [
2183 + mr.state,
2184 + mr.mergeStatusEnum ?? "",
2185 + mr.conflicts,
2186 + mr.diffHeadSha ?? "",
2187 + pipeline?.id ?? "",
2188 + pipeline?.status ?? "",
2189 + jobCounts.map((count) => count ?? "").join("/"),
2190 + bridges,
2191 + ].join(" "),
2192 + remarks: [mr.userNotesCount ?? "", newestEdit].join(" "),
2193 + // GraphQL never asks GitLab to recheck mergeability. The REST detail read does, but only for
2194 + // viewers who can update the merge request, so only they keep detail reads going until it settles.
2195 + coversDetail:
2196 + seesEveryJob &&
2197 + (mr.conflicts ||
2198 + !mr.userPermissions.updateMergeRequest ||
2199 + mr.mergeStatusEnum === "CAN_BE_MERGED" ||
2200 + mr.mergeStatusEnum === "CANNOT_BE_MERGED"),
2201 + });
2202 +}