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

Errors: suspect pull — name the commit that likely caused an error group #17134

opened this

Merged 47h 33m ago, live in production

scout/forge:scout/16972-errors-suspect-pull-name-the-commit-that → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/16972-errors-suspect-pull-name-the-commit-that was merged into main as 0b81c07.

Review

Sign in to review this change.
8 files changed +227 −15
docs/features/errors.md +10 −3
@@ -67,9 +67,16 @@ a stranger holding the public key cannot reopen a group with an invented name. T
6767 forge keeps no record of an app's deploys, so someone who has first sent events under a
6868 name can still use it: this is a limit, not a guarantee.
6969
70 **Suspect.** `GET …/app/errors/:group` answers `suspect`: when the group's first release
71 is a commit id of the repository (an SDK's usual release), the newest commit at or before it
72 that changed the file the error was thrown in (matched by file name, since a stack's paths
73 are the build's), else the release's own commit; with the merged pull that carried it, if
74 any. A release that is not a commit gives `null`: nothing is guessed. The terminal shows
75 it on the Resolve screen (`:` → Errors → pick a group). It is a lead, not a verdict.
76
7077 **What is not here, said plainly.** Resolve is a person typing the release; the
71 fix-to-resolved step is not automatic. There is no suspect pull (the commit that likely
72 caused a group). Also absent: sessions (crash-free %), source maps, browser capture injected by the template, and errors on home and `/flow`.
73 Follow-ups: #16972 (suspect pull), #16974 (automatic resolve).
78 fix-to-resolved step is not automatic. Also absent: sessions (crash-free %),
79 source maps, browser capture injected by the template, and errors on home and `/flow`.
80 Follow-up: #16974 (automatic resolve).
7481
7582 Direction: errors reported by stock Sentry and OpenTelemetry SDKs, kept first-party, close the loop to issues (#6003, #16973).
src/actions/errors.ts +18 −4
@@ -6,7 +6,7 @@
66 * (`http/error_envelope.ts`) and the admin routes both go through here.
77 */
88 import type { App } from "../app.ts";
9 import { MAX_ENVELOPE, parseEnvelope, type ErrorEvent } from "../core/error_envelope.ts";
9 import { MAX_ENVELOPE, parseEnvelope, type ErrorEvent, type Frame } from "../core/error_envelope.ts";
1010 import {
1111 eventsOf,
1212 getGroup,
@@ -26,6 +26,8 @@ import {
2626 type ReleaseErrors,
2727 type StoredEvent,
2828 } from "../core/error_groups.ts";
29 import { suspectOf, type Suspect } from "../core/error_suspect.ts";
30 import { repoDir } from "../git/repos.ts";
2931 import { getAppById, getAppByRepo } from "../core/apps.ts";
3032 import { addComment, createIssue, getIssue, setIssueState } from "../core/issues.ts";
3133 import { getRepoById, type Repo } from "../core/repos.ts";
@@ -226,17 +228,29 @@ export function errorsOf(app: App, actor: User | undefined, repo: Repo, origin:
226228 });
227229 }
228230
229 export function errorGroup(
231 export async function errorGroup(
230232 app: App,
231233 actor: User | undefined,
232234 repo: Repo,
233235 groupId: string,
234 ): Result<{ group: ErrorGroup; events: StoredEvent[] }, "not_found"> {
236 ): Promise<Result<{ group: ErrorGroup; events: StoredEvent[]; suspect: Suspect | null }, "not_found">> {
235237 const admin = requireRepoAdmin(app, actor, repo);
outdated

Frames are read from events[0]; confirm it is the event of the group's first release. The double cast is also needless: type the detail once.

236238 if (!admin.ok) return admin;
237239 const appRecord = getAppByRepo(app.db, repo.id);
238240 const group = appRecord && getGroup(app.db, appRecord.id, groupId);
239 return group ? ok({ group, events: eventsOf(app.db, group.id) }) : err("not_found");
241 if (!group) return err("not_found");
242 const events = eventsOf(app.db, group.id);
243 // The frames of the event that carries the group's first release, not whichever is newest.
244 const first = events.find((e) => e.release === group.firstRelease);
245 const frames = (first?.detail as { frames?: Frame[] } | undefined)?.frames ?? [];
246 const suspect = await suspectOf(
247 app.db,
248 repoDir(app.reposRoot, repo.ownerName, repo.name),
249 repo.id,
250 group.firstRelease,
251 frames,
252 );
253 return ok({ group, events, suspect: suspect ?? null });
240254 }
241255
242256 /** The fix is live in `release`: the group is resolved there, and its issue closes. */
src/core/error_suspect.ts added +62
@@ -0,0 +1,62 @@
1 /**
2 * The suspect for an error group: the commit that likely caused it. An SDK's release is
3 * conventionally a commit id, so the group's first release names a commit in the repository;
4 * the suspect is the newest commit at or before it that touched the file the error was thrown
5 * in (matched by file name, as a stack's paths are the build's, not the repository's), or the
6 * release's own commit when none did. If a merged pull carried that commit (open pulls are not
7 * named), it is named too. Nothing is guessed from a release that is not a commit.
8 */
9 import type { Database } from "bun:sqlite";
10 import { resolveOid } from "../git/merge.ts";
11 import { commitLog } from "../git/read.ts";
12 import type { Frame } from "./error_envelope.ts";
13
14 /** A path-limited log walks the whole history when the file never changed: bound it. */
15 const READ_MS = 3000;
16
17 export interface Suspect {
18 readonly oid: string;
19 readonly subject: string;
20 /** Why this commit: the file it changed, or that it is the release itself. */
21 readonly why: string;
22 readonly pull: { readonly number: number; readonly title: string } | undefined;
23 }
24
25 /**
26 * The file name of the innermost in-app frame; empty when it has none or cannot be a glob-safe
27 * name.
28 */
29 export function culpritFile(frames: readonly Frame[]): string {
30 const f = [...frames].reverse().find((x) => x.inApp);
31 const name = (f?.file ?? "").split(/[?#]/)[0]!.split(/[\\/]/).pop() ?? "";
32 return /^[\w.+@-]{1,100}$/.test(name) ? name : "";
33 }
34
35 export async function suspectOf(
36 db: Database,
37 dir: string,
38 repoId: string,
39 release: string,
40 frames: readonly Frame[],
41 ): Promise<Suspect | undefined> {
42 if (!/^[0-9a-f]{7,40}$/.test(release)) return undefined;
43 const at = await resolveOid(dir, release);
44 if (at === undefined) return undefined;
45 const file = culpritFile(frames);
46 const touched = file === "" ? undefined : await commitLog(dir, at, { limit: 1, path: `:(glob)**/${file}`, timeoutMs: READ_MS });
47 const hit = touched?.ok ? touched.value[0] : undefined;
48 const commit = hit ?? (await commitLog(dir, at, { limit: 1, timeoutMs: READ_MS }).then((r) => (r.ok ? r.value[0] : undefined)));
49 if (commit === undefined) return undefined;
50 const pull = db
outdated

p.head_oid = ?2 matches unmerged pulls too, so an open pull is named as the one that carried the commit. Match merged_oid only (or require the pull to be merged), and test it.

51 .query<{ number: number; title: string }, [string, string]>(
52 `SELECT i.number, i.title FROM pull p JOIN issue i ON i.id = p.issue_id
53 WHERE i.repo_id = ?1 AND p.merged_oid = ?2 ORDER BY p.merged_at DESC LIMIT 1`,
54 )
55 .get(repoId, commit.oid);
56 return {
57 oid: commit.oid,
58 subject: commit.subject.slice(0, 200),
59 why: hit === undefined ? "the release itself" : `last to change ${file}`,
60 pull: pull ?? undefined,
61 };
62 }
src/git/read.ts +3 −1
@@ -671,6 +671,8 @@ export interface LogOptions {
671671 path?: string;
672672 /** Only commits whose message matches this extended regular expression. */
673673 grep?: string;
674 /** Stop git after this long; the git runner's own default when absent. */
675 timeoutMs?: number;
674676 }
675677
676678 /** When `oid` was committed, as an ISO time; undefined when git cannot say. */
@@ -720,7 +722,7 @@ export async function commitLog(
720722 "--",
721723 ];
722724 if (options.path !== undefined) args.push(options.path);
723 const result = await runGitRaw(args, { cwd: dir });
725 const result = await runGitRaw(args, { cwd: dir, ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }) });
724726 if (!result.ok) return result;
725727
726728 return ok(parseLogRecords(result.value));
src/http/api.ts +2 −2
@@ -3234,12 +3234,12 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
32343234 return seen.ok ? json(seen.value) : notFound();
32353235 });
32363236
3237 router.add("GET", "/api/v1/repos/:owner/:name/app/errors/:group", (ctx) => {
3237 router.add("GET", "/api/v1/repos/:owner/:name/app/errors/:group", async (ctx) => {
32383238 const denied = requireScope(ctx, "admin");
32393239 if (denied) return denied;
32403240 const repo = loadRepo(ctx);
32413241 if (!repo) return notFound();
3242 const seen = errorGroup(ctx.app, ctx.auth.user, repo, ctx.params.group ?? "");
3242 const seen = await errorGroup(ctx.app, ctx.auth.user, repo, ctx.params.group ?? "");
32433243 return seen.ok ? json(seen.value) : notFound();
32443244 });
32453245
src/tui/screens/errors.ts +11 −3
@@ -4,7 +4,7 @@
44 * the repository; anyone else gets no rows). Pick a group to see it, then
55 * name the release that carries the fix to resolve it.
66 */
7 import { errorsOf, resolveError } from "../../actions/errors.ts";
7 import { errorGroup, errorsOf, resolveError } from "../../actions/errors.ts";
88 import { getAppByRepo } from "../../core/apps.ts";
99 import type { Repo } from "../../core/repos.ts";
1010 import type { Ctx, Screen } from "../app/app.ts";
@@ -34,13 +34,21 @@ export function errorCommands(f: Session, ctx: Ctx, parent: () => Screen, repo:
3434 label: g.title,
3535 hint: `${g.count}× · ${g.users} users · ${g.status}${g.issueNumber === undefined ? "" : ` · #${g.issueNumber}`}`,
3636 })),
37 onPick: ([id]) => {
37 onPick: async ([id]) => {
3838 const g = seen.value.groups.find((x) => x.id === id);
3939 if (g === undefined) return;

The git read is awaited here with no failure path, and no test covers the suspect: line. Handle a throw as 'suspect: none' and add a TUI test.

40 const sus = await errorGroup(f.app, user, repo, g.id).then(
41 (s) => (s.ok ? s.value.suspect : null),
42 () => null,
43 );
44 const suspect =
45 sus === null
46 ? "suspect: none (the release is not a commit here)"
47 : `suspect: ${sus.oid.slice(0, 8)} ${sus.subject} (${sus.why})${sus.pull ? ` · pull #${sus.pull.number}` : ""}`;
4048 ctx.push(
4149 confirmScreen(ctx, parent(), {
4250 title: "Resolve this error",
43 body: [g.title, g.culprit || "no stack", `first seen in ${g.firstRelease || "unknown"}`],
51 body: [g.title, g.culprit || "no stack", `first seen in ${g.firstRelease || "unknown"}`, suspect],
4452 actions: [{ label: "Leave open", variant: "ghost" }, { label: "Resolve…" }],
4553 onChoose: (i) => {
4654 if (i < 1) return;
test/error-suspect.test.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * The suspect for an error group: the newest commit at or before the group's first release
3 * that changed the file it was thrown in, with the merged pull that carried it.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { newApp } from "../src/actions/apps.ts";
10 import { errorGroup } from "../src/actions/errors.ts";
11 import { commitToBranch } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { getAppBySlug } from "../src/core/apps.ts";
14 import { parseEnvelope } from "../src/core/error_envelope.ts";
15 import { listGroups, record } from "../src/core/error_groups.ts";
16 import { getRepo, type Repo } from "../src/core/repos.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19 import { mergedPull } from "./helpers/plain-git.ts";
20 import { proveAll } from "./helpers/verified.ts";
21
22 quietLogs();
23
24 let dir: string;
25 let app: App;
26 let alice: User;
27 let shop: Repo;
28 let appId: string;
29 let n = 0;
30
31 const commit = async (message: string, path: string): Promise<string> => {
32 const c = await commitToBranch(app, alice, shop, { message, files: [{ path, content: `${message}\n` }] });
33 if (!c.ok) throw new Error(JSON.stringify(c.error));
34 return c.value.commitOid;
35 };
36
37 /** Records a sighting and returns the suspect the group's view names. */
38 async function suspectFor(release: string, file: string, extra: { release: string; file: string }[] = []) {
39 const title = `bad ${++n}`;
40 for (const [rel, f] of [[release, file], ...extra.map((e) => [e.release, e.file] as const)] as const) {
41 const ev = { release: rel, fingerprint: [title], exception: { values: [{ type: "Error", value: title, stacktrace: { frames: [{ filename: f, function: "f", lineno: 1, in_app: true }] } }] } };
42 const body = ["{}", '{"type":"event"}', JSON.stringify(ev)].join("\n");
43 for (const parsed of parseEnvelope(Buffer.from(body), "k")) record(app.db, appId, parsed);
44 }
45 const group = listGroups(app.db, appId, 1000).find((g) => g.title.includes(title))!;
46 const seen = await errorGroup(app, alice, shop, group.id);
47 if (!seen.ok) throw new Error(seen.error);
48 return seen.value.suspect;
49 }
50
51 beforeAll(async () => {
52 dir = await mkdtemp(join(tmpdir(), "forge-error-suspect-"));
53 app = createApp({ dataDir: dir, port: 0 });
54 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
55 if (!made.ok) throw new Error(made.error);
56 alice = made.value;
57 proveAll(app);
58 const r = await newApp(app, alice, { name: "shop", description: "Words", visibility: "public" });
59 if (!r.ok) throw new Error(String(r.error));
60 shop = getRepo(app.db, "alice", "shop")!;
61 appId = getAppBySlug(app.db, "shop")!.id;
62 });
63 afterAll(async () => {
64 app.db.close();
65 await rm(dir, { recursive: true, force: true });
66 });
67
68 describe("the suspect for an error group", () => {
69 test("the last commit to change the file, with the merged pull that carried it", async () => {
70 const culprit = await commit("break charge", "src/suspect.ts");
71 const release = await commit("unrelated later", "README.md");
72 mergedPull(app.db, { repoId: shop.id, branch: "main", authorId: alice.id, n: 90, oid: culprit, at: new Date().toISOString(), title: "Charge by card" });
73 expect(await suspectFor(release, "/srv/build/src/suspect.ts?v=2")).toEqual({
74 oid: culprit,
75 subject: "break charge",
76 why: "last to change suspect.ts",
77 pull: { number: 90, title: "Charge by card" },
78 });
79 });
80
81 test("an open pull whose head is the commit is not named as the one that carried it", async () => {
82 const culprit = await commit("open work", "src/open.ts");
83 mergedPull(app.db, { repoId: shop.id, branch: "main", authorId: alice.id, n: 91, oid: culprit, at: new Date().toISOString(), title: "Still open" });
84 app.db.query("UPDATE pull SET merged_at = NULL, merged_oid = NULL, head_oid = ?1 WHERE issue_id = (SELECT id FROM issue WHERE repo_id = ?2 AND number = 91)").run(culprit, shop.id);
85 expect((await suspectFor(culprit, "src/open.ts"))?.pull).toBeUndefined();
86 });
87
88 test("a file no commit changed falls back to the release itself", async () => {
89 const release = await commit("the release", "src/other.ts");
90 expect(await suspectFor(release, "ghost.ts")).toMatchObject({ oid: release, subject: "the release", why: "the release itself" });
91 });
92
93 test("the frames come from the event of the first release, not the newest", async () => {
94 const first = await commit("first", "src/first.ts");
95 await commit("later", "src/later.ts");
96 const second = await commit("second", "README.md");
97 expect(await suspectFor(first, "first.ts", [{ release: second, file: "later.ts" }])).toMatchObject({ oid: first, why: "last to change first.ts" });
98 });
99
100 test("a release that is not a commit has no suspect", async () => {
101 expect(await suspectFor("v1.2.3", "suspect.ts")).toBeNull();
102 });
103 });
test/tui-errors.test.ts +18 −2
@@ -9,10 +9,11 @@ import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { newApp } from "../src/actions/apps.ts";
1111 import { ingest } from "../src/actions/errors.ts";
12 import { createRepo } from "../src/actions/repos.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1313 import { createApp, type App } from "../src/app.ts";
1414 import { getAppBySlug } from "../src/core/apps.ts";
15 import { keyOf, listGroups } from "../src/core/error_groups.ts";
15 import { parseEnvelope } from "../src/core/error_envelope.ts";
16 import { keyOf, listGroups, record } from "../src/core/error_groups.ts";
1617 import { getRepo, type Repo } from "../src/core/repos.ts";
1718 import { createUser, type User } from "../src/core/users.ts";
1819 import { createForgeApp } from "../src/tui/forge.ts";
@@ -98,4 +99,19 @@ describe("an app's errors, in the terminal", () => {
9899 const g = listGroups(app.db, getAppBySlug(app.db, "shop")!.id)[0]!;
99100 expect(g).toMatchObject({ status: "resolved", resolvedIn: "r9" });
100101 });
102
103 test("the resolve screen names the suspect commit, or says there is none", async () => {
104 const pick = [":", "Errors", "\r", "\r"];
105 expect(await palette(alice, shop, pick)).toContain("suspect: none");
106 const c = await commitToBranch(app, alice, shop, { message: "break pay", files: [{ path: "src/pay.ts", content: "x\n" }] });
107 if (!c.ok) throw new Error(JSON.stringify(c.error));
108 const frame = { filename: "/srv/app/src/pay.ts", function: "pay", lineno: 3, in_app: true };
109 const body = [
110 "{}",
111 '{"type":"event"}',
112 JSON.stringify({ release: c.value.commitOid, exception: { values: [{ type: "Error", value: "bad pay", stacktrace: { frames: [frame] } }] } }),
113 ].join("\n");
114 for (const parsed of parseEnvelope(Buffer.from(body), "k")) record(app.db, getAppBySlug(app.db, "shop")!.id, parsed);
115 expect(await palette(alice, shop, pick)).toContain(`suspect: ${c.value.commitOid.slice(0, 8)} break pay`);
116 });
101117 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs