@troed/oc-ls-stats 1.0.18 → 1.1.5

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.
Files changed (4) hide show
  1. package/README.md +11 -6
  2. package/package.json +4 -1
  3. package/src/stats.ts +208 -0
  4. package/tui.tsx +28 -125
package/README.md CHANGED
@@ -55,15 +55,20 @@ Every 500ms, the plugin polls `GET /slots?model=<model>` on each discovered serv
55
55
 
56
56
  ### State Classification
57
57
 
58
- Each slot is classified as prefill or generation based on the `n_decoded` counter in `next_token[0]`. The plugin tracks a per-slot baseline value:
58
+ Each processing slot is classified as prefill (PP) or generation (TG) by comparing `n_decoded` and `n_prompt_tokens` against per-slot/per-task baselines. The plugin tracks two baseline maps keyed by slot ID:
59
59
 
60
- 1. When a slot first appears as processing, the current `n_decoded` is recorded as the baseline with `hasIncreased = false`.
61
- 2. If `n_decoded <= baseline` and `hasIncreased` is false, the slot is classified as prefilling.
62
- 3. If `n_decoded > baseline`, `hasIncreased` is set to true and the slot is classified as generating.
60
+ - `prevNdBySlot[slotId]` — stores `{ prevNd, idTask, classification }`
61
+ - `prevPromptTokensBySlot[slotId]` — stores `{ tokens, idTask }`
63
62
 
64
- This approach handles the case where `n_decoded` drops when a new request starts on a reused slot, and prevents generation stalls (where `n_decoded` plateaus) from being misclassified as prefill.
63
+ The `idTask` field ensures baselines are invalidated when a slot starts a new task (task reuse).
65
64
 
66
- When no slots are processing, all tracked state for those slots is cleared.
65
+ Classification logic:
66
+
67
+ 1. **First time or after task change/reset**: If we have no baseline for this slot+task, or `n_decoded` or `n_prompt_tokens` dropped below baseline (indicating a new request), use a heuristic: `n_decoded > 0` → TG, otherwise → PP.
68
+ 2. **Compare against baseline**: If `n_decoded > baselineNd` → TG. If `n_prompt_tokens > baselineNt` → PP.
69
+ 3. **Neither increased**: Persist the previous classification. This handles frequent polling where neither field increases on every poll cycle.
70
+
71
+ When a slot stops being processed, all tracked state for that slot is cleared.
67
72
 
68
73
  ### Prefill Rate (PP)
69
74
 
package/package.json CHANGED
@@ -1,13 +1,16 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@troed/oc-ls-stats",
4
- "version": "1.0.18",
4
+ "version": "1.1.5",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  "./tui": {
8
8
  "import": "./tui.tsx"
9
9
  }
10
10
  },
11
+ "scripts": {
12
+ "prepack": "npx -y tsx test-stats.ts"
13
+ },
11
14
  "engines": {
12
15
  "opencode": ">=1.3.14"
13
16
  },
