Skip to content
refs
History
250 lines · 12.8 KBRaw
1import assert from "node:assert/strict";
2import { mock, test } from "node:test";
3import { consumePushes, reconcilePushes, type PushMessage } from "../pushes.ts";
4import { d1, migrated } from "./d1.ts";
5
6const base = "b".repeat(40);
7const recorded = "1".repeat(40);
8const broken = "2".repeat(40);
9const merge = "3".repeat(40);
10const decisionId = "DEC-01JB7Q3M8Z4K2N6V9XWRT5HYCE";
11
12const commits = new Map([
13 [base, { hash: base, parents: [], message: "Start" }],
14 [recorded, { hash: recorded, parents: [base], message: `Decide\n\n\`\`\`decision\ndecision_id: ${decisionId}\ntask: 7\ndecision: "Queue pushes."\nreason:\n - waitUntil drops work\n\`\`\`\n` }],
15 [broken, { hash: broken, parents: [recorded], message: "Break\n\n```decision\ndecision: x\n" }],
16 [merge, { hash: merge, parents: [base, broken], message: "Merge" }],
17]);
18
19function log(tip: string) {
20 const seen: { hash: string; message: string }[] = [];
21 for (let hash: string | undefined = tip; hash; hash = commits.get(hash)!.parents.at(-1)) seen.push(commits.get(hash)!);
22 return seen;
23}
24
25function pkt(line: string): string {
26 return (line.length + 4).toString(16).padStart(4, "0") + line;
27}
28
29function setup() {
30 const sqlite = migrated();
31 sqlite.exec(`
32 INSERT INTO namespaces (id, slug, name, kind, created_at) VALUES ('ns', 'refs', 'refs', 'org', 0); INSERT INTO users (id, email, name, password_hash, created_at) VALUES ('u1', 'a@x', 'Aman', 'h', 0); INSERT INTO memberships (namespace_id, user_id, role, created_at) VALUES ('ns', 'u1', 'owner', 0);
33 INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'private', 'refs-art', 'u1', 0);
34 INSERT INTO tasks (id, repo_id, number, title, author_id, created_at, updated_at) VALUES (1, 'repo', 7, 't', 'u1', 0, 0);
35 INSERT INTO agent_sessions (id, token_hash, user_id, repo_id, runtime, created_at, expires_at, ended_at) VALUES ('s1', 'th', 'u1', 'repo', 'claude-code', 0, 1, 1);
36 INSERT INTO pulls (id, repo_id, number, title, author_id, base_ref, head_ref, created_at, updated_at) VALUES (1, 'repo', 1, 't', 'u1', 'main', 'tasks/7', 0, 0);
37 `);
38 let failures = 0;
39 const ci = { reads: [] as unknown[], down: false };
40 const handle = {
41 readFile: async (query: unknown) => {
42 if (ci.down) throw new Error("ci down");
43 ci.reads.push(query);
44 return null;
45 },
46 log: async ({ ref }: { ref: string }) => log(ref === "main" ? merge : ref),
47 readCommit: async (hash: string) => commits.get(hash) ?? null,
48 info: async () => ({ remote: "https://artifacts.test/refs-art" }),
49 createToken: async () => ({ plaintext: "t" }),
50 [Symbol.dispose]() {},
51 };
52 const env = {
53 DB: d1(sqlite),
54 ARTIFACTS: {
55 get: async () => {
56 if (failures-- > 0) throw new Error("Artifacts unavailable");
57 return handle;
58 },
59 },
60 } as unknown as Env;
61 return { sqlite, env, ci, failNext: (count: number) => (failures = count) };
62}
63
64async function deliver(env: Env, body: PushMessage, attempts = 1, ctx: Pick<ExecutionContext, "waitUntil"> = { waitUntil() {} }): Promise<"ack" | "retry"> {
65 let outcome: "ack" | "retry" | undefined;
66 const message = { body, attempts, ack: () => (outcome = "ack"), retry: () => (outcome = "retry") };
67 await consumePushes({ queue: "refs-pushes", messages: [message] } as unknown as MessageBatch<PushMessage>, env, ctx);
68 return outcome!;
69}
70
71const push: PushMessage = { repoId: "repo", actor: { kind: "agent", person: "u1", session: "s1" }, updates: [{ ref: "refs/heads/main", from: base, to: merge }], at: 100 };
72
73mock.method(globalThis, "fetch", async () => new Response(pkt(`${merge} refs/heads/main\n`) + pkt(`${broken} refs/heads/tasks/7\n`) + "0000"));
74
75function outcome(sqlite: ReturnType<typeof migrated>) {
76 const count = (sql: string) => (sqlite.prepare(sql).get() as { n: number }).n;
77 return {
78 pushed: count("SELECT count(*) AS n FROM events WHERE kind = 'repo.pushed' AND session_id = 's1'"),
79 merged: count("SELECT count(*) AS n FROM pulls WHERE status = 'merged'"),
80 mergedEvents: count("SELECT count(*) AS n FROM events WHERE kind = 'pull.merged'"),
81 decisions: count(`SELECT count(*) AS n FROM decisions WHERE id = '${decisionId}' AND commit_sha = '${recorded}'`),
82 problems: count("SELECT count(*) AS n FROM events WHERE kind = 'session.problem'"),
83 };
84}
85
86const once = { pushed: 1, merged: 1, mergedEvents: 1, decisions: 1, problems: 0 };
87
88test("a push delivered twice, by a session that has since ended, has its consequences once", async () => {
89 const { sqlite, env } = setup();
90 assert.equal(await deliver(env, push), "ack");
91 assert.equal(await deliver(env, push), "ack");
92 assert.deepEqual(outcome(sqlite), once);
93});
94
95test("a push asks CI for the pipeline at its branch tip, and a CI failure does not fail the push", async () => {
96 const { sqlite, env, ci } = setup();
97 assert.equal(await deliver(env, push), "ack");
98 assert.deepEqual(ci.reads, [{ ref: merge, path: ".refs/ci.yml" }]);
99 ci.down = true;
100 const original = console.error;
101 console.error = () => undefined;
102 try {
103 assert.equal(await deliver(env, { ...push, at: 200 }), "ack");
104 } finally {
105 console.error = original;
106 }
107 assert.equal(outcome(sqlite).merged, 1);
108});
109
110test("a push whose processing fails is retried until the pull request is merged and its decisions indexed", async () => {
111 const { sqlite, env, failNext } = setup();
112 failNext(1);
113 assert.equal(await deliver(env, push), "retry");
114 assert.equal(await deliver(env, push, 2), "ack");
115 assert.deepEqual(outcome(sqlite), once);
116});
117
118test("a push is indexed under the session that pushed it, even after the session ended", async () => {
119 const { sqlite, env } = setup();
120 assert.equal(await deliver(env, push), "ack");
121 assert.deepEqual({ ...sqlite.prepare("SELECT session_id FROM decisions").get() }, { session_id: "s1" });
122 assert.deepEqual(outcome(sqlite), once);
123});
124
125test("a human push that lands a pull request is captured once as landed work, and a push refs found is not", async (t) => {
126 const gitResponse = await (await fetch("https://artifacts.test")).text();
127 const captured: { event: string; distinct_id: string; properties: Record<string, unknown> }[] = [];
128 t.mock.method(globalThis, "fetch", async (url: string, init?: RequestInit) => {
129 if (String(url).startsWith("https://us.i.posthog.com/")) {
130 captured.push(JSON.parse(String(init!.body)));
131 return new Response(null, { status: 204 });
132 }
133 return new Response(gitResponse);
134 });
135 for (const [actor, expected] of [[{ kind: "human", person: "u1", via: "token" }, 1], [{ kind: "system" }, 0]] as const) {
136 const { sqlite, env } = setup();
137 Object.assign(env, { POSTHOG_ENABLED: "true", POSTHOG_PROJECT_TOKEN: "project-token", POSTHOG_HOST: "https://us.i.posthog.com" });
138 const pending: Promise<unknown>[] = [];
139 const ctx = { waitUntil: (promise: Promise<unknown>) => void pending.push(promise) };
140 const before = captured.length;
141 assert.equal(await deliver(env, { ...push, actor }, 1, ctx), "ack");
142 assert.equal(await deliver(env, { ...push, actor }, 1, ctx), "ack");
143 await Promise.all(pending);
144 const landed = captured.slice(before).filter((payload) => payload.event === "work.landed");
145 assert.equal(landed.length, expected);
146 if (expected) {
147 assert.equal(landed[0].distinct_id, "human:u1");
148 const { repo_id, task_number, merge_method, $groups } = landed[0].properties;
149 assert.deepEqual({ repo_id, task_number, merge_method, $groups }, { repo_id: "repo", task_number: undefined, merge_method: "push", $groups: { workspace: "ns" } });
150 }
151 }
152});
153
154test("an indexed push is captured with its commit and decision counts, and a push refs found is not", async (t) => {
155 const gitResponse = await (await fetch("https://artifacts.test")).text();
156 const captured: { event: string; distinct_id: string; properties: Record<string, unknown> }[] = [];
157 t.mock.method(globalThis, "fetch", async (url: string, init?: RequestInit) => {
158 if (String(url).startsWith("https://us.i.posthog.com/")) {
159 captured.push(JSON.parse(String(init!.body)));
160 return new Response(null, { status: 204 });
161 }
162 return new Response(gitResponse);
163 });
164 for (const [actor, expected] of [[push.actor, 1], [{ kind: "system" }, 0]] as const) {
165 const { env } = setup();
166 Object.assign(env, { POSTHOG_ENABLED: "true", POSTHOG_PROJECT_TOKEN: "project-token", POSTHOG_HOST: "https://us.i.posthog.com" });
167 const pending: Promise<unknown>[] = [];
168 const ctx = { waitUntil: (promise: Promise<unknown>) => void pending.push(promise) };
169 const before = captured.length;
170 assert.equal(await deliver(env, { ...push, actor }, 1, ctx), "ack");
171 await Promise.all(pending);
172 const recorded = captured.slice(before).filter((payload) => payload.event === "commits.recorded");
173 assert.equal(recorded.length, expected);
174 if (expected) {
175 const { commit_count, decision_count, task_number, $groups } = recorded[0].properties;
176 assert.deepEqual({ distinct_id: recorded[0].distinct_id, commit_count, decision_count, task_number, $groups }, { distinct_id: "agent:s1", commit_count: 3, decision_count: 1, task_number: undefined, $groups: { workspace: "ns" } });
177 }
178 }
179});
180
181test("a human push to any branch indexes its decisions, with no session", async () => {
182 const { sqlite, env } = setup();
183 const human: PushMessage = { repoId: "repo", actor: { kind: "human", person: "u1", via: "session" }, updates: [{ ref: "refs/heads/fix-queue", from: base, to: broken }], at: 100 };
184 assert.equal(await deliver(env, human), "ack");
185 assert.deepEqual({ ...sqlite.prepare("SELECT session_id FROM decisions").get() }, { session_id: null });
186});
187
188test("a merge into the default branch changes no task, even when the pull request names one with a closing keyword", async () => {
189 const { sqlite, env } = setup();
190 sqlite.exec("UPDATE pulls SET body = 'Closes #7'");
191 assert.equal(await deliver(env, push), "ack");
192 assert.equal(count(sqlite, "SELECT count(*) AS n FROM pulls WHERE status = 'merged'"), 1);
193 assert.equal(count(sqlite, "SELECT count(*) AS n FROM tasks WHERE status = 'closed'"), 0);
194 assert.equal(count(sqlite, "SELECT count(*) AS n FROM events WHERE kind = 'task.closed'"), 0);
195});
196
197function sweepable(seeded: boolean) {
198 const { sqlite, env } = setup();
199 const sent: PushMessage[] = [];
200 Object.assign(env, { PUSHES: { sendBatch: async (messages: { body: PushMessage }[]) => sent.push(...messages.map((message) => message.body)) } });
201 if (seeded) sqlite.exec(`UPDATE repos SET tips_checked_at = 0; INSERT INTO ref_tips (repo_id, ref, sha, seen_at) VALUES ('repo', 'refs/heads/main', '${base}', 0), ('repo', 'refs/heads/tasks/7', '${base}', 0)`);
202 return { sqlite, env, sent };
203}
204
205const count = (sqlite: ReturnType<typeof migrated>, sql: string) => (sqlite.prepare(sql).get() as { n: number }).n;
206
207test("pushes whose messages were lost are found by the sweep and processed once, as refs", async () => {
208 const { sqlite, env, sent } = sweepable(true);
209 await reconcilePushes(env);
210 assert.deepEqual(
211 sent.map((message) => [message.actor, message.updates]),
212 [
213 [{ kind: "system" }, [{ ref: "refs/heads/main", from: base, to: merge }]],
214 [{ kind: "system" }, [{ ref: "refs/heads/tasks/7", from: base, to: broken }]],
215 ],
216 );
217 for (const message of sent) assert.equal(await deliver(env, message), "ack");
218 assert.equal(await deliver(env, push), "ack");
219 assert.equal(count(sqlite, "SELECT count(*) AS n FROM events WHERE kind = 'repo.pushed' AND actor_id = 'refs'"), 2);
220 assert.equal(count(sqlite, "SELECT count(*) AS n FROM events WHERE kind = 'repo.pushed'"), 2);
221 assert.deepEqual({ ...outcome(sqlite), pushed: 1 }, once);
222 assert.equal(count(sqlite, `SELECT count(*) AS n FROM decisions WHERE id = '${decisionId}' AND session_id IS NULL`), 1);
223
224 sent.length = 0;
225 await reconcilePushes(env);
226 assert.deepEqual(sent, []);
227});
228
229test("the first sweep of a repository records its tips without replaying them", async () => {
230 const { sqlite, env, sent } = sweepable(false);
231 await reconcilePushes(env);
232 assert.deepEqual(sent, []);
233 assert.deepEqual(
234 sqlite.prepare("SELECT ref, sha FROM ref_tips ORDER BY ref").all().map((row) => ({ ...row })),
235 [
236 { ref: "refs/heads/main", sha: merge },
237 { ref: "refs/heads/tasks/7", sha: broken },
238 ],
239 );
240 assert.equal(count(sqlite, "SELECT count(*) AS n FROM events"), 0);
241 await reconcilePushes(env);
242 assert.deepEqual(sent, []);
243});
244
245test("a push processed after a later one does not move its ref back", async () => {
246 const { sqlite, env } = sweepable(true);
247 assert.equal(await deliver(env, { ...push, at: 200 }), "ack");
248 assert.equal(await deliver(env, { ...push, actor: { kind: "system" }, updates: [{ ref: "refs/heads/main", from: null, to: base }], at: 150 }), "ack");
249 assert.deepEqual({ ...sqlite.prepare("SELECT sha FROM ref_tips WHERE ref = 'refs/heads/main'").get() }, { sha: merge });
250});