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
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/17007-the-ten-test-files-that-cost-pull-checks → main 0 commits fork
50 files
changed +554
−326
- scripts/gate.ts
- scripts/test-budget.ts
- scripts/test-honesty-allow.json
- scripts/test-shards.ts
- scripts/unused-exports-allow.json
- src/actions/business_plan.ts
- src/actions/dependencies.ts
- src/actions/dependency_words.ts
- src/actions/forge_view.ts
- src/actions/forge_view_ttl.ts
- src/actions/pinned.ts
- src/actions/pinned_lifetime.ts
- src/actions/plan.ts
- src/actions/plan_max.ts
- src/actions/search.ts
- src/actions/search_limit.ts
- src/apps/comment_max.ts
- src/apps/pull_comment.ts
- src/apps/toolbar_comment.ts
- src/cli/commands/search.ts
- src/cloud/experiments.ts
- src/contract/openapi/routes/getApiV1Feed.ts
- src/contract/openapi/routes/getApiV1Search.ts
- src/feed/feed.ts
- src/feed/feed_limit.ts
- src/feed/last_seen.ts
- src/feed/new_count_cap.ts
- src/feed/newer_label.ts
- src/fleet/verbs.ts
- src/http/api/business_plan.ts
- src/http/view_stream.ts
- src/spawn/clients.ts
- src/spawn/door.ts
- src/spawn/reach.ts
- src/spawn/reach_default.ts
- src/spawn/served_window.ts
- src/spawn/watch_probe_default.ts
- src/web/studio/held_posts.ts
- test/engine-split-keep.test.ts
- test/engine-split.test.ts
- test/helpers/engine_split.ts
- test/helpers/preload.ts
- test/load-order.test.ts
- test/page-budget.test.ts
- test/spawn-app-links.test.ts
- test/spawn-in-process-visible.test.ts
- test/spawn-move-cell-sizes.test.ts
- test/spawn-move-cell.test.ts
- test/spawn-sealed-host.test.ts
- test/test-budget.test.ts
scripts/gate.ts +10 −1
| @@ -60,6 +60,9 @@ export const SLOW: readonly Exclusion[] = [ | ||
| 60 | 60 | { 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 }, |
| 61 | 61 | { 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 }, |
| 62 | 62 | { 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 }, | |
| 63 | 66 | { 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 }, |
| 64 | 67 | { 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 }, |
| 65 | 68 | // From the breach list closing this pull's check log at e2a5c15 (#12088): |
| @@ -142,7 +145,13 @@ export const SLOW: readonly Exclusion[] = [ | ||
| 142 | 145 | { 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 }, |
| 143 | 146 | { 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 }, |
| 144 | 147 | { 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 }, | |
| 146 | 155 | { 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 }, |
| 147 | 156 | { 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 }, |
| 148 | 157 | { 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[], | ||
| 342 | 342 | return under.length === 0 ? [] : [`test-shards: in SLOW, yet nothing over the budget this run (its line may be stale): ${under.join(", ")}`]; |
| 343 | 343 | } |
| 344 | 344 | |
| 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 | ||
| 345 | 367 | /** |
| 346 | 368 | * The slowest `n` tests and each one's share of `totalSeconds` (the summed |
| 347 | 369 | * time of every file the run timed), for the gate's closing summary. |
scripts/test-honesty-allow.json +2 −1
| @@ -163,8 +163,9 @@ | ||
| 163 | 163 | "test/egress-leak.test.ts": {"wait":1}, |
| 164 | 164 | "test/egress-metrics-route.test.ts": {"wait":1}, |
| 165 | 165 | "test/egress-totals.test.ts": {"wait":1}, |
| 166 | "test/engine-split-keep.test.ts": {"wait":4}, | |
| 166 | 167 | "test/engine-split-soak.test.ts": {"wait":1}, |
| 167 | "test/engine-split.test.ts": {"wait":7}, | |
| 168 | "test/engine-split.test.ts": {"wait":2}, | |
| 168 | 169 | "test/event-audience.test.ts": {"wait":4}, |
| 169 | 170 | "test/event-order.test.ts": {"wait":1}, |
| 170 | 171 | "test/events-run-log.test.ts": {"wait":1}, |
scripts/test-shards.ts +3 −1
| @@ -114,7 +114,7 @@ import { | ||
| 114 | 114 | import { gateFiles, gateRefusal, looksTests, presentTests, SLOW, slowRefusal } from "./gate.ts"; |
| 115 | 115 | import { findChromium } from "../src/looks/capture.ts"; |
| 116 | 116 | 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"; | |
| 118 | 118 | import { cgroupMemory, summaryLines } from "./gate-summary.ts"; |
| 119 | 119 | import { GATE_STEP_FILE, readGateStep, type Step } from "./step-times.ts"; |
| 120 | 120 | 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[] => | ||
| 1148 | 1148 | slowUnderLines(SLOW.map((entry) => entry.file), results.flatMap((r) => r.slowRan), results.flatMap((r) => r.slowOver)); |
| 1149 | 1149 | if (tier === "fast" && !timed && !junitAsked && fastRanWholeGate) |
| 1150 | 1150 | 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); | |
| 1151 | 1153 | if (record || timed) { |
| 1152 | 1154 | if (ending.code !== 0) { |
| 1153 | 1155 | console.log( |
scripts/unused-exports-allow.json +2 −2
| @@ -128,7 +128,7 @@ | ||
| 128 | 128 | "src/snapshot/drill_job.ts markerLeft", |
| 129 | 129 | "src/spawn/births.ts provideHoldForTest", |
| 130 | 130 | "src/spawn/births.ts provideMemoryForTest", |
| 131 | "src/spawn/door.ts useWatchProbeByDefault", | |
| 131 | "src/spawn/watch_probe_default.ts useWatchProbeByDefault", | |
| 132 | 132 | "src/spawn/child-apps.ts childRuntime", |
| 133 | 133 | "src/spawn/child_db.ts childDbReaders", |
| 134 | 134 | "src/spawn/clients.ts monthsSettled", |
| @@ -139,7 +139,7 @@ | ||
| 139 | 139 | "src/spawn/parent_credential.ts keepParentCredential", |
| 140 | 140 | "src/spawn/pod.ts renderPod", |
| 141 | 141 | "src/spawn/rate.ts resetAnonSpawns", |
| 142 | "src/spawn/reach.ts useReachByDefault", | |
| 142 | "src/spawn/reach_default.ts useReachByDefault", | |
| 143 | 143 | "src/spawn/usage.ts forgetSelfCpu", |
| 144 | 144 | "src/story/records.ts isKnownRecord", |
| 145 | 145 | "src/story/records.ts parseRecords", |
src/actions/business_plan.ts +2 −1
| @@ -24,7 +24,8 @@ import { transact } from "../kernel/db.ts"; | ||
| 24 | 24 | import type { User } from "../core/users.ts"; |
| 25 | 25 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 26 | 26 | 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"; | |
| 28 | 29 | |
| 29 | 30 | /** The description, in words: long enough for a business, short enough to read. */ |
| 30 | 31 | 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"; | ||
| 18 | 18 | import type { User } from "../core/users.ts"; |
| 19 | 19 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 20 | 20 | import type { AccessError } from "./access.ts"; |
| 21 | import { SELF_WAIT } from "./plan_words.ts"; | |
| 22 | 21 | 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 }; | |
| 31 | 24 | |
| 32 | 25 | function requirePlanner( |
| 33 | 26 | 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"; | ||
| 15 | 15 | import { clientLines, IDLE_LINE } from "./client_line.ts"; |
| 16 | 16 | import { crewNow } from "./crew_now.ts"; |
| 17 | 17 | import { readHealth } from "./health.ts"; |
| 18 | import { VIEW_TTL_MS } from "./forge_view_ttl.ts"; | |
| 19 | export { VIEW_TTL_MS }; | |
| 18 | 20 | |
| 19 | export const VIEW_TTL_MS = 2000; | |
| 20 | 21 | /** Most apps listed; `counts.apps` stays the true number. */ |
| 21 | 22 | export const VIEW_APPS = 200; |
| 22 | 23 |
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"; | ||
| 61 | 61 | import { oneAtATime } from "../spawn/own_code.ts"; |
| 62 | 62 | import { resumeWatches, stuckWords, watchPinned, type Seen } from "./pinned_watch.ts"; |
| 63 | 63 | 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 }; | |
| 64 | 66 | |
| 65 | 67 | /** Swapped in tests; the real forge always uses `fetch`, and asks DNS for a name's A records. */ |
| 66 | 68 | 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 | ||
| 780 | 782 | } |
| 781 | 783 | |
| 782 | 784 | 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; | |
| 786 | 785 | /** The refusal of a lifetime that is not a whole number of days in range, at every door. */ |
| 787 | 786 | export const LIFETIME_WORDS = `A lifetime is a whole number of days, 1 to ${MAX_LIFETIME_DAYS}.`; |
| 788 | 787 | 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"; | ||
| 36 | 36 | import { lookAlikes } from "./look_alike.ts"; |
| 37 | 37 | import { SELF_WAIT } from "./plan_words.ts"; |
| 38 | 38 | import { followLink } from "./pillars.ts"; |
| 39 | import { PLAN_MAX } from "./plan_max.ts"; | |
| 40 | export { PLAN_MAX }; | |
| 39 | 41 | |
| 40 | export const PLAN_MAX = 12; | |
| 41 | 42 | /** One sentence, with room. */ |
| 42 | 43 | export const WHY_MAX = 300; |
| 43 | 44 | const KEY = /^[A-Za-z][A-Za-z0-9_.-]{0,39}$/; |
src/actions/plan_max.ts added +8
src/actions/search.ts +2 −5
| @@ -41,11 +41,8 @@ import type { Repo } from "../core/repos.ts"; | ||
| 41 | 41 | import type { User } from "../core/users.ts"; |
| 42 | 42 | import { searchDocs } from "../view/docs.ts"; |
| 43 | 43 | 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 }; | |
| 49 | 46 | |
| 50 | 47 | /** |
| 51 | 48 | * 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"; | ||
| 10 | 10 | import type { User } from "../core/users.ts"; |
| 11 | 11 | import { RateLimiter } from "../core/ratelimit.ts"; |
| 12 | 12 | import { noteClock } from "../actions/app_notes.ts"; |
| 13 | import { COMMENT_MAX } from "./comment_max.ts"; | |
| 14 | export { COMMENT_MAX }; | |
| 13 | 15 | |
| 14 | 16 | /** Comments a minute one person may post from the pill, and one socket address over all people. */ |
| 15 | 17 | export const COMMENTS_PER_PERSON = 6; |
| 16 | 18 | 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; | |
| 22 | 19 | const tick = (): number => noteClock.now(); |
| 23 | 20 | const limiters = new WeakMap<App, { person: RateLimiter; source: RateLimiter }>(); |
| 24 | 21 | function limitsOf(app: App) { |
src/apps/toolbar_comment.ts +2 −2
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | |
| 10 | 10 | import { staticResponse } from "../web/asset.ts"; |
| 11 | 11 | import { sha256 } from "../kernel/hash.ts"; |
| 12 | import { COMMENT_MAX } from "./pull_comment.ts"; | |
| 12 | import { COMMENT_MAX } from "./comment_max.ts"; | |
| 13 | 13 | |
| 14 | 14 | /** What the box says when a post fails without an answer of the forge's. */ |
| 15 | 15 | export const COMMENT_FAILED = "Could not send. Your words are kept."; |
| @@ -50,7 +50,7 @@ const commentSource = `(function () { | ||
| 50 | 50 | var cf = document.createElement("form"), ct = document.createElement("textarea"), cb = document.createElement("button"), cs = document.createElement("div"); |
| 51 | 51 | cf.style.cssText = "display:flex;flex-direction:column;gap:4px"; |
| 52 | 52 | 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). | |
| 54 | 54 | ct.maxLength = ${COMMENT_MAX}; |
| 55 | 55 | ct.setAttribute("aria-label", "Comment on pull #" + k.pull); |
| 56 | 56 | 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"; | ||
| 2 | 2 | import type { Args } from "../args.ts"; |
| 3 | 3 | import { requireConfig } from "../context.ts"; |
| 4 | 4 | import { EXIT } from "../exit.ts"; |
| 5 | import { printUsage } from "../help.ts"; | |
| 6 | 5 | import { inert, type Out } from "../out.ts"; |
| 7 | 6 | import { displayWidth, pad, truncate } from "../../tui/term/width.ts"; |
| 8 | 7 | import type { Command } from "./types.ts"; |
| @@ -19,6 +18,10 @@ async function search(out: Out, args: Args): Promise<number> { | ||
| 19 | 18 | const words = args.positional.join(" ").trim(); |
| 20 | 19 | if (words === "") { |
| 21 | 20 | 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"); | |
| 22 | 25 | printUsage(out); |
| 23 | 26 | return EXIT.usage; |
| 24 | 27 | } |
src/cloud/experiments.ts +1 −1
| @@ -18,7 +18,7 @@ import { getPinned, lifetimeOf, lifetimes, listPinned, setLifetime, type Pinned | ||
| 18 | 18 | import { id as newId } from "../kernel/id.ts"; |
| 19 | 19 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 20 | 20 | import { priced, rowCents } from "./ceiling.ts"; |
| 21 | import { LIFETIME_DAYS } from "../actions/pinned.ts"; | |
| 21 | import { LIFETIME_DAYS } from "../actions/pinned_lifetime.ts"; | |
| 22 | 22 | |
| 23 | 23 | const DAY_MS = 86_400_000; |
| 24 | 24 | /** What a forge attached to an experiment is given to live: what Keep gives. */ |
src/contract/openapi/routes/getApiV1Feed.ts +1 −1
src/contract/openapi/routes/getApiV1Search.ts +1 −1
| @@ -1,4 +1,4 @@ | ||
| 1 | 1 | 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"; | |
| 3 | 3 | |
| 4 | 4 | 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"; | ||
| 23 | 23 | import { stepsOf } from "./step.ts"; |
| 24 | 24 | import { settledOf } from "./settled.ts"; |
| 25 | 25 | 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 }; | |
| 29 | 28 | |
| 30 | 29 | const CURSOR = /^(-?\d{1,6}(?:\.\d{1,6})?)\|([a-z]{2,12}:[A-Za-z0-9_.:-]{1,160})$/; |
| 31 | 30 |
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"; | ||
| 12 | 12 | import type { User } from "../core/users.ts"; |
| 13 | 13 | import { chipHides } from "./chips.ts"; |
| 14 | 14 | 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 }; | |
| 18 | 17 | |
| 19 | 18 | /** |
| 20 | 19 | * 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
src/fleet/verbs.ts +2 −1
| @@ -21,7 +21,8 @@ import { | ||
| 21 | 21 | setIssueLabels, |
| 22 | 22 | setIssueState, |
| 23 | 23 | } 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"; | |
| 25 | 26 | import { updateRepoSettings } from "../actions/repos.ts"; |
| 26 | 27 | import { cancelRepoRun, requeueRepoRun } from "../actions/runs.ts"; |
| 27 | 28 | import { isCrew } from "../core/agents.ts"; |
src/http/api/business_plan.ts +2 −4
| @@ -18,8 +18,6 @@ import type { Handler } from "../context.ts"; | ||
| 18 | 18 | import { apiError, boundedBody, json, notFound, requireScope } from "../respond.ts"; |
| 19 | 19 | import type { Router } from "../router.ts"; |
| 20 | 20 | |
| 21 | const BODY_MAX = ATLAS_BODY_MAX; | |
| 22 | ||
| 23 | 21 | export function businessPlanRoutes(router: Router<Handler>): void { |
| 24 | 22 | router.add("POST", "/api/v1/repos/:owner/:name/atlas", async (ctx) => { |
| 25 | 23 | const denied = requireScope(ctx, "rw"); |
| @@ -27,8 +25,8 @@ export function businessPlanRoutes(router: Router<Handler>): void { | ||
| 27 | 25 | const repo = loadRepo(ctx); |
| 28 | 26 | if (!repo) return notFound(); |
| 29 | 27 | // 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`); | |
| 32 | 30 | const plan = parseBusinessPlan(input.plan); |
| 33 | 31 | if (!plan.ok) return apiError(plan.error.error, 422, plan.error.message); |
| 34 | 32 | const served = checkPillar(ctx.app, repo, input.pillar); |
src/http/view_stream.ts +2 −1
| @@ -9,7 +9,8 @@ | ||
| 9 | 9 | * A stream ends with its token (revoked, expired, its person suspended) and |
| 10 | 10 | * is held at most `STREAMS_PER_TOKEN` at a time per credential. |
| 11 | 11 | */ |
| 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"; | |
| 13 | 14 | import { tokenLive } from "../core/tokens.ts"; |
| 14 | 15 | import { getUserById, isActive } from "../core/users.ts"; |
| 15 | 16 | import { heldOf } from "../perf/held.ts"; |
src/spawn/clients.ts +1 −6
| @@ -40,6 +40,7 @@ import { archiveProposal, type ArchiveProposal } from "./archive_proposal.ts"; | ||
| 40 | 40 | import { appLinkLines, type AppLinkLine } from "./app_links.ts"; |
| 41 | 41 | import { madeFromOf, type MadeFrom } from "./template_record.ts"; |
| 42 | 42 | import { NO_KEY_HELD, NO_KEY_HOST_LINE } from "../crew/no_key.ts"; |
| 43 | import { servedWindow } from "./served_window.ts"; | |
| 43 | 44 | |
| 44 | 45 | /** What a spawned forge says about itself to anyone: nothing more. */ |
| 45 | 46 | export interface ForgeState { |
| @@ -578,12 +579,6 @@ export const memoryOf = (rows: readonly Pick<ClientRow, "size">[]): number => | ||
| 578 | 579 | /** `memoryOf` the list last read; undefined before any was. */ |
| 579 | 580 | export const servedMemoryMiB = (app: App): number | undefined => heldMemory.get(app); |
| 580 | 581 | 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 }; | |
| 587 | 582 | |
| 588 | 583 | /** |
| 589 | 584 | * 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"; | ||
| 13 | 13 | import { linkRequestVisitor } from "../perf/visitor_link.ts"; |
| 14 | 14 | import { templateOfInput } from "../actions/template_timing.ts"; |
| 15 | 15 | import { startWatch, probeOf, type Probe } from "./live.ts"; |
| 16 | import { watchProbeDefault } from "./watch_probe_default.ts"; | |
| 16 | 17 | import { claimByToken, claimOf, TOKEN_SECRET_WORDS } from "./headless_claim.ts"; |
| 17 | 18 | import { firstProof, homeBudgetOf, proves, reachWords, settleChild, type ChildReach } from "./reach.ts"; |
| 18 | 19 | import { |
| @@ -93,16 +94,6 @@ export function probeFor(app: App, url: string, timeoutMs: number): Probe { | ||
| 93 | 94 | return swapped ? swapped(url) : probeOf(url, timeoutMs); |
| 94 | 95 | } |
| 95 | 96 | |
| 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 | ||
| 106 | 97 | /** Tests swap how a new child is asked whether it is live. */ |
| 107 | 98 | export function useProbe(app: App, probe: (url: string) => Probe): void { |
| 108 | 99 | probes.set(app, probe); |
| @@ -599,7 +590,7 @@ export async function spawnDoor( | ||
| 599 | 590 | let watching = false; |
| 600 | 591 | try { |
| 601 | 592 | 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 }); | |
| 603 | 594 | } finally { |
| 604 | 595 | if (!watching) place.release(); |
| 605 | 596 | } |
src/spawn/reach.ts +3 −22
| @@ -30,6 +30,7 @@ import { uncleanInFirstMinutes } from "../kernel/boots.ts"; | ||
| 30 | 30 | import { lastStop, stoppedMark } from "./stopped.ts"; |
| 31 | 31 | import { readRecord } from "./cell_record.ts"; |
| 32 | 32 | import { during } from "../perf/jobs.ts"; |
| 33 | import { reachDefault, type ReachOptions } from "./reach_default.ts"; | |
| 33 | 34 | |
| 34 | 35 | export const APP_HEADER = "x-forge-app"; |
| 35 | 36 | |
| @@ -80,20 +81,7 @@ export interface ChildReach { | ||
| 80 | 81 | } |
| 81 | 82 | |
| 82 | 83 | 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; | |
| 97 | 85 | |
| 98 | 86 | const options = new WeakMap<App, Options>(); |
| 99 | 87 | |
| @@ -102,14 +90,7 @@ export function useReach(app: App, o: Options): void { | ||
| 102 | 90 | options.set(app, o); |
| 103 | 91 | } |
| 104 | 92 | |
| 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(); | |
| 113 | 94 | /** How this forge asks a child's address: the test's fetch, else the real one. */ |
| 114 | 95 | export const fetcherOf = (app: App): FetchLike => optionsOf(app).fetch ?? fetch; |
| 115 | 96 |
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 @@ | ||
| 4 | 4 | * is the same two functions as plain JS for the page. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { NEW_COUNT_CAP } from "../../feed/last_seen.ts"; | |
| 7 | import { NEW_COUNT_CAP } from "../../feed/new_count_cap.ts"; | |
| 8 | 8 | import { newerLabelJs } from "../../feed/newer_label.ts"; |
| 9 | 9 | |
| 10 | 10 | /** 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 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | 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"; | |
| 14 | 10 | import type { ForgeEvent } from "../src/core/events.ts"; |
| 15 | import { claimRun, createRun } from "../src/core/runs.ts"; | |
| 16 | 11 | import { createUser } from "../src/core/users.ts"; |
| 17 | import { createRepo } from "../src/actions/repos.ts"; | |
| 18 | 12 | import { engineChoice } from "../src/engine/mode.ts"; |
| 19 | 13 | import { live } from "../src/tui/screens/common.ts"; |
| 20 | 14 | 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"; | |
| 24 | 16 | import { transact } from "../src/kernel/db.ts"; |
| 25 | 17 | import { quietLogs } from "./helpers/globals.ts"; |
| 18 | import { cleanEngineSplit, engines, forge, tails, until, WRITER } from "./helpers/engine_split.ts"; | |
| 26 | 19 | |
| 27 | 20 | quietLogs(); |
| 28 | 21 | |
| 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); | |
| 59 | 23 | |
| 60 | 24 | describe("the mode", () => { |
| 61 | 25 | test("is inline unless asked, and stays inline for a child, a standby and a test", () => { |
| @@ -292,182 +256,6 @@ describe("the engine thread", () => { | ||
| 292 | 256 | }, 60_000); |
| 293 | 257 | }); |
| 294 | 258 | |
| 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 | ||
| 471 | 259 | describe("the terminal's listeners are ordered too", () => { |
| 472 | 260 | test("a live screen sees both threads' events once each in seq order, and none that rolled back", async () => { |
| 473 | 261 | 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"; | ||
| 7 | 7 | import { provideCpusForTest } from "../../src/core/capacity.ts"; |
| 8 | 8 | import { provideMirrorOutboundForTest } from "../../src/origins/git-mirror.ts"; |
| 9 | 9 | 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"; | |
| 12 | 12 | import "./roomy-disk.ts"; |
| 13 | 13 | import { provideEmptyImagesForTest } from "../../src/kernel/db.ts"; |
| 14 | 14 | import { emptyImagesIn } from "./empty-images.ts"; |
| @@ -60,5 +60,5 @@ const { provideMemoryForTest } = await import("../../src/spawn/births.ts"); | ||
| 60 | 60 | provideMemoryForTest(() => 64 * 1024 ** 3); |
| 61 | 61 | |
| 62 | 62 | // 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"); | |
| 64 | 64 | 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 { | ||
| 157 | 157 | } |
| 158 | 158 | |
| 159 | 159 | /** |
| 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. | |
| 162 | 163 | */ |
| 163 | 164 | async function count(b: PageBudget): Promise<{ status: number; statements: number; phases: PageMeasure["phases"] }> { |
| 164 | 165 | const first = await fetch(url(b), init(b)); |
| 165 | 166 | await first.arrayBuffer(); |
| 166 | 167 | let status = first.status; |
| 167 | 168 | 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); | |
| 179 | 176 | return { status, statements: fewest, phases: parsePhases(header) }; |
| 180 | 177 | } |
| 181 | 178 |
test/spawn-app-links.test.ts +2 −1
| @@ -53,7 +53,8 @@ import { bootHostedChild, openChildren } from "../src/spawn/host.ts"; | ||
| 53 | 53 | import { watchLandings } from "../src/spawn/app_follow.ts"; |
| 54 | 54 | import { chmodSync } from "node:fs"; |
| 55 | 55 | import { forgetKey } from "../src/kernel/secret.ts"; |
| 56 | import { dropServed, refreshServed, servedRows, servedWindow } from "../src/spawn/clients.ts"; | |
| 56 | import { dropServed, refreshServed, servedRows } from "../src/spawn/clients.ts"; | |
| 57 | import { servedWindow } from "../src/spawn/served_window.ts"; | |
| 57 | 58 | import { anchorsOf, appLinkSummary, appLinkWords, reasonOf } from "../src/spawn/app_links.ts"; |
| 58 | 59 | import { setFollowTaking } from "../src/core/upstream_follow.ts"; |
| 59 | 60 |
test/spawn-in-process-visible.test.ts +2 −1
| @@ -22,7 +22,8 @@ import { | ||
| 22 | 22 | import { during, jobWatchOf } from "../src/perf/jobs.ts"; |
| 23 | 23 | import { liveOf } from "../src/perf/live.ts"; |
| 24 | 24 | 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"; | |
| 26 | 27 | import { closeHostedChildren, openChildren, provideCellsForTest } from "../src/spawn/host.ts"; |
| 27 | 28 | import { hostedPlacement } from "../src/spawn/placement.ts"; |
| 28 | 29 | import { |
test/spawn-move-cell-sizes.test.ts +2 −1
| @@ -14,7 +14,8 @@ import { | ||
| 14 | 14 | } from "bun:test"; |
| 15 | 15 | import { writeFileSync } from "node:fs"; |
| 16 | 16 | 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"; | |
| 18 | 19 | import { provideCellsForTest, sleepIdleChildren } from "../src/spawn/host.ts"; |
| 19 | 20 | import { moveDisk } from "../src/spawn/move_check.ts"; |
| 20 | 21 | import { |
test/spawn-move-cell.test.ts +2 −1
| @@ -20,7 +20,8 @@ import { | ||
| 20 | 20 | import { Database } from "bun:sqlite"; |
| 21 | 21 | import { readFileSync, rmSync, writeFileSync } from "node:fs"; |
| 22 | 22 | 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"; | |
| 24 | 25 | import { provideCellsForTest, sleepIdleChildren } from "../src/spawn/host.ts"; |
| 25 | 26 | import { moveDisk } from "../src/spawn/move_check.ts"; |
| 26 | 27 | import { |
test/spawn-sealed-host.test.ts +2 −1
| @@ -30,7 +30,8 @@ import { | ||
| 30 | 30 | stopCellChildren, |
| 31 | 31 | type CellChild, |
| 32 | 32 | } 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"; | |
| 34 | 35 | import { |
| 35 | 36 | bootHostedChild, |
| 36 | 37 | closeHostedChildren, |
test/test-budget.test.ts +19
| @@ -20,6 +20,7 @@ import { | ||
| 20 | 20 | retimeFiles, |
| 21 | 21 | retimeVerdict, |
| 22 | 22 | slowestTestLines, |
| 23 | slowSecondsLines, | |
| 23 | 24 | slowUnderLines, |
| 24 | 25 | TEST_BUDGET_SECONDS, |
| 25 | 26 | underLoadLines, |
| @@ -257,6 +258,24 @@ describe("slowUnderLines", () => { | ||
| 257 | 258 | }); |
| 258 | 259 | }); |
| 259 | 260 | |
| 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 | ||
| 260 | 279 | describe("slowestTestLines", () => { |
| 261 | 280 | test("the five slowest with their share of the run's work", () => { |
| 262 | 281 | const tests = [0.1, 4, 2, 1, 3, 0.5, 0.2].map((seconds, i) => ({ file: "test/a.test.ts", test: `t${i}`, seconds })); |
new above
offline