Public: anyone can read this; the crew can change it.

Ask-to-live: record at deploy time which merges a production deploy carries, and count each issue once #1556

Closed opened this
Closed without merging

scout/forge:scout/1516-ask-to-live-record-at-deploy-time-which → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +255 −65
README.md +3
@@ -379,6 +379,9 @@ mechanical rather than advisory.
379379 what "ready now" means to a person and to the crew. The map also shows each
380380 pillar's ask-to-live: the median hours from an issue opening to its change live
381381 in production, over the last 7 days (also in the map and milestones API and MCP).
382 It is read from `pull_live`, which each finished production deploy fills with the
383 merged pulls it first carries (one git ask per pull, once), so a view runs no git;
384 an issue closed by several pulls counts once, at its first time live.
382385
383386 `docs/STUDIO.md` is the front door from the top of this page in full: the five
384387 words and where each is decided, the box, the three lists, a tell, a run
src/apps/runtime.ts +21 −1
@@ -44,8 +44,10 @@ import {
4444 type Run,
4545 } from "../core/runs.ts";
4646 import { Gate } from "../git/env.ts";
47 import { reachesIn } from "../git/local.ts";
4748 import { resolveOid } from "../git/merge.ts";
4849 import { repoDir } from "../git/repos.ts";
50 import { recordPullsLive } from "../core/pull_live.ts";
4951 import { createLog } from "../kernel/log.ts";
5052 import type { Result } from "../kernel/result.ts";
5153 import { holdLease, STALE_AFTER_MS } from "../runs/lease.ts";
@@ -1108,7 +1110,10 @@ export class AppsRuntime {
11081110 summary: `running at ${url}`,
11091111 });
11101112 write(`done: ${url}`);
1111 if (done) announceRun(this.app, done);
1113 if (done) {
1114 announceRun(this.app, done);
1115 if (state.env === "production") await this.recordLive(repo);
1116 }
11121117 return;
11131118 }
11141119 // The tests failed, but the deployment that answered is what was asked
@@ -1124,6 +1129,21 @@ export class AppsRuntime {
11241129 if (done) announceRun(this.app, done);
11251130 }
11261131
1132 /** Note which merged pulls the production deploy that just finished carries; never fails the deploy. */
1133 private async recordLive(repo: Repo): Promise<void> {
1134 try {
1135 await recordPullsLive(
1136 this.app.db,
1137 repo.id,
1138 reachesIn(repoDir(this.app.reposRoot, repo.ownerName, repo.name)),
1139 );
1140 } catch (error) {
1141 log.error("could not record the pulls a deploy carries", {
1142 error: String(error),
1143 });
1144 }
1145 }
1146
11271147 private async bringUp(
11281148 state: Environment,
11291149 repo: Repo,
src/core/pillars.ts +40 −46
@@ -259,9 +259,8 @@ export function mergedByPillar(
259259 }
260260
261261 interface MergedPull {
262 readonly id: string;
262263 readonly closes: readonly number[];
263 readonly mergedAt: string;
264 readonly mergedOid: string;
265264 }
266265
267266 interface ClosedIssue {
@@ -291,8 +290,8 @@ function mergedPulls(
291290 scope: SealedScope = {},
292291 ): { pulls: MergedPull[]; issues: Map<number, ClosedIssue> } {
293292 const rows = db
294 .query<{ body: string; at: string; oid: string | null }, string[]>(
295 `SELECT i.body, p.merged_at AS at, p.merged_oid AS oid
293 .query<{ id: string; body: string }, string[]>(
294 `SELECT p.issue_id AS id, i.body
296295 FROM pull p JOIN issue i ON i.id = p.issue_id
297296 WHERE i.repo_id = ?1 AND p.merged_at IS NOT NULL AND p.merged_at >= ?2
298297 AND ${sealedClause("i", scope, 3)}
@@ -300,9 +299,8 @@ function mergedPulls(
300299 )
301300 .all(repoId, since, ...sealedParams(scope));
302301 const pulls = rows.map((row) => ({
302 id: row.id,
303303 closes: closesFromBody(row.body),
304 mergedAt: row.at,
305 mergedOid: row.oid ?? "",
306304 }));
307305 const numbers = [...new Set(pulls.flatMap((pull) => pull.closes))];
308306 const issues = new Map<number, ClosedIssue>();
@@ -342,9 +340,6 @@ function pillarOf(
342340
343341 // ---- ask-to-live: an issue opening to its change in production (#1185) ----
344342
345 /** Whether `ancestor` is reachable from `descendant`; false when unsure. The git lives in src/git, handed in. */
346 export type Reaches = (ancestor: string, descendant: string) => Promise<boolean>;
347
348343 /** How long the asking took, for one pillar's merged work. */
349344 export interface AskToLive {
350345 /** Median hours from an issue opening to its change live in production. */
@@ -359,54 +354,55 @@ export interface AskToLiveCount {
359354 readonly askToLive: AskToLive | undefined;
360355 }
361356
362 /** Most ancestry questions one request may put to git; a pull left unanswered counts for nothing. */
363 const ASK_GIT_CALLS = 120;
364
365357 /**
366358 * Per pillar, over the pulls merged since an instant: the median and the
367359 * slowest ask-to-live, from the creation of the issue that pull closed to
368360 * the first production deploy that went live on a commit containing the
369 * pull's merge. A pull not yet live counts for nothing. Every name has a
370 * row, in order; one read of deploys however many pulls merged.
361 * pull's merge. That is read from `pull_live` (`pull_live.ts`), written as
362 * each deploy finishes: no git runs here. A pull not yet live counts for
363 * nothing, and an issue closed by several pulls counts once, at the first
364 * time any of them went live. Every name has a row, in order.
371365 */
372 export async function askToLiveByPillar(
366 export function askToLiveByPillar(
373367 db: Database,
374368 repoId: string,
375369 set: Pillars,
376370 served: ReadonlyMap<string, string>,
377371 since: string,
378 reaches: Reaches,
379372 scope: SealedScope = {},
380 ): Promise<AskToLiveCount[]> {
373 ): AskToLiveCount[] {
381374 const { pulls, issues } = mergedPulls(db, repoId, since, scope);
382 const deploys = db
383 .query<{ oid: string; at: string }, [string, string]>(
384 `SELECT commit_oid AS oid, COALESCE(serving_at, finished_at) AS at FROM run
385 WHERE repo_id = ?1 AND kind = 'deploy' AND env = 'production' AND state = 'ok'
386 AND commit_oid != '' AND COALESCE(serving_at, finished_at) >= ?2
387 ORDER BY COALESCE(serving_at, finished_at), id`,
388 )
389 .all(repoId, since);
390 const asked = new Map<string, { number: number; hours: number }[]>();
391 let budget = ASK_GIT_CALLS;
375 const liveAt = new Map(
376 db
377 .query<{ id: string; at: string }, [string]>(
378 `SELECT pull_id AS id, live_at AS at FROM pull_live WHERE repo_id = ?1`,
379 )
380 .all(repoId)
381 .map((row) => [row.id, row.at]),
382 );
383 const first = new Map<
384 number,
385 { pillar: string; at: string; createdAt: string }
386 >();
392387 for (const pull of pulls) {
388 const at = liveAt.get(pull.id);
393389 const ask = pillarOf(pull.closes, issues, served);
394 if (ask === undefined || pull.mergedOid === "") continue;
395 let live: { oid: string; at: string } | undefined;
396 for (const d of deploys) {
397 if (d.at < pull.mergedAt) continue;
398 if (budget-- <= 0) break;
399 if (await reaches(pull.mergedOid, d.oid)) {
400 live = d;
401 break;
402 }
403 }
404 if (live === undefined) continue;
405 const hours = (Date.parse(live.at) - Date.parse(ask.createdAt)) / 3_600_000;
390 if (at === undefined || ask === undefined) continue;
391 const seen = first.get(ask.number);
392 if (seen === undefined || at < seen.at)
393 first.set(ask.number, {
394 pillar: ask.pillar,
395 at,
396 createdAt: ask.createdAt,
397 });
398 }
399 const asked = new Map<string, { number: number; hours: number }[]>();
400 for (const [number, one] of first) {
401 const hours = (Date.parse(one.at) - Date.parse(one.createdAt)) / 3_600_000;
406402 if (!Number.isFinite(hours)) continue;
407 const list = asked.get(ask.pillar) ?? [];
408 list.push({ number: ask.number, hours: Math.max(0, hours) });
409 asked.set(ask.pillar, list);
403 const list = asked.get(one.pillar) ?? [];
404 list.push({ number, hours: Math.max(0, hours) });
405 asked.set(one.pillar, list);
410406 }
411407 return pillarNames(set).map((pillar) => {
412408 const list = (asked.get(pillar) ?? []).sort((a, b) => a.hours - b.hours);
@@ -488,22 +484,20 @@ export function pillarView(
488484 };
489485 }
490486
491 /** A view's ask-to-live over the last `PILLAR_DAYS` days; opt-in, for it reads git. */
487 /** A view's ask-to-live over the last `PILLAR_DAYS` days. */
492488 export function askToLiveOf(
493489 db: Database,
494490 repo: Repo,
495491 view: PillarView,
496 reaches: Reaches,
497492 scope: SealedScope = {},
498493 now = new Date(),
499 ): Promise<AskToLiveCount[]> {
494 ): AskToLiveCount[] {
500495 return askToLiveByPillar(
501496 db,
502497 repo.id,
503498 view.set,
504499 view.of,
505500 pillarWindowStart(now),
506 reaches,
507501 scope,
508502 );
509503 }
src/core/pull_live.ts added +71
@@ -0,0 +1,71 @@
1 /**
2 * Which merged pulls a production deploy carries (#1516). Asked of git once,
3 * as the deploy finishes, and written to `pull_live`; ask-to-live
4 * (`pillars.ts`) reads the record and runs no git on a page view.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import { pillarWindowStart } from "./pillars.ts";
9
10 /** Whether `ancestor` is reachable from `descendant`; false when unsure. The git lives in src/git, handed in. */
11 export type Reaches = (ancestor: string, descendant: string) => Promise<boolean>;
12
13 /** Most ancestry questions one deploy may put to git; a pull left unanswered is asked again at the next. */
14 const ASK_GIT_CALLS = 120;
15
16 /**
17 * Record, for every pull merged in the window that has no record yet, the
18 * first successful production deploy whose commit contains its merge. A
19 * pull no deploy carries yet is left for the next one. Returns how many
20 * pulls were recorded.
21 */
22 export async function recordPullsLive(
23 db: Database,
24 repoId: string,
25 reaches: Reaches,
26 now = new Date(),
27 ): Promise<number> {
28 const since = pillarWindowStart(now);
29 const pulls = db
30 .query<{ id: string; at: string; oid: string }, [string, string]>(
31 `SELECT p.issue_id AS id, p.merged_at AS at, p.merged_oid AS oid
32 FROM pull p JOIN issue i ON i.id = p.issue_id JOIN repo r ON r.id = i.repo_id
33 WHERE i.repo_id = ?1 AND p.merged_at >= ?2 AND p.base_branch = r.default_branch
34 AND COALESCE(p.merged_oid, '') != ''
35 AND NOT EXISTS (SELECT 1 FROM pull_live l WHERE l.pull_id = p.issue_id)
36 ORDER BY p.merged_at LIMIT 1000`,
37 )
38 .all(repoId, since);
39 if (pulls.length === 0) return 0;
40 const deploys = db
41 .query<{ id: string; oid: string; at: string }, [string, string]>(
42 `SELECT id, commit_oid AS oid, COALESCE(serving_at, finished_at) AS at FROM run
43 WHERE repo_id = ?1 AND kind = 'deploy' AND env = 'production' AND state = 'ok'
44 AND commit_oid != '' AND COALESCE(serving_at, finished_at) >= ?2
45 ORDER BY COALESCE(serving_at, finished_at), id`,
46 )
47 .all(repoId, since);
48 const newest = deploys[deploys.length - 1];
49 if (newest === undefined) return 0;
50 const insert = db.query(
51 `INSERT OR IGNORE INTO pull_live (pull_id, repo_id, run_id, live_at) VALUES (?1, ?2, ?3, ?4)`,
52 );
53 let budget = ASK_GIT_CALLS;
54 let recorded = 0;
55 for (const pull of pulls) {
56 // Ancestry only grows along production: a pull the newest deploy does
57 // not carry is carried by none, and costs one question, not one per deploy.
58 if (budget-- <= 0) return recorded;
59 if (!(await reaches(pull.oid, newest.oid))) continue;
60 for (const d of deploys) {
61 if (d.at < pull.at) continue;
62 if (budget-- <= 0) return recorded;
63 if (await reaches(pull.oid, d.oid)) {
64 insert.run(pull.id, repoId, d.id, d.at);
65 recorded++;
66 break;
67 }
68 }
69 }
70 return recorded;
71 }
src/core/schema.ts +12
@@ -1595,6 +1595,18 @@ export const migrations: readonly string[] = [
15951595 PRIMARY KEY (repo_id, parent_id, issue_id)
15961596 );
15971597 `,
1598 // 76 — which merged pull a production deploy first carried (#1516), written
1599 // as the deploy finishes so a page view asks git nothing. One row per pull:
1600 // the first deploy to carry it, and the instant that deploy went live.
1601 `
1602 CREATE TABLE pull_live (
1603 pull_id TEXT PRIMARY KEY REFERENCES pull(issue_id) ON DELETE CASCADE,
1604 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
1605 run_id TEXT NOT NULL,
1606 live_at TEXT NOT NULL
1607 );
1608 CREATE INDEX pull_live_repo ON pull_live (repo_id);
1609 `,
15981610 ];
15991611
16001612 /**
src/http/api.ts +1 −1
@@ -2590,7 +2590,7 @@ export function apiRoutes(router: Router<Handler>): void {
25902590 listActiveRuns(ctx.app.db, [repo.id]),
25912591 ),
25922592 pillars,
2593 await askToLiveFor(ctx.app, repo, pillars, ctx.auth.user),
2593 askToLiveFor(ctx.app, repo, pillars, ctx.auth.user),
25942594 ),
25952595 );
25962596 });
src/http/mcp.ts +1 −1
@@ -1245,7 +1245,7 @@ const TOOLS: readonly Tool[] = [
12451245 listActiveRuns(ctx.app.db, [repo.id]),
12461246 ),
12471247 pillars,
1248 await askToLiveFor(ctx.app, repo, pillars, user),
1248 askToLiveFor(ctx.app, repo, pillars, user),
12491249 ),
12501250 );
12511251 },
src/web/ask_to_live.ts +5 −13
@@ -1,7 +1,7 @@
11 /**
22 * A repository's pillars' ask-to-live, for the surfaces that show it (the map,
3 * the milestones, their data). Opt-in and async: it asks git which deploys
4 * carry which merges, so only the callers that print it pay for it.
3 * the milestones, their data). Read from what each production deploy recorded
4 * (`core/pull_live.ts`): no git runs on a view.
55 */
66
77 import type { App } from "../app.ts";
@@ -13,21 +13,13 @@ import {
1313 import type { Repo } from "../core/repos.ts";
1414 import { sealedScope } from "../core/sealed.ts";
1515 import type { User } from "../core/users.ts";
16 import { reachesIn } from "../git/local.ts";
17 import { repoDir } from "../git/repos.ts";
1816
1917 export function askToLiveFor(
2018 app: App,
2119 repo: Repo,
2220 view: PillarView | undefined,
2321 user: User | undefined,
24 ): Promise<AskToLiveCount[]> {
25 if (view === undefined) return Promise.resolve([]);
26 return askToLiveOf(
27 app.db,
28 repo,
29 view,
30 reachesIn(repoDir(app.reposRoot, repo.ownerName, repo.name)),
31 sealedScope(app.db, repo, user),
32 );
22 ): AskToLiveCount[] {
23 if (view === undefined) return [];
24 return askToLiveOf(app.db, repo, view, sealedScope(app.db, repo, user));
3325 }
src/web/pages/map.ts +1 −1
@@ -1419,7 +1419,7 @@ export async function mapPage(ctx: Ctx): Promise<Response> {
14191419 graph.issues.map((i) => wordFor(i, readySet, marks)),
14201420 );
14211421 const pillars = pillarView(db, repo);
1422 const ask = await askToLiveFor(ctx.app, repo, pillars, ctx.auth.user);
1422 const ask = askToLiveFor(ctx.app, repo, pillars, ctx.auth.user);
14231423 const body = html`${repoHeader(ctx, repo, "map")}
14241424 <div class="page-head mt">
14251425 <h1>Map</h1>
src/web/pages/milestones.ts +1 −1
@@ -541,7 +541,7 @@ async function askByUmbrella(
541541 // A milestone that is no pillar's umbrella has none: ask git for nothing.
542542 if (only !== undefined && !view.set.pillars.some((p) => p.umbrella.number === only))
543543 return out;
544 const ask = await askToLiveFor(ctx.app, repo, view, ctx.auth.user);
544 const ask = askToLiveFor(ctx.app, repo, view, ctx.auth.user);
545545 for (const pillar of view.set.pillars)
546546 out.set(
547547 pillar.umbrella.number,
test/pillars.test.ts +99 −1
@@ -39,6 +39,9 @@ import {
3939 type Issue,
4040 } from "../src/core/issues.ts";
4141 import { pillarsOf, pillarView } from "../src/core/pillars.ts";
42 import { recordPullsLive } from "../src/core/pull_live.ts";
43 import { reachesIn } from "../src/git/local.ts";
44 import { repoDir } from "../src/git/repos.ts";
4245 import { askToLiveFor } from "../src/web/ask_to_live.ts";
4346 import { getRepoById, type Repo } from "../src/core/repos.ts";
4447 import { createToken } from "../src/core/tokens.ts";
@@ -495,7 +498,13 @@ describe("pillars", () => {
495498 // Holds queue's merge, and sandbox's before it: queue was asked 10h ago, live 5h.
496499 deploy("production", queuePull.oid, "ok", 5);
497500 const view = pillarView(app.db, fresh(), new Date(T))!;
498 const asked = await askToLiveFor(app, fresh(), view, alice);
501 // Nothing is recorded until a deploy finishes: a view runs no git.
502 expect(askToLiveFor(app, fresh(), view, alice)[0]!.askToLive).toBeUndefined();
503 const reaches = reachesIn(repoDir(app.reposRoot, "alice", "engine"));
504 expect(await recordPullsLive(app.db, repo.id, reaches, new Date(T))).toBe(2);
505 // Recorded once: a second deploy finishing asks about no pull again.
506 expect(await recordPullsLive(app.db, repo.id, reaches, new Date(T))).toBe(0);
507 const asked = askToLiveFor(app, fresh(), view, alice);
499508 const ask = (name: string) =>
500509 asked.find((a) => a.pillar === name)!.askToLive;
501510 // sandbox: 30h -> deploy at 18h ago = 12h; queue: 10h -> 5h ago = 5h.
@@ -587,6 +596,95 @@ describe("pillars", () => {
587596 }
588597 });
589598
599 test("ask-to-live counts an issue once, at the first time it went live, however many pulls closed it", async () => {
600 // Continues above: sandbox was asked 30h ago and live 12h later; queue 5h.
601 const composer = app.db
602 .query<{ id: string; oid: string; body: string }, []>(
603 `SELECT p.issue_id AS id, p.merged_oid AS oid, i.body FROM pull p
604 JOIN issue i ON i.id = p.issue_id WHERE i.title = 'Land composer'`,
605 )
606 .get()!;
607 const before = askToLiveFor(app, fresh(), pillarView(app.db, fresh())!, alice);
608 app.db
609 .query("UPDATE issue SET body = ?1 WHERE id = ?2")
610 .run(`Closes #${sandbox.number}`, composer.id);
611 app.db
612 .query(
613 `INSERT INTO run (id, repo_id, kind, env, commit_oid, state, serving_at, finished_at)
614 VALUES (?1, ?2, 'deploy', 'production', ?3, 'ok', ?4, ?4)`,
615 )
616 .run(`ask-${nextId++}`, repo.id, composer.oid, new Date(Date.now() - 3_600_000).toISOString());
617 try {
618 const reaches = reachesIn(repoDir(app.reposRoot, "alice", "engine"));
619 expect(await recordPullsLive(app.db, repo.id, reaches)).toBe(1);
620 // A second pull closing sandbox, live later, changes nothing.
621 const after = askToLiveFor(app, fresh(), pillarView(app.db, fresh())!, alice);
622 expect(after.find((a) => a.pillar === "P0 Trust")!.askToLive).toEqual(
623 before.find((a) => a.pillar === "P0 Trust")!.askToLive,
624 );
625 expect(after.find((a) => a.pillar === "P1 Feed")!.askToLive).toBeUndefined();
626 } finally {
627 app.db.query("UPDATE issue SET body = ?1 WHERE id = ?2").run(composer.body, composer.id);
628 app.db.query("DELETE FROM pull_live WHERE pull_id = ?1").run(composer.id);
629 }
630 });
631
632 test("ask-to-live: a pull no deploy carries does not starve a later one, and a pull on another base is not asked", async () => {
633 const row = (title: string) =>
634 app.db
635 .query<{ id: string; oid: string; at: string; base: string }, [string]>(
636 `SELECT p.issue_id AS id, p.merged_oid AS oid, p.merged_at AS at, p.base_branch AS base
637 FROM pull p JOIN issue i ON i.id = p.issue_id WHERE i.title = ?1`,
638 )
639 .get(`Land ${title}`)!;
640 const stuck = row("composer");
641 const later = row("queue");
642 const bogus = "f".repeat(40);
643 const asked: string[] = [];
644 const real = reachesIn(repoDir(app.reposRoot, "alice", "engine"));
645 const reaches = (a: string, d: string) => {
646 asked.push(a);
647 return real(a, d);
648 };
649 const hours = (n: number) => new Date(Date.now() - n * 3_600_000).toISOString();
650 const ids: string[] = [];
651 for (let i = 0; i < 130; i++) {
652 const id = `starve-${nextId++}`;
653 ids.push(id);
654 app.db
655 .query(
656 `INSERT INTO run (id, repo_id, kind, env, commit_oid, state, serving_at, finished_at)
657 VALUES (?1, ?2, 'deploy', 'production', ?3, 'ok', ?4, ?4)`,
658 )
659 .run(id, repo.id, later.oid, hours(3 - i / 100));
660 }
661 const merged = app.db.query("UPDATE pull SET merged_at = ?1, merged_oid = ?2 WHERE issue_id = ?3");
662 merged.run(hours(5), bogus, stuck.id);
663 merged.run(hours(4), later.oid, later.id);
664 app.db.query("DELETE FROM pull_live WHERE pull_id IN (?1, ?2)").run(stuck.id, later.id);
665 try {
666 expect(await recordPullsLive(app.db, repo.id, reaches)).toBe(1);
667 expect(
668 app.db.query("SELECT 1 FROM pull_live WHERE pull_id = ?1").get(later.id),
669 ).not.toBeNull();
670 // The stuck pull cost one question, not one per deploy.
671 expect(asked.filter((a) => a === bogus).length).toBe(1);
672 // A pull merged into another base is never asked.
673 app.db.query("DELETE FROM pull_live WHERE pull_id = ?1").run(later.id);
674 app.db.query("UPDATE pull SET base_branch = 'other' WHERE issue_id = ?1").run(later.id);
675 asked.length = 0;
676 await recordPullsLive(app.db, repo.id, reaches);
677 expect(app.db.query("SELECT 1 FROM pull_live WHERE pull_id = ?1").get(later.id)).toBeNull();
678 } finally {
679 app.db.query("UPDATE pull SET base_branch = ?1 WHERE issue_id = ?2").run(later.base, later.id);
680 merged.run(stuck.at, stuck.oid, stuck.id);
681 merged.run(later.at, later.oid, later.id);
682 app.db.query("DELETE FROM pull_live WHERE pull_id = ?1").run(stuck.id);
683 for (const id of ids) app.db.query("DELETE FROM run WHERE id = ?1").run(id);
684 await recordPullsLive(app.db, repo.id, real);
685 }
686 });
687
590688 test("a repository with no pillars shows none of it", async () => {
591689 const made = await createRepo(app, alice, {
592690 name: "plain",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs