@troed/oc-ls-stats 1.6.0 → 1.6.2

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 CHANGED
@@ -77,10 +77,12 @@ The plugin detects each server's type automatically by probing `GET /health`: a
77
77
 
78
78
  ### Slot Polling
79
79
 
80
- Every 500ms, the plugin polls each discovered server, always carrying the current session's model as `?model=<model>`. For a llama.cpp server it calls `GET /slots?model=<model>`; for a Strata or Basalt server it calls `GET /health?model=<model>` (to identify the server) and `GET /metrics?model=<model>` (reading the `live` object). Plain llama.cpp, Strata and Basalt servers ignore the extra parameter; a routing layer that dispatches by model (e.g. one fronting several nodes) uses it to forward the call to the backend serving that model. If the model cannot be discovered from the current route's session, the plugin polls without it — direct servers still answer, while a model-dispatched router rejects the bare call and the plugin shows `n/a`.
80
+ Every 500ms, the plugin polls each discovered server, always carrying the selected model as `?model=<model>` — the prompt's live selection, falling back to the session record. For a llama.cpp server it calls `GET /slots?model=<model>`; for a Strata or Basalt server it calls `GET /health?model=<model>` (to identify the server) and `GET /metrics?model=<model>` (reading the `live` object). Plain llama.cpp, Strata and Basalt servers ignore the extra parameter; a routing layer that dispatches by model (e.g. one fronting several nodes) uses it to forward the call to the backend serving that model. If no model is known yet, the plugin polls without it — direct servers still answer, while a model-dispatched router rejects the bare call and the plugin shows `n/a`.
81
81
 
82
82
  When a server returns an error (e.g. HTTP 502) or is unreachable, the plugin backs off with an exponentially increasing delay per server (1s, 2s, 4s, ...) capped at 10s, with a small random jitter to stagger multiple servers. Backoff resets as soon as the server responds successfully again.
83
83
 
84
+ A single failed poll is not treated as an outage: a routing layer in front of a single-slot backend briefly answers 503 (or holds `/slots` open) while the backend switches tasks or loads a model. Requests carry a 5s timeout, an in-flight poll is never started twice, and failures inside a 10s grace window keep the last reading on screen while retrying at the normal 500ms cadence. Only once the window outlives the grace does the readout switch to `n/a` and the backoff kick in.
85
+
84
86
  ### State Classification
85
87
 
86
88
  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:
@@ -128,7 +130,7 @@ Both instead report the live rates directly in `GET /metrics`, under `live`:
128
130
  - `prefill_tok_s_mean` — prompt processing rate while `reading` (PP)
129
131
  - `tok_s` — instantaneous decode rate while `generating` (TG)
130
132
 
131
- The plugin detects them per server URL from `GET /health` (`service: "strata"` or `service: "basalt"`) and maps these fields straight onto the display, so PP/TG are shown without delta estimation. Detection is cached per URL, and servers of all kinds can be polled side by side. Like the `/slots` requests, the plugin sends no API key; if Strata or Basalt is configured to require one, it cannot read the stats.
133
+ The plugin detects them per server URL from `GET /health` (`service: "strata"` or `service: "basalt"`) and maps these fields straight onto the display, so PP/TG are shown without delta estimation. Detection is cached per URL and model for a short TTL (10 s), and a failed `/metrics` read drops the cached kind immediately: a router that swaps the backend behind a stable URL (for example a conduct/bazinga profile swap between Basalt and llama.cpp) is re-detected instead of leaving the plugin polling the wrong endpoint. Servers of all kinds can be polled side by side. Like the `/slots` requests, the plugin sends no API key; if Strata or Basalt is configured to require one, it cannot read the stats.
132
134
 
133
135
  ## Limitations
134
136
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@troed/oc-ls-stats",
4
- "version": "1.6.0",
4
+ "version": "1.6.2",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "tui.tsx",
package/src/stats.ts CHANGED
@@ -2,6 +2,47 @@ export function backoffDelayMs(failures: number, baseMs: number = 1000, maxMs: n
2
2
  return Math.min(maxMs, baseMs * 2 ** (failures - 1))
3
3
  }
4
4
 
