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

app-home-batched boots one forge for the file, and each test has its own account and repositories #17805

opened this

Merged 15h 37m ago, live in production

home-batched-once → main 0 commits 4 threads · 4 unresolved

  • Merged. home-batched-once was merged into main as 4763617.

Review

Sign in to review this change.
1 file changed +172 −150
test/app-home-batched.test.ts +172 −150
@@ -1,5 +1,5 @@
11 /** An app home's `now` and `following` read in batches: 200 issues, 40 pulls, 5 runs (#6184); no statement grows with the rows (#6819). */
2 import { afterEach, beforeEach, expect, test } from "bun:test";
2 import { afterAll, beforeAll, expect, test } from "bun:test";
33 import { mkdtempSync, rmSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
@@ -8,10 +8,11 @@ import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
88 import { createApp, type App } from "../src/app.ts";
99 import { forkRelation } from "../src/core/following.ts";
1010 import { deferredOf, repoGraph } from "../src/core/dependencies.ts";
11 import { getRepo } from "../src/core/repos.ts";
12 import { setMember } from "../src/core/roles.ts";
13 import { createUser } from "../src/core/users.ts";
11 import type { Repo } from "../src/core/repos.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createUser, type User } from "../src/core/users.ts";
1414 import { serve, type Servers } from "../src/http/server.ts";
15 import { promote } from "./helpers/members.ts";
1516 import { proveAll } from "./helpers/verified.ts";
1617 import { quietLogs } from "./helpers/globals.ts";
1718 import { quiet } from "./helpers/statements.ts";
@@ -64,16 +65,145 @@ function seedLive(db: App["db"], repoId: string, author: string, from: number):
6465 let root = "";
6566 let app: App;
6667 let servers: Servers;
67 let cookie = "";
68 const PAGES = ["/alice/vault", "/alice/vault-fork"];
69 /** Statements a page cost with few rows. */
70 const small: Record<string, number> = {};
71 /** Every statement of the home, by text, after each seed step. */
72 let fewStatements = new Map<string, number>();
73 let manyStatements = new Map<string, number>();
68 let bob: User;
69
70 async function account(username: string): Promise<User> {
71 const made = await createUser(app.db, {
72 origin: "seed",
73 trusted: true,
74 username,
75 email: `${username}@forge.local`,
76 password: "a-good-passphrase",
77 });
78 if (!made.ok) throw new Error(made.error);
79 proveAll(app);
80 // A member may own a repository and make an app of it; a guest may not.
81 promote(app.db, made.value);
82 return made.value;
83 }
84
85 /**
86 * One forge for the file. What a test reads or writes is its own: an account and that account's
87 * private repositories (`home`), so no test's rows are in another's page, in any order. No account is
88 * an admin: an admin reads past its own rows, and nothing here needs one.
89 */
90 beforeAll(async () => {
outdated

alice is no longer created in this file; point forgeRepo at something that exists here.

91 root = mkdtempSync(join(tmpdir(), "forge-home-batched-"));
92 app = createApp({ dataDir: root, port: 0 });
93 bob = await account("bob");
94 servers = await serve(app);
95 });
96 afterAll(() => {
97 servers.stop();
98 app.close();
99 rmSync(root, { recursive: true, force: true });
100 });
101
102 interface Home {
103 readonly owner: User;
104 readonly vault: Repo;
105 readonly cookie: string;
106 /** The app's home, and its diverged fork's. */
107 readonly path: string;
108 readonly forkPath: string;
109 /** From the few rows a home starts with to 200 issues, 40 pulls and 5 runs. */
110 readonly grow: () => void;
111 }
112
113 async function newVault(owner: User): Promise<Repo> {
114 const made = await createRepo(app, owner, { name: "vault" });
115 if (!made.ok) throw new Error(String(made.error));
116 return made.value;
117 }
118
119 /** An account of its own with an app, its diverged fork, and a few rows in each. */
120 async function home(who: string): Promise<Home> {
outdated

Admin sees every private repo, including earlier tests' rows. Use a non-admin owner so the isolation holds in any order.

121 const owner = await account(who);
122 const vault = await newVault(owner);
123 const seeded = await commitToBranch(app, owner, vault, {
124 message: "Start",
125 files: [{ path: "README.md", content: "v\n" }],
126 });
127 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
128 const enabled = await enableApp(app, owner, vault, { slug: `${who}-vault` });
129 if (!enabled.ok) throw new Error(String(enabled.error));
130 const forked = await forkRepo(app, owner, vault, "vault-fork");
131 if (!forked.ok) throw new Error(String(forked.error));
132 const enabledFork = await enableApp(app, owner, forked.value, { slug: `${who}-vault-fork` });
133 if (!enabledFork.ok) throw new Error(String(enabledFork.error));
134 // Both sides edit the same line: diverged, and git cannot merge them.
135 for (const [repo, content] of [[forked.value, "fork\n"], [vault, "parent\n"]] as const) {
136 const moved = await commitToBranch(app, owner, repo, {
137 message: "Edit",
138 files: [{ path: "README.md", content }],
139 });
140 if (!moved.ok) throw new Error(JSON.stringify(moved.error));
141 }
142 // The parent's push is followed as it lands; wait for the fork to read diverged.
143 // Git may be slow on a loaded machine; the wait is for a verdict, not a clock.
144 let diverged = false;
145 for (let i = 0; i < 1000 && !diverged; i++) {
146 diverged = (await forkRelation(app, forked.value))?.state === "diverged";
147 if (!diverged) await new Promise((r) => setTimeout(r, 5)); // real-timer: git follows the parent in the background; poll for its verdict
148 }
149 if (!diverged) throw new Error("the fork never read diverged");
150 const db = app.db;
151 const repoIds = [vault.id, forked.value.id];
outdated

A shared agent as assignee leaks across tests. Assign to owner.id always.

152 // A repository of someone else's that the viewer does not follow: work assigned to them there
153 // needs a real read per repository, not per row (the `canRead` memo in asks.ts).
154 const elsewhere = await createRepo(app, bob, { name: `elsewhere-${who}` });
155 if (!elsewhere.ok) throw new Error(String(elsewhere.error));
156 const seedElsewhere = (from: number, to: number) =>
157 db.transaction(() => {
158 for (let i = from; i < to; i++)
159 db.query(
160 `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, assignee_id, state)
161 VALUES (?1, ?2, ?3, 'issue', ?4, '', ?5, ?6, 'open')`,
162 ).run(`${elsewhere.value.id}i${i}`, elsewhere.value.id, 1 + i, `Away ${i}`, bob.id, owner.id);
163 })();
164 // Rows are added in two steps: a few, measured; then up to 200/40/5, measured again.
165 const seed = (issues: [number, number], pulls: [number, number], runs: [number, number]) =>
166 db.transaction(() => {
167 for (const repoId of repoIds) {
168 for (let i = issues[0]; i < issues[1]; i++) {
169 db.query(
170 `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, assignee_id, state)
171 VALUES (?1, ?2, ?3, 'issue', ?4, '', ?5, ?6, 'open')`,
172 ).run(`${repoId}i${i}`, repoId, 1 + i, `Tell ${i}`, owner.id, i % 2 === 0 ? owner.id : null);
173 }
174 for (let i = pulls[0]; i < pulls[1]; i++) {
175 db.query(
176 `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state)
177 VALUES (?1, ?2, ?3, 'pull', ?4, ?5, ?6, 'open')`,
178 ).run(`${repoId}p${i}`, repoId, 1000 + i, `Pull ${i}`, `Closes #${i + 1}`, owner.id);
179 db.query(
180 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid)
181 VALUES (?1, 'main', ?2, 'x', 'y')`,
182 ).run(`${repoId}p${i}`, `b${i}`);
183 }
184 for (let i = runs[0]; i < runs[1]; i++)
185 db.query(
186 `INSERT INTO run (id, repo_id, kind, state, issue_id) VALUES (?1, ?2, 'agent', 'running', ?3)`,
187 ).run(`${repoId}r${i}`, repoId, `${repoId}i${i * 2 + 1}`);
188 }
189 })();
190 seed([0, 10], [0, 2], [0, 1]);
191 seedElsewhere(0, 2);
192 return {
193 owner,
194 vault,
195 cookie: `forge_session=${createSession(app.db, owner.id).token}`,
196 path: `/${who}/vault`,
197 forkPath: `/${who}/vault-fork`,
198 grow: () => {
199 seed([10, 200], [2, 40], [1, 5]);
200 seedElsewhere(2, 30);
201 },
202 };
203 }
74204
75205 /** SQL statements one signed-in GET prepares: load-independent, unlike its milliseconds. */
76 async function queriesFor(path: string): Promise<number> {
206 async function queriesFor(path: string, cookie: string): Promise<number> {
77207 const db = app.db as unknown as { query: (sql: string) => unknown };
78208 const real = db.query;
79209 let n = 0;
@@ -96,133 +226,15 @@ async function queriesFor(path: string): Promise<number> {
96226 * while a page is read, and only ever adds to the count; the fewest of three reads is the page's
97227 * own cost.
98228 */
99 async function costOf(path: string): Promise<number> {
229 async function costOf(path: string, cookie: string): Promise<number> {
100230 let least = Infinity;
101231 for (let i = 0; i < 3; i++) {
102232 await quiet(app.db); // start from rest, not in the tail of the last request's work
103 least = Math.min(least, await queriesFor(path));
233 least = Math.min(least, await queriesFor(path, cookie));
104234 }
105235 return least;
106236 }
107237
108 beforeEach(async () => {
109 root = mkdtempSync(join(tmpdir(), "forge-home-batched-"));
110 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
111 const u = await createUser(app.db, {
112 origin: "seed",
113 trusted: true,
114 username: "alice",
115 email: "[email protected]",
116 password: "a-good-passphrase",
117 adminIfFirst: true,
118 });
119 if (!u.ok) throw new Error(u.error);
120 proveAll(app);
121 const made = await createRepo(app, u.value, { name: "vault" });
122 if (!made.ok) throw new Error(String(made.error));
123 const seeded = await commitToBranch(app, u.value, made.value, {
124 message: "Start",
125 files: [{ path: "README.md", content: "v\n" }],
126 });
127 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
128 const enabled = await enableApp(app, u.value, made.value, { slug: "vault" });
129 if (!enabled.ok) throw new Error(String(enabled.error));
130 const forked = await forkRepo(app, u.value, made.value, "vault-fork");
131 if (!forked.ok) throw new Error(String(forked.error));
132 const enabledFork = await enableApp(app, u.value, forked.value, { slug: "vault-fork" });
133 if (!enabledFork.ok) throw new Error(String(enabledFork.error));
134 // Both sides edit the same line: diverged, and git cannot merge them.
135 for (const [repo, content] of [[forked.value, "fork\n"], [made.value, "parent\n"]] as const) {
136 const moved = await commitToBranch(app, u.value, repo, {
137 message: "Edit",
138 files: [{ path: "README.md", content }],
139 });
140 if (!moved.ok) throw new Error(JSON.stringify(moved.error));
141 }
142 // The parent's push is followed as it lands; wait for the fork to read diverged.
143 // Git may be slow on a loaded machine; the wait is for a verdict, not a clock.
144 let diverged = false;
145 for (let i = 0; i < 1000 && !diverged; i++) {
146 diverged = (await forkRelation(app, forked.value))?.state === "diverged";
147 if (!diverged) await new Promise((r) => setTimeout(r, 5)); // real-timer: git follows the parent in the background; poll for its verdict
148 }
149 if (!diverged) throw new Error("the fork never read diverged");
150 const db = app.db;
151 const agent = db.query<{ id: string }, []>("SELECT id FROM user WHERE kind = 'agent' LIMIT 1").get();
152 const assignee = agent?.id ?? u.value.id;
153 const repoIds = [made.value.id, forked.value.id];
154 // A public repository the viewer does not follow: work assigned to them there
155 // needs a real read per repository, not per row (the `canRead` memo in asks.ts).
156 const bob = await createUser(app.db, {
157 origin: "seed",
158 trusted: true,
159 username: "bob",
160 email: "[email protected]",
161 password: "a-good-passphrase",
162 });
163 if (!bob.ok) throw new Error(bob.error);
164 proveAll(app);
165 setMember(app.db, bob.value.id, true, u.value.id, new Date());
166 const elsewhere = await createRepo(app, bob.value, { name: "elsewhere" });
167 if (!elsewhere.ok) throw new Error(String(elsewhere.error));
168 const seedElsewhere = (from: number, to: number) =>
169 db.transaction(() => {
170 for (let i = from; i < to; i++)
171 db.query(
172 `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, assignee_id, state)
173 VALUES (?1, ?2, ?3, 'issue', ?4, '', ?5, ?6, 'open')`,
174 ).run(`${elsewhere.value.id}i${i}`, elsewhere.value.id, 1 + i, `Away ${i}`, bob.value.id, u.value.id);
175 })();
176 // Rows are added in two steps: a few, measured; then up to 200/40/5, measured again.
177 const seed = (issues: [number, number], pulls: [number, number], runs: [number, number]) =>
178 db.transaction(() => {
179 for (const repoId of repoIds) {
180 for (let i = issues[0]; i < issues[1]; i++) {
181 db.query(
182 `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, assignee_id, state)
183 VALUES (?1, ?2, ?3, 'issue', ?4, '', ?5, ?6, 'open')`,
184 ).run(`${repoId}i${i}`, repoId, 1 + i, `Tell ${i}`, u.value.id, i % 2 === 0 ? assignee : null);
185 }
186 for (let i = pulls[0]; i < pulls[1]; i++) {
187 db.query(
188 `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state)
189 VALUES (?1, ?2, ?3, 'pull', ?4, ?5, ?6, 'open')`,
190 ).run(`${repoId}p${i}`, repoId, 1000 + i, `Pull ${i}`, `Closes #${i + 1}`, u.value.id);
191 db.query(
192 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid)
193 VALUES (?1, 'main', ?2, 'x', 'y')`,
194 ).run(`${repoId}p${i}`, `b${i}`);
195 }
196 for (let i = runs[0]; i < runs[1]; i++)
197 db.query(
198 `INSERT INTO run (id, repo_id, kind, state, issue_id) VALUES (?1, ?2, 'agent', 'running', ?3)`,
199 ).run(`${repoId}r${i}`, repoId, `${repoId}i${i * 2 + 1}`);
200 }
201 })();
202 seed([0, 10], [0, 2], [0, 1]);
203 seedElsewhere(0, 2);
204 servers = await serve(app);
205 const signin = await fetch(`${servers.url}/signin`, {
206 method: "POST",
207 headers: { origin: servers.url },
208 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
209 redirect: "manual",
210 });
211 cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
212 for (const path of PAGES) {
213 small[path] = await costOf(path);
214 }
215 fewStatements = await statementsByText(PAGES[0]!);
216 seed([10, 200], [2, 40], [1, 5]);
217 seedElsewhere(2, 30);
218 manyStatements = await statementsByText(PAGES[0]!);
219 });
220 afterEach(() => {
221 servers.stop();
222 app.close();
223 rmSync(root, { recursive: true, force: true });
224 });
225
226238 // A page may take a statement or two more once a list is long (a "more" link);
227239 // a loop adds one per row, at least 38 here.
228240 const SLACK = 3;
@@ -230,21 +242,25 @@ const SLACK = 3;
230242 // Batched reads cost the same however many rows there are: a statement per
231243 // issue, pull or run would make the 200/40/5 page cost more than the 10/2/1 one.
232244 test("now reads its rows in batches with 200 open issues, 40 open pulls and 5 active runs", async () => {
233 const path = "/alice/vault";
234 expect(Math.abs((await costOf(path)) - small[path]!)).toBeLessThanOrEqual(SLACK);
245 const h = await home("ann");
246 const small = await costOf(h.path, h.cookie);
247 h.grow();
248 expect(Math.abs((await costOf(h.path, h.cookie)) - small)).toBeLessThanOrEqual(SLACK);
235249 });
236250
237251 test("following stays cheap on a diverged fork (regression guard; this pull does not change it)", async () => {
238 const path = "/alice/vault-fork";
239 const res = await fetch(`${servers.url}${path}`, { headers: { cookie } });
252 const h = await home("fay");
253 const small = await costOf(h.forkPath, h.cookie);
254 h.grow();
255 const res = await fetch(`${servers.url}${h.forkPath}`, { headers: { cookie: h.cookie } });
240256 expect(res.headers.get("server-timing") ?? "").toContain("following");
241 expect(Math.abs((await costOf(path)) - small[path]!)).toBeLessThanOrEqual(SLACK);
257 expect(Math.abs((await costOf(h.forkPath, h.cookie)) - small)).toBeLessThanOrEqual(SLACK);
242258 });
243259
244 /** Open issues past the seeded ones, then the live shape: closed issues, edges and pillars. */
245 const growToLive = (repoId: string, author: string) =>
260 /** Open issues from number `from` on, then the live shape: closed issues, edges and pillars. */
261 const growToLive = (repoId: string, author: string, from: number) =>
246262 app.db.transaction(() => {
247 for (let i = 200; i < 280; i++)
263 for (let i = from; i < 280; i++)
248264 app.db.query(
249265 `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state)
250266 VALUES (?1, ?2, ?3, 'issue', ?4, '', ?5, 'open')`,
@@ -253,26 +269,28 @@ const growToLive = (repoId: string, author: string) =>
253269 })();
254270
255271 test("now costs the same statements on the live shape: 300 open issues, 2,000 closed, 3,500 edges, 20 pillars", async () => {
256 const repo = getRepo(app.db, "alice", "vault")!;
257 const author = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!.id;
258 growToLive(repo.id, author);
272 const h = await home("lea");
273 const small = await costOf(h.path, h.cookie);
274 h.grow();
275 growToLive(h.vault.id, h.owner.id, 200);
259276 // Counted, not timed: 2,000 closed issues and 3,500 edges cost four statements more than the small page
260277 // (measured), not one per row; a per-row read would add thousands.
261 expect(Math.abs((await costOf("/alice/vault")) - small["/alice/vault"]!)).toBeLessThanOrEqual(4);
278 expect(Math.abs((await costOf(h.path, h.cookie)) - small)).toBeLessThanOrEqual(4);
262279 });
263280
264 test("the lean deferred read says what the whole graph says, and something is deferred", () => {
265 const repo = getRepo(app.db, "alice", "vault")!;
281 test("the lean deferred read says what the whole graph says, and something is deferred", async () => {
282 // No page is read: a repository with the live shape is all it needs.
283 const owner = await account("gus");
284 const repo = await newVault(owner);
outdated

Same here: non-admin.

266285 // The live shape is what defers anything: a few issues alone defer nothing.
267 const author = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!.id;
268 growToLive(repo.id, author);
286 growToLive(repo.id, owner.id, 0);
269287 const whole = repoGraph(app.db, repo.id).deferred;
270288 expect(whole.size).toBeGreaterThan(0);
271289 expect([...deferredOf(app.db, repo)].sort()).toEqual([...whole].sort());
272290 });
273291
274292 /** Every statement the page runs, by its text, with how many times. */
275 async function statementsByText(path: string): Promise<Map<string, number>> {
293 async function statementsByText(path: string, cookie: string): Promise<Map<string, number>> {
276294 const door = app.db as unknown as { query: (sql: string) => unknown };
277295 const original = app.db.query.bind(app.db);
278296 let best: Map<string, number> | undefined;
@@ -305,7 +323,11 @@ async function statementsByText(path: string): Promise<Map<string, number>> {
305323 return best!;
306324 }
307325
308 test("every statement the home runs costs the same with 200 issues, 40 pulls and 5 runs as with a few", () => {
326 test("every statement the home runs costs the same with 200 issues, 40 pulls and 5 runs as with a few", async () => {
327 const h = await home("sam");
328 const fewStatements = await statementsByText(h.path, h.cookie);
329 h.grow();
330 const manyStatements = await statementsByText(h.path, h.cookie);
309331 const grown: string[] = [];
310332 for (const [sql, n] of manyStatements)
311333 if (n !== (fewStatements.get(sql) ?? 0)) grown.push(`${fewStatements.get(sql) ?? 0} -> ${n}: ${sql}`);

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

Keyboard shortcuts

Docs