package/src/stats.ts ADDED
@@ -0,0 +1,208 @@
1
+ export interface SlotState {
2
+ id: number
3
+ is_processing: boolean
4
+ n_prompt_tokens: number
5
+ next_token: { n_decoded: number }[]
6
+ id_task: number
7
+ }
8
+
9
+ export interface TrackerState {
10
+ prevNdBySlot: Record<number, { prevNd: number; idTask: number; classification: "TG" | "PP" | "neither" }>
11
+ prevPromptTokensBySlot: Record<number, { tokens: number; idTask: number }>
12
+ isPrefilling: boolean
13
+ isGenerating: boolean
14
+ prefillSlotId: number | null
15
+ prefillCapturedTokens: number | null
16
+ prefillStartAt: number
17
+ lastPrefillRate: number
18
+ generateSlotId: number | null
19
+ generatePrevNd: number
20
+ generateStartAt: number
21
+ lastGeneratedTps: number
22
+ }
23
+
24
+ export interface ClassificationResult {
25
+ slotId: number
26
+ nd: number
27
+ prevNd: number
28
+ nt: number
29
+ prevNt: number
30
+ classification: "TG" | "PP" | "neither"
31
+ }
32
+
33
+ export interface PollResult {
34
+ classifications: ClassificationResult[]
35
+ isPrefilling: boolean
36
+ isGenerating: boolean
37
+ lastPrefillRate: number
38
+ lastGeneratedTps: number
39
+ ppEnded: boolean
40
+ tgEnded: boolean
41
+ }
42
+
43
+ export function classifySlot(
44
+ slot: SlotState,
45
+ tracker: TrackerState,
46
+ ): ClassificationResult {
47
+ const slotId = slot.id
48
+ const nd = slot.next_token?.[0]?.n_decoded ?? 0
49
+ const nt = slot.n_prompt_tokens ?? 0
50
+ const idTask = slot.id_task ?? 0
51
+
52
+ const ndEntry = tracker.prevNdBySlot[slotId]
53
+ const ntEntry = tracker.prevPromptTokensBySlot[slotId]
54
+
55
+ // Check if we have valid baseline for this slot/task
56
+ const hasBaseline = ndEntry && ndEntry.idTask === idTask && ntEntry && ntEntry.idTask === idTask
57
+ const baselineNd = hasBaseline ? ndEntry.prevNd : nd
58
+ const baselineNt = hasBaseline ? ntEntry.tokens : nt
59
+
60
+ // Check if values have reset (dropped below baseline) - indicates slot reuse or new request
61
+ const hasReset = hasBaseline && (nd < baselineNd || nt < baselineNt)
62
+
63
+ let classification: "TG" | "PP" | "neither" = "neither"
64
+ let prevNd = nd
65
+ let prevNt = nt
66
+
67
+ if (!hasBaseline || hasReset) {
68
+ // First time seeing this slot/task, or values have reset
69
+ // Use heuristic: if n_decoded > 0, we likely caught it mid-generation
70
+ if (nd > 0) {
71
+ classification = "TG"
72
+ } else {
73
+ classification = "PP"
74
+ }
75
+ } else {
76
+ // Compare against baseline values
77
+ if (nd > baselineNd) {
78
+ classification = "TG"
79
+ } else if (nt > baselineNt) {
80
+ classification = "PP"
81
+ } else {
82
+ // Neither has increased from baseline - persist previous classification
83
+ // This handles frequent polling where we don't see increases every poll
84
+ const prevClassification = ndEntry?.classification
85
+ if (prevClassification) {
86
+ classification = prevClassification
87
+ }
88
+ }
89
+ prevNd = baselineNd
90
+ prevNt = baselineNt
91
+ }
92
+
93
+ return { slotId, nd, prevNd, nt, prevNt, classification }
94
+ }
95
+
96
+ export function processPoll(
97
+ slots: SlotState[],
98
+ tracker: TrackerState,
99
+ now: number = Date.now(),
100
+ ): PollResult {
101
+ const processingSlots = slots.filter(s => s.is_processing)
102
+ const processingSlotIds = new Set(processingSlots.map(s => s.id))
103
+
104
+ // Clean up tracking state for slots that went idle
105
+ for (const key of Object.keys(tracker.prevNdBySlot)) {
106
+ const slotId = Number(key)
107
+ if (!processingSlotIds.has(slotId)) {
108
+ delete tracker.prevNdBySlot[slotId]
109
+ }
110
+ }
111
+ for (const key of Object.keys(tracker.prevPromptTokensBySlot)) {
112
+ const slotId = Number(key)
113
+ if (!processingSlotIds.has(slotId)) {
114
+ delete tracker.prevPromptTokensBySlot[slotId]
115
+ }
116
+ }
117
+
118
+ // Classify each processing slot
119
+ const classifications: ClassificationResult[] = []
120
+ let prefillSlot: ClassificationResult | null = null
121
+ let generateSlot: ClassificationResult | null = null
122
+
123
+ for (const slot of processingSlots) {
124
+ const result = classifySlot(slot, tracker)
125
+ classifications.push(result)
126
+
127
+ if (result.classification === "TG") {
128
+ generateSlot = result
129
+ } else if (result.classification === "PP") {
130
+ prefillSlot = result
131
+ }
132
+
133
+ // Update tracker state - store baseline values and classification
134
+ tracker.prevNdBySlot[slot.id] = { prevNd: result.nd, idTask: slot.id_task, classification: result.classification }
135
+ tracker.prevPromptTokensBySlot[slot.id] = { tokens: result.nt, idTask: slot.id_task }
136
+ }
137
+
138
+ let anyPrefilling = false
139
+ let anyGenerating = false
140
+ let ppEnded = false
141
+ let tgEnded = false
142
+
143
+ // Handle PP phase
144
+ if (prefillSlot) {
145
+ anyPrefilling = true
146
+ const nt = prefillSlot.nt
147
+ if (tracker.prefillSlotId === prefillSlot.slotId) {
148
+ const dt = (now - tracker.prefillStartAt) / 1000
149
+ const delta = nt - (tracker.prefillCapturedTokens ?? 0)
150
+ if (dt > 0 && delta > 0) {
151
+ tracker.lastPrefillRate = delta / dt
152
+ }
153
+ } else {
154
+ tracker.prefillSlotId = prefillSlot.slotId
155
+ tracker.prefillCapturedTokens = nt
156
+ tracker.prefillStartAt = now
157
+ tracker.lastPrefillRate = 0
158
+ }
159
+ } else if (processingSlotIds.size > 0 && !generateSlot) {
160
+ anyPrefilling = tracker.isPrefilling
161
+ } else if (tracker.isPrefilling) {
162
+ tracker.prefillSlotId = null
163
+ tracker.prefillCapturedTokens = null
164
+ tracker.prefillStartAt = 0
165
+ ppEnded = true
166
+ }
167
+
168
+ // Handle TG phase
169
+ if (generateSlot) {
170
+ anyGenerating = true
171
+ const nd = generateSlot.nd
172
+ if (tracker.generateSlotId === generateSlot.slotId) {
173
+ const dt = (now - tracker.generateStartAt) / 1000
174
+ const delta = nd - tracker.generatePrevNd
175
+ if (dt > 0 && delta > 0) {
176
+ tracker.lastGeneratedTps = delta / dt
177
+ }
178
+ tracker.generatePrevNd = nd
179
+ tracker.generateStartAt = now
180
+ } else {
181
+ tracker.generateSlotId = generateSlot.slotId
182
+ tracker.generatePrevNd = nd
183
+ tracker.generateStartAt = now
184
+ tracker.lastGeneratedTps = 0
185
+ }
186
+ } else if (processingSlotIds.size > 0 && !prefillSlot) {
187
+ anyGenerating = tracker.isGenerating
188
+ } else if (tracker.isGenerating) {
189
+ tracker.generateSlotId = null
190
+ tracker.generatePrevNd = 0
191
+ tracker.generateStartAt = 0
192
+ tracker.lastGeneratedTps = 0
193
+ tgEnded = true
194
+ }
195
+
196
+ tracker.isPrefilling = anyPrefilling
197
+ tracker.isGenerating = anyGenerating
198
+
199
+ return {
200
+ classifications,
201
+ isPrefilling: tracker.isPrefilling,
202
+ isGenerating: tracker.isGenerating,
203
+ lastPrefillRate: tracker.lastPrefillRate,
204
+ lastGeneratedTps: tracker.lastGeneratedTps,
205
+ ppEnded,
206
+ tgEnded,
207
+ }
208
+ }
package/tui.tsx CHANGED
@@ -2,8 +2,9 @@
2
2
  import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
