GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(pm-aggregator): prime analytics cache sliced at boot + warm progr… · developing-today/code@1837d2b

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pm-stack/aggregator
    • src
      • analytics-store.ts
      • server.ts
    • test
      • program-prime-5082.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pm-stack/aggregator/src/analytics-store.ts‎

Copy file name to clipboardExpand all lines: pm-stack/aggregator/src/analytics-store.ts
+42-1Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -412,7 +412,7 @@ const AGGREGATES_TTL_MS = 300_000;
412412
let aggregatesCache: { path: string; at: number; data: AttemptAggregates } | null = null;
413413
let aggregatesRefreshing = false;
414414

415-
function refreshAttemptAggregates(db: Database, path: string): void {
415+
function refreshAttemptAggregates(db: Database, path: string, onSettled?: () => void): void {
416416
if (aggregatesRefreshing) return;
417417
aggregatesRefreshing = true;
418418
const now = Date.now();
@@ -474,6 +474,7 @@ function refreshAttemptAggregates(db: Database, path: string): void {
474474
if (idx >= steps.length) {
475475
aggregatesCache = { path, at: Date.now(), data: data as AttemptAggregates };
476476
aggregatesRefreshing = false;
477+
onSettled?.();
477478
return;
478479
}
479480
const next = steps[idx++];
@@ -482,6 +483,7 @@ function refreshAttemptAggregates(db: Database, path: string): void {
482483
} catch {
483484
// fail-soft: keep serving the stale copy; a later stale read retries
484485
aggregatesRefreshing = false;
486+
onSettled?.();
485487
return;
486488
}
487489
setTimeout(step, 0);
@@ -500,6 +502,45 @@ function loadAttemptAggregates(db: Database, path: string, now: number): Attempt
500502
return data;
501503
}
502504

505+
/**
506+
* Boot prime (#5082 follow-up, 2026-11-13): fill the aggregates cache
507+
* through the SLICED refresh instead of the synchronous first build.
508+
* The cold computeAttemptAggregates path measures ~12 s of
509+
* uninterrupted event-loop time over the live ledger; when server.ts
510+
* paid it inside the boot warm-up, every request that arrived during
511+
* the warm-up queued behind it — the first /api/program.json after a
512+
* restart measured 26.4 s while every later hit measured ~0.03 s.
513+
* Priming runs the same day-sliced steps as a stale refresh (widest
514+
* slice ~0.3 s, one per macrotask), so the loop stays responsive and
515+
* no request path ever pays the cold build at boot. A /quota request
516+
* that lands before the prime settles still takes the synchronous
517+
* cold path in loadAttemptAggregates — unchanged semantics, bounded
518+
* to that one request.
519+
*
520+
* Returns true when a prime was started. When there is nothing to do
521+
* (cache already populated for this DB, a refresh already in flight,
522+
* or no readable DB) it returns false and `onSettled` fires
523+
* immediately, so an awaiting caller never hangs; when a prime is
524+
* started, `onSettled` fires once it lands or aborts fail-soft.
525+
*/
526+
export function primeAttemptAggregates(
527+
opencodeDbPath: string = OPENCODE_DB_DEFAULT,
528+
onSettled?: () => void,
529+
): boolean {
530+
if (aggregatesCache && aggregatesCache.path === opencodeDbPath) {
531+
onSettled?.();
532+
return false;
533+
}
534+
if (aggregatesRefreshing) return false;
535+
const db = getDb(opencodeDbPath);
536+
if (!db) {
537+
onSettled?.();
538+
return false;
539+
}
540+
refreshAttemptAggregates(db, opencodeDbPath, onSettled);
541+
return true;
542+
}
543+
503544
function addInto(into: BurnBucket, r: { calls: number; success: number; input: number; output: number; reasoning: number; cache_read: number; cache_write: number; cost: number; cost_rows: number }): void {
504545
into.calls += r.calls;
505546
into.success += r.success;
Collapse file

‎pm-stack/aggregator/src/server.ts‎

Copy file name to clipboardExpand all lines: pm-stack/aggregator/src/server.ts
+20-19Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
// apply actions; the dashboard only records them.
99
import { readFile, stat } from "node:fs/promises";
1010
import { createQuotaRefresher, systemdTrigger } from "./quota-refresh.ts";
11-
import { buildQuotaAnalytics, type QuotaAnalytics } from "./analytics-store.ts";
11+
import { buildQuotaAnalytics, primeAttemptAggregates, type QuotaAnalytics } from "./analytics-store.ts";
1212
import { decodePathSegment } from "./path-segment.ts";
1313
import { errorBoundaryResponse, notFoundResponse } from "./error-boundary.ts";
1414
import { ACTION_STATES, ActionsStore, validateNewAction, type DashAction } from "./actions.ts";
@@ -4059,28 +4059,29 @@ for (const server of servers) {
40594059
console.log(`aggregator listening on http://${server.hostname}:${server.port} (source: ${cfg.source})`);
40604060
}
40614061

4062-
// #5082: warm the quota-analytics aggregates once at boot. The first
4063-
// build pays the route_attempt scans synchronously (~10 s over the
4064-
// 21 GB ledger); paying it here, off the request path, means no
4065-
// /quota or /api/quota-analytics.json request ever waits on them —
4066-
// later builds ride the stale-while-revalidate cache in
4067-
// analytics-store.ts.
4062+
// #5082: warm the quota-analytics aggregates once at boot, and the
4063+
// page assemblies with them. The aggregates warm-up no longer calls
4064+
// buildQuotaAnalytics synchronously: the first build's unsliced scans
4065+
// measure ~12 s of uninterrupted event-loop time over the 21 GB
4066+
// ledger, and a request that arrived during the old warm-up queued
4067+
// behind the whole window — the first /api/program.json after a
4068+
// restart measured 26.4 s against ~0.03 s warm (2026-11-13
4069+
// follow-up). primeAttemptAggregates fills the same cache through
4070+
// the day-sliced stale-while-revalidate refresh instead, so the loop
4071+
// stays responsive; later builds ride that cache as before, and a
4072+
// /quota request landing before the prime settles still pays the
4073+
// synchronous cold build on its own path (unchanged semantics).
4074+
// programSources joins the warmed assemblies in the same follow-up:
4075+
// it was the one major assembly left out, so /program's first
4076+
// post-restart request always paid its cold fan-out on the request
4077+
// path, inside whatever loop backlog the boot window left behind.
40684078
setTimeout(() => {
40694079
void (async () => {
40704080
try {
4071-
const [quota, usage] = await Promise.all([
4072-
source.quota().catch(() => emptyQuotaView()),
4073-
source.usage().catch(() => emptyUsageView()),
4074-
]);
4075-
buildQuotaAnalytics({ quota, usage, quotaCurrentPath: cfg.quotaCurrentFile });
4076-
// #5082 follow-up: warm the page assemblies too, so the first
4077-
// request after a restart never pays a cold board/overview/today
4078-
// fan-out either. With the caches now stale-while-revalidate,
4079-
// later expiries refresh behind the stale copy instead of on
4080-
// the request path.
4081-
await Promise.allSettled([boardContext(), overviewContext(), todayContext()]);
4081+
primeAttemptAggregates();
4082+
await Promise.allSettled([boardContext(), overviewContext(), todayContext(), programSources()]);
40824083
} catch {
4083-
// fail-soft: the first real /quota request retries the build
4084+
// fail-soft: the first real request retries its own assembly
40844085
}
40854086
})();
40864087
}, 0);
Collapse file

‎pm-stack/aggregator/test/program-prime-5082.test.ts‎

Copy file name to clipboard
+155Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2+
import { Database } from "bun:sqlite";
3+
import { spawn, type Subprocess } from "bun";
4+
import { mkdtempSync, rmSync } from "node:fs";
5+
import { tmpdir } from "node:os";
6+
import { join } from "node:path";
7+
import { buildQuotaAnalytics, primeAttemptAggregates } from "../src/analytics-store.ts";
8+
import type { QuotaView, UsageView } from "../src/model.ts";
9+
10+
// #5082 follow-up (2026-11-13): the /program cold-path stall. The
11+
// program assembly was the one major assembly the boot warm-up never
12+
// warmed, and the warm-up itself monopolized the single event loop:
13+
// its synchronous first buildQuotaAnalytics measured ~12 s, and the
14+
// first /api/program.json after a restart measured 26.4 s against
15+
// ~0.03 s warm — while the program legs themselves total ~0.3 s and
16+
// warm TTL-expiry passes serve stale in ~0.02 s. The fix primes the
17+
// aggregates cache through the day-sliced refresh (never the
18+
// synchronous cold build at boot) and warms programSources with the
19+
// other assemblies.
20+
//
21+
// The unit section pins the prime contract against a fixture
22+
// route_attempt DB; the route section pins that a booted server's
23+
// first /api/program.json is served by the warmed path.
24+
25+
const emptyQuota = (): QuotaView =>
26+
({ pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }) as QuotaView;
27+
const emptyUsage = (): UsageView =>
28+
({
29+
services: [],
30+
uninstrumentedServices: [],
31+
payg: [],
32+
charges: [],
33+
attention: [],
34+
domains: null,
35+
subscriptions: [],
36+
history: {},
37+
}) as unknown as UsageView;
38+
39+
describe("attempt-aggregates boot prime (#5082)", () => {
40+
const dir = mkdtempSync(join(tmpdir(), "agg-prime-"));
41+
const dbPath = join(dir, "fixture.db");
42+
const now = Date.now();
43+
const rowOld = now - 2 * 86_400_000;
44+
const rowNew = now - 3_600_000;
45+
46+
beforeAll(() => {
47+
const db = new Database(dbPath, { create: true });
48+
db.run(`CREATE TABLE route_attempt (
49+
time_started INTEGER, provider_id TEXT, credential_id TEXT,
50+
model_id TEXT, variant TEXT, outcome TEXT,
51+
tokens_input INTEGER, tokens_output INTEGER, tokens_reasoning INTEGER,
52+
tokens_cache_read INTEGER, tokens_cache_write INTEGER, cost_usd REAL
53+
)`);
54+
const ins = db.query(
55+
`INSERT INTO route_attempt VALUES (?, 'prov-a', 'cred-1', 'model-x', NULL, 'success', 100, 50, 0, 10, 5, 0.25)`,
56+
);
57+
ins.run(rowOld);
58+
ins.run(rowNew);
59+
ins.run(rowNew);
60+
db.close();
61+
});
62+
63+
afterAll(() => {
64+
rmSync(dir, { recursive: true, force: true });
65+
});
66+
67+
test("prime fills the cache through the sliced refresh; the build then serves the primed coverage", async () => {
68+
let settle!: () => void;
69+
const settled = new Promise<void>((resolve) => {
70+
settle = resolve;
71+
});
72+
expect(primeAttemptAggregates(dbPath, settle)).toBe(true);
73+
// A second prime while the first is in flight starts nothing.
74+
expect(primeAttemptAggregates(dbPath)).toBe(false);
75+
await settled;
76+
77+
const analytics = buildQuotaAnalytics({
78+
quota: emptyQuota(),
79+
usage: emptyUsage(),
80+
quotaCurrentPath: join(dir, "no-such-quota-current.json"),
81+
opencodeDbPath: dbPath,
82+
now,
83+
});
84+
expect(analytics.dbAvailable).toBe(true);
85+
expect(analytics.attemptsFrom).toBe(new Date(rowOld).toISOString());
86+
expect(analytics.attemptsTo).toBe(new Date(rowNew).toISOString());
87+
expect(analytics.totals.last7d.calls).toBe(3);
88+
89+
// Cache populated: a later prime is a no-op whose callback fires.
90+
let fired = false;
91+
expect(
92+
primeAttemptAggregates(dbPath, () => {
93+
fired = true;
94+
}),
95+
).toBe(false);
96+
expect(fired).toBe(true);
97+
});
98+
99+
test("prime against a missing DB is a fail-soft no-op", async () => {
100+
let fired = false;
101+
expect(
102+
primeAttemptAggregates(join(dir, "absent.db"), () => {
103+
fired = true;
104+
}),
105+
).toBe(false);
106+
expect(fired).toBe(true);
107+
});
108+
});
109+
110+
describe("booted server serves the program path (#5082)", () => {
111+
let proc: Subprocess<"ignore", "pipe", "inherit"> | null = null;
112+
let port = 0;
113+
114+
beforeAll(async () => {
115+
port = 5100 + Math.floor(Math.random() * 1000);
116+
proc = spawn({
117+
cmd: ["bun", "run", "src/server.ts"],
118+
cwd: import.meta.dir + "/..",
119+
env: {
120+
...Bun.env,
121+
PM_AGG_PORT: String(port),
122+
PM_AGG_FRESHNESS_PORT: String(port + 2000),
123+
PM_AGG_SOURCE: "fixtures",
124+
},
125+
stdout: "pipe",
126+
stderr: "inherit",
127+
});
128+
const deadline = Date.now() + 10_000;
129+
let ready = false;
130+
while (Date.now() < deadline) {
131+
try {
132+
const res = await fetch(`http://127.0.0.1:${port}/api/health`);
133+
if (res.ok) {
134+
ready = true;
135+
break;
136+
}
137+
} catch {
138+
/* not up yet */
139+
}
140+
await Bun.sleep(120);
141+
}
142+
expect(ready).toBe(true);
143+
});
144+
145+
afterAll(() => {
146+
proc?.kill();
147+
});
148+
149+
test("first /api/program.json after boot answers 200 with the program payload", async () => {
150+
const res = await fetch(`http://127.0.0.1:${port}/api/program.json`);
151+
expect(res.status).toBe(200);
152+
const body = (await res.json()) as { projects?: unknown[] };
153+
expect(Array.isArray(body.projects)).toBe(true);
154+
});
155+
});

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.