-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuilder.go
More file actions
1377 lines (1248 loc) · 39.1 KB
/
builder.go
File metadata and controls
1377 lines (1248 loc) · 39.1 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 gin
import (
"encoding/json"
"fmt"
"io"
"math"
"runtime"
"sort"
"strconv"
"strings"
"github.com/cespare/xxhash/v2"
"github.com/pkg/errors"
"github.com/amikos-tech/ami-gin/logging"
"github.com/amikos-tech/ami-gin/telemetry"
)
const maxExactFloatInt = int64(1 << 53)
const maxInt64AsFloat64 = float64(1 << 63) // upper bound for float64→int64; math.MaxInt64 rounds up to this
const validatorMissedPanicPrefix = "validator missed "
const validatorMissedMixedNumericPromotion = validatorMissedPanicPrefix + "unsupported mixed numeric promotion"
var errSkipDocument = errors.New("skip document")
type softSkipKind string
const (
errorTypeDeserialization = "deserialization"
softSkipKindOther softSkipKind = "other"
softSkipKindParser softSkipKind = "parser"
softSkipKindNumeric softSkipKind = "numeric"
)
type softSkipDocumentError struct {
kind softSkipKind
err error
}
func (e *softSkipDocumentError) Error() string { return e.err.Error() }
func (e *softSkipDocumentError) Unwrap() error { return e.err }
func (e *softSkipDocumentError) Cause() error { return e.err }
type stageCallbackError struct {
err error
}
func (e *stageCallbackError) Error() string { return e.err.Error() }
func (e *stageCallbackError) Unwrap() error { return e.err }
func (e *stageCallbackError) Cause() error { return e.err }
func isSkipDocument(err error) bool {
return errors.Is(err, errSkipDocument)
}
func newSoftSkipNumericDocumentError(path string) error {
return &softSkipDocumentError{
kind: softSkipKindNumeric,
err: errors.Wrapf(errSkipDocument, "soft numeric failure at %s", path),
}
}
func softSkipDocumentKind(err error) softSkipKind {
var skipped *softSkipDocumentError
if errors.As(err, &skipped) && skipped.kind != "" {
return skipped.kind
}
// Defensive fallback: every builder-created errSkipDocument should carry
// a typed softSkipDocumentError so metrics/logs can classify it precisely.
// Treat bare sentinels as "other" rather than guessing from message text.
return softSkipKindOther
}
func tagStageError(err error) error {
if err == nil || isSkipDocument(err) || isStageCallbackError(err) {
return err
}
return &stageCallbackError{err: err}
}
func isStageCallbackError(err error) bool {
var tagged *stageCallbackError
return errors.As(err, &tagged)
}
func unwrapStageCallbackError(err error) error {
var tagged *stageCallbackError
if errors.As(err, &tagged) {
return tagged.err
}
return err
}
type GINBuilder struct {
config GINConfig
numRGs int
numDocs uint64
numSoftSkips uint64
numSoftRepresentationSkips uint64
maxRGID int
pathData map[string]*pathBuildData
bloom *BloomFilter
codec DocIDCodec
docIDToPos map[DocID]int
posToDocID []DocID
nextPos int
// tragicErr closes the builder after an internal invariant violation or recovered merge panic.
// Finalize then returns nil because prior partial merges may have left an undefined subset of paths.
tragicErr error
// parser defaults to stdlibParser{} at NewBuilder; parserName is the
// cached Parser.Name() result. During AddDocument, parserSink.BeginDocument
// hands the staged state back through currentDocState and increments
// beginDocumentCalls so AddDocument can enforce the sink contract after
// Parse returns.
parser Parser
parserName string
currentDocState *documentBuildState
beginDocumentCalls int
testHooks builderTestHooks
}
type builderTestHooks struct {
mergeStagedPathsPanicHook func()
}
type pathBuildData struct {
pathID uint16
observedTypes uint8
uniqueValues map[string]struct{}
stringTerms map[string]*RGSet
numericStats map[int]*RGNumericStat
stringLengthStats map[int]*RGStringLengthStat
nullRGs *RGSet
presentRGs *RGSet
hll *HyperLogLog
trigrams *TrigramIndex
hasNumericValues bool
numericValueType NumericValueType
intGlobalMin int64
intGlobalMax int64
floatGlobalMin float64
floatGlobalMax float64
}
type stagedNumericValue struct {
isInt bool
intVal int64
floatVal float64
raw string
}
type stagedPathData struct {
observedTypes uint8
present bool
isNull bool
stringTerms map[string]struct{}
numericValues []stagedNumericValue
numericSeeded bool
numericSimHasValue bool
numericSimValueType NumericValueType
numericSimIntMin int64
numericSimIntMax int64
numericSimFloatMin float64
numericSimFloatMax float64
}
type documentBuildState struct {
rgID int
paths map[string]*stagedPathData
}
func newDocumentBuildState(rgID int) *documentBuildState {
return &documentBuildState{
rgID: rgID,
paths: make(map[string]*stagedPathData),
}
}
func (s *documentBuildState) getOrCreatePath(path string) *stagedPathData {
if pd, ok := s.paths[path]; ok {
return pd
}
pd := &stagedPathData{
stringTerms: make(map[string]struct{}),
}
s.paths[path] = pd
return pd
}
type BuilderOption func(*GINBuilder) error
func WithCodec(codec DocIDCodec) BuilderOption {
return func(b *GINBuilder) error {
if codec == nil {
return errors.New("codec cannot be nil")
}
b.codec = codec
return nil
}
}
func NewBuilder(config GINConfig, numRGs int, opts ...BuilderOption) (*GINBuilder, error) {
if numRGs <= 0 {
return nil, errors.New("numRGs must be greater than 0")
}
if err := config.validate(); err != nil {
return nil, err
}
config.ParserFailureMode = normalizeIngestFailureMode(config.ParserFailureMode)
config.NumericFailureMode = normalizeIngestFailureMode(config.NumericFailureMode)
bloom, err := NewBloomFilter(config.BloomFilterSize, config.BloomFilterHashes)
if err != nil {
return nil, errors.Wrap(err, "create bloom filter")
}
b := &GINBuilder{
config: config,
numRGs: numRGs,
pathData: make(map[string]*pathBuildData),
bloom: bloom,
codec: NewIdentityCodec(),
docIDToPos: make(map[DocID]int),
posToDocID: make([]DocID, 0),
}
for _, opt := range opts {
if err := opt(b); err != nil {
return nil, err
}
}
if b.parser == nil {
b.parser = stdlibParser{}
}
name := b.parser.Name()
if name == "" {
return nil, errors.New("parser name cannot be empty")
}
b.parserName = name
return b, nil
}
func adaptiveBucketIndex(term string, bucketCount int) int {
if bucketCount <= 0 {
panic("adaptive bucket count must be greater than 0")
}
return int(xxhash.Sum64String(term) & uint64(bucketCount-1))
}
func buildStringIndex(stringTerms map[string]*RGSet) *StringIndex {
si := &StringIndex{
Terms: make([]string, 0, len(stringTerms)),
RGBitmaps: make([]*RGSet, 0, len(stringTerms)),
}
terms := make([]string, 0, len(stringTerms))
for term := range stringTerms {
terms = append(terms, term)
}
sort.Strings(terms)
for _, term := range terms {
si.Terms = append(si.Terms, term)
si.RGBitmaps = append(si.RGBitmaps, stringTerms[term])
}
return si
}
type adaptivePromotionCandidate struct {
term string
coverage int
}
func (b *GINBuilder) selectAdaptivePromotedTerms(pd *pathBuildData) map[string]struct{} {
if b.config.AdaptivePromotedTermCap == 0 || len(pd.stringTerms) == 0 {
return map[string]struct{}{}
}
candidates := make([]adaptivePromotionCandidate, 0, len(pd.stringTerms))
for term, rgSet := range pd.stringTerms {
coverage := rgSet.Count()
if coverage < b.config.AdaptiveMinRGCoverage {
continue
}
if float64(coverage)/float64(b.numRGs) > b.config.AdaptiveCoverageCeiling {
continue
}
candidates = append(candidates, adaptivePromotionCandidate{
term: term,
coverage: coverage,
})
}
sort.Slice(candidates, func(i, j int) bool {
if candidates[i].coverage == candidates[j].coverage {
return candidates[i].term < candidates[j].term
}
return candidates[i].coverage > candidates[j].coverage
})
if len(candidates) > b.config.AdaptivePromotedTermCap {
candidates = candidates[:b.config.AdaptivePromotedTermCap]
}
promoted := make(map[string]struct{}, len(candidates))
for _, candidate := range candidates {
promoted[candidate.term] = struct{}{}
}
return promoted
}
func (b *GINBuilder) buildAdaptiveStringIndex(pd *pathBuildData) *AdaptiveStringIndex {
promoted := b.selectAdaptivePromotedTerms(pd)
terms := make([]string, 0, len(promoted))
rgBitmaps := make([]*RGSet, 0, len(promoted))
bucketBitmaps := make([]*RGSet, b.config.AdaptiveBucketCount)
for bucketID := range bucketBitmaps {
bucketBitmaps[bucketID] = MustNewRGSet(b.numRGs)
}
for term := range promoted {
terms = append(terms, term)
}
sort.Strings(terms)
for _, term := range terms {
rgBitmaps = append(rgBitmaps, pd.stringTerms[term].Clone())
}
for term, rgSet := range pd.stringTerms {
if _, ok := promoted[term]; ok {
continue
}
bucketID := adaptiveBucketIndex(term, len(bucketBitmaps))
bucketBitmaps[bucketID].UnionWith(rgSet)
}
adaptive, err := NewAdaptiveStringIndex(terms, rgBitmaps, bucketBitmaps)
if err != nil {
panic(err)
}
return adaptive
}
func (b *GINBuilder) shouldEnableTrigrams(path string) bool {
if !b.config.EnableTrigrams {
return false
}
if len(b.config.ftsPaths) == 0 {
return true
}
for _, pattern := range b.config.ftsPaths {
if matchFTSPath(pattern, path) {
return true
}
}
return false
}
func matchFTSPath(pattern, path string) bool {
if strings.HasSuffix(pattern, ".*") {
prefix := strings.TrimSuffix(pattern, ".*")
return path == prefix || strings.HasPrefix(path, prefix+".")
}
return pattern == path
}
func (b *GINBuilder) getOrCreatePath(path string) *pathBuildData {
if pd, ok := b.pathData[path]; ok {
return pd
}
pd := &pathBuildData{
pathID: uint16(len(b.pathData)),
uniqueValues: make(map[string]struct{}),
stringTerms: make(map[string]*RGSet),
numericStats: make(map[int]*RGNumericStat),
stringLengthStats: make(map[int]*RGStringLengthStat),
nullRGs: MustNewRGSet(b.numRGs),
presentRGs: MustNewRGSet(b.numRGs),
hll: MustNewHyperLogLog(b.config.HLLPrecision),
}
if b.shouldEnableTrigrams(path) {
pd.trigrams = MustNewTrigramIndex(b.numRGs)
}
b.pathData[path] = pd
return pd
}
func (b *GINBuilder) AddDocument(docID DocID, jsonDoc []byte) error {
if b.tragicErr != nil {
return errors.Wrap(b.tragicErr, "builder closed by prior tragic failure; discard and rebuild")
}
pos, exists := b.docIDToPos[docID]
if !exists {
pos = b.nextPos
if pos >= b.numRGs {
return errors.Errorf("position %d exceeds numRGs %d", pos, b.numRGs)
}
}
// Parse errors become parser-layer IngestErrors unless soft-mode or a
// stage-callback error takes the document down a different path. Reset the
// handoff fields before dispatch so AddDocument can verify Parse called
// BeginDocument exactly once with the expected row-group id.
b.currentDocState = nil
b.beginDocumentCalls = 0
defer func() {
b.currentDocState = nil
b.beginDocumentCalls = 0
}()
if err := b.parser.Parse(jsonDoc, pos, b); err != nil {
if isSkipDocument(err) {
// Invariant: bare errSkipDocument sentinels (softSkipKindOther)
// originate only from the parser path here. Numeric and other
// skip sites must construct a typed softSkipDocumentError with
// an explicit kind; if a new non-parser site returns a bare
// sentinel, it will be misclassified as a parser skip.
kind := softSkipDocumentKind(err)
if kind == softSkipKindOther {
kind = softSkipKindParser
}
b.recordSoftDocumentSkip(kind)
return nil
}
if isStageCallbackError(err) {
return unwrapStageCallbackError(err)
}
if b.config.ParserFailureMode == IngestFailureSoft {
b.recordSoftDocumentSkip(softSkipKindParser)
return nil
}
return newIngestErrorString(IngestLayerParser, "", string(jsonDoc), err)
}
if b.beginDocumentCalls == 0 {
return errors.Errorf("parser %q did not call BeginDocument", b.parserName)
}
if b.beginDocumentCalls != 1 {
return errors.Errorf(
"parser %q called BeginDocument %d times; want exactly 1",
b.parserName,
b.beginDocumentCalls,
)
}
if b.currentDocState.rgID != pos {
return errors.Errorf(
"parser %q BeginDocument rgID mismatch: got %d, want %d",
b.parserName,
b.currentDocState.rgID,
pos,
)
}
return b.mergeDocumentState(docID, pos, exists, b.currentDocState)
}
func normalizeWalkPath(path string) string {
if !strings.Contains(path, "['") && !strings.Contains(path, `["`) {
return path
}
return NormalizePath(path)
}
func (b *GINBuilder) walkJSON(path string, value any, rgID int) error {
if b.tragicErr != nil {
return errors.Wrap(b.tragicErr, "builder closed by prior tragic failure; discard and rebuild")
}
state := newDocumentBuildState(rgID)
if err := b.stageMaterializedValue(path, value, state, true); err != nil {
return err
}
return b.commitStagedPaths(state)
}
func ensureDecoderEOF(decoder *json.Decoder) error {
if _, err := decoder.Token(); err == io.EOF {
return nil
} else if err != nil {
return err
}
return errors.New("unexpected trailing JSON content")
}
func decodeAny(decoder *json.Decoder) (any, error) {
var value any
if err := decoder.Decode(&value); err != nil {
return nil, err
}
return value, nil
}
func sortedObjectKeys(values map[string]any) []string {
keys := make([]string, 0, len(values))
for key := range values {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
func prepareTransformerValue(value any) any {
switch v := value.(type) {
case json.Number:
if floatVal, err := strconv.ParseFloat(v.String(), 64); err == nil {
return floatVal
}
return v.String()
case []any:
out := make([]any, len(v))
for i, item := range v {
out[i] = prepareTransformerValue(item)
}
return out
case map[string]any:
out := make(map[string]any, len(v))
for key, item := range v {
out[key] = prepareTransformerValue(item)
}
return out
default:
return value
}
}
func (b *GINBuilder) stageScalarToken(canonicalPath string, token any, state *documentBuildState) error {
pathState := state.getOrCreatePath(canonicalPath)
pathState.present = true
switch v := token.(type) {
case nil:
pathState.observedTypes |= TypeNull
pathState.isNull = true
return nil
case bool:
pathState.observedTypes |= TypeBool
pathState.stringTerms[strconv.FormatBool(v)] = struct{}{}
return nil
case string:
pathState.observedTypes |= TypeString
pathState.stringTerms[v] = struct{}{}
return nil
case json.Number:
return b.stageJSONNumberLiteral(canonicalPath, v.String(), state)
default:
return newIngestError(
IngestLayerSchema,
canonicalPath,
token,
errors.Errorf("unsupported JSON token type %T", token),
)
}
}
func (b *GINBuilder) stageMaterializedValue(path string, value any, state *documentBuildState, allowTransform bool) error {
canonicalPath := normalizeWalkPath(path)
if allowTransform {
if err := b.stageCompanionRepresentations(canonicalPath, value, state); err != nil {
return err
}
}
pathState := state.getOrCreatePath(canonicalPath)
pathState.present = true
switch v := value.(type) {
case nil:
pathState.observedTypes |= TypeNull
pathState.isNull = true
return nil
case bool:
pathState.observedTypes |= TypeBool
pathState.stringTerms[strconv.FormatBool(v)] = struct{}{}
return nil
case string:
pathState.observedTypes |= TypeString
pathState.stringTerms[v] = struct{}{}
return nil
case json.Number:
return b.stageJSONNumberLiteral(canonicalPath, v.String(), state)
case float64:
return b.stageNativeNumeric(canonicalPath, v, state)
case float32:
return b.stageNativeNumeric(canonicalPath, float64(v), state)
case int:
return b.stageNativeNumeric(canonicalPath, int64(v), state)
case int8:
return b.stageNativeNumeric(canonicalPath, int64(v), state)
case int16:
return b.stageNativeNumeric(canonicalPath, int64(v), state)
case int32:
return b.stageNativeNumeric(canonicalPath, int64(v), state)
case int64:
return b.stageNativeNumeric(canonicalPath, v, state)
case uint:
return b.stageNativeNumeric(canonicalPath, v, state)
case uint8:
return b.stageNativeNumeric(canonicalPath, int64(v), state)
case uint16:
return b.stageNativeNumeric(canonicalPath, int64(v), state)
case uint32:
return b.stageNativeNumeric(canonicalPath, int64(v), state)
case uint64:
return b.stageNativeNumeric(canonicalPath, v, state)
case []any:
for i, item := range v {
if err := b.stageMaterializedValue(fmt.Sprintf("%s[%d]", path, i), item, state, true); err != nil {
return err
}
if err := b.stageMaterializedValue(path+"[*]", item, state, true); err != nil {
return err
}
}
return nil
case map[string]any:
for _, key := range sortedObjectKeys(v) {
if err := b.stageMaterializedValue(path+"."+key, v[key], state, true); err != nil {
return err
}
}
return nil
default:
return newIngestError(
IngestLayerSchema,
canonicalPath,
value,
errors.Errorf("unsupported transformed value type %T", value),
)
}
}
func (b *GINBuilder) stageCompanionRepresentations(canonicalPath string, value any, state *documentBuildState) error {
registrations := b.config.representations(canonicalPath)
if len(registrations) == 0 {
return nil
}
prepared := prepareTransformerValue(value)
for _, registration := range registrations {
transformed, ok := registration.FieldTransformer(prepared)
if !ok {
if normalizeTransformerFailureMode(registration.Transformer.FailureMode) == IngestFailureSoft {
b.numSoftRepresentationSkips++
logging.Info(
b.config.Logger,
"builder skipped companion representation after soft transformer failure",
logging.AttrOperation("builder.transform"),
logging.AttrStatus("skipped"),
logging.AttrErrorType(telemetry.ErrorTypeOther),
)
continue
}
return newIngestError(
IngestLayerTransformer,
canonicalPath,
value,
errors.Errorf("companion transformer %q failed to produce a value", registration.Alias),
)
}
if err := b.stageMaterializedValue(registration.TargetPath, transformed, state, false); err != nil {
remapCompanionIngestErrorPath(err, canonicalPath, registration.TargetPath)
return err
}
}
return nil
}
// remapCompanionIngestErrorPath hides internal derived-path names from
// user-facing ingest errors by rewriting any leaked companion target path back
// to the source path in place via the caller's error pointer discovered through
// errors.As. The offending Value is left untouched because it still reflects
// the transformed representation that actually failed. Returns without effect
// when err does not unwrap to *IngestError, when the path is empty, or when the
// path does not match the companion target/internal-prefix shape.
func remapCompanionIngestErrorPath(err error, sourcePath, targetPath string) {
var ingestErr *IngestError
if !errors.As(err, &ingestErr) || ingestErr == nil {
return
}
path := ingestErr.Path()
if path == "" {
return
}
if path == targetPath ||
strings.HasPrefix(path, targetPath+".") ||
strings.HasPrefix(path, targetPath+"[") ||
strings.HasPrefix(path, internalRepresentationPathPrefix) {
ingestErr.path = sourcePath
}
}
func (b *GINBuilder) stageJSONNumberLiteral(path, raw string, state *documentBuildState) error {
isInt, intVal, floatVal, err := parseJSONNumberLiteral(raw)
if err != nil {
if b.config.NumericFailureMode == IngestFailureSoft {
return newSoftSkipNumericDocumentError(path)
}
return newIngestErrorString(IngestLayerNumeric, path, raw, errors.Wrap(err, "parse numeric"))
}
return b.stageNumericObservation(path, stagedNumericValue{
isInt: isInt,
intVal: intVal,
floatVal: floatVal,
raw: raw,
}, state)
}
func parseJSONNumberLiteral(raw string) (bool, int64, float64, error) {
if strings.ContainsAny(raw, ".eE") {
floatVal, err := strconv.ParseFloat(raw, 64)
if err != nil {
return false, 0, 0, err
}
if math.IsNaN(floatVal) || math.IsInf(floatVal, 0) {
return false, 0, 0, errors.New("non-finite numeric value")
}
return false, 0, floatVal, nil
}
intVal, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return false, 0, 0, errors.Wrap(err, "unsupported integer literal")
}
return true, intVal, 0, nil
}
func (b *GINBuilder) stageNativeNumeric(path string, value any, state *documentBuildState) error {
obs, err := stagedNumericFromValue(value)
if err != nil {
if b.config.NumericFailureMode == IngestFailureSoft {
return newSoftSkipNumericDocumentError(path)
}
return newIngestError(IngestLayerNumeric, path, value, errors.Wrap(err, "parse numeric"))
}
return b.stageNumericObservation(path, obs, state)
}
func stagedNumericFromValue(value any) (stagedNumericValue, error) {
switch v := value.(type) {
case int64:
return stagedNumericValue{isInt: true, intVal: v}, nil
case uint:
if v > math.MaxInt64 {
return stagedNumericValue{}, errors.New("unsupported integer")
}
return stagedNumericValue{isInt: true, intVal: int64(v)}, nil
case uint64:
if v > math.MaxInt64 {
return stagedNumericValue{}, errors.New("unsupported integer")
}
return stagedNumericValue{isInt: true, intVal: int64(v)}, nil
case float64:
if math.IsNaN(v) || math.IsInf(v, 0) {
return stagedNumericValue{}, errors.New("non-finite numeric value")
}
if v == math.Trunc(v) && v >= math.MinInt64 && v < maxInt64AsFloat64 {
return stagedNumericValue{isInt: true, intVal: int64(v)}, nil
}
return stagedNumericValue{floatVal: v}, nil
default:
return stagedNumericValue{}, errors.Errorf("unsupported numeric type %T", value)
}
}
func formatStagedNumericValue(value stagedNumericValue) string {
if value.raw != "" {
return value.raw
}
if value.isInt {
return strconv.FormatInt(value.intVal, 10)
}
return strconv.FormatFloat(value.floatVal, 'g', -1, 64)
}
func (b *GINBuilder) stageNumericObservation(path string, observation stagedNumericValue, state *documentBuildState) error {
pathState := state.getOrCreatePath(path)
pathState.present = true
b.seedNumericSimulation(path, pathState)
if !pathState.numericSimHasValue {
pathState.numericSimHasValue = true
if observation.isInt {
pathState.numericSimValueType = NumericValueTypeIntOnly
pathState.numericSimIntMin = observation.intVal
pathState.numericSimIntMax = observation.intVal
pathState.observedTypes |= TypeInt
} else {
pathState.numericSimValueType = NumericValueTypeFloatMixed
pathState.numericSimFloatMin = observation.floatVal
pathState.numericSimFloatMax = observation.floatVal
pathState.observedTypes |= TypeFloat
}
pathState.numericValues = append(pathState.numericValues, observation)
return nil
}
if pathState.numericSimValueType == NumericValueTypeIntOnly {
if observation.isInt {
if observation.intVal < pathState.numericSimIntMin {
pathState.numericSimIntMin = observation.intVal
}
if observation.intVal > pathState.numericSimIntMax {
pathState.numericSimIntMax = observation.intVal
}
pathState.observedTypes |= TypeInt
pathState.numericValues = append(pathState.numericValues, observation)
return nil
}
if !canRepresentIntAsExactFloat(pathState.numericSimIntMin) || !canRepresentIntAsExactFloat(pathState.numericSimIntMax) {
if b.config.NumericFailureMode == IngestFailureSoft {
return newSoftSkipNumericDocumentError(path)
}
return newIngestErrorString(
IngestLayerNumeric,
path,
formatStagedNumericValue(observation),
errors.New("unsupported mixed numeric promotion"),
)
}
pathState.numericSimValueType = NumericValueTypeFloatMixed
pathState.numericSimFloatMin = math.Min(float64(pathState.numericSimIntMin), observation.floatVal)
pathState.numericSimFloatMax = math.Max(float64(pathState.numericSimIntMax), observation.floatVal)
pathState.observedTypes |= TypeFloat
pathState.numericValues = append(pathState.numericValues, observation)
return nil
}
if observation.isInt {
if !canRepresentIntAsExactFloat(observation.intVal) {
if b.config.NumericFailureMode == IngestFailureSoft {
return newSoftSkipNumericDocumentError(path)
}
return newIngestErrorString(
IngestLayerNumeric,
path,
formatStagedNumericValue(observation),
errors.New("unsupported mixed numeric promotion"),
)
}
floatVal := float64(observation.intVal)
if floatVal < pathState.numericSimFloatMin {
pathState.numericSimFloatMin = floatVal
}
if floatVal > pathState.numericSimFloatMax {
pathState.numericSimFloatMax = floatVal
}
pathState.observedTypes |= TypeInt
pathState.numericValues = append(pathState.numericValues, observation)
return nil
}
if observation.floatVal < pathState.numericSimFloatMin {
pathState.numericSimFloatMin = observation.floatVal
}
if observation.floatVal > pathState.numericSimFloatMax {
pathState.numericSimFloatMax = observation.floatVal
}
pathState.observedTypes |= TypeFloat
pathState.numericValues = append(pathState.numericValues, observation)
return nil
}
func (b *GINBuilder) seedNumericSimulation(path string, pathState *stagedPathData) {
if pathState.numericSeeded {
return
}
pathState.numericSeeded = true
pd, ok := b.pathData[path]
if !ok || !pd.hasNumericValues {
return
}
pathState.numericSimHasValue = true
pathState.numericSimValueType = pd.numericValueType
if pd.numericValueType == NumericValueTypeIntOnly {
pathState.numericSimIntMin = pd.intGlobalMin
pathState.numericSimIntMax = pd.intGlobalMax
return
}
pathState.numericSimFloatMin = pd.floatGlobalMin
pathState.numericSimFloatMax = pd.floatGlobalMax
}
func canRepresentIntAsExactFloat(value int64) bool {
return value >= -maxExactFloatInt && value <= maxExactFloatInt
}
func (b *GINBuilder) mergeDocumentState(docID DocID, pos int, exists bool, state *documentBuildState) error {
if err := b.commitStagedPaths(state); err != nil {
if isSkipDocument(err) {
b.recordSoftDocumentSkip(softSkipDocumentKind(err))
return nil
}
return err
}
if !exists {
b.docIDToPos[docID] = pos
b.posToDocID = append(b.posToDocID, docID)
b.nextPos++
}
if pos > b.maxRGID {
b.maxRGID = pos
}
b.numDocs++
return nil
}
func (b *GINBuilder) commitStagedPaths(state *documentBuildState) error {
if err := b.validateStagedPaths(state); err != nil {
return err
}
if err := runMergeWithRecover(b.config.Logger, func() { b.mergeStagedPaths(state) }); err != nil {
b.tragicErr = err
return err
}
return nil
}
func runMergeWithRecover(logger logging.Logger, fn func()) (err error) {
defer func() {
if recovered := recover(); recovered != nil {
attrs := []logging.Attr{
logging.AttrErrorType(telemetry.ErrorTypeOther),
logging.Attr{Key: "panic_type", Value: fmt.Sprintf("%T", recovered)},
}
if message, ok := safeMergePanicMessage(recovered); ok {
attrs = append(attrs, logging.Attr{Key: "panic_message", Value: message})
}
logging.Error(logger, "builder tragic: recovered panic in merge", attrs...)
if e, ok := recovered.(error); ok {
err = errors.Wrap(e, "builder tragic: recovered panic in merge")
return
}
err = errors.Errorf("builder tragic: recovered panic in merge: %v", recovered)
}
}()
fn()
return nil
}
func safeMergePanicMessage(recovered any) (string, bool) {
e, ok := recovered.(error)
if !ok {
return "", false
}
message := e.Error()
if strings.HasPrefix(message, validatorMissedPanicPrefix) {
return message, true
}
if _, ok := recovered.(runtime.Error); ok {
return message, true
}
return "", false
}
// NumSoftSkippedDocuments reports how many documents were dropped because a
// builder-level soft ingest mode chose skip-over-error semantics.
func (b *GINBuilder) NumSoftSkippedDocuments() uint64 {
return b.numSoftSkips
}
// SoftSkippedDocuments reports how many documents were dropped because a
// builder-level soft ingest mode chose skip-over-error semantics.
//
// Deprecated: use NumSoftSkippedDocuments.
func (b *GINBuilder) SoftSkippedDocuments() uint64 {
return b.NumSoftSkippedDocuments()
}
// NumSoftSkippedRepresentations reports how many companion representations
// were omitted because a per-transformer soft failure kept the source document
// and skipped only the failed derived value.
func (b *GINBuilder) NumSoftSkippedRepresentations() uint64 {
return b.numSoftRepresentationSkips
}
// Err returns the tragic builder error that closes the builder, if any.
// User-input document failures are reported from AddDocument and do not appear here.
func (b *GINBuilder) Err() error {
return b.tragicErr
}
func (b *GINBuilder) recordSoftDocumentSkip(kind softSkipKind) {
b.numSoftSkips++
message := "builder skipped document after soft ingest failure"
errorType := telemetry.ErrorTypeOther
switch kind {
case softSkipKindParser:
message = "builder skipped document after soft parser failure"
errorType = errorTypeDeserialization
case softSkipKindNumeric:
message = "builder skipped document after soft numeric failure"
}
logging.Info(