Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions plugins/stewards/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1085,8 +1085,25 @@ describe("roles.json backlog role (BB-332, BB-395)", () => {
it("leaves a role without backlog exactly as before", () => {
const parsed = backlog({ k8sNamespaces: ["prod"] });
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value.definitions.backlog).toStrictEqual({ k8sNamespaces: ["prod"], autoAdopt: [], sentry: { projects: [], resolveOnDone: false }, alertmanager: { namespaces: [] }, pulls: [] });
expect(parsed.value.roles["trotterdylan"]!.ops).toStrictEqual({ k8sNamespaces: ["prod"], autoAdopt: [], sentry: { projects: [], resolveOnDone: false }, alertmanager: { namespaces: [] }, pulls: [] });
expect(parsed.value.definitions.backlog).toStrictEqual({ k8sNamespaces: ["prod"], autoAdopt: [], sentry: { projects: [], resolveOnDone: false }, alertmanager: { namespaces: [], evidence: [] }, pulls: [] });
expect(parsed.value.roles["trotterdylan"]!.ops).toStrictEqual({ k8sNamespaces: ["prod"], autoAdopt: [], sentry: { projects: [], resolveOnDone: false }, alertmanager: { namespaces: [], evidence: [] }, pulls: [] });
});
});

describe("the evidence pilot role (BB-419)", () => {
const parse = (alertmanager: Record<string, unknown>) => parseRolesFile(JSON.stringify({ version: 2, roles: { ops: { alertmanager } }, holders: { jane: ["ops"] } }));

it("parses the pilot namespaces on the definition and the effective role", () => {
const parsed = parse({ namespaces: ["bithub2-production"], evidence: ["bithub2-production"] });
if (!parsed.ok) throw new Error(parsed.error);
expect(parsed.value.roles["jane"]!.ops?.alertmanager).toEqual({ namespaces: ["bithub2-production"], evidence: ["bithub2-production"] });
});

it("is off when the role lists none, and refuses a bad namespace", () => {
const off = parse({ namespaces: ["bithub2-production"] });
if (!off.ok) throw new Error(off.error);
expect(off.value.roles["jane"]!.ops?.alertmanager.evidence).toEqual([]);
expect(parse({ evidence: ["Not A Namespace"] })).toMatchObject({ ok: false });
});
});

