bump dependencies
Signed-off-by: Jörn Friedrich Dreyer <jfd@butonic.de>
This commit is contained in:
-17
@@ -1,17 +0,0 @@
|
||||
version = 1
|
||||
|
||||
test_patterns = [
|
||||
'**/*_test.go'
|
||||
]
|
||||
|
||||
exclude_patterns = [
|
||||
|
||||
]
|
||||
|
||||
[[analyzers]]
|
||||
name = 'go'
|
||||
enabled = true
|
||||
|
||||
|
||||
[analyzers.meta]
|
||||
import_path = 'github.com/dgraph-io/ristretto'
|
||||
+1
-1
@@ -1 +1 @@
|
||||
1.17.11
|
||||
1.19
|
||||
|
||||
+18
-12
@@ -1,23 +1,29 @@
|
||||
run:
|
||||
tests: false
|
||||
skip-dirs:
|
||||
- contrib
|
||||
- sim
|
||||
skip-files:
|
||||
|
||||
linters-settings:
|
||||
lll:
|
||||
line-length: 120
|
||||
staticcheck:
|
||||
checks:
|
||||
- all
|
||||
- '-SA1019' # it is okay to use math/rand at times.
|
||||
gosec:
|
||||
excludes:
|
||||
- G404 # it is okay to use math/rand at times.
|
||||
|
||||
linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
#- errcheck
|
||||
#- ineffassign
|
||||
- gas
|
||||
#- gofmt
|
||||
#- golint
|
||||
#- gosimple
|
||||
#- govet
|
||||
- errcheck
|
||||
- gofmt
|
||||
- goimports
|
||||
- gosec
|
||||
- gosimple
|
||||
- govet
|
||||
- ineffassign
|
||||
- lll
|
||||
#- varcheck
|
||||
#- unused
|
||||
- staticcheck
|
||||
- unconvert
|
||||
- unused
|
||||
|
||||
+1
-1
@@ -172,7 +172,7 @@ improve performance and reduce memory requirements.
|
||||
### Fixed
|
||||
|
||||
- Fix the way metrics are handled for deletions. ([#111][])
|
||||
- Support nil `*Cache` values in `Clear` and `Close`. ([#119][])
|
||||
- Support nil `*Cache` values in `Clear` and `Close`. ([#119][])
|
||||
- Delete item immediately. ([#113][])
|
||||
- Remove key from policy after TTL eviction. ([#130][])
|
||||
|
||||
|
||||
+47
-38
@@ -7,8 +7,7 @@
|
||||
|
||||
Ristretto is a fast, concurrent cache library built with a focus on performance and correctness.
|
||||
|
||||
The motivation to build Ristretto comes from the need for a contention-free
|
||||
cache in [Dgraph][].
|
||||
The motivation to build Ristretto comes from the need for a contention-free cache in [Dgraph][].
|
||||
|
||||
[Dgraph]: https://github.com/dgraph-io/dgraph
|
||||
|
||||
@@ -19,7 +18,7 @@ cache in [Dgraph][].
|
||||
* **Admission: TinyLFU** - extra performance with little memory overhead (12 bits per counter).
|
||||
* **Fast Throughput** - we use a variety of techniques for managing contention and the result is excellent throughput.
|
||||
* **Cost-Based Eviction** - any large new item deemed valuable can evict multiple smaller items (cost could be anything).
|
||||
* **Fully Concurrent** - you can use as many goroutines as you want with little throughput degradation.
|
||||
* **Fully Concurrent** - you can use as many goroutines as you want with little throughput degradation.
|
||||
* **Metrics** - optional performance metrics for throughput, hit ratios, and other stats.
|
||||
* **Simple API** - just figure out your ideal `Config` values and you're off and running.
|
||||
|
||||
@@ -29,34 +28,41 @@ Ristretto is production-ready. See [Projects using Ristretto](#projects-using-ri
|
||||
|
||||
## Table of Contents
|
||||
|
||||
* [Usage](#Usage)
|
||||
* [Example](#Example)
|
||||
* [Config](#Config)
|
||||
* [NumCounters](#Config)
|
||||
* [MaxCost](#Config)
|
||||
* [BufferItems](#Config)
|
||||
* [Metrics](#Config)
|
||||
* [OnEvict](#Config)
|
||||
* [KeyToHash](#Config)
|
||||
* [Cost](#Config)
|
||||
* [Benchmarks](#Benchmarks)
|
||||
* [Hit Ratios](#Hit-Ratios)
|
||||
* [Search](#Search)
|
||||
* [Database](#Database)
|
||||
* [Looping](#Looping)
|
||||
* [CODASYL](#CODASYL)
|
||||
* [Throughput](#Throughput)
|
||||
* [Mixed](#Mixed)
|
||||
* [Read](#Read)
|
||||
* [Write](#Write)
|
||||
* [Projects using Ristretto](#projects-using-ristretto)
|
||||
* [FAQ](#FAQ)
|
||||
- [Ristretto](#ristretto)
|
||||
- [Features](#features)
|
||||
- [Status](#status)
|
||||
- [Table of Contents](#table-of-contents)
|
||||
- [Usage](#usage)
|
||||
- [Example](#example)
|
||||
- [Config](#config)
|
||||
- [Benchmarks](#benchmarks)
|
||||
- [Hit Ratios](#hit-ratios)
|
||||
- [Search](#search)
|
||||
- [Database](#database)
|
||||
- [Looping](#looping)
|
||||
- [CODASYL](#codasyl)
|
||||
- [Throughput](#throughput)
|
||||
- [Mixed](#mixed)
|
||||
- [Read](#read)
|
||||
- [Write](#write)
|
||||
- [Projects Using Ristretto](#projects-using-ristretto)
|
||||
- [FAQ](#faq)
|
||||
- [How are you achieving this performance? What shortcuts are you taking?](#how-are-you-achieving-this-performance-what-shortcuts-are-you-taking)
|
||||
- [Is Ristretto distributed?](#is-ristretto-distributed)
|
||||
|
||||
## Usage
|
||||
|
||||
### Example
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/dgraph-io/ristretto"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cache, err := ristretto.NewCache(&ristretto.Config{
|
||||
NumCounters: 1e7, // number of keys to track frequency of (10M).
|
||||
@@ -69,46 +75,49 @@ func main() {
|
||||
|
||||
// set a value with a cost of 1
|
||||
cache.Set("key", "value", 1)
|
||||
|
||||
// wait for value to pass through buffers
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// wait for value to pass through buffers
|
||||
cache.Wait()
|
||||
|
||||
// get value from cache
|
||||
value, found := cache.Get("key")
|
||||
if !found {
|
||||
panic("missing value")
|
||||
}
|
||||
fmt.Println(value)
|
||||
|
||||
// del value from cache
|
||||
cache.Del("key")
|
||||
}
|
||||
```
|
||||
|
||||
### Config
|
||||
|
||||
The `Config` struct is passed to `NewCache` when creating Ristretto instances (see the example above).
|
||||
The `Config` struct is passed to `NewCache` when creating Ristretto instances (see the example above).
|
||||
|
||||
**NumCounters** `int64`
|
||||
|
||||
NumCounters is the number of 4-bit access counters to keep for admission and eviction. We've seen good performance in setting this to 10x the number of items you expect to keep in the cache when full.
|
||||
NumCounters is the number of 4-bit access counters to keep for admission and eviction. We've seen good performance in setting this to 10x the number of items you expect to keep in the cache when full.
|
||||
|
||||
For example, if you expect each item to have a cost of 1 and MaxCost is 100, set NumCounters to 1,000. Or, if you use variable cost values but expect the cache to hold around 10,000 items when full, set NumCounters to 100,000. The important thing is the *number of unique items* in the full cache, not necessarily the MaxCost value.
|
||||
For example, if you expect each item to have a cost of 1 and MaxCost is 100, set NumCounters to 1,000. Or, if you use variable cost values but expect the cache to hold around 10,000 items when full, set NumCounters to 100,000. The important thing is the *number of unique items* in the full cache, not necessarily the MaxCost value.
|
||||
|
||||
**MaxCost** `int64`
|
||||
|
||||
MaxCost is how eviction decisions are made. For example, if MaxCost is 100 and a new item with a cost of 1 increases total cache cost to 101, 1 item will be evicted.
|
||||
MaxCost is how eviction decisions are made. For example, if MaxCost is 100 and a new item with a cost of 1 increases total cache cost to 101, 1 item will be evicted.
|
||||
|
||||
MaxCost can also be used to denote the max size in bytes. For example, if MaxCost is 1,000,000 (1MB) and the cache is full with 1,000 1KB items, a new item (that's accepted) would cause 5 1KB items to be evicted.
|
||||
MaxCost can also be used to denote the max size in bytes. For example, if MaxCost is 1,000,000 (1MB) and the cache is full with 1,000 1KB items, a new item (that's accepted) would cause 5 1KB items to be evicted.
|
||||
|
||||
MaxCost could be anything as long as it matches how you're using the cost values when calling Set.
|
||||
MaxCost could be anything as long as it matches how you're using the cost values when calling Set.
|
||||
|
||||
**BufferItems** `int64`
|
||||
|
||||
BufferItems is the size of the Get buffers. The best value we've found for this is 64.
|
||||
BufferItems is the size of the Get buffers. The best value we've found for this is 64.
|
||||
|
||||
If for some reason you see Get performance decreasing with lots of contention (you shouldn't), try increasing this value in increments of 64. This is a fine-tuning mechanism and you probably won't have to touch this.
|
||||
|
||||
**Metrics** `bool`
|
||||
|
||||
Metrics is true when you want real-time logging of a variety of stats. The reason this is a Config flag is because there's a 10% throughput performance overhead.
|
||||
Metrics is true when you want real-time logging of a variety of stats. The reason this is a Config flag is because there's a 10% throughput performance overhead.
|
||||
|
||||
**OnEvict** `func(hashes [2]uint64, value interface{}, cost int64)`
|
||||
|
||||
@@ -213,8 +222,8 @@ Below is a list of known projects that use Ristretto:
|
||||
|
||||
We go into detail in the [Ristretto blog post](https://blog.dgraph.io/post/introducing-ristretto-high-perf-go-cache/), but in short: our throughput performance can be attributed to a mix of batching and eventual consistency. Our hit ratio performance is mostly due to an excellent [admission policy](https://arxiv.org/abs/1512.00727) and SampledLFU eviction policy.
|
||||
|
||||
As for "shortcuts," the only thing Ristretto does that could be construed as one is dropping some Set calls. That means a Set call for a new item (updates are guaranteed) isn't guaranteed to make it into the cache. The new item could be dropped at two points: when passing through the Set buffer or when passing through the admission policy. However, this doesn't affect hit ratios much at all as we expect the most popular items to be Set multiple times and eventually make it in the cache.
|
||||
As for "shortcuts," the only thing Ristretto does that could be construed as one is dropping some Set calls. That means a Set call for a new item (updates are guaranteed) isn't guaranteed to make it into the cache. The new item could be dropped at two points: when passing through the Set buffer or when passing through the admission policy. However, this doesn't affect hit ratios much at all as we expect the most popular items to be Set multiple times and eventually make it in the cache.
|
||||
|
||||
### Is Ristretto distributed?
|
||||
|
||||
No, it's just like any other Go library that you can import into your project and use in a single process.
|
||||
No, it's just like any other Go library that you can import into your project and use in a single process.
|
||||
|
||||
+10
-3
@@ -135,6 +135,8 @@ type Config struct {
|
||||
// cost passed to set is not using bytes as units. Keep in mind that setting
|
||||
// this to true will increase the memory usage.
|
||||
IgnoreInternalCost bool
|
||||
// TtlTickerDurationInSec set the value of time ticker for cleanup keys on ttl
|
||||
TtlTickerDurationInSec int64
|
||||
}
|
||||
|
||||
type itemFlag byte
|
||||
@@ -165,6 +167,8 @@ func NewCache(config *Config) (*Cache, error) {
|
||||
return nil, errors.New("MaxCost can't be zero")
|
||||
case config.BufferItems == 0:
|
||||
return nil, errors.New("BufferItems can't be zero")
|
||||
case config.TtlTickerDurationInSec == 0:
|
||||
config.TtlTickerDurationInSec = bucketDurationSecs
|
||||
}
|
||||
policy := newPolicy(config.NumCounters, config.MaxCost)
|
||||
cache := &Cache{
|
||||
@@ -176,7 +180,7 @@ func NewCache(config *Config) (*Cache, error) {
|
||||
stop: make(chan struct{}),
|
||||
cost: config.Cost,
|
||||
ignoreInternalCost: config.IgnoreInternalCost,
|
||||
cleanupTicker: time.NewTicker(time.Duration(bucketDurationSecs) * time.Second / 2),
|
||||
cleanupTicker: time.NewTicker(time.Duration(config.TtlTickerDurationInSec) * time.Second / 2),
|
||||
}
|
||||
cache.onExit = func(val interface{}) {
|
||||
if config.OnExit != nil && val != nil {
|
||||
@@ -208,6 +212,8 @@ func NewCache(config *Config) (*Cache, error) {
|
||||
return cache, nil
|
||||
}
|
||||
|
||||
// Wait blocks until all buffered writes have been applied. This ensures a call to Set()
|
||||
// will be visible to future calls to Get().
|
||||
func (c *Cache) Wait() {
|
||||
if c == nil || c.isClosed {
|
||||
return
|
||||
@@ -220,7 +226,7 @@ func (c *Cache) Wait() {
|
||||
|
||||
// Get returns the value (if any) and a boolean representing whether the
|
||||
// value was found or not. The value can be nil and the boolean can be true at
|
||||
// the same time.
|
||||
// the same time. Get will not return expired items.
|
||||
func (c *Cache) Get(key interface{}) (interface{}, bool) {
|
||||
if c == nil || c.isClosed || key == nil {
|
||||
return nil, false
|
||||
@@ -264,7 +270,7 @@ func (c *Cache) SetWithTTL(key, value interface{}, cost int64, ttl time.Duration
|
||||
// No expiration.
|
||||
break
|
||||
case ttl < 0:
|
||||
// Treat this a a no-op.
|
||||
// Treat this a no-op.
|
||||
return false
|
||||
default:
|
||||
expiration = time.Now().Add(ttl)
|
||||
@@ -360,6 +366,7 @@ func (c *Cache) Close() {
|
||||
close(c.stop)
|
||||
close(c.setBuf)
|
||||
c.policy.Close()
|
||||
c.cleanupTicker.Stop()
|
||||
c.isClosed = true
|
||||
}
|
||||
|
||||
|
||||
+3
-4
@@ -31,9 +31,8 @@ const (
|
||||
)
|
||||
|
||||
// policy is the interface encapsulating eviction/admission behavior.
|
||||
//
|
||||
// TODO: remove this interface and just rename defaultPolicy to policy, as we
|
||||
// are probably only going to use/implement/maintain one policy.
|
||||
// are probably only going to use/implement/maintain one policy.
|
||||
type policy interface {
|
||||
ringConsumer
|
||||
// Add attempts to Add the key-cost pair to the Policy. It returns a slice
|
||||
@@ -223,7 +222,7 @@ func (p *defaultPolicy) Del(key uint64) {
|
||||
|
||||
func (p *defaultPolicy) Cap() int64 {
|
||||
p.Lock()
|
||||
capacity := int64(p.evict.getMaxCost() - p.evict.used)
|
||||
capacity := p.evict.getMaxCost() - p.evict.used
|
||||
p.Unlock()
|
||||
return capacity
|
||||
}
|
||||
@@ -346,7 +345,7 @@ func (p *sampledLFU) updateIfHas(key uint64, cost int64) bool {
|
||||
p.metrics.add(keyUpdate, key, 1)
|
||||
if prev > cost {
|
||||
diff := prev - cost
|
||||
p.metrics.add(costAdd, key, ^uint64(uint64(diff)-1))
|
||||
p.metrics.add(costAdd, key, ^(uint64(diff) - 1))
|
||||
} else if cost > prev {
|
||||
diff := cost - prev
|
||||
p.metrics.add(costAdd, key, uint64(diff))
|
||||
|
||||
+1
-1
@@ -103,7 +103,7 @@ func newCmRow(numCounters int64) cmRow {
|
||||
}
|
||||
|
||||
func (r cmRow) get(n uint64) byte {
|
||||
return byte(r[n/2]>>((n&1)*4)) & 0x0f
|
||||
return (r[n/2] >> ((n & 1) * 4)) & 0x0f
|
||||
}
|
||||
|
||||
func (r cmRow) increment(n uint64) {
|
||||
|
||||
+6
-4
@@ -127,8 +127,9 @@ func (m *expirationMap) cleanup(store store, policy policy, onEvict itemCallback
|
||||
m.Unlock()
|
||||
|
||||
for key, conflict := range keys {
|
||||
expr := store.Expiration(key)
|
||||
// Sanity check. Verify that the store agrees that this key is expired.
|
||||
if store.Expiration(key).After(now) {
|
||||
if expr.After(now) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -138,9 +139,10 @@ func (m *expirationMap) cleanup(store store, policy policy, onEvict itemCallback
|
||||
|
||||
if onEvict != nil {
|
||||
onEvict(&Item{Key: key,
|
||||
Conflict: conflict,
|
||||
Value: value,
|
||||
Cost: cost,
|
||||
Conflict: conflict,
|
||||
Value: value,
|
||||
Cost: cost,
|
||||
Expiration: expr,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+16
-16
@@ -1,22 +1,22 @@
|
||||
## bbloom: a bitset Bloom filter for go/golang
|
||||
===
|
||||
|
||||
package implements a fast bloom filter with real 'bitset' and JSONMarshal/JSONUnmarshal to store/reload the Bloom filter.
|
||||
package implements a fast bloom filter with real 'bitset' and JSONMarshal/JSONUnmarshal to store/reload the Bloom filter.
|
||||
|
||||
NOTE: the package uses unsafe.Pointer to set and read the bits from the bitset. If you're uncomfortable with using the unsafe package, please consider using my bloom filter package at github.com/AndreasBriese/bloom
|
||||
|
||||
===
|
||||
|
||||
changelog 11/2015: new thread safe methods AddTS(), HasTS(), AddIfNotHasTS() following a suggestion from Srdjan Marinovic (github @a-little-srdjan), who used this to code a bloomfilter cache.
|
||||
changelog 11/2015: new thread safe methods AddTS(), HasTS(), AddIfNotHasTS() following a suggestion from Srdjan Marinovic (github @a-little-srdjan), who used this to code a bloomfilter cache.
|
||||
|
||||
This bloom filter was developed to strengthen a website-log database and was tested and optimized for this log-entry mask: "2014/%02i/%02i %02i:%02i:%02i /info.html".
|
||||
Nonetheless bbloom should work with any other form of entries.
|
||||
This bloom filter was developed to strengthen a website-log database and was tested and optimized for this log-entry mask: "2014/%02i/%02i %02i:%02i:%02i /info.html".
|
||||
Nonetheless bbloom should work with any other form of entries.
|
||||
|
||||
~~Hash function is a modified Berkeley DB sdbm hash (to optimize for smaller strings). sdbm http://www.cse.yorku.ca/~oz/hash.html~~
|
||||
|
||||
Found sipHash (SipHash-2-4, a fast short-input PRF created by Jean-Philippe Aumasson and Daniel J. Bernstein.) to be about as fast. sipHash had been ported by Dimtry Chestnyk to Go (github.com/dchest/siphash )
|
||||
|
||||
Minimum hashset size is: 512 ([4]uint64; will be set automatically).
|
||||
Minimum hashset size is: 512 ([4]uint64; will be set automatically).
|
||||
|
||||
###install
|
||||
|
||||
@@ -25,7 +25,7 @@ go get github.com/AndreasBriese/bbloom
|
||||
```
|
||||
|
||||
###test
|
||||
+ change to folder ../bbloom
|
||||
+ change to folder ../bbloom
|
||||
+ create wordlist in file "words.txt" (you might use `python permut.py`)
|
||||
+ run 'go test -bench=.' within the folder
|
||||
|
||||
@@ -52,10 +52,10 @@ import (
|
||||
at your header. In the program use
|
||||
|
||||
```go
|
||||
// create a bloom filter for 65536 items and 1 % wrong-positive ratio
|
||||
// create a bloom filter for 65536 items and 1 % wrong-positive ratio
|
||||
bf := bbloom.New(float64(1<<16), float64(0.01))
|
||||
|
||||
// or
|
||||
// or
|
||||
// create a bloom filter with 650000 for 65536 items and 7 locs per hash explicitly
|
||||
// bf = bbloom.New(float64(650000), float64(7))
|
||||
// or
|
||||
@@ -64,7 +64,7 @@ bf = bbloom.New(650000.0, 7.0)
|
||||
// add one item
|
||||
bf.Add([]byte("butter"))
|
||||
|
||||
// Number of elements added is exposed now
|
||||
// Number of elements added is exposed now
|
||||
// Note: ElemNum will not be included in JSON export (for compatability to older version)
|
||||
nOfElementsInFilter := bf.ElemNum
|
||||
|
||||
@@ -86,7 +86,7 @@ isNotIn = bf.HasTS([]byte("peanutButter")) // should be false
|
||||
added = bf.AddIfNotHasTS([]byte("butter")) // should be false because 'peanutbutter' is already in the set
|
||||
added = bf.AddIfNotHasTS([]byte("peanutbuTTer")) // should be true because 'penutbuTTer' is new
|
||||
|
||||
// convert to JSON ([]byte)
|
||||
// convert to JSON ([]byte)
|
||||
Json := bf.JSONMarshal()
|
||||
|
||||
// bloomfilters Mutex is exposed for external un-/locking
|
||||
@@ -95,7 +95,7 @@ bf.Mtx.Lock()
|
||||
Json = bf.JSONMarshal()
|
||||
bf.Mtx.Unlock()
|
||||
|
||||
// restore a bloom filter from storage
|
||||
// restore a bloom filter from storage
|
||||
bfNew := bbloom.JSONUnmarshal(Json)
|
||||
|
||||
isInNew := bfNew.Has([]byte("butter")) // should be true
|
||||
@@ -105,17 +105,17 @@ isNotInNew := bfNew.Has([]byte("Butter")) // should be false
|
||||
|
||||
to work with the bloom filter.
|
||||
|
||||
### why 'fast'?
|
||||
### why 'fast'?
|
||||
|
||||
It's about 3 times faster than William Fitzgeralds bitset bloom filter https://github.com/willf/bloom . And it is about so fast as my []bool set variant for Boom filters (see https://github.com/AndreasBriese/bloom ) but having a 8times smaller memory footprint:
|
||||
|
||||
It's about 3 times faster than William Fitzgeralds bitset bloom filter https://github.com/willf/bloom . And it is about so fast as my []bool set variant for Boom filters (see https://github.com/AndreasBriese/bloom ) but having a 8times smaller memory footprint:
|
||||
|
||||
|
||||
Bloom filter (filter size 524288, 7 hashlocs)
|
||||
github.com/AndreasBriese/bbloom 'Add' 65536 items (10 repetitions): 6595800 ns (100 ns/op)
|
||||
github.com/AndreasBriese/bbloom 'Has' 65536 items (10 repetitions): 5986600 ns (91 ns/op)
|
||||
github.com/AndreasBriese/bloom 'Add' 65536 items (10 repetitions): 6304684 ns (96 ns/op)
|
||||
github.com/AndreasBriese/bloom 'Has' 65536 items (10 repetitions): 6568663 ns (100 ns/op)
|
||||
|
||||
|
||||
github.com/willf/bloom 'Add' 65536 items (10 repetitions): 24367224 ns (371 ns/op)
|
||||
github.com/willf/bloom 'Test' 65536 items (10 repetitions): 21881142 ns (333 ns/op)
|
||||
github.com/dataence/bloom/standard 'Add' 65536 items (10 repetitions): 23041644 ns (351 ns/op)
|
||||
@@ -126,4 +126,4 @@ It's about 3 times faster than William Fitzgeralds bitset bloom filter https://g
|
||||
(on MBPro15 OSX10.8.5 i7 4Core 2.4Ghz)
|
||||
|
||||
|
||||
With 32bit bloom filters (bloom32) using modified sdbm, bloom32 does hashing with only 2 bit shifts, one xor and one substraction per byte. smdb is about as fast as fnv64a but gives less collisions with the dataset (see mask above). bloom.New(float64(10 * 1<<16),float64(7)) populated with 1<<16 random items from the dataset (see above) and tested against the rest results in less than 0.05% collisions.
|
||||
With 32bit bloom filters (bloom32) using modified sdbm, bloom32 does hashing with only 2 bit shifts, one xor and one substraction per byte. smdb is about as fast as fnv64a but gives less collisions with the dataset (see mask above). bloom.New(float64(10 * 1<<16),float64(7)) populated with 1<<16 random items from the dataset (see above) and tested against the rest results in less than 0.05% collisions.
|
||||
|
||||
+3
-4
@@ -23,10 +23,9 @@ package z
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"math"
|
||||
"unsafe"
|
||||
|
||||
"github.com/golang/glog"
|
||||
)
|
||||
|
||||
// helper
|
||||
@@ -60,7 +59,7 @@ func NewBloomFilter(params ...float64) (bloomfilter *Bloom) {
|
||||
entries, locs = uint64(params[0]), uint64(params[1])
|
||||
}
|
||||
} else {
|
||||
glog.Fatal("usage: New(float64(number_of_entries), float64(number_of_hashlocations))" +
|
||||
log.Fatal("usage: New(float64(number_of_entries), float64(number_of_hashlocations))" +
|
||||
" i.e. New(float64(1000), float64(3)) or New(float64(number_of_entries)," +
|
||||
" float64(number_of_hashlocations)) i.e. New(float64(1000), float64(0.03))")
|
||||
}
|
||||
@@ -205,7 +204,7 @@ func (bl Bloom) JSONMarshal() []byte {
|
||||
}
|
||||
data, err := json.Marshal(bloomImEx)
|
||||
if err != nil {
|
||||
glog.Fatal("json.Marshal failed: ", err)
|
||||
log.Fatal("json.Marshal failed: ", err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
+3
@@ -30,6 +30,7 @@ import (
|
||||
var (
|
||||
pageSize = os.Getpagesize()
|
||||
maxKeys = (pageSize / 16) - 1
|
||||
//nolint:unused
|
||||
oneThird = int(float64(maxKeys) / 3)
|
||||
)
|
||||
|
||||
@@ -480,6 +481,8 @@ func (t *Tree) split(pid uint64) node {
|
||||
// shareWithSiblingXXX is unused for now. The idea is to move some keys to
|
||||
// sibling when a node is full. But, I don't see any special benefits in our
|
||||
// access pattern. It doesn't result in better occupancy ratios.
|
||||
//
|
||||
//nolint:unused
|
||||
func (t *Tree) shareWithSiblingXXX(n node, idx int) bool {
|
||||
if idx == 0 {
|
||||
return false
|
||||
|
||||
+19
-17
@@ -19,12 +19,11 @@ package z
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"sort"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/golang/glog"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
@@ -92,7 +91,7 @@ func NewBufferTmp(dir string, capacity int) (*Buffer, error) {
|
||||
if dir == "" {
|
||||
dir = tmpDir
|
||||
}
|
||||
file, err := ioutil.TempFile(dir, "buffer")
|
||||
file, err := os.CreateTemp(dir, "buffer")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -200,7 +199,7 @@ func (b *Buffer) Grow(n int) {
|
||||
// If autoMmap gets triggered, copy the slice over to an mmaped file.
|
||||
if b.autoMmapAfter > 0 && b.curSz > b.autoMmapAfter {
|
||||
b.bufType = UseMmap
|
||||
file, err := ioutil.TempFile(b.autoMmapDir, "")
|
||||
file, err := os.CreateTemp(b.autoMmapDir, "")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -254,8 +253,8 @@ func (b *Buffer) AllocateOffset(n int) int {
|
||||
}
|
||||
|
||||
func (b *Buffer) writeLen(sz int) {
|
||||
buf := b.Allocate(4)
|
||||
binary.BigEndian.PutUint32(buf, uint32(sz))
|
||||
buf := b.Allocate(8)
|
||||
binary.BigEndian.PutUint64(buf, uint64(sz))
|
||||
}
|
||||
|
||||
// SliceAllocate would encode the size provided into the buffer, followed by a call to Allocate,
|
||||
@@ -263,7 +262,7 @@ func (b *Buffer) writeLen(sz int) {
|
||||
// this big buffer.
|
||||
// Note that SliceAllocate should NOT be mixed with normal calls to Write.
|
||||
func (b *Buffer) SliceAllocate(sz int) []byte {
|
||||
b.Grow(4 + sz)
|
||||
b.Grow(8 + sz)
|
||||
b.writeLen(sz)
|
||||
return b.Allocate(sz)
|
||||
}
|
||||
@@ -281,7 +280,9 @@ func (b *Buffer) SliceIterate(f func(slice []byte) error) error {
|
||||
if b.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
slice, next := []byte{}, b.StartOffset()
|
||||
|
||||
next := b.StartOffset()
|
||||
var slice []byte
|
||||
for next >= 0 {
|
||||
slice, next = b.Slice(next)
|
||||
if len(slice) == 0 {
|
||||
@@ -291,6 +292,7 @@ func (b *Buffer) SliceIterate(f func(slice []byte) error) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -339,19 +341,19 @@ func (s *sortHelper) sortSmall(start, end int) {
|
||||
})
|
||||
// Now we iterate over the s.small offsets and copy over the slices. The result is now in order.
|
||||
for _, off := range s.small {
|
||||
s.tmp.Write(rawSlice(s.b.buf[off:]))
|
||||
_, _ = s.tmp.Write(rawSlice(s.b.buf[off:]))
|
||||
}
|
||||
assert(end-start == copy(s.b.buf[start:end], s.tmp.Bytes()))
|
||||
}
|
||||
|
||||
func assert(b bool) {
|
||||
if !b {
|
||||
glog.Fatalf("%+v", errors.Errorf("Assertion failure"))
|
||||
log.Fatalf("%+v", errors.Errorf("Assertion failure"))
|
||||
}
|
||||
}
|
||||
func check(err error) {
|
||||
if err != nil {
|
||||
glog.Fatalf("%+v", err)
|
||||
log.Fatalf("%+v", err)
|
||||
}
|
||||
}
|
||||
func check2(_ interface{}, err error) {
|
||||
@@ -392,7 +394,7 @@ func (s *sortHelper) merge(left, right []byte, start, end int) {
|
||||
rs = rawSlice(right)
|
||||
|
||||
// We skip the first 4 bytes in the rawSlice, because that stores the length.
|
||||
if s.less(ls[4:], rs[4:]) {
|
||||
if s.less(ls[8:], rs[8:]) {
|
||||
copyLeft()
|
||||
} else {
|
||||
copyRight()
|
||||
@@ -454,7 +456,7 @@ func (b *Buffer) SortSliceBetween(start, end int, less LessFunc) {
|
||||
small: make([]int, 0, 1024),
|
||||
tmp: NewBuffer(szTmp, b.tag),
|
||||
}
|
||||
defer s.tmp.Release()
|
||||
defer func() { _ = s.tmp.Release() }()
|
||||
|
||||
left := offsets[0]
|
||||
for _, off := range offsets[1:] {
|
||||
@@ -465,8 +467,8 @@ func (b *Buffer) SortSliceBetween(start, end int, less LessFunc) {
|
||||
}
|
||||
|
||||
func rawSlice(buf []byte) []byte {
|
||||
sz := binary.BigEndian.Uint32(buf)
|
||||
return buf[:4+int(sz)]
|
||||
sz := binary.BigEndian.Uint64(buf)
|
||||
return buf[:8+int(sz)]
|
||||
}
|
||||
|
||||
// Slice would return the slice written at offset.
|
||||
@@ -475,8 +477,8 @@ func (b *Buffer) Slice(offset int) ([]byte, int) {
|
||||
return nil, -1
|
||||
}
|
||||
|
||||
sz := binary.BigEndian.Uint32(b.buf[offset:])
|
||||
start := offset + 4
|
||||
sz := binary.BigEndian.Uint64(b.buf[offset:])
|
||||
start := offset + 8
|
||||
next := start + int(sz)
|
||||
res := b.buf[start:next]
|
||||
if next >= int(b.offset) {
|
||||
|
||||
+1
@@ -2,6 +2,7 @@
|
||||
// of this source code is governed by a BSD-style license that can be found in
|
||||
// the LICENSE file.
|
||||
|
||||
//go:build amd64 || arm64 || arm64be || ppc64 || ppc64le || mips64 || mips64le || riscv64 || s390x || sparc64
|
||||
// +build amd64 arm64 arm64be ppc64 ppc64le mips64 mips64le riscv64 s390x sparc64
|
||||
|
||||
package z
|
||||
|
||||
+2
-1
@@ -2,6 +2,7 @@
|
||||
// of this source code is governed by a BSD-style license that can be found in
|
||||
// the LICENSE file.
|
||||
|
||||
//go:build !jemalloc || !cgo
|
||||
// +build !jemalloc !cgo
|
||||
|
||||
package z
|
||||
@@ -34,4 +35,4 @@ func StatsPrint() {
|
||||
|
||||
// ReadMemStats doesn't do anything since all the memory is being managed
|
||||
// by the Go runtime.
|
||||
func ReadMemStats(_ *MemStats) { return }
|
||||
func ReadMemStats(_ *MemStats) {}
|
||||
|
||||
+3
-1
@@ -61,7 +61,9 @@ func OpenMmapFileUsing(fd *os.File, sz int, writable bool) (*MmapFile, error) {
|
||||
|
||||
if fileSize == 0 {
|
||||
dir, _ := filepath.Split(filename)
|
||||
go SyncDir(dir)
|
||||
if err := SyncDir(dir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &MmapFile{
|
||||
Data: buf,
|
||||
|
||||
+1
@@ -1,3 +1,4 @@
|
||||
//go:build !linux
|
||||
// +build !linux
|
||||
|
||||
/*
|
||||
|
||||
+10
-10
@@ -2,6 +2,7 @@ package z
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
@@ -10,7 +11,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/golang/glog"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
@@ -109,7 +109,7 @@ type SuperFlag struct {
|
||||
func NewSuperFlag(flag string) *SuperFlag {
|
||||
sf, err := newSuperFlagImpl(flag)
|
||||
if err != nil {
|
||||
glog.Fatal(err)
|
||||
log.Fatal(err)
|
||||
}
|
||||
return sf
|
||||
}
|
||||
@@ -136,7 +136,7 @@ func (sf *SuperFlag) String() string {
|
||||
func (sf *SuperFlag) MergeAndCheckDefault(flag string) *SuperFlag {
|
||||
sf, err := sf.mergeAndCheckDefaultImpl(flag)
|
||||
if err != nil {
|
||||
glog.Fatal(err)
|
||||
log.Fatal(err)
|
||||
}
|
||||
return sf
|
||||
}
|
||||
@@ -162,7 +162,7 @@ func (sf *SuperFlag) mergeAndCheckDefaultImpl(flag string) (*SuperFlag, error) {
|
||||
}
|
||||
}
|
||||
if numKeys != 0 {
|
||||
return nil, fmt.Errorf("superflag: found invalid options in flag: %s.\nvalid options: %v", sf, flag)
|
||||
return nil, fmt.Errorf("superflag: found invalid options: %s.\nvalid options: %v", sf, flag)
|
||||
}
|
||||
for k, v := range src {
|
||||
if _, ok := sf.m[k]; !ok {
|
||||
@@ -207,7 +207,7 @@ func (sf *SuperFlag) GetBool(opt string) bool {
|
||||
err = errors.Wrapf(err,
|
||||
"Unable to parse %s as bool for key: %s. Options: %s\n",
|
||||
val, opt, sf)
|
||||
glog.Fatalf("%+v", err)
|
||||
log.Fatalf("%+v", err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -222,7 +222,7 @@ func (sf *SuperFlag) GetFloat64(opt string) float64 {
|
||||
err = errors.Wrapf(err,
|
||||
"Unable to parse %s as float64 for key: %s. Options: %s\n",
|
||||
val, opt, sf)
|
||||
glog.Fatalf("%+v", err)
|
||||
log.Fatalf("%+v", err)
|
||||
}
|
||||
return f
|
||||
}
|
||||
@@ -237,7 +237,7 @@ func (sf *SuperFlag) GetInt64(opt string) int64 {
|
||||
err = errors.Wrapf(err,
|
||||
"Unable to parse %s as int64 for key: %s. Options: %s\n",
|
||||
val, opt, sf)
|
||||
glog.Fatalf("%+v", err)
|
||||
log.Fatalf("%+v", err)
|
||||
}
|
||||
return i
|
||||
}
|
||||
@@ -252,7 +252,7 @@ func (sf *SuperFlag) GetUint64(opt string) uint64 {
|
||||
err = errors.Wrapf(err,
|
||||
"Unable to parse %s as uint64 for key: %s. Options: %s\n",
|
||||
val, opt, sf)
|
||||
glog.Fatalf("%+v", err)
|
||||
log.Fatalf("%+v", err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
@@ -267,7 +267,7 @@ func (sf *SuperFlag) GetUint32(opt string) uint32 {
|
||||
err = errors.Wrapf(err,
|
||||
"Unable to parse %s as uint32 for key: %s. Options: %s\n",
|
||||
val, opt, sf)
|
||||
glog.Fatalf("%+v", err)
|
||||
log.Fatalf("%+v", err)
|
||||
}
|
||||
return uint32(u)
|
||||
}
|
||||
@@ -283,7 +283,7 @@ func (sf *SuperFlag) GetPath(opt string) string {
|
||||
p := sf.GetString(opt)
|
||||
path, err := expandPath(p)
|
||||
if err != nil {
|
||||
glog.Fatalf("Failed to get path: %+v", err)
|
||||
log.Fatalf("Failed to get path: %+v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
// +build !windows,!darwin,!plan9,!linux
|
||||
//go:build !windows && !darwin && !plan9 && !linux && !wasip1
|
||||
// +build !windows,!darwin,!plan9,!linux,!wasip1
|
||||
|
||||
/*
|
||||
* Copyright 2019 Dgraph Labs, Inc. and Contributors
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
//go:build wasip1
|
||||
|
||||
/*
|
||||
* Copyright 2023 Dgraph Labs, Inc. and Contributors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package z
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func mmap(fd *os.File, writeable bool, size int64) ([]byte, error) {
|
||||
return nil, syscall.ENOSYS
|
||||
}
|
||||
|
||||
func munmap(b []byte) error {
|
||||
return syscall.ENOSYS
|
||||
}
|
||||
|
||||
func madvise(b []byte, readahead bool) error {
|
||||
return syscall.ENOSYS
|
||||
}
|
||||
|
||||
func msync(b []byte) error {
|
||||
return syscall.ENOSYS
|
||||
}
|
||||
+1
@@ -1,3 +1,4 @@
|
||||
//go:build !arm64
|
||||
// +build !arm64
|
||||
|
||||
/*
|
||||
|
||||
+3
@@ -27,10 +27,12 @@ import (
|
||||
)
|
||||
|
||||
// NanoTime returns the current time in nanoseconds from a monotonic clock.
|
||||
//
|
||||
//go:linkname NanoTime runtime.nanotime
|
||||
func NanoTime() int64
|
||||
|
||||
// CPUTicks is a faster alternative to NanoTime to measure time duration.
|
||||
//
|
||||
//go:linkname CPUTicks runtime.cputicks
|
||||
func CPUTicks() int64
|
||||
|
||||
@@ -60,6 +62,7 @@ func MemHashString(str string) uint64 {
|
||||
}
|
||||
|
||||
// FastRand is a fast thread local random function.
|
||||
//
|
||||
//go:linkname FastRand runtime.fastrand
|
||||
func FastRand() uint32
|
||||
|
||||
|
||||
+3
@@ -98,6 +98,7 @@ func Binary(keys []uint64, key uint64) int16 {
|
||||
}))
|
||||
}
|
||||
|
||||
//nolint:unused
|
||||
func cmp2_native(twos, pk [2]uint64) int16 {
|
||||
if twos[0] == pk[0] {
|
||||
return 0
|
||||
@@ -108,6 +109,7 @@ func cmp2_native(twos, pk [2]uint64) int16 {
|
||||
return 2
|
||||
}
|
||||
|
||||
//nolint:unused
|
||||
func cmp4_native(fours, pk [4]uint64) int16 {
|
||||
for i := range fours {
|
||||
if fours[i] >= pk[i] {
|
||||
@@ -117,6 +119,7 @@ func cmp4_native(fours, pk [4]uint64) int16 {
|
||||
return 4
|
||||
}
|
||||
|
||||
//nolint:unused
|
||||
func cmp8_native(a [8]uint64, pk [4]uint64) int16 {
|
||||
for i := range a {
|
||||
if a[i] >= pk[0] {
|
||||
|
||||
+7
-8
@@ -23,14 +23,13 @@ import (
|
||||
"github.com/cespare/xxhash/v2"
|
||||
)
|
||||
|
||||
// TODO: Figure out a way to re-use memhash for the second uint64 hash, we
|
||||
// already know that appending bytes isn't reliable for generating a
|
||||
// second hash (see Ristretto PR #88).
|
||||
//
|
||||
// We also know that while the Go runtime has a runtime memhash128
|
||||
// function, it's not possible to use it to generate [2]uint64 or
|
||||
// anything resembling a 128bit hash, even though that's exactly what
|
||||
// we need in this situation.
|
||||
// TODO: Figure out a way to re-use memhash for the second uint64 hash,
|
||||
// we already know that appending bytes isn't reliable for generating a
|
||||
// second hash (see Ristretto PR #88).
|
||||
// We also know that while the Go runtime has a runtime memhash128
|
||||
// function, it's not possible to use it to generate [2]uint64 or
|
||||
// anything resembling a 128bit hash, even though that's exactly what
|
||||
// we need in this situation.
|
||||
func KeyToHash(key interface{}) (uint64, uint64) {
|
||||
if key == nil {
|
||||
return 0, 0
|
||||
|
||||
Reference in New Issue
Block a user