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

The ten test files that cost pull checks the most seconds each finish in under 30 s, with no test skipped #17030

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/17007-the-ten-test-files-that-cost-pull-checks → main 0 commits fork

  • Merged. torque/17007-the-ten-test-files-that-cost-pull-checks was merged into main as d1623ea.

Review

Sign in to review this change.
50 files changed +554 −326
scripts/gate.ts +10 −1
@@ -60,6 +60,9 @@ export const SLOW: readonly Exclusion[] = [
6060 { file: "test/apps-toolbar.test.ts", reason: "its opt-out test deploys a real scaffolded app twice; 2.35 s under full-suite load, 2.8 s alone here", issue: 13773 },
6161 { file: "test/following-incoming.test.ts", reason: "makes 52 real commits to pass the 50-line cap of the incoming list; 2.4 s under full-suite load, 0.5 s alone", issue: 13144 },
6262 { file: "test/release-sweep-safety-14784.test.ts", reason: "boots the real src/main.ts twice at once (proof and live control) to prove the outbox untouched; 4.1 s a test under full-suite load", issue: 14784 },
63 // A fresh module graph is what it tests: no process or fixture can be shared, and no clock is
64 // waited on (#17007).
65 { file: "test/load-order.test.ts", reason: "loads src/ first in 13 fresh processes at once; one parses 4,286 files (24 MB) in 2.4 s alone, 2.46 s under full-suite load", issue: 17007 },
6366 { file: "test/spawn-cell-looks.test.ts", reason: "boots a real child forge in a cell (~30 s) and waits for its own looks job to take a picture", issue: 10620 },
6467 { file: "test/snapshot-stream.test.ts", reason: "its service test takes a real stream pass and a real snapshot of a forge with a database, about 1 s each; 3.1 s a test under full-suite load", issue: 16977 },
6568 // From the breach list closing this pull's check log at e2a5c15 (#12088):
@@ -142,7 +145,13 @@ export const SLOW: readonly Exclusion[] = [
142145 { file: "test/drill-run.test.ts", reason: "spawns the drill script with piped stdin and waits for its JSON; 2.4 s a test on the gate box", issue: 1242 },
143146 { file: "test/drill-verdict.test.ts", reason: "boots a restored directory as a real process on a side port; 2.2 s a test on the gate box", issue: 1242 },
144147 { file: "test/engine-split-soak.test.ts", reason: "soaks 48 write-then-read round trips beside a second engine process writing flat out (1000 nightly); its engine starts in a worker; 3-5 s a test", issue: 1242 },
145 { file: "test/engine-split.test.ts", reason: "races two engine threads over the same queued runs; 3.1 s a test on the gate box", issue: 1242 },
148 // No clock is waited on (restartMinMs is already 20 ms) and no fixture can be shared: a killed or
149 // given-up engine is the state under test, so each test boots its own Worker threads (#17007).
150 { file: "test/engine-split-keep.test.ts", reason: "split from engine-split; each test boots real engine Workers (about 1.5 s a life), the give-up test three; 2.7-5.0 s a test alone", issue: 17007 },
151 // The engine host reads Date.now and setInterval, not an injected clock, and the stall limit must
152 // outlast a Worker's boot under load; judgeSilence itself is tested with a given clock in
153 // engine-stall.test.ts.
154 { file: "test/engine-split.test.ts", reason: "its stall test waits out a real 12 s stall limit; 14.5 s for that test alone, under 2.7 s each of the rest", issue: 1242 },
146155 { file: "test/flow-phone-fit.test.ts", reason: "starts a real Chromium to measure the owner flow page at phone width; 4.5 s a test on the gate box", issue: 12805 },
147156 { file: "test/forbidden-page.test.ts", reason: "posts to every form route across sites and as a non-admin; 5.4 s a test on the gate box", issue: 1242 },
148157 { file: "test/fork-pull-approval.test.ts", reason: "deploys previews of fork pulls and waits for one to be taken down; 4.2 s a test on the gate box", issue: 1242 },
scripts/test-budget.ts +22
@@ -342,6 +342,28 @@ export function slowUnderLines(slow: readonly string[], ran: readonly string[],
342342 return under.length === 0 ? [] : [`test-shards: in SLOW, yet nothing over the budget this run (its line may be stale): ${under.join(", ")}`];
343343 }
344344
345 /**
346 * The seconds each SLOW file's tests took this run, summed from the report,
347 * dearest first: a pull's log keeps only its tail, and the shards holding
348 * SLOW files run first, so this closing list is where a check's time for a
349 * SLOW file can still be read (#17007). Setup outside a test is not in it.
350 */
351 export function slowSecondsLines(slow: readonly string[], tests: readonly TestTime[]): string[] {
352 const wanted = new Set(slow);
353 const sums = new Map<string, number>();
354 for (const t of tests) {
355 const file = t.file.replace(/^\.\//, "");
356 if (t.skipped || !wanted.has(file)) continue;
357 sums.set(file, (sums.get(file) ?? 0) + t.seconds);
358 }
359 if (sums.size === 0) return [];
360 const sorted = [...sums].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
361 return [
362 `test-shards: SLOW files this run, their tests' seconds summed: ${sorted.length}`,
363 ...sorted.map(([file, seconds]) => ` ${seconds.toFixed(1).padStart(6)}s ${file}`),
364 ];
365 }
366
345367 /**
346368 * The slowest `n` tests and each one's share of `totalSeconds` (the summed
347369 * time of every file the run timed), for the gate's closing summary.
scripts/test-honesty-allow.json +2 −1
@@ -163,8 +163,9 @@
163163 "test/egress-leak.test.ts": {"wait":1},
164164 "test/egress-metrics-route.test.ts": {"wait":1},
165165 "test/egress-totals.test.ts": {"wait":1},
166 "test/engine-split-keep.test.ts": {"wait":4},
166167 "test/engine-split-soak.test.ts": {"wait":1},
167 "test/engine-split.test.ts": {"wait":7},
168 "test/engine-split.test.ts": {"wait":2},
168169 "test/event-audience.test.ts": {"wait":4},
169170 "test/event-order.test.ts": {"wait":1},
170171 "test/events-run-log.test.ts": {"wait":1},
scripts/test-shards.ts +3 −1
@@ -114,7 +114,7 @@ import {
114114 import { gateFiles, gateRefusal, looksTests, presentTests, SLOW, slowRefusal } from "./gate.ts";
115115 import { findChromium } from "../src/looks/capture.ts";
116116 import { chromiumRuns } from "../test/helpers/chrome.ts";
117 import { breaches, breachReport, budgetsFrom, retimeVerdict, breachClosing, breachWarnings, formatTestTimes, loadVerdict, retimeFiles, RETIME_SECONDS, slowUnderLines, parseJunit, slowestTestLines, underLoadLines, unverifiedLines, type AloneRun, type Breach, type TestTime, type UnderLoad, type Unverified } from "./test-budget.ts";
117 import { breaches, breachReport, budgetsFrom, retimeVerdict, breachClosing, breachWarnings, formatTestTimes, loadVerdict, retimeFiles, RETIME_SECONDS, slowSecondsLines, slowUnderLines, parseJunit, slowestTestLines, underLoadLines, unverifiedLines, type AloneRun, type Breach, type TestTime, type UnderLoad, type Unverified } from "./test-budget.ts";
118118 import { cgroupMemory, summaryLines } from "./gate-summary.ts";
119119 import { GATE_STEP_FILE, readGateStep, type Step } from "./step-times.ts";
120120 import { GATE_FILE, LOADS_ONLY, coverOf, executedFiles, formatImpact, gateListAdds, handedImpact, mergeImpact, packImpact, usedFiles, type Cover } from "../src/checks/impact.ts";
@@ -1148,6 +1148,8 @@ const slowUnder = (): string[] =>
11481148 slowUnderLines(SLOW.map((entry) => entry.file), results.flatMap((r) => r.slowRan), results.flatMap((r) => r.slowOver));
11491149 if (tier === "fast" && !timed && !junitAsked && fastRanWholeGate)
11501150 for (const line of slowUnder()) console.log(line);
1151 if (tier === "fast" && !timed && !junitAsked)
1152 for (const line of slowSecondsLines([...SLOW_FILES], results.flatMap((r) => r.tests))) console.log(line);
11511153 if (record || timed) {
11521154 if (ending.code !== 0) {
11531155 console.log(
scripts/unused-exports-allow.json +2 −2
@@ -128,7 +128,7 @@
128128 "src/snapshot/drill_job.ts markerLeft",
129129 "src/spawn/births.ts provideHoldForTest",
130130 "src/spawn/births.ts provideMemoryForTest",
131 "src/spawn/door.ts useWatchProbeByDefault",
131 "src/spawn/watch_probe_default.ts useWatchProbeByDefault",
132132 "src/spawn/child-apps.ts childRuntime",
133133 "src/spawn/child_db.ts childDbReaders",
134134 "src/spawn/clients.ts monthsSettled",
@@ -139,7 +139,7 @@
139139 "src/spawn/parent_credential.ts keepParentCredential",
140140 "src/spawn/pod.ts renderPod",
141141 "src/spawn/rate.ts resetAnonSpawns",
142 "src/spawn/reach.ts useReachByDefault",
142 "src/spawn/reach_default.ts useReachByDefault",
143143 "src/spawn/usage.ts forgetSelfCpu",
144144 "src/story/records.ts isKnownRecord",
145145 "src/story/records.ts parseRecords",
src/actions/business_plan.ts +2 −1
@@ -24,7 +24,8 @@ import { transact } from "../kernel/db.ts";
2424 import type { User } from "../core/users.ts";
2525 import { err, ok, type Result } from "../kernel/result.ts";
2626 import { MAX_DIRECTION_CHARS, MAX_FRESH_CHARS } from "../spawn/plan.ts";
27 import { openPlan, PLAN_MAX, proposePlan, type PlanItem, type Planned, type Proposed } from "./plan.ts";
27 import { PLAN_MAX } from "./plan_max.ts";
28 import { openPlan, proposePlan, type PlanItem, type Planned, type Proposed } from "./plan.ts";
2829
2930 /** The description, in words: long enough for a business, short enough to read. */
3031 export const DESCRIPTION_MAX = 4_000;
src/actions/dependencies.ts +2 −9
@@ -18,16 +18,9 @@ import { canRead, canWrite, type Repo } from "../core/repos.ts";
1818 import type { User } from "../core/users.ts";
1919 import { err, ok, type Result } from "../kernel/result.ts";
2020 import type { AccessError } from "./access.ts";
21 import { SELF_WAIT } from "./plan_words.ts";
2221 import { followLink } from "./pillars.ts";
23
24 /** What a refused link says, in the words the API and the MCP share. */
25 export const dependencyWords: Record<string, string> = {
26 self: SELF_WAIT,
27 cycle: "that would make a loop",
28 cross_repo: "dependencies stay inside one repository",
29 not_an_issue: "only issues can depend on issues",
30 };
22 import { dependencyWords } from "./dependency_words.ts";
23 export { dependencyWords };
3124
3225 function requirePlanner(
3326 app: App,
src/actions/dependency_words.ts added +15
@@ -0,0 +1,15 @@
1 /**
2 * A refused link's words, apart from `dependencies.ts`: `fleet/verbs.ts`
3 * spreads them into its table while it loads, and importing them from
4 * dependencies.ts closed a cycle that left them uninitialised when
5 * dependencies.ts was loaded first (#17007).
6 */
7 import { SELF_WAIT } from "./plan_words.ts";
8
9 /** What a refused link says, in the words the API and the MCP share. */
10 export const dependencyWords: Record<string, string> = {
11 self: SELF_WAIT,
12 cycle: "that would make a loop",
13 cross_repo: "dependencies stay inside one repository",
14 not_an_issue: "only issues can depend on issues",
15 };
src/actions/forge_view.ts +2 −1
@@ -15,8 +15,9 @@ import { appsOf } from "../web/studio/asks.ts";
1515 import { clientLines, IDLE_LINE } from "./client_line.ts";
1616 import { crewNow } from "./crew_now.ts";
1717 import { readHealth } from "./health.ts";
18 import { VIEW_TTL_MS } from "./forge_view_ttl.ts";
19 export { VIEW_TTL_MS };
1820
19 export const VIEW_TTL_MS = 2000;
2021 /** Most apps listed; `counts.apps` stays the true number. */
2122 export const VIEW_APPS = 200;
2223
src/actions/forge_view_ttl.ts added +8
@@ -0,0 +1,8 @@
1 /**
2 * How long a reader's forge view is reused, in a module that imports nothing:
3 * `http/view_stream.ts` reads it while it loads, and importing it from
4 * `forge_view.ts` closed a cycle that left it uninitialised when
5 * forge_view.ts was loaded first (#17007).
6 */
7
8 export const VIEW_TTL_MS = 2000;
src/actions/pinned.ts +2 −3
@@ -61,6 +61,8 @@ import { isStale, refreshIfDue } from "./places_refresh.ts";
6161 import { oneAtATime } from "../spawn/own_code.ts";
6262 import { resumeWatches, stuckWords, watchPinned, type Seen } from "./pinned_watch.ts";
6363 import { markStep, watchOf, type WatchTimes } from "../core/pinned_watch.ts";
64 import { LIFETIME_DAYS, MAX_LIFETIME_DAYS } from "./pinned_lifetime.ts";
65 export { LIFETIME_DAYS, MAX_LIFETIME_DAYS };
6466
6567 /** Swapped in tests; the real forge always uses `fetch`, and asks DNS for a name's A records. */
6668 export const net: { fetch: Fetch; probe: Fetch; resolve: (host: string) => Promise<string[]> } = {
@@ -780,9 +782,6 @@ async function retireNow(app: App, who: Who, name: string, o: { withData?: boole
780782 }
781783
782784 const DAY_MS = 86_400_000;
783 /** What a forge on an experiment is given, and what Keep adds (#16696). */
784 export const LIFETIME_DAYS = 7;
785 export const MAX_LIFETIME_DAYS = 90;
786785 /** The refusal of a lifetime that is not a whole number of days in range, at every door. */
787786 export const LIFETIME_WORDS = `A lifetime is a whole number of days, 1 to ${MAX_LIFETIME_DAYS}.`;
788787 const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
src/actions/pinned_lifetime.ts added +10
@@ -0,0 +1,10 @@
1 /**
2 * How long a forge on an experiment lives, in a module that imports nothing:
3 * `cloud/experiments.ts` reads it while it loads, and importing it from
4 * `pinned.ts` closed a cycle that left it uninitialised when pinned.ts (or
5 * any of a dozen modules that reach it) was loaded first (#17007).
6 */
7
8 /** What a forge on an experiment is given, and what Keep adds (#16696). */
9 export const LIFETIME_DAYS = 7;
10 export const MAX_LIFETIME_DAYS = 90;
src/actions/plan.ts +2 −1
@@ -36,8 +36,9 @@ import { isMirror } from "../origins/write-through.ts";
3636 import { lookAlikes } from "./look_alike.ts";
3737 import { SELF_WAIT } from "./plan_words.ts";
3838 import { followLink } from "./pillars.ts";
39 import { PLAN_MAX } from "./plan_max.ts";
40 export { PLAN_MAX };
3941
40 export const PLAN_MAX = 12;
4142 /** One sentence, with room. */
4243 export const WHY_MAX = 300;
4344 const KEY = /^[A-Za-z][A-Za-z0-9_.-]{0,39}$/;
src/actions/plan_max.ts added +8
@@ -0,0 +1,8 @@
1 /**
2 * The most issues one plan opens, in a module that imports nothing:
3 * `business_plan.ts` reads it while it loads, and importing it from
4 * `plan.ts` closed a cycle that left it uninitialised when plan.ts was
5 * loaded first (#17007).
6 */
7
8 export const PLAN_MAX = 12;
src/actions/search.ts +2 −5
@@ -41,11 +41,8 @@ import type { Repo } from "../core/repos.ts";
4141 import type { User } from "../core/users.ts";
4242 import { searchDocs } from "../view/docs.ts";
4343 import { providerForOrigin } from "../origins/credential.ts";
44
45 /** Default page size for each list. */
46 export const SEARCH_LIMIT = 20;
47 /** Hard ceiling on a caller-chosen limit. */
48 export const SEARCH_LIMIT_MAX = 100;
44 import { SEARCH_LIMIT, SEARCH_LIMIT_MAX } from "./search_limit.ts";
45 export { SEARCH_LIMIT, SEARCH_LIMIT_MAX };
4946
5047 /**
5148 * The refusal an API or MCP caller gets for a `kind` or `limit` the search
src/actions/search_limit.ts added +11
@@ -0,0 +1,11 @@
1 /**
2 * The search's page sizes, in a module that imports nothing: the OpenAPI
3 * route reads the ceiling, and importing it from `search.ts` closed a cycle
4 * (search → core → mcp_card → openapi → route → search) that left the
5 * constant uninitialised when search.ts was loaded first.
6 */
7
8 /** Default page size for each list. */
9 export const SEARCH_LIMIT = 20;
10 /** Hard ceiling on a caller-chosen limit. */
11 export const SEARCH_LIMIT_MAX = 100;
src/apps/comment_max.ts added +9
@@ -0,0 +1,9 @@
1 /**
2 * The longest comment the pill takes, in characters: well inside the door's 16 KB request read
3 * (`REQUEST_MAX` in feedback.ts), so a long one is named too long, never cut into "empty".
4 *
5 * A module that imports nothing: `toolbar_comment.ts` writes it into its script while it loads,
6 * and importing it from `pull_comment.ts` closed a cycle that left it uninitialised when
7 * pull_comment.ts was loaded first (#17007).
8 */
9 export const COMMENT_MAX = 4000;
src/apps/pull_comment.ts +2 −5
@@ -10,15 +10,12 @@ import type { Repo } from "../core/repos.ts";
1010 import type { User } from "../core/users.ts";
1111 import { RateLimiter } from "../core/ratelimit.ts";
1212 import { noteClock } from "../actions/app_notes.ts";
13 import { COMMENT_MAX } from "./comment_max.ts";
14 export { COMMENT_MAX };
1315
1416 /** Comments a minute one person may post from the pill, and one socket address over all people. */
1517 export const COMMENTS_PER_PERSON = 6;
1618 export const COMMENTS_PER_SOURCE = 20;
17 /**
18 * The longest comment the pill takes, in characters: well inside the door's 16 KB request read
19 * (`REQUEST_MAX` in feedback.ts), so a long one is named too long, never cut into "empty".
20 */
21 export const COMMENT_MAX = 4000;
2219 const tick = (): number => noteClock.now();
2320 const limiters = new WeakMap<App, { person: RateLimiter; source: RateLimiter }>();
2421 function limitsOf(app: App) {
src/apps/toolbar_comment.ts +2 −2
@@ -9,7 +9,7 @@
99
1010 import { staticResponse } from "../web/asset.ts";
1111 import { sha256 } from "../kernel/hash.ts";
12 import { COMMENT_MAX } from "./pull_comment.ts";
12 import { COMMENT_MAX } from "./comment_max.ts";
1313
1414 /** What the box says when a post fails without an answer of the forge's. */
1515 export const COMMENT_FAILED = "Could not send. Your words are kept.";
@@ -50,7 +50,7 @@ const commentSource = `(function () {
5050 var cf = document.createElement("form"), ct = document.createElement("textarea"), cb = document.createElement("button"), cs = document.createElement("div");
5151 cf.style.cssText = "display:flex;flex-direction:column;gap:4px";
5252 ct.rows = 2;
53 // The door's own limit (COMMENT_MAX in src/apps/pull_comment.ts).
53 // The door's own limit (COMMENT_MAX in src/apps/comment_max.ts).
5454 ct.maxLength = ${COMMENT_MAX};
5555 ct.setAttribute("aria-label", "Comment on pull #" + k.pull);
5656 ct.style.cssText = "font:inherit;box-sizing:border-box;width:100%;resize:vertical;min-height:44px";
src/cli/commands/search.ts +4 −1
@@ -2,7 +2,6 @@ import { ForgeApi } from "../api.ts";
22 import type { Args } from "../args.ts";
33 import { requireConfig } from "../context.ts";
44 import { EXIT } from "../exit.ts";
5 import { printUsage } from "../help.ts";
65 import { inert, type Out } from "../out.ts";
76 import { displayWidth, pad, truncate } from "../../tui/term/width.ts";
87 import type { Command } from "./types.ts";
@@ -19,6 +18,10 @@ async function search(out: Out, args: Args): Promise<number> {
1918 const words = args.positional.join(" ").trim();
2019 if (words === "") {
2120 out.err("forge search: what for? e.g. forge search retry budget");
21 // Loaded here, not at the top: help.ts lists every command, this one
22 // too, so a static import is a cycle that met `search` uninitialised
23 // when this file was loaded first (#17007).
24 const { printUsage } = await import("../help.ts");
2225 printUsage(out);
2326 return EXIT.usage;
2427 }
src/cloud/experiments.ts +1 −1
@@ -18,7 +18,7 @@ import { getPinned, lifetimeOf, lifetimes, listPinned, setLifetime, type Pinned
1818 import { id as newId } from "../kernel/id.ts";
1919 import { err, ok, type Result } from "../kernel/result.ts";
2020 import { priced, rowCents } from "./ceiling.ts";
21 import { LIFETIME_DAYS } from "../actions/pinned.ts";
21 import { LIFETIME_DAYS } from "../actions/pinned_lifetime.ts";
2222
2323 const DAY_MS = 86_400_000;
2424 /** What a forge attached to an experiment is given to live: what Keep gives. */
src/contract/openapi/routes/getApiV1Feed.ts +1 −1
@@ -1,5 +1,5 @@
11 import { type Route, limitTo } from "../shared.ts";
2 import { FEED_LIMIT_MAX } from "../../../feed/feed.ts";
2 import { FEED_LIMIT_MAX } from "../../../feed/feed_limit.ts";
33
44 export const route: Route = {
55 method: "get",
src/contract/openapi/routes/getApiV1Search.ts +1 −1
@@ -1,4 +1,4 @@
11 import { type Route, limitTo } from "../shared.ts";
2 import { SEARCH_LIMIT_MAX } from "../../../actions/search.ts";
2 import { SEARCH_LIMIT_MAX } from "../../../actions/search_limit.ts";
33
44 export const route: Route = { method: "get", path: "/api/v1/search", summary: "Search guides, issues, pulls, repositories and code; `kind` narrows it", auth: false, role: "anonymous", query: { q: "string", kind: "string", limit: limitTo(SEARCH_LIMIT_MAX) }, refusals: { invalid_kind: "kind is not all, repos, issues, pulls or code (422)", invalid_limit: "limit is not a whole number from 1 to 100 (422)" }, reply: { repos: "array", issues: "array", code: "array", docs: "array of { title, path, snippet }, at most 5, guides matching; only for kind all", truncated: "object", moreCode: "boolean", codeSkipped: "boolean", note: "string, only when q is blank: what to send" } };
src/feed/feed.ts +2 −3
@@ -23,9 +23,8 @@ import { likersOf, likesOf, type LikedItem } from "./likes.ts";
2323 import { stepsOf } from "./step.ts";
2424 import { settledOf } from "./settled.ts";
2525 import { repliesOf } from "./replies.ts";
26
27 export const FEED_LIMIT_DEFAULT = 20;
28 export const FEED_LIMIT_MAX = 50;
26 import { FEED_LIMIT_DEFAULT, FEED_LIMIT_MAX } from "./feed_limit.ts";
27 export { FEED_LIMIT_DEFAULT, FEED_LIMIT_MAX };
2928
3029 const CURSOR = /^(-?\d{1,6}(?:\.\d{1,6})?)\|([a-z]{2,12}:[A-Za-z0-9_.:-]{1,160})$/;
3130
src/feed/feed_limit.ts added +9
@@ -0,0 +1,9 @@
1 /**
2 * The feed's page sizes, in a module that imports nothing: the OpenAPI route
3 * reads the ceiling while it loads, and importing it from `feed.ts` closed a
4 * cycle (feed → … → openapi → route → feed) that left it uninitialised when
5 * feed.ts was loaded first (#17007).
6 */
7
8 export const FEED_LIMIT_DEFAULT = 20;
9 export const FEED_LIMIT_MAX = 50;
src/feed/last_seen.ts +2 −3
@@ -12,9 +12,8 @@ import { dismissedItems, mutedRepos } from "../core/interactions.ts";
1212 import type { User } from "../core/users.ts";
1313 import { chipHides } from "./chips.ts";
1414 import { viewerCandidates } from "./feed.ts";
15
16 /** Counted up to here; more is "99+", so the read never walks a long absence. */
17 export const NEW_COUNT_CAP = 99;
15 import { NEW_COUNT_CAP } from "./new_count_cap.ts";
16 export { NEW_COUNT_CAP };
1817
1918 /**
2019 * How long a count stands when no event has been written: what no event sees (a grant, a watch).
src/feed/new_count_cap.ts added +9
@@ -0,0 +1,9 @@
1 /**
2 * Where counting new posts stops, in a module that imports nothing: the
3 * label scripts splice it in while they load, and importing it from
4 * `last_seen.ts` closed a cycle that left it uninitialised when last_seen.ts
5 * was loaded first (#17007).
6 */
7
8 /** Counted up to here; more is "99+", so the read never walks a long absence. */
9 export const NEW_COUNT_CAP = 99;
src/feed/newer_label.ts +1 −1
@@ -4,7 +4,7 @@
44 * function as plain JS for the page's poll.
55 */
66
7 import { NEW_COUNT_CAP } from "./last_seen.ts";
7 import { NEW_COUNT_CAP } from "./new_count_cap.ts";
88
99 export function newerLabel(n: number): string {
1010 if (!(n >= 1)) return "";
src/fleet/verbs.ts +2 −1
@@ -21,7 +21,8 @@ import {
2121 setIssueLabels,
2222 setIssueState,
2323 } from "../actions/issues.ts";
24 import { linkIssue, unlinkIssue, dependencyWords } from "../actions/dependencies.ts";
24 import { linkIssue, unlinkIssue } from "../actions/dependencies.ts";
25 import { dependencyWords } from "../actions/dependency_words.ts";
2526 import { updateRepoSettings } from "../actions/repos.ts";
2627 import { cancelRepoRun, requeueRepoRun } from "../actions/runs.ts";
2728 import { isCrew } from "../core/agents.ts";
src/http/api/business_plan.ts +2 −4
@@ -18,8 +18,6 @@ import type { Handler } from "../context.ts";
1818 import { apiError, boundedBody, json, notFound, requireScope } from "../respond.ts";
1919 import type { Router } from "../router.ts";
2020
21 const BODY_MAX = ATLAS_BODY_MAX;
22
2321 export function businessPlanRoutes(router: Router<Handler>): void {
2422 router.add("POST", "/api/v1/repos/:owner/:name/atlas", async (ctx) => {
2523 const denied = requireScope(ctx, "rw");
@@ -27,8 +25,8 @@ export function businessPlanRoutes(router: Router<Handler>): void {
2725 const repo = loadRepo(ctx);
2826 if (!repo) return notFound();
2927 // The bytes read are what is counted: a chunked body has no length to claim.
30 const input = await boundedBody(ctx.request, BODY_MAX);
31 if (input === "too_large") return apiError("too_large", 413, `a plan is at most ${BODY_MAX} bytes`);
28 const input = await boundedBody(ctx.request, ATLAS_BODY_MAX);
29 if (input === "too_large") return apiError("too_large", 413, `a plan is at most ${ATLAS_BODY_MAX} bytes`);
3230 const plan = parseBusinessPlan(input.plan);
3331 if (!plan.ok) return apiError(plan.error.error, 422, plan.error.message);
3432 const served = checkPillar(ctx.app, repo, input.pillar);
src/http/view_stream.ts +2 −1
@@ -9,7 +9,8 @@
99 * A stream ends with its token (revoked, expired, its person suspended) and
1010 * is held at most `STREAMS_PER_TOKEN` at a time per credential.
1111 */
12 import { forgeViewText, VIEW_TTL_MS } from "../actions/forge_view.ts";
12 import { forgeViewText } from "../actions/forge_view.ts";
13 import { VIEW_TTL_MS } from "../actions/forge_view_ttl.ts";
1314 import { tokenLive } from "../core/tokens.ts";
1415 import { getUserById, isActive } from "../core/users.ts";
1516 import { heldOf } from "../perf/held.ts";
src/spawn/clients.ts +1 −6
@@ -40,6 +40,7 @@ import { archiveProposal, type ArchiveProposal } from "./archive_proposal.ts";
4040 import { appLinkLines, type AppLinkLine } from "./app_links.ts";
4141 import { madeFromOf, type MadeFrom } from "./template_record.ts";
4242 import { NO_KEY_HELD, NO_KEY_HOST_LINE } from "../crew/no_key.ts";
43 import { servedWindow } from "./served_window.ts";
4344
4445 /** What a spawned forge says about itself to anyone: nothing more. */
4546 export interface ForgeState {
@@ -578,12 +579,6 @@ export const memoryOf = (rows: readonly Pick<ClientRow, "size">[]): number =>
578579 /** `memoryOf` the list last read; undefined before any was. */
579580 export const servedMemoryMiB = (app: App): number | undefined => heldMemory.get(app);
580581 const building = new WeakMap<App, Promise<ClientRow[]>>();
581 /**
582 * The list a page serves is looked at again in the background when it is older than `ms`. At 0
583 * (the suite's setting) a read waits for a fresh one: a test changes a forge and reads the list at
584 * once.
585 */
586 export const servedWindow = { ms: 15_000 };
587582
588583 /**
589584 * Read every row now, off the request: what `servedRows` answers from. One at a time; a caller
src/spawn/door.ts +2 −11
@@ -13,6 +13,7 @@ import { nameShapeVerdict } from "./name_verdict.ts";
1313 import { linkRequestVisitor } from "../perf/visitor_link.ts";
1414 import { templateOfInput } from "../actions/template_timing.ts";
1515 import { startWatch, probeOf, type Probe } from "./live.ts";
16 import { watchProbeDefault } from "./watch_probe_default.ts";
1617 import { claimByToken, claimOf, TOKEN_SECRET_WORDS } from "./headless_claim.ts";
1718 import { firstProof, homeBudgetOf, proves, reachWords, settleChild, type ChildReach } from "./reach.ts";
1819 import {
@@ -93,16 +94,6 @@ export function probeFor(app: App, url: string, timeoutMs: number): Probe {
9394 return swapped ? swapped(url) : probeOf(url, timeoutMs);
9495 }
9596
96 let watchProbe: (url: string) => Probe = probeOf;
97 /**
98 * Tests: how a new child is asked whether it is live, for every forge, unless `useProbe` gave one.
99 * The suite's children answer nowhere, so each would keep its place among the births for the whole
100 * cap; `test/helpers/preload.ts` has them answer at once.
101 */
102 export function useWatchProbeByDefault(probe: ((url: string) => Probe) | undefined): void {
103 watchProbe = probe ?? probeOf;
104 }
105
10697 /** Tests swap how a new child is asked whether it is live. */
10798 export function useProbe(app: App, probe: (url: string) => Probe): void {
10899 probes.set(app, probe);
@@ -599,7 +590,7 @@ export async function spawnDoor(
599590 let watching = false;
600591 try {
601592 up = bootHostedChild(ctx.app, made.value.name);
602 watching = startWatch(ctx.app, { name: made.value.name, startedAt, ...templateOfInput(raw["template"]), probe: (probes.get(ctx.app) ?? watchProbe)(made.value.url), ...(drilling ? { drill: true } : {}), onSettled: place.release });
593 watching = startWatch(ctx.app, { name: made.value.name, startedAt, ...templateOfInput(raw["template"]), probe: (probes.get(ctx.app) ?? watchProbeDefault() ?? probeOf)(made.value.url), ...(drilling ? { drill: true } : {}), onSettled: place.release });
603594 } finally {
604595 if (!watching) place.release();
605596 }
src/spawn/reach.ts +3 −22
@@ -30,6 +30,7 @@ import { uncleanInFirstMinutes } from "../kernel/boots.ts";
3030 import { lastStop, stoppedMark } from "./stopped.ts";
3131 import { readRecord } from "./cell_record.ts";
3232 import { during } from "../perf/jobs.ts";
33 import { reachDefault, type ReachOptions } from "./reach_default.ts";
3334
3435 export const APP_HEADER = "x-forge-app";
3536
@@ -80,20 +81,7 @@ export interface ChildReach {
8081 }
8182
8283 type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
83
84 interface Options {
85 /**
86 * True where there is no public network to prove through (a test suite); an injected `fetch`
87 * still works.
88 */
89 readonly off?: boolean;
90 readonly fetch?: FetchLike;
91 readonly settleMs?: number;
92 /** How long a spawn waits for the new home to answer before it replies. */
93 readonly homeWaitMs?: number;
94 readonly pollMs?: number;
95 readonly confirmMs?: number;
96 }
84 type Options = ReachOptions;
9785
9886 const options = new WeakMap<App, Options>();
9987
@@ -102,14 +90,7 @@ export function useReach(app: App, o: Options): void {
10290 options.set(app, o);
10391 }
10492
105 let fallback: Options = {};
106
107 /** What every app without its own `useReach` does; the test preload turns proving off. */
108 export function useReachByDefault(o: Options): void {
109 fallback = o;
110 }
111
112 const optionsOf = (app: App): Options => options.get(app) ?? fallback;
93 const optionsOf = (app: App): Options => options.get(app) ?? reachDefault();
11394 /** How this forge asks a child's address: the test's fetch, else the real one. */
11495 export const fetcherOf = (app: App): FetchLike => optionsOf(app).fetch ?? fetch;
11596
src/spawn/reach_default.ts added +32
@@ -0,0 +1,32 @@
1 /**
2 * How a forge proves its children's public addresses when no `useReach` was given for it: the
3 * default `reach.ts` falls back to. A leaf on purpose (#17007): the test preload sets it for every
4 * test process, and `reach.ts` reaches the whole forge through `actions/spawn.ts`, which cost each
5 * `bun test` 2.5 s before its first test.
6 */
7
8 type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
9
10 export interface ReachOptions {
11 /**
12 * True where there is no public network to prove through (a test suite); an injected `fetch`
13 * still works.
14 */
15 readonly off?: boolean;
16 readonly fetch?: FetchLike;
17 readonly settleMs?: number;
18 /** How long a spawn waits for the new home to answer before it replies. */
19 readonly homeWaitMs?: number;
20 readonly pollMs?: number;
21 readonly confirmMs?: number;
22 }
23
24 let fallback: ReachOptions = {};
25
26 /** What every app without its own `useReach` does; the test preload turns proving off. */
27 export function useReachByDefault(o: ReachOptions): void {
28 fallback = o;
29 }
30
31 /** The default `useReachByDefault` last set: `{}` until it is called. */
32 export const reachDefault = (): ReachOptions => fallback;
src/spawn/served_window.ts added +10
@@ -0,0 +1,10 @@
1 /**
2 * How old the served list of child forges (`clients.ts`) may grow before a read looks again. A
3 * leaf on purpose (#17007): the test preload sets it for every test process, and `clients.ts`
4 * reaches the whole forge, which cost each `bun test` 2.5 s before its first test.
5 *
6 * The list a page serves is looked at again in the background when it is older than `ms`. At 0
7 * (the suite's setting) a read waits for a fresh one: a test changes a forge and reads the list at
8 * once.
9 */
10 export const servedWindow = { ms: 15_000 };
src/spawn/watch_probe_default.ts added +20
@@ -0,0 +1,20 @@
1 /**
2 * How a new child is asked whether it is live, for every forge `useProbe` gave none (`door.ts`).
3 * A leaf on purpose (#17007): the test preload sets it for every test process, and `door.ts`
4 * reaches the whole forge, which cost each `bun test` 1.7 s before its first test.
5 */
6 import type { Probe } from "./live.ts";
7
8 let watchProbe: ((url: string) => Probe) | undefined;
9
10 /**
11 * Tests: how a new child is asked whether it is live, for every forge, unless `useProbe` gave one.
12 * The suite's children answer nowhere, so each would keep its place among the births for the whole
13 * cap; `test/helpers/preload.ts` has them answer at once. `undefined` is `/healthz` again.
14 */
15 export function useWatchProbeByDefault(probe: ((url: string) => Probe) | undefined): void {
16 watchProbe = probe;
17 }
18
19 /** The probe `useWatchProbeByDefault` last set, or undefined for the real one. */
20 export const watchProbeDefault = (): ((url: string) => Probe) | undefined => watchProbe;
src/web/studio/held_posts.ts +1 −1
@@ -4,7 +4,7 @@
44 * is the same two functions as plain JS for the page.
55 */
66
7 import { NEW_COUNT_CAP } from "../../feed/last_seen.ts";
7 import { NEW_COUNT_CAP } from "../../feed/new_count_cap.ts";
88 import { newerLabelJs } from "../../feed/newer_label.ts";
99
1010 /** The ids in `fresh` not in `shown`, in `fresh`'s order, each once. */
test/engine-split-keep.test.ts added +197
@@ -0,0 +1,197 @@
1 /**
2 * The engine on a thread of its own, continued from test/engine-split.test.ts (split for time,
3 * #17007): an engine that cannot be kept is given up, a run is started once whoever asks, and a
4 * stream that resumes while the engine writes joins replay and live without a seam.
5 */
6
7 import { afterEach, describe, expect, test } from "bun:test";
8 import { tailEvents } from "../src/core/event_tail.ts";
9 import { claimRun, createRun } from "../src/core/runs.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { startEngine } from "../src/engine/host.ts";
14 import { runSplit, tuneForSplit } from "../src/engine/run.ts";
15 import { transact } from "../src/kernel/db.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17 import { cleanEngineSplit, engines, forge, tails, until, WRITER } from "./helpers/engine_split.ts";
18
19 quietLogs();
20
21 afterEach(cleanEngineSplit);
22
23 describe("an engine that cannot be kept", () => {
24 test("refusing to start its duties every life, it is given up after a few deaths and the serving thread takes the duties back", async () => {
25 const serve = await forge();
26 const tail = tailEvents(serve.db, serve.bus);
27 tails.push(tail);
28 const loneWriter = tuneForSplit(serve.db);
29 expect(serve.db.query<{ wal_autocheckpoint: number }, []>("PRAGMA wal_autocheckpoint").get()?.wal_autocheckpoint).toBe(0);
30 process.env["ENGINE_TEST"] = "refuse";
31 const chose = { mode: "worker" as const, why: "FORGE_ENGINE=worker is set" };
32 const split = runSplit(serve, chose, tail, loneWriter, { extra: [WRITER], restartMinMs: 20, giveUpDeaths: 3 });
33 engines.push(split.engine!);
34 try {
35 await until(() => split.fellBack() !== undefined, 30_000);
36 expect(split.fellBack()).toMatch(/^died 3 times in \d+ s \(the last: Error: the engine refuses to start\)$/);
37 expect(split.engine!.gaveUp()).toBe(split.fellBack());
38 expect(split.engine!.restarts()).toBe(2);
39 expect(serve.config.engine).toMatchObject({ mode: "inline", fellBack: split.fellBack()! });
40 expect(serve.db.query<{ wal_autocheckpoint: number }, []>("PRAGMA wal_autocheckpoint").get()?.wal_autocheckpoint).toBe(1000);
41 // No fourth engine comes, and nobody waits on one.
42 await split.engine!.ready();
43 await Bun.sleep(300); // real-timer: a restart, were one still coming, is a real timer of the host's
44 expect(split.engine!.restarts()).toBe(2);
45 // Serving went on throughout.
46 const made = serve.bus.append({ kind: "serve.probe", payload: {} });
47 expect(serve.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM event WHERE id = ?1").get(made.id)?.n).toBe(1);
48 } finally {
49 split.stop();
50 }
51 }, 60_000);
52
53 test("one death is not given up on: the engine comes back, as before", async () => {
54 const serve = await forge();
55 const tail = tailEvents(serve.db, serve.bus);
56 tails.push(tail);
57 process.env["ENGINE_TEST"] = "idle";
58 const chose = { mode: "worker" as const, why: "FORGE_ENGINE=worker is set" };
59 const split = runSplit(serve, chose, tail, tuneForSplit(serve.db), { extra: [WRITER], restartMinMs: 20 });
60 engines.push(split.engine!);
61 try {
62 await split.engine!.ready();
63 split.engine!.kill();
64 await until(() => split.engine!.restarts() === 1);
65 await split.engine!.ready();
66 expect(split.fellBack()).toBeUndefined();
67 expect(serve.config.engine).toBeUndefined();
68 } finally {
69 split.stop();
70 }
71 }, 30_000);
72 });
73
74 describe("a run is started once", () => {
75 test("two threads asking for the same queued runs: each run has exactly one taker", async () => {
76 const serve = await forge();
77 const tail = tailEvents(serve.db, serve.bus);
78 tails.push(tail);
79 const made = await createUser(serve.db, {
80 origin: "seed",
81 trusted: true,
82 username: "alice",
83 email: "[email protected]",
84 password: "a-good-passphrase",
85 adminIfFirst: true,
86 });
87 if (!made.ok) throw new Error(String(made.error));
88 const repo = await createRepo(serve, made.value, {
89 name: "r",
90 visibility: "public",
91 });
92 if (!repo.ok) throw new Error(String(repo.error));
93 const ids: string[] = [];
94 transact(serve.db, () => {
95 for (let i = 0; i < 3000; i++)
96 ids.push(
97 createRun(serve.db, {
98 repoId: repo.value.id,
99 kind: "check",
100 commitOid: `c${i}`,
101 }).id,
102 );
103 });
104 process.env["ENGINE_TEST"] = "claimer";
105 const engine = startEngine(serve.config, tail, { extra: [WRITER] });
106 engines.push(engine);
107 // This thread takes its first few before the engine is up (it may be quicker than this thread
108 // once it is), then they compete.
109 let mine = 0;
110 for (const id of ids.slice(0, 300)) if (claimRun(serve.db, id) !== undefined) mine++;
111 await engine.ready();
112 for (const id of ids) {
113 if (claimRun(serve.db, id) !== undefined) mine++;
114 if (mine % 10 === 0) await Bun.sleep(0); // real-timer: a yield, so the engine thread's claims interleave with these
115 }
116 // The engine counts a claim in a statement of its own, just after the claim: wait for the books
117 // to close.
118 const theirsNow = (): number =>
119 serve.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM engine_scratch WHERE n = -1").get()?.n ?? 0;
120 await until(() => mine + theirsNow() >= 3000);
121 await Bun.sleep(200); // real-timer: no event says no more claims are coming; a late one would show here
122 const theirs = theirsNow();
123 expect(mine + theirs).toBe(3000);
124 expect(serve.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM run WHERE state = 'running'").get()?.n).toBe(3000);
125 expect(mine).toBeGreaterThan(0);
126 expect(theirs).toBeGreaterThan(0);
127 }, 60_000);
128 });
129
130 describe("a stream that resumes while the engine writes", () => {
131 test("sees every event after its cursor once, in the outbox's order, replay and live joined without a seam", async () => {
132 const serve_ = await forge();
133 const servers: Servers = await serve(serve_);
134 try {
135 const tail = tailEvents(serve_.db, serve_.bus);
136 tails.push(tail);
137 const made = await createUser(serve_.db, { origin: "seed", trusted: true, isAdmin: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
138 if (!made.ok) throw new Error(String(made.error));
139 const repo = await createRepo(serve_, made.value, { name: "r", visibility: "public" });
140 if (!repo.ok) throw new Error(String(repo.error));
141 process.env["ENGINE_TEST"] = "writer";
142 process.env["ENGINE_TEST_REPO"] = repo.value.id;
143 process.env["ENGINE_TEST_KIND"] = "issue.labeled";
144 process.env["ENGINE_TEST_EVERY_MS"] = "1";
145 const engine = startEngine(serve_.config, tail, { extra: [WRITER] });
146 engines.push(engine);
147 await engine.ready();
148 const kindsOf = (): { id: string; seq: number }[] =>
149 serve_.db.query<{ id: string; seq: number }, [string]>("SELECT id, seq FROM event WHERE repo_id = ?1 AND kind = 'issue.labeled' ORDER BY seq").all(repo.value.id);
150 await until(() => kindsOf().length >= 150);
151 const cursor = kindsOf()[40]!;
152 for (let round = 0; round < 5; round++) {
153 const controller = new AbortController();
154 const res = await fetch(`${servers.url}/events`, { headers: { "last-event-id": cursor.id }, signal: controller.signal });
155 const got: string[] = [];
156 const reader = res.body!.getReader();
157 const decoder = new TextDecoder();
158 let buffer = "";
159 const stop = Date.now() + 400;
160 // One read in flight at a time: a read the timeout outran still holds the next chunk, and a
161 // fresh read() in its place would drop it.
162 let pending: ReturnType<typeof reader.read> | undefined;
163 while (Date.now() < stop) {
164 pending ??= reader.read();
165 const chunk = await Promise.race([pending, Bun.sleep(100).then(() => undefined)]); // real-timer: read timeout on a live HTTP stream
166 if (chunk === undefined) continue;
167 pending = undefined;
168 if (chunk.done) break;
169 buffer += decoder.decode(chunk.value, { stream: true });
170 let cut: number;
171 while ((cut = buffer.indexOf("\n\n")) >= 0) {
172 const id = /^id: (.+)$/m.exec(buffer.slice(0, cut))?.[1];
173 if (id !== undefined) got.push(id);
174 buffer = buffer.slice(cut + 2);
175 }
176 }
177 controller.abort();
178 const seqOf = new Map(kindsOf().map((e) => [e.id, e.seq]));
179 // Once each...
180 expect(new Set(got).size).toBe(got.length);
181 // ...in the outbox's order...
182 const seqs = got.map((id) => seqOf.get(id)!);
183 for (let i = 1; i < seqs.length; i++) expect(seqs[i]).toBeGreaterThan(seqs[i - 1]!);
184 // ...and none missing between its first and its last frame (the replay is the newest 200
185 // after the cursor).
186 const first = seqs[0]!;
187 const last = seqs[seqs.length - 1]!;
188 expect(got).toEqual(kindsOf().filter((e) => e.seq >= first && e.seq <= last).map((e) => e.id));
189 expect(got.length).toBeGreaterThan(10);
190 }
191 } finally {
192 delete process.env["ENGINE_TEST_KIND"];
193 delete process.env["ENGINE_TEST_EVERY_MS"];
194 servers.stop();
195 }
196 }, 60_000);
197 });
test/engine-split.test.ts +4 −216
@@ -6,56 +6,20 @@
66 */
77
88 import { afterEach, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { tailEvents, type EventTail } from "../src/core/event_tail.ts";
9 import { tailEvents } from "../src/core/event_tail.ts";
1410 import type { ForgeEvent } from "../src/core/events.ts";
15 import { claimRun, createRun } from "../src/core/runs.ts";
1611 import { createUser } from "../src/core/users.ts";
17 import { createRepo } from "../src/actions/repos.ts";
1812 import { engineChoice } from "../src/engine/mode.ts";
1913 import { live } from "../src/tui/screens/common.ts";
2014 import { endOnSuspension } from "../src/tui/ssh.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { startEngine, type Engine } from "../src/engine/host.ts";
23 import { runSplit, tuneForSplit } from "../src/engine/run.ts";
15 import { startEngine } from "../src/engine/host.ts";
2416 import { transact } from "../src/kernel/db.ts";
2517 import { quietLogs } from "./helpers/globals.ts";
18 import { cleanEngineSplit, engines, forge, tails, until, WRITER } from "./helpers/engine_split.ts";
2619
2720 quietLogs();
2821
29 const WRITER = new URL("./helpers/engine_writer.ts", import.meta.url).href;
30 const dirs: string[] = [];
31 const apps: App[] = [];
32 const tails: EventTail[] = [];
33 const engines: Engine[] = [];
34
35 afterEach(async () => {
36 for (const e of engines.splice(0)) await e.stop();
37 for (const t of tails.splice(0)) t.stop();
38 for (const a of apps.splice(0)) a.close();
39 for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true });
40 delete process.env["ENGINE_TEST"];
41 delete process.env["ENGINE_TEST_REPO"];
42 });
43
44 async function forge(dir?: string): Promise<App> {
45 const dataDir = dir ?? (await mkdtemp(join(tmpdir(), "forge-engine-")));
46 if (dir === undefined) dirs.push(dataDir);
47 const app = createApp({ dataDir, port: 0 });
48 apps.push(app);
49 return app;
50 }
51
52 const until = async (ok: () => boolean, ms = 10_000): Promise<void> => {
53 const end = Date.now() + ms;
54 while (!ok()) {
55 if (Date.now() > end) throw new Error("timed out");
56 await Bun.sleep(5);
57 }
58 };
22 afterEach(cleanEngineSplit);
5923
6024 describe("the mode", () => {
6125 test("is inline unless asked, and stays inline for a child, a standby and a test", () => {
@@ -292,182 +256,6 @@ describe("the engine thread", () => {
292256 }, 60_000);
293257 });
294258
295 describe("an engine that cannot be kept", () => {
296 test("refusing to start its duties every life, it is given up after a few deaths and the serving thread takes the duties back", async () => {
297 const serve = await forge();
298 const tail = tailEvents(serve.db, serve.bus);
299 tails.push(tail);
300 const loneWriter = tuneForSplit(serve.db);
301 expect(serve.db.query<{ wal_autocheckpoint: number }, []>("PRAGMA wal_autocheckpoint").get()?.wal_autocheckpoint).toBe(0);
302 process.env["ENGINE_TEST"] = "refuse";
303 const chose = { mode: "worker" as const, why: "FORGE_ENGINE=worker is set" };
304 const split = runSplit(serve, chose, tail, loneWriter, { extra: [WRITER], restartMinMs: 20, giveUpDeaths: 3 });
305 engines.push(split.engine!);
306 try {
307 await until(() => split.fellBack() !== undefined, 30_000);
308 expect(split.fellBack()).toMatch(/^died 3 times in \d+ s \(the last: Error: the engine refuses to start\)$/);
309 expect(split.engine!.gaveUp()).toBe(split.fellBack());
310 expect(split.engine!.restarts()).toBe(2);
311 expect(serve.config.engine).toMatchObject({ mode: "inline", fellBack: split.fellBack()! });
312 expect(serve.db.query<{ wal_autocheckpoint: number }, []>("PRAGMA wal_autocheckpoint").get()?.wal_autocheckpoint).toBe(1000);
313 // No fourth engine comes, and nobody waits on one.
314 await split.engine!.ready();
315 await Bun.sleep(300); // real-timer: a restart, were one still coming, is a real timer of the host's
316 expect(split.engine!.restarts()).toBe(2);
317 // Serving went on throughout.
318 const made = serve.bus.append({ kind: "serve.probe", payload: {} });
319 expect(serve.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM event WHERE id = ?1").get(made.id)?.n).toBe(1);
320 } finally {
321 split.stop();
322 }
323 }, 60_000);
324
325 test("one death is not given up on: the engine comes back, as before", async () => {
326 const serve = await forge();
327 const tail = tailEvents(serve.db, serve.bus);
328 tails.push(tail);
329 process.env["ENGINE_TEST"] = "idle";
330 const chose = { mode: "worker" as const, why: "FORGE_ENGINE=worker is set" };
331 const split = runSplit(serve, chose, tail, tuneForSplit(serve.db), { extra: [WRITER], restartMinMs: 20 });
332 engines.push(split.engine!);
333 try {
334 await split.engine!.ready();
335 split.engine!.kill();
336 await until(() => split.engine!.restarts() === 1);
337 await split.engine!.ready();
338 expect(split.fellBack()).toBeUndefined();
339 expect(serve.config.engine).toBeUndefined();
340 } finally {
341 split.stop();
342 }
343 }, 30_000);
344 });
345
346 describe("a run is started once", () => {
347 test("two threads asking for the same queued runs: each run has exactly one taker", async () => {
348 const serve = await forge();
349 const tail = tailEvents(serve.db, serve.bus);
350 tails.push(tail);
351 const made = await createUser(serve.db, {
352 origin: "seed",
353 trusted: true,
354 username: "alice",
355 email: "[email protected]",
356 password: "a-good-passphrase",
357 adminIfFirst: true,
358 });
359 if (!made.ok) throw new Error(String(made.error));
360 const repo = await createRepo(serve, made.value, {
361 name: "r",
362 visibility: "public",
363 });
364 if (!repo.ok) throw new Error(String(repo.error));
365 const ids: string[] = [];
366 transact(serve.db, () => {
367 for (let i = 0; i < 3000; i++)
368 ids.push(
369 createRun(serve.db, {
370 repoId: repo.value.id,
371 kind: "check",
372 commitOid: `c${i}`,
373 }).id,
374 );
375 });
376 process.env["ENGINE_TEST"] = "claimer";
377 const engine = startEngine(serve.config, tail, { extra: [WRITER] });
378 engines.push(engine);
379 // This thread takes its first few before the engine is up (it may be quicker than this thread
380 // once it is), then they compete.
381 let mine = 0;
382 for (const id of ids.slice(0, 300)) if (claimRun(serve.db, id) !== undefined) mine++;
383 await engine.ready();
384 for (const id of ids) {
385 if (claimRun(serve.db, id) !== undefined) mine++;
386 if (mine % 10 === 0) await Bun.sleep(0);
387 }
388 // The engine counts a claim in a statement of its own, just after the claim: wait for the books
389 // to close.
390 const theirsNow = (): number =>
391 serve.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM engine_scratch WHERE n = -1").get()?.n ?? 0;
392 await until(() => mine + theirsNow() >= 3000);
393 await Bun.sleep(200);
394 const theirs = theirsNow();
395 expect(mine + theirs).toBe(3000);
396 expect(serve.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM run WHERE state = 'running'").get()?.n).toBe(3000);
397 expect(mine).toBeGreaterThan(0);
398 expect(theirs).toBeGreaterThan(0);
399 }, 60_000);
400 });
401
402 describe("a stream that resumes while the engine writes", () => {
403 test("sees every event after its cursor once, in the outbox's order, replay and live joined without a seam", async () => {
404 const serve_ = await forge();
405 const servers: Servers = await serve(serve_);
406 try {
407 const tail = tailEvents(serve_.db, serve_.bus);
408 tails.push(tail);
409 const made = await createUser(serve_.db, { origin: "seed", trusted: true, isAdmin: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
410 if (!made.ok) throw new Error(String(made.error));
411 const repo = await createRepo(serve_, made.value, { name: "r", visibility: "public" });
412 if (!repo.ok) throw new Error(String(repo.error));
413 process.env["ENGINE_TEST"] = "writer";
414 process.env["ENGINE_TEST_REPO"] = repo.value.id;
415 process.env["ENGINE_TEST_KIND"] = "issue.labeled";
416 process.env["ENGINE_TEST_EVERY_MS"] = "1";
417 const engine = startEngine(serve_.config, tail, { extra: [WRITER] });
418 engines.push(engine);
419 await engine.ready();
420 const kindsOf = (): { id: string; seq: number }[] =>
421 serve_.db.query<{ id: string; seq: number }, [string]>("SELECT id, seq FROM event WHERE repo_id = ?1 AND kind = 'issue.labeled' ORDER BY seq").all(repo.value.id);
422 await until(() => kindsOf().length >= 150);
423 const cursor = kindsOf()[40]!;
424 for (let round = 0; round < 5; round++) {
425 const controller = new AbortController();
426 const res = await fetch(`${servers.url}/events`, { headers: { "last-event-id": cursor.id }, signal: controller.signal });
427 const got: string[] = [];
428 const reader = res.body!.getReader();
429 const decoder = new TextDecoder();
430 let buffer = "";
431 const stop = Date.now() + 400;
432 // One read in flight at a time: a read the timeout outran still holds the next chunk, and a
433 // fresh read() in its place would drop it.
434 let pending: ReturnType<typeof reader.read> | undefined;
435 while (Date.now() < stop) {
436 pending ??= reader.read();
437 const chunk = await Promise.race([pending, Bun.sleep(100).then(() => undefined)]); // real-timer: read timeout on a live HTTP stream
438 if (chunk === undefined) continue;
439 pending = undefined;
440 if (chunk.done) break;
441 buffer += decoder.decode(chunk.value, { stream: true });
442 let cut: number;
443 while ((cut = buffer.indexOf("\n\n")) >= 0) {
444 const id = /^id: (.+)$/m.exec(buffer.slice(0, cut))?.[1];
445 if (id !== undefined) got.push(id);
446 buffer = buffer.slice(cut + 2);
447 }
448 }
449 controller.abort();
450 const seqOf = new Map(kindsOf().map((e) => [e.id, e.seq]));
451 // Once each...
452 expect(new Set(got).size).toBe(got.length);
453 // ...in the outbox's order...
454 const seqs = got.map((id) => seqOf.get(id)!);
455 for (let i = 1; i < seqs.length; i++) expect(seqs[i]).toBeGreaterThan(seqs[i - 1]!);
456 // ...and none missing between its first and its last frame (the replay is the newest 200
457 // after the cursor).
458 const first = seqs[0]!;
459 const last = seqs[seqs.length - 1]!;
460 expect(got).toEqual(kindsOf().filter((e) => e.seq >= first && e.seq <= last).map((e) => e.id));
461 expect(got.length).toBeGreaterThan(10);
462 }
463 } finally {
464 delete process.env["ENGINE_TEST_KIND"];
465 delete process.env["ENGINE_TEST_EVERY_MS"];
466 servers.stop();
467 }
468 }, 60_000);
469 });
470
471259 describe("the terminal's listeners are ordered too", () => {
472260 test("a live screen sees both threads' events once each in seq order, and none that rolled back", async () => {
473261 const a = await forge();
test/helpers/engine_split.ts added +43
@@ -0,0 +1,43 @@
1 /**
2 * What test/engine-split.test.ts and test/engine-split-keep.test.ts share (#17007: one file was
3 * 45 s alone): a forge in a fresh directory, the engine writer seam, a poll that ends, and the
4 * cleanup each test's leftovers need. Call `cleanEngineSplit` in each file's `afterEach`.
5 */
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../../src/app.ts";
10 import type { EventTail } from "../../src/core/event_tail.ts";
11 import type { Engine } from "../../src/engine/host.ts";
12 import { waitFor } from "./poll.ts";
13
14 /** The engine thread's test duties (`engine_writer.ts`), by `ENGINE_TEST`. */
15 export const WRITER = new URL("./engine_writer.ts", import.meta.url).href;
16 const dirs: string[] = [];
17 const apps: App[] = [];
18 export const tails: EventTail[] = [];
19 export const engines: Engine[] = [];
20
21 /** Stops what a test started, in the order it depends on, and forgets its seams. */
22 export async function cleanEngineSplit(): Promise<void> {
23 for (const e of engines.splice(0)) await e.stop();
24 for (const t of tails.splice(0)) t.stop();
25 for (const a of apps.splice(0)) a.close();
26 for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true });
27 delete process.env["ENGINE_TEST"];
28 delete process.env["ENGINE_TEST_REPO"];
29 }
30
31 /** A forge in `dir`, or in a fresh directory removed after the test. */
32 export async function forge(dir?: string): Promise<App> {
33 const dataDir = dir ?? (await mkdtemp(join(tmpdir(), "forge-engine-")));
34 if (dir === undefined) dirs.push(dataDir);
35 const app = createApp({ dataDir, port: 0 });
36 apps.push(app);
37 return app;
38 }
39
40 /** Polls `ok` every 5 ms (`waitFor`) until it holds; throws "timed out" after `ms`. */
41 export const until = async (ok: () => boolean, ms = 10_000): Promise<void> => {
42 if (!(await waitFor(ok, { every: 5, within: ms }))) throw new Error("timed out");
43 };
test/helpers/preload.ts +3 −3
@@ -7,8 +7,8 @@ import "../../src/kernel/bun_guard.ts";
77 import { provideCpusForTest } from "../../src/core/capacity.ts";
88 import { provideMirrorOutboundForTest } from "../../src/origins/git-mirror.ts";
99 import { installCheapHash } from "./cheap-hash.ts";
10 import { useReachByDefault } from "../../src/spawn/reach.ts";
11 import { servedWindow } from "../../src/spawn/clients.ts";
10 import { useReachByDefault } from "../../src/spawn/reach_default.ts";
11 import { servedWindow } from "../../src/spawn/served_window.ts";
1212 import "./roomy-disk.ts";
1313 import { provideEmptyImagesForTest } from "../../src/kernel/db.ts";
1414 import { emptyImagesIn } from "./empty-images.ts";
@@ -60,5 +60,5 @@ const { provideMemoryForTest } = await import("../../src/spawn/births.ts");
6060 provideMemoryForTest(() => 64 * 1024 ** 3);
6161
6262 // A new child of the suite answers its first look, so its place among the births is given back.
63 const { useWatchProbeByDefault } = await import("../../src/spawn/door.ts");
63 const { useWatchProbeByDefault } = await import("../../src/spawn/watch_probe_default.ts");
6464 useWatchProbeByDefault(() => async () => true);
test/load-order.test.ts added +47
@@ -0,0 +1,47 @@
1 /**
2 * Most of src/ is one import cycle. A module in it that reads another's constant
3 * while it loads throws "Cannot access X before initialization" when the test
4 * file (or the shard before it) happens to enter the cycle at the wrong place.
5 * The old test preload loaded a big part of the graph first, which hid this;
6 * since it stopped (#17007), each of these entry points threw in some shard.
7 *
8 * Each one is loaded first, in its own process, under the suite's preload.
9 */
10 import { expect, test } from "bun:test";
11 import { join } from "node:path";
12
13 const ROOT = join(import.meta.dir, "..");
14
15 /** Each was a first import that met a constant uninitialised, and the constant. */
16 const ENTRIES: readonly (readonly [string, string])[] = [
17 ["src/actions/search.ts", "SEARCH_LIMIT_MAX"],
18 ["src/actions/pinned.ts", "LIFETIME_DAYS"],
19 ["src/feed/feed.ts", "FEED_LIMIT_MAX"],
20 ["src/contract/openapi.ts", "ROUTES"],
21 ["src/actions/dependencies.ts", "dependencyWords"],
22 ["src/actions/forge_view.ts", "VIEW_TTL_MS"],
23 ["src/actions/plan.ts", "PLAN_MAX"],
24 ["src/actions/business_plan.ts", "ATLAS_BODY_MAX"],
25 ["src/apps/pull_comment.ts", "COMMENT_MAX"],
26 ["src/apps/toolbar_comment.ts", "COMMENT_ASSET_PATH"],
27 ["src/cli/commands/search.ts", "search"],
28 ["src/feed/last_seen.ts", "NEW_COUNT_CAP"],
29 ["src/feed/newer_label.ts", "newerLabelJs"],
30 ];
31
32 async function loadFirst(path: string): Promise<string> {
33 const child = Bun.spawn(
34 [process.execPath, "--preload", "./test/helpers/preload.ts", "-e", `await import(${JSON.stringify(`./${path}`)}); process.exit(0)`],
35 { cwd: ROOT, stdin: "ignore", stdout: "ignore", stderr: "pipe" },
36 );
37 const [err, code] = await Promise.all([new Response(child.stderr).text(), child.exited]);
38 if (code === 0) return "";
39 const tdz = /Cannot access '(\w+)' before initialization/.exec(err);
40 return `${path}: ${tdz ? `${tdz[1]} uninitialised` : `exit ${code}: ${err.trim().split("\n").slice(-1)[0] ?? ""}`}`;
41 }
42
43 test("each module that once met a constant uninitialised loads first, alone, without error", async () => {
44 // In parallel: each process loads most of src/, about 1.7 s.
45 const refused = (await Promise.all(ENTRIES.map(([path]) => loadFirst(path)))).filter((line) => line !== "");
46 expect(refused).toEqual([]);
47 }, 60_000);
test/page-budget.test.ts +10 −13
@@ -157,25 +157,22 @@ function url(b: PageBudget): string {
157157 }
158158
159159 /**
160 * One request warms; then the fewest statements of `COUNTED` warm requests is the count, so a
161 * background tick's queries do not land on a page.
160 * One request warms; then the fewest statements of `COUNTED` warm requests, each from rest, is
161 * the count, so a background tick's queries do not land on a page. `statements` already keeps the
162 * fewest of its runs: calling it once with `COUNTED` is the five requests, not five times five.
162163 */
163164 async function count(b: PageBudget): Promise<{ status: number; statements: number; phases: PageMeasure["phases"] }> {
164165 const first = await fetch(url(b), init(b));
165166 await first.arrayBuffer();
166167 let status = first.status;
167168 let header = "";
168 let fewest = Number.POSITIVE_INFINITY;
169 for (let i = 0; i < COUNTED; i++) {
170 const n = await statements(app.db, async () => {
171 const res = await fetch(url(b), init(b));
172 await res.arrayBuffer();
173 status = res.status;
174 header = res.headers.get("server-timing") ?? "";
175 });
176 fewest = Math.min(fewest, n);
177 if (status !== 200) break;
178 }
169 const fewest = await statements(app.db, async () => {
170 if (status !== 200) return;
171 const res = await fetch(url(b), init(b));
172 await res.arrayBuffer();
173 status = res.status;
174 header = res.headers.get("server-timing") ?? "";
175 }, COUNTED);
179176 return { status, statements: fewest, phases: parsePhases(header) };
180177 }
181178
test/spawn-in-process-visible.test.ts +2 −1
@@ -22,7 +22,8 @@ import {
2222 import { during, jobWatchOf } from "../src/perf/jobs.ts";
2323 import { liveOf } from "../src/perf/live.ts";
2424 import { stallLine } from "../src/perf/loop.ts";
25 import { clientRows, servedWindow } from "../src/spawn/clients.ts";
25 import { clientRows } from "../src/spawn/clients.ts";
26 import { servedWindow } from "../src/spawn/served_window.ts";
2627 import { closeHostedChildren, openChildren, provideCellsForTest } from "../src/spawn/host.ts";
2728 import { hostedPlacement } from "../src/spawn/placement.ts";
2829 import {
test/spawn-move-cell-sizes.test.ts +2 −1
@@ -14,7 +14,8 @@ import {
1414 } from "bun:test";
1515 import { writeFileSync } from "node:fs";
1616 import { join } from "node:path";
17 import { servedWindow, clientRows } from "../src/spawn/clients.ts";
17 import { clientRows } from "../src/spawn/clients.ts";
18 import { servedWindow } from "../src/spawn/served_window.ts";
1819 import { provideCellsForTest, sleepIdleChildren } from "../src/spawn/host.ts";
1920 import { moveDisk } from "../src/spawn/move_check.ts";
2021 import {
test/spawn-move-cell.test.ts +2 −1
@@ -20,7 +20,8 @@ import {
2020 import { Database } from "bun:sqlite";
2121 import { readFileSync, rmSync, writeFileSync } from "node:fs";
2222 import { join } from "node:path";
23 import { servedWindow, clientRows } from "../src/spawn/clients.ts";
23 import { clientRows } from "../src/spawn/clients.ts";
24 import { servedWindow } from "../src/spawn/served_window.ts";
2425 import { provideCellsForTest, sleepIdleChildren } from "../src/spawn/host.ts";
2526 import { moveDisk } from "../src/spawn/move_check.ts";
2627 import {
test/spawn-sealed-host.test.ts +2 −1
@@ -30,7 +30,8 @@ import {
3030 stopCellChildren,
3131 type CellChild,
3232 } from "../src/spawn/cell.ts";
33 import { clientRows, servedWindow } from "../src/spawn/clients.ts";
33 import { clientRows } from "../src/spawn/clients.ts";
34 import { servedWindow } from "../src/spawn/served_window.ts";
3435 import {
3536 bootHostedChild,
3637 closeHostedChildren,
test/test-budget.test.ts +19
@@ -20,6 +20,7 @@ import {
2020 retimeFiles,
2121 retimeVerdict,
2222 slowestTestLines,
23 slowSecondsLines,
2324 slowUnderLines,
2425 TEST_BUDGET_SECONDS,
2526 underLoadLines,
@@ -257,6 +258,24 @@ describe("slowUnderLines", () => {
257258 });
258259 });
259260
261 describe("slowSecondsLines", () => {
262 test("each SLOW file that ran, its tests' seconds summed, dearest first; skipped tests and other files left out (#17007)", () => {
263 const tests = [
264 { file: "./test/a.test.ts", test: "one", seconds: 1.25 },
265 { file: "test/a.test.ts", test: "two", seconds: 2.5 },
266 { file: "test/a.test.ts", test: "gone", seconds: 9, skipped: true as const },
267 { file: "test/b.test.ts", test: "t", seconds: 12 },
268 { file: "test/c.test.ts", test: "t", seconds: 40 },
269 ];
270 expect(slowSecondsLines(["test/a.test.ts", "test/b.test.ts", "test/d.test.ts"], tests)).toEqual([
271 "test-shards: SLOW files this run, their tests' seconds summed: 2",
272 " 12.0s test/b.test.ts",
273 " 3.8s test/a.test.ts",
274 ]);
275 expect(slowSecondsLines(["test/d.test.ts"], tests)).toEqual([]);
276 });
277 });
278
260279 describe("slowestTestLines", () => {
261280 test("the five slowest with their share of the run's work", () => {
262281 const tests = [0.1, 4, 2, 1, 3, 0.5, 0.2].map((seconds, i) => ({ file: "test/a.test.ts", test: `t${i}`, seconds }));

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

Keyboard shortcuts

Docs