Expand Down
12 changes: 11 additions & 1 deletion plugins/stewards/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,18 @@ const alertmanagerTargetSchema = z.object({ kind: z.literal("alertmanager"), nam
* `roles.json` as `ops.alertmanager.namespaces`, and the strict parser means a
* server running an older image rejects the key with one problem line until it
* restarts onto the image that knows it.
*
* `evidence` (BB-419) is the pilot list: the namespaces whose failed-Job alerts
* get the read-only triage reply, and the only namespaces the evidence reader
* is allowed to read. Empty is the off state, so a role that watches
* Alertmanager for another namespace reads no evidence there. It is a separate
* list from `namespaces` on purpose: the pilot is narrower than the watch, and
* the allowlist must stay exactly the pilot.
*/
export const roleAlertmanagerSchema = z.object({ namespaces: z.array(alertmanagerNamespace).max(50).default([]) }).strict().default({ namespaces: [] });
export const roleAlertmanagerSchema = z
.object({ namespaces: z.array(alertmanagerNamespace).max(50).default([]), evidence: z.array(alertmanagerNamespace).max(50).default([]) })
.strict()
.default({ namespaces: [], evidence: [] });

export const opsTargetSchema = z.discriminatedUnion("kind", [k8sNamespaceTargetSchema, dependabotTargetSchema, sentryProjectTargetSchema, alertmanagerTargetSchema]);

Expand Down
3 changes: 2 additions & 1 deletion plugins/stewards/migrations.snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -167,5 +167,6 @@
"9bfa4c58d417559cf24b4c721dc8ddc67986f797e5e09ff7fe1b29b0874dc826",
"be12cfc96f19df660c5740253daf702ed4858950168b6adbf06ba171a7f95ba8",
"193891e9acb3e703f3c010e1308450fc982631a34299132247b90ecdc0019163",
"1bf37bfedc440aa3eaa800a6cf3bd69601568ffdaf768cb5d509693859ab2e5a"
"1bf37bfedc440aa3eaa800a6cf3bd69601568ffdaf768cb5d509693859ab2e5a",
"a14a7ecefb461c4e948ff23d9ced37c4bbfa3bdea7078bbdb1ad93525b368fb8"
]
15 changes: 13 additions & 2 deletions plugins/stewards/roles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ function mergeRoleOps(defs: readonly RoleOps[]): RoleOps {
const autoAdopt: RoleOps["autoAdopt"] = [];
const projects: RoleOps["sentry"]["projects"] = [];
const alertmanagerNamespaces: string[] = [];
const evidenceNamespaces: string[] = [];
const dependabot: string[] = [];
const pulls: RoleOps["pulls"] = [];
let dependabotAll = false;
Expand All @@ -227,6 +228,7 @@ function mergeRoleOps(defs: readonly RoleOps[]): RoleOps {
for (const priority of def.autoAdopt) if (!autoAdopt.includes(priority)) autoAdopt.push(priority);
for (const project of def.sentry.projects) if (!projects.some((p) => p.org === project.org && p.project === project.project)) projects.push(project);
for (const namespace of def.alertmanager.namespaces) if (!alertmanagerNamespaces.includes(namespace)) alertmanagerNamespaces.push(namespace);
for (const namespace of def.alertmanager.evidence) if (!evidenceNamespaces.includes(namespace)) evidenceNamespaces.push(namespace);
if (def.context !== undefined && context === undefined) context = def.context;
if (def.team !== undefined && team === undefined) team = def.team;
if (def.backlog !== undefined && backlog === undefined) backlog = def.backlog;
Expand All @@ -235,7 +237,7 @@ function mergeRoleOps(defs: readonly RoleOps[]): RoleOps {
else if (Array.isArray(def.dependabot)) for (const repo of def.dependabot) if (!dependabot.includes(repo)) dependabot.push(repo);
for (const watch of def.pulls) if (!pulls.some((w) => samePullWatch(w, watch))) pulls.push(watch);
}
const ops: RoleOps = { k8sNamespaces, autoAdopt, sentry: { projects, resolveOnDone }, alertmanager: { namespaces: alertmanagerNamespaces }, pulls };
const ops: RoleOps = { k8sNamespaces, autoAdopt, sentry: { projects, resolveOnDone }, alertmanager: { namespaces: alertmanagerNamespaces, evidence: evidenceNamespaces }, pulls };
if (context !== undefined) ops.context = context;
if (team !== undefined) ops.team = team;
if (backlog !== undefined) ops.backlog = backlog;
Expand Down Expand Up @@ -302,6 +304,13 @@ export const roleSentryTargets = (role: Role | null): SentryTarget[] => (role?.o
/** The Kubernetes namespaces a role watches for Alertmanager alerts, which are read through the plugin's Alertmanager URL and rung by the hooks service. */
export const roleAlertmanagerTargets = (role: Role | null): AlertmanagerTarget[] => (role?.ops?.alertmanager?.namespaces ?? []).map((namespace) => ({ kind: "alertmanager", namespace }));

/**
* The pilot namespaces whose failed-Job Alertmanager alerts get the read-only
* triage reply (BB-419). Empty is the off state, and it is also the exact
* allowlist the evidence reader reads within.
*/
export const roleEvidenceNamespaces = (role: Role | null): string[] => role?.ops?.alertmanager?.evidence ?? [];

/** The namespace, Sentry and Alertmanager targets a role watches; the Dependabot watch is separate because it defaults to every repo. */
export const roleOpsTargets = (role: Role | null): OpsTarget[] => [...roleK8sTargets(role), ...roleSentryTargets(role), ...roleAlertmanagerTargets(role)];

Expand Down Expand Up @@ -366,7 +375,9 @@ export function legacyRole(project: ProjectFile): Role {
...(project.ops.context === undefined ? {} : { context: project.ops.context }),
autoAdopt: [...project.ops.autoAdopt],
sentry: { projects: sentryTargets(project).map((t) => ({ org: t.org, project: t.project })), resolveOnDone: project.ops.sentry.resolveOnDone },
alertmanager: { namespaces: alertmanagerTargets(project).map((t) => t.namespace) },
// The legacy `ops.targets` opt-in has no evidence pilot; it is off there,
// exactly as it is for a role that does not list one (BB-419).
alertmanager: { namespaces: alertmanagerTargets(project).map((t) => t.namespace), evidence: [] },
dependabot: explicit.length > 0 ? explicit : "all",
pulls: [],
},
Expand Down
126 changes: 126 additions & 0 deletions plugins/stewards/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13691,6 +13691,132 @@ describe("Alertmanager stewards (BB-314)", () => {
});
});

// BB-419: the read-only Job-failure triage reply. The Alertmanager look now
// reads evidence with the ambient kubectl behind `evidenceKubectlRefusal` and
// composes the reply for a firing `KubeJobFailed` alert in a pilot namespace.
// The Slack post is BB-420, so the flow stops at the occurrence record. The
// pilot list is the switch: empty, nothing is read or composed, and the
// Alertmanager watch is unchanged.
describe("the Job-failure triage reply (BB-419)", () => {
const NAMESPACE = "bithub2-production";
const JOB = "deelsync-28934567";
const FP = "a1b2c3d4e5f6";
const KEY = `${FP}#${JOB}@2026-10-14T14:30:00Z`;
const AM_URL = "http://alertmanager.test:9093";
const TARGET = `alertmanager/${NAMESPACE}`;

const jobAlert = (over: Record<string, unknown> = {}) => ({
fingerprint: FP,
status: { state: "active" },
labels: { alertname: "KubeJobFailed", namespace: NAMESPACE, job_name: JOB, severity: "warning" },
annotations: { summary: "Job failed to complete" },
startsAt: "2026-10-14T14:30:00Z",
endsAt: "0001-01-01T00:00:00Z",
updatedAt: "2026-10-14T14:58:00Z",
generatorURL: "http://prometheus.example/graph",
...over,
});

function fakeAlertmanager(alerts: Array<Record<string, unknown>>) {
const map = new Map(alerts.map((a) => [String(a.fingerprint), a]));
const fetchImpl = (async (url: string | URL) => {
const u = new URL(String(url));
if (u.pathname === "/api/v2/status") return Response.json({ cluster: { name: "kps" }, versionInfo: { version: "0.27.0" } });
if (u.pathname === "/api/v2/alerts") return Response.json([...map.values()]);
return new Response("", { status: 404 });
}) as typeof fetch;
return { map, fetchImpl };
}

const jobItem = () => ({
metadata: { name: JOB, namespace: NAMESPACE },
status: {
startTime: "2026-10-14T14:20:00Z",
completionTime: "2026-10-14T14:29:00Z",
failed: 3,
conditions: [{ type: "Failed", status: "True", reason: "BackoffLimitExceeded", message: "Job has reached the specified backoff limit", lastTransitionTime: "2026-10-14T14:29:00Z" }],
},
});
const podItem = () => ({
metadata: { name: `${JOB}-abc`, namespace: NAMESPACE, labels: { "job-name": JOB }, ownerReferences: [{ kind: "Job", name: JOB, controller: true }] },
status: { phase: "Failed", containerStatuses: [{ name: "sync", ready: false, restartCount: 0, state: {}, lastState: { terminated: { reason: "Error", exitCode: 1, finishedAt: "2026-10-14T14:29:00Z" } } }], conditions: [] },
});
const eventItem = () => ({ involvedObject: { kind: "Pod", name: `${JOB}-abc` }, type: "Warning", reason: "FailedScheduling", message: "0/3 nodes are available", count: 1, lastTimestamp: "2026-10-14T14:21:00Z" });

function fakeKubectl(over: { jobs?: unknown[]; pods?: unknown[]; events?: unknown[]; logs?: string; logsError?: string } = {}) {
const calls: string[][] = [];
const kubectl = async (args: string[]) => {
calls.push(args);
if (args[0] === "get" && args[1] === "jobs") return { exitCode: 0, stdout: JSON.stringify({ items: over.jobs ?? [jobItem()] }), stderr: "", missing: false };
if (args[0] === "get" && args[1] === "pods") return { exitCode: 0, stdout: JSON.stringify({ items: over.pods ?? [podItem()] }), stderr: "", missing: false };
if (args[0] === "get" && args[1] === "events") return { exitCode: 0, stdout: JSON.stringify({ items: over.events ?? [eventItem()] }), stderr: "", missing: false };
if (args[0] === "logs") {
if (over.logsError !== undefined) return { exitCode: 1, stdout: "", stderr: over.logsError, missing: false };
return { exitCode: 0, stdout: over.logs ?? "error: upstream 503 token=sk_live_secret\n", stderr: "", missing: false };
}
return { exitCode: 1, stdout: "", stderr: `unexpected ${args.join(" ")}`, missing: false };
};
return { kubectl, calls };
}

const roles = (evidence: string[]) => JSON.stringify({ version: 2, roles: { ops: { team: "ENG", alertmanager: { namespaces: [NAMESPACE], evidence } } }, holders: { jane: ["ops"] } });

async function watching(options: { alerts?: Array<Record<string, unknown>>; evidence?: string[]; kubectlOver?: Parameters<typeof fakeKubectl>[0] } = {}) {
const am = fakeAlertmanager(options.alerts ?? [jobAlert()]);
const k = fakeKubectl(options.kubectlOver);
const t = await setup({ fetch: am.fetchImpl, kubectl: k.kubectl, env: { ALERTMANAGER_URL: AM_URL } });
t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["ENG"] } });
t.files[ROLES_FILE] = roles(options.evidence ?? [NAMESPACE]);
t.files[playbookPath("ops-watch")] = OPS_WATCH;
await t.hooks.sweep();
await t.flush();
return { t, am, k };
}

it("composes the three-heading reply from the real reader and records the occurrence once", async () => {
const { t, k } = await watching();
const binding = t.hooks.store.open().find((b) => b.kind === "ops")!;
expect(binding.entityKey).toBe(TARGET);
const occ = t.hooks.store.triageOccurrence("p1", KEY)!;
expect(occ).toMatchObject({ bindingId: binding.id, postedTs: null });
expect(occ.text).toContain("**What failed?**");
expect(occ.text).toContain("**Still affecting us?**");
expect(occ.text).toContain("**Next step**");
expect(occ.text).toContain(`Job \`${JOB}\``);
expect(occ.text).toContain("BackoffLimitExceeded");
expect(occ.text).toContain("not proof of data catch-up");
// The evidence reads went through the strict allowlist: `-o json` only.
expect(k.calls.some((a) => a[0] === "get" && a[1] === "jobs" && a.includes("-o") && a.includes("json"))).toBe(true);
expect(k.calls.some((a) => a[0] === "logs")).toBe(true);
});

it("composes and claims at most once for a repeated delivery", async () => {
const { t, k } = await watching();
const before = k.calls.length;
// Ring the same firing again: the occurrence is already claimed, so no
// evidence is read a second time.
t.hooks.alertmanagerDoorbell(FP, NAMESPACE, "firing");
await t.flush();
expect(k.calls.length).toBe(before);
expect(t.hooks.store.open().filter((b) => b.kind === "ops")).toHaveLength(1);
});

it("is off when no pilot namespace is configured, and reads nothing", async () => {
const { t, k } = await watching({ evidence: [] });
expect(k.calls).toEqual([]);
expect(t.hooks.store.triageOccurrence("p1", KEY)).toBeNull();
// The Alertmanager watch itself is unchanged: the steward is still woken.
expect(t.spawns.some((x) => String(x.title).startsWith("Alertmanager watch"))).toBe(true);
});

it("labels unavailable evidence and still composes", async () => {
const { t } = await watching({ kubectlOver: { logsError: 'Error from server (Forbidden): pods "x" is forbidden' } });
const occ = t.hooks.store.triageOccurrence("p1", KEY)!;
expect(occ.text).toContain("could not be read");
expect(occ.text).toContain("What remains to check");
});
});

describe("the backlog watch (BB-334)", () => {
const backlogIssue = (over: Record<string, unknown> = {}) => ({
id: "uuid-1",
Expand Down
Loading