This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 104
/
tsz.go
456 lines (392 loc) · 10.1 KB
/
tsz.go
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
// Package tsz implements time-series compression
// it is a fork of https://github.com/dgryski/go-tsz
// which implements http://www.vldb.org/pvldb/vol8/p1816-teller.pdf
// see devdocs/chunk-format.md for more info
package tsz
import (
"bytes"
"encoding/binary"
"io"
"math"
"math/bits"
"sync"
)
// Series4h is the basic series primitive
// you can concurrently put values, finish the stream, and create iterators
// you shouldn't use it for chunks longer than 4.5 hours, due to overflow
// of the first delta (14 bits), though in some cases, the corresponding iterator
// can reconstruct the data. Only works for <=9h deltas/chunks though.
// See https://github.com/grafana/metrictank/pull/1126
type Series4h struct {
sync.Mutex
// TODO(dgryski): timestamps in the paper are uint64
T0 uint32
t uint32
val float64
bw bstream
leading uint8
trailing uint8
finished bool
tDelta uint32
}
// NewSeries4h creates a new Series4h
func NewSeries4h(t0 uint32) *Series4h {
s := Series4h{
T0: t0,
leading: ^uint8(0),
}
// block header
s.bw.writeBits(uint64(t0), 32)
return &s
}
// Bytes value of the series stream
func (s *Series4h) Bytes() []byte {
s.Lock()
defer s.Unlock()
return s.bw.bytes()
}
// Finish the series by writing an end-of-stream record
func (s *Series4h) Finish() {
s.Lock()
if !s.finished {
finishV1(&s.bw)
s.finished = true
}
s.Unlock()
}
// Push a timestamp and value to the series
func (s *Series4h) Push(t uint32, v float64) {
s.Lock()
defer s.Unlock()
if s.t == 0 {
// first point
s.t = t
s.val = v
s.tDelta = t - s.T0
s.bw.writeBits(uint64(s.tDelta), 14)
s.bw.writeBits(math.Float64bits(v), 64)
return
}
tDelta := t - s.t
dod := int32(tDelta - s.tDelta)
switch {
case dod == 0:
s.bw.writeBit(zero)
case -63 <= dod && dod <= 64:
s.bw.writeBits(0x02, 2) // '10'
s.bw.writeBits(uint64(dod), 7)
case -255 <= dod && dod <= 256:
s.bw.writeBits(0x06, 3) // '110'
s.bw.writeBits(uint64(dod), 9)
case -2047 <= dod && dod <= 2048:
s.bw.writeBits(0x0e, 4) // '1110'
s.bw.writeBits(uint64(dod), 12)
default:
s.bw.writeBits(0x0f, 4) // '1111'
s.bw.writeBits(uint64(dod), 32)
}
vDelta := math.Float64bits(v) ^ math.Float64bits(s.val)
if vDelta == 0 {
s.bw.writeBit(zero)
} else {
s.bw.writeBit(one)
leading := uint8(bits.LeadingZeros64(vDelta))
trailing := uint8(bits.TrailingZeros64(vDelta))
// clamp number of leading zeros to avoid overflow when encoding
if leading >= 32 {
leading = 31
}
// TODO(dgryski): check if it's 'cheaper' to reset the leading/trailing bits instead
if s.leading != ^uint8(0) && leading >= s.leading && trailing >= s.trailing {
s.bw.writeBit(zero)
s.bw.writeBits(vDelta>>s.trailing, 64-int(s.leading)-int(s.trailing))
} else {
s.leading, s.trailing = leading, trailing
s.bw.writeBit(one)
s.bw.writeBits(uint64(leading), 5)
// Note that if leading == trailing == 0, then sigbits == 64. But that value doesn't actually fit into the 6 bits we have.
// Luckily, we never need to encode 0 significant bits, since that would put us in the other case (vdelta == 0).
// So instead we write out a 0 and adjust it back to 64 on unpacking.
sigbits := 64 - leading - trailing
s.bw.writeBits(uint64(sigbits), 6)
s.bw.writeBits(vDelta>>trailing, int(sigbits))
}
}
s.tDelta = tDelta
s.t = t
s.val = v
}
// Iter4h lets you iterate over a series. It is not concurrency-safe.
func (s *Series4h) Iter(intervalHint uint32) *Iter4h {
s.Lock()
w := s.bw.clone()
s.Unlock()
finishV1(w)
iter, _ := bstreamIterator4h(w, intervalHint)
return iter
}
// Iter4h lets you iterate over a Series4h. It is not concurrency-safe.
// For more info, see Series4h
type Iter4h struct {
T0 uint32
intervalHint uint32 // hint to recover corrupted delta's
t uint32
val float64
br bstream
leading uint8
trailing uint8
finished bool
tDelta uint32
err error
}
func bstreamIterator4h(br *bstream, intervalHint uint32) (*Iter4h, error) {
br.count = 8
t0, err := br.readBits(32)
if err != nil {
return nil, err
}
return &Iter4h{
T0: uint32(t0),
intervalHint: intervalHint,
br: *br,
}, nil
}
// NewIterator4h creates an Iter4h
func NewIterator4h(b []byte, intervalHint uint32) (*Iter4h, error) {
return bstreamIterator4h(newBReader(b), intervalHint)
}
func (it *Iter4h) dod() (int32, bool) {
var d byte
for i := 0; i < 4; i++ {
d <<= 1
bit, err := it.br.readBit()
if err != nil {
it.err = err
return 0, false
}
if bit == zero {
break
}
d |= 1
}
var dod int32
var sz uint
switch d {
case 0x00:
// dod == 0
case 0x02: // '10'
sz = 7
case 0x06: // '110'
sz = 9
case 0x0e: // '1110'
sz = 12
case 0x0f: // '1111'
bits, err := it.br.readBits(32)
if err != nil {
it.err = err
return 0, false
}
// end of stream
if bits == 0xffffffff {
it.finished = true
return 0, false
}
dod = int32(bits)
}
if sz != 0 {
bits, err := it.br.readBits(int(sz))
if err != nil {
it.err = err
return 0, false
}
if bits > (1 << (sz - 1)) {
// or something
bits = bits - (1 << sz)
}
dod = int32(bits)
}
return dod, true
}
// Next iteration of the series iterator
func (it *Iter4h) Next() bool {
if it.err != nil || it.finished {
return false
}
if it.t == 0 {
// read first t and v
tDelta, err := it.br.readBits(14)
if err != nil {
it.err = err
return false
}
it.tDelta = uint32(tDelta)
it.t = it.T0 + it.tDelta
v, err := it.br.readBits(64)
if err != nil {
it.err = err
return false
}
it.val = math.Float64frombits(v)
// look for delta overflow and remediate it
// see https://github.com/grafana/metrictank/pull/1126 and
// https://github.com/grafana/metrictank/pull/1129
// first, let's try the hint based check
// if we're aware of a consistent interval that the points should have
// - which is the case for rollup archives: they have known, consistent intervals -
// then we can simply rely on that to tell whether our delta overflowed.
// this requires the interval to be >1 (always true for rollup chunks)
// and not be a divisor of 16384 (also true for rollup chunks, they use long, round intervals like 300)
if it.intervalHint > 0 && it.t%it.intervalHint != 0 {
it.tDelta += 16384
it.t += 16384
return true
}
// if we don't have a hint - e.g. for raw data - read upcoming dod
// if delta+dod <0 (aka the upcoming delta < 0),
// our current delta overflowed, because points should always be in increasing time order
// (have delta's > 0)
// we must take a backup of the stream because reading from the stream reader modifies it.
// note that potentially we could skip this remediation by using another hint: the chunkspan,
// since we know the overflow cannot possibly happen for chunks <=4h in length. perhaps a future optimization.
brBackup := it.br.clone()
dod, ok := it.dod()
if !ok {
// this case should only happen if we're out of data (only a single point in the chunk)
// in this case we can't know if the point is right or wrong.
// so, nothing much to do in this case. return the possibly incorrect point.
// though it is very unlikely to be wrong, because the overflow problem only tends to happen in long aggregated chunks
// that have an intervalHint.
// and for return value, stick to normal iter semantics:
// this read succeeded, though we already know the next one will fail
it.br = *brBackup
return true
}
if dod+int32(tDelta) < 0 {
it.tDelta += 16384
it.t += 16384
}
it.br = *brBackup
return true
}
// read delta-of-delta
dod, ok := it.dod()
if !ok {
return false
}
tDelta := it.tDelta + uint32(dod)
it.tDelta = tDelta
it.t = it.t + it.tDelta
// read compressed value
bit, err := it.br.readBit()
if err != nil {
it.err = err
return false
}
if bit == zero {
// it.val = it.val
} else {
bit, itErr := it.br.readBit()
if itErr != nil {
it.err = err
return false
}
if bit == zero {
// reuse leading/trailing zero bits
// it.leading, it.trailing = it.leading, it.trailing
} else {
bits, err := it.br.readBits(5)
if err != nil {
it.err = err
return false
}
it.leading = uint8(bits)
bits, err = it.br.readBits(6)
if err != nil {
it.err = err
return false
}
mbits := uint8(bits)
// 0 significant bits here means we overflowed and we actually need 64; see comment in encoder
if mbits == 0 {
mbits = 64
}
it.trailing = 64 - it.leading - mbits
}
mbits := int(64 - it.leading - it.trailing)
bits, err := it.br.readBits(mbits)
if err != nil {
it.err = err
return false
}
vbits := math.Float64bits(it.val)
vbits ^= (bits << it.trailing)
it.val = math.Float64frombits(vbits)
}
return true
}
// Values at the current iterator position
func (it *Iter4h) Values() (uint32, float64) {
return it.t, it.val
}
// Err error at the current iterator position
func (it *Iter4h) Err() error {
return it.err
}
type errMarshal struct {
w io.Writer
r io.Reader
err error
}
func (em *errMarshal) write(t interface{}) {
if em.err != nil {
return
}
em.err = binary.Write(em.w, binary.BigEndian, t)
}
func (em *errMarshal) read(t interface{}) {
if em.err != nil {
return
}
em.err = binary.Read(em.r, binary.BigEndian, t)
}
// MarshalBinary implements the encoding.BinaryMarshaler interface
func (s *Series4h) MarshalBinary() ([]byte, error) {
buf := new(bytes.Buffer)
em := &errMarshal{w: buf}
em.write(s.T0)
em.write(s.leading)
em.write(s.t)
em.write(s.tDelta)
em.write(s.trailing)
em.write(s.val)
bStream, err := s.bw.MarshalBinary()
if err != nil {
return nil, err
}
em.write(bStream)
if em.err != nil {
return nil, em.err
}
return buf.Bytes(), nil
}
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (s *Series4h) UnmarshalBinary(b []byte) error {
buf := bytes.NewReader(b)
em := &errMarshal{r: buf}
em.read(&s.T0)
em.read(&s.leading)
em.read(&s.t)
em.read(&s.tDelta)
em.read(&s.trailing)
em.read(&s.val)
outBuf := make([]byte, buf.Len())
em.read(outBuf)
err := s.bw.UnmarshalBinary(outBuf)
if err != nil {
return err
}
if em.err != nil {
return em.err
}
return nil
}