Skip to content
refs
History
194 lines · 9.5 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 to any branch indexes its decisions, with no session", async () => {
126 const { sqlite, env } = setup();
127 const human: PushMessage = { repoId: "repo", actor: { kind: "human", person: "u1", via: "session" }, updates: [{ ref: "refs/heads/fix-queue", from: base, to: broken }], at: 100 };
128 assert.equal(await deliver(env, human), "ack");
129 assert.deepEqual({ ...sqlite.prepare("SELECT session_id FROM decisions").get() }, { session_id: null });
130});
131
132test("a merge into the default branch changes no task, even when the pull request names one with a closing keyword", async () => {
133 const { sqlite, env } = setup();
134 sqlite.exec("UPDATE pulls SET body = 'Closes #7'");
135 assert.equal(await deliver(env, push), "ack");
136 assert.equal(count(sqlite, "SELECT count(*) AS n FROM pulls WHERE status = 'merged'"), 1);
137 assert.equal(count(sqlite, "SELECT count(*) AS n FROM tasks WHERE status = 'closed'"), 0);
138 assert.equal(count(sqlite, "SELECT count(*) AS n FROM events WHERE kind = 'task.closed'"), 0);
139});
140
141function sweepable(seeded: boolean) {
142 const { sqlite, env } = setup();
143 const sent: PushMessage[] = [];
144 Object.assign(env, { PUSHES: { sendBatch: async (messages: { body: PushMessage }[]) => sent.push(...messages.map((message) => message.body)) } });
145 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)`);
146 return { sqlite, env, sent };
147}
148
149const count = (sqlite: ReturnType<typeof migrated>, sql: string) => (sqlite.prepare(sql).get() as { n: number }).n;
150
151test("pushes whose messages were lost are found by the sweep and processed once, as refs", async () => {
152 const { sqlite, env, sent } = sweepable(true);
153 await reconcilePushes(env);
154 assert.deepEqual(
155 sent.map((message) => [message.actor, message.updates]),
156 [
157 [{ kind: "system" }, [{ ref: "refs/heads/main", from: base, to: merge }]],
158 [{ kind: "system" }, [{ ref: "refs/heads/tasks/7", from: base, to: broken }]],
159 ],
160 );
161 for (const message of sent) assert.equal(await deliver(env, message), "ack");
162 assert.equal(await deliver(env, push), "ack");
163 assert.equal(count(sqlite, "SELECT count(*) AS n FROM events WHERE kind = 'repo.pushed' AND actor_id = 'refs'"), 2);
164 assert.equal(count(sqlite, "SELECT count(*) AS n FROM events WHERE kind = 'repo.pushed'"), 2);
165 assert.deepEqual({ ...outcome(sqlite), pushed: 1 }, once);
166 assert.equal(count(sqlite, `SELECT count(*) AS n FROM decisions WHERE id = '${decisionId}' AND session_id IS NULL`), 1);
167
168 sent.length = 0;
169 await reconcilePushes(env);
170 assert.deepEqual(sent, []);
171});
172
173test("the first sweep of a repository records its tips without replaying them", async () => {
174 const { sqlite, env, sent } = sweepable(false);
175 await reconcilePushes(env);
176 assert.deepEqual(sent, []);
177 assert.deepEqual(
178 sqlite.prepare("SELECT ref, sha FROM ref_tips ORDER BY ref").all().map((row) => ({ ...row })),
179 [
180 { ref: "refs/heads/main", sha: merge },
181 { ref: "refs/heads/tasks/7", sha: broken },
182 ],
183 );
184 assert.equal(count(sqlite, "SELECT count(*) AS n FROM events"), 0);
185 await reconcilePushes(env);
186 assert.deepEqual(sent, []);
187});
188
189test("a push processed after a later one does not move its ref back", async () => {
190 const { sqlite, env } = sweepable(true);
191 assert.equal(await deliver(env, { ...push, at: 200 }), "ack");
192 assert.equal(await deliver(env, { ...push, actor: { kind: "system" }, updates: [{ ref: "refs/heads/main", from: null, to: base }], at: 150 }), "ack");
193 assert.deepEqual({ ...sqlite.prepare("SELECT sha FROM ref_tips WHERE ref = 'refs/heads/main'").get() }, { sha: merge });
194});