@linxiraos/pi-stats 1.5.14 → 1.5.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -16
- package/README.md +7 -1
- package/THIRD-PARTY-NOTICES.txt +1 -1
- package/dist/client/index.js +81 -81
- package/dist/types/aggregator.d.ts +1 -1
- package/dist/types/client/app/Shell.d.ts +1 -1
- package/dist/types/client/data/colors.d.ts +5 -2
- package/dist/types/client/data/view-models.d.ts +30 -11
- package/dist/types/client/types.d.ts +3 -2
- package/dist/types/db.d.ts +23 -2
- package/dist/types/gain-aggregator.d.ts +4 -4
- package/dist/types/parser.d.ts +2 -1
- package/dist/types/rollup.d.ts +12 -4
- package/dist/types/server.d.ts +2 -0
- package/dist/types/shared-types.d.ts +34 -9
- package/dist/types/side-channels.d.ts +28 -0
- package/dist/types/spotlight-ingest.d.ts +8 -5
- package/dist/types/types.d.ts +42 -1
- package/package.json +44 -44
- package/src/aggregator.ts +11 -4
- package/src/client/app/Shell.tsx +1 -1
- package/src/client/charts/TimeChart.tsx +8 -1
- package/src/client/data/colors.ts +9 -3
- package/src/client/data/range.ts +44 -7
- package/src/client/data/view-models.ts +83 -31
- package/src/client/routes/GainRoute.tsx +5 -2
- package/src/client/routes/OverviewRoute.tsx +86 -33
- package/src/client/types.ts +3 -1
- package/src/db.ts +150 -20
- package/src/gain-aggregator.ts +68 -32
- package/src/parser.ts +46 -1
- package/src/rollup.ts +112 -25
- package/src/server.ts +68 -0
- package/src/shared-types.ts +36 -9
- package/src/side-channels.ts +63 -0
- package/src/spotlight-ingest.ts +49 -23
- package/src/types.ts +36 -1
package/src/db.ts
CHANGED
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
hasRecurringTariff,
|
|
11
11
|
} from "@linxiraos/pi-catalog/models";
|
|
12
12
|
import type { ModelCost } from "@linxiraos/pi-catalog/types";
|
|
13
|
-
import { getConfigRootDir, getStatsDbPath, VERSION } from "@linxiraos/pi-utils";
|
|
13
|
+
import { $envpos, getConfigRootDir, getStatsDbPath, VERSION } from "@linxiraos/pi-utils";
|
|
14
14
|
import { ChunkedInsert } from "./chunked-insert";
|
|
15
15
|
import { classifyAgentType, type ParseSessionResult, type SessionParserState } from "./parser";
|
|
16
16
|
import {
|
|
@@ -39,6 +39,7 @@ import type {
|
|
|
39
39
|
ModelHourlyActivityPoint,
|
|
40
40
|
ModelSideCounts,
|
|
41
41
|
ModelSideTimeSeriesPoint,
|
|
42
|
+
SnapcompactCompactionStats,
|
|
42
43
|
ToolCallStats,
|
|
43
44
|
ToolResultLink,
|
|
44
45
|
UserMessageLink,
|
|
@@ -165,9 +166,30 @@ const SPOTLIGHT_ARG_TOKENS_BACKFILL_KEY = "spotlight_v5_arg_tokens";
|
|
|
165
166
|
// count only with the arm that shipped. Every transcript that can hold
|
|
166
167
|
// Spotlight entries is re-parsed once by the new rules.
|
|
167
168
|
const SPOTLIGHT_TOGGLE_BACKFILL_KEY = "spotlight_v6_toggle";
|
|
169
|
+
// Snapcompact compactions are filled by the parser; transcripts ingested before
|
|
170
|
+
// the table existed are re-parsed once. Compaction entries carry `method` and
|
|
171
|
+
// `tokensAfter` only since this date, so older cursors stay put.
|
|
172
|
+
const SNAPCOMPACT_COMPACTIONS_BACKFILL_KEY = "snapcompact_compactions_v1";
|
|
173
|
+
const SNAPCOMPACT_COMPACTIONS_SINCE_MS = Date.parse("2026-08-20T00:00:00Z");
|
|
174
|
+
// `messages.purpose` is filled by the parser from `model_usage` entries, which
|
|
175
|
+
// rows ingested before the column existed stored as anonymous assistant rows;
|
|
176
|
+
// their transcripts are re-parsed once, which also picks up the
|
|
177
|
+
// `duration`/`ttft` newer entries carry. Sessions journal `model_usage` only
|
|
178
|
+
// since this date, so older cursors stay put.
|
|
179
|
+
const MODEL_USAGE_PURPOSE_BACKFILL_KEY = "model_usage_purpose_v1";
|
|
180
|
+
const MODEL_USAGE_SINCE_MS = Date.parse("2026-08-31T00:00:00Z");
|
|
168
181
|
function shouldResetBackfill(value: string | undefined): boolean {
|
|
169
182
|
return value !== BACKFILL_COMPLETE && value !== BACKFILL_PENDING;
|
|
170
183
|
}
|
|
184
|
+
const BUSY_TIMEOUT_MS = 5000;
|
|
185
|
+
/**
|
|
186
|
+
* Env var overriding {@link BUSY_TIMEOUT_MS} (positive milliseconds) for the
|
|
187
|
+
* stats database's busy handler.
|
|
188
|
+
*/
|
|
189
|
+
export const STATS_BUSY_TIMEOUT_MS_ENV = "ZETA_STATS_BUSY_TIMEOUT_MS";
|
|
190
|
+
function busyTimeoutPragma(): string {
|
|
191
|
+
return `PRAGMA busy_timeout = ${$envpos(STATS_BUSY_TIMEOUT_MS_ENV, BUSY_TIMEOUT_MS)}`;
|
|
192
|
+
}
|
|
171
193
|
/**
|
|
172
194
|
* Initialize the database and create tables.
|
|
173
195
|
*/
|
|
@@ -179,8 +201,8 @@ export async function initDb(): Promise<Database> {
|
|
|
179
201
|
|
|
180
202
|
db = new Database(getStatsDbPath());
|
|
181
203
|
// Install the busy handler BEFORE any lock-taking statement. See
|
|
182
|
-
// https://github.com/
|
|
183
|
-
db.run(
|
|
204
|
+
// https://github.com/Linxira-OS/linxira-zeta/issues/2421.
|
|
205
|
+
db.run(busyTimeoutPragma());
|
|
184
206
|
db.run("PRAGMA journal_mode = WAL");
|
|
185
207
|
// The database is a derived cache of the transcripts, so WAL's NORMAL sync
|
|
186
208
|
// (fsync only at checkpoints) is safe: a crash can drop the newest batches,
|
|
@@ -229,6 +251,7 @@ export async function initDb(): Promise<Database> {
|
|
|
229
251
|
cost_unpriced INTEGER NOT NULL DEFAULT 0,
|
|
230
252
|
agent_type TEXT NOT NULL DEFAULT 'main',
|
|
231
253
|
service_tier TEXT,
|
|
254
|
+
purpose TEXT,
|
|
232
255
|
UNIQUE(session_file, entry_id)
|
|
233
256
|
);
|
|
234
257
|
|
|
@@ -437,6 +460,18 @@ export async function initDb(): Promise<Database> {
|
|
|
437
460
|
edit TEXT NOT NULL,
|
|
438
461
|
PRIMARY KEY (session_file, tool_call_id)
|
|
439
462
|
) WITHOUT ROWID;
|
|
463
|
+
|
|
464
|
+
-- Snapcompact compactions: the session's context estimate before and after each one.
|
|
465
|
+
CREATE TABLE IF NOT EXISTS snapcompact_compactions (
|
|
466
|
+
session_file TEXT NOT NULL,
|
|
467
|
+
entry_id TEXT NOT NULL,
|
|
468
|
+
folder TEXT NOT NULL,
|
|
469
|
+
timestamp INTEGER NOT NULL,
|
|
470
|
+
tokens_before INTEGER NOT NULL,
|
|
471
|
+
tokens_after INTEGER NOT NULL,
|
|
472
|
+
PRIMARY KEY (session_file, entry_id)
|
|
473
|
+
) WITHOUT ROWID;
|
|
474
|
+
CREATE INDEX IF NOT EXISTS idx_snapcompact_compactions_entry ON snapcompact_compactions(entry_id, timestamp);
|
|
440
475
|
`);
|
|
441
476
|
|
|
442
477
|
const offsetColumns = db.query("PRAGMA table_info(file_offsets)").all() as { name: string }[];
|
|
@@ -497,6 +532,12 @@ export async function initDb(): Promise<Database> {
|
|
|
497
532
|
if (!messageColumns.some(column => column.name === "cost_unpriced")) {
|
|
498
533
|
db.run("ALTER TABLE messages ADD COLUMN cost_unpriced INTEGER NOT NULL DEFAULT 0");
|
|
499
534
|
}
|
|
535
|
+
// Off-transcript model calls (`model_usage` entries) keep their raw purpose;
|
|
536
|
+
// assistant messages stay NULL. Rows ingested before this column existed are
|
|
537
|
+
// all NULL until the `model_usage_purpose_v1` re-parse below rewrites them.
|
|
538
|
+
if (!messageColumns.some(column => column.name === "purpose")) {
|
|
539
|
+
db.run("ALTER TABLE messages ADD COLUMN purpose TEXT");
|
|
540
|
+
}
|
|
500
541
|
// Token-usage-by-agent: each message is classified main / subagent / advisor
|
|
501
542
|
// from its transcript path. A brand-new table gets the column from CREATE
|
|
502
543
|
// TABLE and the parser labels rows at insert time; a pre-existing table gets
|
|
@@ -512,10 +553,13 @@ export async function initDb(): Promise<Database> {
|
|
|
512
553
|
// sentinel write (process killed in between) still reclassifies on the next
|
|
513
554
|
// init instead of silently leaving every row as the 'main' default. A
|
|
514
555
|
// brand-new empty table has nothing to reclassify, so it settles COMPLETE.
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
556
|
+
// Checked before writing: an open of a settled database takes no write lock.
|
|
557
|
+
if (!db.query("SELECT 1 FROM meta WHERE key = ?").get(AGENT_TYPE_BACKFILL_KEY)) {
|
|
558
|
+
db.query("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)").run(
|
|
559
|
+
AGENT_TYPE_BACKFILL_KEY,
|
|
560
|
+
messagesTableExisted ? BACKFILL_PENDING : BACKFILL_COMPLETE,
|
|
561
|
+
);
|
|
562
|
+
}
|
|
519
563
|
db.run("CREATE INDEX IF NOT EXISTS idx_messages_timestamp_agent_type ON messages(timestamp, agent_type)");
|
|
520
564
|
// Each behavior-metric bump invalidates previously-ingested rows. We detect
|
|
521
565
|
// the stale schema by column name and drop the table; `IF NOT EXISTS` above
|
|
@@ -599,11 +643,13 @@ export async function initDb(): Promise<Database> {
|
|
|
599
643
|
backfillMissingCatalogCosts(db);
|
|
600
644
|
backfillNoCacheInputCosts(db);
|
|
601
645
|
backfillForkDuplicates(db);
|
|
602
|
-
|
|
646
|
+
reparseModifiedSince(db, SPOTLIGHT_BACKFILL_KEY, SPOTLIGHT_SINCE_MS);
|
|
603
647
|
reparseSpotlightSessions(db, SPOTLIGHT_EDITS_BACKFILL_KEY);
|
|
604
648
|
reparseSpotlightSessions(db, SPOTLIGHT_NEEDS_BACKFILL_KEY);
|
|
605
649
|
reparseSpotlightSessions(db, SPOTLIGHT_ARG_TOKENS_BACKFILL_KEY);
|
|
606
|
-
|
|
650
|
+
reparseModifiedSince(db, SPOTLIGHT_TOGGLE_BACKFILL_KEY, SPOTLIGHT_SINCE_MS);
|
|
651
|
+
reparseModifiedSince(db, SNAPCOMPACT_COMPACTIONS_BACKFILL_KEY, SNAPCOMPACT_COMPACTIONS_SINCE_MS);
|
|
652
|
+
reparseModifiedSince(db, MODEL_USAGE_PURPOSE_BACKFILL_KEY, MODEL_USAGE_SINCE_MS);
|
|
607
653
|
ensureRollupSchema(db);
|
|
608
654
|
return db;
|
|
609
655
|
}
|
|
@@ -841,18 +887,20 @@ function backfillNoCacheInputCosts(database: Database): void {
|
|
|
841
887
|
}
|
|
842
888
|
|
|
843
889
|
/**
|
|
844
|
-
* Re-parse, once per key, the transcripts
|
|
845
|
-
*
|
|
846
|
-
* older cursor stays, so this never triggers a full-history
|
|
847
|
-
* sync rebuilds those files from byte zero, replacing their
|
|
848
|
-
* Keys: {@link SPOTLIGHT_BACKFILL_KEY} (the
|
|
849
|
-
* {@link SPOTLIGHT_TOGGLE_BACKFILL_KEY} (the experiment became
|
|
890
|
+
* Re-parse, once per key, the transcripts modified since `sinceMs` (the first
|
|
891
|
+
* day they can hold the entries the key's rows come from) by dropping their
|
|
892
|
+
* cursors; every older cursor stays, so this never triggers a full-history
|
|
893
|
+
* re-parse. The next sync rebuilds those files from byte zero, replacing their
|
|
894
|
+
* parser-filled rows. Keys: {@link SPOTLIGHT_BACKFILL_KEY} (the Spotlight
|
|
895
|
+
* tables are new), {@link SPOTLIGHT_TOGGLE_BACKFILL_KEY} (the experiment became
|
|
896
|
+
* a toggle), {@link SNAPCOMPACT_COMPACTIONS_BACKFILL_KEY} (the table is new),
|
|
897
|
+
* {@link MODEL_USAGE_PURPOSE_BACKFILL_KEY} (`messages.purpose` is new).
|
|
850
898
|
*/
|
|
851
|
-
function
|
|
899
|
+
function reparseModifiedSince(database: Database, key: string, sinceMs: number): void {
|
|
852
900
|
const row = database.query<{ value: string }, [string]>("SELECT value FROM meta WHERE key = ?").get(key);
|
|
853
901
|
if (row?.value === BACKFILL_COMPLETE) return;
|
|
854
902
|
database.transaction(() => {
|
|
855
|
-
database.query("DELETE FROM file_offsets WHERE last_modified >= ?").run(
|
|
903
|
+
database.query("DELETE FROM file_offsets WHERE last_modified >= ?").run(sinceMs);
|
|
856
904
|
database.query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(key, BACKFILL_COMPLETE);
|
|
857
905
|
})();
|
|
858
906
|
}
|
|
@@ -1142,6 +1190,27 @@ export function applySessionParseResults(sessions: ParsedSession[]): {
|
|
|
1142
1190
|
for (const table of SPOTLIGHT_TABLES) {
|
|
1143
1191
|
changes += database.query(`DELETE FROM ${table} WHERE session_file = ?`).run(sessionFile).changes;
|
|
1144
1192
|
}
|
|
1193
|
+
}
|
|
1194
|
+
// The parse covers the whole transcript: drop compactions it no longer holds or has
|
|
1195
|
+
// rewritten. A removed one may live on in a fork, which only another replay can credit.
|
|
1196
|
+
const parsedCompactions = new Map(result.snapcompactCompactions.map(row => [row.entryId, row]));
|
|
1197
|
+
const storedCompactions = database
|
|
1198
|
+
.query<{ entry_id: string; timestamp: number; tokens_before: number; tokens_after: number }, [string]>(
|
|
1199
|
+
"SELECT entry_id, timestamp, tokens_before, tokens_after FROM snapcompact_compactions WHERE session_file = ?",
|
|
1200
|
+
)
|
|
1201
|
+
.all(sessionFile);
|
|
1202
|
+
for (const stored of storedCompactions) {
|
|
1203
|
+
const parsed = parsedCompactions.get(stored.entry_id);
|
|
1204
|
+
if (parsed?.timestamp !== stored.timestamp) {
|
|
1205
|
+
reconcile = true;
|
|
1206
|
+
} else if (parsed.tokensBefore === stored.tokens_before && parsed.tokensAfter === stored.tokens_after) {
|
|
1207
|
+
continue;
|
|
1208
|
+
}
|
|
1209
|
+
changes += database
|
|
1210
|
+
.query("DELETE FROM snapcompact_compactions WHERE session_file = ? AND entry_id = ?")
|
|
1211
|
+
.run(sessionFile, stored.entry_id).changes;
|
|
1212
|
+
}
|
|
1213
|
+
if (replace) {
|
|
1145
1214
|
if (messages.length > 0) {
|
|
1146
1215
|
changes += database.query("DELETE FROM messages WHERE session_file = ?").run(sessionFile).changes;
|
|
1147
1216
|
}
|
|
@@ -1175,6 +1244,7 @@ export function applySessionParseResults(sessions: ParsedSession[]): {
|
|
|
1175
1244
|
updateUserMessageLinks(parsedRows(writes, result => result.userLinks)) +
|
|
1176
1245
|
insertToolCalls(parsedRows(writes, result => result.toolCalls)) +
|
|
1177
1246
|
updateToolResults(parsedRows(writes, result => result.toolResults)) +
|
|
1247
|
+
insertSnapcompactCompactions(parsedRows(writes, result => result.snapcompactCompactions)) +
|
|
1178
1248
|
insertSpotlightSessions(parsedRows(writes, result => result.spotlight.sessions)) +
|
|
1179
1249
|
updateSpotlightTitles(parsedRows(writes, result => result.spotlight.titles)) +
|
|
1180
1250
|
upsertSpotlightShapes(parsedRows(writes, result => result.spotlight.shapes)) +
|
|
@@ -1226,7 +1296,10 @@ export function completeSessionSync(reconcile: boolean): void {
|
|
|
1226
1296
|
* first-write-wins across the lineage. Same-file re-syncs still hit the
|
|
1227
1297
|
* `ON CONFLICT(session_file, entry_id)` upsert below, which re-derives the
|
|
1228
1298
|
* stored cost (orchestration-aware) and keeps `premium_requests` monotonic, so
|
|
1229
|
-
* a forced re-parse repairs historical `premium_requests` and cost fix-ups.
|
|
1299
|
+
* a forced re-parse repairs historical `premium_requests` and cost fix-ups. It
|
|
1300
|
+
* also rewrites the parser-derived `purpose`, `duration` and `ttft`, so a row
|
|
1301
|
+
* stored by a build that did not read them from `model_usage` entries is
|
|
1302
|
+
* repaired by the same re-parse.
|
|
1230
1303
|
*/
|
|
1231
1304
|
export function insertMessageStats(stats: Iterable<MessageStatsInput>): number {
|
|
1232
1305
|
if (!db) return 0;
|
|
@@ -1260,9 +1333,13 @@ export function insertMessageStats(stats: Iterable<MessageStatsInput>): number {
|
|
|
1260
1333
|
"cost_unpriced",
|
|
1261
1334
|
"agent_type",
|
|
1262
1335
|
"service_tier",
|
|
1336
|
+
"purpose",
|
|
1263
1337
|
],
|
|
1264
1338
|
identity: ["entry_id", "timestamp"],
|
|
1265
1339
|
upsert: `ON CONFLICT(session_file, entry_id) DO UPDATE SET
|
|
1340
|
+
duration = excluded.duration,
|
|
1341
|
+
ttft = excluded.ttft,
|
|
1342
|
+
purpose = excluded.purpose,
|
|
1266
1343
|
premium_requests = MAX(messages.premium_requests, excluded.premium_requests),
|
|
1267
1344
|
cost_input = excluded.cost_input,
|
|
1268
1345
|
cost_output = excluded.cost_output,
|
|
@@ -1307,6 +1384,7 @@ export function insertMessageStats(stats: Iterable<MessageStatsInput>): number {
|
|
|
1307
1384
|
unpriced ? 1 : 0,
|
|
1308
1385
|
s.agentType,
|
|
1309
1386
|
s.serviceTier ?? null,
|
|
1387
|
+
s.purpose ?? null,
|
|
1310
1388
|
],
|
|
1311
1389
|
);
|
|
1312
1390
|
}
|
|
@@ -1364,6 +1442,7 @@ function rowToMessageStats(row: any): MessageStats {
|
|
|
1364
1442
|
},
|
|
1365
1443
|
},
|
|
1366
1444
|
agentType: (row.agent_type as AgentType) ?? "main",
|
|
1445
|
+
purpose: (row.purpose as string | null) ?? null,
|
|
1367
1446
|
serviceTier: (row.service_tier as ServiceTier | null) ?? null,
|
|
1368
1447
|
costUnpriced: row.cost_unpriced === 1,
|
|
1369
1448
|
};
|
|
@@ -1408,9 +1487,36 @@ export function getMessageById(id: number): MessageStats | null {
|
|
|
1408
1487
|
* raw rows while its rebuild backlog is too large for exact reads.
|
|
1409
1488
|
*/
|
|
1410
1489
|
export async function getDailyActivity(days = 371, now = Date.now()): Promise<DailyActivityPoint[]> {
|
|
1411
|
-
|
|
1490
|
+
return dailyActivity(await initDb(), days, now);
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
/**
|
|
1494
|
+
* {@link getDailyActivity} from the stored rows through a connection of its
|
|
1495
|
+
* own that never writes: no schema setup or one-time pass runs first, so
|
|
1496
|
+
* another process holding the write lock never delays or fails it (WAL
|
|
1497
|
+
* readers do not wait for writers). Returns null when the stats database
|
|
1498
|
+
* cannot be opened, as before one exists.
|
|
1499
|
+
*/
|
|
1500
|
+
export function readDailyActivity(days = 371): DailyActivityPoint[] | null {
|
|
1501
|
+
let reader: Database;
|
|
1502
|
+
try {
|
|
1503
|
+
reader = new Database(getStatsDbPath(), { readwrite: true, create: false });
|
|
1504
|
+
} catch {
|
|
1505
|
+
// `create: false` refuses to open a database that does not exist yet.
|
|
1506
|
+
return null;
|
|
1507
|
+
}
|
|
1508
|
+
try {
|
|
1509
|
+
reader.run(busyTimeoutPragma());
|
|
1510
|
+
reader.run("PRAGMA query_only = 1");
|
|
1511
|
+
return dailyActivity(reader, days);
|
|
1512
|
+
} finally {
|
|
1513
|
+
reader.close();
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
function dailyActivity(database: Database, days: number, now = Date.now()): DailyActivityPoint[] {
|
|
1412
1518
|
const cutoff = now - days * 24 * 60 * 60 * 1000;
|
|
1413
|
-
const rolled = getDailyActivityFromRollup(cutoff);
|
|
1519
|
+
const rolled = getDailyActivityFromRollup(cutoff, database);
|
|
1414
1520
|
if (rolled) return rolled;
|
|
1415
1521
|
const stmt = database.query(`
|
|
1416
1522
|
SELECT
|
|
@@ -2397,6 +2503,30 @@ export function updateToolResults(links: Iterable<ToolResultLink>): number {
|
|
|
2397
2503
|
return updated;
|
|
2398
2504
|
}
|
|
2399
2505
|
|
|
2506
|
+
/**
|
|
2507
|
+
* Insert snapcompact compaction rows. Forked transcripts copy compaction
|
|
2508
|
+
* entries verbatim, so the fork guard keeps one row per entry across the lineage.
|
|
2509
|
+
*/
|
|
2510
|
+
export function insertSnapcompactCompactions(rows: Iterable<SnapcompactCompactionStats>): number {
|
|
2511
|
+
if (!db) return 0;
|
|
2512
|
+
const writer = new ChunkedInsert(db, {
|
|
2513
|
+
verb: "INSERT OR IGNORE",
|
|
2514
|
+
table: "snapcompact_compactions",
|
|
2515
|
+
columns: ["session_file", "entry_id", "folder", "timestamp", "tokens_before", "tokens_after"],
|
|
2516
|
+
identity: ["entry_id", "timestamp"],
|
|
2517
|
+
});
|
|
2518
|
+
return atomically(db, () => {
|
|
2519
|
+
for (const row of rows) {
|
|
2520
|
+
writer.add(
|
|
2521
|
+
row.sessionFile,
|
|
2522
|
+
[row.entryId, row.timestamp],
|
|
2523
|
+
[row.sessionFile, row.entryId, row.folder, row.timestamp, row.tokensBefore, row.tokensAfter],
|
|
2524
|
+
);
|
|
2525
|
+
}
|
|
2526
|
+
return writer.finish();
|
|
2527
|
+
});
|
|
2528
|
+
}
|
|
2529
|
+
|
|
2400
2530
|
/** Tables the parser fills for the Spotlight dashboard, all keyed by `session_file`. */
|
|
2401
2531
|
const SPOTLIGHT_TABLES = [
|
|
2402
2532
|
"spotlight_sessions",
|
package/src/gain-aggregator.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Aggregates token-savings data for the Gain dashboard.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* 1.
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* Sources:
|
|
5
|
+
* 1. Imaged tool results: colocated with stats.db as snapcompact-savings.jsonl
|
|
6
|
+
* (a missing file is zero records, never an error)
|
|
7
|
+
* 2. Snapcompact compactions: the `snapcompact_compactions` table the session sync fills
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import type { Stats } from "node:fs";
|
|
@@ -229,6 +229,27 @@ async function readSnapcompactRecords(cutoff: number | null, project: string | n
|
|
|
229
229
|
return { records, projects };
|
|
230
230
|
}
|
|
231
231
|
|
|
232
|
+
interface CompactionRow {
|
|
233
|
+
folder: string;
|
|
234
|
+
timestamp: number;
|
|
235
|
+
tokens_before: number;
|
|
236
|
+
tokens_after: number;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function readSnapcompactCompactions(
|
|
240
|
+
cutoff: number | null,
|
|
241
|
+
project: string | null,
|
|
242
|
+
): Promise<{ rows: CompactionRow[]; projects: Set<string> }> {
|
|
243
|
+
const database = await initDb();
|
|
244
|
+
const rows = database
|
|
245
|
+
.query<CompactionRow, [number]>(
|
|
246
|
+
"SELECT folder, timestamp, tokens_before, tokens_after FROM snapcompact_compactions WHERE timestamp >= ?",
|
|
247
|
+
)
|
|
248
|
+
.all(cutoff ?? 0);
|
|
249
|
+
const projects = new Set(rows.map(row => row.folder));
|
|
250
|
+
return { rows: project === null ? rows : rows.filter(row => matchesProject(row.folder, project)), projects };
|
|
251
|
+
}
|
|
252
|
+
|
|
232
253
|
// ---------------------------------------------------------------------------
|
|
233
254
|
// Aggregation helpers
|
|
234
255
|
// ---------------------------------------------------------------------------
|
|
@@ -255,35 +276,51 @@ export async function getGainDashboardStats(
|
|
|
255
276
|
const { cutoff: effectiveCutoff } = getTimeRangeConfig(range);
|
|
256
277
|
const effectiveProject: string | null = project?.trim() || null;
|
|
257
278
|
|
|
258
|
-
const
|
|
259
|
-
|
|
260
|
-
effectiveProject,
|
|
261
|
-
);
|
|
279
|
+
const toolResultSets = await readSnapcompactRecords(effectiveCutoff, effectiveProject);
|
|
280
|
+
const compactionSets = await readSnapcompactCompactions(effectiveCutoff, effectiveProject);
|
|
262
281
|
|
|
263
|
-
const
|
|
264
|
-
const
|
|
282
|
+
const toolResults = emptyTotals();
|
|
283
|
+
const compaction = emptyTotals();
|
|
284
|
+
const timeMap = new Map<string, { snapcompact: number; compaction: number }>();
|
|
285
|
+
const bucketFor = (epochMs: number) => {
|
|
286
|
+
// Local calendar day, matching the dashboard's local day buckets.
|
|
287
|
+
const date = format(epochMs, "yyyy-MM-dd");
|
|
288
|
+
let bucket = timeMap.get(date);
|
|
289
|
+
if (!bucket) {
|
|
290
|
+
bucket = { snapcompact: 0, compaction: 0 };
|
|
291
|
+
timeMap.set(date, bucket);
|
|
292
|
+
}
|
|
293
|
+
return bucket;
|
|
294
|
+
};
|
|
265
295
|
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
296
|
+
// The journal records no original size, so imaged tool results leave reductionPercent null.
|
|
297
|
+
for (const rec of toolResultSets.records) {
|
|
298
|
+
toolResults.savedTokens += rec.savedTokens;
|
|
299
|
+
toolResults.savedBytes += rec.savedTokens * BYTES_PER_TOKEN_ESTIMATE;
|
|
300
|
+
toolResults.hits += 1;
|
|
301
|
+
bucketFor(rec.ts).snapcompact += rec.savedTokens;
|
|
302
|
+
}
|
|
271
303
|
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
|
|
304
|
+
// A compaction whose estimate did not shrink kept nothing out of context.
|
|
305
|
+
for (const row of compactionSets.rows) {
|
|
306
|
+
const saved = Math.max(0, row.tokens_before - row.tokens_after);
|
|
307
|
+
compaction.savedTokens += saved;
|
|
308
|
+
compaction.savedBytes += saved * BYTES_PER_TOKEN_ESTIMATE;
|
|
309
|
+
compaction.originalBytes += row.tokens_before * BYTES_PER_TOKEN_ESTIMATE;
|
|
310
|
+
compaction.hits += 1;
|
|
311
|
+
bucketFor(row.timestamp).compaction += saved;
|
|
277
312
|
}
|
|
278
|
-
|
|
313
|
+
compaction.outputBytes = compaction.originalBytes - compaction.savedBytes;
|
|
314
|
+
compaction.reductionPercent = compaction.originalBytes > 0 ? compaction.savedBytes / compaction.originalBytes : null;
|
|
279
315
|
|
|
316
|
+
// The overall reduction is known only while every hit has a known original size.
|
|
280
317
|
const overall: GainSourceTotals = {
|
|
281
|
-
savedTokens:
|
|
282
|
-
savedBytes:
|
|
283
|
-
hits:
|
|
284
|
-
outputBytes: 0,
|
|
285
|
-
originalBytes: 0,
|
|
286
|
-
reductionPercent: null,
|
|
318
|
+
savedTokens: toolResults.savedTokens + compaction.savedTokens,
|
|
319
|
+
savedBytes: toolResults.savedBytes + compaction.savedBytes,
|
|
320
|
+
hits: toolResults.hits + compaction.hits,
|
|
321
|
+
outputBytes: toolResults.hits === 0 ? compaction.outputBytes : 0,
|
|
322
|
+
originalBytes: toolResults.hits === 0 ? compaction.originalBytes : 0,
|
|
323
|
+
reductionPercent: toolResults.hits === 0 ? compaction.reductionPercent : null,
|
|
287
324
|
};
|
|
288
325
|
|
|
289
326
|
const timeSeries: GainTimeSeriesPoint[] = Array.from(timeMap.entries())
|
|
@@ -291,16 +328,15 @@ export async function getGainDashboardStats(
|
|
|
291
328
|
.map(([date, bucket]) => ({
|
|
292
329
|
date,
|
|
293
330
|
snapcompact: bucket.snapcompact,
|
|
294
|
-
|
|
331
|
+
...(bucket.compaction > 0 ? { compaction: bucket.compaction } : {}),
|
|
332
|
+
total: bucket.snapcompact + bucket.compaction,
|
|
295
333
|
}));
|
|
296
334
|
|
|
297
|
-
const projects = dedupeProjects(
|
|
335
|
+
const projects = dedupeProjects(new Set([...toolResultSets.projects, ...compactionSets.projects]));
|
|
298
336
|
|
|
299
337
|
return {
|
|
300
338
|
overall,
|
|
301
|
-
bySource: {
|
|
302
|
-
snapcompact: snapcompactTotals,
|
|
303
|
-
},
|
|
339
|
+
bySource: { snapcompact: toolResults, compaction },
|
|
304
340
|
timeSeries,
|
|
305
341
|
project: effectiveProject,
|
|
306
342
|
projects,
|
package/src/parser.ts
CHANGED
|
@@ -23,6 +23,8 @@ import type {
|
|
|
23
23
|
SessionMessageEntry,
|
|
24
24
|
SessionModelUsageEntry,
|
|
25
25
|
SessionServiceTierChangeEntry,
|
|
26
|
+
SessionTypedEntry,
|
|
27
|
+
SnapcompactCompactionStats,
|
|
26
28
|
ToolCallStats,
|
|
27
29
|
ToolResultLink,
|
|
28
30
|
UserMessageLink,
|
|
@@ -121,6 +123,24 @@ function isToolResultMessage(entry: SessionEntry): entry is SessionMessageEntry
|
|
|
121
123
|
return (entry as SessionMessageEntry).message?.role === "toolResult";
|
|
122
124
|
}
|
|
123
125
|
|
|
126
|
+
/**
|
|
127
|
+
* Build the row for a snapcompact compaction entry. Entries of other methods,
|
|
128
|
+
* legacy entries without `tokensAfter`, and malformed ones yield null.
|
|
129
|
+
*/
|
|
130
|
+
function extractSnapcompactCompaction(
|
|
131
|
+
sessionFile: string,
|
|
132
|
+
folder: string,
|
|
133
|
+
entry: SessionEntry,
|
|
134
|
+
): SnapcompactCompactionStats | null {
|
|
135
|
+
if (entry.type !== "compaction") return null;
|
|
136
|
+
const { id, timestamp, method, tokensBefore, tokensAfter } = entry as SessionTypedEntry;
|
|
137
|
+
if (method !== "snapcompact" || typeof id !== "string" || id.length === 0) return null;
|
|
138
|
+
if (!isFiniteCount(tokensBefore) || !isFiniteCount(tokensAfter)) return null;
|
|
139
|
+
const ts = typeof timestamp === "string" ? Date.parse(timestamp) : Number.NaN;
|
|
140
|
+
if (!Number.isFinite(ts)) return null;
|
|
141
|
+
return { sessionFile, entryId: id, folder, timestamp: ts, tokensBefore, tokensAfter };
|
|
142
|
+
}
|
|
143
|
+
|
|
124
144
|
/**
|
|
125
145
|
* Concatenate the `text` content blocks of a message payload, skipping every
|
|
126
146
|
* other block type (thinking/reasoning, tool calls, tool results, images).
|
|
@@ -380,6 +400,17 @@ function extractStats(
|
|
|
380
400
|
};
|
|
381
401
|
}
|
|
382
402
|
|
|
403
|
+
/**
|
|
404
|
+
* Stored for a `model_usage` entry whose `purpose` is missing or not a string:
|
|
405
|
+
* a non-null purpose is what keeps the row off the conversation turns.
|
|
406
|
+
*/
|
|
407
|
+
const UNKNOWN_PURPOSE = "unknown";
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Row for a `model_usage` entry (usage of a model call that is not a
|
|
411
|
+
* conversation turn). It keeps the entry's raw `purpose`, which assistant
|
|
412
|
+
* messages lack, and the request timings newer entries carry.
|
|
413
|
+
*/
|
|
383
414
|
function extractModelUsageStats(
|
|
384
415
|
sessionFile: string,
|
|
385
416
|
folder: string,
|
|
@@ -387,7 +418,7 @@ function extractModelUsageStats(
|
|
|
387
418
|
agentType: AgentType,
|
|
388
419
|
): MessageStatsInput | null {
|
|
389
420
|
const timestamp = Date.parse(entry.timestamp);
|
|
390
|
-
|
|
421
|
+
const stats = extractStats(
|
|
391
422
|
sessionFile,
|
|
392
423
|
folder,
|
|
393
424
|
{
|
|
@@ -405,11 +436,16 @@ function extractModelUsageStats(
|
|
|
405
436
|
stopReason: entry.stopReason ?? "stop",
|
|
406
437
|
errorMessage: entry.errorMessage,
|
|
407
438
|
timestamp: Number.isFinite(timestamp) ? timestamp : 0,
|
|
439
|
+
duration: isFiniteCount(entry.duration) ? entry.duration : undefined,
|
|
440
|
+
ttft: isFiniteCount(entry.ttft) ? entry.ttft : undefined,
|
|
408
441
|
},
|
|
409
442
|
},
|
|
410
443
|
undefined,
|
|
411
444
|
agentType,
|
|
412
445
|
);
|
|
446
|
+
if (!stats) return null;
|
|
447
|
+
stats.purpose = typeof entry.purpose === "string" && entry.purpose.length > 0 ? entry.purpose : UNKNOWN_PURPOSE;
|
|
448
|
+
return stats;
|
|
413
449
|
}
|
|
414
450
|
|
|
415
451
|
/** Message timestamp, falling back to the entry's ISO timestamp, then 0. */
|
|
@@ -655,6 +691,7 @@ export interface ParseSessionResult {
|
|
|
655
691
|
userLinks: UserMessageLink[];
|
|
656
692
|
toolCalls: ToolCallStats[];
|
|
657
693
|
toolResults: ToolResultLink[];
|
|
694
|
+
snapcompactCompactions: SnapcompactCompactionStats[];
|
|
658
695
|
spotlight: SpotlightParseRows;
|
|
659
696
|
newOffset: number;
|
|
660
697
|
parserState?: SessionParserState;
|
|
@@ -707,6 +744,7 @@ export async function parseSessionFile(
|
|
|
707
744
|
const userLinks: UserMessageLink[] = [];
|
|
708
745
|
const toolCalls: ToolCallStats[] = [];
|
|
709
746
|
const toolResults: ToolResultLink[] = [];
|
|
747
|
+
const snapcompactCompactions: SnapcompactCompactionStats[] = [];
|
|
710
748
|
// First call per id: the row `INSERT OR IGNORE` keeps, so it can be written with its result.
|
|
711
749
|
const callsById = new Map<string, ToolCallStats>();
|
|
712
750
|
let spotlight = new SpotlightCollector(sessionPath, folder, emptySpotlightState());
|
|
@@ -732,6 +770,11 @@ export async function parseSessionFile(
|
|
|
732
770
|
currentServiceTier = coerceServiceTierByFamily(entry.serviceTier);
|
|
733
771
|
return;
|
|
734
772
|
}
|
|
773
|
+
const compaction = extractSnapcompactCompaction(sessionPath, folder, entry);
|
|
774
|
+
if (compaction) {
|
|
775
|
+
snapcompactCompactions.push(compaction);
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
735
778
|
if (isUserMessage(entry)) {
|
|
736
779
|
const userMsg = extractUserStats(sessionPath, folder, entry, prevUserText);
|
|
737
780
|
if (userMsg) {
|
|
@@ -843,6 +886,7 @@ export async function parseSessionFile(
|
|
|
843
886
|
userLinks: [],
|
|
844
887
|
toolCalls: [],
|
|
845
888
|
toolResults: [],
|
|
889
|
+
snapcompactCompactions: [],
|
|
846
890
|
spotlight: emptySpotlightRows(),
|
|
847
891
|
newOffset: fromOffset,
|
|
848
892
|
};
|
|
@@ -858,6 +902,7 @@ export async function parseSessionFile(
|
|
|
858
902
|
userLinks,
|
|
859
903
|
toolCalls,
|
|
860
904
|
toolResults,
|
|
905
|
+
snapcompactCompactions,
|
|
861
906
|
spotlight: spotlight.rows,
|
|
862
907
|
newOffset,
|
|
863
908
|
reset,
|