5
+ // --- Transient stats failures ------------------------------------------------
6
+ // A stats request should never hang the poll loop: a routing layer can hold a
7
+ // /slots request open while the backend switches tasks or loads a model.
8
+ // Conduct's own /health handler can spend ~4s probing a slow node, so the
9
+ // timeout must sit above that or the plugin gives up on answers it would get.
10
+ export const STATS_REQUEST_TIMEOUT_MS = 5_000
11
+
12
+ // A single failed poll is not necessarily an outage. A router in front of a
13
+ // single-slot backend briefly answers 503 (or hangs) while the backend switches
14
+ // tasks, so the readout keeps its last reading and retries at the normal poll
15
+ // cadence until this window expires.
16
+ export const STATS_STALE_GRACE_MS = 10_000
17
+
18
+ /**
19
+ * Tracks consecutive failed stats polls so a short router hiccup (a slot
20
+ * handover) does not blank the readout and grow the retry backoff. The window
21
+ * opens on the first failure; failures inside the grace are reported as stale
22
+ * (keep the last reading), and only a window that outlives the grace counts as
23
+ * an outage. A successful poll resets the window.
24
+ */
25
+ export class PollFailureWindow {
26
+ private startedAt: number | null = null
27
+ private count = 0
28
+
29
+ constructor(private readonly graceMs: number = STATS_STALE_GRACE_MS) {}
30
+
31
+ failure(now: number = Date.now()): { consecutive: number; expired: boolean } {
32
+ if (this.startedAt === null) {
33
+ this.startedAt = now
34
+ this.count = 0
35
+ }
36
+ this.count += 1
37
+ return { consecutive: this.count, expired: now - this.startedAt >= this.graceMs }
38
+ }
39
+
40
+ success(): void {
41
+ this.startedAt = null
42
+ this.count = 0
43
+ }
44
+ }
45
+
5
46
  export interface SlotState {
6
47
  id: number
7
48
  is_processing: boolean
@@ -401,3 +442,61 @@ export function statsUrl(baseUrl: string, path: string, model?: string): string
401
442
  export function serverKindKey(baseUrl: string, model?: string): string {
402
443
  return `${baseUrl}\u0000${model ?? ""}`
403
444
  }
445
+
446
+ // --- Server-kind cache ------------------------------------------------------
447
+ // A routing layer (conduct) answers /health for whichever backend it currently
448
+ // has loaded, not per model, so the kind behind a stable URL changes when the
449
+ // router swaps backends (a bazinga basalt -> llama flavor swap). The cache must
450
+ // therefore expire, and a failed backend-specific probe must invalidate it, or
451
+ // the plugin keeps calling /metrics on a llama server and shows n/a.
452
+
453
+ export const SERVER_KIND_TTL_MS = 10_000
454
+
455
+ export class ServerKindCache {
456
+ private readonly entries = new Map<string, { kind: ServerType; at: number }>()
457
+
458
+ constructor(private readonly ttlMs: number = SERVER_KIND_TTL_MS) {}
459
+
460
+ /** Drop a cached kind so the next resolve probes /health again. */
461
+ invalidate(baseUrl: string, model?: string): void {
462
+ this.entries.delete(serverKindKey(baseUrl, model))
463
+ }
464
+
465
+ /**
466
+ * Return the cached kind while it is fresh, else probe. An unavailable
467
+ * /health is reported as "llama" (the historical fallback) and not cached,
468
+ * so a later probe can still identify a Strata or Basalt server.
469
+ */
470
+ async resolve(
471
+ baseUrl: string,
472
+ model: string | undefined,
473
+ probe: () => Promise<ServerType | null>,
474
+ now: number = Date.now(),
475
+ ): Promise<ServerType> {
476
+ const key = serverKindKey(baseUrl, model)
477
+ const cached = this.entries.get(key)
478
+ if (cached && now - cached.at < this.ttlMs) return cached.kind
479
+ const kind = await probe()
480
+ if (kind == null) return "llama"
481
+ this.entries.set(key, { kind, at: now })
482
+ return kind
483
+ }
484
+ }
485
+
486
+ export interface PollModel {
487
+ id: string
488
+ providerID?: string
489
+ }
490
+
491
+ /**
492
+ * The model to poll for. The prompt's live selection changes before the
493
+ * session record does, so prefer it and fall back to the session's model.
494
+ */
495
+ export function selectPollModel(
496
+ prompt: { modelID: string; providerID: string } | undefined,
497
+ session: { id: string; providerID: string } | undefined,
498
+ ): PollModel | undefined {
499
+ if (prompt && prompt.modelID) return { id: prompt.modelID, providerID: prompt.providerID }
500
+ if (session && session.id) return { id: session.id, providerID: session.providerID }
501
+ return undefined
502
+ }
package/tui.tsx CHANGED
@@ -12,6 +12,10 @@ import {
12
12
  mapLiveMetrics,
13
13
  statsUrl,
14
14
  serverKindKey,
15
+ ServerKindCache,
16
+ PollFailureWindow,
17
+ STATS_REQUEST_TIMEOUT_MS,
18
+ selectPollModel,
15
19
  type ServerType,
16
20
  } from "./src/stats.ts"
17
21
 
@@ -55,8 +59,9 @@ function estimateStreamTokens(delta: string) {
55
59
  }
56
60
 
57
61
  async function fetchSlots(baseUrl: string, model?: string): Promise<unknown | null> {
62
+ const url = statsUrl(baseUrl, "/slots", model)
58
63
  try {
59
- const resp = await fetch(statsUrl(baseUrl, "/slots", model))
64
+ const resp = await fetch(url, { signal: AbortSignal.timeout(STATS_REQUEST_TIMEOUT_MS) })
60
65
  if (!resp.ok) return null
61
66
  return await resp.json()
62
67
  } catch {
@@ -65,8 +70,9 @@ async function fetchSlots(baseUrl: string, model?: string): Promise<unknown | nu
65
70
  }
66
71
 
67
72
  async function fetchHealth(baseUrl: string, model?: string): Promise<unknown | null> {
73
+ const url = statsUrl(baseUrl, "/health", model)
68
74
  try {
69
- const resp = await fetch(statsUrl(baseUrl, "/health", model))
75
+ const resp = await fetch(url, { signal: AbortSignal.timeout(STATS_REQUEST_TIMEOUT_MS) })
70
76
  if (!resp.ok) return null
71
77
  return await resp.json()
72
78
  } catch {
@@ -80,8 +86,9 @@ async function fetchHealth(baseUrl: string, model?: string): Promise<unknown | n
80
86
  // the backend can forward the call; plain llama.cpp / Strata / Basalt servers
81
87
  // ignore the parameter.
82
88
  async function fetchLiveMetrics(baseUrl: string, model?: string): Promise<unknown | null> {
89
+ const url = statsUrl(baseUrl, "/metrics", model)
83
90
  try {
84
- const resp = await fetch(statsUrl(baseUrl, "/metrics", model))
91
+ const resp = await fetch(url, { signal: AbortSignal.timeout(STATS_REQUEST_TIMEOUT_MS) })
85
92
  if (!resp.ok) return null
86
93
  const body = await resp.json()
87
94
  if (body && typeof body === "object" && "live" in body) return (body as { live: unknown }).live
@@ -216,6 +223,7 @@ const tui: TuiPlugin = async (api, options) => {
216
223
  let llamaServerUrls: string[] = []
217
224
  let llamaServerModel: string | undefined
218
225
  const backoffByUrl = new Map<string, { failures: number; nextRetryAt: number }>()
226
+ const outage = new PollFailureWindow()
219
227
  const serverKindByUrl = new Map<string, ServerType>()
220
228
  const forcedServerType = serverTypeOverride((options as Record<string, unknown> | undefined)?.serverType)
221
229
 
@@ -279,9 +287,10 @@ const tui: TuiPlugin = async (api, options) => {
279
287
  if ((await resolveServerKind(baseUrl, model)) !== "llama") {
280
288
  const live = await fetchLiveMetrics(baseUrl, model)
281
289
  if (live == null) {
282
- noteServerFailure(baseUrl)
290
+ if (outage.failure().expired) noteServerFailure(baseUrl)
283
291
  continue
284
292
  }
293
+ outage.success()
285
294
  backoffByUrl.delete(baseUrl)
286
295
  tracker.failure = null
287
296
  mapLiveMetrics(live, tracker)
@@ -291,9 +300,13 @@ const tui: TuiPlugin = async (api, options) => {
291
300
 
292
301
  const slots = await fetchSlots(baseUrl, model)
293
302
  if (slots == null) {
294
- noteServerFailure(baseUrl)
303
+ // A handover on a single-slot backend briefly 503s or stalls /slots.
304
+ // Keep the last reading inside the grace and only back off once the
305
+ // outage outlives it.
306
+ if (outage.failure().expired) noteServerFailure(baseUrl)
295
307
  continue
296
308
  }
309
+ outage.success()
297
310
 
298
311
  backoffByUrl.delete(baseUrl)
299
312
  const slotList = Array.isArray(slots) ? slots : Object.values(slots)
@@ -370,8 +383,15 @@ const tui: TuiPlugin = async (api, options) => {
370
383
  pruneSamples()
371
384
  }, 1000)
372
385
 
386
+ let polling = false
373
387
  const slotTimer = setInterval(async () => {
374
- await pollMetrics()
388
+ if (polling) return
389
+ polling = true
390
+ try {
391
+ await pollMetrics()
392
+ } finally {
393
+ polling = false
394
+ }
375
395
  }, SLOT_POLL_MS)
376
396
 
377
397
  api.lifecycle.onDispose(() => {
@@ -506,21 +526,16 @@ const v2Setup = async (context: any) => {
506
526
  let llamaServerUrls: string[] = []
507
527
  let providerList: unknown[] = []
508
528
  const backoffByUrl = new Map<string, { failures: number; nextRetryAt: number }>()
509
- const serverKindByUrl = new Map<string, ServerType>()
529
+ const outage = new PollFailureWindow()
530
+ const serverKindCache = new ServerKindCache()
510
531
  const forcedServerType = serverTypeOverride((context.options as Record<string, unknown> | undefined)?.serverType)
511
532
 
512
533
  const resolveServerKind = async (baseUrl: string, model?: string): Promise<ServerType> => {
513
534
  if (forcedServerType) return forcedServerType
514
- const key = serverKindKey(baseUrl, model)
515
- const cached = serverKindByUrl.get(key)
516
- if (cached) return cached
517
- const health = await fetchHealth(baseUrl, model)
518
- if (health != null) {
519
- const kind = serverTypeFromHealth(health)
520
- serverKindByUrl.set(key, kind)
521
- return kind
522
- }
523
- return "llama"
535
+ return serverKindCache.resolve(baseUrl, model, async () => {
536
+ const health = await fetchHealth(baseUrl, model)
537
+ return health == null ? null : serverTypeFromHealth(health)
538
+ })
524
539
  }
525
540
 
526
541
  const noteServerFailure = (baseUrl: string) => {
@@ -545,16 +560,13 @@ const v2Setup = async (context: any) => {
545
560
  const pollMetrics = async () => {
546
561
  if (!llamaServerUrls.length) return
547
562
 
548
- let model: string | undefined
549
- let sessionProviderId: string | undefined
550
563
  const routeSessionID = currentSessionID()
551
- if (routeSessionID) {
552
- const session = context.data.session.get(routeSessionID)
553
- if (session?.model?.id) {
554
- model = session.model.id
555
- }
556
- sessionProviderId = session?.model?.providerID
557
- }
564
+ const route = context.ui.router.current?.()
565
+ const promptModel = route?.sessionID ? context.ui.model?.current?.() : undefined
566
+ const session = routeSessionID ? context.data.session.get(routeSessionID) : undefined
567
+ const selected = selectPollModel(promptModel, session?.model)
568
+ const model = selected?.id
569
+ const sessionProviderId = selected?.providerID
558
570
 
559
571
  const activeUrls = selectSessionUrls(llamaServerUrls, providerList, sessionProviderId)
560
572
  if (!activeUrls.length) {
@@ -574,9 +586,14 @@ const v2Setup = async (context: any) => {
574
586
  if ((await resolveServerKind(baseUrl, model)) !== "llama") {
575
587
  const live = await fetchLiveMetrics(baseUrl, model)
576
588
  if (live == null) {
577
- noteServerFailure(baseUrl)
589
+ // A router can swap the backend behind this URL (a bazinga flavor
590
+ // swap), and /health then reports the new one. Drop the cached kind
591
+ // so the next poll re-detects instead of polling /metrics forever.
592
+ serverKindCache.invalidate(baseUrl, model)
593
+ if (outage.failure().expired) noteServerFailure(baseUrl)
578
594
  continue
579
595
  }
596
+ outage.success()
580
597
  backoffByUrl.delete(baseUrl)
581
598
  tracker.failure = null
582
599
  mapLiveMetrics(live, tracker)
@@ -586,9 +603,13 @@ const v2Setup = async (context: any) => {
586
603
 
587
604
  const slots = await fetchSlots(baseUrl, model)
588
605
  if (slots == null) {
589
- noteServerFailure(baseUrl)
606
+ // A handover on a single-slot backend briefly 503s or stalls /slots.
607
+ // Keep the last reading inside the grace and only back off once the
608
+ // outage outlives it.
609
+ if (outage.failure().expired) noteServerFailure(baseUrl)
590
610
  continue
591
611
  }
612
+ outage.success()
592
613
 
593
614
  backoffByUrl.delete(baseUrl)
594
615
  const slotList = Array.isArray(slots) ? slots : Object.values(slots)
@@ -672,8 +693,15 @@ const v2Setup = async (context: any) => {
672
693
  pruneSamples()
673
694
  }, 1000)
674
695
 
675
- const slotTimer = setInterval(() => {
676
- void pollMetrics()
696
+ let polling = false
697
+ const slotTimer = setInterval(async () => {
698
+ if (polling) return
699
+ polling = true
700
+ try {
701
+ await pollMetrics()
702
+ } finally {
703
+ polling = false
704
+ }
677
705
  }, SLOT_POLL_MS)
678
706
 
679
707
  try {