-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialize.go
More file actions
1881 lines (1711 loc) · 64.5 KB
/
serialize.go
File metadata and controls
1881 lines (1711 loc) · 64.5 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 (
"bytes"
"context"
"encoding/binary"
"encoding/json"
stderrors "errors"
"io"
"math"
"sort"
"github.com/RoaringBitmap/roaring/v2"
"github.com/klauspost/compress/zstd"
"github.com/pkg/errors"
"github.com/amikos-tech/ami-gin/telemetry"
)
const (
maxConfigSize = 1 << 20 // 1MB max config size
maxRepresentationSectionSize = 1 << 20 // 1MB max representation metadata size
)
const (
// maxDecodedIndexSize caps zstd.DecodeAll's output buffer to defend against
// decompression bombs. 64 MiB accommodates multi-TB Parquet catalogs (tested
// up to ~1M row groups / 100M docs) while bounding per-decode allocation to a
// value safe on 1 GiB heaps.
maxDecodedIndexSize = 64 << 20
// maxRGSetSize limits roaring bitmap deserialization.
// 16MB covers worst-case bitmaps for millions of row groups.
maxRGSetSize = 16 << 20
// maxNumPaths matches PathID's uint16 range.
maxNumPaths = 65535
// maxHeaderRowGroups bounds NumRowGroups-driven allocations during Decode.
// 1M matches the largest observed Parquet catalogs (~1 PiB at 1 GiB per RG);
// values above this are rejected as corrupt.
maxHeaderRowGroups = 1_000_000
// maxHeaderDocs bounds NumDocs-driven allocations (primarily DocIDMapping,
// which is a []DocID of uint64 entries). 100M caps DocIDMapping at ~800 MiB.
maxHeaderDocs = 100_000_000
// maxTermsPerPath caps string index terms per path.
// Default CardinalityThreshold is 10,000; 1M is generous headroom.
maxTermsPerPath = 1_000_000
// maxTrigramsPerPath caps trigram entries per path.
// ASCII ceiling is ~2M (128^3); 10M covers extreme Unicode FTS.
maxTrigramsPerPath = 10_000_000
// maxBloomWords caps bloom filter word count.
// Default is 65536 bits (1024 words). 1M words (~8MB) is generous.
maxBloomWords = 1 << 20
// maxHLLRegisters caps HyperLogLog register count.
// Max precision 16 needs 2^16 = 65536 registers.
maxHLLRegisters = 1 << 16
// maxAdaptivePaths reuses maxNumPaths because at most one adaptive section
// can exist per path, and the uint16 PathID ceiling is the real bound.
maxAdaptivePaths = maxNumPaths
// maxAdaptiveTermsPerPath caps promoted exact terms persisted per path.
// PathEntry summary counters are uint16-backed, so larger values would be ambiguous.
maxAdaptiveTermsPerPath = 1<<16 - 1
// maxAdaptiveBucketsPerPath caps fixed bucket fan-out for adaptive paths.
// Default is 128; 4096 preserves headroom without allowing pathological allocations.
maxAdaptiveBucketsPerPath = 1 << 12
)
var (
// ErrVersionMismatch is returned by Decode when the binary format version
// does not match the expected version (Version constant).
ErrVersionMismatch = errors.New("version mismatch")
// ErrInvalidFormat is returned by Decode when the binary data is structurally
// invalid: unrecognized magic bytes, oversized allocations, or corrupt fields.
ErrInvalidFormat = errors.New("invalid format")
// ErrDecodedSizeExceedsLimit is returned by Decode when compressed input
// expands beyond maxDecodedIndexSize during zstd decompression.
ErrDecodedSizeExceedsLimit = errors.New("decoded size exceeds configured limit")
// ErrNilIndex is returned when a serialization or persistence boundary is
// asked to operate on a nil index.
ErrNilIndex = errors.New("nil index")
)
// CompressionLevel specifies the compression level for index serialization.
type CompressionLevel int
const (
CompressionNone CompressionLevel = 0 // No compression
CompressionFastest CompressionLevel = 1 // zstd level 1
CompressionBalanced CompressionLevel = 3 // zstd level 3
CompressionBetter CompressionLevel = 9 // zstd level 9
CompressionBest CompressionLevel = 15 // zstd level 15 (recommended)
CompressionMax CompressionLevel = 19 // zstd level 19 (slow)
)
const (
uncompressedMagic = "GINu"
compressedMagic = "GINc"
)
const (
compactStringModeRaw uint8 = iota
compactStringModeFrontCoded
)
type SerializedConfig struct {
BloomFilterSize uint32 `json:"bloom_filter_size"`
BloomFilterHashes uint8 `json:"bloom_filter_hashes"`
EnableTrigrams bool `json:"enable_trigrams"`
TrigramMinLength int `json:"trigram_min_length"`
HLLPrecision uint8 `json:"hll_precision"`
PrefixBlockSize int `json:"prefix_block_size"`
AdaptiveMinRGCoverage int `json:"adaptive_min_rg_coverage"`
AdaptivePromotedTermCap int `json:"adaptive_promoted_term_cap"`
AdaptiveCoverageCeiling float64 `json:"adaptive_coverage_ceiling"`
AdaptiveBucketCount int `json:"adaptive_bucket_count"`
FTSPaths []string `json:"fts_paths,omitempty"`
Transformers []TransformerSpec `json:"transformers,omitempty"`
}
func transformerFailureModeWireToken(mode IngestFailureMode) IngestFailureMode {
switch normalizeTransformerFailureMode(mode) {
case IngestFailureHard:
return transformerFailureWireStrict
case IngestFailureSoft:
return transformerFailureWireSoft
default:
return mode
}
}
func writeRGSet(w io.Writer, rs *RGSet) error {
if err := binary.Write(w, binary.LittleEndian, uint32(rs.NumRGs)); err != nil {
return err
}
data, err := rs.Roaring().ToBytes()
if err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, uint32(len(data))); err != nil {
return err
}
_, err = w.Write(data)
return err
}
func readRGSet(r io.Reader, maxRGs uint32) (*RGSet, error) {
var numRGs uint32
if err := binary.Read(r, binary.LittleEndian, &numRGs); err != nil {
return nil, err
}
if numRGs > maxRGs {
return nil, errors.Wrapf(ErrInvalidFormat, "rgset numRGs %d exceeds max %d", numRGs, maxRGs)
}
var dataLen uint32
if err := binary.Read(r, binary.LittleEndian, &dataLen); err != nil {
return nil, err
}
if dataLen > maxRGSetSize {
return nil, errors.Wrapf(ErrInvalidFormat, "rgset data length %d exceeds max %d", dataLen, maxRGSetSize)
}
data := make([]byte, dataLen)
if _, err := io.ReadFull(r, data); err != nil {
return nil, err
}
bitmap := roaring.New()
if err := bitmap.UnmarshalBinary(data); err != nil {
return nil, err
}
return RGSetFromRoaring(bitmap, int(numRGs)), nil
}
// encodeRuntime carries runtime-only observability for raw serialization.
// Raw encode/decode are package-level functions with no GINConfig receiver,
// so caller-supplied options provide the only per-call observability override.
type encodeRuntime struct {
signals telemetry.Signals
}
// EncodeOption configures runtime observability for EncodeContext or EncodeWithLevelContext.
// Construct options with the exported WithEncodeSignals helper; the underlying
// runtime struct is intentionally unexported.
type EncodeOption func(*encodeRuntime)
// WithEncodeSignals overrides the telemetry signals used by EncodeContext and
// EncodeWithLevelContext. By default the encoder seeds signals from idx.Config;
// this option lets external callers provide explicit signals when the index
// config is unavailable or when they want to override it per call.
func WithEncodeSignals(signals telemetry.Signals) EncodeOption {
return func(rt *encodeRuntime) {
rt.signals = signals
}
}
// decodeRuntime carries runtime-only observability for raw deserialization.
type decodeRuntime struct {
signals telemetry.Signals
}
// DecodeOption configures runtime observability for DecodeContext.
// Construct options with the exported WithDecodeSignals helper; the underlying
// runtime struct is intentionally unexported.
type DecodeOption func(*decodeRuntime)
// WithDecodeSignals sets the telemetry signals used by DecodeContext. Decode has
// no index receiver, so signals default to telemetry.Disabled(); callers use
// this option to route spans and metrics into an existing provider.
func WithDecodeSignals(signals telemetry.Signals) DecodeOption {
return func(rt *decodeRuntime) {
rt.signals = signals
}
}
// Encode serializes the index using zstd-15 compression (recommended default).
// It delegates to EncodeContext with context.Background().
func Encode(idx *GINIndex) ([]byte, error) {
return EncodeContext(context.Background(), idx)
}
// EncodeContext is the context-aware sibling of Encode. It wraps
// EncodeWithLevelContext at CompressionBest and emits a coarse boundary span.
func EncodeContext(ctx context.Context, idx *GINIndex, opts ...EncodeOption) ([]byte, error) {
return EncodeWithLevelContext(ctx, idx, CompressionBest, opts...)
}
// EncodeWithLevel serializes the index with the specified compression level.
// It delegates to EncodeWithLevelContext with context.Background().
// Use CompressionNone (0) for no compression, or 1-19 for zstd compression levels.
func EncodeWithLevel(idx *GINIndex, level CompressionLevel) ([]byte, error) {
return EncodeWithLevelContext(context.Background(), idx, level)
}
// EncodeWithLevelContext is the context-aware, configurable-compression sibling
// of EncodeWithLevel. Observability is seeded from idx.Config when present;
// caller EncodeOptions override it. Cancellation is checked before the blocking
// encode body, but the zstd codec itself cannot be preempted once it starts.
func EncodeWithLevelContext(ctx context.Context, idx *GINIndex, level CompressionLevel, opts ...EncodeOption) ([]byte, error) {
if ctx == nil {
ctx = context.Background()
}
var cfg *GINConfig
if idx != nil {
cfg = idx.Config
}
rt := &encodeRuntime{
signals: configSignals(cfg),
}
for _, o := range opts {
o(rt)
}
var result []byte
err := telemetry.RunBoundaryOperation(ctx, rt.signals, telemetry.BoundaryConfig{
Scope: "github.com/amikos-tech/ami-gin/serialize",
Operation: telemetry.OperationEncode,
ClassifyError: classifySerializeError,
}, func(bctx context.Context) error {
if err := bctx.Err(); err != nil {
return err
}
var encErr error
result, encErr = encodeWithLevel(idx, level)
return encErr
})
return result, err
}
// encodeWithLevel is the internal implementation of serialization with a specific compression level.
func encodeWithLevel(idx *GINIndex, level CompressionLevel) ([]byte, error) {
if level < 0 || level > 19 {
return nil, errors.Errorf("compression level must be 0-19, got %d", level)
}
if idx == nil {
return nil, errors.Wrap(ErrNilIndex, "encode index")
}
if err := idx.validatePathReferences(); err != nil {
return nil, errors.Wrap(err, "validate path references")
}
var buf bytes.Buffer
if len(idx.DocIDMapping) > 0 {
idx.Header.Flags |= FlagHasDocIDMap
}
if err := writeHeader(&buf, idx); err != nil {
return nil, errors.Wrap(err, "write header")
}
if err := writePathDirectory(&buf, idx); err != nil {
return nil, errors.Wrap(err, "write path directory")
}
if err := writeBloomFilter(&buf, idx.GlobalBloom); err != nil {
return nil, errors.Wrap(err, "write bloom filter")
}
if err := writeStringIndexes(&buf, idx); err != nil {
return nil, errors.Wrap(err, "write string indexes")
}
if err := writeAdaptiveStringIndexes(&buf, idx); err != nil {
return nil, errors.Wrap(err, "write adaptive string indexes")
}
if err := writeStringLengthIndexes(&buf, idx); err != nil {
return nil, errors.Wrap(err, "write string length indexes")
}
if err := writeNumericIndexes(&buf, idx); err != nil {
return nil, errors.Wrap(err, "write numeric indexes")
}
if err := writeNullIndexes(&buf, idx); err != nil {
return nil, errors.Wrap(err, "write null indexes")
}
if err := writeTrigramIndexes(&buf, idx); err != nil {
return nil, errors.Wrap(err, "write trigram indexes")
}
if err := writeHyperLogLogs(&buf, idx); err != nil {
return nil, errors.Wrap(err, "write hyperloglog")
}
if idx.Header.Flags&FlagHasDocIDMap != 0 {
if err := writeDocIDMapping(&buf, idx.DocIDMapping); err != nil {
return nil, errors.Wrap(err, "write docid mapping")
}
}
if err := writeConfig(&buf, idx.Config); err != nil {
return nil, errors.Wrap(err, "write config")
}
if err := writeRepresentations(&buf, idx); err != nil {
return nil, errors.Wrap(err, "write representations")
}
if level == CompressionNone {
return append([]byte(uncompressedMagic), buf.Bytes()...), nil
}
encoder, err := zstd.NewWriter(nil,
zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(int(level))))
if err != nil {
return nil, errors.Wrap(err, "create zstd encoder")
}
defer func() { _ = encoder.Close() }()
compressed := encoder.EncodeAll(buf.Bytes(), nil)
return append([]byte(compressedMagic), compressed...), nil
}
// Decode deserializes an index, validates cross-structure path references, and
// canonicalizes supported JSONPath spellings in PathDirectory while rebuilding
// derived lookup state. It delegates to DecodeContext with context.Background().
func Decode(data []byte) (*GINIndex, error) {
return DecodeContext(context.Background(), data)
}
// DecodeContext is the context-aware sibling of Decode. It wraps the
// deserialization work in a coarse boundary span. Caller DecodeOptions can
// supply explicit observability signals since Decode has no config receiver.
// Cancellation is checked before the blocking decode body, but zstd
// decompression itself cannot be preempted once it starts.
func DecodeContext(ctx context.Context, data []byte, opts ...DecodeOption) (*GINIndex, error) {
if ctx == nil {
ctx = context.Background()
}
rt := &decodeRuntime{
signals: telemetry.Disabled(),
}
for _, o := range opts {
o(rt)
}
var idx *GINIndex
err := telemetry.RunBoundaryOperation(ctx, rt.signals, telemetry.BoundaryConfig{
Scope: "github.com/amikos-tech/ami-gin/serialize",
Operation: telemetry.OperationDecode,
ClassifyError: classifySerializeError,
}, func(bctx context.Context) error {
if err := bctx.Err(); err != nil {
return err
}
var decErr error
idx, decErr = decodeCore(data)
return decErr
})
return idx, err
}
// decodeCore is the internal deserialization implementation.
func decodeCore(data []byte) (*GINIndex, error) {
if len(data) < 4 {
return nil, errors.Wrap(ErrInvalidFormat, "data too short")
}
var decompressed []byte
magic := string(data[:4])
switch magic {
case uncompressedMagic:
decompressed = data[4:]
case compressedMagic:
decoder, err := zstd.NewReader(nil,
zstd.WithDecoderMaxMemory(maxDecodedIndexSize),
zstd.WithDecoderMaxWindow(maxDecodedIndexSize),
zstd.WithDecodeAllCapLimit(true),
)
if err != nil {
return nil, errors.Wrap(err, "create zstd decoder")
}
defer decoder.Close()
decompressed, err = decoder.DecodeAll(data[4:], make([]byte, 0, maxDecodedIndexSize))
if err != nil {
if stderrors.Is(err, zstd.ErrDecoderSizeExceeded) {
return nil, errors.Wrap(ErrDecodedSizeExceedsLimit, "decompress data")
}
return nil, errors.Wrap(err, "decompress data")
}
default:
return nil, errors.Wrapf(ErrInvalidFormat, "unrecognized magic bytes: %q", magic)
}
buf := bytes.NewReader(decompressed)
idx := NewGINIndex()
if err := readHeader(buf, idx); err != nil {
return nil, errors.Wrap(err, "read header")
}
if err := readPathDirectory(buf, idx); err != nil {
return nil, errors.Wrap(err, "read path directory")
}
bloom, err := readBloomFilter(buf)
if err != nil {
return nil, errors.Wrap(err, "read bloom filter")
}
idx.GlobalBloom = bloom
if err := readStringIndexes(buf, idx); err != nil {
return nil, errors.Wrap(err, "read string indexes")
}
if err := readAdaptiveStringIndexes(buf, idx); err != nil {
return nil, errors.Wrap(err, "read adaptive string indexes")
}
if err := readStringLengthIndexes(buf, idx, idx.Header.NumRowGroups); err != nil {
return nil, errors.Wrap(err, "read string length indexes")
}
if err := readNumericIndexes(buf, idx, idx.Header.NumRowGroups); err != nil {
return nil, errors.Wrap(err, "read numeric indexes")
}
if err := readNullIndexes(buf, idx); err != nil {
return nil, errors.Wrap(err, "read null indexes")
}
if err := readTrigramIndexes(buf, idx); err != nil {
return nil, errors.Wrap(err, "read trigram indexes")
}
if err := readHyperLogLogs(buf, idx); err != nil {
return nil, errors.Wrap(err, "read hyperloglog")
}
if idx.Header.Flags&FlagHasDocIDMap != 0 {
mapping, err := readDocIDMapping(buf, idx.Header.NumDocs)
if err != nil {
return nil, errors.Wrap(err, "read docid mapping")
}
idx.DocIDMapping = mapping
}
cfg, err := readConfig(buf)
if err != nil {
return nil, errors.Wrap(err, "read config")
}
idx.Config = cfg
representations, err := readRepresentations(buf)
if err != nil {
return nil, errors.Wrap(err, "read representations")
}
idx.representations = representations
if err := idx.rebuildPathLookup(); err != nil {
return nil, errors.Wrap(err, "rebuild path lookup")
}
if err := idx.rebuildRepresentationLookup(); err != nil {
return nil, errors.Wrap(err, "rebuild representation lookup")
}
return idx, nil
}
// classifySerializeError maps a serialization error to the frozen error.type vocabulary.
func classifySerializeError(err error) string {
if err == nil {
return ""
}
if stderrors.Is(err, context.Canceled) || stderrors.Is(err, context.DeadlineExceeded) {
return telemetry.ErrorTypeOther
}
if stderrors.Is(err, ErrInvalidFormat) {
return "invalid_format"
}
if stderrors.Is(err, ErrVersionMismatch) {
return errorTypeDeserialization
}
if stderrors.Is(err, ErrDecodedSizeExceedsLimit) {
return "integrity"
}
return telemetry.ErrorTypeOther
}
func writeHeader(w io.Writer, idx *GINIndex) error {
if _, err := w.Write(idx.Header.Magic[:]); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, idx.Header.Version); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, idx.Header.Flags); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, idx.Header.NumRowGroups); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, idx.Header.NumDocs); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, idx.Header.NumPaths); err != nil {
return err
}
return binary.Write(w, binary.LittleEndian, idx.Header.CardinalityThresh)
}
func readHeader(r io.Reader, idx *GINIndex) error {
if _, err := io.ReadFull(r, idx.Header.Magic[:]); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read header magic: %v", err)
}
if string(idx.Header.Magic[:]) != MagicBytes {
return errors.Wrapf(ErrInvalidFormat, "invalid inner magic bytes: %q", string(idx.Header.Magic[:]))
}
if err := binary.Read(r, binary.LittleEndian, &idx.Header.Version); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read header version: %v", err)
}
if idx.Header.Version != Version {
return errors.Wrapf(ErrVersionMismatch, "got version %d, expected %d", idx.Header.Version, Version)
}
if err := binary.Read(r, binary.LittleEndian, &idx.Header.Flags); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read header flags: %v", err)
}
if err := binary.Read(r, binary.LittleEndian, &idx.Header.NumRowGroups); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read header num row groups: %v", err)
}
if idx.Header.NumRowGroups > maxHeaderRowGroups {
return errors.Wrapf(ErrInvalidFormat, "row-group count %d exceeds max %d", idx.Header.NumRowGroups, maxHeaderRowGroups)
}
if err := binary.Read(r, binary.LittleEndian, &idx.Header.NumDocs); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read header num docs: %v", err)
}
if idx.Header.NumDocs > maxHeaderDocs {
return errors.Wrapf(ErrInvalidFormat, "doc count %d exceeds max %d", idx.Header.NumDocs, maxHeaderDocs)
}
if err := binary.Read(r, binary.LittleEndian, &idx.Header.NumPaths); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read header num paths: %v", err)
}
if err := binary.Read(r, binary.LittleEndian, &idx.Header.CardinalityThresh); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read header cardinality threshold: %v", err)
}
return nil
}
func rejectDuplicateSectionPath[T any](kind string, sections map[uint16]T, pathID uint16) error {
if _, exists := sections[pathID]; exists {
return errors.Wrapf(ErrInvalidFormat, "duplicate %s for path %d", kind, pathID)
}
return nil
}
func orderedStringBlockSize(idx *GINIndex) int {
if idx != nil && idx.Config != nil && idx.Config.PrefixBlockSize > 0 {
return idx.Config.PrefixBlockSize
}
return defaultPrefixBlockSize
}
func wrapOrderedStringFormatError(context string, err error) error {
if err == nil {
return nil
}
if stderrors.Is(err, ErrInvalidFormat) {
return err
}
return errors.Wrapf(ErrInvalidFormat, "%s: %v", context, err)
}
func writeOrderedStrings(w io.Writer, values []string, blockSize int) error {
if blockSize < 1 {
blockSize = defaultPrefixBlockSize
}
// Front-coding a zero- or single-value slice cannot beat raw, so skip the
// second encoder entirely for trivial inputs.
if len(values) <= 1 {
rawPayload, err := encodeRawOrderedStrings(values)
if err != nil {
return err
}
_, err = w.Write(rawPayload.Bytes())
return err
}
rawPayload, err := encodeRawOrderedStrings(values)
if err != nil {
return err
}
frontPayload, err := encodeFrontCodedOrderedStrings(values, blockSize)
if err != nil {
return err
}
selected := frontPayload
// Prefer raw on equal size to keep the wire format deterministic across
// encoder changes that leave both encodings equally compact.
if rawPayload.Len() <= frontPayload.Len() {
selected = rawPayload
}
_, err = w.Write(selected.Bytes())
return err
}
func validateOrderedStringLengths(values []string) error {
for i, value := range values {
if len(value) > math.MaxUint16 {
return errors.Errorf("ordered string %d length %d exceeds max %d", i, len(value), math.MaxUint16)
}
}
return nil
}
func encodeRawOrderedStrings(values []string) (*bytes.Buffer, error) {
if err := validateOrderedStringLengths(values); err != nil {
return nil, err
}
var buf bytes.Buffer
if err := buf.WriteByte(compactStringModeRaw); err != nil {
return nil, err
}
if err := binary.Write(&buf, binary.LittleEndian, uint32(len(values))); err != nil {
return nil, err
}
for _, value := range values {
valueBytes := []byte(value)
if err := binary.Write(&buf, binary.LittleEndian, uint16(len(valueBytes))); err != nil {
return nil, err
}
if _, err := buf.Write(valueBytes); err != nil {
return nil, err
}
}
return &buf, nil
}
func encodeFrontCodedOrderedStrings(values []string, blockSize int) (*bytes.Buffer, error) {
if err := validateOrderedStringLengths(values); err != nil {
return nil, err
}
pc, err := NewPrefixCompressor(blockSize)
if err != nil {
return nil, err
}
var buf bytes.Buffer
if err := buf.WriteByte(compactStringModeFrontCoded); err != nil {
return nil, err
}
if err := writeCompressedTerms(&buf, pc.CompressInOrder(values)); err != nil {
return nil, err
}
return &buf, nil
}
func readOrderedStrings(r io.Reader, expectedCount uint32) ([]string, error) {
var mode uint8
if err := binary.Read(r, binary.LittleEndian, &mode); err != nil {
return nil, wrapOrderedStringFormatError("read compact string mode", err)
}
switch mode {
case compactStringModeRaw:
return readRawOrderedStrings(r, expectedCount)
case compactStringModeFrontCoded:
return readFrontCodedOrderedStrings(r, expectedCount)
default:
return nil, errors.Wrapf(ErrInvalidFormat, "unknown compact string mode %d", mode)
}
}
func readFrontCodedOrderedStrings(r io.Reader, expectedCount uint32) ([]string, error) {
var numBlocks uint32
if err := binary.Read(r, binary.LittleEndian, &numBlocks); err != nil {
return nil, wrapOrderedStringFormatError("read front-coded block count", err)
}
if numBlocks > expectedCount {
return nil, errors.Wrapf(ErrInvalidFormat, "front-coded block count %d exceeds expected count %d", numBlocks, expectedCount)
}
blocks := make([]CompressedTermBlock, numBlocks)
decodedCount := uint32(0)
for i := uint32(0); i < numBlocks; i++ {
var firstLen uint16
if err := binary.Read(r, binary.LittleEndian, &firstLen); err != nil {
return nil, wrapOrderedStringFormatError("read front-coded first length", err)
}
firstBytes := make([]byte, firstLen)
if _, err := io.ReadFull(r, firstBytes); err != nil {
return nil, wrapOrderedStringFormatError("read front-coded first bytes", err)
}
blocks[i].FirstTerm = string(firstBytes)
var numEntries uint16
if err := binary.Read(r, binary.LittleEndian, &numEntries); err != nil {
return nil, wrapOrderedStringFormatError("read front-coded entry count", err)
}
decodedCount++
if decodedCount+uint32(numEntries) > expectedCount {
return nil, errors.Wrapf(ErrInvalidFormat, "front-coded block %d entry count %d exceeds expected total %d", i, numEntries, expectedCount)
}
blocks[i].Entries = make([]PrefixEntry, numEntries)
prev := blocks[i].FirstTerm
for j := uint16(0); j < numEntries; j++ {
if err := binary.Read(r, binary.LittleEndian, &blocks[i].Entries[j].PrefixLen); err != nil {
return nil, wrapOrderedStringFormatError("read front-coded prefix length", err)
}
var suffixLen uint16
if err := binary.Read(r, binary.LittleEndian, &suffixLen); err != nil {
return nil, wrapOrderedStringFormatError("read front-coded suffix length", err)
}
suffixBytes := make([]byte, suffixLen)
if _, err := io.ReadFull(r, suffixBytes); err != nil {
return nil, wrapOrderedStringFormatError("read front-coded suffix bytes", err)
}
blocks[i].Entries[j].Suffix = string(suffixBytes)
prefixLen := int(blocks[i].Entries[j].PrefixLen)
if prefixLen > len(prev) {
return nil, errors.Wrapf(
ErrInvalidFormat,
"front-coded block %d entry %d prefix length %d exceeds previous term length %d",
i,
j,
blocks[i].Entries[j].PrefixLen,
len(prev),
)
}
prev = prev[:prefixLen] + blocks[i].Entries[j].Suffix
}
decodedCount += uint32(numEntries)
}
if decodedCount != expectedCount {
return nil, errors.Wrapf(ErrInvalidFormat, "ordered string count mismatch: got %d want %d", decodedCount, expectedCount)
}
// decompressCompressedTerms emits exactly one string per block FirstTerm
// plus one per entry, so its output length equals decodedCount, which the
// guard above has already verified against expectedCount.
return decompressCompressedTerms(blocks), nil
}
func readRawOrderedStrings(r io.Reader, expectedCount uint32) ([]string, error) {
var count uint32
if err := binary.Read(r, binary.LittleEndian, &count); err != nil {
return nil, wrapOrderedStringFormatError("read raw ordered string count", err)
}
if count != expectedCount {
return nil, errors.Wrapf(ErrInvalidFormat, "ordered string count mismatch: got %d want %d", count, expectedCount)
}
values := make([]string, expectedCount)
for i := uint32(0); i < expectedCount; i++ {
var valueLen uint16
if err := binary.Read(r, binary.LittleEndian, &valueLen); err != nil {
return nil, wrapOrderedStringFormatError("read raw ordered string length", err)
}
valueBytes := make([]byte, valueLen)
if _, err := io.ReadFull(r, valueBytes); err != nil {
return nil, wrapOrderedStringFormatError("read raw ordered string bytes", err)
}
values[i] = string(valueBytes)
}
return values, nil
}
func writePathDirectory(w io.Writer, idx *GINIndex) error {
pathNames := make([]string, len(idx.PathDirectory))
for i, entry := range idx.PathDirectory {
pathNames[i] = entry.PathName
}
if err := writeOrderedStrings(w, pathNames, orderedStringBlockSize(idx)); err != nil {
return err
}
for _, entry := range idx.PathDirectory {
if err := binary.Write(w, binary.LittleEndian, entry.PathID); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, entry.ObservedTypes); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, entry.Cardinality); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, entry.Mode); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, entry.Flags); err != nil {
return err
}
}
return nil
}
func readPathDirectory(r io.Reader, idx *GINIndex) error {
if idx.Header.NumPaths > maxNumPaths {
return errors.Wrapf(ErrInvalidFormat, "path count %d exceeds max %d", idx.Header.NumPaths, maxNumPaths)
}
pathNames, err := readOrderedStrings(r, idx.Header.NumPaths)
if err != nil {
return err
}
for i := uint32(0); i < idx.Header.NumPaths; i++ {
entry := PathEntry{PathName: pathNames[i]}
if err := binary.Read(r, binary.LittleEndian, &entry.PathID); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read path id for entry %d: %v", i, err)
}
if err := binary.Read(r, binary.LittleEndian, &entry.ObservedTypes); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read observed types for entry %d: %v", i, err)
}
if err := binary.Read(r, binary.LittleEndian, &entry.Cardinality); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read cardinality for entry %d: %v", i, err)
}
if err := binary.Read(r, binary.LittleEndian, &entry.Mode); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read mode for entry %d: %v", i, err)
}
if !entry.Mode.IsValid() {
return errors.Wrapf(ErrInvalidFormat, "path %q has unknown mode %d", entry.PathName, entry.Mode)
}
if err := binary.Read(r, binary.LittleEndian, &entry.Flags); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read flags for entry %d: %v", i, err)
}
idx.PathDirectory = append(idx.PathDirectory, entry)
}
return nil
}
func writeBloomFilter(w io.Writer, bf *BloomFilter) error {
if err := binary.Write(w, binary.LittleEndian, bf.NumBits()); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, bf.NumHashes()); err != nil {
return err
}
bits := bf.Bits()
if err := binary.Write(w, binary.LittleEndian, uint32(len(bits))); err != nil {
return err
}
for _, word := range bits {
if err := binary.Write(w, binary.LittleEndian, word); err != nil {
return err
}
}
return nil
}
func readBloomFilter(r io.Reader) (*BloomFilter, error) {
var numBits uint32
if err := binary.Read(r, binary.LittleEndian, &numBits); err != nil {
return nil, err
}
var numHashes uint8
if err := binary.Read(r, binary.LittleEndian, &numHashes); err != nil {
return nil, err
}
var numWords uint32
if err := binary.Read(r, binary.LittleEndian, &numWords); err != nil {
return nil, err
}
if numWords > maxBloomWords {
return nil, errors.Wrapf(ErrInvalidFormat, "bloom filter word count %d exceeds max %d", numWords, maxBloomWords)
}
bits := make([]uint64, numWords)
for i := uint32(0); i < numWords; i++ {
if err := binary.Read(r, binary.LittleEndian, &bits[i]); err != nil {
return nil, err
}
}
return BloomFilterFromBits(bits, numBits, numHashes), nil
}
func writeStringIndexes(w io.Writer, idx *GINIndex) error {
if err := binary.Write(w, binary.LittleEndian, uint32(len(idx.StringIndexes))); err != nil {
return err
}
blockSize := orderedStringBlockSize(idx)
for _, pathID := range sortedPathIDs(idx.StringIndexes) {
si := idx.StringIndexes[pathID]
if err := binary.Write(w, binary.LittleEndian, pathID); err != nil {
return err
}
if err := binary.Write(w, binary.LittleEndian, uint32(len(si.Terms))); err != nil {
return err
}
if err := writeOrderedStrings(w, si.Terms, blockSize); err != nil {
return err
}
for i := range si.Terms {
if err := writeRGSet(w, si.RGBitmaps[i]); err != nil {
return err
}
}
}
return nil
}
func readStringIndexes(r io.Reader, idx *GINIndex) error {
var numPaths uint32
if err := binary.Read(r, binary.LittleEndian, &numPaths); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read string index path count: %v", err)
}
if numPaths > maxNumPaths {
return errors.Wrapf(ErrInvalidFormat, "string index path count %d exceeds max %d", numPaths, maxNumPaths)
}
for i := uint32(0); i < numPaths; i++ {
var pathID uint16
if err := binary.Read(r, binary.LittleEndian, &pathID); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read string index path id: %v", err)
}
if err := rejectDuplicateSectionPath("string index", idx.StringIndexes, pathID); err != nil {
return err
}
var numTerms uint32
if err := binary.Read(r, binary.LittleEndian, &numTerms); err != nil {
return errors.Wrapf(ErrInvalidFormat, "read string index term count: %v", err)
}
if numTerms > maxTermsPerPath {
return errors.Wrapf(ErrInvalidFormat, "terms count %d for path %d exceeds max %d", numTerms, pathID, maxTermsPerPath)
}
terms, err := readOrderedStrings(r, numTerms)
if err != nil {
return err
}
si := &StringIndex{
Terms: terms,
RGBitmaps: make([]*RGSet, numTerms),
}
for j := uint32(0); j < numTerms; j++ {
rgSet, err := readRGSet(r, idx.Header.NumRowGroups)
if err != nil {
return err
}
si.RGBitmaps[j] = rgSet
}
idx.StringIndexes[pathID] = si
}
return nil
}
func writeAdaptiveStringIndexes(w io.Writer, idx *GINIndex) error {
if err := binary.Write(w, binary.LittleEndian, uint32(len(idx.AdaptiveStringIndexes))); err != nil {
return err
}
blockSize := orderedStringBlockSize(idx)
for _, pathID := range sortedPathIDs(idx.AdaptiveStringIndexes) {
adaptive := idx.AdaptiveStringIndexes[pathID]
if adaptive == nil {