@laoyuehanni/dsh-token-usage 0.4.2 → 0.4.4-rc.1
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/README.md +8 -7
- package/README.zh.md +8 -7
- package/lib/client/SessionTable.d.ts.map +1 -1
- package/lib/client/SessionTable.js +10 -4
- package/lib/client/SessionTable.js.map +1 -1
- package/lib/client/TokenUsageCard.d.ts +7 -2
- package/lib/client/TokenUsageCard.d.ts.map +1 -1
- package/lib/client/TokenUsageCard.js +15 -5
- package/lib/client/TokenUsageCard.js.map +1 -1
- package/lib/client/TokenUsageSection.d.ts +9 -5
- package/lib/client/TokenUsageSection.d.ts.map +1 -1
- package/lib/client/TokenUsageSection.js +44 -16
- package/lib/client/TokenUsageSection.js.map +1 -1
- package/lib/client/TrendChart.d.ts +1 -1
- package/lib/client/TrendChart.d.ts.map +1 -1
- package/lib/client/TrendChart.js +39 -15
- package/lib/client/TrendChart.js.map +1 -1
- package/lib/client/UsageView.js +2 -2
- package/lib/client/UsageView.js.map +1 -1
- package/lib/client/card-form.d.ts +33 -4
- package/lib/client/card-form.d.ts.map +1 -1
- package/lib/client/card-form.js +20 -8
- package/lib/client/card-form.js.map +1 -1
- package/lib/client/format.d.ts.map +1 -1
- package/lib/client/format.js +12 -4
- package/lib/client/format.js.map +1 -1
- package/lib/client/index.d.ts +18 -3
- package/lib/client/index.d.ts.map +1 -1
- package/lib/client/index.js +137 -25
- package/lib/client/index.js.map +1 -1
- package/lib/client/locales.d.ts +11 -2
- package/lib/client/locales.d.ts.map +1 -1
- package/lib/client/locales.js +22 -4
- package/lib/client/locales.js.map +1 -1
- package/lib/client/trend-chart/index.d.ts +1 -1
- package/lib/client/trend-chart/index.d.ts.map +1 -1
- package/lib/client/trend-chart/index.js +1 -1
- package/lib/client/trend-chart/index.js.map +1 -1
- package/lib/client/trend-chart/path.d.ts +46 -0
- package/lib/client/trend-chart/path.d.ts.map +1 -1
- package/lib/client/trend-chart/path.js +140 -0
- package/lib/client/trend-chart/path.js.map +1 -1
- package/lib/client/use-color-scheme.d.ts +6 -0
- package/lib/client/use-color-scheme.d.ts.map +1 -1
- package/lib/client/use-color-scheme.js +53 -1
- package/lib/client/use-color-scheme.js.map +1 -1
- package/lib/client.js +553 -115
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +30 -52
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +152 -143
- package/lib/index.js.map +1 -1
- package/lib/pricing.d.ts +36 -0
- package/lib/pricing.d.ts.map +1 -1
- package/lib/pricing.js +45 -4
- package/lib/pricing.js.map +1 -1
- package/lib/stats-route.d.ts.map +1 -1
- package/lib/stats-route.js +9 -7
- package/lib/stats-route.js.map +1 -1
- package/lib/stats.d.ts +23 -9
- package/lib/stats.d.ts.map +1 -1
- package/lib/stats.js +56 -22
- package/lib/stats.js.map +1 -1
- package/lib/sync-state.d.ts +17 -6
- package/lib/sync-state.d.ts.map +1 -1
- package/lib/sync-state.js +28 -6
- package/lib/sync-state.js.map +1 -1
- package/lib/sync.d.ts +102 -16
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js +121 -13
- package/lib/sync.js.map +1 -1
- package/lib/usage-log.d.ts +49 -0
- package/lib/usage-log.d.ts.map +1 -1
- package/lib/usage-log.js +239 -1
- package/lib/usage-log.js.map +1 -1
- package/lib/usage-record.d.ts +20 -2
- package/lib/usage-record.d.ts.map +1 -1
- package/lib/usage-record.js +74 -3
- package/lib/usage-record.js.map +1 -1
- package/lib/wire.d.ts +3 -1
- package/lib/wire.d.ts.map +1 -1
- package/lib/wire.js +1 -1
- package/package.json +42 -36
package/lib/sync.js
CHANGED
|
@@ -11,10 +11,64 @@
|
|
|
11
11
|
* the run — one unreadable file must not keep the rest of the history
|
|
12
12
|
* out of the ledger.
|
|
13
13
|
*
|
|
14
|
+
* Reads go through whichever persistence seam the running host exposes: the
|
|
15
|
+
* handle generation (`dsh` 0.1.3-alpha.1 and later, `open`/`read`/`close`) or
|
|
16
|
+
* the older inspect generation (`dsh` 0.1.2-rc.1 and earlier, `inspect`). One
|
|
17
|
+
* probe per run picks the seam, so a single build walks history on both.
|
|
18
|
+
*
|
|
14
19
|
* @module token-usage/sync
|
|
15
20
|
*/
|
|
16
21
|
import { markInitialized, markMetaSynced, readSyncState } from "./sync-state.js";
|
|
17
|
-
import { modelOfEvent, recordOfEvent } from "./usage-record.js";
|
|
22
|
+
import { extractFirstTokenTimeFromStream, modelOfEvent, recordOfEvent } from "./usage-record.js";
|
|
23
|
+
/**
|
|
24
|
+
* Probe which persistence seam the running host exposes and normalize it.
|
|
25
|
+
*
|
|
26
|
+
* The probe runs once per sync, never once per session: a host does not change
|
|
27
|
+
* generation mid-process, and probing per session would report a wholesale
|
|
28
|
+
* mismatch as N individually unreadable sessions — precisely the silent
|
|
29
|
+
* failure the two seams invite.
|
|
30
|
+
* @param persistence - the host's `ctx.sessionPersistence` (or a test twin).
|
|
31
|
+
* @returns the normalized reader.
|
|
32
|
+
* @throws {Error} when the persistence exposes neither seam (a host older or
|
|
33
|
+
* newer than either generation), which must fail loudly rather than report
|
|
34
|
+
* every session as unreadable.
|
|
35
|
+
*/
|
|
36
|
+
export function readerOf(persistence) {
|
|
37
|
+
const { open, inspect } = persistence;
|
|
38
|
+
const idOf = (entry) => 'header' in entry ? entry.header.id : entry.id;
|
|
39
|
+
if (typeof open === 'function') {
|
|
40
|
+
return {
|
|
41
|
+
async list(signal) {
|
|
42
|
+
return (await persistence.list(signal === undefined ? {} : { signal })).map(idOf);
|
|
43
|
+
},
|
|
44
|
+
async read(id, signal) {
|
|
45
|
+
const handle = await open.call(persistence, id, 'read', signal === undefined ? {} : { signal });
|
|
46
|
+
try {
|
|
47
|
+
const { events } = await handle.read();
|
|
48
|
+
return { events, meta: handle.header };
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
// Best-effort teardown: the rows are already collected, so a failing
|
|
52
|
+
// close must not turn a good read into an unreadable session. It
|
|
53
|
+
// still has to run on every path — the host counts a leaked read
|
|
54
|
+
// handle as a resource leak.
|
|
55
|
+
await handle.close().catch(() => { });
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
if (typeof inspect === 'function') {
|
|
61
|
+
return {
|
|
62
|
+
async list(signal) {
|
|
63
|
+
return (await persistence.list(signal)).map(idOf);
|
|
64
|
+
},
|
|
65
|
+
async read(id, signal) {
|
|
66
|
+
return await inspect.call(persistence, id, signal);
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
throw new Error('token-usage: sessionPersistence exposes neither open() (dsh 0.1.3-alpha.1+) nor inspect() (dsh <= 0.1.2-rc.1)');
|
|
71
|
+
}
|
|
18
72
|
/**
|
|
19
73
|
* The latest-wins `session/title` text of one event, or undefined: the
|
|
20
74
|
* event type is host-merged (`dsh-session-title`), so the plugin reads the
|
|
@@ -41,21 +95,32 @@ export function titleOfEvent(event) {
|
|
|
41
95
|
*/
|
|
42
96
|
export async function syncHistory(deps, onTick, signal) {
|
|
43
97
|
await deps.log.scan();
|
|
44
|
-
|
|
98
|
+
// Snapshot before the walk: only rows already saved are reconcile
|
|
99
|
+
// candidates, so a request landing live mid-walk is never deleted.
|
|
100
|
+
const eligible = deps.log.ids();
|
|
101
|
+
const reader = readerOf(deps.persistence);
|
|
102
|
+
const sessions = await reader.list(signal);
|
|
45
103
|
let added = 0;
|
|
46
104
|
let skipped = 0;
|
|
105
|
+
let removed = 0;
|
|
47
106
|
let failedSessions = 0;
|
|
48
107
|
const total = sessions.length;
|
|
49
108
|
let processed = 0;
|
|
50
|
-
|
|
51
|
-
|
|
109
|
+
/** Every id this walk reproduces; the reconcile pass keeps exactly these. */
|
|
110
|
+
const reproduced = new Set();
|
|
111
|
+
/** Sessions this walk read in full. Only their rows may be reconciled: a
|
|
112
|
+
* row whose session is missing from the list (deleted, or hidden behind a
|
|
113
|
+
* header this build cannot read) is never dropped for its absence. */
|
|
114
|
+
const readable = new Set();
|
|
115
|
+
onTick?.({ processed, total, added, skipped, removed, failedSessions });
|
|
116
|
+
for (const id of sessions) {
|
|
52
117
|
signal?.throwIfAborted();
|
|
53
118
|
// One unreadable session log (a format the current dsh build rejects,
|
|
54
119
|
// a torn file, …) must not abort the whole walk: skip the session,
|
|
55
120
|
// report it, and let the rest of the history land.
|
|
56
121
|
let inspection;
|
|
57
122
|
try {
|
|
58
|
-
inspection = await
|
|
123
|
+
inspection = await reader.read(id, signal);
|
|
59
124
|
}
|
|
60
125
|
catch (error) {
|
|
61
126
|
// A cancellation is the caller's (or the host read path's) abort —
|
|
@@ -64,10 +129,13 @@ export async function syncHistory(deps, onTick, signal) {
|
|
|
64
129
|
throw error;
|
|
65
130
|
failedSessions += 1;
|
|
66
131
|
processed += 1;
|
|
67
|
-
deps.onSessionFailure?.(
|
|
68
|
-
onTick?.({ processed, total, added, skipped, failedSessions });
|
|
132
|
+
deps.onSessionFailure?.(id, error);
|
|
133
|
+
onTick?.({ processed, total, added, skipped, removed, failedSessions });
|
|
69
134
|
continue;
|
|
70
135
|
}
|
|
136
|
+
// The session was read in full: this walk is now the authority for what
|
|
137
|
+
// the ledger must hold, so its stale coordinates become droppable.
|
|
138
|
+
readable.add(id);
|
|
71
139
|
// Last-known route model of this session: failure rows need a model to
|
|
72
140
|
// attribute, and turn/end names none, so the walk follows the same
|
|
73
141
|
// request/context + assistant/message events the live recorder does.
|
|
@@ -76,17 +144,51 @@ export async function syncHistory(deps, onTick, signal) {
|
|
|
76
144
|
// seen is the current title — a rename, an auto-generated title, and a
|
|
77
145
|
// fallback all land as the same append, one fold covers every source.
|
|
78
146
|
let title;
|
|
147
|
+
let openStep = null;
|
|
79
148
|
for (const event of inspection.events) {
|
|
80
149
|
signal?.throwIfAborted();
|
|
150
|
+
if (event.type === 'step/start') {
|
|
151
|
+
openStep = {
|
|
152
|
+
turn: event.data.turn,
|
|
153
|
+
step: event.data.step,
|
|
154
|
+
startTime: event.time,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
81
157
|
const revealed = modelOfEvent(event);
|
|
82
158
|
if (revealed !== undefined)
|
|
83
159
|
model = revealed;
|
|
84
160
|
const revealedTitle = titleOfEvent(event);
|
|
85
161
|
if (revealedTitle !== undefined)
|
|
86
162
|
title = revealedTitle;
|
|
87
|
-
|
|
163
|
+
let timing;
|
|
164
|
+
if (event.type === 'assistant/message'
|
|
165
|
+
&& openStep !== null
|
|
166
|
+
&& openStep.turn === event.data.turn
|
|
167
|
+
&& openStep.step === event.data.step) {
|
|
168
|
+
const latencyMs = Math.max(0, event.time - openStep.startTime);
|
|
169
|
+
// dsh 0.1.7 embeds the timed model stream inside assistant/message;
|
|
170
|
+
// the first token delta's timestamp is read from those compact records.
|
|
171
|
+
const firstTokenTime = 'stream' in event.data && event.data.stream
|
|
172
|
+
? extractFirstTokenTimeFromStream(event.data.stream)
|
|
173
|
+
: undefined;
|
|
174
|
+
const firstTokenLatencyMs = firstTokenTime !== undefined
|
|
175
|
+
? Math.max(0, firstTokenTime - openStep.startTime)
|
|
176
|
+
: undefined;
|
|
177
|
+
timing = {
|
|
178
|
+
latencyMs,
|
|
179
|
+
...(firstTokenLatencyMs !== undefined ? { firstTokenLatencyMs } : {}),
|
|
180
|
+
};
|
|
181
|
+
openStep = null;
|
|
182
|
+
}
|
|
183
|
+
else if (event.type === 'step/end' || event.type === 'turn/end') {
|
|
184
|
+
openStep = null;
|
|
185
|
+
}
|
|
186
|
+
const record = recordOfEvent(event, id, model, deps.recordCompaction !== false, timing);
|
|
88
187
|
if (record === null)
|
|
89
188
|
continue;
|
|
189
|
+
// Keep the id whether the row was already saved or lands now: the
|
|
190
|
+
// reconcile pass keeps exactly the ids this walk produced.
|
|
191
|
+
reproduced.add(record.requestId);
|
|
90
192
|
if (await deps.log.record(record))
|
|
91
193
|
added += 1;
|
|
92
194
|
else
|
|
@@ -104,12 +206,18 @@ export async function syncHistory(deps, onTick, signal) {
|
|
|
104
206
|
...(header?.parentSession !== undefined && header.parentSession !== '' ? { parentSession: header.parentSession } : {}),
|
|
105
207
|
};
|
|
106
208
|
if (Object.keys(patch).length > 0)
|
|
107
|
-
await deps.meta.upsert(
|
|
209
|
+
await deps.meta.upsert(id, patch);
|
|
108
210
|
}
|
|
109
211
|
processed += 1;
|
|
110
|
-
onTick?.({ processed, total, added, skipped, failedSessions });
|
|
212
|
+
onTick?.({ processed, total, added, skipped, removed, failedSessions });
|
|
213
|
+
}
|
|
214
|
+
// Reconcile last, once every readable session has spoken for its rows: a
|
|
215
|
+
// saved row no readable session reproduces is a relic of an older stored
|
|
216
|
+
// format. A session that merely failed to load protects its own rows.
|
|
217
|
+
if (deps.reconcile !== false) {
|
|
218
|
+
removed = await deps.log.reconcile(reproduced, readable, eligible);
|
|
111
219
|
}
|
|
112
|
-
return { added, skipped, failedSessions };
|
|
220
|
+
return { added, skipped, removed, failedSessions };
|
|
113
221
|
}
|
|
114
222
|
/**
|
|
115
223
|
* Run the gated automatic work, then persist the markers:
|
|
@@ -131,9 +239,9 @@ export async function autoSyncIfNeeded(deps, dir) {
|
|
|
131
239
|
const state = await readSyncState(dir);
|
|
132
240
|
if (state !== null && state.metaSyncedAt !== undefined)
|
|
133
241
|
return null;
|
|
134
|
-
const result = await syncHistory(deps);
|
|
242
|
+
const result = await syncHistory({ ...deps, reconcile: false });
|
|
135
243
|
if (state === null)
|
|
136
|
-
await markInitialized(dir, undefined, true);
|
|
244
|
+
await markInitialized(dir, undefined, true, true);
|
|
137
245
|
else
|
|
138
246
|
await markMetaSynced(dir);
|
|
139
247
|
return result;
|
package/lib/sync.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.js","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"sync.js","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAQH,OAAO,EAAE,eAAe,EAAE,cAAc,EA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BAAgB,CAAC,IAAc,EAAE,GAAW;IAChE,MAAM,KAAK,GAAG,MAAM,aAAa,CAAC,GAAG,CAAC,CAAA;IACtC,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,YAAY,KAAK,SAAS;QAAE,OAAO,IAAI,CAAA;IACnE,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAA;IAC/D,IAAI,KAAK,KAAK,IAAI;QAAE,MAAM,eAAe,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;;QAChE,MAAM,cAAc,CAAC,GAAG,CAAC,CAAA;IAC9B,OAAO,MAAM,CAAA;AACf,CAAC"}
|
package/lib/usage-log.d.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { type LoggerLike } from './log.ts';
|
|
11
11
|
import { type UsageRecord } from './usage-record.ts';
|
|
12
|
+
import { type SyncPersistence } from './sync.ts';
|
|
12
13
|
declare const DAY_FILE: RegExp;
|
|
13
14
|
/** Test for this store's per-day file names; the migration shares the naming contract. */
|
|
14
15
|
export { DAY_FILE };
|
|
@@ -28,6 +29,9 @@ export declare class UsageLog {
|
|
|
28
29
|
private readonly dir;
|
|
29
30
|
private readonly logger;
|
|
30
31
|
private readonly seen;
|
|
32
|
+
/** Owning session of every saved id; the reconcile pass uses it to protect
|
|
33
|
+
* the rows of sessions whose log could not be read. */
|
|
34
|
+
private readonly owners;
|
|
31
35
|
private queue;
|
|
32
36
|
private ready;
|
|
33
37
|
/**
|
|
@@ -37,6 +41,12 @@ export declare class UsageLog {
|
|
|
37
41
|
constructor(dir: string, logger?: LoggerLike);
|
|
38
42
|
/** Whether a request id is already known to this log. */
|
|
39
43
|
has(requestId: string): boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Snapshot every saved request id. A reconcile pass takes this *before* the
|
|
46
|
+
* session walk so a row appended by a live request while the walk runs is
|
|
47
|
+
* never a deletion candidate.
|
|
48
|
+
*/
|
|
49
|
+
ids(): ReadonlySet<string>;
|
|
40
50
|
/**
|
|
41
51
|
* Settle every queued append. The chain never rejects (each task absorbs
|
|
42
52
|
* its own failure), so this is the quiescence point a data-directory
|
|
@@ -63,6 +73,40 @@ export declare class UsageLog {
|
|
|
63
73
|
* @returns the number of rows that had to move.
|
|
64
74
|
*/
|
|
65
75
|
refileByEventDay(): Promise<number>;
|
|
76
|
+
/**
|
|
77
|
+
* Backfill missing latencyMs and firstTokenLatencyMs into existing day files
|
|
78
|
+
* from the authoritative session persistence events.
|
|
79
|
+
* Runs on the append queue so a live write cannot interleave with the rewrite.
|
|
80
|
+
* @param persistence - host session persistence.
|
|
81
|
+
* @returns the number of rows that were backfilled with timing.
|
|
82
|
+
*/
|
|
83
|
+
backfillTiming(persistence: SyncPersistence): Promise<number>;
|
|
84
|
+
/**
|
|
85
|
+
* Drop every saved row that the authoritative session walk did not
|
|
86
|
+
* reproduce. A row whose request id no longer appears in any session log is
|
|
87
|
+
* a relic of an older stored format: the host rewrote the event coordinates
|
|
88
|
+
* when it migrated the log to the current format generation, so the walk
|
|
89
|
+
* reproduces the same requests under new ids.
|
|
90
|
+
*
|
|
91
|
+
* Three guards keep this pass from destroying live data:
|
|
92
|
+
* - only ids in `eligible` (the snapshot taken before the walk) are
|
|
93
|
+
* candidates, so a row a live request appended during the walk survives;
|
|
94
|
+
* - a row is dropped only when its owning session was read **in full** by
|
|
95
|
+
* the walk, so "the walk did not see it" is never inferred from a session
|
|
96
|
+
* that failed to load, from a session missing out of the list (deleted,
|
|
97
|
+
* or hidden behind a header this build cannot read), or from a row whose
|
|
98
|
+
* owner is unknown;
|
|
99
|
+
* - malformed lines are never candidates and stay where they are.
|
|
100
|
+
*
|
|
101
|
+
* A day file is rewritten only when it actually loses a row, and the
|
|
102
|
+
* rewrite is atomic. Runs on the append queue so a live write cannot
|
|
103
|
+
* interleave with it.
|
|
104
|
+
* @param keep - request ids the walk reproduced from readable sessions.
|
|
105
|
+
* @param readableSessions - sessions the walk read in full.
|
|
106
|
+
* @param eligible - the pre-walk snapshot of saved request ids.
|
|
107
|
+
* @returns the number of rows removed.
|
|
108
|
+
*/
|
|
109
|
+
reconcile(keep: ReadonlySet<string>, readableSessions: ReadonlySet<string>, eligible: ReadonlySet<string>): Promise<number>;
|
|
66
110
|
/** The directory is created once and remembered; an external deletion
|
|
67
111
|
* forces a rebuild on the next append (see {@link appendOnce}). */
|
|
68
112
|
private ensureDir;
|
|
@@ -76,4 +120,9 @@ export declare class UsageLog {
|
|
|
76
120
|
*/
|
|
77
121
|
private appendOnce;
|
|
78
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Scan day files for plain requests lacking latencyMs, resolve their timing
|
|
125
|
+
* from session persistence events, and rewrite touched day files atomically.
|
|
126
|
+
*/
|
|
127
|
+
export declare function backfillDayFilesTiming(dir: string, persistence: SyncPersistence, logger?: LoggerLike): Promise<number>;
|
|
79
128
|
//# sourceMappingURL=usage-log.d.ts.map
|
package/lib/usage-log.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-log.d.ts","sourceRoot":"","sources":["../src/usage-log.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;
|
|
1
|
+
{"version":3,"file":"usage-log.d.ts","sourceRoot":"","sources":["../src/usage-log.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,EAAiB,KAAK,UAAU,EAAE,MAAM,UAAU,CAAA;AACzD,OAAO,EAAiE,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAA;AACnH,OAAO,EAAY,KAAK,eAAe,EAAE,MAAM,WAAW,CAAA;AAE1D,QAAA,MAAM,QAAQ,QAAsC,CAAA;AAEpD,0FAA0F;AAC1F,OAAO,EAAE,QAAQ,EAAE,CAAA;AAEnB,0EAA0E;AAC1E,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,MA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,MAAM,EACX,WAAW,EAAE,eAAe,EAC5B,MAAM,GAAE,UAA0B,GACjC,OAAO,CAAC,MAAM,CAAC,CAoGjB"}
|
package/lib/usage-log.js
CHANGED
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
import { appendFile, mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
11
11
|
import { join } from 'node:path';
|
|
12
12
|
import { consoleLogger } from "./log.js";
|
|
13
|
-
import { parseRecord, serializeRecord } from "./usage-record.js";
|
|
13
|
+
import { extractFirstTokenTimeFromStream, parseRecord, serializeRecord } from "./usage-record.js";
|
|
14
|
+
import { readerOf } from "./sync.js";
|
|
14
15
|
const DAY_FILE = /^usage-\d{4}-\d{2}-\d{2}\.jsonl$/u;
|
|
15
16
|
/** Test for this store's per-day file names; the migration shares the naming contract. */
|
|
16
17
|
export { DAY_FILE };
|
|
@@ -40,6 +41,9 @@ export class UsageLog {
|
|
|
40
41
|
dir;
|
|
41
42
|
logger;
|
|
42
43
|
seen = new Set();
|
|
44
|
+
/** Owning session of every saved id; the reconcile pass uses it to protect
|
|
45
|
+
* the rows of sessions whose log could not be read. */
|
|
46
|
+
owners = new Map();
|
|
43
47
|
queue = Promise.resolve();
|
|
44
48
|
ready;
|
|
45
49
|
/**
|
|
@@ -54,6 +58,14 @@ export class UsageLog {
|
|
|
54
58
|
has(requestId) {
|
|
55
59
|
return this.seen.has(requestId);
|
|
56
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Snapshot every saved request id. A reconcile pass takes this *before* the
|
|
63
|
+
* session walk so a row appended by a live request while the walk runs is
|
|
64
|
+
* never a deletion candidate.
|
|
65
|
+
*/
|
|
66
|
+
ids() {
|
|
67
|
+
return new Set(this.seen);
|
|
68
|
+
}
|
|
57
69
|
/**
|
|
58
70
|
* Settle every queued append. The chain never rejects (each task absorbs
|
|
59
71
|
* its own failure), so this is the quiescence point a data-directory
|
|
@@ -95,6 +107,7 @@ export class UsageLog {
|
|
|
95
107
|
continue;
|
|
96
108
|
}
|
|
97
109
|
this.seen.add(record.requestId);
|
|
110
|
+
this.owners.set(record.requestId, record.sessionId);
|
|
98
111
|
}
|
|
99
112
|
}
|
|
100
113
|
}
|
|
@@ -107,6 +120,7 @@ export class UsageLog {
|
|
|
107
120
|
return Promise.resolve(false);
|
|
108
121
|
// Claim before queueing: a concurrent call with the same id dedupes here.
|
|
109
122
|
this.seen.add(record.requestId);
|
|
123
|
+
this.owners.set(record.requestId, record.sessionId);
|
|
110
124
|
const task = this.queue.then(async () => {
|
|
111
125
|
await this.ensureDir();
|
|
112
126
|
await this.appendOnce(record);
|
|
@@ -118,6 +132,7 @@ export class UsageLog {
|
|
|
118
132
|
.catch((error) => {
|
|
119
133
|
// Release the claim so a later sync can retry this row.
|
|
120
134
|
this.seen.delete(record.requestId);
|
|
135
|
+
this.owners.delete(record.requestId);
|
|
121
136
|
this.logger.error('[token-usage] append failed:', error);
|
|
122
137
|
return false;
|
|
123
138
|
});
|
|
@@ -141,6 +156,69 @@ export class UsageLog {
|
|
|
141
156
|
return 0;
|
|
142
157
|
});
|
|
143
158
|
}
|
|
159
|
+
/**
|
|
160
|
+
* Backfill missing latencyMs and firstTokenLatencyMs into existing day files
|
|
161
|
+
* from the authoritative session persistence events.
|
|
162
|
+
* Runs on the append queue so a live write cannot interleave with the rewrite.
|
|
163
|
+
* @param persistence - host session persistence.
|
|
164
|
+
* @returns the number of rows that were backfilled with timing.
|
|
165
|
+
*/
|
|
166
|
+
backfillTiming(persistence) {
|
|
167
|
+
let patched = 0;
|
|
168
|
+
const task = this.queue.then(async () => {
|
|
169
|
+
await this.ensureDir();
|
|
170
|
+
patched = await backfillDayFilesTiming(this.dir, persistence, this.logger);
|
|
171
|
+
});
|
|
172
|
+
this.queue = task.catch(() => { });
|
|
173
|
+
return task.then(() => patched).catch((error) => {
|
|
174
|
+
this.logger.error('[token-usage] timing backfill failed:', error);
|
|
175
|
+
return 0;
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Drop every saved row that the authoritative session walk did not
|
|
180
|
+
* reproduce. A row whose request id no longer appears in any session log is
|
|
181
|
+
* a relic of an older stored format: the host rewrote the event coordinates
|
|
182
|
+
* when it migrated the log to the current format generation, so the walk
|
|
183
|
+
* reproduces the same requests under new ids.
|
|
184
|
+
*
|
|
185
|
+
* Three guards keep this pass from destroying live data:
|
|
186
|
+
* - only ids in `eligible` (the snapshot taken before the walk) are
|
|
187
|
+
* candidates, so a row a live request appended during the walk survives;
|
|
188
|
+
* - a row is dropped only when its owning session was read **in full** by
|
|
189
|
+
* the walk, so "the walk did not see it" is never inferred from a session
|
|
190
|
+
* that failed to load, from a session missing out of the list (deleted,
|
|
191
|
+
* or hidden behind a header this build cannot read), or from a row whose
|
|
192
|
+
* owner is unknown;
|
|
193
|
+
* - malformed lines are never candidates and stay where they are.
|
|
194
|
+
*
|
|
195
|
+
* A day file is rewritten only when it actually loses a row, and the
|
|
196
|
+
* rewrite is atomic. Runs on the append queue so a live write cannot
|
|
197
|
+
* interleave with it.
|
|
198
|
+
* @param keep - request ids the walk reproduced from readable sessions.
|
|
199
|
+
* @param readableSessions - sessions the walk read in full.
|
|
200
|
+
* @param eligible - the pre-walk snapshot of saved request ids.
|
|
201
|
+
* @returns the number of rows removed.
|
|
202
|
+
*/
|
|
203
|
+
reconcile(keep, readableSessions, eligible) {
|
|
204
|
+
let removed = 0;
|
|
205
|
+
const task = this.queue.then(async () => {
|
|
206
|
+
// Deliberately no ensureDir: a reconcile still queued when this store's
|
|
207
|
+
// directory is relocated away would otherwise resurrect it. A missing
|
|
208
|
+
// directory has nothing to reconcile, and readdir reports exactly that.
|
|
209
|
+
const dropped = await reconcileDayFiles(this.dir, { keep, readableSessions, eligible, owners: this.owners }, this.logger);
|
|
210
|
+
removed = dropped.length;
|
|
211
|
+
for (const id of dropped) {
|
|
212
|
+
this.seen.delete(id);
|
|
213
|
+
this.owners.delete(id);
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
this.queue = task.catch(() => { });
|
|
217
|
+
return task.then(() => removed).catch((error) => {
|
|
218
|
+
this.logger.error('[token-usage] reconcile failed:', error);
|
|
219
|
+
return 0;
|
|
220
|
+
});
|
|
221
|
+
}
|
|
144
222
|
/** The directory is created once and remembered; an external deletion
|
|
145
223
|
* forces a rebuild on the next append (see {@link appendOnce}). */
|
|
146
224
|
async ensureDir() {
|
|
@@ -253,4 +331,164 @@ async function refileDayFiles(dir, logger) {
|
|
|
253
331
|
}
|
|
254
332
|
return moved;
|
|
255
333
|
}
|
|
334
|
+
/**
|
|
335
|
+
* Rewrite every day file without the rows {@link ReconcileSets} marks
|
|
336
|
+
* droppable, and report the dropped ids. A file is touched only when it
|
|
337
|
+
* actually loses a row; malformed lines stay in place so a bad row is never
|
|
338
|
+
* silently dropped by the pass that exists to remove rows on purpose.
|
|
339
|
+
*/
|
|
340
|
+
async function reconcileDayFiles(dir, sets, logger) {
|
|
341
|
+
let names;
|
|
342
|
+
try {
|
|
343
|
+
names = (await readdir(dir)).filter(name => DAY_FILE.test(name)).sort();
|
|
344
|
+
}
|
|
345
|
+
catch (error) {
|
|
346
|
+
logger.error('[token-usage] cannot list data dir ' + dir + ':', error);
|
|
347
|
+
return [];
|
|
348
|
+
}
|
|
349
|
+
const dropped = [];
|
|
350
|
+
for (const name of names) {
|
|
351
|
+
const lines = await readDayLines(dir, name, logger);
|
|
352
|
+
const stay = [];
|
|
353
|
+
const stray = [];
|
|
354
|
+
let lost = 0;
|
|
355
|
+
for (const line of lines) {
|
|
356
|
+
if (line.record === null) {
|
|
357
|
+
stray.push(line.raw);
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
const id = line.record.requestId;
|
|
361
|
+
const doomed = sets.eligible.has(id)
|
|
362
|
+
&& !sets.keep.has(id)
|
|
363
|
+
&& sets.readableSessions.has(sets.owners.get(id) ?? '');
|
|
364
|
+
if (doomed) {
|
|
365
|
+
dropped.push(id);
|
|
366
|
+
lost += 1;
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
stay.push(line.record);
|
|
370
|
+
}
|
|
371
|
+
if (lost === 0)
|
|
372
|
+
continue;
|
|
373
|
+
if (stray.length > 0) {
|
|
374
|
+
const target = join(dir, name);
|
|
375
|
+
const body = `${stay.map(serializeRecord).join('\n')}${stay.length > 0 ? '\n' : ''}${stray.join('\n')}\n`;
|
|
376
|
+
const tmp = join(dir, `${name}.tmp`);
|
|
377
|
+
await writeFile(tmp, body, 'utf8');
|
|
378
|
+
await unlink(target).catch(() => undefined);
|
|
379
|
+
await rename(tmp, target);
|
|
380
|
+
}
|
|
381
|
+
else {
|
|
382
|
+
await rewriteDayFile(dir, name, stay);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
return dropped;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Scan day files for plain requests lacking latencyMs, resolve their timing
|
|
389
|
+
* from session persistence events, and rewrite touched day files atomically.
|
|
390
|
+
*/
|
|
391
|
+
export async function backfillDayFilesTiming(dir, persistence, logger = consoleLogger) {
|
|
392
|
+
let names;
|
|
393
|
+
try {
|
|
394
|
+
names = (await readdir(dir)).filter(name => DAY_FILE.test(name)).sort();
|
|
395
|
+
}
|
|
396
|
+
catch (error) {
|
|
397
|
+
logger.error('[token-usage] cannot list data dir ' + dir + ':', error);
|
|
398
|
+
return 0;
|
|
399
|
+
}
|
|
400
|
+
const fileLines = new Map();
|
|
401
|
+
const missingBySession = new Map();
|
|
402
|
+
for (const name of names) {
|
|
403
|
+
const lines = await readDayLines(dir, name, logger);
|
|
404
|
+
let fileHasMissing = false;
|
|
405
|
+
for (const line of lines) {
|
|
406
|
+
if (line.record === null)
|
|
407
|
+
continue;
|
|
408
|
+
// Only plain requests lacking latencyMs or firstTokenLatencyMs are backfill candidates
|
|
409
|
+
if (line.record.kind === undefined && (line.record.latencyMs === undefined || line.record.firstTokenLatencyMs === undefined)) {
|
|
410
|
+
fileHasMissing = true;
|
|
411
|
+
let sessionMap = missingBySession.get(line.record.sessionId);
|
|
412
|
+
if (sessionMap === undefined) {
|
|
413
|
+
sessionMap = new Map();
|
|
414
|
+
missingBySession.set(line.record.sessionId, sessionMap);
|
|
415
|
+
}
|
|
416
|
+
sessionMap.set(line.record.requestId, line.record);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
if (fileHasMissing) {
|
|
420
|
+
fileLines.set(name, lines);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
if (missingBySession.size === 0)
|
|
424
|
+
return 0;
|
|
425
|
+
const reader = readerOf(persistence);
|
|
426
|
+
let patchedCount = 0;
|
|
427
|
+
for (const [sessionId, targetMap] of missingBySession) {
|
|
428
|
+
try {
|
|
429
|
+
const inspection = await reader.read(sessionId);
|
|
430
|
+
let openStep = null;
|
|
431
|
+
for (const event of inspection.events) {
|
|
432
|
+
if (event.type === 'step/start') {
|
|
433
|
+
openStep = {
|
|
434
|
+
turn: event.data.turn,
|
|
435
|
+
step: event.data.step,
|
|
436
|
+
startTime: event.time,
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
else if (event.type === 'assistant/message') {
|
|
440
|
+
if (targetMap.has(event.data.message.id)) {
|
|
441
|
+
const targetRecord = targetMap.get(event.data.message.id);
|
|
442
|
+
if (openStep !== null
|
|
443
|
+
&& openStep.turn === event.data.turn
|
|
444
|
+
&& openStep.step === event.data.step) {
|
|
445
|
+
targetRecord.latencyMs = Math.max(0, event.time - openStep.startTime);
|
|
446
|
+
// dsh 0.1.7 embeds the timed model stream inside assistant/message.
|
|
447
|
+
const firstTokenTime = 'stream' in event.data && event.data.stream
|
|
448
|
+
? extractFirstTokenTimeFromStream(event.data.stream)
|
|
449
|
+
: undefined;
|
|
450
|
+
if (firstTokenTime !== undefined) {
|
|
451
|
+
targetRecord.firstTokenLatencyMs = Math.max(0, firstTokenTime - openStep.startTime);
|
|
452
|
+
}
|
|
453
|
+
patchedCount += 1;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
openStep = null;
|
|
457
|
+
}
|
|
458
|
+
else if (event.type === 'step/end' || event.type === 'turn/end') {
|
|
459
|
+
openStep = null;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
catch (error) {
|
|
464
|
+
logger.warn(`[token-usage] session ${sessionId} unreadable during timing backfill, skipped:`, error instanceof Error ? error.message : String(error));
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
if (patchedCount === 0)
|
|
468
|
+
return 0;
|
|
469
|
+
for (const [name, lines] of fileLines) {
|
|
470
|
+
const stay = [];
|
|
471
|
+
const stray = [];
|
|
472
|
+
for (const line of lines) {
|
|
473
|
+
if (line.record === null) {
|
|
474
|
+
stray.push(line.raw);
|
|
475
|
+
}
|
|
476
|
+
else {
|
|
477
|
+
stay.push(line.record);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
if (stray.length > 0) {
|
|
481
|
+
const target = join(dir, name);
|
|
482
|
+
const body = `${stay.map(serializeRecord).join('\n')}${stay.length > 0 ? '\n' : ''}${stray.join('\n')}\n`;
|
|
483
|
+
const tmp = join(dir, `${name}.tmp`);
|
|
484
|
+
await writeFile(tmp, body, 'utf8');
|
|
485
|
+
await unlink(target).catch(() => undefined);
|
|
486
|
+
await rename(tmp, target);
|
|
487
|
+
}
|
|
488
|
+
else {
|
|
489
|
+
await rewriteDayFile(dir, name, stay);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return patchedCount;
|
|
493
|
+
}
|
|
256
494
|
//# sourceMappingURL=usage-log.js.map
|