-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathhttp_debug_network.go
More file actions
1630 lines (1501 loc) · 61.8 KB
/
Copy pathhttp_debug_network.go
File metadata and controls
1630 lines (1501 loc) · 61.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package hmnet
import (
"context"
"fmt"
"html/template"
"math"
"net/http"
"sort"
"time"
"seed/backend/hmnet/syncing"
"seed/backend/util/bwcounter"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
)
// NetworkDebugHandler returns an interactive HTML report of per-phase
// sync/discovery latency, peer-table state, and reachability — modeled on
// /debug/traces. Latency cells are color-coded against fixed thresholds
// (p10>50ms, p50>100ms, p90>1s, p99>5s warn).
//
// schedulerSnap is an optional callback returning the syncing scheduler's
// counters. Pass nil if no syncing service is wired up; the page omits the
// scheduler section in that case.
func (n *Node) NetworkDebugHandler(schedulerSnap func() syncing.SchedulerSnapshot) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
page := n.buildPage(r.Context())
page.Scheduler = buildScheduler(schedulerSnap)
if err := pageTpl.Execute(w, page); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
}
// --- page data model --------------------------------------------------------
type networkPage struct {
GeneratedAt string
Uptime string
PeerID string
ProtocolID string
HowToRead template.HTML
Sections []section
Bandwidth bandwidthSection
Reachability reachSection
Scheduler *schedulerDebugSection
}
// schedulerDebugSection renders the syncing scheduler's instantaneous
// queue/in-progress sizes plus cumulative preemption counters, so a human
// looking at /debug/network can confirm whether the preemption machinery
// is firing at all in production.
type schedulerDebugSection struct {
TasksTotal string
QueueLen string
InProgress string
InProgressHot string
InProgressSubscription string
PreemptHotCount string
PreemptSubsCount string
}
// bandwidthSection holds all bandwidth-related tables for the page. Each table
// is independent and may be empty if no traffic has been recorded for that
// layer yet. The layout is intentionally a single H2 with multiple sub-tables
// so the user can compare loopback vs remote across libp2p / HTTP server /
// HTTP client without scrolling.
type bandwidthSection struct {
Help template.HTML
Layers []bwLayerRow
Protocols []bwTagRow // libp2p protocol breakdown
Peers []bwPeerRow
HTTPIn []bwTagRow // inbound HTTP by URL-prefix tag
HTTPOut []bwTagRow // outbound HTTP by destination host
Bitswap *bitswapDedupRow
DB *dbGrowthRow
SyncDiscard *syncDiscardRow
Drift *indexDriftRow
CodecMismatch []codecMismatchRow
Preflight *preflightRow
}
// preflightRow shows how many CIDs the syncing pre-flight Has filter has
// dropped from RBSR-produced wantlists before bitswap got to fetch them.
// Each skipped CID is one WANT_HAVE → HAVE → WANT_BLOCK → BLOCK round-trip
// AND one block delivery NOT paid for on the wire — the inbound bandwidth
// the filter is actively saving versus letting the request go through and
// dropping at putBlock with the `exists` outcome.
type preflightRow struct {
Skipped string
// SkippedClass goes "good" when we're saving real fetches, neutral
// when nothing has been filtered yet (newly started daemon).
SkippedClass string
}
// indexDriftRow surfaces the count of blobs present on disk but missing from
// structural_blobs — exactly the rows RBSR's local-set query (collectBlobs in
// discovery.go) cannot see. Non-zero DagCbor here is the smoking gun for
// "RBSR keeps asking for blobs we already have."
type indexDriftRow struct {
Total string
TotalBytes string
DagCbor string
DagPb string
Other string
Class string
}
// codecMismatchRow shows the (stored_codec → incoming_codec) pairs whenever
// putBlock takes the `exists` branch. Non-zero rows mean RBSR's CID-keyed set
// diff is asymmetric for the same content because peers ship the same
// multihash under a different codec than we have stored.
type codecMismatchRow struct {
StoredCodec string
IncomingCodec string
Count string
}
// dbGrowthRow shows SQLite logical size at startup vs now, with the absolute
// growth and the implied compression-ratio against bitswap-received unique
// bytes. Surfaced so a user can compare on-the-wire downloads against actual
// disk growth in the same session.
type dbGrowthRow struct {
StartSize string
NowSize string
Growth string
Elapsed string
GrowthVsRecv string // e.g. "growth / unique recv = 0.42 (i.e. ~58% of unique blob bytes never reached disk)"
}
// syncDiscardRow now surfaces persist-pipeline health. The original "ctx
// cancelled before persist" path no longer exists post-streaming refactor,
// but we keep the discard counter (should be 0) and add the rollback counter
// for the new failure mode: a streaming PutMany batch that fails inside
// indexBlob (most often a cross-blob ordering dependency).
type syncDiscardRow struct {
Events string
Blocks string
RollbackBatches string
RollbackBlocks string
HasDiscard bool
HasRollback bool
}
// bitswapDedupRow shows how much of the bitswap recv stream is wasted on
// duplicate blocks (the same blob delivered by multiple peers). A high
// duplicate share is the smoking gun for "WANT broadcast to N peers, M
// peers raced to send the block" — it directly explains spikes in libp2p
// remote-in without corresponding new content downloaded.
//
// The Already* fields surface putBlock outcome counters so we can see the
// distinct case "block delivered from the network but blobs row already
// populated" — that means we re-fetched something we already had.
type bitswapDedupRow struct {
BlocksReceived string
DataReceived string
DupBlocks string
DupData string
DupDataPct string
DupDataPctClass string
BlocksSent string
DataSent string
NewBlocks string
NewBytes string
UpdateBlocks string
UpdateBytes string
AlreadyBlocks string
AlreadyBytes string
AlreadyPct string
AlreadyPctClass string
}
type bwLayerRow struct {
Layer string
LoopbackIn string
LoopbackOut string
RemoteIn string
RemoteOut string
Total string
}
type bwTagRow struct {
Scope string // "loopback" or "remote"
Tag string
In string
Out string
}
type bwPeerRow struct {
PeerID string
Scope string
In string
Out string
LastActive string
}
type section struct {
Title string
Subtitle string
Note string
// Help is HTML rendered inside a collapsible <details> block beneath the
// table. Use it for short row-by-row explanations so newcomers can
// orient themselves without leaving the page.
Help template.HTML
// Each section renders one of:
// Latency: per-row p10/p50/p90/p99 + count
// Counter: per-row label + count
// Bucket: per-row "<= X" + count
// KV: per-row key/value diagnostic values
Latency *latencyTable
Counter *counterTable
Bucket *bucketTable
KV *kvTable
}
// withHelp attaches a Help HTML blob to a section produced by one of the
// build* helpers. Lets buildPage stay declarative: each section is one line
// "build the table, attach the explanation."
func withHelp(s section, h template.HTML) section {
s.Help = h
return s
}
type latencyTable struct {
LabelHeader string // e.g. "phase" or "outcome"
N uint64
Rows []latencyRow
}
type latencyRow struct {
Label string
HasData bool
P10 string
P50 string
P90 string
P99 string
Count uint64
// Severity classes computed at build time so the template stays simple.
P10Class string
P50Class string
P90Class string
P99Class string
}
type counterTable struct {
LabelHeader string
Rows []counterRow
Total uint64
}
type counterRow struct {
Label string
Count uint64
Class string // optional severity (e.g. high idle_timeout share)
}
type kvTable struct {
Rows []kvRow
}
type kvRow struct {
Key string
Value string
Class string
}
type bucketTable struct {
N uint64
Mean string // pre-formatted mean (with unit)
Rows []bucketRow
UpperLabel string // e.g. "<= ratio" or "<= blobs"
}
type bucketRow struct {
UpperBound string
Count uint64
}
type reachSection struct {
Total int
Rows []reachRow
OverflowN int
}
type reachRow struct {
PID string
State string
Class string // green for Connected, gray for NotConnected
}
// --- thresholds for severity highlighting ----------------------------------
const (
warnP10 = 50 * time.Millisecond
warnP50 = 100 * time.Millisecond
warnP90 = 1 * time.Second
warnP99 = 5 * time.Second
)
// --- page builder -----------------------------------------------------------
func (n *Node) buildPage(ctx context.Context) networkPage {
page := networkPage{
GeneratedAt: time.Now().Format("15:04:05"),
PeerID: n.p2p.Host.ID().String(),
ProtocolID: string(n.protocol.ID),
HowToRead: helpHowToRead,
}
if !n.startedAt.IsZero() {
page.Uptime = time.Since(n.startedAt).Truncate(time.Second).String()
} else {
page.Uptime = "—"
}
page.Sections = []section{
withHelp(buildLatencySection(
"Discovery latency",
"time spent in each phase of one Subscribe / DiscoverObject call",
"phase",
"seed_discover_phase_seconds",
[]string{"peer_select", "connected_sync", "dht_discover", "dht_sync"},
), helpDiscoveryPhases),
withHelp(buildLatencySection(
"Discovery end-to-end",
"total Subscribe wall-clock, grouped by how it ended",
"outcome",
"seed_discover_total_seconds",
[]string{"connected", "dht", "notfound", "error"},
), helpDiscoveryOutcomes),
withHelp(buildLatencySection(
"Sync-with-peer latency",
"for each peer in a sync, time per phase (multiple peers run in parallel)",
"phase",
"seed_syncpeer_phase_seconds",
[]string{"dial", "reconcile_rpc", "bitswap_fetch", "putmany"},
), helpSyncPeerPhases),
withHelp(buildBitswapOutcomesSection(), helpBitswapOutcomes),
withHelp(buildLatencySection(
"Bitswap fetch wall-clock by outcome",
"same per-call timing as bitswap_fetch above, split by why the loop ended",
"outcome",
"seed_syncpeer_bitswap_seconds",
[]string{"complete", "idle_timeout", "ctx_done"},
), helpBitswapByOutcome),
withHelp(buildLatencySection(
"Bitswap last-block-age at loop exit",
"time between the final block we received and the loop exit",
"outcome",
"seed_syncpeer_bitswap_last_block_age_seconds",
[]string{"complete", "idle_timeout", "ctx_done"},
), helpBitswapLastBlockAge),
withHelp(buildBitswapCompletenessSection(), helpBitswapCompleteness),
withHelp(buildBucketSection(
"Wantlist size per peer-sync (RBSR diff)",
"how many blobs RBSR identified as missing from us, per peer. Healthy: clusters near 0. High and stable: RBSR's local-set query is undercounting what we have on disk and we re-fetch every cycle.",
"<= wants",
"seed_syncpeer_wanted_blobs",
"%.0f",
), helpWantlistSize),
withHelp(buildLatencySection(
"Reconcile server sub-phase",
"when other peers call OUR ReconcileBlobs, what we spend time on (proxy for what gateways spend when WE call them)",
"phase",
"seed_reconcile_server_phase_seconds",
[]string{"auth_resolve", "load_store", "rbsr_session", "rbsr_reconcile"},
), helpReconcileServerPhases),
withHelp(buildReconcileServerTotalSection(), helpReconcileServerTotal),
withHelp(buildReconcileLimiterSection(), helpReconcileLimiter),
withHelp(buildBucketSection(
"Reconcile server: store size per request",
"how many blobs the RBSR set ends up holding per inbound request",
"<= blobs",
"seed_reconcile_server_store_size",
"%.0f",
), helpReconcileServerStoreSize),
withHelp(buildLatencySection(
"Reconcile client by connection reuse",
"per-round timing of OUR outbound ReconcileBlobs, split by whether we reused an existing gRPC connection to this peer",
"call",
"seed_reconcile_client_round_seconds",
[]string{"new_conn", "reused_conn"},
), helpReconcileClientConnReuse),
withHelp(buildSyncOutcomesSection(), helpSyncOutcomes),
}
page.Bandwidth = n.buildBandwidth(ctx)
page.Reachability = n.buildReachability()
return page
}
// buildScheduler renders a syncing-scheduler snapshot block, or nil if no
// snapshot func was provided.
func buildScheduler(snap func() syncing.SchedulerSnapshot) *schedulerDebugSection {
if snap == nil {
return nil
}
s := snap()
return &schedulerDebugSection{
TasksTotal: fmt.Sprintf("%d", s.TasksTotal),
QueueLen: fmt.Sprintf("%d", s.QueueLen),
InProgress: fmt.Sprintf("%d", s.InProgress),
InProgressHot: fmt.Sprintf("%d", s.InProgressHot),
InProgressSubscription: fmt.Sprintf("%d", s.InProgressSubscription),
PreemptHotCount: fmt.Sprintf("%d", s.PreemptHotCount),
PreemptSubsCount: fmt.Sprintf("%d", s.PreemptSubsCount),
}
}
// buildBandwidth assembles the bandwidth section from the libp2p metrics and
// the two HTTP counters owned by the Node. Numbers are pre-formatted into
// human-readable strings so the template stays simple.
func (n *Node) buildBandwidth(ctx context.Context) bandwidthSection {
out := bandwidthSection{Help: helpBandwidth}
var p2p bwcounter.Snapshot
if n.metrics != nil {
p2p = n.metrics.BW.Snapshot()
}
srv := bwcounter.Snapshot{}
if n.httpServerBW != nil {
srv = n.httpServerBW.Snapshot()
}
cli := bwcounter.Snapshot{}
if n.httpClientBW != nil {
cli = n.httpClientBW.Snapshot()
}
out.Layers = []bwLayerRow{
makeLayerRow("libp2p", p2p),
makeLayerRow("http server", srv),
makeLayerRow("http client", cli),
makeTotalLayerRow(p2p, srv, cli),
}
for _, t := range topNTagRows(p2p.Tags, 12) {
out.Protocols = append(out.Protocols, formatTagRow(t))
}
for _, t := range topNTagRows(srv.Tags, 12) {
out.HTTPIn = append(out.HTTPIn, formatTagRow(t))
}
for _, t := range topNTagRows(cli.Tags, 12) {
out.HTTPOut = append(out.HTTPOut, formatTagRow(t))
}
if n.metrics != nil {
now := time.Now()
for _, p := range n.metrics.PeerBytesSnapshot(10) {
scope := "remote"
if p.Loopback {
scope = "loopback"
}
last := "—"
if !p.LastActive.IsZero() {
last = humanAgo(now.Sub(p.LastActive))
}
out.Peers = append(out.Peers, bwPeerRow{
PeerID: p.PeerID.String(),
Scope: scope,
In: humanBytes(p.In),
Out: humanBytes(p.Out),
LastActive: last,
})
}
}
var bitswapUniqueRecv uint64 // for the DB growth ratio below
if n.bitswap != nil && n.bitswap.Bitswap != nil {
if st, err := n.bitswap.Bitswap.Stat(); err == nil && st != nil {
row := &bitswapDedupRow{
BlocksReceived: fmt.Sprintf("%d", st.BlocksReceived),
DataReceived: humanBytes(st.DataReceived),
DupBlocks: fmt.Sprintf("%d", st.DupBlksReceived),
DupData: humanBytes(st.DupDataReceived),
BlocksSent: fmt.Sprintf("%d", st.BlocksSent),
DataSent: humanBytes(st.DataSent),
}
if st.DataReceived > 0 {
pct := float64(st.DupDataReceived) / float64(st.DataReceived) * 100
row.DupDataPct = fmt.Sprintf("%.1f%%", pct)
if pct > 20 {
row.DupDataPctClass = "warn"
}
} else {
row.DupDataPct = "—"
}
outcomeCounts, _ := collectCounterVec("seed_blob_putblock_outcome_total")
outcomeBytes, _ := collectCounterVec("seed_blob_putblock_bytes_total")
newBlocks := outcomeCounts["new"]
newBytes := outcomeBytes["new"]
updBlocks := outcomeCounts["update"]
updBytes := outcomeBytes["update"]
alrBlocks := outcomeCounts["exists"]
alrBytes := outcomeBytes["exists"]
row.NewBlocks = fmt.Sprintf("%.0f", newBlocks)
row.NewBytes = humanBytes(uint64(newBytes))
row.UpdateBlocks = fmt.Sprintf("%.0f", updBlocks)
row.UpdateBytes = humanBytes(uint64(updBytes))
row.AlreadyBlocks = fmt.Sprintf("%.0f", alrBlocks)
row.AlreadyBytes = humanBytes(uint64(alrBytes))
if total := newBytes + updBytes + alrBytes; total > 0 {
pct := alrBytes / total * 100
row.AlreadyPct = fmt.Sprintf("%.1f%%", pct)
if pct > 20 {
row.AlreadyPctClass = "warn"
}
} else {
row.AlreadyPct = "—"
}
out.Bitswap = row
if st.DataReceived > st.DupDataReceived {
bitswapUniqueRecv = st.DataReceived - st.DupDataReceived
}
}
}
// codec-mismatch table: rows are (stored,incoming) → count, sorted desc
if mfs, err := prometheus.DefaultGatherer.Gather(); err == nil {
var rows []codecMismatchRow
for _, mf := range mfs {
if mf.GetName() != "seed_blob_putblock_codec_mismatch_total" {
continue
}
for _, m := range mf.GetMetric() {
if m.Counter == nil {
continue
}
var stored, incoming string
for _, l := range m.GetLabel() {
switch l.GetName() {
case "stored_codec":
stored = l.GetValue()
case "incoming_codec":
incoming = l.GetValue()
}
}
rows = append(rows, codecMismatchRow{
StoredCodec: stored + " (" + codecName(stored) + ")",
IncomingCodec: incoming + " (" + codecName(incoming) + ")",
Count: fmt.Sprintf("%.0f", m.Counter.GetValue()),
})
}
}
if len(rows) > 0 {
out.CodecMismatch = rows
}
}
if drift, err := n.IndexDrift(ctx); err == nil {
row := &indexDriftRow{
Total: fmt.Sprintf("%d", drift.Total),
TotalBytes: humanBytes(uint64(drift.TotalBytes)),
DagCbor: fmt.Sprintf("%d", drift.DagCbor),
DagPb: fmt.Sprintf("%d", drift.DagPb),
Other: fmt.Sprintf("%d", drift.Other),
}
if drift.DagCbor > 0 {
row.Class = "warn"
}
out.Drift = row
}
discardEvents, _ := collectSingleMetricValue("seed_syncpeer_discarded_events_total")
discardBlocks, _ := collectSingleMetricValue("seed_syncpeer_discarded_blobs_total")
rollbackBatches, _ := collectSingleMetricValue("seed_syncpeer_persist_rollback_total")
rollbackBlocks, _ := collectSingleMetricValue("seed_syncpeer_persist_rollback_blocks_total")
preflightSkipped, _ := collectSingleMetricValue("seed_syncpeer_preflight_skipped_total")
{
row := &preflightRow{
Skipped: fmt.Sprintf("%.0f", preflightSkipped),
}
if preflightSkipped > 0 {
row.SkippedClass = "good"
}
out.Preflight = row
}
if discardEvents > 0 || rollbackBatches > 0 {
out.SyncDiscard = &syncDiscardRow{
Events: fmt.Sprintf("%.0f", discardEvents),
Blocks: fmt.Sprintf("%.0f", discardBlocks),
RollbackBatches: fmt.Sprintf("%.0f", rollbackBatches),
RollbackBlocks: fmt.Sprintf("%.0f", rollbackBlocks),
HasDiscard: discardEvents > 0,
HasRollback: rollbackBatches > 0,
}
}
startSize, startTime := n.DBSizeAtStart()
if startSize > 0 {
nowSize, err := n.DBSizeNow(ctx)
if err == nil {
var growth uint64
if nowSize > startSize {
growth = nowSize - startSize
}
elapsed := "—"
if !startTime.IsZero() {
elapsed = time.Since(startTime).Truncate(time.Second).String()
}
row := &dbGrowthRow{
StartSize: humanBytes(startSize),
NowSize: humanBytes(nowSize),
Growth: humanBytes(growth),
Elapsed: elapsed,
}
if bitswapUniqueRecv > 0 {
ratio := float64(growth) / float64(bitswapUniqueRecv)
gone := 1 - ratio
row.GrowthVsRecv = fmt.Sprintf(
"growth / unique-bitswap-recv = %s / %s = %.2f (≈%.0f%% of unique recv never reached disk)",
humanBytes(growth), humanBytes(bitswapUniqueRecv), ratio, gone*100,
)
}
out.DB = row
}
}
return out
}
func makeLayerRow(name string, s bwcounter.Snapshot) bwLayerRow {
return bwLayerRow{
Layer: name,
LoopbackIn: humanBytes(s.LoopbackIn),
LoopbackOut: humanBytes(s.LoopbackOut),
RemoteIn: humanBytes(s.RemoteIn),
RemoteOut: humanBytes(s.RemoteOut),
Total: humanBytes(s.LoopbackIn + s.LoopbackOut + s.RemoteIn + s.RemoteOut),
}
}
func makeTotalLayerRow(snaps ...bwcounter.Snapshot) bwLayerRow {
var li, lo, ri, ro uint64
for _, s := range snaps {
li += s.LoopbackIn
lo += s.LoopbackOut
ri += s.RemoteIn
ro += s.RemoteOut
}
return bwLayerRow{
Layer: "TOTAL",
LoopbackIn: humanBytes(li),
LoopbackOut: humanBytes(lo),
RemoteIn: humanBytes(ri),
RemoteOut: humanBytes(ro),
Total: humanBytes(li + lo + ri + ro),
}
}
func topNTagRows(rows []bwcounter.TagRow, n int) []bwcounter.TagRow {
// Snapshot already sorts by Total() desc.
if n > 0 && len(rows) > n {
return rows[:n]
}
return rows
}
func formatTagRow(t bwcounter.TagRow) bwTagRow {
scope := "remote"
if t.Scope == bwcounter.ScopeLoopback {
scope = "loopback"
}
tag := t.Tag
if tag == "" {
tag = "(unlabeled)"
}
return bwTagRow{
Scope: scope,
Tag: tag,
In: humanBytes(t.In),
Out: humanBytes(t.Out),
}
}
// humanBytes formats a byte count as a short string (e.g. "1.2 MB").
// Uses 1024-based units to match what users see in OS-level network monitors.
func humanBytes(n uint64) string {
const unit = 1024
if n < unit {
return fmt.Sprintf("%d B", n)
}
div, exp := uint64(unit), 0
for x := n / unit; x >= unit; x /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB", float64(n)/float64(div), "KMGTPE"[exp])
}
// codecName returns the short multicodec name for a numeric codec string.
// Covers the codecs we actually see in this codebase; everything else is "?".
func codecName(s string) string {
switch s {
case "85":
return "raw"
case "112":
return "dag-pb"
case "113":
return "dag-cbor"
case "0":
return "identity"
}
return "?"
}
func humanAgo(d time.Duration) string {
if d < time.Second {
return "just now"
}
if d < time.Minute {
return fmt.Sprintf("%ds ago", int(d.Seconds()))
}
if d < time.Hour {
return fmt.Sprintf("%dm ago", int(d.Minutes()))
}
return fmt.Sprintf("%dh ago", int(d.Hours()))
}
func buildLatencySection(title, subtitle, header, family string, rowLabels []string) section {
stats, total, ok := collectHistogramStats(family)
tbl := &latencyTable{LabelHeader: header, N: total}
if !ok {
return section{Title: title, Subtitle: subtitle, Note: "no observations yet", Latency: tbl}
}
for _, lbl := range rowLabels {
s, found := stats[lbl]
if !found || s.count == 0 {
tbl.Rows = append(tbl.Rows, latencyRow{Label: lbl, HasData: false})
continue
}
row := latencyRow{
Label: lbl,
HasData: true,
P10: formatDuration(s.percentile(0.10)),
P50: formatDuration(s.percentile(0.50)),
P90: formatDuration(s.percentile(0.90)),
P99: formatDuration(s.percentile(0.99)),
Count: s.count,
}
row.P10Class = warnClass(asDur(s.percentile(0.10)) > warnP10)
row.P50Class = warnClass(asDur(s.percentile(0.50)) > warnP50)
row.P90Class = warnClass(asDur(s.percentile(0.90)) > warnP90)
row.P99Class = warnClass(asDur(s.percentile(0.99)) > warnP99)
tbl.Rows = append(tbl.Rows, row)
}
return section{Title: title, Subtitle: subtitle, Latency: tbl}
}
func buildBitswapOutcomesSection() section {
counts, ok := collectCounterVec("seed_syncpeer_bitswap_outcome_total")
tbl := &counterTable{LabelHeader: "outcome"}
if !ok || len(counts) == 0 {
return section{Title: "Bitswap fetch outcome counts", Note: "no fetches yet", Counter: tbl}
}
var total uint64
for _, lbl := range []string{"complete", "idle_timeout", "ctx_done"} {
v := uint64(counts[lbl])
total += v
}
for _, lbl := range []string{"complete", "idle_timeout", "ctx_done"} {
c := uint64(counts[lbl])
row := counterRow{Label: lbl, Count: c}
// Highlight idle_timeout if it's >20% of total — that means the timer is firing on a meaningful share.
if lbl == "idle_timeout" && total > 0 && float64(c)/float64(total) > 0.2 {
row.Class = "warn"
}
tbl.Rows = append(tbl.Rows, row)
}
tbl.Total = total
return section{
Title: "Bitswap fetch outcome counts",
Subtitle: "termination reason for each download loop",
Counter: tbl,
}
}
func buildBitswapCompletenessSection() section {
mf, _ := findMetricFamily("seed_syncpeer_bitswap_completeness_ratio")
if mf == nil || len(mf.Metric) == 0 || mf.Metric[0].Histogram == nil {
return section{Title: "Bitswap completeness ratio", Note: "no fetches yet"}
}
h := mf.Metric[0].Histogram
total := h.GetSampleCount()
if total == 0 {
return section{Title: "Bitswap completeness ratio", Note: "no fetches yet"}
}
tbl := &bucketTable{
N: total,
Mean: formatRatio(h.GetSampleSum() / float64(total)),
UpperLabel: "<= ratio",
}
var prev uint64
for _, b := range h.GetBucket() {
cum := b.GetCumulativeCount()
tbl.Rows = append(tbl.Rows, bucketRow{
UpperBound: formatRatio(b.GetUpperBound()),
Count: cum - prev,
})
prev = cum
}
if overflow := total - prev; overflow > 0 {
tbl.Rows = append(tbl.Rows, bucketRow{UpperBound: "> 1.0", Count: overflow})
}
return section{
Title: "Bitswap completeness ratio",
Subtitle: "downloaded / wanted per fetch — 1.00 means we got every blob asked",
Bucket: tbl,
}
}
func buildReconcileServerTotalSection() section {
mf, _ := findMetricFamily("seed_reconcile_server_total_seconds")
if mf == nil || len(mf.Metric) == 0 || mf.Metric[0].Histogram == nil {
return section{Title: "Reconcile server: total handler", Note: "no inbound requests yet"}
}
h := mf.Metric[0].Histogram
if h.GetSampleCount() == 0 {
return section{Title: "Reconcile server: total handler", Note: "no inbound requests yet"}
}
s := &histStats{count: h.GetSampleCount(), sum: h.GetSampleSum(), buckets: h.GetBucket()}
tbl := &latencyTable{LabelHeader: "row", N: s.count, Rows: []latencyRow{{
Label: "TOTAL",
HasData: true,
P10: formatDuration(s.percentile(0.10)),
P50: formatDuration(s.percentile(0.50)),
P90: formatDuration(s.percentile(0.90)),
P99: formatDuration(s.percentile(0.99)),
Count: s.count,
P10Class: warnClass(asDur(s.percentile(0.10)) > warnP10),
P50Class: warnClass(asDur(s.percentile(0.50)) > warnP50),
P90Class: warnClass(asDur(s.percentile(0.90)) > warnP90),
P99Class: warnClass(asDur(s.percentile(0.99)) > warnP99),
}}}
return section{
Title: "Reconcile server: total handler",
Subtitle: "directly comparable to client-side reconcile_rpc",
Latency: tbl,
}
}
func buildReconcileLimiterSection() section {
tbl := &kvTable{}
limit, limitOK := collectSingleMetricValue("seed_reconcile_server_limiter_limit")
inFlight, _ := collectSingleMetricValue("seed_reconcile_server_limiter_in_flight")
waiting, _ := collectSingleMetricValue("seed_reconcile_server_limiter_waiting")
accepted, _ := collectSingleMetricValue("seed_reconcile_server_limiter_accepted_total")
rejected, _ := collectSingleMetricValue("seed_reconcile_server_limiter_rejected_total")
limitValue := "—"
if limitOK {
if limit < 0 {
limitValue = "unlimited"
} else {
limitValue = fmt.Sprintf("%.0f", limit)
}
}
inFlightClass := "num"
if limitOK && limit > 0 && inFlight >= limit {
inFlightClass = "num warn"
}
waitingClass := "num"
if waiting > 0 {
waitingClass = "num warn"
}
rejectedClass := "num"
if rejected > 0 {
rejectedClass = "num warn"
}
tbl.Rows = append(tbl.Rows,
kvRow{Key: "limit", Value: limitValue, Class: "num"},
kvRow{Key: "in_flight", Value: fmt.Sprintf("%.0f", inFlight), Class: inFlightClass},
kvRow{Key: "waiting", Value: fmt.Sprintf("%.0f", waiting), Class: waitingClass},
kvRow{Key: "accepted_total", Value: fmt.Sprintf("%.0f", accepted), Class: "num"},
kvRow{Key: "rejected_total", Value: fmt.Sprintf("%.0f", rejected), Class: rejectedClass},
)
queueWait := "—"
queueWaitClass := "num"
if mf, _ := findMetricFamily("seed_reconcile_server_limiter_wait_seconds"); mf != nil && len(mf.Metric) > 0 && mf.Metric[0].Histogram != nil {
h := mf.Metric[0].Histogram
if h.GetSampleCount() > 0 {
s := &histStats{count: h.GetSampleCount(), sum: h.GetSampleSum(), buckets: h.GetBucket()}
p50 := s.percentile(0.50)
p90 := s.percentile(0.90)
p99 := s.percentile(0.99)
queueWait = fmt.Sprintf("%s / %s / %s (n=%d)", formatDuration(p50), formatDuration(p90), formatDuration(p99), s.count)
if asDur(p99) > 500*time.Millisecond {
queueWaitClass = "num warn"
}
}
}
tbl.Rows = append(tbl.Rows, kvRow{Key: "queue_wait p50/p90/p99", Value: queueWait, Class: queueWaitClass})
return section{
Title: "Inbound ReconcileBlobs limiter",
Subtitle: "server-side backpressure before expensive RBSR/SQLite work",
KV: tbl,
}
}
func buildBucketSection(title, subtitle, upperLabel, family, fmtSpec string) section {
mf, _ := findMetricFamily(family)
if mf == nil || len(mf.Metric) == 0 || mf.Metric[0].Histogram == nil {
return section{Title: title, Subtitle: subtitle, Note: "no observations yet"}
}
h := mf.Metric[0].Histogram
total := h.GetSampleCount()
if total == 0 {
return section{Title: title, Subtitle: subtitle, Note: "no observations yet"}
}
mean := fmt.Sprintf(fmtSpec, h.GetSampleSum()/float64(total))
tbl := &bucketTable{N: total, Mean: mean, UpperLabel: upperLabel}
var prev uint64
for _, b := range h.GetBucket() {
cum := b.GetCumulativeCount()
if cum-prev == 0 {
prev = cum
continue
}
tbl.Rows = append(tbl.Rows, bucketRow{
UpperBound: fmt.Sprintf(fmtSpec, b.GetUpperBound()),
Count: cum - prev,
})
prev = cum
}
if overflow := total - prev; overflow > 0 {
tbl.Rows = append(tbl.Rows, bucketRow{UpperBound: "+inf", Count: overflow})
}
return section{Title: title, Subtitle: subtitle, Bucket: tbl}
}
func buildSyncOutcomesSection() section {
counts, ok := collectCounterVec("seed_sync_outcome_total")
tbl := &counterTable{LabelHeader: "outcome"}
if !ok || len(counts) == 0 {
return section{Title: "Sync-with-peer outcomes", Note: "no observations yet", Counter: tbl}
}
labels := []string{"ok", "protocol_mismatch", "dial_failed", "rpc_error", "preempted", "putmany_failed"}
var total uint64
for _, lbl := range labels {
total += uint64(counts[lbl])
}
for _, lbl := range labels {
c := uint64(counts[lbl])
row := counterRow{Label: lbl, Count: c}
// Highlight any non-trivial error class.
if lbl != "ok" && c > 0 && total > 0 && float64(c)/float64(total) > 0.05 {
row.Class = "warn"
}
tbl.Rows = append(tbl.Rows, row)
}
tbl.Total = total
return section{
Title: "Sync-with-peer outcomes",
Subtitle: "cumulative count per syncWithPeer call",
Counter: tbl,
}
}
func (n *Node) buildReachability() reachSection {
peers := n.p2p.Peerstore().Peers()
out := reachSection{Total: len(peers)}
if len(peers) == 0 {
return out
}
type entry struct {
pid peer.ID
state string
}
rows := make([]entry, 0, len(peers))
net := n.p2p.Network()
self := n.p2p.Host.ID()
for _, pid := range peers {
if pid == self {
continue
}
rows = append(rows, entry{pid: pid, state: net.Connectedness(pid).String()})
}
sort.Slice(rows, func(i, j int) bool {
if rows[i].state != rows[j].state {
if rows[i].state == network.Connected.String() {
return true
}
if rows[j].state == network.Connected.String() {
return false
}
}