Repository navigation
Expand file tree
/
Copy pathrender_diagnostics.go
More file actions
1218 lines (1125 loc) · 36 KB
/
Copy pathrender_diagnostics.go
File metadata and controls
1218 lines (1125 loc) · 36 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 plush
import (
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/gobuffalo/plush/v5/helpers/hctx"
)
const (
RenderModeNameInterpreter = "interpreter"
RenderModeNameVM = "vm"
VMBytecodeCacheDisabled = "disabled"
VMBytecodeCacheHit = "hit"
VMBytecodeCacheHitStatic = "hit-static"
VMBytecodeCacheHitSource = "hit-source"
VMBytecodeCacheMiss = "miss"
VMBytecodeCacheMissStore = "miss-store"
VMBytecodeCacheMissStoreSource = "miss-store-source"
VMBytecodeCacheDirect = "compiled-template"
RenderFastPathStatic = "static"
RenderFastPathFast = "fast"
RenderFastPathGeneric = "generic"
RenderFastPathInterpreterFallback = "interpreter-fallback"
RenderPartialFallbackGenericBytecode RenderPartialFallbackReason = "generic-bytecode"
RenderPartialFallbackBlockCallCompatibility RenderPartialFallbackReason = "block-call-compatibility"
RenderPartialFallbackInheritedInterpreter RenderPartialFallbackReason = "inherited-interpreter"
PunchHoleCacheDisabled = "disabled"
PunchHoleCacheHit = "hit"
PunchHoleCacheMiss = "miss"
renderPartialOutputDetailLimit = 8
renderLoopOutputDetailLimit = 8
renderVMHelperPathDetailLimit = 8
renderPartialFallbackDetailLimit = 16
)
// RenderVMHelperCallPath identifies how the VM invoked a Go helper.
type RenderVMHelperCallPath string
const (
// RenderVMHelperCallDirect is a statically typed Go invocation.
RenderVMHelperCallDirect RenderVMHelperCallPath = "direct"
// RenderVMHelperCallReflection is a reflect.Value.Call compatibility invocation.
RenderVMHelperCallReflection RenderVMHelperCallPath = "reflection"
)
var renderDiagnosticsKey = "__plush_internal_render_diagnostics_" + fmt.Sprintf("%d", time.Now().UnixNano()) + "__"
var renderVMHotspotDiagnosticsKey = "__plush_internal_render_vm_hotspot_diagnostics_" + fmt.Sprintf("%d", time.Now().UnixNano()) + "__"
var renderDiagnosticsRootActiveKey = "__plush_internal_render_diagnostics_root_active_" + fmt.Sprintf("%d", time.Now().UnixNano()) + "__"
var renderPartialFallbackDiagnosticsKey = "__plush_internal_render_partial_fallback_diagnostics_" + fmt.Sprintf("%d", time.Now().UnixNano()) + "__"
var renderPartialFallbackActiveKey = "__plush_internal_render_partial_fallback_active_" + fmt.Sprintf("%d", time.Now().UnixNano()) + "__"
// RenderPartialFallbackReason describes why a partial executed through the
// interpreter while the surrounding render was using the VM.
type RenderPartialFallbackReason string
type renderDiagnosticsState struct {
mu sync.Mutex
diagnostics RenderDiagnostics
}
type RenderDiagnostics struct {
Mode string
TemplateFilename string
VMBytecodeCache string
FastPath string
FastRejectLine int
FastReject string
PunchHoleCache string
EngineDuration time.Duration
FastPlan RenderFastPlanDiagnostics
OutputSize RenderOutputSizeDiagnostics
LoopOutput RenderLoopOutputSizeDiagnostics
PartialOutput RenderPartialOutputSizeDiagnostics
VMHotspots RenderVMHotspotDiagnostics
PartialFallbacks RenderPartialFallbackDiagnostics
}
// RenderPartialFallbackDiagnostics aggregates VM partials that entered the
// interpreter. Details are bounded so diagnostics cannot grow with arbitrary
// dynamic partial names.
type RenderPartialFallbackDiagnostics struct {
Calls int
DetailsDropped int
Details []RenderPartialFallbackDetail
}
// RenderPartialFallbackDetail aggregates one partial filename and fallback
// reason within a render.
type RenderPartialFallbackDetail struct {
Name string
Reason RenderPartialFallbackReason
Calls int
}
type RenderOutputSizeDiagnostics struct {
Available bool
Scope string
Contextual bool
YieldSize int
OverheadBefore int
OverheadActual int
OverheadAfter int
OverheadPredictor string
OverheadPredictorAfter string
OverheadAbsolute int
OverheadRatio int
OverheadAbsoluteErrorScore float64
OverheadRatioErrorScore float64
StaticSize int
FallbackHint int
GrowHint int
Headroom int
EstimateBefore int
Actual int
EstimateAfter int
SamplesBefore uint64
SamplesAfter uint64
Observed bool
ProfileBand string
RefinedProfileBand string
ProfileDepth int
ProfileChildren int
ProfileFallback bool
ProfileFallbackMinimum int
YieldConsumed bool
AccuracyValid bool
Minimum int
Maximum int
Unstable bool
Limited bool
GrowCalled bool
CapacityBefore int
CapacityGrow int
CapacityFinal int
UnusedCapacity int
GrowAllocated int
}
type RenderLoopOutputSizeDiagnostics struct {
Calls int
Items int
KnownCount int
Learned int
GrowHint int
Actual int
AbsoluteError int
WithinTen int
Limited int
GrowCalls int
GrowAllocated int
Details []RenderLoopOutputSizeDetail
}
type RenderLoopOutputSizeDetail struct {
Name string
Line int
Calls int
Items int
Learned int
GrowHint int
Actual int
AbsoluteError int
WithinTen int
KnownCount int
LearnedBytesPerItem int
ActualBytesPerItem int
EstimateBytesPerItem int
SamplesBefore uint64
SamplesAfter uint64
Limited int
GrowCalls int
GrowAllocated int
}
type RenderPartialOutputSizeDiagnostics struct {
Calls int
Learned int
GrowHint int
Actual int
AbsoluteError int
WithinTen int
Unstable int
Limited int
GrowCalls int
GrowAllocated int
Details []RenderPartialOutputSizeDetail
}
type RenderPartialOutputSizeDetail struct {
Name string
Calls int
Learned int
GrowHint int
Actual int
AbsoluteError int
Estimate int
Samples uint64
Minimum int
Maximum int
Unstable bool
Limited int
GrowCalls int
GrowAllocated int
}
type RenderPartialOutputAllocation struct {
GrowCalled bool
SpeculativeAllocated int
Unstable bool
Limited bool
Minimum int
Maximum int
}
type RenderFastPlanDiagnostics struct {
Bindings int
Segments int
StaticSegments int
NameSegments int
PropertyReads int
ValueWrites int
HelperCalls int
Conditionals int
Loops int
LoopParts int
Partials int
MaxDepth int
HelperNames []string
PartialNames []string
}
type RenderVMHotspotDiagnostics struct {
HelperCalls int
HelperDuration time.Duration
HelperDirectCalls int
HelperDirectDuration time.Duration
HelperReflectionCalls int
HelperReflectionDuration time.Duration
HelperDirectDetailsDropped int
HelperReflectionDetailsDropped int
PartialCalls int
PartialDuration time.Duration
Helpers []RenderVMHotspot
Partials []RenderVMHotspot
HelperCallPaths []RenderVMHelperCallPathDiagnostics
}
type RenderVMHotspot struct {
Name string
Calls int
Duration time.Duration
}
// RenderVMHelperCallPathDiagnostics aggregates one retained helper name,
// signature, and invocation-path combination.
type RenderVMHelperCallPathDiagnostics struct {
Name string
Signature string
Path RenderVMHelperCallPath
Calls int
Duration time.Duration
}
// RenderVMHotspotDiagnosticsRecorder is a render-scoped snapshot of VM
// hotspot diagnostics. VM renderers capture it once and reuse it so disabled
// diagnostics do not require a context lookup for every helper or partial.
type RenderVMHotspotDiagnosticsRecorder struct {
state *renderDiagnosticsState
captured bool
}
func (d RenderDiagnostics) EngineDurationMilliseconds() float64 {
return float64(d.EngineDuration) / float64(time.Millisecond)
}
func (d RenderDiagnostics) VMHelperDurationMilliseconds() float64 {
return float64(d.VMHotspots.HelperDuration) / float64(time.Millisecond)
}
func (d RenderDiagnostics) VMPartialDurationMilliseconds() float64 {
return float64(d.VMHotspots.PartialDuration) / float64(time.Millisecond)
}
func (d RenderDiagnostics) VMHelperDirectDurationMilliseconds() float64 {
return float64(d.VMHotspots.HelperDirectDuration) / float64(time.Millisecond)
}
func (d RenderDiagnostics) VMHelperReflectionDurationMilliseconds() float64 {
return float64(d.VMHotspots.HelperReflectionDuration) / float64(time.Millisecond)
}
func (d RenderDiagnostics) VMHelperReflectionPercent() float64 {
if d.VMHotspots.HelperCalls == 0 {
return 0
}
return float64(d.VMHotspots.HelperReflectionCalls) * 100 / float64(d.VMHotspots.HelperCalls)
}
func (d RenderDiagnostics) FastPlanHelperNamesHeader() string {
return strings.Join(d.FastPlan.HelperNames, ";")
}
func (d RenderDiagnostics) FastPlanPartialNamesHeader() string {
return strings.Join(d.FastPlan.PartialNames, ";")
}
func (d RenderDiagnostics) OutputSizeHeader() string {
if !d.OutputSize.Available {
return ""
}
scope := d.OutputSize.Scope
if scope == "" {
scope = "template"
}
observed := 0
withinTen := 0
accuracyValid := d.OutputSize.Observed
if d.OutputSize.Contextual {
accuracyValid = accuracyValid && d.OutputSize.AccuracyValid
}
if d.OutputSize.Observed {
observed = 1
errorSize := d.OutputSize.EstimateBefore - d.OutputSize.Actual
if errorSize < 0 {
errorSize = -errorSize
}
if accuracyValid && outputSizeErrorPercent(errorSize, d.OutputSize.Actual) < 10 {
withinTen = 1
}
}
errorSize := d.OutputSize.EstimateBefore - d.OutputSize.Actual
if errorSize < 0 {
errorSize = -errorSize
}
header := fmt.Sprintf(
"scope=%s;static=%d;fallback=%d;hint=%d;headroom=%d;learned=%d;actual=%d;error=%.2f;within-10=%d;estimate=%d;samples=%d;observed=%d;accuracy-valid=%d;min=%d;max=%d;unstable=%d;limited=%d;grow-called=%d;grow-allocated=%d;cap-before=%d;cap-after-grow=%d;cap-final=%d;unused-cap=%d",
scope,
d.OutputSize.StaticSize,
d.OutputSize.FallbackHint,
d.OutputSize.GrowHint,
d.OutputSize.Headroom,
d.OutputSize.EstimateBefore,
d.OutputSize.Actual,
outputSizeErrorPercent(errorSize, d.OutputSize.Actual),
withinTen,
d.OutputSize.EstimateAfter,
d.OutputSize.SamplesAfter,
observed,
boolHeaderValue(accuracyValid),
d.OutputSize.Minimum,
d.OutputSize.Maximum,
boolHeaderValue(d.OutputSize.Unstable),
boolHeaderValue(d.OutputSize.Limited),
boolHeaderValue(d.OutputSize.GrowCalled),
d.OutputSize.GrowAllocated,
d.OutputSize.CapacityBefore,
d.OutputSize.CapacityGrow,
d.OutputSize.CapacityFinal,
d.OutputSize.UnusedCapacity,
)
if !d.OutputSize.Contextual {
return header
}
return fmt.Sprintf(
"scope=%s;profile=%s;refined-profile=%s;profile-depth=%d;profile-children=%d;profile-fallback=%d;profile-fallback-min=%d;yield=%d;yield-consumed=%d;accuracy-valid=%d;predictor=%s;predictor-after=%s;overhead=%d;overhead-absolute=%d;overhead-ratio=%d;absolute-error-score=%.2f;ratio-error-score=%.2f;overhead-actual=%d;overhead-estimate=%d;static=%d;fallback=%d;hint=%d;headroom=%d;learned=%d;actual=%d;error=%.2f;within-10=%d;estimate=%d;samples=%d;observed=%d;min=%d;max=%d;unstable=%d;limited=%d;grow-called=%d;grow-allocated=%d;cap-before=%d;cap-after-grow=%d;cap-final=%d;unused-cap=%d",
scope,
outputSizeProfileBand(d.OutputSize.ProfileBand),
outputSizeProfileBand(d.OutputSize.RefinedProfileBand),
d.OutputSize.ProfileDepth,
d.OutputSize.ProfileChildren,
boolHeaderValue(d.OutputSize.ProfileFallback),
d.OutputSize.ProfileFallbackMinimum,
d.OutputSize.YieldSize,
boolHeaderValue(d.OutputSize.YieldConsumed),
boolHeaderValue(accuracyValid),
d.OutputSize.OverheadPredictor,
d.OutputSize.OverheadPredictorAfter,
d.OutputSize.OverheadBefore,
d.OutputSize.OverheadAbsolute,
d.OutputSize.OverheadRatio,
d.OutputSize.OverheadAbsoluteErrorScore,
d.OutputSize.OverheadRatioErrorScore,
d.OutputSize.OverheadActual,
d.OutputSize.OverheadAfter,
d.OutputSize.StaticSize,
d.OutputSize.FallbackHint,
d.OutputSize.GrowHint,
d.OutputSize.Headroom,
d.OutputSize.EstimateBefore,
d.OutputSize.Actual,
outputSizeErrorPercent(errorSize, d.OutputSize.Actual),
withinTen,
d.OutputSize.EstimateAfter,
d.OutputSize.SamplesAfter,
observed,
d.OutputSize.Minimum,
d.OutputSize.Maximum,
boolHeaderValue(d.OutputSize.Unstable),
boolHeaderValue(d.OutputSize.Limited),
boolHeaderValue(d.OutputSize.GrowCalled),
d.OutputSize.GrowAllocated,
d.OutputSize.CapacityBefore,
d.OutputSize.CapacityGrow,
d.OutputSize.CapacityFinal,
d.OutputSize.UnusedCapacity,
)
}
func (d RenderDiagnostics) PartialOutputSizeHeader() string {
partial := d.PartialOutput
if partial.Calls == 0 {
return ""
}
return fmt.Sprintf(
"calls=%d;learned=%d;hint=%d;actual=%d;absolute-error=%d;error=%.2f;within-10=%d;unstable=%d;limited=%d;grow-calls=%d;grow-allocated=%d",
partial.Calls,
partial.Learned,
partial.GrowHint,
partial.Actual,
partial.AbsoluteError,
outputSizeErrorPercent(partial.AbsoluteError, partial.Actual),
partial.WithinTen,
partial.Unstable,
partial.Limited,
partial.GrowCalls,
partial.GrowAllocated,
)
}
func (d RenderDiagnostics) PartialOutputSizeDetailsHeader() string {
if len(d.PartialOutput.Details) == 0 {
return ""
}
parts := make([]string, 0, len(d.PartialOutput.Details))
for _, detail := range d.PartialOutput.Details {
parts = append(parts, fmt.Sprintf(
"name=%s,calls=%d,learned=%d,hint=%d,actual=%d,error=%.2f,estimate=%d,samples=%d,min=%d,max=%d,unstable=%d,limited=%d,grow-calls=%d,grow-allocated=%d",
partialOutputHeaderName(detail.Name),
detail.Calls,
detail.Learned,
detail.GrowHint,
detail.Actual,
outputSizeErrorPercent(detail.AbsoluteError, detail.Actual),
detail.Estimate,
detail.Samples,
detail.Minimum,
detail.Maximum,
boolHeaderValue(detail.Unstable),
detail.Limited,
detail.GrowCalls,
detail.GrowAllocated,
))
}
return strings.Join(parts, "|")
}
func AddRenderDiagnosticPartialOutput(ctx hctx.Context, name string, learned, growHint, actual, estimate int, samples uint64) {
AddRenderDiagnosticPartialOutputAllocation(ctx, name, learned, growHint, actual, estimate, samples, RenderPartialOutputAllocation{})
}
func AddRenderDiagnosticLoopOutput(ctx hctx.Context, name string, line, items, learnedBytesPerItem, growHint, actual, estimateBytesPerItem int, samplesBefore, samplesAfter uint64, itemCountKnown, limited, growCalled bool, growAllocated int) {
if ctx == nil || items <= 0 || actual < 0 {
return
}
mode := GetOutputSizeEstimatorDiagnosticsMode()
if mode == OutputSizeEstimatorDiagnosticsOff {
return
}
if name == "" {
name = "<expression>"
}
learned := outputSizeProduct(learnedBytesPerItem, items)
errorSize := learned - actual
if errorSize < 0 {
errorSize = -errorSize
}
withinTen := outputSizeErrorPercent(errorSize, actual) < 10
actualBytesPerItem := actual / items
UpdateRenderDiagnostics(ctx, func(d *RenderDiagnostics) {
loop := &d.LoopOutput
loop.Calls++
loop.Items += items
if itemCountKnown {
loop.KnownCount++
}
loop.Learned += learned
loop.GrowHint += growHint
loop.Actual += actual
loop.AbsoluteError += errorSize
if withinTen {
loop.WithinTen++
}
if limited {
loop.Limited++
}
if growCalled {
loop.GrowCalls++
}
loop.GrowAllocated += growAllocated
if mode != OutputSizeEstimatorDiagnosticsDetailed {
return
}
for i := range loop.Details {
if loop.Details[i].Name == name && loop.Details[i].Line == line {
addLoopOutputDetail(&loop.Details[i], items, learned, growHint, actual, errorSize, learnedBytesPerItem, actualBytesPerItem, estimateBytesPerItem, samplesBefore, samplesAfter, withinTen, itemCountKnown, limited, growCalled, growAllocated)
return
}
}
if len(loop.Details) >= renderLoopOutputDetailLimit {
return
}
detail := RenderLoopOutputSizeDetail{Name: name, Line: line}
addLoopOutputDetail(&detail, items, learned, growHint, actual, errorSize, learnedBytesPerItem, actualBytesPerItem, estimateBytesPerItem, samplesBefore, samplesAfter, withinTen, itemCountKnown, limited, growCalled, growAllocated)
loop.Details = append(loop.Details, detail)
})
}
func addLoopOutputDetail(detail *RenderLoopOutputSizeDetail, items, learned, growHint, actual, errorSize, learnedBytesPerItem, actualBytesPerItem, estimateBytesPerItem int, samplesBefore, samplesAfter uint64, withinTen, itemCountKnown, limited, growCalled bool, growAllocated int) {
detail.Calls++
detail.Items += items
detail.Learned += learned
detail.GrowHint += growHint
detail.Actual += actual
detail.AbsoluteError += errorSize
if withinTen {
detail.WithinTen++
}
if itemCountKnown {
detail.KnownCount++
}
detail.LearnedBytesPerItem = learnedBytesPerItem
detail.ActualBytesPerItem = actualBytesPerItem
detail.EstimateBytesPerItem = estimateBytesPerItem
detail.SamplesBefore = samplesBefore
detail.SamplesAfter = samplesAfter
if limited {
detail.Limited++
}
if growCalled {
detail.GrowCalls++
}
detail.GrowAllocated += growAllocated
}
func AddRenderDiagnosticPartialOutputAllocation(ctx hctx.Context, name string, learned, growHint, actual, estimate int, samples uint64, allocation RenderPartialOutputAllocation) {
if ctx == nil || actual < 0 {
return
}
mode := GetOutputSizeEstimatorDiagnosticsMode()
if mode == OutputSizeEstimatorDiagnosticsOff {
return
}
if name == "" {
name = "<anonymous>"
}
errorSize := learned - actual
if errorSize < 0 {
errorSize = -errorSize
}
withinTen := outputSizeErrorPercent(errorSize, actual) < 10
UpdateRenderDiagnostics(ctx, func(d *RenderDiagnostics) {
partial := &d.PartialOutput
partial.Calls++
partial.Learned += learned
partial.GrowHint += growHint
partial.Actual += actual
partial.AbsoluteError += errorSize
if withinTen {
partial.WithinTen++
}
if allocation.Unstable {
partial.Unstable++
}
if allocation.Limited {
partial.Limited++
}
if allocation.GrowCalled {
partial.GrowCalls++
}
partial.GrowAllocated += allocation.SpeculativeAllocated
if mode != OutputSizeEstimatorDiagnosticsDetailed {
return
}
for i := range partial.Details {
if partial.Details[i].Name == name {
addPartialOutputDetail(&partial.Details[i], learned, growHint, actual, errorSize, estimate, samples, allocation)
return
}
}
if len(partial.Details) >= renderPartialOutputDetailLimit {
return
}
detail := RenderPartialOutputSizeDetail{Name: name}
addPartialOutputDetail(&detail, learned, growHint, actual, errorSize, estimate, samples, allocation)
partial.Details = append(partial.Details, detail)
})
}
func addPartialOutputDetail(detail *RenderPartialOutputSizeDetail, learned, growHint, actual, errorSize, estimate int, samples uint64, allocation RenderPartialOutputAllocation) {
detail.Calls++
detail.Learned += learned
detail.GrowHint += growHint
detail.Actual += actual
detail.AbsoluteError += errorSize
detail.Estimate = estimate
detail.Samples = samples
detail.Minimum = allocation.Minimum
detail.Maximum = allocation.Maximum
detail.Unstable = allocation.Unstable
if allocation.Limited {
detail.Limited++
}
if allocation.GrowCalled {
detail.GrowCalls++
}
detail.GrowAllocated += allocation.SpeculativeAllocated
}
func boolHeaderValue(value bool) int {
if value {
return 1
}
return 0
}
func outputSizeProfileBand(band string) string {
if band == "" {
return "none"
}
return band
}
func outputSizeErrorPercent(errorSize, actual int) float64 {
if actual <= 0 {
if errorSize == 0 {
return 0
}
return 100
}
return float64(errorSize) * 100 / float64(actual)
}
func outputSizeProduct(left, right int) int {
if left <= 0 || right <= 0 {
return 0
}
maximum := int(^uint(0) >> 1)
if left > maximum/right {
return maximum
}
return left * right
}
func partialOutputHeaderName(name string) string {
name = strings.ReplaceAll(name, "\\", "/")
pathParts := strings.Split(name, "/")
trimmed := false
for i := len(pathParts) - 1; i >= 0; i-- {
if pathParts[i] == "templates" {
name = ".../" + strings.Join(pathParts[i:], "/")
trimmed = true
break
}
}
if !trimmed && len(pathParts) > 3 {
name = ".../" + strings.Join(pathParts[len(pathParts)-3:], "/")
}
name = strings.Map(func(r rune) rune {
switch r {
case ',', ';', '|', '=':
return ' '
default:
return r
}
}, name)
runes := []rune(name)
if len(runes) > 120 {
name = string(runes[:120])
}
return name
}
func (d RenderDiagnostics) VMHelperHotspotsHeader() string {
return renderVMHotspotsHeader(d.VMHotspots.Helpers)
}
func (d RenderDiagnostics) VMPartialHotspotsHeader() string {
return renderVMHotspotsHeader(d.VMHotspots.Partials)
}
func (d RenderDiagnostics) VMHelperCallPathsHeader() string {
stats := d.VMHotspots
if stats.HelperCalls == 0 {
return ""
}
unclassified := stats.HelperCalls - stats.HelperDirectCalls - stats.HelperReflectionCalls
if unclassified < 0 {
unclassified = 0
}
return fmt.Sprintf(
"direct-calls=%d;reflection-calls=%d;unclassified-calls=%d;reflection-percent=%.2f;direct-time-ms=%.3f;reflection-time-ms=%.3f;direct-details-dropped=%d;reflection-details-dropped=%d",
stats.HelperDirectCalls,
stats.HelperReflectionCalls,
unclassified,
d.VMHelperReflectionPercent(),
d.VMHelperDirectDurationMilliseconds(),
d.VMHelperReflectionDurationMilliseconds(),
stats.HelperDirectDetailsDropped,
stats.HelperReflectionDetailsDropped,
)
}
func (d RenderDiagnostics) VMHelperCallPathDetailsHeader() string {
if len(d.VMHotspots.HelperCallPaths) == 0 {
return ""
}
details := append([]RenderVMHelperCallPathDiagnostics(nil), d.VMHotspots.HelperCallPaths...)
sort.Slice(details, func(i, j int) bool {
if details[i].Path != details[j].Path {
return details[i].Path == RenderVMHelperCallReflection
}
if details[i].Duration != details[j].Duration {
return details[i].Duration > details[j].Duration
}
if details[i].Calls != details[j].Calls {
return details[i].Calls > details[j].Calls
}
if details[i].Name != details[j].Name {
return details[i].Name < details[j].Name
}
return details[i].Signature < details[j].Signature
})
if len(details) > renderVMHelperPathDetailLimit {
details = details[:renderVMHelperPathDetailLimit]
}
parts := make([]string, 0, len(details))
for _, detail := range details {
parts = append(parts, fmt.Sprintf(
"path=%s,name=%s,signature=%s,calls=%d,time-ms=%.3f",
detail.Path,
renderVMHelperPathHeaderValue(detail.Name),
renderVMHelperPathHeaderValue(detail.Signature),
detail.Calls,
float64(detail.Duration)/float64(time.Millisecond),
))
}
return strings.Join(parts, "|")
}
func AddRenderDiagnosticVMHelperTiming(ctx hctx.Context, name string, duration time.Duration) {
addRenderDiagnosticVMHotspot(ctx, name, duration, true)
}
// AddRenderDiagnosticVMHelperCall records a classified helper invocation when
// VM hotspot diagnostics are enabled on ctx.
func AddRenderDiagnosticVMHelperCall(ctx hctx.Context, name, signature string, path RenderVMHelperCallPath, duration time.Duration) {
if ctx == nil || duration < 0 || !RenderVMHotspotDiagnosticsEnabled(ctx) {
return
}
RenderVMHotspotDiagnosticsRecorder{state: renderDiagnosticsStateFromContext(ctx, true), captured: true}.AddHelperCall(name, signature, path, duration)
}
func AddRenderDiagnosticVMPartialTiming(ctx hctx.Context, name string, duration time.Duration) {
addRenderDiagnosticVMHotspot(ctx, name, duration, false)
}
// CaptureRenderVMHotspotDiagnostics snapshots the diagnostics setting for one
// render. Changes made afterward apply when the next render captures its
// recorder.
func CaptureRenderVMHotspotDiagnostics(ctx hctx.Context) RenderVMHotspotDiagnosticsRecorder {
if ctx == nil {
return RenderVMHotspotDiagnosticsRecorder{}
}
if provider, ok := ctx.(interface {
RenderVMHotspotDiagnosticsRecorder() RenderVMHotspotDiagnosticsRecorder
}); ok {
if recorder := provider.RenderVMHotspotDiagnosticsRecorder(); recorder.captured {
return recorder
}
}
if !RenderVMHotspotDiagnosticsEnabled(ctx) {
return RenderVMHotspotDiagnosticsRecorder{captured: true}
}
return RenderVMHotspotDiagnosticsRecorder{state: renderDiagnosticsStateFromContext(ctx, true), captured: true}
}
// Enabled reports whether VM hotspot timing was enabled when this recorder was
// captured.
func (r RenderVMHotspotDiagnosticsRecorder) Enabled() bool {
return r.state != nil
}
// AddHelperTiming records a helper duration without re-reading the diagnostics
// setting from the render context.
func (r RenderVMHotspotDiagnosticsRecorder) AddHelperTiming(name string, duration time.Duration) {
r.add(name, duration, true)
}
// AddHelperCall records the invocation path and Go signature of one VM helper
// call without re-reading the diagnostics setting from the render context.
func (r RenderVMHotspotDiagnosticsRecorder) AddHelperCall(name, signature string, path RenderVMHelperCallPath, duration time.Duration) {
if r.state == nil || duration < 0 {
return
}
if name == "" {
name = "<anonymous>"
}
if signature == "" {
signature = "<unknown>"
}
updateRenderDiagnosticsState(r.state, func(d *RenderDiagnostics) {
d.VMHotspots.HelperCalls++
d.VMHotspots.HelperDuration += duration
addRenderVMHotspot(&d.VMHotspots.Helpers, name, duration)
addRenderVMHelperCallPath(&d.VMHotspots, name, signature, path, duration)
})
}
// AddPartialTiming records a partial duration without re-reading the
// diagnostics setting from the render context.
func (r RenderVMHotspotDiagnosticsRecorder) AddPartialTiming(name string, duration time.Duration) {
r.add(name, duration, false)
}
func (r RenderVMHotspotDiagnosticsRecorder) add(name string, duration time.Duration, helper bool) {
if r.state == nil || duration < 0 {
return
}
if name == "" {
name = "<anonymous>"
}
updateRenderDiagnosticsState(r.state, func(d *RenderDiagnostics) {
if helper {
d.VMHotspots.HelperCalls++
d.VMHotspots.HelperDuration += duration
addRenderVMHotspot(&d.VMHotspots.Helpers, name, duration)
return
}
d.VMHotspots.PartialCalls++
d.VMHotspots.PartialDuration += duration
addRenderVMHotspot(&d.VMHotspots.Partials, name, duration)
})
}
func EnableRenderVMHotspotDiagnostics(ctx hctx.Context) {
SetRenderVMHotspotDiagnostics(ctx, true)
}
func DisableRenderVMHotspotDiagnostics(ctx hctx.Context) {
SetRenderVMHotspotDiagnostics(ctx, false)
}
func SetRenderVMHotspotDiagnostics(ctx hctx.Context, enabled bool) {
if ctx == nil {
return
}
ctx.Set(renderVMHotspotDiagnosticsKey, enabled)
if enabled {
renderDiagnosticsStateFromContext(ctx, true)
}
}
func RenderVMHotspotDiagnosticsEnabled(ctx hctx.Context) bool {
if ctx == nil {
return false
}
enabled, _ := ctx.Value(renderVMHotspotDiagnosticsKey).(bool)
return enabled
}
func RenderDiagnosticsFromContext(ctx hctx.Context) (RenderDiagnostics, bool) {
if ctx == nil {
return RenderDiagnostics{}, false
}
return renderDiagnosticsFromValue(ctx.Value(renderDiagnosticsKey))
}
func RenderDiagnosticsFromData(data map[string]interface{}) (RenderDiagnostics, bool) {
if data == nil {
return RenderDiagnostics{}, false
}
return renderDiagnosticsFromValue(data[renderDiagnosticsKey])
}
func SetRenderDiagnostics(ctx hctx.Context, diagnostics RenderDiagnostics) {
if ctx == nil {
return
}
if state := renderDiagnosticsStateFromContext(ctx, true); state != nil {
state.mu.Lock()
state.diagnostics = diagnostics
state.mu.Unlock()
}
}
func UpdateRenderDiagnostics(ctx hctx.Context, update func(*RenderDiagnostics)) {
if ctx == nil || update == nil {
return
}
state := renderDiagnosticsStateFromContext(ctx, true)
updateRenderDiagnosticsState(state, update)
}
func updateRenderDiagnosticsState(state *renderDiagnosticsState, update func(*RenderDiagnostics)) {
if state == nil || update == nil {
return
}
state.mu.Lock()
defer state.mu.Unlock()
update(&state.diagnostics)
}
func UpdateRenderDiagnosticsForTemplate(ctx hctx.Context, filename string, update func(*RenderDiagnostics)) {
if update == nil {
return
}
UpdateRenderDiagnostics(ctx, func(d *RenderDiagnostics) {
if !renderDiagnosticsCanUpdateTemplate(d, filename) {
return
}
update(d)
})
}
// AddRenderDiagnosticPartialFallback records one partial that entered the
// interpreter during a VM render. Recording is available with regular render
// diagnostics and does not require VM hotspot timing to be enabled.
func AddRenderDiagnosticPartialFallback(ctx hctx.Context, name string, reason RenderPartialFallbackReason) {
if ctx == nil || !RenderPartialFallbackDiagnosticsEnabled(ctx) {
return
}
if name == "" {
name = "<anonymous>"
}
if reason == "" {
reason = RenderPartialFallbackGenericBytecode
}
UpdateRenderDiagnostics(ctx, func(d *RenderDiagnostics) {
d.PartialFallbacks.Calls++
for i := range d.PartialFallbacks.Details {
detail := &d.PartialFallbacks.Details[i]
if detail.Name == name && detail.Reason == reason {
detail.Calls++
return
}
}
if len(d.PartialFallbacks.Details) >= renderPartialFallbackDetailLimit {
d.PartialFallbacks.DetailsDropped++
return
}
d.PartialFallbacks.Details = append(d.PartialFallbacks.Details, RenderPartialFallbackDetail{
Name: name,
Reason: reason,
Calls: 1,
})
})
}
// BeginRenderDiagnosticPartialFallback marks nested partial calls as inherited
// interpreter work until the returned restore function is called.
func BeginRenderDiagnosticPartialFallback(ctx hctx.Context) func() {
if ctx == nil || !RenderPartialFallbackDiagnosticsEnabled(ctx) {
return nil
}
previous := ctx.Value(renderPartialFallbackActiveKey)
ctx.Set(renderPartialFallbackActiveKey, true)
return func() {
if previous == nil {
ctx.Set(renderPartialFallbackActiveKey, false)
return
}
ctx.Set(renderPartialFallbackActiveKey, previous)
}
}
// RenderDiagnosticPartialFallbackActive reports whether the current
// interpreter render was entered as a VM partial fallback.
func RenderDiagnosticPartialFallbackActive(ctx hctx.Context) bool {
if ctx == nil {
return false
}
active, _ := ctx.Value(renderPartialFallbackActiveKey).(bool)
return active
}
// EnableRenderPartialFallbackDiagnostics enables bounded partial fallback
// details on ctx.
func EnableRenderPartialFallbackDiagnostics(ctx hctx.Context) {