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
82 changes: 82 additions & 0 deletions plugins/stewards/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1706,6 +1706,27 @@ describe("terminal states and follow-through", () => {
expect(t.archives()).toEqual([t.steward]);
});

it("keeps a deferred archive through an idle that is still busy, and archives on the next", async () => {
const t = await working();
await t.done();
await t.report();
// finishEnding finds the thread busy: the archive is deferred.
t.harness.sdk.stub("threads.get", async (args: { threadId: string }) => ({ ...(await t.sdk.threads.get(args)), status: "active" }));
await t.idle(t.steward);
expect((await t.list())[0]).toMatchObject({ ended: true });
expect(t.archives()).toEqual([]);
// Still busy at the next idle: the flag must survive so a later idle retries
// instead of clearing it and never archiving (BB-60).
await t.idle(t.steward);
expect(t.archives()).toEqual([]);
expect(t.hooks.store.find("ENG-12")!.archiveWhenIdle).toBe(true);

t.harness.sdk.stub("threads.get", t.sdk.threads.get);
await t.idle(t.steward);
expect(t.archives()).toEqual([t.steward]);
expect(t.hooks.store.find("ENG-12")!.archiveWhenIdle).toBe(false);
});

it("keeps the binding open while the steward follows through, and ends it once the work is done", async () => {
const t = await working();
await t.done();
Expand Down Expand Up @@ -1766,13 +1787,67 @@ describe("terminal states and follow-through", () => {
expect((await t.list())[0]).toMatchObject({ ended: true });
});

it("keeps a terminal binding open on a report that escalates without a follow-through", async () => {
const t = await working();
await t.done();
// The deps-prs timeline in BB-60: escalate a merge decision in the wrap-up
// report without followThrough. The report must not end the binding and
// auto-resolve the question the user has not seen.
const reported = await t.report({ escalate: { kind: "decision", question: "Merge bb-gate#39?", meanwhile: "Wait.", choices: ["Merge", "Close"] } });
expect(reported.error).toBe(false);
const id = /(esc_[\w-]+) from ENG-12/u.exec(t.sends.filter((x) => x.threadId === t.project).at(-1)!.text)![1]!;
await t.idle(t.steward);
expect((await t.list())[0]).toMatchObject({ ended: false });
expect(t.hooks.store.escalation(id)).toMatchObject({ status: "open" });
const b = t.hooks.store.find("ENG-12")!;
expect(b.followThrough).toBe("Merge bb-gate#39?");
expect(b.followThroughUntil).not.toBeNull();
});

it("ends an escalation without waking the binding it just ended", async () => {
const t = await working();
await t.tool("steward_report", { phase: "In Progress", summary: "Building.", nextAction: "Wait", actor: "other", escalate: { kind: "decision", question: "Include SSO?", meanwhile: "Building the rest." } }, t.steward);
const id = /(esc_[\w-]+) from ENG-12/u.exec(t.sends.filter((x) => x.threadId === t.project).at(-1)!.text)![1]!;
await t.done();
await t.report({ followThrough: "watch the deploy" });
await t.idle(t.steward);
expect((await t.list())[0]).toMatchObject({ ended: false });

const before = t.sends.filter((x) => x.threadId === t.steward).length;
// The follow-through deadline ends the binding and resolves the escalation.
t.advance(6 * 3_600_000 + 60_000);
await t.hooks.sweep();
await t.flush();
expect((await t.list())[0]).toMatchObject({ ended: true });
expect(t.hooks.store.escalation(id)).toMatchObject({ status: "resolved", resolution: "The binding ended." });
// finishEnding resolved it quietly: no delivery was queued for the ended
// binding.
expect(t.hooks.store.pendingDeliveries().some((d) => d.escalationId === id)).toBe(false);

// flushDeliveries also skips a delivery whose origin binding has ended.
t.hooks.db
.prepare("INSERT INTO pending_deliveries (id, escalation_id, origin_thread_id, origin_binding_id, text, decided_by, created_at) VALUES ('dlv_manual', ?, ?, ?, ?, 'plugin', ?)")
.run(id, t.steward, t.hooks.store.find("ENG-12")!.id, "The binding ended.", t.now());
await t.hooks.sweep();
await t.flush();
expect(t.sends.filter((x) => x.threadId === t.steward)).toHaveLength(before);
expect(t.hooks.store.pendingDeliveries().some((d) => d.id === "dlv_manual")).toBe(false);
});

it("takes an answer to an escalation the ending resolved, once, keeping what the ending said", async () => {
const t = await working();
await t.tool("steward_report", { phase: "In Progress", summary: "Building.", nextAction: "Wait", actor: "other", escalate: { kind: "decision", question: "Include SSO?", meanwhile: "Building the rest." } }, t.steward);
const id = /(esc_[\w-]+) from ENG-12/u.exec(t.sends.filter((x) => x.threadId === t.project).at(-1)!.text)![1]!;
await t.done();
// The open escalation keeps the binding alive through the wrap-up report
// (BB-60); the follow-through deadline is what ends it and resolves the
// escalation.
await t.report();
await t.idle(t.steward);
expect((await t.list())[0]).toMatchObject({ ended: false });
t.advance(6 * 3_600_000 + 60_000);
await t.hooks.sweep();
await t.flush();
expect((await t.list())[0]).toMatchObject({ ended: true });
expect(t.hooks.store.escalation(id)).toMatchObject({ status: "resolved", resolution: "The binding ended." });

Expand All @@ -1791,8 +1866,15 @@ describe("terminal states and follow-through", () => {
const id = /(esc_[\w-]+) from ENG-12/u.exec(t.sends.filter((x) => x.threadId === t.project).at(-1)!.text)![1]!;
const qst = /(qst_[\w-]+)/u.exec((await t.tool("steward_update", { binding: "ENG-12", forward: id }, t.project)).text)![1]!;
await t.done();
// The forwarded escalation keeps the binding alive through the wrap-up
// report (BB-60); the follow-through deadline ends it and closes both the
// escalation and its question.
await t.report();
await t.idle(t.steward);
expect((await t.list())[0]).toMatchObject({ ended: false });
t.advance(6 * 3_600_000 + 60_000);
await t.hooks.sweep();
await t.flush();
expect((await t.list())[0]).toMatchObject({ ended: true });
expect(t.hooks.store.question(qst)).toMatchObject({ status: "answered", answer: "The binding ended." });

Expand Down
64 changes: 42 additions & 22 deletions plugins/stewards/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2658,7 +2658,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P
*/
async function finishEnding(b: Binding, reason: string): Promise<void> {
b = store.patch(b.id, { ending: null, endingAt: null, followThrough: null, followThroughUntil: null, endedAt: now(), endReason: reason, awaitingReport: false, requeueAt: null });
for (const x of store.openEscalations(b.id)) store.resolve(x.id, "The binding ended.");
// Mechanical cleanup, not a decision: the origin binding has ended, so
// resolve its escalations without queuing a wake it would never read
// (BB-60).
for (const x of store.openEscalations(b.id)) store.resolve(x.id, "The binding ended.", "plugin", false);
await releaseBehind(b, `ended (${reason})`);
await stopWorkers(b);
const info = b.threadId === null ? null : await threadInfo(b.threadId).catch(() => null);
Expand Down Expand Up @@ -3664,13 +3667,18 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P
if (b === null) return;
if (b.endedAt !== null) {
// The binding ended while this turn was running: finishEnding left the
// archive to this idle. Once only, so a later turn the owner starts in
// the ended steward is not archived under them.
// archive to this idle. Clear the flag only once the archive actually
// happens, so a thread still busy here (or an archive that fails) is
// retried on the next idle rather than never archived (BB-60).
if (b.archiveWhenIdle) {
store.patch(b.id, { archiveWhenIdle: false });
const info = await threadInfo(thread.id).catch(() => null);
if (info !== null && info.deletedAt === null && info.archivedAt === null && !busy(info.status)) {
await quietly(`archive ${b.entityKey}'s ended steward`, () => bb.sdk.threads.archive({ threadId: info.id }));
try {
await bb.sdk.threads.archive({ threadId: info.id });
store.patch(b.id, { archiveWhenIdle: false });
} catch (error) {
bb.log.warn(`stewards: could not archive ${b.entityKey}'s ended steward: ${errorMessage(error)}`);
}
}
}
return;
Expand Down Expand Up @@ -4780,9 +4788,17 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P
const config = await loadConfig(b.projectId);
const playbook = config === null ? null : bindingPlaybook(config, b);
const priorGate = playbook !== null && playbook.ready !== null ? gateState(playbook, priorReady, priorSnapshot === null ? (priorReady.approval?.specHash ?? "") : specHashFor(b, priorSnapshot.entity)) : null;
// A terminal binding that raises an escalation, or already has one
// open, keeps the binding open on that question: the report must not
// reset its follow-through to null, or the plugin ends the binding,
// auto-resolves the escalation and leaves the user's question
// unanswered (BB-60).
const openBeforeReport = b.ending === "terminal" ? store.openEscalations(b.id) : [];
const escalationFollowThrough = b.ending !== "terminal" ? null : (input.escalate?.question ?? openBeforeReport[0]?.question ?? null);
const followThrough = input.followThrough ?? escalationFollowThrough;
// Follow-through has one deadline from when it was first declared; a
// requeue past it is a requeue at it.
const followThroughUntil = b.ending !== "terminal" ? null : (b.followThroughUntil ?? (input.followThrough === undefined ? null : now() + (playbook?.followThroughMs ?? DEFAULT_FOLLOW_THROUGH_MS)));
const followThroughUntil = b.ending !== "terminal" ? null : (b.followThroughUntil ?? (followThrough === null ? null : now() + (playbook?.followThroughMs ?? DEFAULT_FOLLOW_THROUGH_MS)));
const requeueMs = Math.min(input.requeueAfter ?? playbook?.requeueDefaultMs ?? 2 * 86_400_000, followThroughUntil === null ? Infinity : Math.max(60_000, followThroughUntil - now()));
let ready = b.ready;
if (input.ready !== undefined) {
Expand Down Expand Up @@ -4880,7 +4896,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P
...(input.touches === undefined ? {} : { touches: normalizeTouches(input.touches) }),
...(input.noMorePulls === undefined ? {} : { noMorePulls: input.noMorePulls ? true : null }),
...(input.noMorePulls === false && b.noMorePulls === true && b.scheduleAsked.length > 0 ? { scheduleAsked: [] } : {}),
...(b.ending === "terminal" ? { followThrough: input.followThrough ?? null, followThroughUntil } : {}),
...(b.ending === "terminal" ? { followThrough, followThroughUntil } : {}),
});
const requested = playbook === null ? null : await syncApprovalRequest(b, playbook);
const scheduling = playbook === null ? null : await syncScheduleRequest(b, playbook);
Expand Down Expand Up @@ -5581,23 +5597,27 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P
async function flushDeliveries(): Promise<void> {
for (const d of store.pendingDeliveries()) {
const origin = d.originBindingId === null ? null : store.binding(d.originBindingId);
try {
if (origin !== null && origin.threadId !== null && origin.threadId === d.originThreadId) {
const config = await loadConfig(origin.projectId);
const playbook = config === null ? null : bindingPlaybook(config, origin);
let observed: Observed | null = origin.lastSnapshot;
if (observed === null && origin.source !== "ops") {
const entity = await snapshot(origin.source, origin.entityId).catch(() => null);
if (entity !== null) observed = { entity, pulls: [] };
}
if (config !== null && playbook !== null && observed !== null) {
await wake(origin, config, playbook, observed, [`Escalation ${d.escalationId} was answered by ${d.decidedBy}: ${d.text}`], "changed");
// A binding the plugin already ended is not woken for an answer to an
// escalation it resolved on the way out (BB-60).
if (origin === null || origin.endedAt === null) {
try {
if (origin !== null && origin.threadId !== null && origin.threadId === d.originThreadId) {
const config = await loadConfig(origin.projectId);
const playbook = config === null ? null : bindingPlaybook(config, origin);
let observed: Observed | null = origin.lastSnapshot;
if (observed === null && origin.source !== "ops") {
const entity = await snapshot(origin.source, origin.entityId).catch(() => null);
if (entity !== null) observed = { entity, pulls: [] };
}
if (config !== null && playbook !== null && observed !== null) {
await wake(origin, config, playbook, observed, [`Escalation ${d.escalationId} was answered by ${d.decidedBy}: ${d.text}`], "changed");
}
} else if (d.originThreadId !== null) {
await sendTo(d.originThreadId, `An escalation you raised was answered by ${d.decidedBy}: ${d.text}`);
}
} else if (d.originThreadId !== null) {
await sendTo(d.originThreadId, `An escalation you raised was answered by ${d.decidedBy}: ${d.text}`);
} catch (error) {
bb.log.warn(`stewards: could not deliver an answer to ${d.originThreadId ?? d.originBindingId ?? "?"}: ${errorMessage(error)}`);
}
} catch (error) {
bb.log.warn(`stewards: could not deliver an answer to ${d.originThreadId ?? d.originBindingId ?? "?"}: ${errorMessage(error)}`);
}
store.markDeliveryDone(d.id);
}
Expand Down
17 changes: 10 additions & 7 deletions plugins/stewards/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1156,22 +1156,24 @@ export function createStore(db: Database.Database, now: () => number, options: S
* the escalation a question was forwarded from closes too, so a close on the
* page (answer, Done, a finished requester, a secret import) resolves the
* whole pair in one write and the originator hears the answer (BB-51). `by`
* is who answered it.
* is who answered it. `deliver` is false for a mechanical close of an
* escalation whose origin binding has ended: it is resolved, but no wake is
* queued for a binding that is already gone (BB-60).
*/
function resolve(id: string, resolution: string, by = "plugin"): boolean {
function resolve(id: string, resolution: string, by = "plugin", deliver = true): boolean {
return coalescing(() => {
const resolved = db.transaction(() => {
const at = now();
if (resolveEscalation.run(resolution, at, id).changes === 0) return false;
answerForEscalation.run(resolution, by, at, id);
const x = getEscalation.get(id);
if (x !== undefined) recordResolutionDelivery(toEscalation(x), resolution, by);
if (x !== undefined) recordResolutionDelivery(toEscalation(x), resolution, by, deliver);
// Follow the link up: a question resolved on the page also resolves the
// escalation the project steward forwarded it from.
const parent = forwardedFromOf.get(id);
if (parent !== undefined && String(parent.status) === "open") {
resolveEscalation.run(resolution, at, String(parent.id));
recordResolutionDelivery(toEscalation(parent), resolution, by);
recordResolutionDelivery(toEscalation(parent), resolution, by, deliver);
answerForEscalation.run(resolution, by, at, String(parent.id));
}
return true;
Expand All @@ -1189,9 +1191,10 @@ export function createStore(db: Database.Database, now: () => number, options: S
* (verbatim, with who decided as its author) and a quiet note on each binding
* the escalation passed through, then queue one delivery to the originating
* thread. The server flushes the queue; a worker gets a tell, a steward a
* wake. This is the one road every resolve takes (BB-30).
* wake. This is the one road every resolve takes (BB-30). `deliver` is
* false for a resolve that must not wake the origin (BB-60).
*/
function recordResolutionDelivery(x: Escalation, resolution: string, by: string): void {
function recordResolutionDelivery(x: Escalation, resolution: string, by: string, deliver = true): void {
const originBindingId = x.origin.bindingId ?? x.bindingId;
// A mechanical closure (the plugin withdrawing or closing something) is
// not a decision: it is noted, but it is not written as guidance a worker
Expand All @@ -1212,7 +1215,7 @@ export function createStore(db: Database.Database, now: () => number, options: S
const b = rowToBinding(raw);
patch(hop.bindingId, { pending: [...b.pending, { at: now(), text: `Escalation ${x.id} was answered by ${by}: ${resolution}`, quiet: true }].slice(-30) });
}
if (x.origin.threadId !== null && x.origin.threadId !== "") insertDelivery.run(newId("dlv"), x.id, x.origin.threadId, originBindingId === "" ? null : originBindingId, resolution, by, now());
if (deliver && x.origin.threadId !== null && x.origin.threadId !== "") insertDelivery.run(newId("dlv"), x.id, x.origin.threadId, originBindingId === "" ? null : originBindingId, resolution, by, now());
}

function patch(id: string, fields: BindingPatch): Binding {
Expand Down
Loading