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

A spark finding on the games page links to the slow tick it came from #18241

opened this

Its check is red, 2h 4m ago

check failed: gate: rule "the diff is the change": test/tui-games.test.ts:458 only rewraps a comment this pull did not write; restore the lines, and keep the diff to the change (`bun scripts/gate.ts --fix` rewraps…

torque/forge:torque/18213-a-spark-finding-on-the-games-page-links → main 6 commits fork

Review

Sign in to review this change.
8 files changed +155 −4
docs/features/game-spark.md +4
@@ -15,3 +15,7 @@ Installing spark (`mods_install spark`, or as a plugin of a new server) writes s
1515 ## The call tree and flame graph (#18208)
1616
1717 A listed profile opens `/games/<box>/spark/<key>` (the bytes stay at `/games/<box>/@spark/<key>`): `decodeSparkProfile` reads it per request, and each thread shows its time sampled (milliseconds), a flame graph (an SVG drawn on the server, no script; a box is as wide as its share of the thread, the call and time in its tooltip) and the call tree as text with shares. The terminal shows the same lines: on a box's Profiles screen (`p`), `j`/`k` pick a profile and Enter opens `src/tui/screens/game_spark_view.ts`. Only the 10 heaviest threads are drawn, on both doors; the rest are named as "N more threads not drawn, download the profile". Only a grant on the box reads it; a body that is not a profile says why and links the download. The tree is the decoder's pruned one: 12 deep, 8 wide, at most 2,000 nodes a thread, from a body of at most 8 MiB (64 MiB unpacked). Under the threads, both doors show (#18140, `summarySections`) the slowest tick windows, time per mod, GC and memory, and the mods listed. Not done: a finding that links to a slow frame; a flame box is not zoomable. Code: `src/games/spark_view.ts` (layout), `src/web/pages/games_spark_view.ts`.
18
19 ## A finding links to its slow tick (#18213)
20
21 When a box's newest sampler profile has a slowest tick over 50 ms (one tick's budget at 20 TPS), the Profiles block of `/games/<box>` says so in one line ("Tick time reached 62.5 ms at its slowest…") and links it to `/games/<box>/spark/<key>#tick-<window>`; the slowest-ticks row of that page has the matching `id="tick-<window>"`. The key is read from the box's own stored profiles, never from a request, so another box's profile is never linked; a box with no slow profile has no line. The terminal's Profiles screen (`p`) shows the same sentence with the profile key and row. Decoded once per profile per forge. Code: `src/games/spark_finding.ts`.
src/games/spark_finding.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * A finding from a stored spark profile (#18213): the box's newest sampler profile whose slowest
3 * tick passed the 50 ms a server has to finish one (20 TPS), said once, with the profile's key and
4 * the tick window it came from, so the box page links the line to that row of the profile page
5 * (`/games/<box>/spark/<key>#tick-<window>`). A box with no readable profile, or none that slow,
6 * has no such finding. Only a profile the box itself holds is linked: the key comes from
7 * `profilesOf`, never from a request.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { profileOf, profilesOf } from "./spark.ts";
12 import { READ_UNPACKED, decodeSparkProfile, type SparkSummary } from "./spark_profile.ts";
13 import { millis, tickAnchor } from "./spark_view.ts";
14
15 /** One tick's budget in milliseconds: 1000 ms / 20 ticks a second (Minecraft's own tick rate). */
16 export const TICK_BUDGET_MS = 50;
17
18 export interface SparkFinding {
19 readonly says: string;
20 /** The stored profile's key, one of the box's own. */
21 readonly key: string;
22 /** The slowest tick's window, the anchor's number. */
23 readonly window: number;
24 }
25
26 /** Where the finding points: the profile page, on the row of its tick. */
27 export const findingHref = (box: string, f: SparkFinding): string => `/games/${box}/spark/${f.key}#${tickAnchor(f.window)}`;
28
29 /** What the summary says when its slowest tick is over budget (pure). */
30 export function sparkSays(s: SparkSummary): { says: string; window: number } | undefined {
31 const t = s.slowestTicks[0];
32 if (t === undefined || t.msptMax <= TICK_BUDGET_MS) return undefined;
33 const mod = s.perMod[0];
34 const says = `Tick time reached ${millis(t.msptMax)} at its slowest (budget ${String(TICK_BUDGET_MS)} ms, window ${String(t.window)}, ${t.tps.toFixed(1)} TPS)${mod === undefined ? "" : `; most time attributed to ${mod.source}, ${(mod.share * 100).toFixed(0)}%`}.`;
35 return { says, window: t.window };
36 }
37
38 // Profiles never change under their key, so each is decoded once per forge (keyed by its database,
39 // #12569: no process-wide state), at most this many.
40 const SEEN = 64;
41 const seenBy = new WeakMap<Database, Map<string, { says: string; window: number } | null>>();
42
43 /** The box's spark findings: at most one, from its newest sampler profile. */
44 export function sparkFindingsOf(db: Database, boxId: string): SparkFinding[] {
45 const newest = profilesOf(db, boxId).find((p) => p.type === "application/x-spark-sampler");
46 if (newest === undefined) return [];
47 const id = `${boxId}/${newest.key}`;
48 const seen = seenBy.get(db) ?? new Map<string, { says: string; window: number } | null>();
49 seenBy.set(db, seen);
50 let got = seen.get(id);
51 if (got === undefined) {
52 const stored = profileOf(db, boxId, newest.key);
53 const read = stored === undefined ? undefined : decodeSparkProfile(stored.body, READ_UNPACKED);
54 got = read !== undefined && read.ok ? (sparkSays(read.summary) ?? null) : null;
55 if (seen.size >= SEEN) seen.delete(seen.keys().next().value as string);
56 seen.set(id, got);
57 }
58 return got === null ? [] : [{ ...got, key: newest.key }];
59 }
src/games/spark_view.ts +5 −2
@@ -82,8 +82,11 @@ export function sparkHeadLines(s: SparkSummary): string[] {
8282 ];
8383 }
8484
85 /** The anchor of a slow tick's row on the profile page (#18213), which a finding links to. */
86 export const tickAnchor = (window: number): string => `tick-${String(window)}`;
87
8588 export interface SparkFact { readonly label: string; readonly value: string }
86 export interface SparkRow { readonly title: string; readonly facts: readonly SparkFact[] }
89 export interface SparkRow { readonly id?: string; readonly title: string; readonly facts: readonly SparkFact[] }
8790 export interface SparkSection { readonly id: string; readonly title: string; readonly rows: readonly SparkRow[]; readonly empty: string }
8891
8992 const mib = (bytes: number): string => `${String(Math.round(bytes / 1048576))} MiB`;
@@ -99,7 +102,7 @@ export function summarySections(s: SparkSummary): SparkSection[] {
99102 return [
100103 {
101104 id: "ticks", title: "Slowest ticks", empty: "The profile recorded no tick windows.",
102 rows: s.slowestTicks.map((t, i) => ({ title: `Window ${String(i + 1)}`, facts: [
105 rows: s.slowestTicks.map((t) => ({ id: tickAnchor(t.window), title: `Window ${String(t.window)}`, facts: [
103106 { label: "Worst tick", value: `${String(t.msptMax)} ms` }, { label: "Median", value: `${String(t.msptMedian)} ms` },
104107 { label: "TPS", value: String(t.tps) }, { label: "Ticks", value: String(t.ticks) }, { label: "Players", value: String(t.players) },
105108 ] })),
src/tui/screens/game_spark.ts +3
@@ -7,6 +7,8 @@
77 */
88
99 import { publicOrigin } from "../../core/public_origin.ts";
10 import { sparkFindingsOf } from "../../games/spark_finding.ts";
11 import { tickAnchor } from "../../games/spark_view.ts";
1012 import { SPARK_WORDS, newSparkSecret, profilesOf, sparkBase } from "../../games/spark.ts";
1113 import { mayDo, roleOn, type GameBox } from "../../games/store.ts";
1214 import type { Ctx, Screen } from "../app/app.ts";
@@ -24,6 +26,7 @@ export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
2426 return [
2527 ...wrap(SPARK_WORDS, w),
2628 "",
29 ...sparkFindingsOf(f.app.db, box.id).flatMap((x) => [...wrap(`${x.says} Profile ${x.key}, row ${tickAnchor(x.window)}.`, w), ""]),
2730 ...(address === "" ? [] : [`bytebin-url: ${address}`, "This is the only time it is shown.", ""]),
2831 ...(stored.length === 0 ? ["None stored yet."] : stored.map((p, i) => `${i === at ? ">" : " "} ${p.at.slice(0, 16).replace("T", " ")} ${p.type.replace("application/x-spark-", "spark ")} ${String(Math.ceil(p.size / 1024))} KiB ${p.key}`)),
2932 ];
src/web/pages/games.ts +2
@@ -13,6 +13,7 @@ import { verdictsOf } from "../../games/set_verdict.ts";
1313 import { offered, SETS, SET_PREFIX } from "../../games/mod_sets.ts";
1414 import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf, type Mods, type Plan } from "../../games/mods.ts";
1515 import { search, searchPacks, type Hit, type Result } from "../../games/modrinth.ts";
16 import { findingHref, sparkFindingsOf } from "../../games/spark_finding.ts";
1617 import { SPARK_WORDS, hasSparkSecret, profilesOf } from "../../games/spark.ts";
1718 import { packRow } from "../../games/client_pack.ts";
1819 import { packCheckLines } from "../../games/pack_check.ts";
@@ -509,6 +510,7 @@ function sparkBlock(ctx: Ctx, box: GameBox, owner: boolean): Html {
509510 return html`<section class="settings-block" id="spark">
510511 <h2>Profiles</h2>
511512 <p class="muted small">${SPARK_WORDS}</p>
513 ${sparkFindingsOf(ctx.app.db, box.id).map((f) => html`<p><a href="${findingHref(box.name, f)}">${f.says}</a></p>`)}
512514 ${stored.length === 0
513515 ? html`<p class="muted small">None stored yet.</p>`
514516 : rowList(stored.map((p) => row({ href: `/games/${box.name}/spark/${p.key}`, title: p.type.replace("application/x-spark-", "spark "), meta: html`${p.at.slice(0, 16).replace("T", " ")} · ${Math.ceil(p.size / 1024)} KiB` })))}
src/web/pages/games_spark_view.ts +1 −1
@@ -55,7 +55,7 @@ export function gameSparkView(ctx: Ctx): Response {
5555 <details ${i === 0 ? html`open` : null}><summary>Call tree</summary><pre>${treeLines(t.tree, t.ms).join("\n")}</pre></details>`}
5656 </section>`)}
5757 ${shown?.note ? html`<p class="muted small">${shown.note} <a href="${href}">Download it</a>.</p>` : null}
58 ${summarySections(read.summary).map((x) => html`<section class="settings-block" id="${x.id}"><h2>${x.title}</h2>${x.rows.length === 0 ? html`<p class="muted small">${x.empty}</p>` : rowList(x.rows.map((r) => row({ title: r.title, facts: r.facts })))}</section>`)}`;
58 ${summarySections(read.summary).map((x) => html`<section class="settings-block" id="${x.id}"><h2>${x.title}</h2>${x.rows.length === 0 ? html`<p class="muted small">${x.empty}</p>` : rowList(x.rows.map((r) => row({ ...(r.id === undefined ? {} : { id: r.id }), title: r.title, facts: r.facts })))}</section>`)}`;
5959 return page({
6060 ctx,
6161 title: `Games · ${got.box.name} · profile`,
test/games-spark-finding.test.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * A spark finding on the box page links to the slow tick it came from (#18213): the link and the
3 * profile page's row anchor are the one string, only the box's own profile is linked, and a box
4 * with no slow profile has no such line. Numbers are checked by hand: 62.5 ms against a 50 ms
5 * budget is over; 40 ms is not.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { gzipSync } from "node:zlib";
12 import { createApp, type App } from "../src/app.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createUser, getUserByName } from "../src/core/users.ts";
15 import { keepProfile } from "../src/games/spark.ts";
16 import { findingHref, sparkFindingsOf } from "../src/games/spark_finding.ts";
17 import { tickAnchor } from "../src/games/spark_view.ts";
18 import { createGameBox, boxNamed } from "../src/games/store.ts";
19 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21
22 quietLogs();
23
24 const varint = (n: number): number[] => { const o: number[] = []; while (n > 127) { o.push((n % 128) | 128); n = Math.floor(n / 128); } o.push(n); return o; };
25 const key = (n: number, t: number) => varint(n * 8 + t);
26 const bytes = (n: number, b: number[]) => [...key(n, 2), ...varint(b.length), ...b];
27 const dbl = (v: number) => [...new Uint8Array(new Float64Array([v]).buffer)];
28 // One window's statistics: ticks (1), tps (4), median (5), max (6), players (7), keyed by window.
29 const win = (w: number, max: number) => bytes(7, [...key(1, 0), ...varint(w), ...bytes(2, [...key(1, 0), ...varint(100), ...key(4, 1), ...dbl(18.5), ...key(5, 1), ...dbl(30), ...key(6, 1), ...dbl(max), ...key(7, 0), ...varint(3)])]);
30 const profile = (maxes: [number, number][]): Uint8Array => gzipSync(Uint8Array.from(maxes.flatMap(([w, m]) => win(w, m))));
31
32 let dir: string;
33 let app: App;
34 let http: ForgeHttp;
35 let slow: string;
36 const get = (path: string) => http.handle(new Request(`http://forge.test${path}`, { headers: { cookie: `forge_session=${createSession(app.db, getUserByName(app.db, "alice")!.id).token}` } }));
37
38 beforeAll(async () => {
39 dir = await mkdtemp(join(tmpdir(), "forge-spark-finding-"));
40 app = createApp({ dataDir: dir, port: 0 });
41 http = forgeHttp(app);
42 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
43 if (!made.ok) throw new Error(made.error);
44 createGameBox(app.db, { name: "net", repo: "alice/mc-network", path: "net/docker-compose.yml" });
45 createGameBox(app.db, { name: "calm", repo: "alice/mc-calm", path: "calm/docker-compose.yml" });
46 const keep = (box: string, b: Uint8Array) => { const k = keepProfile(app.db, boxNamed(app.db, box)!.id, "application/x-spark-sampler", b); if (!k.ok) throw new Error(k.error); return k.value; };
47 slow = keep("net", profile([[9, 40], [3, 62.5]]));
48 keep("calm", profile([[4, 40]]));
49 });
50 afterAll(async () => { await rm(dir, { recursive: true, force: true }); });
51
52 test("the slowest window over budget becomes a finding carrying the key and window", () => {
53 const f = sparkFindingsOf(app.db, boxNamed(app.db, "net")!.id);
54 expect(f.length).toBe(1);
55 expect(f[0]!.key).toBe(slow);
56 expect(f[0]!.window).toBe(3);
57 expect(f[0]!.says).toContain("62.5 ms");
58 expect(findingHref("net", f[0]!)).toBe(`/games/net/spark/${slow}#tick-3`);
59 });
60
61 test("a box whose ticks are within budget has no spark finding", () => {
62 expect(sparkFindingsOf(app.db, boxNamed(app.db, "calm")!.id)).toEqual([]);
63 });
64
65 test("the box page's link and the profile page's row anchor are the same", async () => {
66 const box = await (await get("/games/net")).text();
67 const href = `/games/net/spark/${slow}#${tickAnchor(3)}`;
68 expect(box).toContain(`<a href="${href}">Tick time reached 62.5 ms`);
69 const prof = await (await get(`/games/net/spark/${slow}`)).text();
70 expect(prof).toContain('<li id="tick-3">');
71 expect(prof).toContain('<li id="tick-9">');
72 // A box with nothing slow shows no such line.
73 expect(await (await get("/games/calm")).text()).not.toContain("Tick time reached");
74 });
75
76 test("another box never links a profile it does not hold", () => {
77 expect(sparkFindingsOf(app.db, boxNamed(app.db, "calm")!.id).map((f) => f.key)).not.toContain(slow);
78 expect(sparkFindingsOf(app.db, "nobody")).toEqual([]);
79 });
test/tui-games.test.ts +2 −1
@@ -455,7 +455,8 @@ test("Enter on a stored spark profile opens its call tree in the terminal, as th
455455 await owner.type("\r");
456456 await settleUntil(owner.tui, "Main thread");
457457 expect(owner.tui.screen.toText()).toContain("100.0% 100.0 ms tick");
458 // The terminal ends with the page's two lists, here with no ticks and no mod data (#18212, #18140).
458 // The terminal ends with the page's two lists, here with no ticks and no mod data (#18212,
459 // #18140).
459460 for (let i = 0; i < 40; i++) await owner.type("j");
460461 await settleUntil(owner.tui, "Time per mod");
461462 expect(owner.tui.screen.toText()).toContain("The profile attributes no time to a mod");

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

Keyboard shortcuts

Docs