Skip to content
TypeScript

fix(gitlab): a failed child pipeline no longer shows as a passing check (#24688)

Victor Vogel4146e511989c
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
index d4d8369f97f..86e5d3a154a 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
@@ -963,6 +963,122 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
+ it.effect("shows a failed child pipeline that left the head pipeline green", () =>
+ Effect.gen(function* () {
+ mockedExecute
+ .mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ mergeRequestJson({
+ // A fork's pipeline runs in the source project, so its id is not the target's.
+ head_pipeline: {
+ id: 31,
+ project_id: 12,
+ status: "success",
+ web_url: "https://gitlab.com/bilal/web/-/pipelines/31",
+ },
+ }),
+ ),
+ ),
+ )
+ .mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ JSON.stringify([
+ {
+ name: "deploy",
+ status: "success",
+ downstream_pipeline: {
+ status: "failed",
+ web_url: "https://gitlab.com/bilal/web/-/pipelines/32",
+ },
+ },
+ { name: "docs", status: "created", downstream_pipeline: null },
+ ]),
+ ),
+ ),
+ );
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ const detail = yield* cli.getMergeRequestDetail({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ });
+
+ expect(detail.checks.map((check) => [check.name, check.status, check.url])).toEqual([
+ ["Pipeline", "success", "https://gitlab.com/bilal/web/-/pipelines/31"],
+ ["deploy", "failure", "https://gitlab.com/bilal/web/-/pipelines/32"],
+ ]);
+ expect(argsOfCall(1)[1]).toBe("projects/12/pipelines/31/bridges?per_page=100");
+ }),
+ );
+
+ it.effect("keeps the one pipeline check when the trigger jobs cannot be read whole", () =>
+ Effect.gen(function* () {
+ const detailOutput = output(
+ mergeRequestJson({ head_pipeline: { id: 31, project_id: 12, status: "success" } }),
+ );
+ const failedChild = { name: "deploy", downstream_pipeline: { status: "failed" } };
+ mockedExecute
+ .mockReturnValueOnce(Effect.succeed(detailOutput))
+ .mockReturnValueOnce(
+ Effect.fail(
+ new GitLabCli.GitLabCliCommandError({
+ operation: "execute",
+ command: "glab",
+ cwd: "/w",
+ cause: new Error("403 Forbidden"),
+ }),
+ ),
+ )
+ .mockReturnValueOnce(Effect.succeed(detailOutput))
+ // A full page may have left out the trigger job whose pipeline failed.
+ .mockReturnValueOnce(
+ Effect.succeed(output(JSON.stringify(Array.from({ length: 100 }, () => failedChild)))),
+ );
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ for (const scenario of ["read fails", "page is full"]) {
+ const detail = yield* cli.getMergeRequestDetail({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ });
+ expect(
+ detail.checks.map((check) => [check.name, check.status]),
+ scenario,
+ ).toEqual([["Pipeline", "success"]]);
+ }
+ }),
+ );
+
+ it.effect("reads merge permissions without reading the trigger jobs", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ mergeRequestJson({
+ head_pipeline: { id: 31, project_id: 12, status: "success" },
+ user: { can_merge: false },
+ }),
+ ),
+ ),
+ );
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ const detail = yield* cli.getMergeRequestDetail({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ downstreamChecks: false,
+ });
+
+ expect(detail.viewerCanMerge).toBe(false);
+ expect(mockedExecute).toHaveBeenCalledTimes(1);
+ }),
+ );
+
it.effect("reads who has access to the project and who is already on the merge request", () =>
Effect.gen(function* () {
mockedExecute
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
index f24c4ca314e..51bc927eb9b 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
@@ -8,6 +8,7 @@ import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/co
import type {
PullRequestAction,
PullRequestActor,
+ PullRequestCheck,
PullRequestComment,
PullRequestCommit,
PullRequestInvolvement,
@@ -45,6 +46,7 @@ import {
decodeProjectLabelsJson,
decodeProjectUsersJson,
decodeRepositoryBlobsJson,
+ decodeTriggerJobChecksJson,
decodeViewerJson,
gitLabAwardName,
MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY,
@@ -245,6 +247,8 @@ export class GitLabPullRequestCli extends Context.Service<
readonly host?: string | undefined;
readonly repository: string;
readonly number: number;
+ /** `false` skips the trigger job read; the permission check before every write does. */
+ readonly downstreamChecks?: boolean;
}) => Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError>;
/** Line counts for the given merge requests; one with no answer is left out. */
@@ -996,6 +1000,29 @@ export const make = Effect.gen(function* () {
}),
);
+ // Best-effort: a trigger job read that fails, or a full page that may have left out the one
+ // whose pipeline failed, adds no rows and leaves the detail as it was.
+ const triggerJobChecks = (input: {
+ readonly cwd: string;
+ readonly pipeline: { readonly id: number; readonly projectId: number };
+ }): Effect.Effect<ReadonlyArray<PullRequestCheck>> =>
+ api({
+ cwd: input.cwd,
+ // `bridges` rather than `trigger_jobs`: GitLab 19.2 deprecates it but still serves it, and
+ // older self-managed installs know no other name.
+ path: `projects/${input.pipeline.projectId}/pipelines/${input.pipeline.id}/bridges?${query([
+ ["per_page", String(MAX_PAGE_SIZE)],
+ ])}`,
+ }).pipe(
+ Effect.map((result) => {
+ const decoded = decodeTriggerJobChecksJson(result.stdout.trim());
+ return Result.isSuccess(decoded) && decoded.success.rawCount < MAX_PAGE_SIZE
+ ? decoded.success.checks
+ : [];
+ }),
+ Effect.orElseSucceed((): ReadonlyArray<PullRequestCheck> => []),
+ );
+
const projectUsers = (input: {
readonly cwd: string;
readonly host?: string | undefined;
@@ -1297,7 +1324,19 @@ export const make = Effect.gen(function* () {
return listPage({ ...input, page, collected: [], cursorAdvance: 0 });
}),
- getMergeRequestDetail: mergeRequestDetail,
+ getMergeRequestDetail: Effect.fn("GitLabPullRequestCli.getMergeRequestDetail")(
+ function* (input) {
+ const detail = yield* mergeRequestDetail(input);
+ if (input.downstreamChecks === false || detail.headPipeline === undefined) return detail;
+ const downstream = yield* triggerJobChecks({
+ cwd: input.cwd,
+ pipeline: detail.headPipeline,
+ });
+ return downstream.length === 0
+ ? detail
+ : { ...detail, checks: [...detail.checks, ...downstream] };
+ },
+ ),
listMergeRequestStats,
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
index 0e799bd4c29..fbb8a6c21c2 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
@@ -317,7 +317,7 @@ export const make = Effect.gen(function* () {
// through on, and access granted or withdrawn within the minute must count.
getViewerPermissions: (input) =>
cli
- .getMergeRequestDetail(input)
+ .getMergeRequestDetail({ ...input, downstreamChecks: false })
.pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitLabViewerPermissions)),
forgetChangeRequestReads: (scope) =>
diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts
index d611be04465..74403b4dae9 100644
--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts
+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts
@@ -12,6 +12,7 @@ import {
decodeMergeRequestStatsJson,
decodeNotesJson,
decodeOwnAwardIdJson,
+ decodeTriggerJobChecksJson,
} from "./gitLabMergeRequestJson.ts";
function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
@@ -454,6 +455,26 @@ describe("decodeMergeRequestDiffsJson", () => {
});
});
+describe("decodeTriggerJobChecksJson", () => {
+ it("reads a downstream failure GitLab was told to allow as neutral, not failure", () => {
+ const result = expectSuccess(
+ decodeTriggerJobChecksJson(
+ JSON.stringify([
+ { name: "e2e", allow_failure: true, downstream_pipeline: { status: "failed" } },
+ { name: "deploy", allow_failure: false, downstream_pipeline: { status: "running" } },
+ { name: 7 },
+ ]),
+ ),
+ );
+
+ expect(result.checks.map((check) => [check.name, check.status])).toEqual([
+ ["e2e", "neutral"],
+ ["deploy", "pending"],
+ ]);
+ expect(result.rawCount).toBe(3);
+ });
+});
+
describe("merge request viewer fields", () => {
it("leaves merging permitted where GitLab answered without the field", () => {
expect(expectSuccess(decodeMergeRequestDetailJson(detailJson({}))).viewerCanMerge).toBe(true);
diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
index 73addf6cef6..8f50d9ea665 100644
--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
@@ -32,11 +32,19 @@ const RawUserSchema = Schema.Struct({
});
const RawPipelineSchema = Schema.Struct({
+ id: Schema.optional(Schema.NullOr(Schema.Int)),
+ project_id: Schema.optional(Schema.NullOr(Schema.Int)),
status: Schema.optional(Schema.NullOr(Schema.String)),
web_url: Schema.optional(Schema.NullOr(Schema.String)),
source: Schema.optional(Schema.NullOr(Schema.String)),
});
+const RawTriggerJobSchema = Schema.Struct({
+ name: Schema.String,
+ allow_failure: Schema.optional(Schema.NullOr(Schema.Boolean)),
+ downstream_pipeline: Schema.optional(Schema.NullOr(RawPipelineSchema)),
+});
+
const RawMergeRequestSchema = Schema.Struct({
iid: Schema.Int,
title: Schema.String,
@@ -198,6 +206,8 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
/** Absent means not counted, not up to date. */
readonly divergedCommits?: number;
readonly headSha?: string;
+ /** On a fork the pipeline often belongs to the source project, not the target. */
+ readonly headPipeline?: { readonly id: number; readonly projectId: number };
}
function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) {
@@ -331,12 +341,16 @@ function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLab
: {}),
...(raw.diverged_commits_count == null ? {} : { divergedCommits: raw.diverged_commits_count }),
...(headSha === null ? {} : { headSha }),
+ ...(raw.head_pipeline?.id == null || raw.head_pipeline.project_id == null
+ ? {}
+ : { headPipeline: { id: raw.head_pipeline.id, projectId: raw.head_pipeline.project_id } }),
};
}
const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
const decodeMergeRequestEntry = Schema.decodeUnknownExit(RawMergeRequestSchema);
const decodeMergeRequest = decodeJsonResult(RawMergeRequestSchema);
+const decodeTriggerJobEntry = Schema.decodeUnknownExit(RawTriggerJobSchema);
const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
const decodeCommitEntry = Schema.decodeUnknownExit(RawCommitSchema);
@@ -396,6 +410,42 @@ export function decodeMergeRequestDetailJson(
: Result.fail(decoded.failure);
}
+export interface GitLabTriggerJobChecks {
+ readonly checks: ReadonlyArray<PullRequestCheck>;
+ readonly rawCount: number;
+}
+
+/**
+ * Without `strategy: depend` a trigger job succeeds as soon as it starts its downstream
+ * pipeline, so the head pipeline stays green when that pipeline fails. Each row carries the
+ * downstream pipeline's own status instead of the trigger job's.
+ */
+export function decodeTriggerJobChecksJson(
+ raw: string,
+): Result.Result<GitLabTriggerJobChecks, DecodeFailure> {
+ const decoded = decodeUnknownList(raw);
+ if (!Result.isSuccess(decoded)) {
+ return Result.fail(decoded.failure);
+ }
+ const checks: PullRequestCheck[] = [];
+ for (const entry of decoded.success) {
+ const job = decodeTriggerJobEntry(entry);
+ if (Exit.isFailure(job)) continue;
+ const name = trimmed(job.value.name);
+ const downstream = job.value.downstream_pipeline;
+ if (name === null || !downstream) continue;
+ const status = toPipelineStatus(downstream.status);
+ checks.push({
+ name,
+ // The same reading as `manual`: GitLab was told this failure does not fail the pipeline.
+ status: status === "failure" && job.value.allow_failure === true ? "neutral" : status,
+ description: "Downstream pipeline",
+ url: trimmed(downstream.web_url),
+ });
+ }
+ return Result.succeed({ checks, rawCount: decoded.success.length });
+}
+
export function decodeViewerJson(raw: string): Result.Result<string | null, DecodeFailure> {
const decoded = decodeViewer(raw);
return Result.isSuccess(decoded)