@linxiraos/pi-stats 1.4.6 → 1.4.7
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 +11 -1
- package/README.md +18 -18
- package/dist/client/index.js +78 -78
- package/dist/types/chunked-insert.d.ts +32 -0
- package/dist/types/client/traces/SpanDrawer.d.ts +9 -3
- package/dist/types/client/traces/TimelineCanvas.d.ts +3 -1
- package/dist/types/client/traces/TraceView.d.ts +13 -0
- package/dist/types/client/traces/index.d.ts +5 -0
- package/dist/types/client/traces/trace-colors.d.ts +3 -1
- package/dist/types/client/ui/SearchInput.d.ts +2 -1
- package/dist/types/db.d.ts +5 -5
- package/dist/types/parser.d.ts +1 -1
- package/dist/types/port-conflict.d.ts +9 -3
- package/dist/types/server.d.ts +7 -3
- package/dist/types/shared-types.d.ts +3 -2
- package/dist/types/trace.d.ts +27 -1
- package/dist/types/types.d.ts +6 -1
- package/package.json +13 -7
- package/src/chunked-insert.ts +89 -0
- package/src/client/traces/SpanDrawer.tsx +56 -9
- package/src/client/traces/TimelineCanvas.tsx +13 -4
- package/src/client/traces/TraceView.tsx +171 -153
- package/src/client/traces/index.ts +5 -0
- package/src/client/traces/trace-colors.ts +14 -10
- package/src/client/ui/SearchInput.tsx +9 -1
- package/src/db.ts +201 -150
- package/src/parser.ts +14 -5
- package/src/port-conflict.ts +67 -30
- package/src/server.ts +39 -31
- package/src/shared-types.ts +3 -2
- package/src/trace.ts +119 -35
- package/src/types.ts +6 -1
package/src/db.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
} from "@linxiraos/pi-catalog/models";
|
|
12
12
|
import type { ModelCost } from "@linxiraos/pi-catalog/types";
|
|
13
13
|
import { getConfigRootDir, getStatsDbPath, VERSION } from "@linxiraos/pi-utils";
|
|
14
|
+
import { ChunkedInsert } from "./chunked-insert";
|
|
14
15
|
import { classifyAgentType, type ParseSessionResult, type SessionParserState } from "./parser";
|
|
15
16
|
import { ensureRollupSchema, getDailyActivityFromRollup } from "./rollup";
|
|
16
17
|
import type {
|
|
@@ -143,6 +144,17 @@ export async function initDb(): Promise<Database> {
|
|
|
143
144
|
// https://github.com/can1357/oh-my-pi/issues/2421.
|
|
144
145
|
db.run("PRAGMA busy_timeout = 5000");
|
|
145
146
|
db.run("PRAGMA journal_mode = WAL");
|
|
147
|
+
// The database is a derived cache of the transcripts, so WAL's NORMAL sync
|
|
148
|
+
// (fsync only at checkpoints) is safe: a crash can drop the newest batches,
|
|
149
|
+
// which the next sync re-ingests from their unchanged cursors. Rarer, larger
|
|
150
|
+
// checkpoints cut the F_FULLFSYNC stalls macOS pays per checkpoint. The
|
|
151
|
+
// statement journal and temp b-tree every trigger-carrying insert opens stay
|
|
152
|
+
// in memory instead of a temp file, and a 64 MiB page cache (default 8 MiB)
|
|
153
|
+
// keeps more index pages of a multi-GB database resident between batches.
|
|
154
|
+
db.run("PRAGMA synchronous = NORMAL");
|
|
155
|
+
db.run("PRAGMA temp_store = MEMORY");
|
|
156
|
+
db.run("PRAGMA cache_size = -65536");
|
|
157
|
+
db.run("PRAGMA wal_autocheckpoint = 16384");
|
|
146
158
|
|
|
147
159
|
// Whether `messages` predates this init — drives the one-time agent_type
|
|
148
160
|
// backfill below, so it must be sampled before CREATE TABLE adds the table.
|
|
@@ -182,11 +194,17 @@ export async function initDb(): Promise<Database> {
|
|
|
182
194
|
UNIQUE(session_file, entry_id)
|
|
183
195
|
);
|
|
184
196
|
|
|
185
|
-
|
|
186
|
-
|
|
197
|
+
-- Fork-guard identity lookups key on (entry_id, timestamp). Time-first
|
|
198
|
+
-- keeps one transcript's rows in a few neighbouring leaves; entry-first
|
|
199
|
+
-- scattered every insert, delete and lookup across the whole index. The
|
|
200
|
+
-- composite also serves every timestamp range scan.
|
|
201
|
+
DROP INDEX IF EXISTS idx_messages_timestamp;
|
|
202
|
+
DROP INDEX IF EXISTS idx_messages_entry_timestamp;
|
|
203
|
+
CREATE INDEX IF NOT EXISTS idx_messages_timestamp_entry ON messages(timestamp, entry_id);
|
|
187
204
|
CREATE INDEX IF NOT EXISTS idx_messages_model ON messages(model);
|
|
188
205
|
CREATE INDEX IF NOT EXISTS idx_messages_folder ON messages(folder);
|
|
189
|
-
|
|
206
|
+
-- UNIQUE(session_file, entry_id) already indexes session_file lookups.
|
|
207
|
+
DROP INDEX IF EXISTS idx_messages_session;
|
|
190
208
|
CREATE INDEX IF NOT EXISTS idx_messages_timestamp_model_provider ON messages(timestamp, model, provider);
|
|
191
209
|
CREATE INDEX IF NOT EXISTS idx_messages_timestamp_folder ON messages(timestamp, folder);
|
|
192
210
|
CREATE INDEX IF NOT EXISTS idx_messages_stop_reason_timestamp ON messages(stop_reason, timestamp);
|
|
@@ -221,8 +239,9 @@ export async function initDb(): Promise<Database> {
|
|
|
221
239
|
UNIQUE(session_file, entry_id)
|
|
222
240
|
);
|
|
223
241
|
|
|
224
|
-
|
|
225
|
-
|
|
242
|
+
DROP INDEX IF EXISTS idx_user_messages_timestamp;
|
|
243
|
+
DROP INDEX IF EXISTS idx_user_messages_entry_timestamp;
|
|
244
|
+
CREATE INDEX IF NOT EXISTS idx_user_messages_timestamp_entry ON user_messages(timestamp, entry_id);
|
|
226
245
|
CREATE INDEX IF NOT EXISTS idx_user_messages_timestamp_model ON user_messages(timestamp, model, provider);
|
|
227
246
|
|
|
228
247
|
-- Model-side analysis: one row per assistant turn that produced prose.
|
|
@@ -286,8 +305,9 @@ export async function initDb(): Promise<Database> {
|
|
|
286
305
|
UNIQUE(session_file, tool_call_id)
|
|
287
306
|
);
|
|
288
307
|
|
|
289
|
-
|
|
290
|
-
|
|
308
|
+
DROP INDEX IF EXISTS idx_tool_calls_timestamp;
|
|
309
|
+
DROP INDEX IF EXISTS idx_tool_calls_entry_timestamp;
|
|
310
|
+
CREATE INDEX IF NOT EXISTS idx_tool_calls_timestamp_entry ON tool_calls(timestamp, entry_id);
|
|
291
311
|
CREATE INDEX IF NOT EXISTS idx_tool_calls_tool_timestamp ON tool_calls(tool_name, timestamp);
|
|
292
312
|
|
|
293
313
|
CREATE TABLE IF NOT EXISTS meta (
|
|
@@ -398,7 +418,7 @@ export async function initDb(): Promise<Database> {
|
|
|
398
418
|
prose_hash TEXT NOT NULL DEFAULT '',
|
|
399
419
|
UNIQUE(session_file, entry_id)
|
|
400
420
|
);
|
|
401
|
-
CREATE INDEX IF NOT EXISTS
|
|
421
|
+
CREATE INDEX IF NOT EXISTS idx_user_messages_timestamp_entry ON user_messages(timestamp, entry_id);
|
|
402
422
|
CREATE INDEX IF NOT EXISTS idx_user_messages_timestamp_model ON user_messages(timestamp, model, provider);
|
|
403
423
|
`);
|
|
404
424
|
} else if (!userMessageColumns.some(column => column.name === "prose")) {
|
|
@@ -725,6 +745,17 @@ export function setFileOffset(
|
|
|
725
745
|
stmt.run(sessionFile, offset, lastModified, parserState ? JSON.stringify(parserState) : null);
|
|
726
746
|
}
|
|
727
747
|
|
|
748
|
+
/**
|
|
749
|
+
* Run `fn` atomically: inline when the caller already holds a transaction,
|
|
750
|
+
* otherwise in a fresh one. Nesting `db.transaction` would open a savepoint,
|
|
751
|
+
* which copies every page the batch touches into the statement journal; each
|
|
752
|
+
* statement end then rewinds that ever-growing journal, so a long batch
|
|
753
|
+
* degrades quadratically.
|
|
754
|
+
*/
|
|
755
|
+
function atomically<T>(database: Database, fn: () => T): T {
|
|
756
|
+
return database.inTransaction ? fn() : database.transaction(fn)();
|
|
757
|
+
}
|
|
758
|
+
|
|
728
759
|
/** Parsed transcript queued by the sync loop for an atomic database batch. */
|
|
729
760
|
export interface ParsedSession {
|
|
730
761
|
sessionFile: string;
|
|
@@ -954,7 +985,7 @@ export function completeSessionSync(reconcile: boolean): void {
|
|
|
954
985
|
* `provider`, token counts, and `responseId`. The `UNIQUE(session_file,
|
|
955
986
|
* entry_id)` constraint alone keys each row by file, so without the guard
|
|
956
987
|
* below the same provider request would land twice and inflate every
|
|
957
|
-
* aggregate. The
|
|
988
|
+
* aggregate. The {@link ChunkedInsert} fork guard skips inserts whose
|
|
958
989
|
* `(entry_id, timestamp)` already exists under a different `session_file` —
|
|
959
990
|
* first-write-wins across the lineage. Same-file re-syncs still hit the
|
|
960
991
|
* `ON CONFLICT(session_file, entry_id)` upsert below, which re-derives the
|
|
@@ -963,21 +994,39 @@ export function completeSessionSync(reconcile: boolean): void {
|
|
|
963
994
|
*/
|
|
964
995
|
export function insertMessageStats(stats: Iterable<MessageStatsInput>): number {
|
|
965
996
|
if (!db) return 0;
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
997
|
+
const writer = new ChunkedInsert(db, {
|
|
998
|
+
verb: "INSERT",
|
|
999
|
+
table: "messages",
|
|
1000
|
+
columns: [
|
|
1001
|
+
"session_file",
|
|
1002
|
+
"entry_id",
|
|
1003
|
+
"folder",
|
|
1004
|
+
"model",
|
|
1005
|
+
"provider",
|
|
1006
|
+
"api",
|
|
1007
|
+
"timestamp",
|
|
1008
|
+
"duration",
|
|
1009
|
+
"ttft",
|
|
1010
|
+
"stop_reason",
|
|
1011
|
+
"error_message",
|
|
1012
|
+
"input_tokens",
|
|
1013
|
+
"output_tokens",
|
|
1014
|
+
"cache_read_tokens",
|
|
1015
|
+
"cache_write_tokens",
|
|
1016
|
+
"total_tokens",
|
|
1017
|
+
"premium_requests",
|
|
1018
|
+
"cost_input",
|
|
1019
|
+
"cost_output",
|
|
1020
|
+
"cost_cache_read",
|
|
1021
|
+
"cost_cache_write",
|
|
1022
|
+
"cost_total",
|
|
1023
|
+
"cost_no_cache_input",
|
|
1024
|
+
"cost_unpriced",
|
|
1025
|
+
"agent_type",
|
|
1026
|
+
"service_tier",
|
|
1027
|
+
],
|
|
1028
|
+
identity: ["entry_id", "timestamp"],
|
|
1029
|
+
upsert: `ON CONFLICT(session_file, entry_id) DO UPDATE SET
|
|
981
1030
|
premium_requests = MAX(messages.premium_requests, excluded.premium_requests),
|
|
982
1031
|
cost_input = excluded.cost_input,
|
|
983
1032
|
cost_output = excluded.cost_output,
|
|
@@ -986,53 +1035,47 @@ export function insertMessageStats(stats: Iterable<MessageStatsInput>): number {
|
|
|
986
1035
|
cost_total = excluded.cost_total,
|
|
987
1036
|
cost_no_cache_input = excluded.cost_no_cache_input,
|
|
988
1037
|
cost_unpriced = excluded.cost_unpriced,
|
|
989
|
-
service_tier = excluded.service_tier
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
let inserted = 0;
|
|
993
|
-
const insert = db.transaction(() => {
|
|
1038
|
+
service_tier = excluded.service_tier`,
|
|
1039
|
+
});
|
|
1040
|
+
return atomically(db, () => {
|
|
994
1041
|
for (const s of stats) {
|
|
995
1042
|
const { cost, unpriced } = resolveStoredCost(s);
|
|
996
1043
|
const noCacheInputCost = calculateNoCacheInputCost(s.provider, s.model, s.usage, s.timestamp) ?? 0;
|
|
997
|
-
|
|
998
|
-
s.sessionFile,
|
|
999
|
-
s.entryId,
|
|
1000
|
-
s.folder,
|
|
1001
|
-
s.model,
|
|
1002
|
-
s.provider,
|
|
1003
|
-
s.api,
|
|
1004
|
-
s.timestamp,
|
|
1005
|
-
s.duration,
|
|
1006
|
-
s.ttft,
|
|
1007
|
-
s.stopReason,
|
|
1008
|
-
s.errorMessage,
|
|
1009
|
-
s.usage.input,
|
|
1010
|
-
s.usage.output,
|
|
1011
|
-
s.usage.cacheRead,
|
|
1012
|
-
s.usage.cacheWrite,
|
|
1013
|
-
s.usage.totalTokens,
|
|
1014
|
-
s.usage.premiumRequests ?? 0,
|
|
1015
|
-
cost.input,
|
|
1016
|
-
cost.output,
|
|
1017
|
-
cost.cacheRead,
|
|
1018
|
-
cost.cacheWrite,
|
|
1019
|
-
cost.total,
|
|
1020
|
-
noCacheInputCost,
|
|
1021
|
-
unpriced ? 1 : 0,
|
|
1022
|
-
s.agentType,
|
|
1023
|
-
s.serviceTier ?? null,
|
|
1024
|
-
// `WHERE NOT EXISTS` binds: skip when a different session_file
|
|
1025
|
-
// already holds this (entry_id, timestamp).
|
|
1026
|
-
s.entryId,
|
|
1027
|
-
s.timestamp,
|
|
1044
|
+
writer.add(
|
|
1028
1045
|
s.sessionFile,
|
|
1046
|
+
[s.entryId, s.timestamp],
|
|
1047
|
+
[
|
|
1048
|
+
s.sessionFile,
|
|
1049
|
+
s.entryId,
|
|
1050
|
+
s.folder,
|
|
1051
|
+
s.model,
|
|
1052
|
+
s.provider,
|
|
1053
|
+
s.api,
|
|
1054
|
+
s.timestamp,
|
|
1055
|
+
s.duration,
|
|
1056
|
+
s.ttft,
|
|
1057
|
+
s.stopReason,
|
|
1058
|
+
s.errorMessage,
|
|
1059
|
+
s.usage.input,
|
|
1060
|
+
s.usage.output,
|
|
1061
|
+
s.usage.cacheRead,
|
|
1062
|
+
s.usage.cacheWrite,
|
|
1063
|
+
s.usage.totalTokens,
|
|
1064
|
+
s.usage.premiumRequests ?? 0,
|
|
1065
|
+
cost.input,
|
|
1066
|
+
cost.output,
|
|
1067
|
+
cost.cacheRead,
|
|
1068
|
+
cost.cacheWrite,
|
|
1069
|
+
cost.total,
|
|
1070
|
+
noCacheInputCost,
|
|
1071
|
+
unpriced ? 1 : 0,
|
|
1072
|
+
s.agentType,
|
|
1073
|
+
s.serviceTier ?? null,
|
|
1074
|
+
],
|
|
1029
1075
|
);
|
|
1030
|
-
if (result.changes > 0) inserted++;
|
|
1031
1076
|
}
|
|
1077
|
+
return writer.finish();
|
|
1032
1078
|
});
|
|
1033
|
-
|
|
1034
|
-
insert();
|
|
1035
|
-
return inserted;
|
|
1036
1079
|
}
|
|
1037
1080
|
|
|
1038
1081
|
/**
|
|
@@ -1446,60 +1489,66 @@ export function markSessionBackfillsComplete(): void {
|
|
|
1446
1489
|
|
|
1447
1490
|
/**
|
|
1448
1491
|
* Insert user-message stats. Idempotent via UNIQUE(session_file, entry_id).
|
|
1449
|
-
* The
|
|
1450
|
-
*
|
|
1451
|
-
*
|
|
1492
|
+
* The fork guard matches {@link insertMessageStats}: forks copy user entries
|
|
1493
|
+
* verbatim into the child JSONL, so the same `(entry_id, timestamp)` must not
|
|
1494
|
+
* land twice across different session files.
|
|
1452
1495
|
*/
|
|
1453
1496
|
export function insertUserMessageStats(stats: Iterable<UserMessageStats>): number {
|
|
1454
1497
|
if (!db) return 0;
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1498
|
+
const writer = new ChunkedInsert(db, {
|
|
1499
|
+
verb: "INSERT OR IGNORE",
|
|
1500
|
+
table: "user_messages",
|
|
1501
|
+
columns: [
|
|
1502
|
+
"session_file",
|
|
1503
|
+
"entry_id",
|
|
1504
|
+
"folder",
|
|
1505
|
+
"timestamp",
|
|
1506
|
+
"model",
|
|
1507
|
+
"provider",
|
|
1508
|
+
"chars",
|
|
1509
|
+
"words",
|
|
1510
|
+
"yelling",
|
|
1511
|
+
"profanity",
|
|
1512
|
+
"anguish",
|
|
1513
|
+
"negation",
|
|
1514
|
+
"repetition",
|
|
1515
|
+
"blame",
|
|
1516
|
+
"emphasis",
|
|
1517
|
+
"unsupported_script",
|
|
1518
|
+
"prose",
|
|
1519
|
+
"prose_hash",
|
|
1520
|
+
],
|
|
1521
|
+
identity: ["entry_id", "timestamp"],
|
|
1522
|
+
});
|
|
1523
|
+
return atomically(db, () => {
|
|
1472
1524
|
for (const s of stats) {
|
|
1473
|
-
|
|
1474
|
-
s.sessionFile,
|
|
1475
|
-
s.entryId,
|
|
1476
|
-
s.folder,
|
|
1477
|
-
s.timestamp,
|
|
1478
|
-
s.model,
|
|
1479
|
-
s.provider,
|
|
1480
|
-
s.chars,
|
|
1481
|
-
s.words,
|
|
1482
|
-
s.yelling,
|
|
1483
|
-
s.profanity,
|
|
1484
|
-
s.anguish,
|
|
1485
|
-
s.negation,
|
|
1486
|
-
s.repetition,
|
|
1487
|
-
s.blame,
|
|
1488
|
-
s.emphasis,
|
|
1489
|
-
s.unsupportedScript,
|
|
1490
|
-
s.prose,
|
|
1491
|
-
s.proseHash,
|
|
1492
|
-
// `WHERE NOT EXISTS` binds: skip when a different session_file
|
|
1493
|
-
// already holds this (entry_id, timestamp).
|
|
1494
|
-
s.entryId,
|
|
1495
|
-
s.timestamp,
|
|
1525
|
+
writer.add(
|
|
1496
1526
|
s.sessionFile,
|
|
1527
|
+
[s.entryId, s.timestamp],
|
|
1528
|
+
[
|
|
1529
|
+
s.sessionFile,
|
|
1530
|
+
s.entryId,
|
|
1531
|
+
s.folder,
|
|
1532
|
+
s.timestamp,
|
|
1533
|
+
s.model,
|
|
1534
|
+
s.provider,
|
|
1535
|
+
s.chars,
|
|
1536
|
+
s.words,
|
|
1537
|
+
s.yelling,
|
|
1538
|
+
s.profanity,
|
|
1539
|
+
s.anguish,
|
|
1540
|
+
s.negation,
|
|
1541
|
+
s.repetition,
|
|
1542
|
+
s.blame,
|
|
1543
|
+
s.emphasis,
|
|
1544
|
+
s.unsupportedScript,
|
|
1545
|
+
s.prose,
|
|
1546
|
+
s.proseHash,
|
|
1547
|
+
],
|
|
1497
1548
|
);
|
|
1498
|
-
if (result.changes > 0) inserted++;
|
|
1499
1549
|
}
|
|
1550
|
+
return writer.finish();
|
|
1500
1551
|
});
|
|
1501
|
-
insert();
|
|
1502
|
-
return inserted;
|
|
1503
1552
|
}
|
|
1504
1553
|
|
|
1505
1554
|
/**
|
|
@@ -1577,13 +1626,12 @@ export function updateUserMessageLinks(links: Iterable<UserMessageLink>): number
|
|
|
1577
1626
|
`);
|
|
1578
1627
|
|
|
1579
1628
|
let updated = 0;
|
|
1580
|
-
|
|
1629
|
+
atomically(db, () => {
|
|
1581
1630
|
for (const link of links) {
|
|
1582
1631
|
const result = stmt.run(link.model, link.provider, link.sessionFile, link.entryId);
|
|
1583
1632
|
if (result.changes > 0) updated++;
|
|
1584
1633
|
}
|
|
1585
1634
|
});
|
|
1586
|
-
apply();
|
|
1587
1635
|
return updated;
|
|
1588
1636
|
}
|
|
1589
1637
|
|
|
@@ -1915,7 +1963,7 @@ export function upsertFrustrationVerdicts(verdicts: readonly FrustrationVerdict[
|
|
|
1915
1963
|
|
|
1916
1964
|
/**
|
|
1917
1965
|
* Insert tool-call rows. Idempotent via UNIQUE(session_file, tool_call_id);
|
|
1918
|
-
* the
|
|
1966
|
+
* the fork guard mirrors {@link insertMessageStats}: forked
|
|
1919
1967
|
* sessions deep-copy assistant entries (same `entry_id`, `timestamp`, and
|
|
1920
1968
|
* tool-call ids under a new file), so first-write-wins across the lineage
|
|
1921
1969
|
* keeps aggregates from double counting. Keyed on the assistant entry
|
|
@@ -1924,46 +1972,50 @@ export function upsertFrustrationVerdicts(verdicts: readonly FrustrationVerdict[
|
|
|
1924
1972
|
*/
|
|
1925
1973
|
export function insertToolCalls(calls: Iterable<ToolCallStats>): number {
|
|
1926
1974
|
if (!db) return 0;
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1975
|
+
const writer = new ChunkedInsert(db, {
|
|
1976
|
+
verb: "INSERT OR IGNORE",
|
|
1977
|
+
table: "tool_calls",
|
|
1978
|
+
columns: [
|
|
1979
|
+
"session_file",
|
|
1980
|
+
"entry_id",
|
|
1981
|
+
"tool_call_id",
|
|
1982
|
+
"folder",
|
|
1983
|
+
"tool_name",
|
|
1984
|
+
"model",
|
|
1985
|
+
"provider",
|
|
1986
|
+
"timestamp",
|
|
1987
|
+
"agent_type",
|
|
1988
|
+
"calls_in_turn",
|
|
1989
|
+
"args_chars",
|
|
1990
|
+
"result_chars",
|
|
1991
|
+
"is_error",
|
|
1992
|
+
],
|
|
1993
|
+
identity: ["entry_id", "timestamp", "tool_call_id"],
|
|
1994
|
+
});
|
|
1995
|
+
return atomically(db, () => {
|
|
1942
1996
|
for (const c of calls) {
|
|
1943
|
-
|
|
1944
|
-
c.sessionFile,
|
|
1945
|
-
c.entryId,
|
|
1946
|
-
c.toolCallId,
|
|
1947
|
-
c.folder,
|
|
1948
|
-
c.toolName,
|
|
1949
|
-
c.model,
|
|
1950
|
-
c.provider,
|
|
1951
|
-
c.timestamp,
|
|
1952
|
-
c.agentType,
|
|
1953
|
-
c.callsInTurn,
|
|
1954
|
-
c.argsChars,
|
|
1955
|
-
// `WHERE NOT EXISTS` binds: skip when a different session_file
|
|
1956
|
-
// already holds this (entry_id, timestamp, tool_call_id).
|
|
1957
|
-
c.entryId,
|
|
1958
|
-
c.timestamp,
|
|
1959
|
-
c.toolCallId,
|
|
1997
|
+
writer.add(
|
|
1960
1998
|
c.sessionFile,
|
|
1999
|
+
[c.entryId, c.timestamp, c.toolCallId],
|
|
2000
|
+
[
|
|
2001
|
+
c.sessionFile,
|
|
2002
|
+
c.entryId,
|
|
2003
|
+
c.toolCallId,
|
|
2004
|
+
c.folder,
|
|
2005
|
+
c.toolName,
|
|
2006
|
+
c.model,
|
|
2007
|
+
c.provider,
|
|
2008
|
+
c.timestamp,
|
|
2009
|
+
c.agentType,
|
|
2010
|
+
c.callsInTurn,
|
|
2011
|
+
c.argsChars,
|
|
2012
|
+
c.resultChars ?? null,
|
|
2013
|
+
c.isError === undefined ? null : c.isError ? 1 : 0,
|
|
2014
|
+
],
|
|
1961
2015
|
);
|
|
1962
|
-
if (result.changes > 0) inserted++;
|
|
1963
2016
|
}
|
|
2017
|
+
return writer.finish();
|
|
1964
2018
|
});
|
|
1965
|
-
insert();
|
|
1966
|
-
return inserted;
|
|
1967
2019
|
}
|
|
1968
2020
|
|
|
1969
2021
|
/**
|
|
@@ -1983,12 +2035,11 @@ export function updateToolResults(links: Iterable<ToolResultLink>): number {
|
|
|
1983
2035
|
`);
|
|
1984
2036
|
|
|
1985
2037
|
let updated = 0;
|
|
1986
|
-
|
|
2038
|
+
atomically(db, () => {
|
|
1987
2039
|
for (const link of links) {
|
|
1988
2040
|
const result = stmt.run(link.resultChars, link.isError ? 1 : 0, link.sessionFile, link.toolCallId);
|
|
1989
2041
|
updated += result.changes;
|
|
1990
2042
|
}
|
|
1991
2043
|
});
|
|
1992
|
-
apply();
|
|
1993
2044
|
return updated;
|
|
1994
2045
|
}
|
package/src/parser.ts
CHANGED
|
@@ -620,6 +620,8 @@ export async function parseSessionFile(
|
|
|
620
620
|
const userLinks: UserMessageLink[] = [];
|
|
621
621
|
const toolCalls: ToolCallStats[] = [];
|
|
622
622
|
const toolResults: ToolResultLink[] = [];
|
|
623
|
+
// First call per id: the row `INSERT OR IGNORE` keeps, so it can be written with its result.
|
|
624
|
+
const callsById = new Map<string, ToolCallStats>();
|
|
623
625
|
|
|
624
626
|
// The previous user message, for the whole-message repetition signal. An
|
|
625
627
|
// incremental parse starts mid-session, so the first message of a resumed
|
|
@@ -649,9 +651,13 @@ export async function parseSessionFile(
|
|
|
649
651
|
}
|
|
650
652
|
if (isToolResultMessage(entry)) {
|
|
651
653
|
const link = extractToolResultLink(sessionPath, entry);
|
|
652
|
-
if (link)
|
|
653
|
-
|
|
654
|
-
|
|
654
|
+
if (!link) return;
|
|
655
|
+
toolResults.push(link);
|
|
656
|
+
if (link.isError) pendingToolErrors++;
|
|
657
|
+
const call = callsById.get(link.toolCallId);
|
|
658
|
+
if (call && call.resultChars === undefined) {
|
|
659
|
+
call.resultChars = link.resultChars;
|
|
660
|
+
call.isError = link.isError;
|
|
655
661
|
}
|
|
656
662
|
return;
|
|
657
663
|
}
|
|
@@ -663,7 +669,10 @@ export async function parseSessionFile(
|
|
|
663
669
|
if (isAssistantMessage(entry)) {
|
|
664
670
|
const msgStats = extractStats(sessionPath, folder, entry, currentServiceTier, agentType);
|
|
665
671
|
if (msgStats) stats.push(msgStats);
|
|
666
|
-
|
|
672
|
+
for (const call of extractToolCalls(sessionPath, folder, entry, agentType)) {
|
|
673
|
+
toolCalls.push(call);
|
|
674
|
+
if (!callsById.has(call.toolCallId)) callsById.set(call.toolCallId, call);
|
|
675
|
+
}
|
|
667
676
|
const textStats = extractAssistantTextStats(
|
|
668
677
|
sessionPath,
|
|
669
678
|
folder,
|
|
@@ -785,7 +794,7 @@ export async function listSessionFolders(): Promise<string[]> {
|
|
|
785
794
|
* transcripts, never transcripts of their own; a killed run can leave one
|
|
786
795
|
* behind until the next `zetacode gc --compress --apply` removes it.
|
|
787
796
|
*/
|
|
788
|
-
export const COMPRESS_SCRATCH_PREFIX = ".
|
|
797
|
+
export const COMPRESS_SCRATCH_PREFIX = ".zeta-gc-compress-";
|
|
789
798
|
|
|
790
799
|
/** Whether `relativePath` (from any ancestor directory) lies inside a compress scratch directory. */
|
|
791
800
|
export function isCompressScratchPath(relativePath: string): boolean {
|
package/src/port-conflict.ts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import type { Dirent } from "node:fs";
|
|
2
2
|
import * as fs from "node:fs/promises";
|
|
3
3
|
import * as path from "node:path";
|
|
4
|
-
import { $which } from "@linxiraos/pi-utils";
|
|
4
|
+
import { $which, logger } from "@linxiraos/pi-utils";
|
|
5
5
|
import { $ } from "bun";
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Upper bound on the identity probe. A live dashboard ingests on its main thread
|
|
9
|
+
* (serially on macOS), which stalls its responses for over a second on large
|
|
10
|
+
* histories; giving up sooner mistakes a busy dashboard for a hung listener.
|
|
11
|
+
*/
|
|
12
|
+
const STATS_PROBE_TIMEOUT_MS = 3_000;
|
|
8
13
|
const PROCESS_EXIT_POLL_MS = 50;
|
|
9
14
|
const PROCESS_EXIT_POLLS = 10;
|
|
10
15
|
const STATS_RUNTIME_IMAGES: Record<string, true> = {
|
|
@@ -35,15 +40,29 @@ export const STATS_DASHBOARD_SECURITY_VERSION = "3";
|
|
|
35
40
|
/** IPv4 loopback address shared by the dashboard server and reuse probe. */
|
|
36
41
|
export const STATS_DASHBOARD_HOSTNAME = "127.0.0.1";
|
|
37
42
|
|
|
38
|
-
|
|
43
|
+
/**
|
|
44
|
+
* What answers on the dashboard port:
|
|
45
|
+
* - `reusable`: a current dashboard bound to the requested host.
|
|
46
|
+
* - `replaceable`: an older dashboard this version may upgrade.
|
|
47
|
+
* - `occupied`: any other HTTP answer.
|
|
48
|
+
* - `unresponsive`: accepted the connection but did not answer in time (busy or hung).
|
|
49
|
+
* - `unreachable`: the connection failed, typically because nothing listens there.
|
|
50
|
+
*/
|
|
51
|
+
type StatsDashboardProbe = "reusable" | "replaceable" | "occupied" | "unresponsive" | "unreachable";
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* How {@link startServer} proceeds with the requested port: bind it, reuse the
|
|
55
|
+
* dashboard already serving it, or fall back to an ephemeral port because the
|
|
56
|
+
* holder is neither reusable nor safe to stop.
|
|
57
|
+
*/
|
|
58
|
+
export type StatsPortClaim = "bind" | "reuse" | "fallback";
|
|
39
59
|
|
|
40
60
|
async function probeStatsDashboard(port: number, hostname: string): Promise<StatsDashboardProbe> {
|
|
41
61
|
const probeHostname = hostname === "0.0.0.0" ? STATS_DASHBOARD_HOSTNAME : hostname === "::" ? "::1" : hostname;
|
|
42
62
|
const urlHostname = probeHostname.includes(":") ? `[${probeHostname}]` : probeHostname;
|
|
63
|
+
const signal = AbortSignal.timeout(STATS_PROBE_TIMEOUT_MS);
|
|
43
64
|
try {
|
|
44
|
-
const response = await fetch(`http://${urlHostname}:${port}/api/stats/models`, {
|
|
45
|
-
signal: AbortSignal.timeout(STATS_PROBE_TIMEOUT_MS),
|
|
46
|
-
});
|
|
65
|
+
const response = await fetch(`http://${urlHostname}:${port}/api/stats/models`, { signal });
|
|
47
66
|
const dashboardVersionHeader = response.headers.get(STATS_DASHBOARD_HEADER);
|
|
48
67
|
const dashboardVersion = dashboardVersionHeader === null ? Number.NaN : Number(dashboardVersionHeader);
|
|
49
68
|
// Never replace a newer dashboard: an older CLI must not downgrade it.
|
|
@@ -61,7 +80,7 @@ async function probeStatsDashboard(port: number, hostname: string): Promise<Stat
|
|
|
61
80
|
if (reusable) return "reusable";
|
|
62
81
|
return replaceable ? "replaceable" : "occupied";
|
|
63
82
|
} catch {
|
|
64
|
-
return "unreachable";
|
|
83
|
+
return signal.aborted ? "unresponsive" : "unreachable";
|
|
65
84
|
}
|
|
66
85
|
}
|
|
67
86
|
|
|
@@ -236,13 +255,16 @@ async function terminatePortHolder(holder: PortHolder): Promise<void> {
|
|
|
236
255
|
await Bun.sleep(PROCESS_EXIT_POLL_MS);
|
|
237
256
|
}
|
|
238
257
|
|
|
239
|
-
|
|
258
|
+
/**
|
|
259
|
+
* Stop the stats dashboard answering `probe` on `port` so it can be rebound.
|
|
260
|
+
* Holders that cannot be positively identified as a zeta stats dashboard, or
|
|
261
|
+
* that refuse to stop, are left running and yield `"fallback"`.
|
|
262
|
+
*/
|
|
263
|
+
async function reclaimStatsPort(port: number, probe: "replaceable" | "occupied"): Promise<StatsPortClaim> {
|
|
240
264
|
const holder = await findPortHolder(port);
|
|
241
|
-
if (!holder) {
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
if (holder.pid === process.pid) {
|
|
245
|
-
throw new Error(`Port ${port} is held by the current process (${holder.image}, PID ${holder.pid}).`);
|
|
265
|
+
if (!holder || holder.pid === process.pid) {
|
|
266
|
+
logger.debug("Stats dashboard port holder not reclaimable", { port, holder });
|
|
267
|
+
return "fallback";
|
|
246
268
|
}
|
|
247
269
|
|
|
248
270
|
const normalizedImage = holder.image
|
|
@@ -258,33 +280,48 @@ async function reclaimStatsPort(port: number, hasDashboardIdentity = false): Pro
|
|
|
258
280
|
((normalizedImage === "zetacode" || normalizedImage === "omp") &&
|
|
259
281
|
/(?:^|\s)stats(?:\s|$)/.test(normalizedCommand)) ||
|
|
260
282
|
/(?:^|\/)(?:zetacode|omp)(?:\.exe)?["'\s]+stats(?:["'\s]|$)/.test(normalizedCommand);
|
|
283
|
+
const hasDashboardIdentity = probe === "replaceable";
|
|
261
284
|
if (!STATS_RUNTIME_IMAGES[normalizedImage] || (!hasStatsIdentity && !hasDashboardIdentity)) {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
);
|
|
285
|
+
logger.debug("Stats dashboard port held by an unidentified process", { port, holder });
|
|
286
|
+
return "fallback";
|
|
265
287
|
}
|
|
266
288
|
|
|
267
|
-
|
|
268
|
-
|
|
289
|
+
try {
|
|
290
|
+
await terminatePortHolder(holder);
|
|
291
|
+
} catch (error) {
|
|
292
|
+
logger.warn("Failed to stop stale stats dashboard", { port, pid: holder.pid, error: String(error) });
|
|
293
|
+
return "fallback";
|
|
294
|
+
}
|
|
295
|
+
return "bind";
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function claimStatsPort(port: number, hostname: string, ifUnreachable: StatsPortClaim): Promise<StatsPortClaim> {
|
|
299
|
+
const probe = await probeStatsDashboard(port, hostname);
|
|
300
|
+
switch (probe) {
|
|
301
|
+
case "reusable":
|
|
302
|
+
return "reuse";
|
|
303
|
+
case "replaceable":
|
|
304
|
+
case "occupied":
|
|
305
|
+
return reclaimStatsPort(port, probe);
|
|
306
|
+
case "unresponsive":
|
|
307
|
+
// Busy or hung: a dashboard stalled mid-ingest must never be stopped.
|
|
308
|
+
return "fallback";
|
|
309
|
+
case "unreachable":
|
|
310
|
+
return ifUnreachable;
|
|
311
|
+
}
|
|
269
312
|
}
|
|
270
313
|
|
|
271
314
|
/**
|
|
272
|
-
* Reuse a
|
|
315
|
+
* Reuse a current dashboard, or upgrade an older one, before binding.
|
|
273
316
|
* The preflight is needed on platforms that permit wildcard and loopback-specific
|
|
274
317
|
* listeners to coexist on one port.
|
|
275
318
|
*/
|
|
276
|
-
export async function prepareStatsPort(port: number, hostname = STATS_DASHBOARD_HOSTNAME): Promise<
|
|
277
|
-
if (port === 0) return "
|
|
278
|
-
|
|
279
|
-
if (probe === "reusable") return "reuse";
|
|
280
|
-
if (probe === "replaceable") return reclaimStatsPort(port, true);
|
|
281
|
-
if (probe === "occupied") return reclaimStatsPort(port);
|
|
282
|
-
return "retry";
|
|
319
|
+
export async function prepareStatsPort(port: number, hostname = STATS_DASHBOARD_HOSTNAME): Promise<StatsPortClaim> {
|
|
320
|
+
if (port === 0) return "bind";
|
|
321
|
+
return claimStatsPort(port, hostname, "bind");
|
|
283
322
|
}
|
|
284
323
|
|
|
285
324
|
/** Reuse or reclaim a listener found after the server bind reports EADDRINUSE. */
|
|
286
|
-
export async function recoverStatsPort(port: number, hostname = STATS_DASHBOARD_HOSTNAME): Promise<
|
|
287
|
-
|
|
288
|
-
if (probe === "reusable") return "reuse";
|
|
289
|
-
return reclaimStatsPort(port, probe === "replaceable");
|
|
325
|
+
export async function recoverStatsPort(port: number, hostname = STATS_DASHBOARD_HOSTNAME): Promise<StatsPortClaim> {
|
|
326
|
+
return claimStatsPort(port, hostname, "fallback");
|
|
290
327
|
}
|