3
3
  import { createMemo, createSignal } from "solid-js"
4
4
  import { appendFileSync } from "fs"
5
+ import { processPoll } from "./src/stats.ts"
5
6
 
6
- const DEBUG_ENABLED = true
7
+ const DEBUG_ENABLED = false
7
8
  const DEBUG_LOG = "/tmp/oc-ls-stats-debug.log"
8
9
  function debug(...args: unknown[]) {
9
10
  if (!DEBUG_ENABLED) return
@@ -41,7 +42,8 @@ type MessageTiming = {
41
42
  generateSlotId: number | null
42
43
  generatePrevNd: number
43
44
  generateStartAt: number
44
- prevNdBySlot: Record<number, { baseline: number; hasIncreased: boolean; idTask: number }>
45
+ prevNdBySlot: Record<number, { prevNd: number; idTask: number; classification: "TG" | "PP" | "neither" }>
46
+ prevPromptTokensBySlot: Record<number, { tokens: number; idTask: number }>
45
47
  failure: string | null
46
48
  }
47
49
 
@@ -141,16 +143,23 @@ function SessionPromptRight(props: {
141
143
  })
142
144
 
143
145
  const text = createMemo(() => {
146
+ props.clock()
144
147
  if (props.tracker.failure) return props.tracker.failure
145
148
  const pp = prefillRate()
146
149
  const tps = liveTps()
147
150
  if (props.tracker.isPrefilling && pp) {
148
- return `${formatPps(pp)} tps (PP)`
151
+ const result = `${formatPps(pp)} tps (PP)`
152
+ debug(`UI_TEXT="${result}" isPrefilling=${props.tracker.isPrefilling} isGenerating=${props.tracker.isGenerating} failure=${props.tracker.failure} pp=${pp} tps=${tps}`)
153
+ return result
149
154
  }
150
155
  if (props.tracker.isGenerating && tps) {
151
- return `${formatTps(tps)} tps (TG)`
156
+ const result = `${formatTps(tps)} tps (TG)`
157
+ debug(`UI_TEXT="${result}" isPrefilling=${props.tracker.isPrefilling} isGenerating=${props.tracker.isGenerating} failure=${props.tracker.failure} pp=${pp} tps=${tps}`)
158
+ return result
152
159
  }
153
- return `- tps (TG)`
160
+ const result = `- tps (TG)`
161
+ debug(`UI_TEXT="${result}" isPrefilling=${props.tracker.isPrefilling} isGenerating=${props.tracker.isGenerating} failure=${props.tracker.failure} pp=${pp} tps=${tps}`)
162
+ return result
154
163
  })
155
164
 
156
165
  return <>{text() ? <text fg={props.api.theme.current.textMuted}>{text()}</text> : null}</>
@@ -172,6 +181,7 @@ const tui: TuiPlugin = async (api) => {
172
181
  generatePrevNd: 0,
173
182
  generateStartAt: 0,
174
183
  prevNdBySlot: {},
184
+ prevPromptTokensBySlot: {},
175
185
  failure: null,
176
186
  }
177
187
  const [version, setVersion] = createSignal(0)
@@ -237,18 +247,11 @@ const tui: TuiPlugin = async (api) => {
237
247
  }
238
248
  }
239
249
 
240
- let anyPrefilling = false
241
- let anyGenerating = false
242
- let genEnded = false
243
-
244
- const prevProcessingSlotIds = new Set(Object.keys(tracker.prevNdBySlot).map(Number))
245
- const currProcessingSlotIds = new Set<number>()
246
-
247
- debug(`pollMetrics: urls=${JSON.stringify(llamaServerUrls)} model=${model}`)
250
+ debug(`pollMetrics: urls=${JSON.stringify(llamaServerUrls)} model=${model}`)
248
251
  for (const baseUrl of llamaServerUrls) {
249
252
  debug(`pollMetrics: polling ${baseUrl}`)
250
253
  const slots = await fetchSlots(baseUrl, model)
251
- debug(`pollMetrics: ${baseUrl} response=${JSON.stringify(slots)?.slice(0, 500)}`)
254
+ debug(`pollMetrics: ${baseUrl} response=${JSON.stringify(slots)}`)
252
255
  const slotList = Array.isArray(slots) ? slots : slots ? Object.values(slots) : []
253
256
  debug(`pollMetrics: ${baseUrl} slotList.length=${slotList.length}`)
254
257
  if (slotList.length === 0) {
@@ -259,122 +262,21 @@ const tui: TuiPlugin = async (api) => {
259
262
  tracker.failure = null
260
263
  bump()
261
264
 
262
-
265
+ const result = processPoll(slotList, tracker)
266
+ bump()
263
267
 
264
- for (const slot of slotList) {
265
- if (slot?.is_processing) {
266
- currProcessingSlotIds.add(slot.id)
267
- }
268
+ if (result.isPrefilling) {
269
+ debug(`PP rate=${Math.round(result.lastPrefillRate)} tps`)
268
270
  }
269
-
270
- for (const slotId of prevProcessingSlotIds) {
271
- if (!currProcessingSlotIds.has(slotId)) {
272
- delete tracker.prevNdBySlot[slotId]
273
- }
271
+ if (result.isGenerating) {
272
+ debug(`TG rate=${Math.round(result.lastGeneratedTps)} tps`)
274
273
  }
275
-
276
- let prefillSlot: any = null
277
- let generateSlot: any = null
278
- for (const slot of slotList) {
279
- if (!slot?.is_processing) continue
280
- const slotId = slot.id
281
- const nd = slot.next_token?.[0]?.n_decoded ?? 0
282
- const idTask = slot.id_task ?? 0
283
- const entry = tracker.prevNdBySlot[slotId]
284
- const baseline = entry?.idTask === idTask ? entry.baseline : nd
285
- const hasIncreased = entry?.idTask === idTask ? entry.hasIncreased : false
286
-
287
- if (entry && entry.idTask !== idTask) {
288
- debug(`slot ${slotId} id_task changed from ${entry.idTask} to ${idTask}, resetting state`)
289
- }
290
-
291
- if (!hasIncreased && nd <= baseline) {
292
- prefillSlot = slot
293
- break
294
- } else if (nd > baseline) {
295
- tracker.prevNdBySlot[slotId] = { baseline, hasIncreased: true, idTask }
296
- generateSlot = slot
297
- }
274
+ if (result.ppEnded) {
275
+ debug(`PP ended rate=${Math.round(result.lastPrefillRate)} tps`)
298
276
  }
299
-
300
- for (const slot of slotList) {
301
- if (slot?.is_processing) {
302
- const slotId = slot.id
303
- const nd = slot.next_token?.[0]?.n_decoded ?? 0
304
- const idTask = slot.id_task ?? 0
305
- const entry = tracker.prevNdBySlot[slotId]
306
- if (entry === undefined || entry.idTask !== idTask) {
307
- tracker.prevNdBySlot[slotId] = { baseline: nd, hasIncreased: false, idTask }
308
- }
309
- }
277
+ if (result.tgEnded) {
278
+ debug(`TG ended rate=${Math.round(result.lastGeneratedTps)} tps`)
310
279
  }
311
-
312
- if (prefillSlot) {
313
- anyPrefilling = true
314
- const slotId = prefillSlot.id
315
- const now = Date.now()
316
- const nt = prefillSlot.n_prompt_tokens ?? 0
317
-
318
- if (tracker.prefillSlotId === slotId) {
319
- const dt = (now - tracker.prefillStartAt) / 1000
320
- const delta = nt - tracker.prefillCapturedTokens!
321
- if (dt > 0 && delta > 0) {
322
- tracker.lastPrefillRate = delta / dt
323
- }
324
- } else {
325
- tracker.prefillSlotId = slotId
326
- tracker.prefillCapturedTokens = nt
327
- tracker.prefillStartAt = now
328
- tracker.lastPrefillRate = 0
329
-
330
- }
331
- } else {
332
- if (tracker.isPrefilling) {
333
- tracker.prefillSlotId = null
334
- tracker.prefillCapturedTokens = null
335
- tracker.prefillStartAt = 0
336
- }
337
- }
338
-
339
- if (generateSlot) {
340
- anyGenerating = true
341
- const slotId = generateSlot.id
342
- const now = Date.now()
343
- const nd = generateSlot.next_token?.[0]?.n_decoded ?? 0
344
-
345
- if (tracker.generateSlotId === slotId) {
346
- const dt = (now - tracker.generateStartAt) / 1000
347
- const delta = nd - tracker.generatePrevNd
348
- if (dt > 0 && delta > 0) {
349
- tracker.lastGeneratedTps = delta / dt
350
-
351
- }
352
- tracker.generatePrevNd = nd
353
- tracker.generateStartAt = now
354
- } else {
355
- tracker.generateSlotId = slotId
356
- tracker.generatePrevNd = nd
357
- tracker.generateStartAt = now
358
- tracker.lastGeneratedTps = 0
359
-
360
- }
361
- } else {
362
- if (tracker.isGenerating) {
363
- tracker.generateSlotId = null
364
- tracker.generatePrevNd = 0
365
- tracker.generateStartAt = 0
366
- tracker.lastGeneratedTps = 0
367
- genEnded = true
368
-
369
- }
370
- }
371
-
372
- tracker.isPrefilling = anyPrefilling
373
- tracker.isGenerating = anyGenerating
374
- }
375
-
376
- if (tracker.lastPrefillRate > 0 || tracker.lastGeneratedTps > 0 || genEnded) {
377
- bump()
378
280
  }
379
281
  }
380
282
 
@@ -462,6 +364,7 @@ const tui: TuiPlugin = async (api) => {
462
364
  api.slots.register({
463
365
  slots: {
464
366
  session_prompt_right(_ctx, value) {
367
+ debug(`slot_callback: session=${value.session_id}`)
465
368
  return <SessionPromptRight api={api} sessionID={value.session_id} tracker={tracker} version={version} clock={clock} />
466
369
  },
467
370
  },