diff --git a/.circleci/config.yml b/.circleci/config.yml index f2e70731e..42de1db0c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -13,55 +13,53 @@ executors: - image: circleci/golang:<< parameters.version >> resource_class: << parameters.resource_class >> working_directory: /go/src/github.com/pilosa/pilosa - environment: - GO111MODULE: "on" # TODO: Only needed for Go <1.13, remove when dropping support for 1.11/1.12. commands: add-github-auth: steps: - run: git config --global url."https://moleculacorp:${GITHUB_PERSONAL_ACCESS_TOKEN}@github.com".insteadOf "https://github.com" + restore-mod-cache: + steps: + - restore_cache: + key: mod-cache-{{ checksum "go.sum" }} + save-mod-cache: + steps: + - save_cache: + key: mod-cache-{{ checksum "go.sum" }} + paths: + - /go/pkg/mod/ + checkout-plus: + steps: + - add-github-auth + - checkout + - restore-mod-cache jobs: setup: executor: name: golang steps: - - add-github-auth - - checkout - - restore_cache: - keys: - - mod-cache-{{ checksum "go.sum" }} - - run: "go mod download" - - save_cache: - key: mod-cache-{{ checksum "go.sum" }} - paths: - - /go/pkg/mod/ - - persist_to_workspace: - root: . - paths: "*" + - checkout-plus + - run: go mod download + - save-mod-cache check-license-headers: executor: name: golang steps: - - attach_workspace: - at: . + - checkout-plus - run: make check-license-headers linter: executor: name: golang steps: - - attach_workspace: - at: . - - add-github-auth + - checkout-plus - run: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sudo sh -s -- -b /usr/local/bin v1.23.8 - run: make golangci-lint test-build-arm: executor: name: golang steps: - - attach_workspace: - at: . - - add-github-auth + - checkout-plus - run: make build GOOS=linux GOARCH=arm GOARM=5 - run: make build GOOS=linux GOARCH=arm GOARM=6 - run: make build GOOS=linux GOARCH=arm GOARM=7 @@ -91,9 +89,7 @@ jobs: version: << parameters.golang_version >> resource_class: << parameters.resource_class >> steps: - - attach_workspace: - at: . - - add-github-auth + - checkout-plus - run: sudo apt-get install lsof - run: command: make << parameters.test_make_target >> SHARD_WIDTH=<< parameters.shard_width >> GOARCH=<< parameters.goarch >> @@ -102,18 +98,14 @@ jobs: executor: name: golang steps: - - attach_workspace: - at: . - - add-github-auth + - checkout-plus - setup_remote_docker - run: make clustertests-build prerelease: executor: name: golang steps: - - attach_workspace: - at: . - - add-github-auth + - checkout-plus - run: make prerelease - store_artifacts: path: build @@ -124,6 +116,7 @@ jobs: executor: name: golang steps: + - checkout-plus - attach_workspace: at: . - run: make release @@ -136,50 +129,39 @@ jobs: docker: - image: circleci/python:2.7-jessie steps: + - checkout-plus - attach_workspace: at: . - run: sudo pip install awscli - run: make prerelease-upload - dockerhub-upload: - parameters: - tag_branch: - type: boolean - default: true - tag_tag: - type: boolean - default: false - tag_latest: - type: boolean - default: false - target_name: - type: string - default: moleculacorp/pilosa + dockerhub-upload-unstable: executor: name: golang steps: - - attach_workspace: - at: . - - add-github-auth + - checkout-plus - setup_remote_docker - run: make docker - run: docker login -u $DOCKER_USER -p $DOCKER_PASS - - when: - condition: << parameters.tag_branch >> - steps: - - run: make docker-tag-push DOCKER_TARGET=<< parameters.target_name >>:<< pipeline.git.branch >> - - when: - condition: << parameters.tag_tag >> - steps: - - run: make docker-tag-push DOCKER_TARGET=<< parameters.target_name >>:$(git describe --tags) - - when: - condition: << parameters.tag_latest >> - steps: - - run: make docker-tag-push DOCKER_TARGET=<< parameters.target_name >>:latest - + - run: make docker-tag-push DOCKER_TARGET=moleculacorp/pilosa:<< pipeline.git.branch >> + dockerhub-upload-stable: + executor: + name: golang + steps: + - checkout-plus + - setup_remote_docker + - run: make docker + - run: docker login -u $DOCKER_USER -p $DOCKER_PASS + - run: make docker-tag-push DOCKER_TARGET=moleculacorp/pilosa:<< pipeline.git.tag >> + - run: make docker-tag-push DOCKER_TARGET=moleculacorp/pilosa:latest + workflows: build: jobs: - - setup + - setup: + context: molecula + filters: + tags: + only: /^v.*/ - linter: requires: - setup @@ -193,9 +175,12 @@ workflows: name: test-golang-<< matrix.golang_version >> matrix: parameters: - golang_version: ["1.14", "1.13", "1.12", "1.11"] + golang_version: ["1.14", "1.13"] requires: - setup + filters: + tags: + only: /^v.*/ - test: name: test-race test_make_target: test-race @@ -220,27 +205,17 @@ workflows: - linter - check-license-headers - test-golang-1.14 - - dockerhub-upload: - name: dockerhub-upload-unstable - tag_branch: true - tag_tag: false - tag_latest: false + - dockerhub-upload-unstable: + context: molecula requires: - - linter - - check-license-headers - - test-golang-1.14 + - setup filters: branches: only: master - - dockerhub-upload: - name: dockerhub-upload-stable - tag_branch: true - tag_tag: true - tag_latest: true + - dockerhub-upload-stable: + context: molecula requires: - - linter - - check-license-headers - - test-golang-1.14 + - setup filters: tags: only: /^v.*/ diff --git a/Makefile b/Makefile index 847b78eff..511a5900d 100644 --- a/Makefile +++ b/Makefile @@ -2,19 +2,18 @@ CLONE_URL=github.com/pilosa/pilosa VERSION := $(shell git describe --tags 2> /dev/null || echo unknown) -VERSION_ID = $(if $(ENTERPRISE_ENABLED),enterprise-)$(VERSION)-$(GOOS)-$(GOARCH) +VARIANT = Molecula +VERSION_ID = $(VERSION)-$(GOOS)-$(GOARCH) BRANCH := $(if $(TRAVIS_BRANCH),$(TRAVIS_BRANCH),$(if $(CIRCLE_BRANCH),$(CIRCLE_BRANCH),$(shell git rev-parse --abbrev-ref HEAD))) BRANCH_ID := $(BRANCH)-$(GOOS)-$(GOARCH) BUILD_TIME := $(shell date -u +%FT%T%z) SHARD_WIDTH = 20 -LDFLAGS="-X github.com/pilosa/pilosa/v2.Version=$(VERSION) -X github.com/pilosa/pilosa/v2.BuildTime=$(BUILD_TIME) -X github.com/pilosa/pilosa/v2.Enterprise=$(if $(ENTERPRISE_ENABLED),1)" +COMMIT := $(shell git describe --exact-match >/dev/null 2>&1 || git rev-parse --short HEAD) +LDFLAGS="-X github.com/pilosa/pilosa/v2.Version=$(VERSION) -X github.com/pilosa/pilosa/v2.BuildTime=$(BUILD_TIME) -X github.com/pilosa/pilosa/v2.Variant=$(VARIANT) -X github.com/pilosa/pilosa/v2.Commit=$(COMMIT)" GO_VERSION=latest -ENTERPRISE ?= 0 -ENTERPRISE_ENABLED = $(subst 0,,$(ENTERPRISE)) RELEASE ?= 0 RELEASE_ENABLED = $(subst 0,,$(RELEASE)) NOCHECKPTR=$(shell go version | grep -q 'go1.1[4,5,6,7]' && echo \"-gcflags=all=-d=checkptr=0\" ) -BUILD_TAGS += $(if $(ENTERPRISE_ENABLED),enterprise) BUILD_TAGS += $(if $(RELEASE_ENABLED),release) BUILD_TAGS += shardwidth$(SHARD_WIDTH) BUILD_TAGS += $(foreach p,$(PLUGINS),plugin$(p)) @@ -66,8 +65,7 @@ build: # Create a single release build under the build directory release-build: $(MAKE) $(if $(DOCKER_BUILD),docker-)build FLAGS="-o build/pilosa-$(VERSION_ID)/pilosa" RELEASE=1 - cp NOTICE README.md build/pilosa-$(VERSION_ID) - $(if $(ENTERPRISE_ENABLED),cp enterprise/COPYING build/pilosa-$(VERSION_ID),cp LICENSE build/pilosa-$(VERSION_ID)) + cp NOTICE README.md LICENSE build/pilosa-$(VERSION_ID) tar -cvz -C build -f build/pilosa-$(VERSION_ID).tar.gz pilosa-$(VERSION_ID)/ @echo Created release build: build/pilosa-$(VERSION_ID).tar.gz @@ -80,11 +78,8 @@ endif # Create release build tarballs for all supported platforms. Linux compilation happens under Docker. release: check-clean $(MAKE) release-build GOOS=darwin GOARCH=amd64 - $(MAKE) release-build GOOS=darwin GOARCH=amd64 ENTERPRISE=1 $(MAKE) release-build GOOS=linux GOARCH=amd64 - $(MAKE) release-build GOOS=linux GOARCH=amd64 ENTERPRISE=1 $(MAKE) release-build GOOS=linux GOARCH=386 - $(MAKE) release-build GOOS=linux GOARCH=386 ENTERPRISE=1 # try (e.g.) internal/clustertests/docker-compose-replication2.yml @@ -146,11 +141,6 @@ docker-tag-push: vendor docker push $(DOCKER_TARGET) @echo Pushed docker image: $(DOCKER_TARGET) -# Create Docker image from Dockerfile (enterprise) -docker-enterprise: vendor - docker build --build-arg MAKE_FLAGS="ENTERPRISE=1" -t "pilosa-enterprise:$(VERSION)" . - @echo Created docker image: pilosa-enterprise:$(VERSION) - # Compile Pilosa inside Docker container docker-build: docker run --rm -v $(PWD):/go/src/$(CLONE_URL) -w /go/src/$(CLONE_URL) -e GOOS=$(GOOS) -e GOARCH=$(GOARCH) golang:$(GO_VERSION) go build -tags='$(BUILD_TAGS)' -ldflags $(LDFLAGS) $(FLAGS) $(CLONE_URL)/cmd/pilosa diff --git a/NOTICE b/NOTICE index 63c95e3c3..594272a27 100644 --- a/NOTICE +++ b/NOTICE @@ -14,27 +14,6 @@ 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. -Enterprise Edition software license -=================================== - -Files contained under the directory `enterprise` are subject to the following -license notice (Full license included in the file `COPYING`): - - Copyright (C) 2018 Pilosa Corp. All rights reserved. - - Pilosa Enterprise Edition is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Pilosa Enterprise Edition is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with Pilosa Enterprise Edition. If not, see . - Third-party software licenses ============================= diff --git a/README.md b/README.md index 3d7af147c..8057a469d 100644 --- a/README.md +++ b/README.md @@ -63,13 +63,12 @@ There are supported libraries for the following languages: - [Java](https://www.pilosa.com/docs/client-libraries/#java) - [Python](https://www.pilosa.com/docs/client-libraries/#python) -## Licenses +## License -The core Pilosa code base and all default builds (referred to as Pilosa Community Edition) are licensed completely under the Apache License, Version 2.0. -If you build Pilosa with the `enterprise` build tag (Pilosa Enterprise Edition), then that build will include features licensed under the GNU Affero General -Public License (AGPL). Enterprise code is located entirely in the [github.com/pilosa/pilosa/enterprise](https://github.com/pilosa/pilosa/tree/master/enterprise) -directory. See [github.com/pilosa/pilosa/NOTICE](https://github.com/pilosa/pilosa/blob/master/NOTICE) and -[github.com/pilosa/pilosa/LICENSE](https://github.com/pilosa/pilosa/blob/master/LICENSE) for more information about Pilosa licenses. +Pilosa is licensed under the Apache License, Version 2.0. + +A copy of the license is located in [github.com/pilosa/pilosa/LICENSE](https://github.com/pilosa/pilosa/blob/master/LICENSE). +More details about licensing are found in [github.com/pilosa/pilosa/NOTICE](https://github.com/pilosa/pilosa/blob/master/NOTICE). ## Get Support diff --git a/api.go b/api.go index 5f5b3807f..2d52676c7 100644 --- a/api.go +++ b/api.go @@ -370,7 +370,8 @@ func importWorker(importWork chan importJob) { var doClear bool switch doAction { case RequestActionOverwrite: - if err := j.field.importRoaringOverwrite(j.ctx, viewData, j.shard, viewName, j.req.Block); err != nil { + tx := &RoaringTx{Field: j.field} + if err := j.field.importRoaringOverwrite(j.ctx, tx, viewData, j.shard, viewName, j.req.Block); err != nil { return errors.Wrap(err, "importing roaring as overwrite") } case RequestActionClear: @@ -581,6 +582,9 @@ func (api *API) ExportCSV(ctx context.Context, indexName string, fieldName strin return ErrFragmentNotFound } + // Obtain transaction + tx := &RoaringTx{Index: index} + // Wrap writer with a CSV writer. cw := csv.NewWriter(w) @@ -616,7 +620,7 @@ func (api *API) ExportCSV(ctx context.Context, indexName string, fieldName strin } // Iterate over each column. - if err := f.forEachBit(fn); err != nil { + if err := f.forEachBit(tx, fn); err != nil { return errors.Wrap(err, "writing CSV") } @@ -643,7 +647,7 @@ func (api *API) ShardNodes(ctx context.Context, indexName string, shard uint64) // FragmentBlockData is an endpoint for internal usage. It is not guaranteed to // return anything useful. Currently it returns protobuf encoded row and column // ids from a "block" which is a subdivision of a fragment. -func (api *API) FragmentBlockData(ctx context.Context, body io.Reader) ([]byte, error) { +func (api *API) FragmentBlockData(ctx context.Context, body io.Reader) (_ []byte, err error) { span, _ := tracing.StartSpanFromContext(ctx, "API.FragmentBlockData") defer span.Finish() @@ -667,7 +671,10 @@ func (api *API) FragmentBlockData(ctx context.Context, body io.Reader) ([]byte, } var resp = BlockDataResponse{} - resp.RowIDs, resp.ColumnIDs = f.blockData(int(req.Block)) + resp.RowIDs, resp.ColumnIDs, err = f.blockData(int(req.Block)) + if err != nil { + return nil, err + } // Encode response. buf, err := api.Serializer.Marshal(&resp) @@ -694,8 +701,7 @@ func (api *API) FragmentBlocks(ctx context.Context, indexName, fieldName, viewNa } // Retrieve blocks. - blocks := f.Blocks() - return blocks, nil + return f.Blocks() } // FragmentData returns all data in the specified fragment. @@ -795,11 +801,30 @@ func (api *API) ClusterMessage(ctx context.Context, reqBody io.Reader) error { // Forward the message. if err := api.server.receiveMessage(msg); err != nil { - return errors.Wrap(err, "receiving message") + return MessageProcessingError{err} } return nil } +// MessageProcessingError is an error indicating that a cluster message could not be processed. +type MessageProcessingError struct { + Err error +} + +func (err MessageProcessingError) Error() string { + return "processing message: " + err.Err.Error() +} + +// Cause allows the error to be unwrapped. +func (err MessageProcessingError) Cause() error { + return err.Err +} + +// Unwrap allows the error to be unwrapped. +func (err MessageProcessingError) Unwrap() error { + return err.Err +} + // Schema returns information about each index in Pilosa including which fields // they contain. func (api *API) Schema(ctx context.Context) []*IndexInfo { @@ -1035,6 +1060,9 @@ func (api *API) Import(ctx context.Context, req *ImportRequest, opts ...ImportOp return errors.Wrap(err, "getting index and field") } + // Obtain transaction. + tx := &RoaringTx{Index: index} + if err := req.ValidateWithTimestamp(index.CreatedAt(), field.CreatedAt()); err != nil { return errors.Wrap(err, "validating import value request") } @@ -1127,14 +1155,14 @@ func (api *API) Import(ctx context.Context, req *ImportRequest, opts ...ImportOp // Import columnIDs into existence field. if !options.Clear { - if err := importExistenceColumns(index, req.ColumnIDs); err != nil { + if err := importExistenceColumns(tx, index, req.ColumnIDs); err != nil { api.server.logger.Printf("import existence error: index=%s, field=%s, shard=%d, columns=%d, err=%s", req.Index, req.Field, req.Shard, len(req.ColumnIDs), err) return errors.Wrap(err, "importing existence columns") } } // Import into fragment. - err = field.Import(req.RowIDs, req.ColumnIDs, timestamps, opts...) + err = field.Import(tx, req.RowIDs, req.ColumnIDs, timestamps, opts...) if err != nil { api.server.logger.Printf("import error: index=%s, field=%s, shard=%d, columns=%d, err=%s", req.Index, req.Field, req.Shard, len(req.ColumnIDs), err) } @@ -1159,6 +1187,9 @@ func (api *API) ImportValue(ctx context.Context, req *ImportValueRequest, opts . return errors.Wrap(err, "validating import value request") } + // Obtain transaction. + tx := &RoaringTx{Index: index} + // Set up import options. options, err := setUpImportOptions(opts...) if err != nil { @@ -1225,7 +1256,7 @@ func (api *API) ImportValue(ctx context.Context, req *ImportValueRequest, opts . } // Import columnIDs into existence field. if !options.Clear { - if err := importExistenceColumns(index, req.ColumnIDs); err != nil { + if err := importExistenceColumns(tx, index, req.ColumnIDs); err != nil { api.server.logger.Printf("import existence error: index=%s, field=%s, shard=%d, columns=%d, err=%s", req.Index, req.Field, req.Shard, len(req.ColumnIDs), err) return errors.Wrap(err, "importing existence columns") } @@ -1233,12 +1264,12 @@ func (api *API) ImportValue(ctx context.Context, req *ImportValueRequest, opts . // Import into fragment. if len(req.Values) > 0 { - err = field.importValue(req.ColumnIDs, req.Values, options) + err = field.importValue(tx, req.ColumnIDs, req.Values, options) if err != nil { api.server.logger.Printf("import error: index=%s, field=%s, shard=%d, columns=%d, err=%s", req.Index, req.Field, req.Shard, len(req.ColumnIDs), err) } } else if len(req.FloatValues) > 0 { - err = field.importFloatValue(req.ColumnIDs, req.FloatValues, options) + err = field.importFloatValue(tx, req.ColumnIDs, req.FloatValues, options) if err != nil { api.server.logger.Printf("import error: index=%s, field=%s, shard=%d, columns=%d, err=%s", req.Index, req.Field, req.Shard, len(req.ColumnIDs), err) } @@ -1323,14 +1354,14 @@ func (api *API) ImportColumnAttrs(ctx context.Context, req *ImportColumnAttrsReq return nil } -func importExistenceColumns(index *Index, columnIDs []uint64) error { +func importExistenceColumns(tx Tx, index *Index, columnIDs []uint64) error { ef := index.existenceField() if ef == nil { return nil } existenceRowIDs := make([]uint64, len(columnIDs)) - return ef.Import(existenceRowIDs, columnIDs, nil) + return ef.Import(tx, existenceRowIDs, columnIDs, nil) } // MaxShards returns the maximum shard number for each index in a map. @@ -1496,6 +1527,10 @@ func (api *API) Info() serverInfo { } } +func (api *API) Inspect(ctx context.Context, req *InspectRequest) (*HolderInfo, error) { + return api.holder.Inspect(ctx, req) +} + // GetTranslateEntryReader provides an entry reader for key translation logs starting at offset. func (api *API) GetTranslateEntryReader(ctx context.Context, offsets TranslateOffsetMap) (_ TranslateEntryReader, err error) { span, ctx := tracing.StartSpanFromContext(ctx, "API.GetTranslateEntryReader") diff --git a/api/client/grpc.go b/api/client/grpc.go index 649faacec..f36f764e4 100644 --- a/api/client/grpc.go +++ b/api/client/grpc.go @@ -174,7 +174,7 @@ func (c *GRPCClient) QueryUnary(ctx context.Context, index string, pql string) ( // Inspect returns a stream of RowResponse for the given index, columns, and filters. // It is intended to mimic something like "select [fields] from table where recordID IN (...)". -func (c *GRPCClient) Inspect(ctx context.Context, index string, columnIDs []uint64, columnKeys []string, fieldFilters []string, limit, offset uint64) (pb.StreamClient, error) { +func (c *GRPCClient) Inspect(ctx context.Context, index string, columnIDs []uint64, columnKeys []string, query string, fieldFilters []string, limit, offset uint64) (pb.StreamClient, error) { conn := c.Conn() if conn == nil { @@ -201,6 +201,7 @@ func (c *GRPCClient) Inspect(ctx context.Context, index string, columnIDs []uint FilterFields: fieldFilters, Limit: limit, Offset: offset, + Query: query, }) if err != nil { diff --git a/api_test.go b/api_test.go index 02e8a182f..3942a7337 100644 --- a/api_test.go +++ b/api_test.go @@ -361,7 +361,7 @@ func TestAPI_ImportValue(t *testing.T) { if err != nil { t.Fatalf("creating index: %v", err) } - fld, err := m1.API.CreateField(ctx, index, field, pilosa.OptFieldTypeDecimal(1)) + _, err = m1.API.CreateField(ctx, index, field, pilosa.OptFieldTypeDecimal(1)) if err != nil { t.Fatalf("creating field: %v", err) } @@ -386,66 +386,14 @@ func TestAPI_ImportValue(t *testing.T) { t.Fatal(err) } - pql := fmt.Sprintf("Row(%s>6)", field) + query := fmt.Sprintf("Row(%s>6)", field) // Query node0. - if res, err := m0.API.Query(ctx, &pilosa.QueryRequest{Index: index, Query: pql}); err != nil { + if res, err := m0.API.Query(ctx, &pilosa.QueryRequest{Index: index, Query: query}); err != nil { t.Fatal(err) } else if ids := res.Results[0].(*pilosa.Row).Columns(); !reflect.DeepEqual(ids, colIDs[6:]) { t.Fatalf("unexpected column keys: %+v", ids) } - - sum, count, err := fld.FloatSum(nil, field) - if err != nil { - t.Fatalf("getting floatsum: %v", err) - } else if sum != 0.1+1.1+2.1+3.1+4.1+5.1+6.1+7.1+8.1+9.1 { - t.Fatalf("unexpected sum: %f", sum) - } else if count != 10 { - t.Fatalf("unexpected count: %d", count) - } - - min, count, err := fld.FloatMin(nil, field) - if err != nil { - t.Fatalf("getting floatmin: %v", err) - } else if min != 0.1 { - t.Fatalf("unexpected min: %f", min) - } else if count != 1 { - t.Fatalf("unexpected count: %d", count) - } - - max, count, err := fld.FloatMax(nil, field) - if err != nil { - t.Fatalf("getting floatmax: %v", err) - } else if max != 9.1 { - t.Fatalf("unexpected max: %f", max) - } else if count != 1 { - t.Fatalf("unexpected count: %d", count) - } - - val, exists, err := fld.FloatValue(1) - if err != nil { - t.Fatalf("unepxected err getting floatvalue") - } else if !exists { - t.Fatalf("column 1 should exist") - } else if val != 1.1 { - t.Fatalf("unexpected floatvalue %f", val) - } - - changed, err := fld.SetFloatValue(11, 11.1) - if err != nil { - t.Fatalf("setting float value: %v", err) - } else if !changed { - t.Fatalf("expected change") - } - - val, exists, err = fld.FloatValue(11) - if err != nil { - t.Fatalf("getting float val: %v", err) - } else if !exists { - t.Fatalf("should exist") - } else if val != 11.1 { - t.Fatalf("unexpected val: %f", 11.1) - } }) t.Run("ValDecimalFieldNegativeScale", func(t *testing.T) { diff --git a/cache.go b/cache.go index 1c00ed6fd..ec7b3aa85 100644 --- a/cache.go +++ b/cache.go @@ -121,7 +121,8 @@ func (c *lruCache) Top() []bitmapPair { Count: n, }) } - sort.Sort(bitmapPairs(a)) + pairs := bitmapPairs(a) + sort.Sort(&pairs) return a } @@ -137,9 +138,10 @@ var _ cache = &lruCache{} // rankCache represents a cache with sorted entries. type rankCache struct { - mu sync.Mutex - entries map[uint64]uint64 - rankings []bitmapPair // cached, ordered list + mu sync.Mutex + entries map[uint64]uint64 + rankings bitmapPairs // cached, ordered list + rankingsRead bool updateN int updateTime time.Time @@ -214,12 +216,15 @@ func (c *rankCache) Len() int { func (c *rankCache) IDs() []uint64 { c.mu.Lock() defer c.mu.Unlock() - a := make([]uint64, 0, len(c.entries)) - for id := range c.entries { - a = append(a, id) + if len(c.entries) == 0 { + return nil } - sort.Sort(uint64Slice(a)) - return a + ids := make([]uint64, 0, len(c.entries)) + for id := range c.entries { + ids = append(ids, id) + } + sort.Sort(uint64Slice(ids)) + return ids } // Invalidate recalculates the entries by rank. @@ -248,18 +253,26 @@ func (c *rankCache) invalidate() { } func (c *rankCache) recalculate() { + if c.rankingsRead { + c.rankings = nil + c.rankingsRead = false + } + // Convert cache to a sorted list. - rankings := make([]bitmapPair, 0, len(c.entries)) + rankings := c.rankings[:0] + if cap(rankings) < len(c.entries) { + rankings = make([]bitmapPair, 0, len(c.entries)) + } for id, cnt := range c.entries { rankings = append(rankings, bitmapPair{ ID: id, Count: cnt, }) } - sort.Sort(bitmapPairs(rankings)) + c.rankings = rankings + sort.Sort(&c.rankings) // Store the count of the item at the threshold index. - c.rankings = rankings length := len(c.rankings) c.stats.Gauge(MetricRankCacheLength, float64(length), 1.0) @@ -290,7 +303,13 @@ func (c *rankCache) SetStats(s stats.StatsClient) { } // Top returns an ordered list of pairs. -func (c *rankCache) Top() []bitmapPair { return c.rankings } +func (c *rankCache) Top() []bitmapPair { + c.mu.Lock() + defer c.mu.Unlock() + + c.rankingsRead = true + return c.rankings +} // WriteTo writes the cache to w. func (c *rankCache) WriteTo(w io.Writer) (n int64, err error) { @@ -314,9 +333,9 @@ type bitmapPair struct { // bitmapPairs is a sortable list of BitmapPair objects. type bitmapPairs []bitmapPair -func (p bitmapPairs) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -func (p bitmapPairs) Len() int { return len(p) } -func (p bitmapPairs) Less(i, j int) bool { return p[i].Count > p[j].Count } +func (p *bitmapPairs) Swap(i, j int) { (*p)[i], (*p)[j] = (*p)[j], (*p)[i] } +func (p *bitmapPairs) Len() int { return len(*p) } +func (p *bitmapPairs) Less(i, j int) bool { return (*p)[i].Count > (*p)[j].Count } // Pair holds an id/count pair. type Pair struct { diff --git a/cluster.go b/cluster.go index eacad25f7..9695a4dd1 100644 --- a/cluster.go +++ b/cluster.go @@ -755,7 +755,7 @@ func (c *cluster) fragsByHost(idx *Index) fragsByHost { // for the given set of shards with data. func (c *cluster) fragCombos(idx string, availableShards *roaring.Bitmap, fieldViews viewsByField) fragsByHost { t := make(fragsByHost) - availableShards.ForEach(func(i uint64) { + _ = availableShards.ForEach(func(i uint64) error { nodes := c.shardNodes(idx, i) for _, n := range nodes { // for each field/view combination: @@ -765,6 +765,7 @@ func (c *cluster) fragCombos(idx string, availableShards *roaring.Bitmap, fieldV } } } + return nil }) return t } @@ -1060,7 +1061,7 @@ func (c *cluster) unprotectedOwnsPartition(nodeID string, partition int) bool { // containsShards is like OwnsShards, but it includes replicas. func (c *cluster) containsShards(index string, availableShards *roaring.Bitmap, node *Node) []uint64 { var shards []uint64 - availableShards.ForEach(func(i uint64) { + _ = availableShards.ForEach(func(i uint64) error { p := c.shardPartition(index, i) // Determine the nodes for partition. nodes := c.partitionNodes(p) @@ -1069,6 +1070,7 @@ func (c *cluster) containsShards(index string, availableShards *roaring.Bitmap, shards = append(shards, i) } } + return nil }) return shards } @@ -2036,7 +2038,9 @@ func (c *cluster) nodeJoin(node *Node) error { if c.haveTopologyAgreement() { return c.unprotectedSetStateAndBroadcast(ClusterStateNormal) } - return nil + // This lets the remote node to proceed with opening its holder, + // instead of waiting in DOWN state because cluster is in STARTING state. + return c.sendTo(node, c.unprotectedStatus()) } else if err != nil { return errors.Wrap(err, "checking if holder has data") } diff --git a/cluster_internal_test.go b/cluster_internal_test.go index b9e714326..00492d068 100644 --- a/cluster_internal_test.go +++ b/cluster_internal_test.go @@ -96,7 +96,7 @@ func newIndexWithTempPath(name string) *Index { if err != nil { panic(err) } - index, err := NewIndex(path, name, DefaultPartitionN) + index, err := NewIndex(NewHolder(DefaultPartitionN), path, name) if err != nil { panic(err) } @@ -105,7 +105,6 @@ func newIndexWithTempPath(name string) *Index { // Ensure that fragSources creates the correct fragment mapping. func TestFragSources(t *testing.T) { - uri0, err := NewURIFromAddress("host0") if err != nil { t.Fatal(err) @@ -159,23 +158,28 @@ func TestFragSources(t *testing.T) { idx := newIndexWithTempPath("i") defer idx.Close() + + // Obtain transaction. + tx := &RoaringTx{Index: idx} + defer func() { _ = tx.Rollback() }() + field, err := idx.CreateFieldIfNotExists("f", OptFieldTypeDefault()) if err != nil { t.Fatal(err) } - _, err = field.SetBit(1, 101, nil) + _, err = field.SetBit(tx, 1, 101, nil) if err != nil { t.Fatal(err) } - _, err = field.SetBit(1, ShardWidth+1, nil) + _, err = field.SetBit(tx, 1, ShardWidth+1, nil) if err != nil { t.Fatal(err) } - _, err = field.SetBit(1, ShardWidth*2+1, nil) + _, err = field.SetBit(tx, 1, ShardWidth*2+1, nil) if err != nil { t.Fatal(err) } - _, err = field.SetBit(1, ShardWidth*3+1, nil) + _, err = field.SetBit(tx, 1, ShardWidth*3+1, nil) if err != nil { t.Fatal(err) } @@ -795,7 +799,10 @@ func TestCluster_ResizeStates(t *testing.T) { node0Field := node0.holder.Field("i", "f") node0View := node0Field.view("standard") node0Fragment := node0View.Fragment(1) - node0Checksum := node0Fragment.Checksum() + node0Checksum, err := node0Fragment.Checksum() + if err != nil { + t.Fatal(err) + } // addNode needs to block until the resize process has completed. if err := tc.addNode(); err != nil { @@ -828,7 +835,9 @@ func TestCluster_ResizeStates(t *testing.T) { node1Fragment := node1View.Fragment(1) // Ensure checksums are the same. - if chksum := node1Fragment.Checksum(); !bytes.Equal(chksum, node0Checksum) { + if chksum, err := node1Fragment.Checksum(); err != nil { + t.Fatal(err) + } else if !bytes.Equal(chksum, node0Checksum) { t.Fatalf("expected standard view checksum to match: %x - %x", chksum, node0Checksum) } diff --git a/cmd/inspect.go b/cmd/convert.go similarity index 71% rename from cmd/inspect.go rename to cmd/convert.go index 4a2e852f6..86452905d 100644 --- a/cmd/inspect.go +++ b/cmd/convert.go @@ -45,5 +45,12 @@ Inspects a data file and provides stats. return inspector.Run(context.Background()) }, } + flags := inspectCmd.Flags() + flags.BoolVarP(&inspector.Quiet, "quiet", "q", false, "don't list details of containers") + flags.IntVarP(&inspector.Max, "max", "n", 0, "list at most max items (0 = unlimited)") + flags.StringVarP(&inspector.InspectOpts.Indexes, "index", "i", "", "filter indexes") + flags.StringVarP(&inspector.InspectOpts.Views, "view", "v", "", "filter views") + flags.StringVarP(&inspector.InspectOpts.Fields, "field", "f", "", "filter fields") + flags.StringVarP(&inspector.InspectOpts.Shards, "shard", "s", "", "filter shards") return inspectCmd } diff --git a/cmd/convert/main.go b/cmd/convert/main.go new file mode 100644 index 000000000..5be45bb58 --- /dev/null +++ b/cmd/convert/main.go @@ -0,0 +1,44 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 main + +import ( + "log" + "os" + + "github.com/pilosa/pilosa/v2" + "github.com/pilosa/pilosa/v2/rbf" +) + +func main() { + + if len(os.Args) != 3 { + log.Fatal("USAGE convert srcPath destPath") + + } + holder := pilosa.NewHolder(256) + holder.Path = os.Args[1] + err := holder.Open() + + if err != nil { + log.Fatal(err) + + } + c := &pilosa.RBFConverter{ + Dbs: make(map[string]*rbf.DB), + Base: os.Args[2], + } + holder.ConvertToRBF(c) +} diff --git a/cmd/root.go b/cmd/root.go index 228d3ed29..e3c25ef50 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -26,10 +26,6 @@ import ( ) func NewRootCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command { - productName := "Pilosa " + pilosa.Version - if pilosa.EnterpriseEnabled { - productName = "Pilosa Enterprise " + pilosa.Version - } rc := &cobra.Command{ Use: "pilosa", // TODO: These short/long descriptions could use some updating. @@ -41,8 +37,7 @@ tools for administering Pilosa, importing/exporting data, backing up, and more. Complete documentation is available at https://www.pilosa.com/docs/. -` + productName + ` -Build Time: ` + pilosa.BuildTime + "\n", +` + pilosa.VersionInfo() + "\n", PersistentPreRunE: func(cmd *cobra.Command, args []string) error { v := viper.New() err := setAllConfig(v, cmd.Flags(), "PILOSA") diff --git a/ctl/inspect.go b/ctl/inspect.go index 48924b89d..eb24a0597 100644 --- a/ctl/inspect.go +++ b/ctl/inspect.go @@ -16,15 +16,23 @@ package ctl import ( "context" + "encoding/binary" "fmt" + "hash/fnv" "io" + "io/ioutil" "os" + "path/filepath" + "sort" + "strconv" + "strings" "syscall" "text/tabwriter" "time" - "unsafe" + "github.com/gogo/protobuf/proto" "github.com/pilosa/pilosa/v2" + "github.com/pilosa/pilosa/v2/internal" "github.com/pilosa/pilosa/v2/roaring" "github.com/pkg/errors" ) @@ -33,6 +41,12 @@ import ( type InspectCommand struct { // Path to data file Path string + // don't list details of objects + Quiet bool + // list only this many objects + Max int + // Filters: + InspectOpts pilosa.InspectRequest // Standard input/output *pilosa.CmdIO @@ -45,8 +59,119 @@ func NewInspectCommand(stdin io.Reader, stdout, stderr io.Writer) *InspectComman } } +type pointerContext struct { + from, to uintptr +} + +func (p *pointerContext) pretty(c roaring.ContainerInfo) string { + var pointer string + if c.Mapped { + if c.Pointer >= p.from && c.Pointer < p.to { + pointer = fmt.Sprintf("@+0x%x", c.Pointer-p.from) + } else { + pointer = fmt.Sprintf("!0x%x!", c.Pointer) + } + } else { + pointer = fmt.Sprintf("0x%x", c.Pointer) + } + return fmt.Sprintf("%s \t%d \t%d \t%s ", c.Type, c.N, c.Alloc, pointer) +} + +func (cmd *InspectCommand) PrintOps(info roaring.BitmapInfo) { + fmt.Fprintln(cmd.Stdout, " Ops:") + tw := tabwriter.NewWriter(cmd.Stdout, 0, 8, 0, '\t', 0) + fmt.Fprintf(tw, " \t%s\t%s\t%s\t\n", "TYPE", "OpN", "SIZE") + printed := 0 + for _, op := range info.OpDetails { + fmt.Fprintf(tw, "\t%s\t%d\t%d\t\n", op.Type, op.OpN, op.Size) + printed++ + if cmd.Max != 0 && printed >= cmd.Max { + break + } + } + tw.Flush() +} + +func (cmd *InspectCommand) PrintContainers(info roaring.BitmapInfo, pC pointerContext) { + fmt.Fprintln(cmd.Stdout, " Containers:") + tw := tabwriter.NewWriter(cmd.Stdout, 0, 8, 0, '\t', 0) + fmt.Fprintf(tw, " \t\tRoaring\t\t\t\tOps\t\t\t\tFlags\t\n") + fmt.Fprintf(tw, "\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n", "KEY", "TYPE", "N", "ALLOC", "OFFSET", "TYPE", "N", "ALLOC", "OFFSET", "FLAGS") + c1s := info.Containers + c2s := info.OpContainers + l1 := len(c1s) + l2 := len(c2s) + i1 := 0 + i2 := 0 + var c1, c2 roaring.ContainerInfo + c1.Key = ^uint64(0) + c2.Key = ^uint64(0) + c1e := false + c2e := false + if i1 < l1 { + c1 = c1s[i1] + i1++ + c1e = true + } + if i2 < l2 { + c2 = c2s[i2] + i2++ + c2e = true + } + printed := 0 + for c1e || c2e { + c1used := false + c2used := false + var key uint64 + c1fmt := "-\t\t\t" + c2fmt := "-\t\t\t" + // If c2 exists, we'll always prefer its flags, + // if it doesn't, this gets overwritten. + flags := c2.Flags + if !c2e || (c1e && c1.Key < c2.Key) { + c1fmt = pC.pretty(c1) + key = c1.Key + c1used = true + flags = c1.Flags + } else if !c1e || (c2e && c2.Key < c1.Key) { + c2fmt = pC.pretty(c2) + key = c2.Key + c2used = true + } else { + // c1e and c2e both set, and neither key is < the other. + c1fmt = pC.pretty(c1) + c2fmt = pC.pretty(c2) + key = c1.Key + c1used = true + c2used = true + } + if c1used { + if i1 < l1 { + c1 = c1s[i1] + i1++ + } else { + c1e = false + } + } + if c2used { + if i2 < l2 { + c2 = c2s[i2] + i2++ + } else { + c2e = false + } + } + fmt.Fprintf(tw, "\t%d\t%s\t%s\t%s\t\n", key, c1fmt, c2fmt, flags) + printed++ + if cmd.Max > 0 && printed >= cmd.Max { + break + } + } + tw.Flush() +} + // Run executes the inspect command. -func (cmd *InspectCommand) Run(_ context.Context) error { +func (cmd *InspectCommand) Run(ctx context.Context) error { // Open file handle. f, err := os.Open(cmd.Path) if err != nil { @@ -58,7 +183,173 @@ func (cmd *InspectCommand) Run(_ context.Context) error { if err != nil { return errors.Wrap(err, "statting file") } + if fi.IsDir() { + total := 0 + infos, err := f.Readdir(0) + if err != nil { + return err + } + if len(infos) == 0 { + return errors.New("directory contains no files") + } + names := make([]string, len(infos)) + nameToInfo := make(map[string]os.FileInfo, len(infos)) + // find numeric-only names; we'll operate on + // either those, or the whole holder if we find + // a .topology file. + n := 0 + for _, fi := range infos { + name := fi.Name() + if name == ".topology" { + return cmd.InspectHolder(ctx, cmd.Path) + } + if _, err := strconv.Atoi(name); err == nil { + names[n] = name + nameToInfo[name] = fi + n++ + } + } + if n == 0 { + return fmt.Errorf("directory contains no fragments (looking for numeric names)") + } + names = names[:n] + fmt.Fprintf(cmd.Stdout, "%s contains %d fragments:\n", cmd.Path, n) + for _, name := range names { + f2, err := os.Open(filepath.Join(cmd.Path, name)) + if err != nil { + return fmt.Errorf("opening %q: %v", name, err) + } + fmt.Fprintf(cmd.Stdout, "%s/%s:\n", cmd.Path, name) + err = cmd.InspectFile(f2, nameToInfo[name]) + total++ + f2.Close() + if err != nil { + return fmt.Errorf("inspecting %q: %v", name, err) + } + } + return nil + } + return cmd.InspectFile(f, fi) +} + +// loadTopology is copied almost exactly from pilosa/cluster.go. +func loadTopology(path string) (topology internal.Topology, myID string, err error) { + buf, err := ioutil.ReadFile(filepath.Join(path, ".topology")) + if os.IsNotExist(err) { + return topology, myID, err + } else if err != nil { + return topology, myID, errors.Wrap(err, "reading file") + } + if err := proto.Unmarshal(buf, &topology); err != nil { + return topology, myID, errors.Wrap(err, "unmarshalling") + } + sort.Slice(topology.NodeIDs, + func(i, j int) bool { + return topology.NodeIDs[i] < topology.NodeIDs[j] + }) + buf, err = ioutil.ReadFile(filepath.Join(path, ".id")) + if os.IsNotExist(err) { + return topology, myID, err + } else if err != nil { + return topology, myID, nil + } + myID = strings.TrimSpace(string(buf)) + return topology, myID, nil +} + +var partitions = make(map[string]map[uint64]int) + +func findPartition(index string, shard uint64, partitionN int) (partition int) { + var shardMap map[uint64]int + var ok bool + if shardMap, ok = partitions[index]; !ok { + shardMap = make(map[uint64]int) + partitions[index] = shardMap + } + if partition, ok = shardMap[shard]; !ok { + var buf [8]byte + binary.BigEndian.PutUint64(buf[:], shard) + + // Hash the bytes and mod by partition count. + h := fnv.New64a() + _, _ = h.Write([]byte(index)) + _, _ = h.Write(buf[:]) + partition = int(h.Sum64() % uint64(partitionN)) + shardMap[shard] = partition + } + return partition +} + +func findPartitionPath(path string, partitionN int) (int, error) { + parts := strings.Split(path, "/") + shard, err := strconv.ParseUint(parts[len(parts)-1], 10, 64) + if err != nil { + return 0, err + } + return findPartition(parts[0], shard, partitionN), nil +} + +func (cmd *InspectCommand) InspectHolder(ctx context.Context, path string) error { + holder := pilosa.NewHolder(pilosa.DefaultPartitionN) + holder.Path = path + holder.Opts.Inspect = true + holder.Opts.ReadOnly = true + err := holder.Open() + if err != nil { + return fmt.Errorf("%s: holder open: %v", path, err) + } + holderInfo, err := holder.Inspect(ctx, &cmd.InspectOpts) + if err != nil { + return fmt.Errorf("%s: inspect: %v", path, err) + } + myPartition := 0 + topology, myID, err := loadTopology(path) + if err == nil { + fmt.Fprintf(cmd.Stdout, "Cluster ID: %q\n", topology.ClusterID) + if len(topology.NodeIDs) > 1 { + fmt.Fprintf(cmd.Stdout, "Cluster of %d nodes, this node %q\n", len(topology.NodeIDs), myID) + } else { + fmt.Fprintf(cmd.Stdout, "Cluster has only one node: %q\n", myID) + } + found := false + for i := range topology.NodeIDs { + if topology.NodeIDs[i] == myID { + found = true + myPartition = i + break + } + } + if !found { + fmt.Fprintf(cmd.Stdout, "Warning: node ID %q not found in topology (%q)\n", myID, topology.NodeIDs) + } + } else { + fmt.Fprintf(cmd.Stdout, "warning: reading topology failed: %v\n", err) + } + for _, name := range holderInfo.FragmentNames { + partition, err := findPartitionPath(name, len(topology.NodeIDs)) + if err != nil { + fmt.Fprintf(cmd.Stdout, "%s: [can't find partition: %v]\n", name, err) + } else { + if partition == myPartition { + fmt.Fprintf(cmd.Stdout, "%s:\n", name) + } else { + fmt.Fprintf(cmd.Stdout, "%s: [primary node %q]\n", name, topology.NodeIDs[partition]) + } + } + details := holderInfo.FragmentInfo[name] + cmd.DisplayInfo(details.BitmapInfo) + if details.BlockChecksums != nil { + fmt.Fprintf(cmd.Stdout, " Checksums [%d total]:\n", len(details.BlockChecksums)) + for _, block := range details.BlockChecksums { + fmt.Fprintf(cmd.Stdout, " %8d: %x\n", block.ID, block.Checksum) + } + } + } + return nil +} + +func (cmd *InspectCommand) InspectFile(f *os.File, fi os.FileInfo) error { // Memory map the file. data, err := syscall.Mmap(int(f.Fd()), 0, int(fi.Size()), syscall.PROT_READ, syscall.MAP_SHARED) if err != nil { @@ -72,39 +363,37 @@ func (cmd *InspectCommand) Run(_ context.Context) error { }() // Attach the mmap file to the bitmap. t := time.Now() - fmt.Fprintf(cmd.Stderr, "unmarshalling bitmap...") - bm := roaring.NewBitmap() - if err := bm.UnmarshalBinary(data); err != nil { - return errors.Wrap(err, "unmarshalling") + fmt.Fprintf(cmd.Stderr, "inspecting bitmap...") + var info roaring.BitmapInfo + _, _, err = roaring.InspectBinary(data, true, &info) + fmt.Fprintf(cmd.Stderr, " (%s)\n", time.Since(t)) + cmd.DisplayInfo(info) + if err != nil { + return errors.Wrap(err, "inspecting") } - fmt.Fprintf(cmd.Stderr, " (%s)\n", time.Since(t)) + return nil +} - // Retrieve stats. - t = time.Now() - fmt.Fprintf(cmd.Stderr, "calculating stats...") - info := bm.Info() - fmt.Fprintf(cmd.Stderr, " (%s)\n", time.Since(t)) +func (cmd *InspectCommand) DisplayInfo(info roaring.BitmapInfo) { + pC := pointerContext{ + from: info.From, + to: info.To, + } // Print top-level info. - fmt.Fprintf(cmd.Stdout, "== Bitmap Info ==\n") - fmt.Fprintf(cmd.Stdout, "Containers: %d\n", len(info.Containers)) - fmt.Fprintf(cmd.Stdout, "Operations: %d\n", info.OpN) + fmt.Fprintf(cmd.Stdout, " Bitmap Info:\n") + fmt.Fprintf(cmd.Stdout, " Bits: %d\n", info.BitCount) + fmt.Fprintf(cmd.Stdout, " Containers: %d (%d roaring)\n", info.ContainerCount, len(info.Containers)) + fmt.Fprintf(cmd.Stdout, " Operations: %d (%d bits)\n", info.Ops, info.OpN) fmt.Fprintln(cmd.Stdout, "") // Print info for each container. - fmt.Fprintln(cmd.Stdout, "== Containers ==") - tw := tabwriter.NewWriter(cmd.Stdout, 0, 8, 0, '\t', 0) - fmt.Fprintf(tw, "%s\t%s\t% 8s \t% 8s\t%s\n", "KEY", "TYPE", "N", "ALLOC", "OFFSET") - for _, ci := range info.Containers { - fmt.Fprintf(tw, "%d\t%s\t% 8d \t% 8d \t0x%08x\n", - ci.Key, - ci.Type, - ci.N, - ci.Alloc, - uintptr(ci.Pointer)-uintptr(unsafe.Pointer(&data[0])), - ) + if !cmd.Quiet { + if info.ContainerCount > 0 { + cmd.PrintContainers(info, pC) + } + if info.Ops > 0 { + cmd.PrintOps(info) + } } - tw.Flush() - - return nil } diff --git a/ctl/inspect_test.go b/ctl/inspect_test.go index 1ff852712..2698dcc03 100644 --- a/ctl/inspect_test.go +++ b/ctl/inspect_test.go @@ -41,7 +41,7 @@ func TestInspectCommand_Run(t *testing.T) { file.Close() cm.Path = file.Name() err = cm.Run(context.Background()) - expectedError := "unmarshalling: " + expectedError := "inspecting: " if !strings.Contains(err.Error(), expectedError) { t.Fatalf("expected error '%s', got '%v'", expectedError, err) } @@ -52,7 +52,7 @@ func TestInspectCommand_Run(t *testing.T) { if err != nil { t.Fatalf("copying data: %v", err) } - if !strings.Contains(buf.String(), "unmarshalling bitmap...") { + if !strings.Contains(buf.String(), "inspecting bitmap...") { t.Fatalf("Inspect doesn't work: %s", err) } diff --git a/ctl/server.go b/ctl/server.go index 14a262470..8aa0edeb9 100644 --- a/ctl/server.go +++ b/ctl/server.go @@ -28,6 +28,7 @@ func BuildServerFlags(cmd *cobra.Command, srv *server.Command) { flags.StringVarP(&srv.Config.Bind, "bind", "b", srv.Config.Bind, "Default URI on which pilosa should listen.") flags.StringVar(&srv.Config.BindGRPC, "bind-grpc", srv.Config.BindGRPC, "URI on which pilosa should listen for gRPC requests.") flags.StringVar(&srv.Config.Advertise, "advertise", srv.Config.Advertise, "Address to advertise externally.") + flags.StringVar(&srv.Config.AdvertiseGRPC, "advertise-grpc", srv.Config.AdvertiseGRPC, "Address to advertise externally for gRPC.") flags.IntVarP(&srv.Config.MaxWritesPerRequest, "max-writes-per-request", "", srv.Config.MaxWritesPerRequest, "Number of write commands per request.") flags.StringVar(&srv.Config.LogPath, "log-path", srv.Config.LogPath, "Log path") flags.BoolVar(&srv.Config.Verbose, "verbose", srv.Config.Verbose, "Enable verbose logging") diff --git a/docs/configuration.md b/docs/configuration.md index 7b50aba33..57133e666 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -302,7 +302,7 @@ The config file is in the [toml format](https://github.com/toml-lang/toml) and h ```toml [metric] - service = “statsd” + service = "statsd" ``` #### Metric Host @@ -319,7 +319,7 @@ The config file is in the [toml format](https://github.com/toml-lang/toml) and h #### Metric Poll Interval * Description: Rate at which runtime metrics (such as open file handles and memory usage) are collected. -* Flag: `metric.poll-interval=”0m15s”` +* Flag: `metric.poll-interval="0m15s"` * Env: `PILOSA_METRIC_POLL_INTERVAL=0m15s` * Config: diff --git a/docs/examples.md b/docs/examples.md index c7476a722..eae05ab76 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -81,7 +81,7 @@ lfm := pdk.LinearFloatMapper{ } ``` -`Min` and `Max` define the linear function, and `Res` determines the maximum allowed value for the output row ID - we chose these values to produce a “round to nearest integer” behavior. Other predefined mappers have their own specific parameters, usually two or three. +`Min` and `Max` define the linear function, and `Res` determines the maximum allowed value for the output row ID - we chose these values to produce a "round to nearest integer" behavior. Other predefined mappers have their own specific parameters, usually two or three. This mapper function is the core operation, but we need a few other pieces to define the overall process, which is encapsulated in the ColumnMapper object. This object defines which field(s) of the input data source to use (`Fields`), how to parse them (`Parsers`), what mapping to use (`Mapper`), and the name of the field to use (`Field`). ```go diff --git a/docs/query-language.md b/docs/query-language.md index 527cad445..310a4116c 100644 --- a/docs/query-language.md +++ b/docs/query-language.md @@ -52,6 +52,7 @@ curl localhost:10101/index/repository/query \ * `CALL` Any query. * `ROW_CALL` Any query which returns a row, such as `Row`, `Union`, `Difference`, `Xor`, `Intersect`, `Not`. * `ROWS_CALL` A query that returns a `Rows` result (i.e. a list of row IDs). Currently only the `Rows` query. +* `ROWSET_CALL` A query that returns a set of rows. Currently only the `Rows` and `TopN` queries. * `[]ATTR_VALUE` Denotes an array of `ATTR_VALUE`s. (e.g. `["a", "b", "c"]`). ### Write Operations @@ -595,34 +596,6 @@ Count(Row(stargazer=1)) * Result is the number of repositories that user 1 has starred. -#### Shift -**Spec:** - -``` -Shift(, [n=UINT]) -``` - -**Description:** - -Returns the row specified by `ROW_CALL` shifted by `n` bits. - -**Result Type:** object with attrs and columns - -attrs will always be empty - -**Examples:** - -Query all columns with a bit set in row 1 of the field `stargazer` -and shift the result by 2: -```request -Shift(Row(stargazer=1), n=2) -``` -```response -{"attrs":{},"columns":[12, 22]} -``` - -* columns are the repositories which user 1 has starred shifted by 2 bits. - #### TopN **Spec:** @@ -643,9 +616,15 @@ have the attribute specified by `attrName` with one of the values specified in **Caveats:** -* Performing a TopN() query on a field with cache type ranked will return the top rows sorted by count in descending order. -* Fields with cache type lru will maintain an LRU (Least Recently Used replacement policy) cache, thus a TopN query on this type of field will return rows sorted in order of most recently set bit. -* The field's cache size determines the number of sorted rows to maintain in the cache for purposes of TopN queries. There is a tradeoff between performance and accuracy; increasing the cache size will improve accuracy of results at the cost of performance. +In general, the order of the resulting row keys is not guaranteed to reflect the true order of bit counts across an index. The exact solution to the problem of computing the TopN counts is prohibitively expensive, so TopN is instead implemented as a heuristic. This provides a significant performance improvement, at the cost of uncertainty in the result order. + +The implementation is based on a per-shard cache. The accuracy of the results depends on how well the counts for the overall index are reflected in the individual shards (so TopN queries on a single-shard index are exact). If the distribution of bits across shards is uniform, shard counts are representative. This is often a reasonable assumption, especially for the top results for large data sets, in which counts might follow Zipfian, exponential, or other long-tail distributions. However, this assumption may not hold for some applications. + +Additional implementation details: + +* The field's cache size determines the number of sorted rows to maintain in the cache for purposes of TopN queries. There is a tradeoff between performance and accuracy; increasing the cache size will improve accuracy of results at the cost of performance. Note that this per-shard tradeoff is independent of the per-index performance/accuracy tradeoff mentioned above. +* Fields with cache type `ranked` will return the top rows sorted by count in descending order. +* Fields with cache type `lru` will maintain an LRU (Least Recently Used replacement policy) cache, thus a TopN query on this type of field will return rows sorted in order of most recently set bit. * Once full, the cache will truncate the set of rows according to the field option CacheSize. Rows that straddle the limit and have the same count will be truncated in no particular order. * The TopN query's attribute filter is applied to the existing sorted cache of rows. Rows that fall outside of the sorted cache range, even if they would normally pass the filter, are ignored. @@ -818,7 +797,7 @@ Options(Row(f1=10), shards=[0, 2]) **Spec:** ``` -Rows(, previous=, limit=, column=, from=, to=) +Rows(, previous=, limit=, column=, from=, to=, like=) ``` **Description:** @@ -839,6 +818,10 @@ If the field is of type `time`, the `from` and `to` arguments can be provided to restrict the result to a specific time span. If `from` and `to` are not provided, the full range of existing data will be queried. +If `like` is given, only keys matching a pattern will be selected. +A `like` pattern may use `_` as a placeholder to match a single UTF-8 codepoint, and `%` to match 0 or more codepoints. +All other characters will be matched exactly. + **Result Type:** Object with `"rows" or "keys" and an array of integers or strings respectively.` **Examples:** @@ -856,7 +839,15 @@ With keys: Rows(job) ``` ```response -{"rows":null,"keys":["engineer","management","student""]} +{"rows":null,"keys":["engineer","management","student"]} +``` + +With `like`: +```request +Rows(job, like="%t") +``` +```response +{"rows":null,"keys":["management","student"]} ``` #### Group By @@ -945,3 +936,31 @@ GroupBy(Rows(age), Rows(job), limit=7, filter=Row(country=USA)) {"group":[{"field":"age","rowID":22},{"field":"job","rowKey":"student"}],"count":3}, {"group":[{"field":"age","rowID":29},{"field":"job","rowKey":"management"}],"count":7}] ``` + +#### UnionRows + +**Spec:** + +``` +UnionRows([ROWSET_CALL ...]) +``` + +**Description:** + +UnionRows performs a logical OR on the rows matched by the results of all `ROWSET_CALL` queries passed to it. + +**Result Type:** object with attrs and bits + +attrs will always be empty + +**Examples:** + +Query columns with a bit set in any row (repositories that are starred by any user): +```request +UnionRows(Rows(stargazer)) +``` +```response +{"attrs":{},"columns":[10, 20, 30]} +``` + +* columns are repositories that were starred by any user \ No newline at end of file diff --git a/enterprise/COPYING b/enterprise/COPYING deleted file mode 100644 index be3f7b28e..000000000 --- a/enterprise/COPYING +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. diff --git a/enterprise/enterprise.go b/enterprise/enterprise.go deleted file mode 100644 index f3a897551..000000000 --- a/enterprise/enterprise.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2018 Pilosa Corp. All rights reserved. -// -// This file is part of Pilosa Enterprise Edition. -// -// Pilosa Enterprise Edition is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Pilosa Enterprise Edition is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with Pilosa Enterprise Edition. If not, see . - -// Package enterprise is now deprecated, and the functionality under -// enterprise/b has been copied into roaring/. It existed to inject enterprise -// implementations of various Pilosa features when Pilosa was built with -// "ENTERPRISE=1 make install". These features were dual-licensed separately -// from Pilosa community edition under the AGPL and Pilosa's commercial license. -package enterprise diff --git a/executor.go b/executor.go index f2dd49fcb..42abe099c 100644 --- a/executor.go +++ b/executor.go @@ -209,7 +209,15 @@ func (e *executor) Execute(ctx context.Context, index string, q *pql.Query, shar return resp, fmt.Errorf("profiling execution failed: %T is not tracing.Profile", prof) } } - results, err := e.execute(ctx, index, q, shards, opt) + + // TODO: Determine if query is read-only. + tx, err := e.Holder.Begin(true) + if err != nil { + return resp, err + } + defer func() { _ = tx.Rollback() }() + + results, err := e.execute(ctx, tx, index, q, shards, opt) if err != nil { return resp, err } else if err := validateQueryContext(ctx); err != nil { @@ -266,6 +274,11 @@ func (e *executor) Execute(ctx context.Context, index string, q *pql.Query, shar } } + // Commit transaction. + if err := tx.Commit(); err != nil { + return resp, err + } + return resp, nil } @@ -294,7 +307,7 @@ func (e *executor) readColumnAttrSets(index *Index, ids []uint64) ([]*ColumnAttr // handlePreCalls traverses the call tree looking for calls that need // precomputed values. Right now, that's just Distinct. -func (e *executor) handlePreCalls(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) error { +func (e *executor) handlePreCalls(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) error { if c.Name == "Precomputed" { idx := c.Args["valueidx"].(int64) if idx >= 0 && idx < int64(len(opt.EmbeddedData)) { @@ -329,7 +342,7 @@ func (e *executor) handlePreCalls(ctx context.Context, index string, c *pql.Call // like Distinct, where you can't predict output shard for a result // from the shard being queried. if newIndex != "" && newIndex != index { - if err := e.handlePreCallChildren(ctx, index, c, shards, opt); err != nil { + if err := e.handlePreCallChildren(ctx, tx, index, c, shards, opt); err != nil { return err } @@ -340,7 +353,7 @@ func (e *executor) handlePreCalls(ctx context.Context, index string, c *pql.Call } if c.Type == pql.PrecallNone { // otherwise, handle the children - return e.handlePreCallChildren(ctx, index, c, shards, opt) + return e.handlePreCallChildren(ctx, tx, index, c, shards, opt) } // We don't try to handle sub-calls from here. I'm not 100% // sure that's right, but I think the fact that they're happening @@ -351,7 +364,7 @@ func (e *executor) handlePreCalls(ctx context.Context, index string, c *pql.Call // We set c to look like a normal call, and actually execute it: c.Type = pql.PrecallNone // possibly override call index. - v, err := e.executeCall(ctx, index, c, shards, opt) + v, err := e.executeCall(ctx, tx, index, c, shards, opt) if err != nil { return err } @@ -381,13 +394,23 @@ func (e *executor) handlePreCalls(ctx context.Context, index string, c *pql.Call return nil } +// dumpPrecomputedCalls throws away precomputed call data. this is used so we +// can drop any large data associated with a call once we've processed +// the call. +func (e *executor) dumpPrecomputedCalls(ctx context.Context, c *pql.Call) { + for _, call := range c.Children { + e.dumpPrecomputedCalls(ctx, call) + } + c.Precomputed = nil +} + // handlePreCallChildren handles any pre-calls in the children of a given call. -func (e *executor) handlePreCallChildren(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) error { +func (e *executor) handlePreCallChildren(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) error { for i := range c.Children { if err := ctx.Err(); err != nil { return err } - if err := e.handlePreCalls(ctx, index, c.Children[i], shards, opt); err != nil { + if err := e.handlePreCalls(ctx, tx, index, c.Children[i], shards, opt); err != nil { return err } } @@ -397,7 +420,7 @@ func (e *executor) handlePreCallChildren(ctx context.Context, index string, c *p if err := ctx.Err(); err != nil { return err } - if err := e.handlePreCalls(ctx, index, call, shards, opt); err != nil { + if err := e.handlePreCalls(ctx, tx, index, call, shards, opt); err != nil { return err } } @@ -405,7 +428,7 @@ func (e *executor) handlePreCallChildren(ctx context.Context, index string, c *p return nil } -func (e *executor) execute(ctx context.Context, index string, q *pql.Query, shards []uint64, opt *execOptions) ([]interface{}, error) { +func (e *executor) execute(ctx context.Context, tx Tx, index string, q *pql.Query, shards []uint64, opt *execOptions) ([]interface{}, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.execute") defer span.Finish() @@ -428,12 +451,12 @@ func (e *executor) execute(ctx context.Context, index string, q *pql.Query, shar // Optimize handling for bulk attribute insertion. if hasOnlySetRowAttrs(q.Calls) { - return e.executeBulkSetRowAttrs(ctx, index, q.Calls, opt) + return e.executeBulkSetRowAttrs(ctx, tx, index, q.Calls, opt) } // Execute each call serially. results := make([]interface{}, 0, len(q.Calls)) - for _, call := range q.Calls { + for i, call := range q.Calls { if err := validateQueryContext(ctx); err != nil { return nil, err } @@ -444,7 +467,7 @@ func (e *executor) execute(ctx context.Context, index string, q *pql.Query, shar // about the positive values, because only positive values // are valid column IDs. So we don't actually eat top-level // pre calls. - err := e.handlePreCallChildren(ctx, index, call, shards, opt) + err := e.handlePreCallChildren(ctx, tx, index, call, shards, opt) if err != nil { return nil, err } @@ -455,20 +478,130 @@ func (e *executor) execute(ctx context.Context, index string, q *pql.Query, shar // already precomputed by handlePreCallChildren, though, // we don't need this logic in executeCall. if newIndex := call.CallIndex(); newIndex != "" && newIndex != index { - v, err = e.executeCall(ctx, newIndex, call, nil, opt) + v, err = e.executeCall(ctx, tx, newIndex, call, nil, opt) } else { - v, err = e.executeCall(ctx, index, call, shards, opt) + v, err = e.executeCall(ctx, tx, index, call, shards, opt) } if err != nil { return nil, err } results = append(results, v) + // Some Calls can have significant data associated with them + // that gets generated during processing, such as Precomputed + // values. Dumping the precomputed data, if any, lets the GC + // free the memory before we get there. + e.dumpPrecomputedCalls(ctx, q.Calls[i]) } return results, nil } +// preprocessQuery expands any calls that need preprocessing. +// So far, this only needs to process UnionRows. +func (e *executor) preprocessQuery(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (*pql.Call, error) { + switch c.Name { + case "UnionRows": + // Turn UnionRows(Rows(...)) into Union(Row(...), ...). + var rows []*pql.Call + for _, child := range c.Children { + // Check that we can use the call. + switch child.Name { + case "Rows": + case "TopN": + default: + return nil, errors.Errorf("cannot use %v as a rows query", child) + } + + // Execute the call. + rowsResult, err := e.executeCall(ctx, tx, index, child, shards, opt) + if err != nil { + return nil, err + } + + // Turn the results into rows calls. + var resultRows []*pql.Call + switch rowsResult := rowsResult.(type) { + case *PairsField: + // Translate pairs into rows calls. + for _, p := range rowsResult.Pairs { + var val interface{} + switch { + case p.Key != "": + val = p.Key + default: + val = p.ID + } + resultRows = append(resultRows, &pql.Call{ + Name: "Row", + Args: map[string]interface{}{ + rowsResult.Field: val, + }, + }) + } + case RowIDs: + // Translate Row IDs into Row calls. + for _, id := range rowsResult { + resultRows = append(resultRows, &pql.Call{ + Name: "Row", + Args: map[string]interface{}{ + child.Args["_field"].(string): id, + }, + }) + } + default: + return nil, errors.Errorf("unexpected Rows type %T", rowsResult) + } + + // Propogate any special properties of the call. + switch child.Name { + case "Rows": + // Propogate "from" time, if set. + if v, ok := child.Args["from"]; ok { + for _, rowCall := range resultRows { + rowCall.Args["from"] = v + } + } + + // Propogate "to" time, if set. + if v, ok := child.Args["to"]; ok { + for _, rowCall := range resultRows { + rowCall.Args["to"] = v + } + } + } + + rows = append(rows, resultRows...) + } + + // Generate a Union call over the rows. + return &pql.Call{ + Name: "Union", + Children: rows, + }, nil + + default: + // Recurse through child calls. + out := make([]*pql.Call, len(c.Children)) + var changed bool + for i, child := range c.Children { + res, err := e.preprocessQuery(ctx, tx, index, child, shards, opt) + if err != nil { + return nil, err + } + if res != child { + changed = true + } + out[i] = res + } + if changed { + c = c.Clone() + c.Children = out + } + return c, nil + } +} + // executeCall executes a call. -func (e *executor) executeCall(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (interface{}, error) { +func (e *executor) executeCall(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (interface{}, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeCall") defer span.Finish() @@ -506,77 +639,83 @@ func (e *executor) executeCall(ctx context.Context, index string, c *pql.Call, s } } + // Preprocess the query. + c, err := e.preprocessQuery(ctx, tx, index, c, shards, opt) + if err != nil { + return nil, err + } + // Special handling for mutation and top-n calls. if op, ok := e.additionalCountOps[c.Name]; ok { statFn() - return e.executeGenericCount(ctx, index, c, op, shards, opt) + return e.executeGenericCount(ctx, tx, index, c, op, shards, opt) } if op, ok := e.additionalFieldOps[c.Name]; ok { statFn() - return e.executeGenericField(ctx, index, c, op, shards, opt) + return e.executeGenericField(ctx, tx, index, c, op, shards, opt) } switch c.Name { case "Sum": statFn() - return e.executeSum(ctx, index, c, shards, opt) + return e.executeSum(ctx, tx, index, c, shards, opt) case "Min": statFn() - return e.executeMin(ctx, index, c, shards, opt) + return e.executeMin(ctx, tx, index, c, shards, opt) case "Max": statFn() - return e.executeMax(ctx, index, c, shards, opt) + return e.executeMax(ctx, tx, index, c, shards, opt) case "MinRow": statFn() - return e.executeMinRow(ctx, index, c, shards, opt) + return e.executeMinRow(ctx, tx, index, c, shards, opt) case "MaxRow": statFn() - return e.executeMaxRow(ctx, index, c, shards, opt) + return e.executeMaxRow(ctx, tx, index, c, shards, opt) case "Clear": statFn() - return e.executeClearBit(ctx, index, c, opt) + return e.executeClearBit(ctx, tx, index, c, opt) case "ClearRow": statFn() - return e.executeClearRow(ctx, index, c, shards, opt) + return e.executeClearRow(ctx, tx, index, c, shards, opt) case "Store": statFn() - return e.executeSetRow(ctx, index, c, shards, opt) + return e.executeSetRow(ctx, tx, index, c, shards, opt) case "Count": statFn() - return e.executeCount(ctx, index, c, shards, opt) + return e.executeCount(ctx, tx, index, c, shards, opt) case "Set": statFn() - return e.executeSet(ctx, index, c, opt) + return e.executeSet(ctx, tx, index, c, opt) case "SetRowAttrs": statFn() - return nil, e.executeSetRowAttrs(ctx, index, c, opt) + return nil, e.executeSetRowAttrs(ctx, tx, index, c, opt) case "SetColumnAttrs": statFn() - return nil, e.executeSetColumnAttrs(ctx, index, c, opt) + return nil, e.executeSetColumnAttrs(ctx, tx, index, c, opt) case "TopN": statFn() - return e.executeTopN(ctx, index, c, shards, opt) + return e.executeTopN(ctx, tx, index, c, shards, opt) case "Rows": statFn() - return e.executeRows(ctx, index, c, shards, opt) + return e.executeRows(ctx, tx, index, c, shards, opt) case "GroupBy": statFn() - return e.executeGroupBy(ctx, index, c, shards, opt) + return e.executeGroupBy(ctx, tx, index, c, shards, opt) case "Options": statFn() - return e.executeOptionsCall(ctx, index, c, shards, opt) + return e.executeOptionsCall(ctx, tx, index, c, shards, opt) case "IncludesColumn": - return e.executeIncludesColumnCall(ctx, index, c, shards, opt) + return e.executeIncludesColumnCall(ctx, tx, index, c, shards, opt) case "FieldValue": statFn() - return e.executeFieldValueCall(ctx, index, c, shards, opt) + return e.executeFieldValueCall(ctx, tx, index, c, shards, opt) case "All": statFn() - return e.executeAllCall(ctx, index, c, shards, opt) + return e.executeAllCall(ctx, tx, index, c, shards, opt) case "Precomputed": - return e.executePrecomputedCall(ctx, index, c, shards, opt) + return e.executePrecomputedCall(ctx, tx, index, c, shards, opt) default: statFn() - return e.executeBitmapCall(ctx, index, c, shards, opt) + return e.executeBitmapCall(ctx, tx, index, c, shards, opt) } } @@ -599,7 +738,7 @@ func (e *executor) validateCallArgs(c *pql.Call) error { return nil } -func (e *executor) executeOptionsCall(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (interface{}, error) { +func (e *executor) executeOptionsCall(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (interface{}, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeOptionsCall") defer span.Finish() @@ -641,11 +780,11 @@ func (e *executor) executeOptionsCall(ctx context.Context, index string, c *pql. return nil, errors.New("Query(): shards must be a list of unsigned integers") } } - return e.executeCall(ctx, index, c.Children[0], shards, optCopy) + return e.executeCall(ctx, tx, index, c.Children[0], shards, optCopy) } // executeIncludesColumnCall executes an IncludesColumn() call. -func (e *executor) executeIncludesColumnCall(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (bool, error) { +func (e *executor) executeIncludesColumnCall(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (bool, error) { // Get the shard containing the column, since that's the only // shard that needs to execute this query. var shard uint64 @@ -664,7 +803,7 @@ func (e *executor) executeIncludesColumnCall(ctx context.Context, index string, // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeIncludesColumnCallShard(ctx, index, c, shard, col) + return e.executeIncludesColumnCallShard(ctx, tx, index, c, shard, col) } // Merge returned results at coordinating node. @@ -681,10 +820,15 @@ func (e *executor) executeIncludesColumnCall(ctx context.Context, index string, } // executeFieldValueCall executes a FieldValue() call. -func (e *executor) executeFieldValueCall(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (ValCount, error) { +func (e *executor) executeFieldValueCall(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (ValCount, error) { fieldName, ok := c.Args["field"].(string) if !ok || fieldName == "" { - return ValCount{}, errors.New("FieldValue(): field required") + return ValCount{}, ErrFieldRequired + } + + colKey, ok := c.Args["column"] + if !ok || colKey == "" { + return ValCount{}, ErrColumnRequired } // Fetch index. @@ -700,8 +844,8 @@ func (e *executor) executeFieldValueCall(ctx context.Context, index string, c *p } var colID uint64 - if colKey, ok := c.Args["column"].(string); ok && idx.Keys() { - id, err := e.Cluster.translateIndexKey(ctx, index, colKey) + if key, ok := colKey.(string); ok && idx.Keys() { + id, err := e.Cluster.translateIndexKey(ctx, index, key) if err != nil { return ValCount{}, errors.Wrap(err, "getting column id") } @@ -709,7 +853,6 @@ func (e *executor) executeFieldValueCall(ctx context.Context, index string, c *p } else { id, ok, err := c.UintArg("column") if !ok || err != nil { - // TODO: this error is getting swallowed somewhere (via curl) return ValCount{}, errors.Wrap(err, "getting column argument") } colID = id @@ -719,7 +862,7 @@ func (e *executor) executeFieldValueCall(ctx context.Context, index string, c *p // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeFieldValueCallShard(ctx, field, colID, shard) + return e.executeFieldValueCallShard(ctx, tx, field, colID, shard) } // Select single returned result at coordinating node. @@ -740,8 +883,8 @@ func (e *executor) executeFieldValueCall(ctx context.Context, index string, c *p return other, nil } -func (e *executor) executeFieldValueCallShard(ctx context.Context, field *Field, col uint64, shard uint64) (ValCount, error) { - value, exists, err := field.Value(col) +func (e *executor) executeFieldValueCallShard(ctx context.Context, tx Tx, field *Field, col uint64, shard uint64) (ValCount, error) { + value, exists, err := field.Value(tx, col) if err != nil { return ValCount{}, errors.Wrap(err, "getting field value") } else if !exists { @@ -766,7 +909,7 @@ func (e *executor) executeFieldValueCallShard(ctx context.Context, field *Field, } // executeAllCall executes an All() call. -func (e *executor) executeAllCall(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (*Row, error) { +func (e *executor) executeAllCall(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (*Row, error) { rslt := NewRow() var limit uint64 @@ -795,7 +938,7 @@ func (e *executor) executeAllCall(ctx context.Context, index string, c *pql.Call var got uint64 for _, shard := range shards { - row, err := e.executeAllCallMapReduce(ctx, index, c, shard, opt) + row, err := e.executeAllCallMapReduce(ctx, tx, index, c, shard, opt) if err != nil { return nil, errors.Wrap(err, "executing map reduce on shard") } @@ -845,10 +988,10 @@ func (e *executor) executeAllCall(ctx context.Context, index string, c *pql.Call // executeAllCallMapReduce executes a single shard of the All() call // using the executor.mapReduce() method. -func (e *executor) executeAllCallMapReduce(ctx context.Context, index string, c *pql.Call, shard uint64, opt *execOptions) (*Row, error) { +func (e *executor) executeAllCallMapReduce(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64, opt *execOptions) (*Row, error) { // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeAllCallShard(ctx, index, c, shard) + return e.executeAllCallShard(ctx, tx, index, c, shard) } // Merge returned results at coordinating node. @@ -875,12 +1018,12 @@ func (e *executor) executeAllCallMapReduce(ctx context.Context, index string, c } // executeIncludesColumnCallShard -func (e *executor) executeIncludesColumnCallShard(ctx context.Context, index string, c *pql.Call, shard uint64, column uint64) (bool, error) { +func (e *executor) executeIncludesColumnCallShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64, column uint64) (bool, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeIncludesColumnCallShard") defer span.Finish() if len(c.Children) == 1 { - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return false, errors.Wrap(err, "executing bitmap call") } @@ -891,7 +1034,7 @@ func (e *executor) executeIncludesColumnCallShard(ctx context.Context, index str } // executeSum executes a Sum() call. -func (e *executor) executeSum(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (ValCount, error) { +func (e *executor) executeSum(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (ValCount, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeSum") defer span.Finish() @@ -906,7 +1049,7 @@ func (e *executor) executeSum(ctx context.Context, index string, c *pql.Call, sh // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeSumCountShard(ctx, index, c, nil, shard) + return e.executeSumCountShard(ctx, tx, index, c, nil, shard) } // Merge returned results at coordinating node. @@ -946,7 +1089,7 @@ func (e *executor) executeSum(ctx context.Context, index string, c *pql.Call, sh // executeGenericField executes a generic call on a field. Note that in this // implementation, the operation is always a BSI op. -func (e *executor) executeGenericField(ctx context.Context, index string, c *pql.Call, op ext.BitmapOpBSIBitmap, shards []uint64, opt *execOptions) (SignedRow, error) { +func (e *executor) executeGenericField(ctx context.Context, tx Tx, index string, c *pql.Call, op ext.BitmapOpBSIBitmap, shards []uint64, opt *execOptions) (SignedRow, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeGenericField") span.LogKV("name", c.Name) defer span.Finish() @@ -958,7 +1101,7 @@ func (e *executor) executeGenericField(ctx context.Context, index string, c *pql // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeGenericFieldShard(ctx, index, c, op, shard) + return e.executeGenericFieldShard(ctx, tx, index, c, op, shard) } // Merge returned results at coordinating node. @@ -981,7 +1124,7 @@ func (e *executor) executeGenericField(ctx context.Context, index string, c *pql } // executeMin executes a Min() call. -func (e *executor) executeMin(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (ValCount, error) { +func (e *executor) executeMin(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (ValCount, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeMin") defer span.Finish() if field := c.Args["field"]; field == "" { @@ -994,7 +1137,7 @@ func (e *executor) executeMin(ctx context.Context, index string, c *pql.Call, sh // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeMinShard(ctx, index, c, shard) + return e.executeMinShard(ctx, tx, index, c, shard) } // Merge returned results at coordinating node. @@ -1016,7 +1159,7 @@ func (e *executor) executeMin(ctx context.Context, index string, c *pql.Call, sh } // executeMax executes a Max() call. -func (e *executor) executeMax(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (ValCount, error) { +func (e *executor) executeMax(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (ValCount, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeMax") defer span.Finish() @@ -1030,7 +1173,7 @@ func (e *executor) executeMax(ctx context.Context, index string, c *pql.Call, sh // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeMaxShard(ctx, index, c, shard) + return e.executeMaxShard(ctx, tx, index, c, shard) } // Merge returned results at coordinating node. @@ -1052,7 +1195,7 @@ func (e *executor) executeMax(ctx context.Context, index string, c *pql.Call, sh } // executeMinRow executes a MinRow() call. -func (e *executor) executeMinRow(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (interface{}, error) { +func (e *executor) executeMinRow(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (interface{}, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeMinRow") defer span.Finish() @@ -1062,7 +1205,7 @@ func (e *executor) executeMinRow(ctx context.Context, index string, c *pql.Call, // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeMinRowShard(ctx, index, c, shard) + return e.executeMinRowShard(ctx, tx, index, c, shard) } // Merge returned results at coordinating node. @@ -1091,7 +1234,7 @@ func (e *executor) executeMinRow(ctx context.Context, index string, c *pql.Call, } // executeMaxRow executes a MaxRow() call. -func (e *executor) executeMaxRow(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (interface{}, error) { +func (e *executor) executeMaxRow(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (interface{}, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeMaxRow") defer span.Finish() @@ -1101,7 +1244,7 @@ func (e *executor) executeMaxRow(ctx context.Context, index string, c *pql.Call, // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeMaxRowShard(ctx, index, c, shard) + return e.executeMaxRowShard(ctx, tx, index, c, shard) } // Merge returned results at coordinating node. @@ -1130,7 +1273,7 @@ func (e *executor) executeMaxRow(ctx context.Context, index string, c *pql.Call, } // executePrecomputedCall pretends to execute a call that we have a precomputed value for. -func (e *executor) executePrecomputedCall(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (*Row, error) { +func (e *executor) executePrecomputedCall(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (*Row, error) { span, _ := tracing.StartSpanFromContext(ctx, "Executor.executePrecomputedCall") defer span.Finish() result := NewRow() @@ -1142,7 +1285,7 @@ func (e *executor) executePrecomputedCall(ctx context.Context, index string, c * } // executeBitmapCall executes a call that returns a bitmap. -func (e *executor) executeBitmapCall(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (*Row, error) { +func (e *executor) executeBitmapCall(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (*Row, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeBitmapCall") span.LogKV("pqlCallName", c.Name) defer span.Finish() @@ -1158,7 +1301,7 @@ func (e *executor) executeBitmapCall(ctx context.Context, index string, c *pql.C // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeBitmapCallShard(ctx, index, c, shard) + return e.executeBitmapCallShard(ctx, tx, index, c, shard) } // Merge returned results at coordinating node. @@ -1224,7 +1367,7 @@ func (e *executor) executeBitmapCall(ctx context.Context, index string, c *pql.C } // executeBitmapCallShard executes a bitmap call for a single shard. -func (e *executor) executeBitmapCallShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { +func (e *executor) executeBitmapCallShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (*Row, error) { if err := validateQueryContext(ctx); err != nil { return nil, err } @@ -1236,28 +1379,28 @@ func (e *executor) executeBitmapCallShard(ctx context.Context, index string, c * return nil, fmt.Errorf("count op %s used as bitmap call", c.Name) } if op, ok := e.additionalBitmapOps[c.Name]; ok { - return e.executeGenericBitmapShard(ctx, index, c, op, shard) + return e.executeGenericBitmapShard(ctx, tx, index, c, op, shard) } switch c.Name { case "Row", "Range": - return e.executeRowShard(ctx, index, c, shard) + return e.executeRowShard(ctx, tx, index, c, shard) case "Difference": - return e.executeDifferenceShard(ctx, index, c, shard) + return e.executeDifferenceShard(ctx, tx, index, c, shard) case "Intersect": - return e.executeIntersectShard(ctx, index, c, shard) + return e.executeIntersectShard(ctx, tx, index, c, shard) case "Union": - return e.executeUnionShard(ctx, index, c, shard) + return e.executeUnionShard(ctx, tx, index, c, shard) case "Xor": - return e.executeXorShard(ctx, index, c, shard) + return e.executeXorShard(ctx, tx, index, c, shard) case "Not": - return e.executeNotShard(ctx, index, c, shard) + return e.executeNotShard(ctx, tx, index, c, shard) case "Shift": - return e.executeShiftShard(ctx, index, c, shard) + return e.executeShiftShard(ctx, tx, index, c, shard) case "All": // Allow a shard computation to use All() (note, limit/offset not applied) - return e.executeAllCallShard(ctx, index, c, shard) + return e.executeAllCallShard(ctx, tx, index, c, shard) case "Precomputed": - return e.executePrecomputedCallShard(ctx, index, c, shard) + return e.executePrecomputedCallShard(ctx, tx, index, c, shard) default: return nil, fmt.Errorf("unknown call: %s", c.Name) } @@ -1266,14 +1409,14 @@ func (e *executor) executeBitmapCallShard(ctx context.Context, index string, c * // executeGenericFieldShard executes a generic/extension command on a // single shard. Note that in this implementation, the op is always // a BSI op. -func (e *executor) executeGenericFieldShard(ctx context.Context, index string, c *pql.Call, op ext.BitmapOpBSIBitmap, shard uint64) (SignedRow, error) { +func (e *executor) executeGenericFieldShard(ctx context.Context, tx Tx, index string, c *pql.Call, op ext.BitmapOpBSIBitmap, shard uint64) (SignedRow, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeGenericShard") defer span.Finish() var filter *Row var filterBitmap *roaring.Bitmap if len(c.Children) == 1 { - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return SignedRow{}, errors.Wrap(err, "executing bitmap call") } @@ -1316,13 +1459,13 @@ func (e *executor) executeGenericFieldShard(ctx context.Context, index string, c } // executeSumCountShard calculates the sum and count for bsiGroups on a shard. -func (e *executor) executeSumCountShard(ctx context.Context, index string, c *pql.Call, filter *Row, shard uint64) (ValCount, error) { +func (e *executor) executeSumCountShard(ctx context.Context, tx Tx, index string, c *pql.Call, filter *Row, shard uint64) (ValCount, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeSumCountShard") defer span.Finish() // Only calculate the filter if it doesn't exist and a child call as been passed in. if filter == nil && len(c.Children) == 1 { - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return ValCount{}, errors.Wrap(err, "executing bitmap call") } @@ -1348,7 +1491,7 @@ func (e *executor) executeSumCountShard(ctx context.Context, index string, c *pq sumspan, _ := tracing.StartSpanFromContext(ctx, "Executor.executeSumCountShard_fragment.sum") defer sumspan.Finish() - vsum, vcount, err := fragment.sum(filter, bsig.BitDepth) + vsum, vcount, err := fragment.sum(tx, filter, bsig.BitDepth) if err != nil { return ValCount{}, errors.Wrap(err, "computing sum") } @@ -1359,13 +1502,13 @@ func (e *executor) executeSumCountShard(ctx context.Context, index string, c *pq } // executeMinShard calculates the min for bsiGroups on a shard. -func (e *executor) executeMinShard(ctx context.Context, index string, c *pql.Call, shard uint64) (ValCount, error) { +func (e *executor) executeMinShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (ValCount, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeMinShard") defer span.Finish() var filter *Row if len(c.Children) == 1 { - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return ValCount{}, err } @@ -1379,14 +1522,14 @@ func (e *executor) executeMinShard(ctx context.Context, index string, c *pql.Cal return ValCount{}, nil } - return field.MinForShard(shard, filter) + return field.MinForShard(tx, shard, filter) } // executeMaxShard calculates the max for bsiGroups on a shard. -func (e *executor) executeMaxShard(ctx context.Context, index string, c *pql.Call, shard uint64) (ValCount, error) { +func (e *executor) executeMaxShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (ValCount, error) { var filter *Row if len(c.Children) == 1 { - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return ValCount{}, err } @@ -1400,14 +1543,14 @@ func (e *executor) executeMaxShard(ctx context.Context, index string, c *pql.Cal return ValCount{}, nil } - return field.MaxForShard(shard, filter) + return field.MaxForShard(tx, shard, filter) } // executeMinRowShard returns the minimum row ID for a shard. -func (e *executor) executeMinRowShard(ctx context.Context, index string, c *pql.Call, shard uint64) (PairField, error) { +func (e *executor) executeMinRowShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (PairField, error) { var filter *Row if len(c.Children) == 1 { - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return PairField{}, err } @@ -1425,7 +1568,11 @@ func (e *executor) executeMinRowShard(ctx context.Context, index string, c *pql. return PairField{}, nil } - minRowID, count := fragment.minRow(filter) + minRowID, count, err := fragment.minRow(tx, filter) + if err != nil { + return PairField{}, err + } + return PairField{ Pair: Pair{ ID: minRowID, @@ -1436,10 +1583,10 @@ func (e *executor) executeMinRowShard(ctx context.Context, index string, c *pql. } // executeMaxRowShard returns the maximum row ID for a shard. -func (e *executor) executeMaxRowShard(ctx context.Context, index string, c *pql.Call, shard uint64) (PairField, error) { +func (e *executor) executeMaxRowShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (PairField, error) { var filter *Row if len(c.Children) == 1 { - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return PairField{}, err } @@ -1457,7 +1604,11 @@ func (e *executor) executeMaxRowShard(ctx context.Context, index string, c *pql. return PairField{}, nil } - maxRowID, count := fragment.maxRow(filter) + maxRowID, count, err := fragment.maxRow(tx, filter) + if err != nil { + return PairField{}, nil + } + return PairField{ Pair: Pair{ ID: maxRowID, @@ -1470,7 +1621,7 @@ func (e *executor) executeMaxRowShard(ctx context.Context, index string, c *pql. // executeTopN executes a TopN() call. // This first performs the TopN() to determine the top results and then // requeries to retrieve the full counts for each of the top results. -func (e *executor) executeTopN(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (*PairsField, error) { +func (e *executor) executeTopN(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (*PairsField, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeTopN") defer span.Finish() @@ -1486,7 +1637,7 @@ func (e *executor) executeTopN(ctx context.Context, index string, c *pql.Call, s } // Execute original query. - pairs, err := e.executeTopNShards(ctx, index, c, shards, opt) + pairs, err := e.executeTopNShards(ctx, tx, index, c, shards, opt) if err != nil { return nil, errors.Wrap(err, "finding top results") } @@ -1507,7 +1658,7 @@ func (e *executor) executeTopN(ctx context.Context, index string, c *pql.Call, s sort.Sort(uint64Slice(ids)) other.Args["ids"] = ids - trimmedList, err := e.executeTopNShards(ctx, index, other, shards, opt) + trimmedList, err := e.executeTopNShards(ctx, tx, index, other, shards, opt) if err != nil { return nil, errors.Wrap(err, "retrieving full counts") } @@ -1522,13 +1673,13 @@ func (e *executor) executeTopN(ctx context.Context, index string, c *pql.Call, s }, nil } -func (e *executor) executeTopNShards(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (*PairsField, error) { +func (e *executor) executeTopNShards(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (*PairsField, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeTopNShards") defer span.Finish() // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeTopNShard(ctx, index, c, shard) + return e.executeTopNShard(ctx, tx, index, c, shard) } // Merge returned results at coordinating node. @@ -1560,7 +1711,7 @@ func (e *executor) executeTopNShards(ctx context.Context, index string, c *pql.C } // executeTopNShard executes a TopN call for a single shard. -func (e *executor) executeTopNShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*PairsField, error) { +func (e *executor) executeTopNShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (*PairsField, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeTopNShard") defer span.Finish() @@ -1590,7 +1741,7 @@ func (e *executor) executeTopNShard(ctx context.Context, index string, c *pql.Ca // Retrieve bitmap used to intersect. var src *Row if len(c.Children) == 1 { - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return nil, err } @@ -1618,7 +1769,7 @@ func (e *executor) executeTopNShard(ctx context.Context, index string, c *pql.Ca if tanimotoThreshold > 100 { return nil, errors.New("Tanimoto Threshold is from 1 to 100 only") } - pairs, err := f.top(topOptions{ + pairs, err := f.top(tx, topOptions{ N: int(n), Src: src, RowIDs: rowIDs, @@ -1637,7 +1788,7 @@ func (e *executor) executeTopNShard(ctx context.Context, index string, c *pql.Ca } // executeDifferenceShard executes a difference() call for a local shard. -func (e *executor) executeDifferenceShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { +func (e *executor) executeDifferenceShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (*Row, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeDifferenceShard") defer span.Finish() @@ -1646,7 +1797,7 @@ func (e *executor) executeDifferenceShard(ctx context.Context, index string, c * return nil, fmt.Errorf("empty Difference query is currently not supported") } for i, input := range c.Children { - row, err := e.executeBitmapCallShard(ctx, index, input, shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, input, shard) if err != nil { return nil, err } @@ -1752,7 +1903,7 @@ func (r RowIDs) merge(other RowIDs, limit int) RowIDs { return result } -func (e *executor) executeGroupBy(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) ([]GroupCount, error) { +func (e *executor) executeGroupBy(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) ([]GroupCount, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeGroupBy") defer span.Finish() // validate call @@ -1813,7 +1964,7 @@ func (e *executor) executeGroupBy(ctx context.Context, index string, c *pql.Call } if hasLimit || hasCol { // we need to perform this query cluster-wide ahead of executeGroupByShard - childRows[i], err = e.executeRows(ctx, index, child, shards, opt) + childRows[i], err = e.executeRows(ctx, tx, index, child, shards, opt) if err != nil { return nil, errors.Wrap(err, "getting rows for ") } @@ -1825,7 +1976,7 @@ func (e *executor) executeGroupBy(ctx context.Context, index string, c *pql.Call // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeGroupByShard(ctx, index, c, filter, shard, childRows, bases) + return e.executeGroupByShard(ctx, tx, index, c, filter, shard, childRows, bases) } // Merge returned results at coordinating node. reduceFn := func(ctx context.Context, prev, v interface{}) interface{} { @@ -2176,13 +2327,13 @@ func applyConditionToGroupCounts(gcs []GroupCount, subj string, cond *pql.Condit return gcs[:i] } -func (e *executor) executeGroupByShard(ctx context.Context, index string, c *pql.Call, filter *pql.Call, shard uint64, childRows []RowIDs, bases map[int]int64) (_ []GroupCount, err error) { +func (e *executor) executeGroupByShard(ctx context.Context, tx Tx, index string, c *pql.Call, filter *pql.Call, shard uint64, childRows []RowIDs, bases map[int]int64) (_ []GroupCount, err error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeGroupByShard") defer span.Finish() var filterRow *Row if filter != nil { - if filterRow, err = e.executeBitmapCallShard(ctx, index, filter, shard); err != nil { + if filterRow, err = e.executeBitmapCallShard(ctx, tx, index, filter, shard); err != nil { return nil, errors.Wrapf(err, "executing group by filter for shard %d", shard) } } @@ -2193,7 +2344,7 @@ func (e *executor) executeGroupByShard(ctx context.Context, index string, c *pql } newspan, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeGroupByShard_newGroupByIterator") - iter, err := newGroupByIterator(e, childRows, c.Children, aggregate, filterRow, index, shard, e.Holder) + iter, err := newGroupByIterator(e, tx, childRows, c.Children, aggregate, filterRow, index, shard, e.Holder) newspan.Finish() if err != nil { @@ -2234,7 +2385,7 @@ func (e *executor) executeGroupByShard(ctx context.Context, index string, c *pql return results, nil } -func (e *executor) executeRows(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (RowIDs, error) { +func (e *executor) executeRows(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (RowIDs, error) { // Fetch field name from argument. // Check "field" first for backwards compatibility. // TODO: remove at Pilosa 2.0 @@ -2254,7 +2405,7 @@ func (e *executor) executeRows(ctx context.Context, index string, c *pql.Call, s // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeRowsShard(ctx, index, fieldName, c, shard) + return e.executeRowsShard(ctx, tx, index, fieldName, c, shard) } // Determine limit so we can use it when reducing. @@ -2282,7 +2433,7 @@ func (e *executor) executeRows(ctx context.Context, index string, c *pql.Call, s return results, nil } -func (e *executor) executeRowsShard(ctx context.Context, index string, fieldName string, c *pql.Call, shard uint64) (RowIDs, error) { +func (e *executor) executeRowsShard(ctx context.Context, tx Tx, index string, fieldName string, c *pql.Call, shard uint64) (RowIDs, error) { // Fetch index. idx := e.Holder.Index(index) if idx == nil { @@ -2391,6 +2542,14 @@ func (e *executor) executeRowsShard(ctx context.Context, index string, fieldName limit = int(lim) } + var likeErr chan error + if like, hasLike, err := c.StringArg("like"); err != nil { + return nil, errors.Wrap(err, "getting like pattern") + } else if hasLike { + likeErr = make(chan error, 1) + filters = append(filters, filterLike(like, f.TranslateStore(), likeErr)) + } + for _, view := range views { if err := ctx.Err(); err != nil { return nil, err @@ -2400,20 +2559,28 @@ func (e *executor) executeRowsShard(ctx context.Context, index string, fieldName continue } - viewRows := frag.rows(ctx, start, filters...) + viewRows, err := frag.rows(ctx, tx, start, filters...) + if err != nil { + return nil, err + } + select { + case err = <-likeErr: + return nil, err + default: + } rowIDs = rowIDs.merge(viewRows, limit) } return rowIDs, nil } -func (e *executor) executeRowShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { +func (e *executor) executeRowShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (*Row, error) { span, _ := tracing.StartSpanFromContext(ctx, "Executor.executeRowShard") defer span.Finish() // Handle bsiGroup ranges differently. if c.HasConditionArg() { - return e.executeRowBSIGroupShard(ctx, index, c, shard) + return e.executeRowBSIGroupShard(ctx, tx, index, c, shard) } // Fetch index. @@ -2427,18 +2594,11 @@ func (e *executor) executeRowShard(ctx context.Context, index string, c *pql.Cal if err != nil { return nil, errors.New("Row() argument required: field") } - f := e.Holder.Field(index, fieldName) + f := idx.Field(fieldName) if f == nil { return nil, ErrFieldNotFound } - rowID, rowOK, rowErr := c.UintArg(fieldName) - if rowErr != nil { - return nil, fmt.Errorf("Row() error with arg for row: %v", rowErr) - } else if !rowOK { - return nil, fmt.Errorf("Row() must specify %v", rowLabel) - } - // Parse "from" time, if set. var fromTime time.Time if v, ok := c.Args["from"]; ok { @@ -2455,13 +2615,38 @@ func (e *executor) executeRowShard(ctx context.Context, index string, c *pql.Cal } } + timeNotSet := fromTime.IsZero() && toTime.IsZero() + + // This is workaround to support pql.ASSIGN ('=') as condition ('==') for int and decimal fields + if c.Name == "Row" && timeNotSet && + (f.Type() == FieldTypeInt || f.Type() == FieldTypeDecimal) { + // re-write args as conditions for fieldName + for k, v := range c.Args { + if _, ok := v.(*pql.Condition); k == fieldName && !ok { + c.Args[k] = &pql.Condition{ + Op: pql.EQ, + Value: v, + } + + return e.executeRowBSIGroupShard(ctx, tx, index, c, shard) + } + } + } + + rowID, rowOK, rowErr := c.UintArg(fieldName) + if rowErr != nil { + return nil, fmt.Errorf("Row() error with arg for row: %v", rowErr) + } else if !rowOK { + return nil, fmt.Errorf("Row() must specify %v", rowLabel) + } + // Simply return row if times are not set. - if c.Name == "Row" && fromTime.IsZero() && toTime.IsZero() { + if c.Name == "Row" && timeNotSet { frag := e.Holder.fragment(index, fieldName, viewStandard, shard) if frag == nil { return NewRow(), nil } - return frag.row(rowID), nil + return frag.row(tx, rowID) } // If no quantum exists then return an empty bitmap. @@ -2485,7 +2670,11 @@ func (e *executor) executeRowShard(ctx context.Context, index string, c *pql.Cal if f == nil { continue } - rows = append(rows, f.row(rowID)) + row, err := f.row(tx, rowID) + if err != nil { + return nil, err + } + rows = append(rows, row) } if len(rows) == 0 { return &Row{}, nil @@ -2498,7 +2687,7 @@ func (e *executor) executeRowShard(ctx context.Context, index string, c *pql.Cal } // executeRowBSIGroupShard executes a range(bsiGroup) call for a local shard. -func (e *executor) executeRowBSIGroupShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { +func (e *executor) executeRowBSIGroupShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (_ *Row, err error) { span, _ := tracing.StartSpanFromContext(ctx, "Executor.executeRowBSIGroupShard") defer span.Finish() @@ -2540,7 +2729,7 @@ func (e *executor) executeRowBSIGroupShard(ctx context.Context, index string, c return NewRow(), nil } - return frag.notNull() + return frag.notNull(tx) } else if cond.Op == pql.EQ && cond.Value == nil { // Make sure the index supports existence tracking. @@ -2556,7 +2745,9 @@ func (e *executor) executeRowBSIGroupShard(ctx context.Context, index string, c if existenceFrag == nil { existenceRow = NewRow() } else { - existenceRow = existenceFrag.row(0) + if existenceRow, err = existenceFrag.row(tx, 0); err != nil { + return nil, err + } } var notNull *Row @@ -2564,7 +2755,7 @@ func (e *executor) executeRowBSIGroupShard(ctx context.Context, index string, c // Retrieve notNull from fragment if it exists. if frag := e.Holder.fragment(index, fieldName, viewBSIGroupPrefix+fieldName, shard); frag != nil { - if notNull, err = frag.notNull(); err != nil { + if notNull, err = frag.notNull(tx); err != nil { return nil, errors.Wrap(err, "getting fragment not null") } } else { @@ -2609,10 +2800,10 @@ func (e *executor) executeRowBSIGroupShard(ctx context.Context, index string, c // If the query is asking for the entire valid range, just return // the not-null bitmap for the bsiGroup. if predicates[0] <= bsig.Min && predicates[1] >= bsig.Max { - return frag.notNull() + return frag.notNull(tx) } - return frag.rangeBetween(bsig.BitDepth, baseValueMin, baseValueMax) + return frag.rangeBetween(tx, bsig.BitDepth, baseValueMin, baseValueMax) } else { value, err := getScaledInt(f, cond.Value) @@ -2640,20 +2831,20 @@ func (e *executor) executeRowBSIGroupShard(ctx context.Context, index string, c // LT[E] and GT[E] should return all not-null if selected range fully encompasses valid bsiGroup range. if (cond.Op == pql.LT && value > bsig.Max) || (cond.Op == pql.LTE && value >= bsig.Max) || (cond.Op == pql.GT && value < bsig.Min) || (cond.Op == pql.GTE && value <= bsig.Min) { - return frag.notNull() + return frag.notNull(tx) } // outOfRange for NEQ should return all not-null. if outOfRange && cond.Op == pql.NEQ { - return frag.notNull() + return frag.notNull(tx) } - return frag.rangeOp(cond.Op, bsig.BitDepth, baseValue) + return frag.rangeOp(tx, cond.Op, bsig.BitDepth, baseValue) } } // executeIntersectShard executes a intersect() call for a local shard. -func (e *executor) executeIntersectShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { +func (e *executor) executeIntersectShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (*Row, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeIntersectShard") defer span.Finish() @@ -2662,7 +2853,7 @@ func (e *executor) executeIntersectShard(ctx context.Context, index string, c *p return nil, fmt.Errorf("empty Intersect query is currently not supported") } for i, input := range c.Children { - row, err := e.executeBitmapCallShard(ctx, index, input, shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, input, shard) if err != nil { return nil, err } @@ -2678,7 +2869,7 @@ func (e *executor) executeIntersectShard(ctx context.Context, index string, c *p } // executeGenericBitmapShard executes a generic bitmap call for a local shard. -func (e *executor) executeGenericBitmapShard(ctx context.Context, index string, c *pql.Call, op ext.BitmapOpBitmap, shard uint64) (*Row, error) { +func (e *executor) executeGenericBitmapShard(ctx context.Context, tx Tx, index string, c *pql.Call, op ext.BitmapOpBitmap, shard uint64) (*Row, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeGenericBitmapShard") defer span.Finish() @@ -2686,7 +2877,7 @@ func (e *executor) executeGenericBitmapShard(ctx context.Context, index string, if len(c.Children) != 1 { return nil, fmt.Errorf("%s needs exactly one row parameter", c.Name) } - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return nil, err } @@ -2696,7 +2887,7 @@ func (e *executor) executeGenericBitmapShard(ctx context.Context, index string, var err error rows := make([]*Row, len(c.Children)) for i, input := range c.Children { - rows[i], err = e.executeBitmapCallShard(ctx, index, input, shard) + rows[i], err = e.executeBitmapCallShard(ctx, tx, index, input, shard) if err != nil { return nil, err } @@ -2716,13 +2907,13 @@ func (e *executor) executeGenericBitmapShard(ctx context.Context, index string, } // executeUnionShard executes a union() call for a local shard. -func (e *executor) executeUnionShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { +func (e *executor) executeUnionShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (*Row, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeUnionShard") defer span.Finish() other := NewRow() for i, input := range c.Children { - row, err := e.executeBitmapCallShard(ctx, index, input, shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, input, shard) if err != nil { return nil, err } @@ -2738,13 +2929,13 @@ func (e *executor) executeUnionShard(ctx context.Context, index string, c *pql.C } // executeXorShard executes a xor() call for a local shard. -func (e *executor) executeXorShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { +func (e *executor) executeXorShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (*Row, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeXorShard") defer span.Finish() other := NewRow() for i, input := range c.Children { - row, err := e.executeBitmapCallShard(ctx, index, input, shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, input, shard) if err != nil { return nil, err } @@ -2760,7 +2951,7 @@ func (e *executor) executeXorShard(ctx context.Context, index string, c *pql.Cal } // executePrecomputedCallShard pretends to execute a precomputed call for a local shard. -func (e *executor) executePrecomputedCallShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { +func (e *executor) executePrecomputedCallShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (*Row, error) { if c.Precomputed != nil { v := c.Precomputed[shard] if v == nil { @@ -2779,7 +2970,7 @@ func (e *executor) executePrecomputedCallShard(ctx context.Context, index string } // executeNotShard executes a Not() call for a local shard. -func (e *executor) executeNotShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { +func (e *executor) executeNotShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (_ *Row, err error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeNotShard") defer span.Finish() @@ -2802,10 +2993,12 @@ func (e *executor) executeNotShard(ctx context.Context, index string, c *pql.Cal if existenceFrag == nil { existenceRow = NewRow() } else { - existenceRow = existenceFrag.row(0) + if existenceRow, err = existenceFrag.row(tx, 0); err != nil { + return nil, err + } } - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return nil, err } @@ -2814,7 +3007,7 @@ func (e *executor) executeNotShard(ctx context.Context, index string, c *pql.Cal } // executeAllCallShard executes an All() call for a local shard. -func (e *executor) executeAllCallShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { +func (e *executor) executeAllCallShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (_ *Row, err error) { span, _ := tracing.StartSpanFromContext(ctx, "Executor.executeAllCallShard") defer span.Finish() @@ -2835,14 +3028,16 @@ func (e *executor) executeAllCallShard(ctx context.Context, index string, c *pql if existenceFrag == nil { existenceRow = NewRow() } else { - existenceRow = existenceFrag.row(0) + if existenceRow, err = existenceFrag.row(tx, 0); err != nil { + return nil, err + } } return existenceRow, nil } // executeShiftShard executes a shift() call for a local shard. -func (e *executor) executeShiftShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { +func (e *executor) executeShiftShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (*Row, error) { n, _, err := c.IntArg("n") if err != nil { return nil, fmt.Errorf("executeShiftShard: %v", err) @@ -2854,7 +3049,7 @@ func (e *executor) executeShiftShard(ctx context.Context, index string, c *pql.C return nil, errors.New("Shift() only accepts a single row input") } - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return nil, err } @@ -2863,7 +3058,7 @@ func (e *executor) executeShiftShard(ctx context.Context, index string, c *pql.C } // executeGeneric executes a provided count-like call. -func (e *executor) executeGenericCount(ctx context.Context, index string, c *pql.Call, op ext.BitmapOpUnaryCount, shards []uint64, opt *execOptions) (uint64, error) { +func (e *executor) executeGenericCount(ctx context.Context, tx Tx, index string, c *pql.Call, op ext.BitmapOpUnaryCount, shards []uint64, opt *execOptions) (uint64, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeGenericCount") defer span.Finish() @@ -2875,7 +3070,7 @@ func (e *executor) executeGenericCount(ctx context.Context, index string, c *pql // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return 0, err } @@ -2898,7 +3093,7 @@ func (e *executor) executeGenericCount(ctx context.Context, index string, c *pql } // executeCount executes a count() call. -func (e *executor) executeCount(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (uint64, error) { +func (e *executor) executeCount(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (uint64, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeCount") defer span.Finish() @@ -2910,7 +3105,7 @@ func (e *executor) executeCount(ctx context.Context, index string, c *pql.Call, // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return 0, err } @@ -2933,7 +3128,7 @@ func (e *executor) executeCount(ctx context.Context, index string, c *pql.Call, } // executeClearBit executes a Clear() call. -func (e *executor) executeClearBit(ctx context.Context, index string, c *pql.Call, opt *execOptions) (bool, error) { +func (e *executor) executeClearBit(ctx context.Context, tx Tx, index string, c *pql.Call, opt *execOptions) (bool, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeClearBit") defer span.Finish() @@ -2962,7 +3157,7 @@ func (e *executor) executeClearBit(ctx context.Context, index string, c *pql.Cal // Int field. if f.Type() == FieldTypeInt || f.Type() == FieldTypeDecimal { - return e.executeClearValueField(ctx, index, c, f, colID, opt) + return e.executeClearValueField(ctx, tx, index, c, f, colID, opt) } rowID, ok, err := c.UintArg(fieldName) @@ -2972,11 +3167,11 @@ func (e *executor) executeClearBit(ctx context.Context, index string, c *pql.Cal return false, fmt.Errorf("row= argument required to Clear() call") } - return e.executeClearBitField(ctx, index, c, f, colID, rowID, opt) + return e.executeClearBitField(ctx, tx, index, c, f, colID, rowID, opt) } // executeClearBitField executes a Clear() call for a field. -func (e *executor) executeClearBitField(ctx context.Context, index string, c *pql.Call, f *Field, colID, rowID uint64, opt *execOptions) (bool, error) { +func (e *executor) executeClearBitField(ctx context.Context, tx Tx, index string, c *pql.Call, f *Field, colID, rowID uint64, opt *execOptions) (bool, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeClearBitField") defer span.Finish() @@ -2985,7 +3180,7 @@ func (e *executor) executeClearBitField(ctx context.Context, index string, c *pq for _, node := range e.Cluster.shardNodes(index, shard) { // Update locally if host matches. if node.ID == e.Node.ID { - val, err := f.ClearBit(rowID, colID) + val, err := f.ClearBit(tx, rowID, colID) if err != nil { return false, err } else if val { @@ -3009,7 +3204,7 @@ func (e *executor) executeClearBitField(ctx context.Context, index string, c *pq } // executeClearRow executes a ClearRow() call. -func (e *executor) executeClearRow(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (bool, error) { +func (e *executor) executeClearRow(ctx context.Context, tx Tx, index string, c *pql.Call, shards []uint64, opt *execOptions) (bool, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeClearRow") defer span.Finish() @@ -3032,7 +3227,7 @@ func (e *executor) executeClearRow(ctx context.Context, index string, c *pql.Cal // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeClearRowShard(ctx, index, c, shard) + return e.executeClearRowShard(ctx, tx, index, c, shard) } // Merge returned results at coordinating node. @@ -3052,7 +3247,7 @@ func (e *executor) executeClearRow(ctx context.Context, index string, c *pql.Cal } // executeClearRowShard executes a ClearRow() call for a single shard. -func (e *executor) executeClearRowShard(ctx context.Context, index string, c *pql.Call, shard uint64) (bool, error) { +func (e *executor) executeClearRowShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (bool, error) { span, _ := tracing.StartSpanFromContext(ctx, "Executor.executeClearRowShard") defer span.Finish() @@ -3081,7 +3276,7 @@ func (e *executor) executeClearRowShard(ctx context.Context, index string, c *pq if fragment == nil { continue } - cleared, err := fragment.clearRow(rowID) + cleared, err := fragment.clearRow(tx, rowID) if err != nil { return false, errors.Wrapf(err, "clearing row %d on view %s shard %d", rowID, view.name, shard) } @@ -3092,7 +3287,7 @@ func (e *executor) executeClearRowShard(ctx context.Context, index string, c *pq } // executeSetRow executes a Store() call. -func (e *executor) executeSetRow(ctx context.Context, indexName string, c *pql.Call, shards []uint64, opt *execOptions) (bool, error) { +func (e *executor) executeSetRow(ctx context.Context, tx Tx, indexName string, c *pql.Call, shards []uint64, opt *execOptions) (bool, error) { // Ensure the field type supports Store(). fieldName, err := c.FieldArg() if err != nil { @@ -3120,16 +3315,24 @@ func (e *executor) executeSetRow(ctx context.Context, indexName string, c *pql.C // Execute calls in bulk on each remote node and merge. mapFn := func(ctx context.Context, shard uint64) (interface{}, error) { - return e.executeSetRowShard(ctx, indexName, c, shard) + return e.executeSetRowShard(ctx, tx, indexName, c, shard) } // Merge returned results at coordinating node. reduceFn := func(ctx context.Context, prev, v interface{}) interface{} { - val := v.(bool) - if prev == nil { + val, ok := v.(bool) + if !ok { + return errors.Errorf("executeSetRow.reduceFn: val is non-bool (%+v)", v) + } + if val { return val } - return val || prev.(bool) + + pval, ok := prev.(bool) + if !ok { + return errors.Errorf("executeSetRow.reduceFn: prev is non-bool (%+v)", prev) + } + return pval } result, err := e.mapReduce(ctx, indexName, shards, c, opt, mapFn, reduceFn) @@ -3145,7 +3348,7 @@ func (e *executor) executeSetRow(ctx context.Context, indexName string, c *pql.C } // executeSetRowShard executes a SetRow() call for a single shard. -func (e *executor) executeSetRowShard(ctx context.Context, index string, c *pql.Call, shard uint64) (bool, error) { +func (e *executor) executeSetRowShard(ctx context.Context, tx Tx, index string, c *pql.Call, shard uint64) (bool, error) { fieldName, err := c.FieldArg() if err != nil { return false, errors.New("Store() argument required: field") @@ -3167,7 +3370,7 @@ func (e *executor) executeSetRowShard(ctx context.Context, index string, c *pql. // Retrieve source row. var src *Row if len(c.Children) == 1 { - row, err := e.executeBitmapCallShard(ctx, index, c.Children[0], shard) + row, err := e.executeBitmapCallShard(ctx, tx, index, c.Children[0], shard) if err != nil { return false, errors.Wrap(err, "getting source row") } @@ -3190,7 +3393,7 @@ func (e *executor) executeSetRowShard(ctx context.Context, index string, c *pql. return false, errors.Wrapf(err, "creating fragment: %d", shard) } } - set, err := fragment.setRow(src, rowID) + set, err := fragment.setRow(tx, src, rowID) if err != nil { return false, errors.Wrapf(err, "storing row %d on view %s shard %d", rowID, viewStandard, shard) } @@ -3200,7 +3403,7 @@ func (e *executor) executeSetRowShard(ctx context.Context, index string, c *pql. } // executeSet executes a Set() call. -func (e *executor) executeSet(ctx context.Context, index string, c *pql.Call, opt *execOptions) (bool, error) { +func (e *executor) executeSet(ctx context.Context, tx Tx, index string, c *pql.Call, opt *execOptions) (bool, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeSet") defer span.Finish() @@ -3230,7 +3433,7 @@ func (e *executor) executeSet(ctx context.Context, index string, c *pql.Call, op // Set column on existence field. if ef := idx.existenceField(); ef != nil { - if _, err := ef.SetBit(0, colID, nil); err != nil { + if _, err := ef.SetBit(tx, 0, colID, nil); err != nil { return false, errors.Wrap(err, "setting existence column") } } @@ -3257,7 +3460,7 @@ func (e *executor) executeSet(ctx context.Context, index string, c *pql.Call, op if err != nil { return false, fmt.Errorf("reading Set() row (int/decimal): %v", err) } - return e.executeSetValueField(ctx, index, c, f, colID, rowVal, opt) + return e.executeSetValueField(ctx, tx, index, c, f, colID, rowVal, opt) default: // Read row ID. @@ -3278,12 +3481,12 @@ func (e *executor) executeSet(ctx context.Context, index string, c *pql.Call, op timestamp = &t } - return e.executeSetBitField(ctx, index, c, f, colID, rowID, timestamp, opt) + return e.executeSetBitField(ctx, tx, index, c, f, colID, rowID, timestamp, opt) } } // executeSetBitField executes a Set() call for a specific field. -func (e *executor) executeSetBitField(ctx context.Context, index string, c *pql.Call, f *Field, colID, rowID uint64, timestamp *time.Time, opt *execOptions) (bool, error) { +func (e *executor) executeSetBitField(ctx context.Context, tx Tx, index string, c *pql.Call, f *Field, colID, rowID uint64, timestamp *time.Time, opt *execOptions) (bool, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeSetBitField") defer span.Finish() @@ -3293,7 +3496,7 @@ func (e *executor) executeSetBitField(ctx context.Context, index string, c *pql. for _, node := range e.Cluster.shardNodes(index, shard) { // Update locally if host matches. if node.ID == e.Node.ID { - val, err := f.SetBit(rowID, colID, timestamp) + val, err := f.SetBit(tx, rowID, colID, timestamp) if err != nil { return false, err } else if val { @@ -3318,7 +3521,7 @@ func (e *executor) executeSetBitField(ctx context.Context, index string, c *pql. } // executeSetValueField executes a Set() call for a specific int field. -func (e *executor) executeSetValueField(ctx context.Context, index string, c *pql.Call, f *Field, colID uint64, value int64, opt *execOptions) (bool, error) { +func (e *executor) executeSetValueField(ctx context.Context, tx Tx, index string, c *pql.Call, f *Field, colID uint64, value int64, opt *execOptions) (bool, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeSetValueField") defer span.Finish() @@ -3328,7 +3531,7 @@ func (e *executor) executeSetValueField(ctx context.Context, index string, c *pq for _, node := range e.Cluster.shardNodes(index, shard) { // Update locally if host matches. if node.ID == e.Node.ID { - val, err := f.SetValue(colID, value) + val, err := f.SetValue(tx, colID, value) if err != nil { return false, err } else if val { @@ -3353,7 +3556,7 @@ func (e *executor) executeSetValueField(ctx context.Context, index string, c *pq } // executeClearValueField removes value for colID if present -func (e *executor) executeClearValueField(ctx context.Context, index string, c *pql.Call, f *Field, colID uint64, opt *execOptions) (bool, error) { +func (e *executor) executeClearValueField(ctx context.Context, tx Tx, index string, c *pql.Call, f *Field, colID uint64, opt *execOptions) (bool, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeClearValueField") defer span.Finish() @@ -3363,7 +3566,7 @@ func (e *executor) executeClearValueField(ctx context.Context, index string, c * for _, node := range e.Cluster.shardNodes(index, shard) { // Update locally if host matches. if node.ID == e.Node.ID { - val, err := f.ClearValue(colID) + val, err := f.ClearValue(tx, colID) if err != nil { return false, err } else if val { @@ -3388,7 +3591,7 @@ func (e *executor) executeClearValueField(ctx context.Context, index string, c * } // executeSetRowAttrs executes a SetRowAttrs() call. -func (e *executor) executeSetRowAttrs(ctx context.Context, index string, c *pql.Call, opt *execOptions) error { +func (e *executor) executeSetRowAttrs(ctx context.Context, tx Tx, index string, c *pql.Call, opt *execOptions) error { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeSetRowAttrs") defer span.Finish() @@ -3447,7 +3650,7 @@ func (e *executor) executeSetRowAttrs(ctx context.Context, index string, c *pql. } // executeBulkSetRowAttrs executes a set of SetRowAttrs() calls. -func (e *executor) executeBulkSetRowAttrs(ctx context.Context, index string, calls []*pql.Call, opt *execOptions) ([]interface{}, error) { +func (e *executor) executeBulkSetRowAttrs(ctx context.Context, tx Tx, index string, calls []*pql.Call, opt *execOptions) ([]interface{}, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeBulkSetRowAttrs") defer span.Finish() @@ -3547,7 +3750,7 @@ func (e *executor) executeBulkSetRowAttrs(ctx context.Context, index string, cal } // executeSetColumnAttrs executes a SetColumnAttrs() call. -func (e *executor) executeSetColumnAttrs(ctx context.Context, index string, c *pql.Call, opt *execOptions) error { +func (e *executor) executeSetColumnAttrs(ctx context.Context, tx Tx, index string, c *pql.Call, opt *execOptions) error { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeSetColumnAttrs") defer span.Finish() @@ -4000,20 +4203,20 @@ func (e *executor) translateCall(ctx context.Context, indexName string, c *pql.C // are only two possible values. Instead, they are handled // directly. if field.Type() == FieldTypeBool { - // TODO: This code block doesn't make sense for a `Rows()` - // queries on a `bool` field. Need to review this better, - // include it in tests, and probably back-port it to Pilosa. - if c.Name != "Rows" { - boolVal, err := callArgBool(c, rowKey) - if err != nil { - return errors.Wrap(err, "getting bool key") - } - rowID := falseRowID - if boolVal { - rowID = trueRowID - } - c.Args[rowKey] = rowID + if c.Name == "Rows" { + // TranslateInfo for Rows returns "previous" as rowKey, + // so for bool fields we would get "missing bool argument" error + return nil } + boolVal, err := callArgBool(c, rowKey) + if err != nil { + return errors.Wrapf(err, "getting bool key (%+v)", rowKey) + } + rowID := falseRowID + if boolVal { + rowID = trueRowID + } + c.Args[rowKey] = rowID } else if field.Keys() { foreignIndexName := field.ForeignIndex() if c.Args[rowKey] != nil && isCondition(c.Args[rowKey]) { @@ -4441,25 +4644,37 @@ func (s SignedRow) ToTable() (*pb.TableResponse, error) { // ToRows implements the ToRowser interface. func (s SignedRow) ToRows(callback func(*pb.RowResponse) error) error { - // TODO: address the overflow issue with values outside the int64 range + ci := []*pb.ColumnInfo{{Name: s.Field(), Datatype: "int64"}} negs := s.Neg.Columns() for i := len(negs) - 1; i >= 0; i-- { + val, err := toNegInt64(negs[i]) + if err != nil { + return errors.Wrap(err, "converting uint64 to int64 (negative)") + } + if err := callback(&pb.RowResponse{ Headers: ci, Columns: []*pb.ColumnResponse{ - &pb.ColumnResponse{ColumnVal: &pb.ColumnResponse_Int64Val{Int64Val: -1 * int64(negs[i])}}, - }}); err != nil { + &pb.ColumnResponse{ColumnVal: &pb.ColumnResponse_Int64Val{Int64Val: val}}, + }, + }); err != nil { return errors.Wrap(err, "calling callback") } ci = nil } for _, id := range s.Pos.Columns() { + val, err := toInt64(id) + if err != nil { + return errors.Wrap(err, "converting uint64 to int64 (positive)") + } + if err := callback(&pb.RowResponse{ Headers: ci, Columns: []*pb.ColumnResponse{ - &pb.ColumnResponse{ColumnVal: &pb.ColumnResponse_Int64Val{Int64Val: int64(id)}}, - }}); err != nil { + &pb.ColumnResponse{ColumnVal: &pb.ColumnResponse_Int64Val{Int64Val: val}}, + }, + }); err != nil { return errors.Wrap(err, "calling callback") } ci = nil @@ -4467,6 +4682,31 @@ func (s SignedRow) ToRows(callback func(*pb.RowResponse) error) error { return nil } +func toNegInt64(n uint64) (int64, error) { + const absMinInt64 = uint64(1 << 63) + + if n > absMinInt64 { + return 0, errors.Errorf("value %d overflows int64", n) + } + + if n == absMinInt64 { + return int64(-1 << 63), nil + } + + // n < 1 << 63 + return -int64(n), nil +} + +func toInt64(n uint64) (int64, error) { + const maxInt64 = uint64(1<<63) - 1 + + if n > maxInt64 { + return 0, errors.Errorf("value %d overflows int64", n) + } + + return int64(n), nil +} + func (sr *SignedRow) union(other SignedRow) SignedRow { ret := SignedRow{&Row{}, &Row{}, ""} @@ -4720,6 +4960,7 @@ func isValidID(v interface{}) bool { // calls). type groupByIterator struct { executor *executor + tx Tx index string shard uint64 @@ -4751,9 +4992,10 @@ type groupByIterator struct { } // newGroupByIterator initializes a new groupByIterator. -func newGroupByIterator(executor *executor, rowIDs []RowIDs, children []*pql.Call, aggregate *pql.Call, filter *Row, index string, shard uint64, holder *Holder) (*groupByIterator, error) { +func newGroupByIterator(executor *executor, tx Tx, rowIDs []RowIDs, children []*pql.Call, aggregate *pql.Call, filter *Row, index string, shard uint64, holder *Holder) (_ *groupByIterator, err error) { gbi := &groupByIterator{ executor: executor, + tx: tx, index: index, shard: shard, rowIters: make([]rowIterator, len(children)), @@ -4804,7 +5046,10 @@ func newGroupByIterator(executor *executor, rowIDs []RowIDs, children []*pql.Cal if len(rowIDs[i]) > 0 { filters = append(filters, filterWithRows(rowIDs[i])) } - gbi.rowIters[i] = frag.rowIterator(i != 0, filters...) + gbi.rowIters[i], err = frag.rowIterator(tx, i != 0, filters...) + if err != nil { + return nil, err + } prev, hasPrev, err := call.UintArg("previous") if err != nil { @@ -4815,8 +5060,10 @@ func newGroupByIterator(executor *executor, rowIDs []RowIDs, children []*pql.Cal } gbi.rowIters[i].Seek(prev) } - nextRow, rowID, value, wrapped := gbi.rowIters[i].Next() - if nextRow == nil { + nextRow, rowID, value, wrapped, err := gbi.rowIters[i].Next() + if err != nil { + return nil, err + } else if nextRow == nil { gbi.done = true return gbi, nil } @@ -4834,8 +5081,10 @@ func newGroupByIterator(executor *executor, rowIDs []RowIDs, children []*pql.Cal // previous field, and if that one wraps we need to keep going // backward. for j := i - 1; j >= 0; j-- { - nextRow, rowID, value, wrapped := gbi.rowIters[j].Next() - if nextRow == nil { + nextRow, rowID, value, wrapped, err := gbi.rowIters[j].Next() + if err != nil { + return nil, err + } else if nextRow == nil { gbi.done = true return gbi, nil } @@ -4869,8 +5118,10 @@ func (gbi *groupByIterator) nextAtIdx(ctx context.Context, i int) (err error) { if err = ctx.Err(); err != nil { return err } - nr, rowID, value, wrapped := gbi.rowIters[i].Next() - if nr == nil { + nr, rowID, value, wrapped, err := gbi.rowIters[i].Next() + if err != nil { + return err + } else if nr == nil { gbi.done = true return nil } @@ -4923,7 +5174,7 @@ func (gbi *groupByIterator) Next(ctx context.Context) (ret GroupCount, done bool switch gbi.aggregate.Name { case "Sum": - result, err := gbi.executor.executeSumCountShard(ctx, gbi.index, gbi.aggregate, filter, gbi.shard) + result, err := gbi.executor.executeSumCountShard(ctx, gbi.tx, gbi.index, gbi.aggregate, filter, gbi.shard) if err != nil { return ret, false, err } diff --git a/executor_internal_test.go b/executor_internal_test.go index 86ff6cdde..28dd369ef 100644 --- a/executor_internal_test.go +++ b/executor_internal_test.go @@ -133,6 +133,71 @@ func TestExecutor_TranslateGroupByCall(t *testing.T) { } } +func TestExecutor_TranslateRowsOnBool(t *testing.T) { + holder := NewHolder(DefaultPartitionN) + defer holder.Close() + + tx, err := holder.Begin(true) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + + e := &executor{ + Holder: holder, + Cluster: NewTestCluster(1), + } + e.Holder.Path, _ = ioutil.TempDir(*TempDir, "") + if err := e.Holder.Open(); err != nil { + t.Fatalf("opening holder: %v", err) + } + + idx, err := e.Holder.CreateIndex("i", IndexOptions{}) + if err != nil { + t.Fatalf("creating index: %v", err) + } + + fb, errb := idx.CreateField("b", OptFieldTypeBool()) + _, errbk := idx.CreateField("bk", OptFieldTypeBool(), OptFieldKeys()) + if errb != nil || errbk != nil { + t.Fatalf("creating fields %v, %v", errb, errbk) + } + + _, err1 := fb.SetBit(tx, 1, 1, nil) + _, err2 := fb.SetBit(tx, 2, 2, nil) + _, err3 := fb.SetBit(tx, 3, 3, nil) + if err1 != nil || err2 != nil || err3 != nil { + t.Fatalf("setting bit %v, %v, %v", err1, err2, err3) + } + + if err := tx.Commit(); err != nil { + t.Fatal(err) + } + + tests := []struct { + pql string + }{ + {pql: "Rows(b)"}, + {pql: "GroupBy(Rows(b))"}, + {pql: "Set(4, b=true)"}, + } + + for _, test := range tests { + t.Run(test.pql, func(t *testing.T) { + query, err := pql.ParseString(test.pql) + if err != nil { + t.Fatalf("parsing query: %v", err) + } + + c := query.Calls[0] + err = e.translateCall(context.Background(), "i", c, make(map[string]map[string]uint64)) + if err != nil { + t.Fatalf("translating call: %v", err) + } + }) + } +} + func isInt(a interface{}) bool { switch a.(type) { case int, int64, uint, uint64: @@ -439,3 +504,71 @@ func TestValCountComparisons(t *testing.T) { }) } } + +func TestToNegInt64(t *testing.T) { + tests := []struct { + u64 uint64 + i64 int64 + overflow bool + }{ + { + u64: uint64(1 << 63), + i64: int64(-1 << 63), + }, + { + u64: uint64(1<<63) - 1, + i64: int64(-1<<63) + 1, + }, + { + u64: uint64(1<<63) + 1, + overflow: true, + }, + } + + for _, tc := range tests { + val, err := toNegInt64(tc.u64) + if err != nil && !tc.overflow { + t.Fatalf("error: %+v, expected: %+v", err, tc) + } + + if val != tc.i64 { + t.Fatalf("Expected: %+v, Got: %+v", tc.i64, val) + } + } +} + +func TestToInt64(t *testing.T) { + tests := []struct { + u64 uint64 + i64 int64 + overflow bool + }{ + { + u64: uint64(1<<63) - 1, + i64: 1<<63 - 1, + }, + { + u64: uint64(0), + i64: 0, + }, + { + u64: uint64(1 << 63), + overflow: true, + }, + { + u64: 1<<64 - 1, + overflow: true, + }, + } + + for _, tc := range tests { + val, err := toInt64(tc.u64) + if err != nil && !tc.overflow { + t.Fatalf("error: %+v, expected: %+v", err, tc) + } + + if val != tc.i64 { + t.Fatalf("Expected: %+v, Got: %+v", tc.i64, val) + } + } +} diff --git a/executor_test.go b/executor_test.go index 6bf3f2a14..4a39a7713 100644 --- a/executor_test.go +++ b/executor_test.go @@ -903,8 +903,15 @@ func TestExecutor_Execute_SetValue(t *testing.T) { t.Fatal(err) } + // Obtain transaction. + tx, err := hldr.Begin(false) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + f := hldr.Field("i", "f") - if value, exists, err := f.Value(10); err != nil { + if value, exists, err := f.Value(tx, 10); err != nil { t.Fatal(err) } else if !exists { t.Fatal("expected value to exist") @@ -912,7 +919,7 @@ func TestExecutor_Execute_SetValue(t *testing.T) { t.Fatalf("unexpected value: %v", value) } - if value, exists, err := f.Value(100); err != nil { + if value, exists, err := f.Value(tx, 100); err != nil { t.Fatal(err) } else if !exists { t.Fatal("expected value to exist") @@ -3027,6 +3034,121 @@ func TestExecutor_Execute_Remote_Row(t *testing.T) { test.CheckGroupBy(t, expected, results) } }) + + t.Run("Row on ints with ASSIGN condition", func(t *testing.T) { + _, err := c[0].API.CreateIndex(context.Background(), "intidx", pilosa.IndexOptions{}) + if err != nil { + t.Fatalf("creating index: %v", err) + } + + _, err = c[0].API.CreateField(context.Background(), "intidx", "gint", pilosa.OptFieldTypeInt(-1000, 1000)) + if err != nil { + t.Fatalf("creating field: %v", err) + } + if _, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{Index: "intidx", Query: ` + Set(1000, gint=1) + Set(2000, gint=2) + Set(3000, gint=3) + `}); err != nil { + t.Fatalf("querying remote: %v", err) + } + + if res, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{ + Index: "intidx", + Query: `Row(gint=2)Row(gint==1)`, + }); err != nil { + t.Fatalf("Row querying: %v", err) + } else { + + row0, row1 := res.Results[0].(*pilosa.Row), res.Results[1].(*pilosa.Row) + if len(row0.Columns()) != 1 || len(row1.Columns()) != 1 { + t.Fatalf(`Expected: []uint64{2000} []uint64{1000}, Got: %+v %+v`, row0.Columns(), row1.Columns()) + } + if row0.Columns()[0] != 2000 || row1.Columns()[0] != 1000 { + t.Fatalf(`Expected: []uint64{2000} []uint64{1000}, Got: %+v %+v`, row0.Columns(), row1.Columns()) + } + } + }) + + t.Run("Row on decimals with ASSIGN condition", func(t *testing.T) { + _, err := c[0].API.CreateIndex(context.Background(), "decidx", pilosa.IndexOptions{}) + if err != nil { + t.Fatalf("creating index: %v", err) + } + + _, err = c[0].API.CreateField(context.Background(), "decidx", "fdec", pilosa.OptFieldTypeDecimal(0)) + if err != nil { + t.Fatalf("creating field: %v", err) + } + if _, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{Index: "decidx", Query: ` + Set(11, fdec=1.1) + Set(22, fdec=2.2) + Set(33, fdec=3.3) + `}); err != nil { + t.Fatalf("querying remote: %v", err) + } + + if res, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{ + Index: "decidx", + Query: `Row(fdec=2.2)Row(fdec==1.1)`, + }); err != nil { + t.Fatalf("Row querying: %v", err) + } else { + row0, row1 := res.Results[0].(*pilosa.Row), res.Results[1].(*pilosa.Row) + if len(row0.Columns()) != 1 || len(row1.Columns()) != 1 { + t.Fatalf(`Expected: []uint64{22} []uint64{11}, Got: %+v %+v`, row0.Columns(), row1.Columns()) + } + if row0.Columns()[0] != 22 || row1.Columns()[0] != 11 { + t.Fatalf(`Expected: []uint64{22} []uint64{11}, Got: %+v %+v`, row0.Columns(), row1.Columns()) + } + } + }) + + t.Run("Row on foreign key with ASSIGN condition", func(t *testing.T) { + _, err := c[0].API.CreateIndex(context.Background(), "parent", pilosa.IndexOptions{Keys: true}) + if err != nil { + t.Fatalf("creating index: %v", err) + } + _, err = c[0].API.CreateField(context.Background(), "parent", "general", pilosa.OptFieldTypeSet(pilosa.DefaultCacheType, pilosa.DefaultCacheSize)) + if err != nil { + t.Fatalf("creating field: %v", err) + } + _, err = c[0].API.CreateIndex(context.Background(), "child", pilosa.IndexOptions{Keys: false}) + if err != nil { + t.Fatalf("creating index: %v", err) + } + _, err = c[0].API.CreateField(context.Background(), "child", "parentid", + pilosa.OptFieldForeignIndex("parent"), + pilosa.OptFieldTypeInt(-9223372036854775808, 9223372036854775807), + ) + if err != nil { + t.Fatalf("creating field: %v", err) + } + + if _, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{Index: "child", Query: ` + Set(1, parentid="one") + Set(2, parentid="two") + Set(3, parentid="three") + `}); err != nil { + t.Fatalf("querying remote: %v", err) + } + + if res, err := c[1].API.Query(context.Background(), &pilosa.QueryRequest{ + Index: "child", + Query: `Row(parentid="two")Row(parentid=="one")`, + }); err != nil { + t.Fatalf("Row querying: %v", err) + } else { + + row0, row1 := res.Results[0].(*pilosa.Row), res.Results[1].(*pilosa.Row) + if len(row0.Columns()) != 1 || len(row1.Columns()) != 1 { + t.Fatalf(`Expected: []uint64{1} []uint64{0}, Got: %+v %+v`, row0.Columns(), row1.Columns()) + } + if row0.Columns()[0] != 2 || row1.Columns()[0] != 1 { + t.Fatalf(`Expected: []uint64{1} []uint64{0}, Got: %+v %+v`, row0.Columns(), row1.Columns()) + } + } + }) } // Ensure executor returns an error if too many writes are in a single request. @@ -3407,7 +3529,6 @@ func TestExecutor_Execute_Not(t *testing.T) { func TestExecutor_Execute_FieldValue(t *testing.T) { c := test.MustRunCluster(t, 2) defer c.Close() - //hldr := test.Holder{Holder: c[0].Server.Holder()} node0 := c[0] node1 := c[1] @@ -3420,8 +3541,8 @@ func TestExecutor_Execute_FieldValue(t *testing.T) { Set(1, f=3) Set(2, f=-4) Set(` + strconv.Itoa(ShardWidth+1) + `, f=3) - Set(1, dec=12.985) - Set(2, dec=-4.234) + Set(1, dec=12.985) + Set(2, dec=-4.234) `}); err != nil { t.Fatal(err) } @@ -3433,8 +3554,8 @@ func TestExecutor_Execute_FieldValue(t *testing.T) { if _, err := node0.API.Query(context.Background(), &pilosa.QueryRequest{Index: "ik", Query: ` Set("one", f=3) Set("two", f=-4) - Set("one", dec=12.985) - Set("two", dec=-4.234) + Set("one", dec=12.985) + Set("two", dec=-4.234) `}); err != nil { t.Fatal(err) } @@ -3462,6 +3583,8 @@ func TestExecutor_Execute_FieldValue(t *testing.T) { // Errors {index: "i", qry: "FieldValue()", expErr: pilosa.ErrFieldRequired.Error()}, + {index: "i", qry: "FieldValue(field=dec)", expErr: pilosa.ErrColumnRequired.Error()}, + {index: "ik", qry: "FieldValue(field=f)", expErr: pilosa.ErrColumnRequired.Error()}, } for n, node := range []*test.Command{node0, node1} { for i, test := range tests { @@ -4619,6 +4742,10 @@ func TestExecutor_Execute_Rows_Keys(t *testing.T) { q: `Rows(f, previous="1", limit=0, column="0")`, exp: []string{}, }, + { + q: `Rows(f, like="__")`, + exp: []string{"10", "11", "12", "13", "14", "15", "16", "17", "18"}, + }, } for i, test := range tests { @@ -5173,6 +5300,10 @@ func runCallTest(t *testing.T, writeQuery string, readQueries []string, indexOpt return responses } +// NOTE: The shift function in its current state is unsupported. +// If any of these tests fail due to improvements made to the roaring +// code, it is reasonable to remove these tests. See the `Shift()` +// method on `Row` in `row.go`. func TestExecutor_Execute_Shift(t *testing.T) { t.Run("Shift Bit 0", func(t *testing.T) { c := test.MustRunCluster(t, 1) @@ -5715,3 +5846,67 @@ func TestExecutor_Execute_TopNDistinct(t *testing.T) { } }) } + +func Test_Executor_Execute_UnionRows(t *testing.T) { + c := test.MustRunCluster(t, 2) + defer c.Close() + + c.CreateField(t, "i", pilosa.IndexOptions{}, "s", + pilosa.OptFieldTypeSet(pilosa.CacheTypeRanked, 50000), + ) + + // Populate data. + c.Query(t, "i", ` + Set(0, s=1) + Set(1, s=2) + Set(2, s=3) + Set(3, s=1) + Set(3, s=5) + `) + + if res := c.Query(t, "i", `Count(UnionRows(TopN(s, n=1)))`); res.Results[0] != uint64(2) { + t.Errorf("expected 2 columns, got %v", res.Results[0]) + } + if res := c.Query(t, "i", `Count(UnionRows(Rows(s)))`); res.Results[0] != uint64(4) { + t.Errorf("expected 4 columns, got %v", res.Results[0]) + } +} + +func TestTimelessClearRegression(t *testing.T) { + data, err := ioutil.ReadFile("testdata/timeRegressionSchema.json") + if err != nil { + t.Fatal(err) + } + + c := test.MustRunCluster(t, 1) + defer c.Close() + + api := c[0].API + + schema := &pilosa.Schema{} + if err := json.NewDecoder(bytes.NewReader(data)).Decode(schema); err != nil { + t.Fatal(err) + } + if err := api.ApplySchema(context.TODO(), schema, false); err != nil { + t.Fatal(err) + } + + idxName := schema.Indexes[0].Name + + setQuery := `Set(511, stargazer=376)` + if _, err := api.Query(context.TODO(), &pilosa.QueryRequest{Index: idxName, Query: setQuery}); err != nil { + t.Fatal(err) + } + + setQuery = `Set(512, stargazer=300, 2017-05-18T00:00)` + if _, err := api.Query(context.TODO(), &pilosa.QueryRequest{Index: idxName, Query: setQuery}); err != nil { + t.Fatal(err) + } + + clearQuery := `Clear(511, stargazer=376)` + if res, err := api.Query(context.TODO(), &pilosa.QueryRequest{Index: idxName, Query: clearQuery}); err != nil { + t.Fatal(err) + } else if res.Results[0] != true { + t.Fatal("clear supposedly failed") + } +} diff --git a/field.go b/field.go index 84bdbec73..956fbd452 100644 --- a/field.go +++ b/field.go @@ -31,7 +31,6 @@ import ( "github.com/gogo/protobuf/proto" "github.com/pilosa/pilosa/v2/internal" - "github.com/pilosa/pilosa/v2/logger" "github.com/pilosa/pilosa/v2/pql" "github.com/pilosa/pilosa/v2/roaring" "github.com/pilosa/pilosa/v2/stats" @@ -86,11 +85,12 @@ var availableShardFileFlushDuration = &protected{ // Field represents a container for views. type Field struct { - mu sync.RWMutex - createdAt int64 - path string - index string - name string + mu sync.RWMutex + createdAt int64 + path string + index string + name string + qualifiedName string viewMap map[string]*view @@ -117,10 +117,6 @@ type Field struct { // Shards with data on any node in the cluster, according to this node. remoteAvailableShards *roaring.Bitmap - logger logger.Logger - - snapshotQueue snapshotQueue - translateStore TranslateStore // Instantiates new translation stores @@ -338,17 +334,17 @@ func OptFieldTypeBool() FieldOption { // that it's of the type `OptFieldType*`). This means // this function couldn't be used to set, for example, // `FieldOptions.Keys`. -func NewField(path, index, name string, opts FieldOption) (*Field, error) { +func NewField(holder *Holder, path, index, name string, opts FieldOption) (*Field, error) { err := validateName(name) if err != nil { return nil, errors.Wrap(err, "validating name") } - return newField(path, index, name, opts) + return newField(holder, path, index, name, opts) } // newField returns a new instance of field (without name validation). -func newField(path, index, name string, opts FieldOption) (*Field, error) { +func newField(holder *Holder, path, index, name string, opts FieldOption) (*Field, error) { // Apply functional option. fo := FieldOptions{} err := opts(&fo) @@ -357,9 +353,10 @@ func newField(path, index, name string, opts FieldOption) (*Field, error) { } f := &Field{ - path: path, - index: index, - name: name, + path: path, + index: index, + name: name, + qualifiedName: FormatQualifiedFieldName(index, name), viewMap: make(map[string]*view), @@ -372,7 +369,7 @@ func newField(path, index, name string, opts FieldOption) (*Field, error) { remoteAvailableShards: roaring.NewBitmap(), - logger: logger.NopLogger, + holder: holder, OpenTranslateStore: OpenInMemTranslateStore, } @@ -448,7 +445,7 @@ func (f *Field) loadAvailableShards() error { } // some other problem: if err != nil { - f.logger.Printf("available shards file present but unreadable, discarding: %v", err) + f.holder.Logger.Printf("available shards file present but unreadable, discarding: %v", err) err = os.Remove(path) if err != nil { return errors.Wrap(err, "deleting corrupt available shards list") @@ -457,7 +454,7 @@ func (f *Field) loadAvailableShards() error { } bm := roaring.NewBitmap() if err = bm.UnmarshalBinary(buf); err != nil { - f.logger.Printf("available shards file corrupt, discarding: %v", err) + f.holder.Logger.Printf("available shards file corrupt, discarding: %v", err) err = os.Remove(path) if err != nil { return errors.Wrap(err, "deleting corrupt available shards list") @@ -548,17 +545,17 @@ func (f *Field) Options() FieldOptions { func (f *Field) Open() error { if err := func() (err error) { // Ensure the field's path exists. - f.logger.Debugf("ensure field path exists: %s", f.path) + f.holder.Logger.Debugf("ensure field path exists: %s", f.path) if err := os.MkdirAll(f.path, 0777); err != nil { return errors.Wrap(err, "creating field dir") } - f.logger.Debugf("load meta file for index/field: %s/%s", f.index, f.name) + f.holder.Logger.Debugf("load meta file for index/field: %s/%s", f.index, f.name) if err := f.loadMeta(); err != nil { return errors.Wrap(err, "loading meta") } - f.logger.Debugf("load available shards for index/field: %s/%s", f.index, f.name) + f.holder.Logger.Debugf("load available shards for index/field: %s/%s", f.index, f.name) if err := f.loadAvailableShards(); err != nil { return errors.Wrap(err, "loading available shards") } @@ -570,17 +567,17 @@ func (f *Field) Open() error { } // Apply the field options loaded from meta (or set via setOptions()). - f.logger.Debugf("apply options for index/field: %s/%s", f.index, f.name) + f.holder.Logger.Debugf("apply options for index/field: %s/%s", f.index, f.name) if err := f.applyOptions(f.options); err != nil { return errors.Wrap(err, "applying options") } - f.logger.Debugf("open views for index/field: %s/%s", f.index, f.name) + f.holder.Logger.Debugf("open views for index/field: %s/%s", f.index, f.name) if err := f.openViews(); err != nil { return errors.Wrap(err, "opening views") } - f.logger.Debugf("open row attribute store for index/field: %s/%s", f.index, f.name) + f.holder.Logger.Debugf("open row attribute store for index/field: %s/%s", f.index, f.name) if err := f.rowAttrStore.Open(); err != nil { return errors.Wrap(err, "opening attrstore") } @@ -607,7 +604,7 @@ func (f *Field) Open() error { return err } - f.logger.Debugf("successfully opened field index/field: %s/%s", f.index, f.name) + f.holder.Logger.Debugf("successfully opened field index/field: %s/%s", f.index, f.name) return nil } func blockingWriteAvailableShards(fieldPath string, availableShardBytes []byte) { @@ -748,7 +745,7 @@ fileLoop: <-fieldQueue }() name := filepath.Base(fi.Name()) - f.logger.Debugf("open index/field/view: %s/%s/%s", f.index, f.name, fi.Name()) + f.holder.Logger.Debugf("open index/field/view: %s/%s/%s", f.index, f.name, fi.Name()) view := f.newView(f.viewPath(name), name) if err := view.open(); err != nil { return fmt.Errorf("opening view: view=%s, err=%s", view.name, err) @@ -770,7 +767,7 @@ fileLoop: } view.rowAttrStore = f.rowAttrStore - f.logger.Debugf("add index/field/view to field.viewMap: %s/%s/%s", f.index, f.name, view.name) + f.holder.Logger.Debugf("add index/field/view to field.viewMap: %s/%s/%s", f.index, f.name, view.name) mu.Lock() f.viewMap[view.name] = view mu.Unlock() @@ -1093,7 +1090,7 @@ func (f *Field) setTimeQuantum(q TimeQuantum) error { // RowTime gets the row at the particular time with the granularity specified by // the quantum. -func (f *Field) RowTime(rowID uint64, time time.Time, quantum string) (*Row, error) { +func (f *Field) RowTime(tx Tx, rowID uint64, time time.Time, quantum string) (*Row, error) { if !TimeQuantum(quantum).Valid() { return nil, ErrInvalidTimeQuantum } @@ -1102,7 +1099,7 @@ func (f *Field) RowTime(rowID uint64, time time.Time, quantum string) (*Row, err if view == nil { return nil, errors.Errorf("view with quantum %v not found.", quantum) } - return view.row(rowID), nil + return view.row(tx, rowID) } // viewPath returns the path to a view in the field. @@ -1183,14 +1180,10 @@ func (f *Field) createViewIfNotExistsBase(name string) (*view, bool, error) { } func (f *Field) newView(path, name string) *view { - view := newView(path, f.index, f.name, name, f.options) - view.logger = f.logger + view := newView(f.holder, path, f.index, f.name, name, f.options) view.rowAttrStore = f.rowAttrStore view.stats = f.Stats view.broadcaster = f.broadcaster - if f.snapshotQueue != nil { - view.snapshotQueue = f.snapshotQueue - } return view } @@ -1221,21 +1214,21 @@ func (f *Field) deleteView(name string) error { // package, and the fact that it's only allowed on // `set`,`mutex`, and `bool` fields is odd. This may // be considered for deprecation in a future version. -func (f *Field) Row(rowID uint64) (*Row, error) { +func (f *Field) Row(tx Tx, rowID uint64) (*Row, error) { switch f.Type() { case FieldTypeSet, FieldTypeMutex, FieldTypeBool: view := f.view(viewStandard) if view == nil { return nil, ErrInvalidView } - return view.row(rowID), nil + return view.row(tx, rowID) default: return nil, errors.Errorf("row method unsupported for field type: %s", f.Type()) } } // SetBit sets a bit on a view within the field. -func (f *Field) SetBit(rowID, colID uint64, t *time.Time) (changed bool, err error) { +func (f *Field) SetBit(tx Tx, rowID, colID uint64, t *time.Time) (changed bool, err error) { viewName := viewStandard if !f.options.NoStandardView { // Retrieve view. Exit if it doesn't exist. @@ -1245,7 +1238,7 @@ func (f *Field) SetBit(rowID, colID uint64, t *time.Time) (changed bool, err err } // Set non-time bit. - if v, err := view.setBit(rowID, colID); err != nil { + if v, err := view.setBit(tx, rowID, colID); err != nil { return changed, errors.Wrap(err, "setting on view") } else if v { changed = v @@ -1264,7 +1257,7 @@ func (f *Field) SetBit(rowID, colID uint64, t *time.Time) (changed bool, err err return changed, errors.Wrapf(err, "creating view %s", subname) } - if c, err := view.setBit(rowID, colID); err != nil { + if c, err := view.setBit(tx, rowID, colID); err != nil { return changed, errors.Wrapf(err, "setting on view %s", subname) } else if c { changed = true @@ -1275,21 +1268,20 @@ func (f *Field) SetBit(rowID, colID uint64, t *time.Time) (changed bool, err err } // ClearBit clears a bit within the field. -func (f *Field) ClearBit(rowID, colID uint64) (changed bool, err error) { +func (f *Field) ClearBit(tx Tx, rowID, colID uint64) (changed bool, err error) { viewName := viewStandard // Retrieve view. Exit if it doesn't exist. view, present := f.viewMap[viewName] if !present { - return changed, errors.Wrap(err, "clearing missing view") - + return false, errors.Wrap(err, "clearing missing view") } // Clear non-time bit. - if v, err := view.clearBit(rowID, colID); err != nil { - return changed, errors.Wrap(err, "clearing on view") + if v, err := view.clearBit(tx, rowID, colID); err != nil { + return false, errors.Wrap(err, "clearing on view") } else if v { - changed = v + changed = changed || v } if len(f.viewMap) == 1 { // assuming no time views return changed, nil @@ -1304,10 +1296,12 @@ func (f *Field) ClearBit(rowID, colID uint64) (changed bool, err error) { level-- } if level < skipAbove { - if changed, err = view.clearBit(rowID, colID); err != nil { + cleared, err := view.clearBit(tx, rowID, colID) + changed = changed || cleared + if err != nil { return changed, errors.Wrapf(err, "clearing on view %s", view.name) } - if !changed { + if !cleared { skipAbove = level + 1 } else { skipAbove = maxInt @@ -1362,52 +1356,21 @@ func (f *Field) allTimeViewsSortedByQuantum() (me []*view) { // StringValue reads an integer field value for a column, and converts // it to a string based on a foreign index string key. -func (f *Field) StringValue(columnID uint64) (value string, exists bool, err error) { +func (f *Field) StringValue(tx Tx, columnID uint64) (value string, exists bool, err error) { bsig := f.bsiGroup(f.name) if bsig == nil { return value, false, ErrBSIGroupNotFound } - val, exists, err := f.Value(columnID) + val, exists, err := f.Value(tx, columnID) if exists { value, err = f.translateStore.TranslateID(uint64(val)) } return value, exists, err } -// FloatValue reads an integer field value for a column, and converts -// it to a float based on the configured scale. -func (f *Field) FloatValue(columnID uint64) (value float64, exists bool, err error) { - bsig := f.bsiGroup(f.name) - if bsig == nil { - return 0, false, ErrBSIGroupNotFound - } - - val, exists, err := f.Value(columnID) - if exists { - value = float64(val) / math.Pow10(int(bsig.Scale)) - } - return value, exists, err -} - -// DecimalValue reads a decimal field value for a column, and converts -// it to a pql.Decimal based on the configured scale. -func (f *Field) DecimalValue(columnID uint64) (value pql.Decimal, exists bool, err error) { - bsig := f.bsiGroup(f.name) - if bsig == nil { - return value, false, ErrBSIGroupNotFound - } - - val, exists, err := f.Value(columnID) - if exists { - value.Value = val - value.Scale = bsig.Scale - } - return value, exists, err -} - // Value reads a field value for a column. -func (f *Field) Value(columnID uint64) (value int64, exists bool, err error) { +func (f *Field) Value(tx Tx, columnID uint64) (value int64, exists bool, err error) { bsig := f.bsiGroup(f.name) if bsig == nil { return 0, false, ErrBSIGroupNotFound @@ -1419,7 +1382,7 @@ func (f *Field) Value(columnID uint64) (value int64, exists bool, err error) { return 0, false, nil } - v, exists, err := view.value(columnID, bsig.BitDepth) + v, exists, err := view.value(tx, columnID, bsig.BitDepth) if err != nil { return 0, false, err } else if !exists { @@ -1428,20 +1391,8 @@ func (f *Field) Value(columnID uint64) (value int64, exists bool, err error) { return int64(v) + bsig.Base, true, nil } -// SetFloatValue takes a floating point value, and converts it to an -// integer based on the field's configured scale, before setting that -// integer via SetValue. -func (f *Field) SetFloatValue(columnID uint64, value float64) (changed bool, err error) { - bsig := f.bsiGroup(f.name) - if bsig == nil { - return false, ErrBSIGroupNotFound - } - val := int64(float64(value) * math.Pow10(int(bsig.Scale))) - return f.SetValue(columnID, val) -} - // SetValue sets a field value for a column. -func (f *Field) SetValue(columnID uint64, value int64) (changed bool, err error) { +func (f *Field) SetValue(tx Tx, columnID uint64, value int64) (changed bool, err error) { // Fetch bsiGroup & validate min/max. bsig := f.bsiGroup(f.name) if bsig == nil { @@ -1481,11 +1432,11 @@ func (f *Field) SetValue(columnID uint64, value int64) (changed bool, err error) if err != nil { return false, errors.Wrap(err, "creating view") } - return view.setValue(columnID, bsig.BitDepth, baseValue) + return view.setValue(tx, columnID, bsig.BitDepth, baseValue) } // ClearValue removes a field value for a column. -func (f *Field) ClearValue(columnID uint64) (changed bool, err error) { +func (f *Field) ClearValue(tx Tx, columnID uint64) (changed bool, err error) { bsig := f.bsiGroup(f.name) if bsig == nil { return false, ErrBSIGroupNotFound @@ -1495,109 +1446,17 @@ func (f *Field) ClearValue(columnID uint64) (changed bool, err error) { if view == nil { return false, nil } - value, exists, err := view.value(columnID, bsig.BitDepth) + value, exists, err := view.value(tx, columnID, bsig.BitDepth) if err != nil { return false, err } if exists { - return view.clearValue(columnID, bsig.BitDepth, value) + return view.clearValue(tx, columnID, bsig.BitDepth, value) } return false, nil } -// FloatSum performs a Sum query and converts the result to a float -// based on the field's configured scale. -func (f *Field) FloatSum(filter *Row, name string) (sum float64, count int64, err error) { - bsig := f.bsiGroup(f.name) - if bsig == nil { - return 0, 0, ErrBSIGroupNotFound - } - - sumI, count, err := f.Sum(filter, name) - if err == nil { - sum = float64(sumI) / math.Pow10(int(bsig.Scale)) - } - return sum, count, err - -} - -// Sum returns the sum and count for a field. -// An optional filtering row can be provided. -func (f *Field) Sum(filter *Row, name string) (sum, count int64, err error) { - bsig := f.bsiGroup(name) - if bsig == nil { - return 0, 0, ErrBSIGroupNotFound - } - - view := f.view(viewBSIGroupPrefix + name) - if view == nil { - return 0, 0, nil - } - - vsum, vcount, err := view.sum(filter, bsig.BitDepth) - if err != nil { - return 0, 0, err - } - return int64(vsum) + (int64(vcount) * bsig.Base), int64(vcount), nil -} - -// FloatMin performs a Min query and converts the result to a float -// based on the field's configured scale. -// TODO: this and Min are probably worthless -func (f *Field) FloatMin(filter *Row, name string) (min float64, count int64, err error) { - bsig := f.bsiGroup(f.name) - if bsig == nil { - return 0, 0, ErrBSIGroupNotFound - } - - minI, count, err := f.Min(filter, name) - if err == nil { - min = float64(minI) / math.Pow10(int(bsig.Scale)) - } - return min, count, err -} - -// Min returns the min for a field. -// An optional filtering row can be provided. -func (f *Field) Min(filter *Row, name string) (min, count int64, err error) { - bsig := f.bsiGroup(name) - if bsig == nil { - return 0, 0, ErrBSIGroupNotFound - } - - view := f.view(viewBSIGroupPrefix + name) - if view == nil { - return 0, 0, nil - } - - vmin, vcount, err := view.min(filter, bsig.BitDepth) - if err != nil { - return 0, 0, err - } - return int64(vmin) + bsig.Base, int64(vcount), nil -} - -// FloatMax performs a max query and converts the result to a float -// based on the field's configured scale. -// -// TODO, this isn't really used, because it's kind of useless. It will -// only get the max among shards on this node, but all query execution -// already happens at the shard level and bypasses this entirely -// calling fragment.max instead. -func (f *Field) FloatMax(filter *Row, name string) (max float64, count int64, err error) { - bsig := f.bsiGroup(f.name) - if bsig == nil { - return 0, 0, ErrBSIGroupNotFound - } - - maxI, count, err := f.Max(filter, name) - if err == nil { - max = float64(maxI) / math.Pow10(int(bsig.Scale)) - } - return max, count, err -} - -func (f *Field) MaxForShard(shard uint64, filter *Row) (ValCount, error) { +func (f *Field) MaxForShard(tx Tx, shard uint64, filter *Row) (ValCount, error) { bsig := f.bsiGroup(f.name) if bsig == nil { return ValCount{}, ErrBSIGroupNotFound @@ -1613,7 +1472,7 @@ func (f *Field) MaxForShard(shard uint64, filter *Row) (ValCount, error) { return ValCount{}, nil } - max, cnt, err := fragment.max(filter, bsig.BitDepth) + max, cnt, err := fragment.max(tx, filter, bsig.BitDepth) if err != nil { return ValCount{}, errors.Wrap(err, "calling fragment.max") } @@ -1633,7 +1492,7 @@ func (f *Field) MaxForShard(shard uint64, filter *Row) (ValCount, error) { // MinForShard returns the minimum value which appears in this shard // (this field must be an Int or Decimal field). It also returns the // number of times the minimum value appears. -func (f *Field) MinForShard(shard uint64, filter *Row) (ValCount, error) { +func (f *Field) MinForShard(tx Tx, shard uint64, filter *Row) (ValCount, error) { bsig := f.bsiGroup(f.name) if bsig == nil { return ValCount{}, ErrBSIGroupNotFound @@ -1649,7 +1508,7 @@ func (f *Field) MinForShard(shard uint64, filter *Row) (ValCount, error) { return ValCount{}, nil } - min, cnt, err := fragment.min(filter, bsig.BitDepth) + min, cnt, err := fragment.min(tx, filter, bsig.BitDepth) if err != nil { return ValCount{}, errors.Wrap(err, "calling fragment.min") } @@ -1666,28 +1525,8 @@ func (f *Field) MinForShard(shard uint64, filter *Row) (ValCount, error) { return valCount, nil } -// Max returns the max for a field. -// An optional filtering row can be provided. -func (f *Field) Max(filter *Row, name string) (max, count int64, err error) { - bsig := f.bsiGroup(name) - if bsig == nil { - return 0, 0, ErrBSIGroupNotFound - } - - view := f.view(viewBSIGroupPrefix + name) - if view == nil { - return 0, 0, nil - } - - vmax, vcount, err := view.max(filter, bsig.BitDepth) - if err != nil { - return 0, 0, err - } - return int64(vmax) + bsig.Base, int64(vcount), nil -} - // Range performs a conditional operation on Field. -func (f *Field) Range(name string, op pql.Token, predicate int64) (*Row, error) { +func (f *Field) Range(tx Tx, name string, op pql.Token, predicate int64) (*Row, error) { // Retrieve and validate bsiGroup. bsig := f.bsiGroup(name) if bsig == nil { @@ -1707,11 +1546,11 @@ func (f *Field) Range(name string, op pql.Token, predicate int64) (*Row, error) return NewRow(), nil } - return view.rangeOp(op, bsig.BitDepth, baseValue) + return view.rangeOp(tx, op, bsig.BitDepth, baseValue) } // Import bulk imports data. -func (f *Field) Import(rowIDs, columnIDs []uint64, timestamps []*time.Time, opts ...ImportOption) error { +func (f *Field) Import(tx Tx, rowIDs, columnIDs []uint64, timestamps []*time.Time, opts ...ImportOption) error { // Set up import options. options := &ImportOptions{} @@ -1783,7 +1622,7 @@ func (f *Field) Import(rowIDs, columnIDs []uint64, timestamps []*time.Time, opts return errors.Wrap(err, "creating fragment") } - if err := frag.bulkImport(data.RowIDs, data.ColumnIDs, options); err != nil { + if err := frag.bulkImport(tx, data.RowIDs, data.ColumnIDs, options); err != nil { return err } } @@ -1791,7 +1630,7 @@ func (f *Field) Import(rowIDs, columnIDs []uint64, timestamps []*time.Time, opts return nil } -func (f *Field) importFloatValue(columnIDs []uint64, values []float64, options *ImportOptions) error { +func (f *Field) importFloatValue(tx Tx, columnIDs []uint64, values []float64, options *ImportOptions) error { // convert values to int64 values based on scale ivalues := make([]int64, len(values)) bsig := f.bsiGroup(f.name) @@ -1803,11 +1642,11 @@ func (f *Field) importFloatValue(columnIDs []uint64, values []float64, options * ivalues[i] = int64(fval * mult) } // then call importValue - return f.importValue(columnIDs, ivalues, options) + return f.importValue(tx, columnIDs, ivalues, options) } // importValue bulk imports range-encoded value data. -func (f *Field) importValue(columnIDs []uint64, values []int64, options *ImportOptions) error { +func (f *Field) importValue(tx Tx, columnIDs []uint64, values []int64, options *ImportOptions) error { viewName := viewBSIGroupPrefix + f.name // Get the bsiGroup so we know bitDepth. bsig := f.bsiGroup(f.name) @@ -1890,7 +1729,7 @@ func (f *Field) importValue(columnIDs []uint64, values []int64, options *ImportO baseValues[i] = value - bsig.Base } - if err := frag.importValue(data.ColumnIDs, baseValues, requiredDepth, options.Clear); err != nil { + if err := frag.importValue(tx, data.ColumnIDs, baseValues, requiredDepth, options.Clear); err != nil { return err } } @@ -1922,7 +1761,7 @@ func (f *Field) importRoaring(ctx context.Context, data []byte, shard uint64, vi return nil } -func (f *Field) importRoaringOverwrite(ctx context.Context, data []byte, shard uint64, viewName string, block int) error { +func (f *Field) importRoaringOverwrite(ctx context.Context, tx Tx, data []byte, shard uint64, viewName string, block int) error { span, ctx := tracing.StartSpanFromContext(ctx, "Field.importRoaringOverwrite") defer span.Finish() @@ -1939,7 +1778,7 @@ func (f *Field) importRoaringOverwrite(ctx context.Context, data []byte, shard u if err != nil { return errors.Wrap(err, "creating fragment") } - if err := frag.importRoaringOverwrite(ctx, data, block); err != nil { + if err := frag.importRoaringOverwrite(ctx, tx, data, block); err != nil { return err } @@ -1948,9 +1787,14 @@ func (f *Field) importRoaringOverwrite(ctx context.Context, data []byte, shard u switch f.Options().Type { case FieldTypeInt, FieldTypeDecimal: frag.mu.Lock() - frag.calculateMaxRowID() - maxRowID, _ := frag.maxRow(nil) + if err := frag.calculateMaxRowID(); err != nil { + return err + } + maxRowID, _, err := frag.maxRow(tx, nil) frag.mu.Unlock() + if err != nil { + return err + } var bitDepth uint if maxRowID+1 > bsiOffsetBit { @@ -2305,3 +2149,8 @@ func bitDepthInt64(v int64) uint { } return bitDepth(uint64(v)) } + +// FormatQualifiedFieldName generates a qualified name for the field to be used with Tx operations. +func FormatQualifiedFieldName(index, field string) string { + return fmt.Sprintf("%s\x00%s\x00", index, field) +} diff --git a/field_internal_test.go b/field_internal_test.go index db4a3b5e7..8a5aaffe4 100644 --- a/field_internal_test.go +++ b/field_internal_test.go @@ -205,7 +205,7 @@ func NewTestField(t *testing.T, opts FieldOption) *TestField { if err != nil { t.Fatal(err) } - field, err := NewField(path, "i", "f", opts) + field, err := NewField(NewHolder(DefaultPartitionN), path, "i", "f", opts) if err != nil { t.Fatal(err) } @@ -235,7 +235,7 @@ func (f *TestField) Reopen() error { } path, index, name := f.Path(), f.Index(), f.Name() - f.Field, err = NewField(path, index, name, OptFieldTypeDefault()) + f.Field, err = NewField(NewHolder(DefaultPartitionN), path, index, name, OptFieldTypeDefault()) if err != nil { return err } @@ -246,15 +246,15 @@ func (f *TestField) Reopen() error { return nil } -func (f *TestField) MustSetBit(row, col uint64, ts ...time.Time) { +func (f *TestField) MustSetBit(tx Tx, row, col uint64, ts ...time.Time) { if len(ts) == 0 { - _, err := f.Field.SetBit(row, col, nil) + _, err := f.Field.SetBit(tx, row, col, nil) if err != nil { panic(err) } } for _, t := range ts { - _, err := f.Field.SetBit(row, col, &t) + _, err := f.Field.SetBit(tx, row, col, &t) if err != nil { panic(err) } @@ -310,41 +310,44 @@ func TestField_RowTime(t *testing.T) { f := OpenField(t, OptFieldTypeTime(TimeQuantum(""))) defer f.Close() + // Obtain transaction. + tx := &RoaringTx{Field: f.Field} + if err := f.setTimeQuantum(TimeQuantum("YMDH")); err != nil { t.Fatal(err) } - f.MustSetBit(1, 1, time.Date(2010, time.January, 5, 12, 0, 0, 0, time.UTC)) - f.MustSetBit(1, 2, time.Date(2011, time.January, 5, 12, 0, 0, 0, time.UTC)) - f.MustSetBit(1, 3, time.Date(2010, time.February, 5, 12, 0, 0, 0, time.UTC)) - f.MustSetBit(1, 4, time.Date(2010, time.January, 6, 12, 0, 0, 0, time.UTC)) - f.MustSetBit(1, 5, time.Date(2010, time.January, 5, 13, 0, 0, 0, time.UTC)) + f.MustSetBit(tx, 1, 1, time.Date(2010, time.January, 5, 12, 0, 0, 0, time.UTC)) + f.MustSetBit(tx, 1, 2, time.Date(2011, time.January, 5, 12, 0, 0, 0, time.UTC)) + f.MustSetBit(tx, 1, 3, time.Date(2010, time.February, 5, 12, 0, 0, 0, time.UTC)) + f.MustSetBit(tx, 1, 4, time.Date(2010, time.January, 6, 12, 0, 0, 0, time.UTC)) + f.MustSetBit(tx, 1, 5, time.Date(2010, time.January, 5, 13, 0, 0, 0, time.UTC)) - if r, err := f.RowTime(1, time.Date(2010, time.November, 5, 12, 0, 0, 0, time.UTC), "Y"); err != nil { + if r, err := f.RowTime(tx, 1, time.Date(2010, time.November, 5, 12, 0, 0, 0, time.UTC), "Y"); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(r.Columns(), []uint64{1, 3, 4, 5}) { t.Fatalf("wrong columns: %#v", r.Columns()) } - if r, err := f.RowTime(1, time.Date(2010, time.February, 7, 13, 0, 0, 0, time.UTC), "YM"); err != nil { + if r, err := f.RowTime(tx, 1, time.Date(2010, time.February, 7, 13, 0, 0, 0, time.UTC), "YM"); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(r.Columns(), []uint64{3}) { t.Fatalf("wrong columns: %#v", r.Columns()) } - if r, err := f.RowTime(1, time.Date(2010, time.February, 7, 13, 0, 0, 0, time.UTC), "M"); err != nil { + if r, err := f.RowTime(tx, 1, time.Date(2010, time.February, 7, 13, 0, 0, 0, time.UTC), "M"); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(r.Columns(), []uint64{3}) { t.Fatalf("wrong columns: %#v", r.Columns()) } - if r, err := f.RowTime(1, time.Date(2010, time.January, 5, 12, 0, 0, 0, time.UTC), "MD"); err != nil { + if r, err := f.RowTime(tx, 1, time.Date(2010, time.January, 5, 12, 0, 0, 0, time.UTC), "MD"); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(r.Columns(), []uint64{1, 5}) { t.Fatalf("wrong columns: %#v", r.Columns()) } - if r, err := f.RowTime(1, time.Date(2010, time.January, 5, 13, 0, 0, 0, time.UTC), "MDH"); err != nil { + if r, err := f.RowTime(tx, 1, time.Date(2010, time.January, 5, 13, 0, 0, 0, time.UTC), "MDH"); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(r.Columns(), []uint64{5}) { t.Fatalf("wrong columns: %#v", r.Columns()) @@ -578,11 +581,13 @@ func TestBSIGroup_importValue(t *testing.T) { []uint64{100}, }, } { - if err := f.importValue(tt.columnIDs, tt.values, options); err != nil { + tx := &RoaringTx{Field: f.Field} + + if err := f.importValue(tx, tt.columnIDs, tt.values, options); err != nil { t.Fatalf("test %d, importing values: %s", i, err.Error()) } - if row, err := f.Range(f.name, pql.EQ, tt.checkVal); err != nil { + if row, err := f.Range(tx, f.name, pql.EQ, tt.checkVal); err != nil { t.Fatalf("test %d, getting range: %s", i, err.Error()) } else if !reflect.DeepEqual(row.Columns(), tt.expCols) { t.Fatalf("test %d, expected columns: %v, but got: %v", i, tt.expCols, row.Columns()) @@ -643,11 +648,13 @@ func TestIntField_MinMaxForShard(t *testing.T) { }, } { t.Run(test.name+strconv.Itoa(i), func(t *testing.T) { - if err := f.importValue(test.columnIDs, test.values, options); err != nil { + tx := &RoaringTx{Field: f.Field} + + if err := f.importValue(tx, test.columnIDs, test.values, options); err != nil { t.Fatalf("test %d, importing values: %s", i, err.Error()) } - maxvc, err := f.MaxForShard(0, nil) + maxvc, err := f.MaxForShard(tx, 0, nil) if err != nil { t.Fatalf("getting max for shard: %v", err) } @@ -655,7 +662,7 @@ func TestIntField_MinMaxForShard(t *testing.T) { t.Fatalf("max expected:\n%+v\ngot:\n%+v", test.expMax, maxvc) } - minvc, err := f.MinForShard(0, nil) + minvc, err := f.MinForShard(tx, 0, nil) if err != nil { t.Fatalf("getting min for shard: %v", err) } @@ -730,7 +737,7 @@ func TestDecimalField_MinMaxBoundaries(t *testing.T) { }, } { t.Run("minmax"+strconv.Itoa(i), func(t *testing.T) { - _, err := NewField("no-path", "i", "f", OptFieldTypeDecimal(test.scale, test.min, test.max)) + _, err := NewField(NewHolder(DefaultPartitionN), "no-path", "i", "f", OptFieldTypeDecimal(test.scale, test.min, test.max)) if err != nil && test.expErr { if !strings.Contains(err.Error(), "is not supported") { t.Fatal(err) @@ -797,11 +804,13 @@ func TestDecimalField_MinMaxForShard(t *testing.T) { }, } { t.Run(test.name+strconv.Itoa(i), func(t *testing.T) { - if err := f.importFloatValue(test.columnIDs, test.values, options); err != nil { + tx := &RoaringTx{Field: f.Field} + + if err := f.importFloatValue(tx, test.columnIDs, test.values, options); err != nil { t.Fatalf("test %d, importing values: %s", i, err.Error()) } - maxvc, err := f.MaxForShard(0, nil) + maxvc, err := f.MaxForShard(tx, 0, nil) if err != nil { t.Fatalf("getting max for shard: %v", err) } @@ -809,7 +818,7 @@ func TestDecimalField_MinMaxForShard(t *testing.T) { t.Fatalf("max expected:\n%+v\ngot:\n%+v", test.expMax, maxvc) } - minvc, err := f.MinForShard(0, nil) + minvc, err := f.MinForShard(tx, 0, nil) if err != nil { t.Fatalf("getting min for shard: %v", err) } diff --git a/field_test.go b/field_test.go index 40b64728a..aeade9fcd 100644 --- a/field_test.go +++ b/field_test.go @@ -35,16 +35,17 @@ func TestField_SetValue(t *testing.T) { if err != nil { t.Fatal(err) } + tx := &pilosa.RoaringTx{Field: f.Field} // Set value on field. - if changed, err := f.SetValue(100, 21); err != nil { + if changed, err := f.SetValue(tx, 100, 21); err != nil { t.Fatal(err) } else if !changed { t.Fatal("expected change") } // Read value. - if value, exists, err := f.Value(100); err != nil { + if value, exists, err := f.Value(tx, 100); err != nil { t.Fatal(err) } else if value != 21 { t.Fatalf("unexpected value: %d", value) @@ -53,7 +54,7 @@ func TestField_SetValue(t *testing.T) { } // Setting value should return no change. - if changed, err := f.SetValue(100, 21); err != nil { + if changed, err := f.SetValue(tx, 100, 21); err != nil { t.Fatal(err) } else if changed { t.Fatal("expected no change") @@ -68,23 +69,24 @@ func TestField_SetValue(t *testing.T) { if err != nil { t.Fatal(err) } + tx := &pilosa.RoaringTx{Field: f.Field} // Set value. - if changed, err := f.SetValue(100, 21); err != nil { + if changed, err := f.SetValue(tx, 100, 21); err != nil { t.Fatal(err) } else if !changed { t.Fatal("expected change") } // Set different value. - if changed, err := f.SetValue(100, 23); err != nil { + if changed, err := f.SetValue(tx, 100, 23); err != nil { t.Fatal(err) } else if !changed { t.Fatal("expected change") } // Read value. - if value, exists, err := f.Value(100); err != nil { + if value, exists, err := f.Value(tx, 100); err != nil { t.Fatal(err) } else if value != 23 { t.Fatalf("unexpected value: %d", value) @@ -101,9 +103,10 @@ func TestField_SetValue(t *testing.T) { if err != nil { t.Fatal(err) } + tx := &pilosa.RoaringTx{Field: f.Field} // Set value. - if _, err := f.SetValue(100, 21); err != pilosa.ErrBSIGroupNotFound { + if _, err := f.SetValue(tx, 100, 21); err != pilosa.ErrBSIGroupNotFound { t.Fatalf("unexpected error: %s", err) } }) @@ -116,9 +119,10 @@ func TestField_SetValue(t *testing.T) { if err != nil { t.Fatal(err) } + tx := &pilosa.RoaringTx{Field: f.Field} // Set value. - if _, err := f.SetValue(100, 15); err != pilosa.ErrBSIGroupValueTooLow { + if _, err := f.SetValue(tx, 100, 15); err != pilosa.ErrBSIGroupValueTooLow { t.Fatalf("unexpected error: %s", err) } }) @@ -131,9 +135,10 @@ func TestField_SetValue(t *testing.T) { if err != nil { t.Fatal(err) } + tx := &pilosa.RoaringTx{Field: f.Field} // Set value. - if _, err := f.SetValue(100, 31); err != pilosa.ErrBSIGroupValueTooHigh { + if _, err := f.SetValue(tx, 100, 31); err != pilosa.ErrBSIGroupValueTooHigh { t.Fatalf("unexpected error: %s", err) } }) @@ -144,7 +149,7 @@ func TestField_NameRestriction(t *testing.T) { if err != nil { panic(err) } - field, err := pilosa.NewField(path, "i", ".meta", pilosa.OptFieldTypeDefault()) + field, err := pilosa.NewField(pilosa.NewHolder(pilosa.DefaultPartitionN), path, "i", ".meta", pilosa.OptFieldTypeDefault()) if field != nil { t.Fatalf("unexpected field name %s", err) } @@ -177,13 +182,13 @@ func TestField_NameValidation(t *testing.T) { panic(err) } for _, name := range validFieldNames { - _, err := pilosa.NewField(path, "i", name, pilosa.OptFieldTypeDefault()) + _, err := pilosa.NewField(pilosa.NewHolder(pilosa.DefaultPartitionN), path, "i", name, pilosa.OptFieldTypeDefault()) if err != nil { t.Fatalf("unexpected field name: %s %s", name, err) } } for _, name := range invalidFieldNames { - _, err := pilosa.NewField(path, "i", name, pilosa.OptFieldTypeDefault()) + _, err := pilosa.NewField(pilosa.NewHolder(pilosa.DefaultPartitionN), path, "i", name, pilosa.OptFieldTypeDefault()) if err == nil { t.Fatalf("expected error on field name: %s", name) } @@ -199,11 +204,12 @@ func TestField_AvailableShards(t *testing.T) { if err != nil { t.Fatal(err) } + tx := &pilosa.RoaringTx{Field: f.Field} // Set values on shards 0 & 2, and verify. - if _, err := f.SetBit(0, 100, nil); err != nil { + if _, err := f.SetBit(tx, 0, 100, nil); err != nil { t.Fatal(err) - } else if _, err := f.SetBit(0, ShardWidth*2, nil); err != nil { + } else if _, err := f.SetBit(tx, 0, ShardWidth*2, nil); err != nil { t.Fatal(err) } else if diff := cmp.Diff(f.AvailableShards().Slice(), []uint64{0, 2}); diff != "" { t.Fatal(diff) @@ -238,16 +244,17 @@ func TestField_ClearValue(t *testing.T) { if err != nil { t.Fatal(err) } + tx := &pilosa.RoaringTx{Field: f.Field} // Set value on field. - if changed, err := f.SetValue(100, 21); err != nil { + if changed, err := f.SetValue(tx, 100, 21); err != nil { t.Fatal(err) } else if !changed { t.Fatal("expected change") } // Read value. - if value, exists, err := f.Value(100); err != nil { + if value, exists, err := f.Value(tx, 100); err != nil { t.Fatal(err) } else if value != 21 { t.Fatalf("unexpected value: %d", value) @@ -255,14 +262,14 @@ func TestField_ClearValue(t *testing.T) { t.Fatal("expected value to exist") } - if changed, err := f.ClearValue(100); err != nil { + if changed, err := f.ClearValue(tx, 100); err != nil { t.Fatal(err) } else if !changed { t.Fatal(err) } // Read value. - if _, exists, err := f.Value(100); err != nil { + if _, exists, err := f.Value(tx, 100); err != nil { t.Fatal(err) } else if exists { t.Fatal("expected value to not exist") diff --git a/fragment.go b/fragment.go index 5f26828ec..c7bd1e241 100644 --- a/fragment.go +++ b/fragment.go @@ -30,6 +30,7 @@ import ( "os" "runtime/debug" "sort" + "strconv" "strings" "sync" "syscall" @@ -106,6 +107,10 @@ type fragment struct { field string view string shard uint64 + + // parent holder, used to find snapshot queue, etc. + holder *Holder + // debugging tool: addresses of current and previous maps prevdata, currdata struct{ from, to uintptr } @@ -120,6 +125,7 @@ type fragment struct { snapshotCond sync.Cond snapshotErr error // error yielded by the last snapshot operation snapshotStamp time.Time // timestamp of last snapshot + open bool // is this fragment actually open? // Cache for row counts. CacheType string // passed in by field @@ -153,26 +159,26 @@ type fragment struct { stats stats.StatsClient - snapshotQueue snapshotQueue + bitmapInfo *roaring.BitmapInfo } // newFragment returns a new instance of Fragment. -func newFragment(path, index, field, view string, shard uint64, flags byte) *fragment { +func newFragment(holder *Holder, path, index, field, view string, shard uint64, flags byte) *fragment { f := &fragment{ - path: path, - index: index, - field: field, - view: view, - shard: shard, - flags: flags, + path: path, + index: index, + field: field, + view: view, + shard: shard, + flags: flags, + CacheType: DefaultCacheType, CacheSize: DefaultCacheSize, - Logger: logger.NopLogger, + holder: holder, MaxOpN: defaultFragmentMaxOpN, - stats: stats.NopStatsClient, - snapshotQueue: defaultSnapshotQueue, + stats: stats.NopStatsClient, } f.snapshotCond = sync.Cond{L: &f.mu} return f @@ -181,6 +187,23 @@ func newFragment(path, index, field, view string, shard uint64, flags byte) *fra // cachePath returns the path to the fragment's cache data. func (f *fragment) cachePath() string { return f.path + cacheExt } +type FragmentInfo struct { + BitmapInfo roaring.BitmapInfo + BlockChecksums []FragmentBlock `json:"BlockChecksums,omitempty"` +} + +func (f *fragment) inspect(params InspectRequestParams) (fi FragmentInfo) { + if f.bitmapInfo == nil { + fi.BitmapInfo = f.storage.Info(params.Containers) + } else { + fi.BitmapInfo = *f.bitmapInfo + } + if params.Checksum { + fi.BlockChecksums, _ = f.Blocks() + } + return fi +} + // Open opens the underlying storage. func (f *fragment) Open() error { f.mu.Lock() @@ -188,13 +211,13 @@ func (f *fragment) Open() error { if err := func() error { // Initialize storage in a function so we can close if anything goes wrong. - f.Logger.Debugf("open storage for index/field/view/fragment: %s/%s/%s/%d", f.index, f.field, f.view, f.shard) + f.holder.Logger.Debugf("open storage for index/field/view/fragment: %s/%s/%s/%d", f.index, f.field, f.view, f.shard) if err := f.openStorage(true); err != nil { return errors.Wrap(err, "opening storage") } // Fill cache with rows persisted to disk. - f.Logger.Debugf("open cache for index/field/view/fragment: %s/%s/%s/%d", f.index, f.field, f.view, f.shard) + f.holder.Logger.Debugf("open cache for index/field/view/fragment: %s/%s/%s/%d", f.index, f.field, f.view, f.shard) if err := f.openCache(); err != nil { e2 := f.closeStorage() if e2 != nil { @@ -207,14 +230,14 @@ func (f *fragment) Open() error { f.checksums = make(map[int][]byte) // Read last bit to determine max row. - f.maxRowID = f.storage.Max() / ShardWidth - return nil + return f.calculateMaxRowID() }(); err != nil { f.close() return err } + f.open = true - f.Logger.Debugf("successfully opened index/field/view/fragment: %s/%s/%s/%d", f.index, f.field, f.view, f.shard) + f.holder.Logger.Debugf("successfully opened index/field/view/fragment: %s/%s/%s/%d", f.index, f.field, f.view, f.shard) return nil } @@ -222,6 +245,9 @@ func (f *fragment) Open() error { // get no data. It tries to write the current storage to the provided file, // which is assumed to be the file they didn't get any data from. func (f *fragment) emptyStorage(file *os.File) (bool, error) { + if f.holder.Opts.ReadOnly { + return false, errors.New("can't flush/create storage for read-only holder") + } // No data. We'll mark this for no mapping, clear any existing // mapped containers, and set the Source to nil. We also have no // ops. @@ -273,9 +299,12 @@ func (f *fragment) importStorage(data []byte, file *os.File, newGen generation, } return false, fmt.Errorf("unmarshal storage: file=%s, err=%s", file.Name(), err) } - f.Logger.Printf("warning: unmarshal storage, file=%s, err=%v", file.Name(), err) + f.holder.Logger.Printf("warning: unmarshal storage, file=%s, err=%v", file.Name(), err) trunc, ok := cause.(roaring.FileShouldBeTruncatedError) - if ok { + if ok && !f.holder.Opts.ReadOnly { + // if the holder is ReadOnly, we silently ignore the "advisory" + // error. This may be a bad idea. + // generation code looks for a FileShouldBeTruncatedError return false, trunc } @@ -299,7 +328,7 @@ func (f *fragment) applyStorage(data []byte, file *os.File, newGen generation, m if file != nil { fi, err := file.Stat() if err != nil { - f.Logger.Printf("trying to apply new storage to existing bitmap, stat failed: %v", err) + f.holder.Logger.Printf("trying to apply new storage to existing bitmap, stat failed: %v", err) } if err == nil && fi != nil && fi.Size() == 0 { return f.emptyStorage(file) @@ -335,6 +364,12 @@ func (f *fragment) applyStorage(data []byte, file *os.File, newGen generation, m return mapped, err } +func (f *fragment) inspectStorage(data []byte, file *os.File, newGen generation, mapped bool) (didMap bool, err error) { + f.bitmapInfo = &roaring.BitmapInfo{} + f.storage, didMap, err = roaring.InspectBinary(data, mapped, f.bitmapInfo) + return didMap, err +} + // openStorage opens the storage bitmap. // // This has been massively reworked recently, and now hands a lot of @@ -353,13 +388,20 @@ func (f *fragment) openStorage(unmarshalData bool) error { } f.rowCache = &simpleCache{make(map[uint64]*Row)} var storageOp func([]byte, *os.File, generation, bool) (bool, error) - if unmarshalData { - storageOp = f.importStorage + if f.holder.Opts.Inspect { + // note that this will unmarshal even if we already have + // storage; when Inspect is on for a holder, we actually want + // to be able to report this. + storageOp = f.inspectStorage } else { - storageOp = f.applyStorage + if unmarshalData { + storageOp = f.importStorage + } else { + storageOp = f.applyStorage + } } var err error - f.gen, err = newGeneration(f.gen, f.path, unmarshalData, storageOp, f.Logger) + f.gen, err = newGeneration(f.gen, f.path, unmarshalData, storageOp, f.holder.Logger) if f.gen != nil { scratchData := f.gen.Bytes() f.prevdata = f.currdata @@ -407,7 +449,7 @@ func (f *fragment) openCache() error { // Unmarshal cache data. var pb internal.Cache if err := proto.Unmarshal(buf, &pb); err != nil { - f.Logger.Printf("error unmarshaling cache data, skipping: path=%s, err=%s", path, err) + f.holder.Logger.Printf("error unmarshaling cache data, skipping: path=%s, err=%s", path, err) return nil } @@ -429,19 +471,22 @@ func (f *fragment) Close() error { for f.snapshotPending { f.snapshotCond.Wait() } + // Note: snapshots won't progress on a closed fragment, so we + // wait until after a possible pending snapshot to close. + f.open = false return f.close() } func (f *fragment) close() error { // Flush cache if closing gracefully. if err := f.flushCache(); err != nil { - f.Logger.Printf("fragment: error flushing cache on close: err=%s, path=%s", err, f.path) + f.holder.Logger.Printf("fragment: error flushing cache on close: err=%s, path=%s", err, f.path) return errors.Wrap(err, "flushing cache") } // Close underlying storage. if err := f.closeStorage(); err != nil { - f.Logger.Printf("fragment: error closing storage: err=%s, path=%s", err, f.path) + f.holder.Logger.Printf("fragment: error closing storage: err=%s, path=%s", err, f.path) return errors.Wrap(err, "closing storage") } @@ -466,28 +511,40 @@ func (f *fragment) closeStorage() error { } // row returns a row by ID. -func (f *fragment) row(rowID uint64) *Row { +func (f *fragment) row(tx Tx, rowID uint64) (*Row, error) { f.mu.Lock() defer f.mu.Unlock() - return f.unprotectedRow(rowID) + return f.unprotectedRow(tx, rowID) +} + +// mustRow returns a row by ID. Panic on error. Only used for testing. +func (f *fragment) mustRow(tx Tx, rowID uint64) *Row { + row, err := f.row(tx, rowID) + if err != nil { + panic(err) + } + return row } // unprotectedRow returns a row from the row cache if available or from storage // (updating the cache). -func (f *fragment) unprotectedRow(rowID uint64) *Row { +func (f *fragment) unprotectedRow(tx Tx, rowID uint64) (*Row, error) { r, ok := f.rowCache.Fetch(rowID) if ok && r != nil { - return r + return r, nil } - row := f.rowFromStorage(rowID) + row, err := f.rowFromStorage(tx, rowID) + if err != nil { + return nil, err + } f.rowCache.Add(rowID, row) - return row + return row, nil } // rowFromStorage clones a row data out of fragment storage and returns it as a // Row object. -func (f *fragment) rowFromStorage(rowID uint64) *Row { +func (f *fragment) rowFromStorage(tx Tx, rowID uint64) (*Row, error) { // Only use a subset of the containers. // NOTE: The start & end ranges must be divisible by container width. // @@ -495,7 +552,10 @@ func (f *fragment) rowFromStorage(rowID uint64) *Row { // containers which will use copy-on-write semantics. The actual bitmap // and Containers object are new and not shared, but the containers are // shared. - data := f.storage.OffsetRange(f.shard*ShardWidth, rowID*ShardWidth, (rowID+1)*ShardWidth) + data, err := tx.OffsetRange(f.index, f.field, f.view, f.shard, f.shard*ShardWidth, rowID*ShardWidth, (rowID+1)*ShardWidth) + if err != nil { + return nil, err + } row := &Row{ segments: []rowSegment{{ @@ -506,22 +566,22 @@ func (f *fragment) rowFromStorage(rowID uint64) *Row { } row.invalidateCount() - return row + return row, nil } // setBit sets a bit for a given column & row within the fragment. // This updates both the on-disk storage and the in-cache bitmap. -func (f *fragment) setBit(rowID, columnID uint64) (changed bool, err error) { +func (f *fragment) setBit(tx Tx, rowID, columnID uint64) (changed bool, err error) { f.mu.Lock() defer f.mu.Unlock() err = f.gen.Transaction(&f.storage.OpWriter, func() error { // handle mutux field type if f.mutexVector != nil { - if err := f.handleMutex(rowID, columnID); err != nil { + if err := f.handleMutex(tx, rowID, columnID); err != nil { return errors.Wrap(err, "handling mutex") } } - changed, err = f.unprotectedSetBit(rowID, columnID) + changed, err = f.unprotectedSetBit(tx, rowID, columnID) return err }) return changed, err @@ -529,11 +589,11 @@ func (f *fragment) setBit(rowID, columnID uint64) (changed bool, err error) { // handleMutex will clear an existing row and store the new row // in the vector. -func (f *fragment) handleMutex(rowID, columnID uint64) error { - if existingRowID, found, err := f.mutexVector.Get(columnID); err != nil { +func (f *fragment) handleMutex(tx Tx, rowID, columnID uint64) error { + if existingRowID, found, err := f.mutexVector.Get(tx, columnID); err != nil { return errors.Wrap(err, "getting mutex vector data") } else if found && existingRowID != rowID { - if _, err := f.unprotectedClearBit(existingRowID, columnID); err != nil { + if _, err := f.unprotectedClearBit(tx, existingRowID, columnID); err != nil { return errors.Wrap(err, "clearing mutex value") } } @@ -541,7 +601,7 @@ func (f *fragment) handleMutex(rowID, columnID uint64) error { } // unprotectedSetBit TODO should be replaced by an invocation of importPositions with a single bit to set. -func (f *fragment) unprotectedSetBit(rowID, columnID uint64) (changed bool, err error) { +func (f *fragment) unprotectedSetBit(tx Tx, rowID, columnID uint64) (changed bool, err error) { changed = false // Determine the position of the bit in the storage. pos, err := f.pos(rowID, columnID) @@ -550,7 +610,7 @@ func (f *fragment) unprotectedSetBit(rowID, columnID uint64) (changed bool, err } // Write to storage. - if changed, err = f.storage.Add(pos); err != nil { + if changed, err = tx.Add(f.index, f.field, f.view, f.shard, pos); err != nil { return false, errors.Wrap(err, "writing") } @@ -568,7 +628,10 @@ func (f *fragment) unprotectedSetBit(rowID, columnID uint64) (changed bool, err // If we're using a cache, update it. Otherwise skip the // possibly-expensive count operation. if f.CacheType != CacheTypeNone { - n := f.storage.CountRange(rowID*ShardWidth, (rowID+1)*ShardWidth) + n, err := tx.CountRange(f.index, f.field, f.view, f.shard, rowID*ShardWidth, (rowID+1)*ShardWidth) + if err != nil { + return false, err + } f.cache.Add(rowID, n) } // Drop the rowCache entry; it's wrong, and we don't want to force @@ -587,11 +650,11 @@ func (f *fragment) unprotectedSetBit(rowID, columnID uint64) (changed bool, err // clearBit clears a bit for a given column & row within the fragment. // This updates both the on-disk storage and the in-cache bitmap. -func (f *fragment) clearBit(rowID, columnID uint64) (changed bool, err error) { +func (f *fragment) clearBit(tx Tx, rowID, columnID uint64) (changed bool, err error) { f.mu.Lock() defer f.mu.Unlock() err = f.gen.Transaction(&f.storage.OpWriter, func() error { - changed, err = f.unprotectedClearBit(rowID, columnID) + changed, err = f.unprotectedClearBit(tx, rowID, columnID) return err }) return changed, err @@ -599,7 +662,7 @@ func (f *fragment) clearBit(rowID, columnID uint64) (changed bool, err error) { // unprotectedClearBit TODO should be replaced by an invocation of // importPositions with a single bit to clear. -func (f *fragment) unprotectedClearBit(rowID, columnID uint64) (changed bool, err error) { +func (f *fragment) unprotectedClearBit(tx Tx, rowID, columnID uint64) (changed bool, err error) { changed = false // Determine the position of the bit in the storage. pos, err := f.pos(rowID, columnID) @@ -608,7 +671,7 @@ func (f *fragment) unprotectedClearBit(rowID, columnID uint64) (changed bool, er } // Write to storage. - if changed, err = f.storage.Remove(pos); err != nil { + if changed, err = tx.Remove(f.index, f.field, f.view, f.shard, pos); err != nil { return false, errors.Wrap(err, "writing") } @@ -626,7 +689,10 @@ func (f *fragment) unprotectedClearBit(rowID, columnID uint64) (changed bool, er // If we're using a cache, update it. Otherwise skip the // possibly-expensive count operation. if f.CacheType != CacheTypeNone { - n := f.storage.CountRange(rowID*ShardWidth, (rowID+1)*ShardWidth) + n, err := tx.CountRange(f.index, f.field, f.view, f.shard, rowID*ShardWidth, (rowID+1)*ShardWidth) + if err != nil { + return changed, err + } f.cache.Add(rowID, n) } // Drop the rowCache entry; it's wrong, and we don't want to force @@ -640,17 +706,17 @@ func (f *fragment) unprotectedClearBit(rowID, columnID uint64) (changed bool, er // setRow replaces an existing row (specified by rowID) with the given // Row. This updates both the on-disk storage and the in-cache bitmap. -func (f *fragment) setRow(row *Row, rowID uint64) (changed bool, err error) { +func (f *fragment) setRow(tx Tx, row *Row, rowID uint64) (changed bool, err error) { f.mu.Lock() defer f.mu.Unlock() err = f.gen.Transaction(&f.storage.OpWriter, func() error { - changed, err = f.unprotectedSetRow(row, rowID) + changed, err = f.unprotectedSetRow(tx, row, rowID) return err }) return changed, err } -func (f *fragment) unprotectedSetRow(row *Row, rowID uint64) (changed bool, err error) { +func (f *fragment) unprotectedSetRow(tx Tx, row *Row, rowID uint64) (changed bool, err error) { // TODO: In order to return `changed`, we need to first compare // the existing row with the given row. Determine if the overhead // of this is worth having `changed`. @@ -662,7 +728,9 @@ func (f *fragment) unprotectedSetRow(row *Row, rowID uint64) (changed bool, err // Remove every existing container in the row. for i := uint64(0); i < (1 << shardVsContainerExponent); i++ { - f.storage.Containers.Remove(headContainerKey + i) + if err := tx.RemoveContainer(f.index, f.field, f.view, f.shard, headContainerKey+i); err != nil { + return changed, err + } } // From the given row, get the rowSegment for this shard. @@ -675,12 +743,17 @@ func (f *fragment) unprotectedSetRow(row *Row, rowID uint64) (changed bool, err citer, _ := seg.data.Containers.Iterator(f.shard << shardVsContainerExponent) for citer.Next() { k, c := citer.Value() - f.storage.Containers.Put(headContainerKey+(k%(1<= 0 || clear { - if c, err := f.unprotectedClearBit(uint64(bsiSignBit), columnID); err != nil { + if c, err := f.unprotectedClearBit(tx, uint64(bsiSignBit), columnID); err != nil { return errors.Wrap(err, "clearing sign") } else if c { changed = true } } else { - if c, err := f.unprotectedSetBit(uint64(bsiSignBit), columnID); err != nil { + if c, err := f.unprotectedSetBit(tx, uint64(bsiSignBit), columnID); err != nil { return errors.Wrap(err, "marking sign") } else if c { changed = true @@ -904,7 +983,7 @@ func (f *fragment) setValueBase(columnID uint64, bitDepth uint, value int64, cle } // importSetValue is a more efficient SetValue just for imports. -func (f *fragment) importSetValue(columnID uint64, bitDepth uint, value int64, clear bool) (changed int, err error) { // nolint: unparam +func (f *fragment) importSetValue(tx Tx, columnID uint64, bitDepth uint, value int64, clear bool) (changed int, err error) { // nolint: unparam // Convert value to an unsigned representation. uvalue := uint64(value) if value < 0 { @@ -918,13 +997,13 @@ func (f *fragment) importSetValue(columnID uint64, bitDepth uint, value int64, c } if uvalue&(1<= 0 || clear { - if c, err := f.storage.Remove(p); err != nil { + if c, err := tx.Remove(f.index, f.field, f.view, f.shard, p); err != nil { return changed, errors.Wrap(err, "removing sign from storage") } else if c { changed++ } } else { - if c, err := f.storage.Add(p); err != nil { + if c, err := tx.Add(f.index, f.field, f.view, f.shard, p); err != nil { return changed, errors.Wrap(err, "adding sign to storage") } else if c { changed++ @@ -971,16 +1050,21 @@ func (f *fragment) importSetValue(columnID uint64, bitDepth uint, value int64, c // sum returns the sum of a given bsiGroup as well as the number of columns involved. // A bitmap can be passed in to optionally filter the computed columns. -func (f *fragment) sum(filter *Row, bitDepth uint) (sum int64, count uint64, err error) { +func (f *fragment) sum(tx Tx, filter *Row, bitDepth uint) (sum int64, count uint64, err error) { // Compute count based on the existence row. - consider := f.row(bsiExistsBit) - if filter != nil { + consider, err := f.row(tx, bsiExistsBit) + if err != nil { + return sum, count, err + } else if filter != nil { consider = consider.Intersect(filter) } count = consider.Count() // Get negative set - nrow := f.row(bsiSignBit) + nrow, err := f.row(tx, bsiSignBit) + if err != nil { + return sum, count, err + } // Filter negative set nrow = consider.Intersect(nrow) @@ -998,7 +1082,10 @@ func (f *fragment) sum(filter *Row, bitDepth uint) (sum int64, count uint64, err // Execute once for positive numbers and once for negative. Subtract the // negative sum from the positive sum. for i := uint(0); i < bitDepth; i++ { - row := f.row(uint64(bsiOffsetBit + i)) + row, err := f.row(tx, uint64(bsiOffsetBit+i)) + if err != nil { + return sum, count, err + } psum := int64((1 << i) * row.intersectionCount(prow)) nsum := int64((1 << i) * row.intersectionCount(nrow)) @@ -1012,9 +1099,11 @@ func (f *fragment) sum(filter *Row, bitDepth uint) (sum int64, count uint64, err // min returns the min of a given bsiGroup as well as the number of columns involved. // A bitmap can be passed in to optionally filter the computed columns. -func (f *fragment) min(filter *Row, bitDepth uint) (min int64, count uint64, err error) { - consider := f.row(bsiExistsBit) - if filter != nil { +func (f *fragment) min(tx Tx, filter *Row, bitDepth uint) (min int64, count uint64, err error) { + consider, err := f.row(tx, bsiExistsBit) + if err != nil { + return min, count, err + } else if filter != nil { consider = consider.Intersect(filter) } @@ -1027,20 +1116,25 @@ func (f *fragment) min(filter *Row, bitDepth uint) (min int64, count uint64, err // from that set, then negate it, and return it. For example, if values // (-1, -2) exist, they are stored unsigned (1,2) with a negative sign bit // set. We take the highest of that set (2) and negate it and return it. - if row := f.row(bsiSignBit).Intersect(consider); row.Any() { - min, count := f.maxUnsigned(row, bitDepth) - return -min, count, nil + if row, err := f.row(tx, bsiSignBit); err != nil { + return min, count, err + } else if row = row.Intersect(consider); row.Any() { + min, count, err := f.maxUnsigned(tx, row, bitDepth) + return -min, count, err } // Otherwise find lowest positive number. - min, count = f.minUnsigned(consider, bitDepth) - return min, count, nil + return f.minUnsigned(tx, consider, bitDepth) } // minUnsigned the lowest value without considering the sign bit. Filter is required. -func (f *fragment) minUnsigned(filter *Row, bitDepth uint) (min int64, count uint64) { +func (f *fragment) minUnsigned(tx Tx, filter *Row, bitDepth uint) (min int64, count uint64, err error) { for i := int(bitDepth - 1); i >= 0; i-- { - row := filter.Difference(f.row(uint64(bsiOffsetBit + i))) + row, err := f.row(tx, uint64(bsiOffsetBit+i)) + if err != nil { + return min, count, err + } + row = filter.Difference(row) count = row.Count() if count > 0 { filter = row @@ -1051,14 +1145,16 @@ func (f *fragment) minUnsigned(filter *Row, bitDepth uint) (min int64, count uin } } } - return min, count + return min, count, nil } // max returns the max of a given bsiGroup as well as the number of columns involved. // A bitmap can be passed in to optionally filter the computed columns. -func (f *fragment) max(filter *Row, bitDepth uint) (max int64, count uint64, err error) { - consider := f.row(bsiExistsBit) - if filter != nil { +func (f *fragment) max(tx Tx, filter *Row, bitDepth uint) (max int64, count uint64, err error) { + consider, err := f.row(tx, bsiExistsBit) + if err != nil { + return max, count, err + } else if filter != nil { consider = consider.Intersect(filter) } @@ -1068,21 +1164,29 @@ func (f *fragment) max(filter *Row, bitDepth uint) (max int64, count uint64, err } // Find lowest negative number w/o sign and negate, if no positives are available. - pos := consider.Difference(f.row(bsiSignBit)) + row, err := f.row(tx, bsiSignBit) + if err != nil { + return max, count, err + } + pos := consider.Difference(row) if !pos.Any() { - max, count = f.minUnsigned(consider, bitDepth) - return -max, count, nil + max, count, err = f.minUnsigned(tx, consider, bitDepth) + return -max, count, err } // Otherwise find highest positive number. - max, count = f.maxUnsigned(pos, bitDepth) - return max, count, nil + return f.maxUnsigned(tx, pos, bitDepth) } // maxUnsigned the highest value without considering the sign bit. Filter is required. -func (f *fragment) maxUnsigned(filter *Row, bitDepth uint) (max int64, count uint64) { +func (f *fragment) maxUnsigned(tx Tx, filter *Row, bitDepth uint) (max int64, count uint64, err error) { for i := int(bitDepth - 1); i >= 0; i-- { - row := f.row(uint64(bsiOffsetBit + i)).Intersect(filter) + row, err := f.row(tx, uint64(bsiOffsetBit+i)) + if err != nil { + return max, count, err + } + row = row.Intersect(filter) + count = row.Count() if count > 0 { max += (1 << uint(i)) @@ -1091,69 +1195,86 @@ func (f *fragment) maxUnsigned(filter *Row, bitDepth uint) (max int64, count uin count = filter.Count() } } - return max, count + return max, count, nil } // minRow returns minRowID of the rows in the filter and its count. // if filter is nil, it returns fragment.minRowID, 1 // if fragment has no rows, it returns 0, 0 -func (f *fragment) minRow(filter *Row) (uint64, uint64) { - minRowID, hasRowID := f.minRowID() +func (f *fragment) minRow(tx Tx, filter *Row) (uint64, uint64, error) { + minRowID, hasRowID, err := f.minRowID(tx) + if err != nil { + return 0, 0, err + } if hasRowID { if filter == nil { - return minRowID, 1 + return minRowID, 1, nil } // iterate from min row ID and return the first that intersects with filter. for i := minRowID; i <= f.maxRowID; i++ { - row := f.row(i).Intersect(filter) + row, err := f.row(tx, i) + if err != nil { + return 0, 0, err + } + row = row.Intersect(filter) + count := row.Count() if count > 0 { - return i, count + return i, count, nil } } } - return 0, 0 + return 0, 0, nil } // maxRow returns maxRowID of the rows in the filter and its count. // if filter is nil, it returns fragment.maxRowID, 1 // if fragment has no rows, it returns 0, 0 -func (f *fragment) maxRow(filter *Row) (uint64, uint64) { - minRowID, hasRowID := f.minRowID() +func (f *fragment) maxRow(tx Tx, filter *Row) (uint64, uint64, error) { + minRowID, hasRowID, err := f.minRowID(tx) + if err != nil { + return 0, 0, err + } if hasRowID { if filter == nil { - return f.maxRowID, 1 + return f.maxRowID, 1, nil } // iterate back from max row ID and return the first that intersects with filter. // TODO: implement reverse container iteration to improve performance here for sparse data. --Jaffee for i := f.maxRowID; i >= minRowID; i-- { - row := f.row(i).Intersect(filter) + row, err := f.row(tx, i) + if err != nil { + return 0, 0, err + } + row = row.Intersect(filter) + count := row.Count() if count > 0 { - return i, count + return i, count, nil } } } - return 0, 0 + return 0, 0, nil } // calculateMaxRowID determines the field's maxRowID value based // on the contents of its storage, and sets the struct argument. -func (f *fragment) calculateMaxRowID() { +func (f *fragment) calculateMaxRowID() (err error) { f.maxRowID = f.storage.Max() / ShardWidth + return nil } // rangeOp returns bitmaps with a bsiGroup value encoding matching the predicate. -func (f *fragment) rangeOp(op pql.Token, bitDepth uint, predicate int64) (*Row, error) { +func (f *fragment) rangeOp(tx Tx, op pql.Token, bitDepth uint, predicate int64) (*Row, error) { switch op { case pql.EQ: - return f.rangeEQ(bitDepth, predicate) + return f.rangeEQ(tx, bitDepth, predicate) case pql.NEQ: - return f.rangeNEQ(bitDepth, predicate) + return f.rangeNEQ(tx, bitDepth, predicate) case pql.LT, pql.LTE: - return f.rangeLT(bitDepth, predicate, op == pql.LTE) + return f.rangeLT(tx, bitDepth, predicate, op == pql.LTE) case pql.GT, pql.GTE: - return f.rangeGT(bitDepth, predicate, op == pql.GTE) + return f.rangeGT(tx, bitDepth, predicate, op == pql.GTE) default: return nil, ErrInvalidRangeOperation } @@ -1170,21 +1291,35 @@ func absInt64(v int64) uint64 { } } -func (f *fragment) rangeEQ(bitDepth uint, predicate int64) (*Row, error) { +func (f *fragment) rangeEQ(tx Tx, bitDepth uint, predicate int64) (*Row, error) { // Start with set of columns with values set. - b := f.row(bsiExistsBit) + b, err := f.row(tx, bsiExistsBit) + if err != nil { + return nil, err + } // Filter to only positive/negative numbers. upredicate := absInt64(predicate) if predicate < 0 { - b = b.Intersect(f.row(bsiSignBit)) // only negatives + r, err := f.row(tx, bsiSignBit) + if err != nil { + return nil, err + } + b = b.Intersect(r) // only negatives } else { - b = b.Difference(f.row(bsiSignBit)) // only positives + r, err := f.row(tx, bsiSignBit) + if err != nil { + return nil, err + } + b = b.Difference(r) // only positives } // Filter any bits that don't match the current bit value. for i := int(bitDepth - 1); i >= 0; i-- { - row := f.row(uint64(bsiOffsetBit + i)) + row, err := f.row(tx, uint64(bsiOffsetBit+i)) + if err != nil { + return nil, err + } bit := (upredicate >> uint(i)) & 1 if bit == 1 { @@ -1197,12 +1332,15 @@ func (f *fragment) rangeEQ(bitDepth uint, predicate int64) (*Row, error) { return b, nil } -func (f *fragment) rangeNEQ(bitDepth uint, predicate int64) (*Row, error) { +func (f *fragment) rangeNEQ(tx Tx, bitDepth uint, predicate int64) (*Row, error) { // Start with set of columns with values set. - b := f.row(bsiExistsBit) + b, err := f.row(tx, bsiExistsBit) + if err != nil { + return nil, err + } // Get the equal bitmap. - eq, err := f.rangeEQ(bitDepth, predicate) + eq, err := f.rangeEQ(tx, bitDepth, predicate) if err != nil { return nil, err } @@ -1213,16 +1351,22 @@ func (f *fragment) rangeNEQ(bitDepth uint, predicate int64) (*Row, error) { return b, nil } -func (f *fragment) rangeLT(bitDepth uint, predicate int64, allowEquality bool) (*Row, error) { +func (f *fragment) rangeLT(tx Tx, bitDepth uint, predicate int64, allowEquality bool) (*Row, error) { if predicate == 1 && !allowEquality { predicate, allowEquality = 0, true } // Start with set of columns with values set. - b := f.row(bsiExistsBit) + b, err := f.row(tx, bsiExistsBit) + if err != nil { + return nil, err + } // Get the sign bit row. - sign := f.row(bsiSignBit) + sign, err := f.row(tx, bsiSignBit) + if err != nil { + return nil, err + } // Create predicate without sign bit. upredicate := absInt64(predicate) @@ -1233,17 +1377,17 @@ func (f *fragment) rangeLT(bitDepth uint, predicate int64, allowEquality bool) ( return b.Intersect(sign), nil case predicate == 0 && allowEquality: // Match all integers that are either negative or 0. - zeroes, err := f.rangeEQ(bitDepth, 0) + zeroes, err := f.rangeEQ(tx, bitDepth, 0) if err != nil { return nil, err } return b.Intersect(sign).Union(zeroes), nil case predicate < 0: // Match all every negative number beyond the predicate. - return f.rangeGTUnsigned(b.Intersect(sign), bitDepth, upredicate, allowEquality) + return f.rangeGTUnsigned(tx, b.Intersect(sign), bitDepth, upredicate, allowEquality) default: // Match positive numbers less than the predicate, and all negatives. - pos, err := f.rangeLTUnsigned(b.Difference(sign), bitDepth, upredicate, allowEquality) + pos, err := f.rangeLTUnsigned(tx, b.Difference(sign), bitDepth, upredicate, allowEquality) if err != nil { return nil, err } @@ -1261,7 +1405,7 @@ func msb(x uint64) uint { } // rangeLTUnsigned returns all bits LT/LTE the predicate without considering the sign bit. -func (f *fragment) rangeLTUnsigned(filter *Row, bitDepth uint, predicate uint64, allowEquality bool) (*Row, error) { +func (f *fragment) rangeLTUnsigned(tx Tx, filter *Row, bitDepth uint, predicate uint64, allowEquality bool) (*Row, error) { switch { case msb(predicate) > bitDepth: fallthrough @@ -1272,7 +1416,10 @@ func (f *fragment) rangeLTUnsigned(filter *Row, bitDepth uint, predicate uint64, // This query matches everything that is not (1<= 0 && predicate > 0 && remaining.Any(); i-- { - row := f.row(uint64(bsiOffsetBit + i)) + row, err := f.row(tx, uint64(bsiOffsetBit+i)) + if err != nil { + return nil, err + } zeroes := remaining.Difference(row) switch (predicate >> uint(i)) & 1 { case 1: @@ -1300,22 +1450,28 @@ func (f *fragment) rangeLTUnsigned(filter *Row, bitDepth uint, predicate uint64, return matched, nil } -func (f *fragment) rangeGT(bitDepth uint, predicate int64, allowEquality bool) (*Row, error) { +func (f *fragment) rangeGT(tx Tx, bitDepth uint, predicate int64, allowEquality bool) (*Row, error) { if predicate == -1 && !allowEquality { predicate, allowEquality = 0, true } - b := f.row(bsiExistsBit) + b, err := f.row(tx, bsiExistsBit) + if err != nil { + return nil, err + } // Create predicate without sign bit. upredicate := absInt64(predicate) - sign := f.row(bsiSignBit) + sign, err := f.row(tx, bsiSignBit) + if err != nil { + return nil, err + } switch { case predicate == 0 && !allowEquality: // Match all positive numbers except zero. - nonzero, err := f.rangeNEQ(bitDepth, 0) + nonzero, err := f.rangeNEQ(tx, bitDepth, 0) if err != nil { return nil, err } @@ -1326,10 +1482,10 @@ func (f *fragment) rangeGT(bitDepth uint, predicate int64, allowEquality bool) ( return b.Difference(sign), nil case predicate >= 0: // Match all positive numbers greater than the predicate. - return f.rangeGTUnsigned(b.Difference(sign), bitDepth, upredicate, allowEquality) + return f.rangeGTUnsigned(tx, b.Difference(sign), bitDepth, upredicate, allowEquality) default: // Match all positives and greater negatives. - neg, err := f.rangeLTUnsigned(b.Intersect(sign), bitDepth, upredicate, allowEquality) + neg, err := f.rangeLTUnsigned(tx, b.Intersect(sign), bitDepth, upredicate, allowEquality) if err != nil { return nil, err } @@ -1338,7 +1494,7 @@ func (f *fragment) rangeGT(bitDepth uint, predicate int64, allowEquality bool) ( } } -func (f *fragment) rangeGTUnsigned(filter *Row, bitDepth uint, predicate uint64, allowEquality bool) (*Row, error) { +func (f *fragment) rangeGTUnsigned(tx Tx, filter *Row, bitDepth uint, predicate uint64, allowEquality bool) (*Row, error) { switch { case predicate == 0 && allowEquality: // This query matches all possible values. @@ -1347,7 +1503,10 @@ func (f *fragment) rangeGTUnsigned(filter *Row, bitDepth uint, predicate uint64, // This query matches everything that is not 0. matches := NewRow() for i := uint(0); i < bitDepth; i++ { - row := f.row(uint64(bsiOffsetBit + i)) + row, err := f.row(tx, uint64(bsiOffsetBit+i)) + if err != nil { + return nil, err + } matches = matches.Union(filter.Intersect(row)) } return matches, nil @@ -1360,7 +1519,10 @@ func (f *fragment) rangeGTUnsigned(filter *Row, bitDepth uint, predicate uint64, remaining := filter predicate |= (^uint64(0)) << bitDepth for i := int(bitDepth - 1); i >= 0 && predicate < ^uint64(0) && remaining.Any(); i-- { - row := f.row(uint64(bsiOffsetBit + i)) + row, err := f.row(tx, uint64(bsiOffsetBit+i)) + if err != nil { + return nil, err + } ones := remaining.Intersect(row) switch (predicate >> uint(i)) & 1 { case 1: @@ -1377,33 +1539,52 @@ func (f *fragment) rangeGTUnsigned(filter *Row, bitDepth uint, predicate uint64, } // notNull returns the exists row. -func (f *fragment) notNull() (*Row, error) { - return f.row(bsiExistsBit), nil +func (f *fragment) notNull(tx Tx) (*Row, error) { + return f.row(tx, bsiExistsBit) } // rangeBetween returns bitmaps with a bsiGroup value encoding matching any value between predicateMin and predicateMax. -func (f *fragment) rangeBetween(bitDepth uint, predicateMin, predicateMax int64) (*Row, error) { - b := f.row(bsiExistsBit) +func (f *fragment) rangeBetween(tx Tx, bitDepth uint, predicateMin, predicateMax int64) (*Row, error) { + b, err := f.row(tx, bsiExistsBit) + if err != nil { + return nil, err + } // Convert predicates to unsigned values. upredicateMin, upredicateMax := absInt64(predicateMin), absInt64(predicateMax) switch { case predicateMin == predicateMax: - return f.rangeEQ(bitDepth, predicateMin) + return f.rangeEQ(tx, bitDepth, predicateMin) case predicateMin >= 0: // Handle positive-only values. - return f.rangeBetweenUnsigned(b.Difference(f.row(bsiSignBit)), bitDepth, upredicateMin, upredicateMax) - case predicateMax < 0: - // Handle negative-only values. Swap unsigned min/max predicates. - return f.rangeBetweenUnsigned(b.Intersect(f.row(bsiSignBit)), bitDepth, upredicateMax, upredicateMin) - default: - // If predicate crosses positive/negative boundary then handle separately and union. - pos, err := f.rangeLTUnsigned(b.Difference(f.row(bsiSignBit)), bitDepth, upredicateMax, true) + r, err := f.row(tx, bsiSignBit) if err != nil { return nil, err } - neg, err := f.rangeLTUnsigned(b.Intersect(f.row(bsiSignBit)), bitDepth, upredicateMin, true) + return f.rangeBetweenUnsigned(tx, b.Difference(r), bitDepth, upredicateMin, upredicateMax) + case predicateMax < 0: + // Handle negative-only values. Swap unsigned min/max predicates. + r, err := f.row(tx, bsiSignBit) + if err != nil { + return nil, err + } + return f.rangeBetweenUnsigned(tx, b.Intersect(r), bitDepth, upredicateMax, upredicateMin) + default: + // If predicate crosses positive/negative boundary then handle separately and union. + r0, err := f.row(tx, bsiSignBit) + if err != nil { + return nil, err + } + pos, err := f.rangeLTUnsigned(tx, b.Difference(r0), bitDepth, upredicateMax, true) + if err != nil { + return nil, err + } + r1, err := f.row(tx, bsiSignBit) + if err != nil { + return nil, err + } + neg, err := f.rangeLTUnsigned(tx, b.Intersect(r1), bitDepth, upredicateMin, true) if err != nil { return nil, err } @@ -1412,21 +1593,24 @@ func (f *fragment) rangeBetween(bitDepth uint, predicateMin, predicateMax int64) } // rangeBetweenUnsigned returns BSI columns for a range of values. Disregards the sign bit. -func (f *fragment) rangeBetweenUnsigned(filter *Row, bitDepth uint, predicateMin, predicateMax uint64) (*Row, error) { +func (f *fragment) rangeBetweenUnsigned(tx Tx, filter *Row, bitDepth uint, predicateMin, predicateMax uint64) (*Row, error) { switch { case predicateMax > (1< firstDiff; i-- { - row := f.row(uint64(bsiOffsetBit + i)) + row, err := f.row(tx, uint64(bsiOffsetBit+i)) + if err != nil { + return nil, err + } switch (predicateMin >> uint(i)) & 1 { case 1: remaining = remaining.Intersect(row) @@ -1436,11 +1620,11 @@ func (f *fragment) rangeBetweenUnsigned(filter *Row, bitDepth uint, predicateMin } var err error - remaining, err = f.rangeGTUnsigned(remaining, uint(firstDiff+1), predicateMin, true) + remaining, err = f.rangeGTUnsigned(tx, remaining, uint(firstDiff+1), predicateMin, true) if err != nil { return nil, err } - remaining, err = f.rangeLTUnsigned(remaining, uint(firstDiff+1), predicateMax, true) + remaining, err = f.rangeLTUnsigned(tx, remaining, uint(firstDiff+1), predicateMax, true) if err != nil { return nil, err } @@ -1459,29 +1643,23 @@ func (f *fragment) pos(rowID, columnID uint64) (uint64, error) { // forEachBit executes fn for every bit set in the fragment. // Errors returned from fn are passed through. -func (f *fragment) forEachBit(fn func(rowID, columnID uint64) error) error { +func (f *fragment) forEachBit(tx Tx, fn func(rowID, columnID uint64) error) error { f.mu.Lock() defer f.mu.Unlock() - - var err error - f.storage.ForEach(func(i uint64) { - // Skip if an error has already occurred. - if err != nil { - return - } - - // Invoke caller's function. - err = fn(i/ShardWidth, (f.shard*ShardWidth)+(i%ShardWidth)) + return tx.ForEach(f.index, f.field, f.view, f.shard, func(i uint64) error { + return fn(i/ShardWidth, (f.shard*ShardWidth)+(i%ShardWidth)) }) - return err } // top returns the top rows from the fragment. // If opt.Src is specified then only rows which intersect src are returned. // If opt.FilterValues exist then the row attribute specified by field is matched. -func (f *fragment) top(opt topOptions) ([]Pair, error) { +func (f *fragment) top(tx Tx, opt topOptions) ([]Pair, error) { // Retrieve pairs. If no row ids specified then return from cache. - pairs := f.topBitmapPairs(opt.RowIDs) + pairs, err := f.topBitmapPairs(tx, opt.RowIDs) + if err != nil { + return nil, err + } // If row ids are provided, we don't want to truncate the result set if len(opt.RowIDs) > 0 { @@ -1550,7 +1728,11 @@ func (f *fragment) top(opt topOptions) ([]Pair, error) { // Calculate count and append. count := cnt if opt.Src != nil { - count = opt.Src.intersectionCount(f.row(rowID)) + r, err := f.row(tx, rowID) + if err != nil { + return nil, err + } + count = opt.Src.intersectionCount(r) } if count == 0 { continue @@ -1594,7 +1776,11 @@ func (f *fragment) top(opt topOptions) ([]Pair, error) { // Calculate the intersecting column count and skip if it's below our // last row in our current result set. - count := opt.Src.intersectionCount(f.row(rowID)) + r, err := f.row(tx, rowID) + if err != nil { + return nil, err + } + count := opt.Src.intersectionCount(r) if count < threshold { continue } @@ -1613,17 +1799,17 @@ func (f *fragment) top(opt topOptions) ([]Pair, error) { return r, nil } -func (f *fragment) topBitmapPairs(rowIDs []uint64) []bitmapPair { +func (f *fragment) topBitmapPairs(tx Tx, rowIDs []uint64) ([]bitmapPair, error) { // Don't retrieve from storage if CacheTypeNone. if f.CacheType == CacheTypeNone { - return f.cache.Top() + return f.cache.Top(), nil } // If no specific rows are requested, retrieve top rows. if len(rowIDs) == 0 { f.mu.Lock() defer f.mu.Unlock() f.cache.Invalidate() - return f.cache.Top() + return f.cache.Top(), nil } // Otherwise retrieve specific rows. @@ -1638,7 +1824,10 @@ func (f *fragment) topBitmapPairs(rowIDs []uint64) []bitmapPair { continue } - row := f.row(rowID) + row, err := f.row(tx, rowID) + if err != nil { + return nil, err + } if row.Count() > 0 { // Otherwise load from storage. pairs = append(pairs, bitmapPair{ @@ -1647,8 +1836,9 @@ func (f *fragment) topBitmapPairs(rowIDs []uint64) []bitmapPair { }) } } - sort.Sort(bitmapPairs(pairs)) - return pairs + sortPairs := bitmapPairs(pairs) + sort.Sort(&sortPairs) + return pairs, nil } // topOptions represents options passed into the Top() function. @@ -1671,12 +1861,18 @@ type topOptions struct { // Checksum returns a checksum for the entire fragment. // If two fragments have the same checksum then they have the same data. -func (f *fragment) Checksum() []byte { +func (f *fragment) Checksum() ([]byte, error) { h := xxhash.New() - for _, block := range f.Blocks() { + + blocks, err := f.Blocks() + if err != nil { + return nil, err + } + + for _, block := range blocks { _, _ = h.Write(block.Checksum) } - return h.Sum(nil) + return h.Sum(nil), nil } // InvalidateChecksums clears all cached block checksums. @@ -1687,7 +1883,7 @@ func (f *fragment) InvalidateChecksums() { } // Blocks returns info for all blocks containing data. -func (f *fragment) Blocks() []FragmentBlock { +func (f *fragment) Blocks() ([]FragmentBlock, error) { f.mu.Lock() defer f.mu.Unlock() @@ -1703,7 +1899,7 @@ func (f *fragment) Blocks() []FragmentBlock { // Iterate over each value in the fragment. v, eof := itr.Next() if eof { - return nil + return nil, nil } blockID := int(v / (HashBlockSize * ShardWidth)) for { @@ -1749,7 +1945,7 @@ func (f *fragment) Blocks() []FragmentBlock { } } - return a + return a, nil } // readContiguousChecksums appends multiple checksums in a row and returns the count added. @@ -1768,14 +1964,17 @@ func (f *fragment) readContiguousChecksums(a *[]FragmentBlock, blockID int) (n i } // blockData returns bits in a block as row & column ID pairs. -func (f *fragment) blockData(id int) (rowIDs, columnIDs []uint64) { +func (f *fragment) blockData(id int) (rowIDs, columnIDs []uint64, err error) { f.mu.Lock() defer f.mu.Unlock() - f.storage.ForEachRange(uint64(id)*HashBlockSize*ShardWidth, (uint64(id)+1)*HashBlockSize*ShardWidth, func(i uint64) { + if err := f.storage.ForEachRange(uint64(id)*HashBlockSize*ShardWidth, (uint64(id)+1)*HashBlockSize*ShardWidth, func(i uint64) error { rowIDs = append(rowIDs, i/ShardWidth) columnIDs = append(columnIDs, i%ShardWidth) - }) - return rowIDs, columnIDs + return nil + }); err != nil { + return nil, nil, err + } + return rowIDs, columnIDs, nil } // mergeBlock compares the block's bits and computes a diff with another set of block bits. @@ -1784,7 +1983,7 @@ func (f *fragment) blockData(id int) (rowIDs, columnIDs []uint64) { // For example, if 3 blocks are compared and two have a set bit and one has a // cleared bit then the bit is considered set. The function returns the // diff per incoming block so that all can be in sync. -func (f *fragment) mergeBlock(id int, data []pairSet) (sets, clears []pairSet, err error) { +func (f *fragment) mergeBlock(tx Tx, id int, data []pairSet) (sets, clears []pairSet, err error) { // Ensure that all pair sets are of equal length. for i := range data { if len(data[i].rowIDs) != len(data[i].columnIDs) { @@ -1804,10 +2003,14 @@ func (f *fragment) mergeBlock(id int, data []pairSet) (sets, clears []pairSet, e maxColumnID := uint64(ShardWidth) - 1 // Create buffered iterator for local block. + bm, err := tx.RoaringBitmap(f.index, f.field, f.view, f.shard) + if err != nil { + return nil, nil, err + } itrs := make([]*bufIterator, 1, len(data)+1) itrs[0] = newBufIterator( newLimitIterator( - newRoaringIterator(f.storage.Iterator()), maxRowID, maxColumnID, + newRoaringIterator(bm.Iterator()), maxRowID, maxColumnID, ), ) @@ -1905,21 +2108,21 @@ func (f *fragment) mergeBlock(id int, data []pairSet) (sets, clears []pairSet, e // bulkImport bulk imports a set of bits and then snapshots the storage. // The cache is updated to reflect the new data. -func (f *fragment) bulkImport(rowIDs, columnIDs []uint64, options *ImportOptions) error { +func (f *fragment) bulkImport(tx Tx, rowIDs, columnIDs []uint64, options *ImportOptions) error { // Verify that there are an equal number of row ids and column ids. if len(rowIDs) != len(columnIDs) { return fmt.Errorf("mismatch of row/column len: %d != %d", len(rowIDs), len(columnIDs)) } if f.mutexVector != nil && !options.Clear { - return f.bulkImportMutex(rowIDs, columnIDs) + return f.bulkImportMutex(tx, rowIDs, columnIDs) } - return f.bulkImportStandard(rowIDs, columnIDs, options) + return f.bulkImportStandard(tx, rowIDs, columnIDs, options) } // bulkImportStandard performs a bulk import on a standard fragment. May mutate // its rowIDs and columnIDs arguments. -func (f *fragment) bulkImportStandard(rowIDs, columnIDs []uint64, options *ImportOptions) (err error) { +func (f *fragment) bulkImportStandard(tx Tx, rowIDs, columnIDs []uint64, options *ImportOptions) (err error) { // rowSet maintains the set of rowIDs present in this import. It allows the // cache to be updated once per row, instead of once per bit. TODO: consider // sorting by rowID/columnID first and avoiding the map allocation here. (we @@ -2005,11 +2208,11 @@ func (f *fragment) importPositions(set, clear []uint64, rowSet map[uint64]struct // we got an error. it's possible that the error indicates that something went wrong. mappedIn, mappedOut, unmappedIn, errs, e2 := f.storage.SanityCheckMapping(f.currdata.from, f.currdata.to) if errs != 0 { - f.Logger.Printf("transaction failed on %s. storage has %d mapped in range, %d mapped out of range, %d unmapped in range, %d errors total, last %v", + f.holder.Logger.Printf("transaction failed on %s. storage has %d mapped in range, %d mapped out of range, %d unmapped in range, %d errors total, last %v", f.path, mappedIn, mappedOut, unmappedIn, errs, e2) if f.prevdata.from != f.currdata.from { mappedIn, mappedOut, unmappedIn, errs, e2 = f.storage.SanityCheckMapping(f.prevdata.from, f.prevdata.to) - f.Logger.Printf("with previous map, storage would have %d mapped in range, %d mapped out of range, %d unmapped in range, %d errors total, last %v", + f.holder.Logger.Printf("with previous map, storage would have %d mapped in range, %d mapped out of range, %d unmapped in range, %d errors total, last %v", mappedIn, mappedOut, unmappedIn, errs, e2) } } @@ -2021,7 +2224,7 @@ func (f *fragment) importPositions(set, clear []uint64, rowSet map[uint64]struct // mutex restrictions. Because the mutex requirements must be checked // against storage, this method must acquire a write lock on the fragment // during the entire process, and it handles every bit independently. -func (f *fragment) bulkImportMutex(rowIDs, columnIDs []uint64) error { +func (f *fragment) bulkImportMutex(tx Tx, rowIDs, columnIDs []uint64) error { f.mu.Lock() defer f.mu.Unlock() @@ -2040,7 +2243,7 @@ func (f *fragment) bulkImportMutex(rowIDs, columnIDs []uint64) error { clearIdx := 0 for i := range rowIDs { rowID, columnID := rowIDs[i], columnIDs[i] - if existingRowID, found, err := f.mutexVector.Get(columnID); err != nil { + if existingRowID, found, err := f.mutexVector.Get(tx, columnID); err != nil { return errors.Wrap(err, "getting mutex vector data") } else if found && existingRowID != rowID { // Determine the position of the bit in the storage. @@ -2119,7 +2322,7 @@ func (f *fragment) importValueSmallWrite(columnIDs []uint64, values []int64, bit } // importValue bulk imports a set of range-encoded values. -func (f *fragment) importValue(columnIDs []uint64, values []int64, bitDepth uint, clear bool) error { +func (f *fragment) importValue(tx Tx, columnIDs []uint64, values []int64, bitDepth uint, clear bool) error { f.mu.Lock() defer f.mu.Unlock() @@ -2134,12 +2337,14 @@ func (f *fragment) importValue(columnIDs []uint64, values []int64, bitDepth uint // Process every value. // If an error occurs then reopen the storage. - f.storage.OpWriter = nil + if f.storage != nil { + f.storage.OpWriter = nil + } totalChanges := 0 if err := func() (err error) { for i := range columnIDs { columnID, value := columnIDs[i], values[i] - changed, err := f.importSetValue(columnID, bitDepth, value, clear) + changed, err := f.importSetValue(tx, columnID, bitDepth, value, clear) if err != nil { return errors.Wrapf(err, "importSetValue") } @@ -2163,7 +2368,7 @@ func (f *fragment) importValue(columnIDs []uint64, values []int64, bitDepth uint // in theory, this should probably have been queued anyway, but if enough // of the bits matched existing bits, we'll be under our opN estimate, and // we want to ensure that the snapshot happens. - return f.snapshotQueue.Immediate(f) + return f.holder.SnapshotQueue.Immediate(f) } // importRoaring imports from the official roaring data format defined at @@ -2229,12 +2434,12 @@ func (f *fragment) unprotectedImportRoaring(ctx context.Context, data []byte, cl } // importRoaringOverwrite overwrites the specified block with the provided data. -func (f *fragment) importRoaringOverwrite(ctx context.Context, data []byte, block int) error { +func (f *fragment) importRoaringOverwrite(ctx context.Context, tx Tx, data []byte, block int) error { f.mu.Lock() defer f.mu.Unlock() // Clear the existing data from fragment block. - if _, err := f.unprotectedClearBlock(block); err != nil { + if _, err := f.unprotectedClearBlock(tx, block); err != nil { return errors.Wrapf(err, "clearing block: %d", block) } @@ -2251,7 +2456,7 @@ func (f *fragment) incrementOpN(changed int) { f.opN += changed f.ops++ if f.opN > f.MaxOpN { - f.snapshotQueue.Enqueue(f) + f.holder.SnapshotQueue.Enqueue(f) } } @@ -2274,6 +2479,9 @@ func track(start time.Time, message string, stats stats.StatsClient, logger logg // snapshot does the actual snapshot operation. it does not check or care // about f.snapshotPending. func (f *fragment) snapshot() (err error) { + if !f.open { + return errors.New("snapshot request on closed fragment") + } wouldPanic := debug.SetPanicOnFault(true) defer func() { debug.SetPanicOnFault(wouldPanic) @@ -2285,7 +2493,7 @@ func (f *fragment) snapshot() (err error) { // we can't see the actual values that were used to generate this, probably. if e2.Error() == "runtime error: invalid memory address or nil pointer dereference" { mappedIn, mappedOut, unmappedIn, errs, _ := f.storage.SanityCheckMapping(f.currdata.from, f.currdata.to) - f.Logger.Printf("transaction failed on %s. storage has %d mapped in range, %d mapped out of range, %d unmapped in range, %d errors total", + f.holder.Logger.Printf("transaction failed on %s. storage has %d mapped in range, %d mapped out of range, %d unmapped in range, %d errors total", f.path, mappedIn, mappedOut, unmappedIn, errs) } } else { @@ -2305,7 +2513,7 @@ func (f *fragment) snapshot() (err error) { func unprotectedWriteToFragment(f *fragment, bm *roaring.Bitmap) (n int64, err error) { // nolint: interfacer completeMessage := fmt.Sprintf("fragment: snapshot complete %s/%s/%s/%d", f.index, f.field, f.view, f.shard) start := time.Now() - defer track(start, completeMessage, f.stats, f.Logger) + defer track(start, completeMessage, f.stats, f.holder.Logger) // Create a temporary file to snapshot to. snapshotPath := f.path + snapshotExt @@ -2560,9 +2768,9 @@ func (f *fragment) readCacheFromArchive(r io.Reader) error { return nil } -func (f *fragment) minRowID() (uint64, bool) { - min, ok := f.storage.Min() - return min / ShardWidth, ok +func (f *fragment) minRowID(tx Tx) (uint64, bool, error) { + min, ok, err := tx.Min(f.index, f.field, f.view, f.shard) + return min / ShardWidth, ok, err } // rowFilter is a function signature for controlling iteration over containers @@ -2595,6 +2803,22 @@ func filterColumn(col uint64) rowFilter { } } +func filterLike(like string, t TranslateStore, e chan error) rowFilter { + plan := planLike(like) + + return func(rowID, key uint64, c *roaring.Container) (include, done bool) { + keyStr, err := t.TranslateID(rowID) + if err != nil { + select { + case e <- err: + default: + } + return false, true + } + return matchLike(keyStr, plan...), false + } +} + // TODO: this works, but it would be more performant if the fragment could seek // to the next row in the rows list rather than asking the filter for each // container serially. The container iterator would need to expose a seek @@ -2632,24 +2856,27 @@ func filterWithRows(rows []uint64) rowFilter { // returning done == true will cause processing to stop after all filters for // this container have been processed. The rows accumulated up to this point // (including this row if all filters passed) will be returned. -func (f *fragment) rows(ctx context.Context, start uint64, filters ...rowFilter) []uint64 { +func (f *fragment) rows(ctx context.Context, tx Tx, start uint64, filters ...rowFilter) ([]uint64, error) { f.mu.RLock() defer f.mu.RUnlock() - return f.unprotectedRows(ctx, start, filters...) + return f.unprotectedRows(ctx, tx, start, filters...) } // unprotectedRows calls rows without grabbing the mutex. -func (f *fragment) unprotectedRows(ctx context.Context, start uint64, filters ...rowFilter) []uint64 { +func (f *fragment) unprotectedRows(ctx context.Context, tx Tx, start uint64, filters ...rowFilter) ([]uint64, error) { startKey := rowToKey(start) - i, _ := f.storage.Containers.Iterator(startKey) + i, _, err := tx.ContainerIterator(f.index, f.field, f.view, f.shard, startKey) + if err != nil { + return nil, err + } rows := make([]uint64, 0) var lastRow uint64 = math.MaxUint64 // Loop over the existing containers. for i.Next() { // caller doesn't need a result anymore. - if ctx.Err() != nil { - return nil + if err := ctx.Err(); err != nil { + return nil, err } key, c := i.Value() @@ -2676,10 +2903,10 @@ func (f *fragment) unprotectedRows(ctx context.Context, start uint64, filters .. rows = append(rows, vRow) } if done { - return rows + return rows, nil } } - return rows + return rows, nil } // blockToRoaringData converts a fragment block into a roaring.Bitmap @@ -2688,7 +2915,10 @@ func (f *fragment) unprotectedRows(ctx context.Context, start uint64, filters .. // block data as roaring without having to go through // this rows/columns step. func (f *fragment) blockToRoaringData(block int) ([]byte, error) { - rowIDs, columnIDs := f.blockData(block) + rowIDs, columnIDs, err := f.blockData(block) + if err != nil { + return nil, err + } return bitsToRoaringData(pairSet{ columnIDs: columnIDs, rowIDs: rowIDs, @@ -2710,13 +2940,14 @@ func upgradeRoaringBSIv2(f *fragment, bitDepth uint) (string, error) { f.mu.Lock() defer f.mu.Unlock() - f.storage.ForEach(func(i uint64) { + _ = f.storage.ForEach(func(i uint64) error { rowID, columnID := i/ShardWidth, (f.shard*ShardWidth)+(i%ShardWidth) if rowID == uint64(bitDepth) { _, _ = other.Add(pos(bsiExistsBit, columnID)) // move exists bit to beginning } else { _, _ = other.Add(pos(rowID+bsiOffsetBit, columnID)) // move other bits up } + return nil }) }() @@ -2745,17 +2976,17 @@ type rowIterator interface { // Seek(offset int64, whence int) (int64, error) Seek(uint64) - Next() (*Row, uint64, *int64, bool) + Next() (*Row, uint64, *int64, bool, error) } -func (f *fragment) rowIterator(wrap bool, filters ...rowFilter) rowIterator { +func (f *fragment) rowIterator(tx Tx, wrap bool, filters ...rowFilter) (rowIterator, error) { if strings.HasPrefix(f.view, viewBSIGroupPrefix) { - return f.intRowIterator(wrap, filters...) + return f.intRowIterator(tx, wrap, filters...) } // viewStandard // TODO(kuba) - IMHO we should check if f.view is viewStandard, // but because of testing the function returns set iterator as default one. - return f.setRowIterator(wrap, filters...) + return f.setRowIterator(tx, wrap, filters...) } type intRowIterator struct { @@ -2766,7 +2997,7 @@ type intRowIterator struct { wrap bool } -func (f *fragment) intRowIterator(wrap bool, filters ...rowFilter) rowIterator { +func (f *fragment) intRowIterator(tx Tx, wrap bool, filters ...rowFilter) (rowIterator, error) { it := intRowIterator{ f: f, colIDs: make(map[int64][]uint64), @@ -2779,21 +3010,37 @@ func (f *fragment) intRowIterator(wrap bool, filters ...rowFilter) rowIterator { f.mu.RLock() defer f.mu.RUnlock() - f.foreachRow(filters, func(rid uint64) { + if err := f.foreachRow(tx, filters, func(rid uint64) error { // skip exist(0) and sign(1) rows if rid == bsiExistsBit || rid == bsiSignBit { - return + return nil } val := int64(1 << (rid - bsiOffsetBit)) - for _, cid := range f.unprotectedRow(rid).Columns() { + r, err := f.unprotectedRow(tx, rid) + if err != nil { + return err + } + for _, cid := range r.Columns() { acc[cid] |= val } - }) + return nil + }); err != nil { + return nil, err + } // apply exist and sign bits - allCols := f.unprotectedRow(0).Columns() - signCols := f.unprotectedRow(1).Columns() + r0, err := f.unprotectedRow(tx, 0) + if err != nil { + return nil, err + } + allCols := r0.Columns() + + r1, err := f.unprotectedRow(tx, 1) + if err != nil { + return nil, err + } + signCols := r1.Columns() signIdx, signLen := 0, len(signCols) // all distinct values @@ -2818,12 +3065,15 @@ func (f *fragment) intRowIterator(wrap bool, filters ...rowFilter) rowIterator { } sort.Sort(it.values) - return &it + return &it, nil } -func (f *fragment) foreachRow(filters []rowFilter, fn func(rid uint64)) { +func (f *fragment) foreachRow(tx Tx, filters []rowFilter, fn func(rid uint64) error) error { var lastRow uint64 = math.MaxUint64 - i, _ := f.storage.Containers.Iterator(rowToKey(0)) + i, _, err := tx.ContainerIterator(f.index, f.field, f.view, f.shard, rowToKey(0)) + if err != nil { + return err + } // Loop over the existing containers. for i.Next() { key, c := i.Value() @@ -2847,13 +3097,16 @@ func (f *fragment) foreachRow(filters []rowFilter, fn func(rid uint64)) { if addRow { lastRow = vRow if fn != nil { - fn(vRow) + if err := fn(vRow); err != nil { + return err + } } } if done { break } } + return nil } func (it *intRowIterator) Seek(rowID uint64) { @@ -2863,10 +3116,10 @@ func (it *intRowIterator) Seek(rowID uint64) { it.cur = idx } -func (it *intRowIterator) Next() (r *Row, rowID uint64, value *int64, wrapped bool) { +func (it *intRowIterator) Next() (r *Row, rowID uint64, value *int64, wrapped bool, err error) { if it.cur >= len(it.values) { if !it.wrap || len(it.values) == 0 { - return nil, 0, nil, true + return nil, 0, nil, true, nil } wrapped = true it.cur = 0 @@ -2877,22 +3130,28 @@ func (it *intRowIterator) Next() (r *Row, rowID uint64, value *int64, wrapped bo r = NewRow(it.colIDs[*value]...) } it.cur++ - return r, rowID, value, wrapped + return r, rowID, value, wrapped, nil } type setRowIterator struct { + tx Tx f *fragment rowIDs []uint64 cur int wrap bool } -func (f *fragment) setRowIterator(wrap bool, filters ...rowFilter) rowIterator { - return &setRowIterator{ - f: f, - rowIDs: f.rows(context.Background(), 0, filters...), // TODO: this may be memory intensive in high cardinality cases - wrap: wrap, +func (f *fragment) setRowIterator(tx Tx, wrap bool, filters ...rowFilter) (rowIterator, error) { + rows, err := f.rows(context.Background(), tx, 0, filters...) + if err != nil { + return nil, err } + return &setRowIterator{ + tx: tx, + f: f, + rowIDs: rows, // TODO: this may be memory intensive in high cardinality cases + wrap: wrap, + }, nil } func (it *setRowIterator) Seek(rowID uint64) { @@ -2902,21 +3161,24 @@ func (it *setRowIterator) Seek(rowID uint64) { it.cur = idx } -func (it *setRowIterator) Next() (r *Row, rowID uint64, _ *int64, wrapped bool) { +func (it *setRowIterator) Next() (r *Row, rowID uint64, _ *int64, wrapped bool, err error) { if it.cur >= len(it.rowIDs) { if !it.wrap || len(it.rowIDs) == 0 { - return nil, 0, nil, true + return nil, 0, nil, true, nil } it.Seek(0) wrapped = true } id := it.rowIDs[it.cur] - r = it.f.row(id) + r, err = it.f.row(it.tx, id) + if err != nil { + return r, rowID, nil, wrapped, err + } rowID = id it.cur++ - return r, rowID, nil, wrapped + return r, rowID, nil, wrapped, nil } // FragmentBlock represents info about a subsection of the rows in a block. @@ -3001,7 +3263,10 @@ func (s *fragmentSyncer) syncFragment() error { for _, node := range nodes { // Read local blocks. if node.ID == s.Node.ID { - b := s.Fragment.Blocks() + b, err := s.Fragment.Blocks() + if err != nil { + return err + } blockSets = append(blockSets, b) continue } @@ -3095,7 +3360,7 @@ func (s *fragmentSyncer) syncBlockFromPrimary(id int) error { // the primary node. nodes := s.Cluster.shardNodes(f.index, f.shard) if s.Node.ID != nodes[0].ID { - f.Logger.Debugf("non-primary replica expecting sync from primary: %s, index=%s, field=%s, shard=%d", nodes[0].ID, f.index, f.field, f.shard) + f.holder.Logger.Debugf("non-primary replica expecting sync from primary: %s, index=%s, field=%s, shard=%d", nodes[0].ID, f.index, f.field, f.shard) return nil } @@ -3139,6 +3404,7 @@ func (s *fragmentSyncer) syncBlock(id int) error { defer span.Finish() f := s.Fragment + tx := &RoaringTx{fragment: f} // Read pairs from each remote block. var uris []*URI @@ -3174,7 +3440,7 @@ func (s *fragmentSyncer) syncBlock(id int) error { } // Merge blocks together. - sets, clears, err := f.mergeBlock(id, pairSets) + sets, clears, err := f.mergeBlock(tx, id, pairSets) if err != nil { return errors.Wrap(err, "merging") } @@ -3290,7 +3556,7 @@ func pos(rowID, columnID uint64) uint64 { // vector stores the mapping of colID to rowID. // It's used for a mutex field type. type vector interface { - Get(colID uint64) (uint64, bool, error) + Get(tx Tx, colID uint64) (uint64, bool, error) } // rowsVector implements the vector interface by looking @@ -3310,9 +3576,11 @@ func newRowsVector(f *fragment) *rowsVector { // Additionally, it returns true if a value was found, // otherwise it returns false. Ensure that you already // have the mutex before calling this. -func (v *rowsVector) Get(colID uint64) (uint64, bool, error) { - rows := v.f.unprotectedRows(context.Background(), 0, filterColumn(colID)) - if len(rows) > 1 { +func (v *rowsVector) Get(tx Tx, colID uint64) (uint64, bool, error) { + rows, err := v.f.unprotectedRows(context.Background(), tx, 0, filterColumn(colID)) + if err != nil { + return 0, false, err + } else if len(rows) > 1 { return 0, false, errors.New("found multiple row values for column") } else if len(rows) == 1 { return rows[0], true, nil @@ -3344,9 +3612,11 @@ func newBoolVector(f *fragment) *boolVector { // Additionally, it returns true if a value was found, // otherwise it returns false. Ensure that you already // have the fragment mutex before calling this. -func (v *boolVector) Get(colID uint64) (uint64, bool, error) { - rows := v.f.unprotectedRows(context.Background(), 0, filterColumn(colID)) - if len(rows) > 1 { +func (v *boolVector) Get(tx Tx, colID uint64) (uint64, bool, error) { + rows, err := v.f.unprotectedRows(context.Background(), tx, 0, filterColumn(colID)) + if err != nil { + return 0, false, err + } else if len(rows) > 1 { return 0, false, errors.New("found multiple row values for column") } else if len(rows) == 1 { switch rows[0] { @@ -3358,3 +3628,21 @@ func (v *boolVector) Get(colID uint64) (uint64, bool, error) { } return 0, false, nil } + +// FormatQualifiedFragmentName generates a qualified name for the fragment to be used with Tx operations. +func FormatQualifiedFragmentName(index, field, view string, shard uint64) string { + return fmt.Sprintf("%s\x00%s\x00%s\x00%d", index, field, view, shard) +} + +// ParseQualifiedFragmentName parses a qualified name into its parts. +func ParseQualifiedFragmentName(name string) (index, field, view string, shard uint64, err error) { + a := strings.Split(name, "\x00") + if len(a) < 4 { + return "", "", "", 0, fmt.Errorf("invalid qualified name: %q", name) + } + index, field, view = string(a[0]), string(a[1]), string(a[2]) + if shard, err = strconv.ParseUint(a[3], 10, 64); err != nil { + return "", "", "", 0, fmt.Errorf("invalid qualified name: %q", name) + } + return index, field, view, shard, nil +} diff --git a/fragment_internal_test.go b/fragment_internal_test.go index 5912eb132..661f8430a 100644 --- a/fragment_internal_test.go +++ b/fragment_internal_test.go @@ -54,28 +54,31 @@ func TestFragment_SetBit(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set bits on the fragment. - if _, err := f.setBit(120, 1); err != nil { + if _, err := f.setBit(tx, 120, 1); err != nil { t.Fatal(err) - } else if _, err := f.setBit(120, 6); err != nil { + } else if _, err := f.setBit(tx, 120, 6); err != nil { t.Fatal(err) - } else if _, err := f.setBit(121, 0); err != nil { + } else if _, err := f.setBit(tx, 121, 0); err != nil { t.Fatal(err) } // Verify counts on rows. - if n := f.row(120).Count(); n != 2 { + if n := f.mustRow(tx, 120).Count(); n != 2 { t.Fatalf("unexpected count: %d", n) - } else if n := f.row(121).Count(); n != 1 { + } else if n := f.mustRow(tx, 121).Count(); n != 1 { t.Fatalf("unexpected count: %d", n) } // Close and reopen the fragment & verify the data. if err := f.Reopen(); err != nil { t.Fatal(err) - } else if n := f.row(120).Count(); n != 2 { + } else if n := f.mustRow(tx, 120).Count(); n != 2 { t.Fatalf("unexpected count (reopen): %d", n) - } else if n := f.row(121).Count(); n != 1 { + } else if n := f.mustRow(tx, 121).Count(); n != 1 { t.Fatalf("unexpected count (reopen): %d", n) } } @@ -85,24 +88,27 @@ func TestFragment_ClearBit(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set and then clear bits on the fragment. - if _, err := f.setBit(1000, 1); err != nil { + if _, err := f.setBit(tx, 1000, 1); err != nil { t.Fatal(err) - } else if _, err := f.setBit(1000, 2); err != nil { + } else if _, err := f.setBit(tx, 1000, 2); err != nil { t.Fatal(err) - } else if _, err := f.clearBit(1000, 1); err != nil { + } else if _, err := f.clearBit(tx, 1000, 1); err != nil { t.Fatal(err) } // Verify count on row. - if n := f.row(1000).Count(); n != 1 { + if n := f.mustRow(tx, 1000).Count(); n != 1 { t.Fatalf("unexpected count: %d", n) } // Close and reopen the fragment & verify the data. if err := f.Reopen(); err != nil { t.Fatal(err) - } else if n := f.row(1000).Count(); n != 1 { + } else if n := f.mustRow(tx, 1000).Count(); n != 1 { t.Fatalf("unexpected count (reopen): %d", n) } } @@ -111,6 +117,10 @@ func TestFragment_ClearBit(t *testing.T) { func TestFragment_RowcacheMap(t *testing.T) { var done int64 f := mustOpenFragment("i", "f", viewStandard, 0, "") + + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Under -race, this test turns out to take a fairly long time // to run with larger OpN, because we write 50,000 bits to // the bitmap, and everything is being race-detected, and we don't @@ -121,11 +131,11 @@ func TestFragment_RowcacheMap(t *testing.T) { ch := make(chan struct{}) for i := 0; i < f.MaxOpN; i++ { - _, _ = f.setBit(0, uint64(i*32)) + _, _ = f.setBit(tx, 0, uint64(i*32)) } // force snapshot so we get a mmapped row... _ = f.Snapshot() - row := f.row(0) + row := f.mustRow(tx, 0) segment := row.Segments()[0] bitmap := segment.data @@ -143,7 +153,7 @@ func TestFragment_RowcacheMap(t *testing.T) { // then invalidates the other map... for j := 0; j < 5; j++ { for i := 0; i < f.MaxOpN; i++ { - _, _ = f.setBit(0, uint64(i*32+j+1)) + _, _ = f.setBit(tx, 0, uint64(i*32+j+1)) } } atomic.StoreInt64(&done, 1) @@ -155,24 +165,27 @@ func TestFragment_ClearRow(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set and then clear bits on the fragment. - if _, err := f.setBit(1000, 1); err != nil { + if _, err := f.setBit(tx, 1000, 1); err != nil { t.Fatal(err) - } else if _, err := f.setBit(1000, 65536); err != nil { + } else if _, err := f.setBit(tx, 1000, 65536); err != nil { t.Fatal(err) - } else if _, err := f.unprotectedClearRow(1000); err != nil { + } else if _, err := f.unprotectedClearRow(tx, 1000); err != nil { t.Fatal(err) } // Verify count on row. - if n := f.row(1000).Count(); n != 0 { + if n := f.mustRow(tx, 1000).Count(); n != 0 { t.Fatalf("unexpected count: %d", n) } // Close and reopen the fragment & verify the data. if err := f.Reopen(); err != nil { t.Fatal(err) - } else if n := f.row(1000).Count(); n != 0 { + } else if n := f.mustRow(tx, 1000).Count(); n != 0 { t.Fatalf("unexpected count (reopen): %d", n) } } @@ -182,45 +195,48 @@ func TestFragment_SetRow(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 7, "") defer f.Clean(t) + // Obtain transction. + tx := &RoaringTx{fragment: f} + rowID := uint64(1000) // Set bits on the fragment. - if _, err := f.setBit(rowID, 7*ShardWidth+1); err != nil { + if _, err := f.setBit(tx, rowID, 7*ShardWidth+1); err != nil { t.Fatal(err) - } else if _, err := f.setBit(rowID, 7*ShardWidth+65536); err != nil { + } else if _, err := f.setBit(tx, rowID, 7*ShardWidth+65536); err != nil { t.Fatal(err) } // Verify data on row. - if cols := f.row(rowID).Columns(); !reflect.DeepEqual(cols, []uint64{7*ShardWidth + 1, 7*ShardWidth + 65536}) { + if cols := f.mustRow(tx, rowID).Columns(); !reflect.DeepEqual(cols, []uint64{7*ShardWidth + 1, 7*ShardWidth + 65536}) { t.Fatalf("unexpected columns: %+v", cols) } // Verify count on row. - if n := f.row(rowID).Count(); n != 2 { + if n := f.mustRow(tx, rowID).Count(); n != 2 { t.Fatalf("unexpected count: %d", n) } // Set row (overwrite existing data). row := NewRow(7*ShardWidth+1, 7*ShardWidth+65537, 7*ShardWidth+140000) - if changed, err := f.unprotectedSetRow(row, rowID); err != nil { + if changed, err := f.unprotectedSetRow(tx, row, rowID); err != nil { t.Fatal(err) } else if !changed { t.Fatalf("expected changed value: %v", changed) } // Verify data on row. - if cols := f.row(rowID).Columns(); !reflect.DeepEqual(cols, []uint64{7*ShardWidth + 1, 7*ShardWidth + 65537, 7*ShardWidth + 140000}) { + if cols := f.mustRow(tx, rowID).Columns(); !reflect.DeepEqual(cols, []uint64{7*ShardWidth + 1, 7*ShardWidth + 65537, 7*ShardWidth + 140000}) { t.Fatalf("unexpected columns after set row: %+v", cols) } // Verify count on row. - if n := f.row(rowID).Count(); n != 3 { + if n := f.mustRow(tx, rowID).Count(); n != 3 { t.Fatalf("unexpected count after set row: %d", n) } // Close and reopen the fragment & verify the data. if err := f.Reopen(); err != nil { t.Fatal(err) - } else if n := f.row(rowID).Count(); n != 3 { + } else if n := f.mustRow(tx, rowID).Count(); n != 3 { t.Fatalf("unexpected count (reopen): %d", n) } } @@ -231,15 +247,18 @@ func TestFragment_SetValue(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set value. - if changed, err := f.setValue(100, 16, 3829); err != nil { + if changed, err := f.setValue(tx, 100, 16, 3829); err != nil { t.Fatal(err) } else if !changed { t.Fatal("expected change") } // Read value. - if value, exists, err := f.value(100, 16); err != nil { + if value, exists, err := f.value(tx, 100, 16); err != nil { t.Fatal(err) } else if value != 3829 { t.Fatalf("unexpected value: %d", value) @@ -248,7 +267,7 @@ func TestFragment_SetValue(t *testing.T) { } // Setting value should return no change. - if changed, err := f.setValue(100, 16, 3829); err != nil { + if changed, err := f.setValue(tx, 100, 16, 3829); err != nil { t.Fatal(err) } else if changed { t.Fatal("expected no change") @@ -259,22 +278,25 @@ func TestFragment_SetValue(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set value. - if changed, err := f.setValue(100, 16, 3829); err != nil { + if changed, err := f.setValue(tx, 100, 16, 3829); err != nil { t.Fatal(err) } else if !changed { t.Fatal("expected change") } // Overwriting value should overwrite all bits. - if changed, err := f.setValue(100, 16, 2028); err != nil { + if changed, err := f.setValue(tx, 100, 16, 2028); err != nil { t.Fatal(err) } else if !changed { t.Fatal("expected change") } // Read value. - if value, exists, err := f.value(100, 16); err != nil { + if value, exists, err := f.value(tx, 100, 16); err != nil { t.Fatal(err) } else if value != 2028 { t.Fatalf("unexpected value: %d", value) @@ -287,22 +309,25 @@ func TestFragment_SetValue(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set value. - if changed, err := f.setValue(100, 16, 3829); err != nil { + if changed, err := f.setValue(tx, 100, 16, 3829); err != nil { t.Fatal(err) } else if !changed { t.Fatal("expected change") } // Clear value should overwrite all bits, and set not-null to 0. - if changed, err := f.clearValue(100, 16, 2028); err != nil { + if changed, err := f.clearValue(tx, 100, 16, 2028); err != nil { t.Fatal(err) } else if !changed { t.Fatal("expected change") } // Read value. - if value, exists, err := f.value(100, 16); err != nil { + if value, exists, err := f.value(tx, 100, 16); err != nil { t.Fatal(err) } else if value != 0 { t.Fatalf("unexpected value: %d", value) @@ -315,15 +340,18 @@ func TestFragment_SetValue(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set value. - if changed, err := f.setValue(100, 10, 20); err != nil { + if changed, err := f.setValue(tx, 100, 10, 20); err != nil { t.Fatal(err) } else if !changed { t.Fatal("expected change") } // Non-existent value. - if value, exists, err := f.value(101, 11); err != nil { + if value, exists, err := f.value(tx, 101, 11); err != nil { t.Fatal(err) } else if value != 0 { t.Fatalf("unexpected value: %d", value) @@ -345,6 +373,9 @@ func TestFragment_SetValue(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set values. m := make(map[uint64]int64) for _, value := range values { @@ -352,14 +383,14 @@ func TestFragment_SetValue(t *testing.T) { m[columnID] = int64(value) - if _, err := f.setValue(columnID, bitDepth, int64(value)); err != nil { + if _, err := f.setValue(tx, columnID, bitDepth, int64(value)); err != nil { t.Fatal(err) } } // Ensure values are set. for columnID, value := range m { - v, exists, err := f.value(columnID, bitDepth) + v, exists, err := f.value(tx, columnID, bitDepth) if err != nil { t.Fatal(err) } else if value != int64(v) { @@ -383,6 +414,9 @@ func TestFragment_Sum(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set values. vals := []struct { cid uint64 @@ -395,13 +429,13 @@ func TestFragment_Sum(t *testing.T) { {4000, 300}, } for _, v := range vals { - if _, err := f.setValue(v.cid, bitDepth, v.val); err != nil { + if _, err := f.setValue(tx, v.cid, bitDepth, v.val); err != nil { t.Fatal(err) } } t.Run("NoFilter", func(t *testing.T) { - if sum, n, err := f.sum(nil, bitDepth); err != nil { + if sum, n, err := f.sum(tx, nil, bitDepth); err != nil { t.Fatal(err) } else if n != 5 { t.Fatalf("unexpected count: %d", n) @@ -411,7 +445,7 @@ func TestFragment_Sum(t *testing.T) { }) t.Run("WithFilter", func(t *testing.T) { - if sum, n, err := f.sum(NewRow(2000, 4000, 5000), bitDepth); err != nil { + if sum, n, err := f.sum(tx, NewRow(2000, 4000, 5000), bitDepth); err != nil { t.Fatal(err) } else if n != 2 { t.Fatalf("unexpected count: %d", n) @@ -421,11 +455,11 @@ func TestFragment_Sum(t *testing.T) { }) // verify that clearValue clears values - if _, err := f.clearValue(1000, bitDepth, 23); err != nil { + if _, err := f.clearValue(tx, 1000, bitDepth, 23); err != nil { t.Fatal(err) } t.Run("ClearValue", func(t *testing.T) { - if sum, n, err := f.sum(nil, bitDepth); err != nil { + if sum, n, err := f.sum(tx, nil, bitDepth); err != nil { t.Fatal(err) } else if n != 4 { t.Fatalf("unexpected count: %d", n) @@ -442,20 +476,23 @@ func TestFragment_MinMax(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set values. - if _, err := f.setValue(1000, bitDepth, 382); err != nil { + if _, err := f.setValue(tx, 1000, bitDepth, 382); err != nil { t.Fatal(err) - } else if _, err := f.setValue(2000, bitDepth, 300); err != nil { + } else if _, err := f.setValue(tx, 2000, bitDepth, 300); err != nil { t.Fatal(err) - } else if _, err := f.setValue(3000, bitDepth, 2818); err != nil { + } else if _, err := f.setValue(tx, 3000, bitDepth, 2818); err != nil { t.Fatal(err) - } else if _, err := f.setValue(4000, bitDepth, 300); err != nil { + } else if _, err := f.setValue(tx, 4000, bitDepth, 300); err != nil { t.Fatal(err) - } else if _, err := f.setValue(5000, bitDepth, 2818); err != nil { + } else if _, err := f.setValue(tx, 5000, bitDepth, 2818); err != nil { t.Fatal(err) - } else if _, err := f.setValue(6000, bitDepth, 2817); err != nil { + } else if _, err := f.setValue(tx, 6000, bitDepth, 2817); err != nil { t.Fatal(err) - } else if _, err := f.setValue(7000, bitDepth, 0); err != nil { + } else if _, err := f.setValue(tx, 7000, bitDepth, 0); err != nil { t.Fatal(err) } @@ -473,7 +510,7 @@ func TestFragment_MinMax(t *testing.T) { {filter: NewRow(7000), exp: 0, cnt: 1}, } for i, test := range tests { - if min, cnt, err := f.min(test.filter, bitDepth); err != nil { + if min, cnt, err := f.min(tx, test.filter, bitDepth); err != nil { t.Fatal(err) } else if min != test.exp { t.Errorf("test %d expected min: %v, but got: %v", i, test.exp, min) @@ -502,7 +539,7 @@ func TestFragment_MinMax(t *testing.T) { columns = test.filter.Columns() } - if max, cnt, err := f.max(test.filter, bitDepth); err != nil { + if max, cnt, err := f.max(tx, test.filter, bitDepth); err != nil { t.Fatal(err) } else if max != test.exp || cnt != test.cnt { t.Errorf("%d. max(%v, %v)=(%v, %v), expected (%v, %v)", i, columns, bitDepth, max, cnt, test.exp, test.cnt) @@ -519,19 +556,22 @@ func TestFragment_Range(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set values. - if _, err := f.setValue(1000, bitDepth, 382); err != nil { + if _, err := f.setValue(tx, 1000, bitDepth, 382); err != nil { t.Fatal(err) - } else if _, err := f.setValue(2000, bitDepth, 300); err != nil { + } else if _, err := f.setValue(tx, 2000, bitDepth, 300); err != nil { t.Fatal(err) - } else if _, err := f.setValue(3000, bitDepth, 2818); err != nil { + } else if _, err := f.setValue(tx, 3000, bitDepth, 2818); err != nil { t.Fatal(err) - } else if _, err := f.setValue(4000, bitDepth, 300); err != nil { + } else if _, err := f.setValue(tx, 4000, bitDepth, 300); err != nil { t.Fatal(err) } // Query for equality. - if b, err := f.rangeOp(pql.EQ, bitDepth, 300); err != nil { + if b, err := f.rangeOp(tx, pql.EQ, bitDepth, 300); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{2000, 4000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) @@ -542,19 +582,22 @@ func TestFragment_Range(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set values. - if _, err := f.setValue(1000, bitDepth, 382); err != nil { + if _, err := f.setValue(tx, 1000, bitDepth, 382); err != nil { t.Fatal(err) - } else if _, err := f.setValue(2000, bitDepth, 300); err != nil { + } else if _, err := f.setValue(tx, 2000, bitDepth, 300); err != nil { t.Fatal(err) - } else if _, err := f.setValue(3000, bitDepth, 2818); err != nil { + } else if _, err := f.setValue(tx, 3000, bitDepth, 2818); err != nil { t.Fatal(err) - } else if _, err := f.setValue(4000, bitDepth, 300); err != nil { + } else if _, err := f.setValue(tx, 4000, bitDepth, 300); err != nil { t.Fatal(err) } // Query for inequality. - if b, err := f.rangeOp(pql.NEQ, bitDepth, 300); err != nil { + if b, err := f.rangeOp(tx, pql.NEQ, bitDepth, 300); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{1000, 3000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) @@ -565,44 +608,47 @@ func TestFragment_Range(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set values. - if _, err := f.setValue(1000, bitDepth, 382); err != nil { + if _, err := f.setValue(tx, 1000, bitDepth, 382); err != nil { t.Fatal(err) - } else if _, err := f.setValue(2000, bitDepth, 300); err != nil { + } else if _, err := f.setValue(tx, 2000, bitDepth, 300); err != nil { t.Fatal(err) - } else if _, err := f.setValue(3000, bitDepth, 2817); err != nil { + } else if _, err := f.setValue(tx, 3000, bitDepth, 2817); err != nil { t.Fatal(err) - } else if _, err := f.setValue(4000, bitDepth, 301); err != nil { + } else if _, err := f.setValue(tx, 4000, bitDepth, 301); err != nil { t.Fatal(err) - } else if _, err := f.setValue(5000, bitDepth, 1); err != nil { + } else if _, err := f.setValue(tx, 5000, bitDepth, 1); err != nil { t.Fatal(err) - } else if _, err := f.setValue(6000, bitDepth, 0); err != nil { + } else if _, err := f.setValue(tx, 6000, bitDepth, 0); err != nil { t.Fatal(err) } // Query for values less than (ending with set column). - if b, err := f.rangeOp(pql.LT, bitDepth, 301); err != nil { + if b, err := f.rangeOp(tx, pql.LT, bitDepth, 301); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{2000, 5000, 6000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) } // Query for values less than (ending with unset column). - if b, err := f.rangeOp(pql.LT, bitDepth, 300); err != nil { + if b, err := f.rangeOp(tx, pql.LT, bitDepth, 300); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{5000, 6000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) } // Query for values less than or equal to (ending with set column). - if b, err := f.rangeOp(pql.LTE, bitDepth, 301); err != nil { + if b, err := f.rangeOp(tx, pql.LTE, bitDepth, 301); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{2000, 4000, 5000, 6000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) } // Query for values less than or equal to (ending with unset column). - if b, err := f.rangeOp(pql.LTE, bitDepth, 300); err != nil { + if b, err := f.rangeOp(tx, pql.LTE, bitDepth, 300); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{2000, 5000, 6000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) @@ -613,11 +659,14 @@ func TestFragment_Range(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) - if _, err := f.setValue(1, 1, 1); err != nil { + // Obtain transaction. + tx := &RoaringTx{fragment: f} + + if _, err := f.setValue(tx, 1, 1, 1); err != nil { t.Fatal(err) } - if b, err := f.rangeOp(pql.LT, 1, 2); err != nil { + if b, err := f.rangeOp(tx, pql.LT, 1, 2); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{1}) { t.Fatalf("unepxected coulmns: %+v", b.Columns()) @@ -628,13 +677,16 @@ func TestFragment_Range(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) - if _, err := f.setValue(1, 2, 3); err != nil { + // Obtain transaction. + tx := &RoaringTx{fragment: f} + + if _, err := f.setValue(tx, 1, 2, 3); err != nil { t.Fatal(err) - } else if _, err := f.setValue(2, 2, 0); err != nil { + } else if _, err := f.setValue(tx, 2, 2, 0); err != nil { t.Fatal(err) } - if b, err := f.rangeLTUnsigned(NewRow(1, 2), 2, 3, false); err != nil { + if b, err := f.rangeLTUnsigned(tx, NewRow(1, 2), 2, 3, false); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{2}) { t.Fatalf("unepxected coulmns: %+v", b.Columns()) @@ -645,44 +697,47 @@ func TestFragment_Range(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set values. - if _, err := f.setValue(1000, bitDepth, 382); err != nil { + if _, err := f.setValue(tx, 1000, bitDepth, 382); err != nil { t.Fatal(err) - } else if _, err := f.setValue(2000, bitDepth, 300); err != nil { + } else if _, err := f.setValue(tx, 2000, bitDepth, 300); err != nil { t.Fatal(err) - } else if _, err := f.setValue(3000, bitDepth, 2817); err != nil { + } else if _, err := f.setValue(tx, 3000, bitDepth, 2817); err != nil { t.Fatal(err) - } else if _, err := f.setValue(4000, bitDepth, 301); err != nil { + } else if _, err := f.setValue(tx, 4000, bitDepth, 301); err != nil { t.Fatal(err) - } else if _, err := f.setValue(5000, bitDepth, 1); err != nil { + } else if _, err := f.setValue(tx, 5000, bitDepth, 1); err != nil { t.Fatal(err) - } else if _, err := f.setValue(6000, bitDepth, 0); err != nil { + } else if _, err := f.setValue(tx, 6000, bitDepth, 0); err != nil { t.Fatal(err) } // Query for values greater than (ending with unset bit). - if b, err := f.rangeOp(pql.GT, bitDepth, 300); err != nil { + if b, err := f.rangeOp(tx, pql.GT, bitDepth, 300); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{1000, 3000, 4000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) } // Query for values greater than (ending with set bit). - if b, err := f.rangeOp(pql.GT, bitDepth, 301); err != nil { + if b, err := f.rangeOp(tx, pql.GT, bitDepth, 301); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{1000, 3000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) } // Query for values greater than or equal to (ending with unset bit). - if b, err := f.rangeOp(pql.GTE, bitDepth, 300); err != nil { + if b, err := f.rangeOp(tx, pql.GTE, bitDepth, 300); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{1000, 2000, 3000, 4000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) } // Query for values greater than or equal to (ending with set bit). - if b, err := f.rangeOp(pql.GTE, bitDepth, 301); err != nil { + if b, err := f.rangeOp(tx, pql.GTE, bitDepth, 301); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{1000, 3000, 4000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) @@ -693,13 +748,16 @@ func TestFragment_Range(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) - if _, err := f.setValue(1, 2, 0); err != nil { + // Obtain transaction. + tx := &RoaringTx{fragment: f} + + if _, err := f.setValue(tx, 1, 2, 0); err != nil { t.Fatal(err) - } else if _, err := f.setValue(2, 2, 1); err != nil { + } else if _, err := f.setValue(tx, 2, 2, 1); err != nil { t.Fatal(err) } - if b, err := f.rangeGTUnsigned(NewRow(1, 2), 2, 0, false); err != nil { + if b, err := f.rangeGTUnsigned(tx, NewRow(1, 2), 2, 0, false); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{2}) { t.Fatalf("unepxected coulmns: %+v", b.Columns()) @@ -710,44 +768,47 @@ func TestFragment_Range(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set values. - if _, err := f.setValue(1000, bitDepth, 382); err != nil { + if _, err := f.setValue(tx, 1000, bitDepth, 382); err != nil { t.Fatal(err) - } else if _, err := f.setValue(2000, bitDepth, 300); err != nil { + } else if _, err := f.setValue(tx, 2000, bitDepth, 300); err != nil { t.Fatal(err) - } else if _, err := f.setValue(3000, bitDepth, 2817); err != nil { + } else if _, err := f.setValue(tx, 3000, bitDepth, 2817); err != nil { t.Fatal(err) - } else if _, err := f.setValue(4000, bitDepth, 301); err != nil { + } else if _, err := f.setValue(tx, 4000, bitDepth, 301); err != nil { t.Fatal(err) - } else if _, err := f.setValue(5000, bitDepth, 1); err != nil { + } else if _, err := f.setValue(tx, 5000, bitDepth, 1); err != nil { t.Fatal(err) - } else if _, err := f.setValue(6000, bitDepth, 0); err != nil { + } else if _, err := f.setValue(tx, 6000, bitDepth, 0); err != nil { t.Fatal(err) } // Query for values greater than (ending with unset column). - if b, err := f.rangeBetween(bitDepth, 300, 2817); err != nil { + if b, err := f.rangeBetween(tx, bitDepth, 300, 2817); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{1000, 2000, 3000, 4000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) } // Query for values greater than (ending with set column). - if b, err := f.rangeBetween(bitDepth, 301, 2817); err != nil { + if b, err := f.rangeBetween(tx, bitDepth, 301, 2817); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{1000, 3000, 4000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) } // Query for values greater than or equal to (ending with unset column). - if b, err := f.rangeBetween(bitDepth, 301, 2816); err != nil { + if b, err := f.rangeBetween(tx, bitDepth, 301, 2816); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{1000, 4000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) } // Query for values greater than or equal to (ending with set column). - if b, err := f.rangeBetween(bitDepth, 300, 2816); err != nil { + if b, err := f.rangeBetween(tx, bitDepth, 300, 2816); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(b.Columns(), []uint64{1000, 2000, 4000}) { t.Fatalf("unexpected columns: %+v", b.Columns()) @@ -758,11 +819,14 @@ func TestFragment_Range(t *testing.T) { // benchmarkSetValues is a helper function to explore, very roughly, the cost // of setting values. func benchmarkSetValues(b *testing.B, bitDepth uint, f *fragment, cfunc func(uint64) uint64) { + // Obtain transaction. + tx := &RoaringTx{fragment: f} + column := uint64(0) for i := 0; i < b.N; i++ { // We're not checking the error because this is a benchmark. // That does mean the result could be completely wrong... - _, _ = f.setValue(column, bitDepth, int64(i)) + _, _ = f.setValue(tx, column, bitDepth, int64(i)) column = cfunc(column) } } @@ -773,6 +837,7 @@ func BenchmarkFragment_SetValue(b *testing.B) { for _, bitDepth := range depths { name := fmt.Sprintf("Depth%d", bitDepth) f := mustOpenFragment("i", "f", viewBSIGroupPrefix+"foo", 0, "none") + b.Run(name+"_Sparse", func(b *testing.B) { benchmarkSetValues(b, bitDepth, f, func(u uint64) uint64 { return (u + 70000) & (ShardWidth - 1) }) }) @@ -788,6 +853,9 @@ func BenchmarkFragment_SetValue(b *testing.B) { // benchmarkImportValues is a helper function to explore, very roughly, the cost // of setting values using the special setter used for imports. func benchmarkImportValues(b *testing.B, bitDepth uint, f *fragment, cfunc func(uint64) uint64) { + // Obtain transaction. + tx := &RoaringTx{fragment: f} + column := uint64(0) b.StopTimer() columns := make([]uint64, b.N) @@ -798,7 +866,7 @@ func benchmarkImportValues(b *testing.B, bitDepth uint, f *fragment, cfunc func( column = cfunc(column) } b.StartTimer() - err := f.importValue(columns, values, bitDepth, false) + err := f.importValue(tx, columns, values, bitDepth, false) if err != nil { b.Fatalf("error importing values: %s", err) } @@ -851,13 +919,17 @@ func BenchmarkFragment_RepeatedSmallImports(b *testing.B) { f := mustOpenFragment("i", "f", viewStandard, 0, "") f.MaxOpN = opN defer f.Clean(b) + + // Obtain transaction. + tx := &RoaringTx{fragment: f} + err := f.importRoaringT(getZipfRowsSliceRoaring(uint64(numRows), 1, 0, ShardWidth), false) if err != nil { b.Fatalf("importing base data for benchmark: %v", err) } b.StartTimer() for i := 0; i < numUpdates; i++ { - err := f.bulkImportStandard( + err := f.bulkImportStandard(tx, updateRows[bitsPerUpdate*i:bitsPerUpdate*(i+1)], updateRows[bitsPerUpdate*i:bitsPerUpdate*(i+1)], &ImportOptions{}, @@ -887,6 +959,7 @@ func BenchmarkFragment_RepeatedSmallImportsRoaring(b *testing.B) { f := mustOpenFragment("i", "f", viewStandard, 0, "") f.MaxOpN = opN defer f.Clean(b) + err := f.importRoaringT(getZipfRowsSliceRoaring(numRows, 1, 0, ShardWidth), false) if err != nil { b.Fatalf("importing base data for benchmark: %v", err) @@ -935,13 +1008,17 @@ func BenchmarkFragment_RepeatedSmallValueImports(b *testing.B) { b.StopTimer() f := mustOpenBSIFragment("i", "f", viewBSIGroupPrefix+"foo", 0) f.MaxOpN = opN - err := f.importValue(initialCols, initialVals, 21, false) + + // Obtain transaction. + tx := &RoaringTx{fragment: f} + + err := f.importValue(tx, initialCols, initialVals, 21, false) if err != nil { b.Fatalf("initial value import: %v", err) } b.StartTimer() for j := 0; j < numUpdates; j++ { - err := f.importValue( + err := f.importValue(tx, updateCols[valsPerUpdate*j:valsPerUpdate*(j+1)], updateVals[valsPerUpdate*j:valsPerUpdate*(j+1)], 21, @@ -964,26 +1041,29 @@ func TestFragment_Snapshot(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set and then clear bits on the fragment. - if _, err := f.setBit(1000, 1); err != nil { + if _, err := f.setBit(tx, 1000, 1); err != nil { t.Fatal(err) - } else if _, err := f.setBit(1000, 2); err != nil { + } else if _, err := f.setBit(tx, 1000, 2); err != nil { t.Fatal(err) - } else if _, err := f.clearBit(1000, 1); err != nil { + } else if _, err := f.clearBit(tx, 1000, 1); err != nil { t.Fatal(err) } // Snapshot bitmap and verify data. if err := f.Snapshot(); err != nil { t.Fatal(err) - } else if n := f.row(1000).Count(); n != 1 { + } else if n := f.mustRow(tx, 1000).Count(); n != 1 { t.Fatalf("unexpected count: %d", n) } // Close and reopen the fragment & verify the data. if err := f.Reopen(); err != nil { t.Fatal(err) - } else if n := f.row(1000).Count(); n != 1 { + } else if n := f.mustRow(tx, 1000).Count(); n != 1 { t.Fatalf("unexpected count (reopen): %d", n) } } @@ -993,18 +1073,21 @@ func TestFragment_ForEachBit(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set bits on the fragment. - if _, err := f.setBit(100, 20); err != nil { + if _, err := f.setBit(tx, 100, 20); err != nil { t.Fatal(err) - } else if _, err := f.setBit(2, 38); err != nil { + } else if _, err := f.setBit(tx, 2, 38); err != nil { t.Fatal(err) - } else if _, err := f.setBit(2, 37); err != nil { + } else if _, err := f.setBit(tx, 2, 37); err != nil { t.Fatal(err) } // Iterate over bits. var result [][2]uint64 - if err := f.forEachBit(func(rowID, columnID uint64) error { + if err := f.forEachBit(tx, func(rowID, columnID uint64) error { result = append(result, [2]uint64{rowID, columnID}) return nil }); err != nil { @@ -1021,14 +1104,18 @@ func TestFragment_ForEachBit(t *testing.T) { func TestFragment_Top(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, CacheTypeRanked) defer f.Clean(t) + + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set bits on the rows 100, 101, & 102. - f.mustSetBits(100, 1, 3, 200) - f.mustSetBits(101, 1) - f.mustSetBits(102, 1, 2) + f.mustSetBits(tx, 100, 1, 3, 200) + f.mustSetBits(tx, 101, 1) + f.mustSetBits(tx, 102, 1, 2) f.RecalculateCache() // Retrieve top rows. - if pairs, err := f.top(topOptions{N: 2}); err != nil { + if pairs, err := f.top(tx, topOptions{N: 2}); err != nil { t.Fatal(err) } else if len(pairs) != 2 { t.Fatalf("unexpected count: %d", len(pairs)) @@ -1044,10 +1131,13 @@ func TestFragment_Top_Filter(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, CacheTypeRanked) defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set bits on the rows 100, 101, & 102. - f.mustSetBits(100, 1, 3, 200) - f.mustSetBits(101, 1) - f.mustSetBits(102, 1, 2) + f.mustSetBits(tx, 100, 1, 3, 200) + f.mustSetBits(tx, 101, 1) + f.mustSetBits(tx, 102, 1, 2) f.RecalculateCache() // Assign attributes. err := f.RowAttrStore.SetAttrs(101, map[string]interface{}{"x": int64(10)}) @@ -1060,7 +1150,7 @@ func TestFragment_Top_Filter(t *testing.T) { } // Retrieve top rows. - if pairs, err := f.top(topOptions{ + if pairs, err := f.top(tx, topOptions{ N: 2, FilterName: "x", FilterValues: []interface{}{int64(10), int64(15), int64(20)}, @@ -1080,18 +1170,21 @@ func TestFragment_TopN_Intersect(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, CacheTypeRanked) defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Create an intersecting input row. src := NewRow(1, 2, 3) // Set bits on various rows. - f.mustSetBits(100, 1, 10, 11, 12) // one intersection - f.mustSetBits(101, 1, 2, 3, 4) // three intersections - f.mustSetBits(102, 1, 2, 4, 5, 6) // two intersections - f.mustSetBits(103, 1000, 1001, 1002) // no intersection + f.mustSetBits(tx, 100, 1, 10, 11, 12) // one intersection + f.mustSetBits(tx, 101, 1, 2, 3, 4) // three intersections + f.mustSetBits(tx, 102, 1, 2, 4, 5, 6) // two intersections + f.mustSetBits(tx, 103, 1000, 1001, 1002) // no intersection f.RecalculateCache() // Retrieve top rows. - if pairs, err := f.top(topOptions{N: 3, Src: src}); err != nil { + if pairs, err := f.top(tx, topOptions{N: 3, Src: src}); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(pairs, []Pair{ {ID: 101, Count: 3}, @@ -1111,6 +1204,9 @@ func TestFragment_TopN_Intersect_Large(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, CacheTypeRanked) defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Create an intersecting input row. src := NewRow( 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, @@ -1136,7 +1232,7 @@ func TestFragment_TopN_Intersect_Large(t *testing.T) { f.RecalculateCache() // Retrieve top rows. - if pairs, err := f.top(topOptions{N: 10, Src: src}); err != nil { + if pairs, err := f.top(tx, topOptions{N: 10, Src: src}); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(pairs, []Pair{ {ID: 999, Count: 19}, @@ -1159,13 +1255,16 @@ func TestFragment_TopN_IDs(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, CacheTypeRanked) defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set bits on various rows. - f.mustSetBits(100, 1, 2, 3) - f.mustSetBits(101, 4, 5, 6, 7) - f.mustSetBits(102, 8, 9, 10, 11, 12) + f.mustSetBits(tx, 100, 1, 2, 3) + f.mustSetBits(tx, 101, 4, 5, 6, 7) + f.mustSetBits(tx, 102, 8, 9, 10, 11, 12) // Retrieve top rows. - if pairs, err := f.top(topOptions{RowIDs: []uint64{100, 101, 200}}); err != nil { + if pairs, err := f.top(tx, topOptions{RowIDs: []uint64{100, 101, 200}}); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(pairs, []Pair{ {ID: 101, Count: 4}, @@ -1180,13 +1279,16 @@ func TestFragment_TopN_NopCache(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, CacheTypeNone) defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set bits on various rows. - f.mustSetBits(100, 1, 2, 3) - f.mustSetBits(101, 4, 5, 6, 7) - f.mustSetBits(102, 8, 9, 10, 11, 12) + f.mustSetBits(tx, 100, 1, 2, 3) + f.mustSetBits(tx, 101, 4, 5, 6, 7) + f.mustSetBits(tx, 102, 8, 9, 10, 11, 12) // Retrieve top rows. - if pairs, err := f.top(topOptions{RowIDs: []uint64{100, 101, 200}}); err != nil { + if pairs, err := f.top(tx, topOptions{RowIDs: []uint64{100, 101, 200}}); err != nil { t.Fatal(err) } else if !reflect.DeepEqual(pairs, []Pair{}) { t.Fatalf("unexpected pairs: %s", spew.Sdump(pairs)) @@ -1228,13 +1330,16 @@ func TestFragment_TopN_CacheSize(t *testing.T) { } defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set bits on various rows. - f.mustSetBits(100, 1, 2, 3) - f.mustSetBits(101, 4, 5, 6, 7) - f.mustSetBits(102, 8, 9, 10, 11, 12) - f.mustSetBits(103, 8, 9, 10, 11, 12, 13) - f.mustSetBits(104, 8, 9, 10, 11, 12, 13, 14) - f.mustSetBits(105, 10, 11) + f.mustSetBits(tx, 100, 1, 2, 3) + f.mustSetBits(tx, 101, 4, 5, 6, 7) + f.mustSetBits(tx, 102, 8, 9, 10, 11, 12) + f.mustSetBits(tx, 103, 8, 9, 10, 11, 12, 13) + f.mustSetBits(tx, 104, 8, 9, 10, 11, 12, 13, 14) + f.mustSetBits(tx, 105, 10, 11) f.RecalculateCache() @@ -1245,7 +1350,7 @@ func TestFragment_TopN_CacheSize(t *testing.T) { } // Retrieve top rows. - if pairs, err := f.top(topOptions{N: 5}); err != nil { + if pairs, err := f.top(tx, topOptions{N: 5}); err != nil { t.Fatal(err) } else if len(pairs) > int(cacheSize) { t.Fatalf("TopN count cannot exceed cache size: %d", cacheSize) @@ -1261,16 +1366,24 @@ func TestFragment_Checksum(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Retrieve checksum and set bits. - orig := f.Checksum() - if _, err := f.setBit(1, 200); err != nil { + orig, err := f.Checksum() + if err != nil { t.Fatal(err) - } else if _, err := f.setBit(HashBlockSize*2, 200); err != nil { + } + if _, err := f.setBit(tx, 1, 200); err != nil { + t.Fatal(err) + } else if _, err := f.setBit(tx, HashBlockSize*2, 200); err != nil { t.Fatal(err) } // Ensure new checksum is different. - if chksum := f.Checksum(); bytes.Equal(chksum, orig) { + if chksum, err := f.Checksum(); err != nil { + t.Fatal(err) + } else if bytes.Equal(chksum, orig) { t.Fatalf("expected checksum to change: %x - %x", chksum, orig) } } @@ -1280,35 +1393,44 @@ func TestFragment_Blocks(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Retrieve initial checksum. var prev []FragmentBlock // Set first bit. - if _, err := f.setBit(0, 0); err != nil { + if _, err := f.setBit(tx, 0, 0); err != nil { t.Fatal(err) } - blocks := f.Blocks() - if blocks[0].Checksum == nil { + blocks, err := f.Blocks() + if err != nil { + t.Fatal(err) + } else if blocks[0].Checksum == nil { t.Fatalf("expected checksum: %x", blocks[0].Checksum) } prev = blocks // Set bit on different row. - if _, err := f.setBit(20, 0); err != nil { + if _, err := f.setBit(tx, 20, 0); err != nil { t.Fatal(err) } - blocks = f.Blocks() - if bytes.Equal(blocks[0].Checksum, prev[0].Checksum) { + blocks, err = f.Blocks() + if err != nil { + t.Fatal(err) + } else if bytes.Equal(blocks[0].Checksum, prev[0].Checksum) { t.Fatalf("expected checksum to change: %x", blocks[0].Checksum) } prev = blocks // Set bit on different column. - if _, err := f.setBit(20, 100); err != nil { + if _, err := f.setBit(tx, 20, 100); err != nil { t.Fatal(err) } - blocks = f.Blocks() - if bytes.Equal(blocks[0].Checksum, prev[0].Checksum) { + blocks, err = f.Blocks() + if err != nil { + t.Fatal(err) + } else if bytes.Equal(blocks[0].Checksum, prev[0].Checksum) { t.Fatalf("expected checksum to change: %x", blocks[0].Checksum) } } @@ -1318,13 +1440,18 @@ func TestFragment_Blocks_Empty(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set bits on a different block. - if _, err := f.setBit(100, 1); err != nil { + if _, err := f.setBit(tx, 100, 1); err != nil { t.Fatal(err) } // Ensure checksum for block 1 is blank. - if blocks := f.Blocks(); len(blocks) != 1 { + if blocks, err := f.Blocks(); err != nil { + t.Fatal(err) + } else if len(blocks) != 1 { t.Fatalf("unexpected block count: %d", len(blocks)) } else if blocks[0].ID != 1 { t.Fatalf("unexpected block id: %d", blocks[0].ID) @@ -1336,9 +1463,12 @@ func TestFragment_LRUCache_Persistence(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, CacheTypeLRU) defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set bits on the fragment. for i := uint64(0); i < 1000; i++ { - if _, err := f.setBit(i, 0); err != nil { + if _, err := f.setBit(tx, i, 0); err != nil { t.Fatal(err) } } @@ -1386,9 +1516,12 @@ func TestFragment_RankCache_Persistence(t *testing.T) { t.Fatal(err) } + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set bits on the fragment. for i := uint64(0); i < 1000; i++ { - if _, err := f.setBit(i, 0); err != nil { + if _, err := f.setBit(tx, i, 0); err != nil { t.Fatal(err) } } @@ -1421,12 +1554,15 @@ func TestFragment_WriteTo_ReadFrom(t *testing.T) { f0 := mustOpenFragment("i", "f", viewStandard, 0, "") defer f0.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f0} + // Set and then clear bits on the fragment. - if _, err := f0.setBit(1000, 1); err != nil { + if _, err := f0.setBit(tx, 1000, 1); err != nil { t.Fatal(err) - } else if _, err := f0.setBit(1000, 2); err != nil { + } else if _, err := f0.setBit(tx, 1000, 2); err != nil { t.Fatal(err) - } else if _, err := f0.clearBit(1000, 1); err != nil { + } else if _, err := f0.clearBit(tx, 1000, 1); err != nil { t.Fatal(err) } @@ -1445,6 +1581,7 @@ func TestFragment_WriteTo_ReadFrom(t *testing.T) { // Read into another fragment. f1 := mustOpenFragment("i", "f", viewStandard, 0, "") defer f1.Clean(t) + if rn, err := f1.ReadFrom(&buf); err != nil { t.Fatal(err) } else if wn != rn { @@ -1457,7 +1594,7 @@ func TestFragment_WriteTo_ReadFrom(t *testing.T) { } // Verify data in other fragment. - if a := f1.row(1000).Columns(); !reflect.DeepEqual(a, []uint64{2}) { + if a := f1.mustRow(tx, 1000).Columns(); !reflect.DeepEqual(a, []uint64{2}) { t.Fatalf("unexpected columns: %+v", a) } @@ -1466,7 +1603,7 @@ func TestFragment_WriteTo_ReadFrom(t *testing.T) { t.Fatal(err) } else if n := f1.cache.Len(); n != 1 { t.Fatalf("unexpected cache size (reopen): %d", n) - } else if a := f1.row(1000).Columns(); !reflect.DeepEqual(a, []uint64{2}) { + } else if a := f1.mustRow(tx, 1000).Columns(); !reflect.DeepEqual(a, []uint64{2}) { t.Fatalf("unexpected columns (reopen): %+v", a) } } @@ -1477,7 +1614,7 @@ func BenchmarkFragment_Blocks(b *testing.B) { } // Open the fragment specified by the path. - f := newFragment(*FragmentPath, "i", "f", viewStandard, 0, 0) + f := newFragment(NewHolder(DefaultPartitionN), *FragmentPath, "i", "f", viewStandard, 0, 0) if err := f.Open(); err != nil { b.Fatal(err) } @@ -1486,7 +1623,9 @@ func BenchmarkFragment_Blocks(b *testing.B) { // Reset timer and execute benchmark. b.ResetTimer() for i := 0; i < b.N; i++ { - if a := f.Blocks(); len(a) == 0 { + if a, err := f.Blocks(); err != nil { + b.Fatal(err) + } else if len(a) == 0 { b.Fatal("no blocks in fragment") } } @@ -1497,14 +1636,17 @@ func BenchmarkFragment_IntersectionCount(b *testing.B) { defer f.Clean(b) f.MaxOpN = math.MaxInt32 + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Generate some intersecting data. for i := 0; i < 10000; i += 2 { - if _, err := f.setBit(1, uint64(i)); err != nil { + if _, err := f.setBit(tx, 1, uint64(i)); err != nil { b.Fatal(err) } } for i := 0; i < 10000; i += 3 { - if _, err := f.setBit(2, uint64(i)); err != nil { + if _, err := f.setBit(tx, 2, uint64(i)); err != nil { b.Fatal(err) } } @@ -1517,7 +1659,7 @@ func BenchmarkFragment_IntersectionCount(b *testing.B) { // Start benchmark b.ResetTimer() for i := 0; i < b.N; i++ { - if n := f.row(1).intersectionCount(f.row(2)); n == 0 { + if n := f.mustRow(tx, 1).intersectionCount(f.mustRow(tx, 2)); n == 0 { b.Fatalf("unexpected count: %d", n) } } @@ -1527,15 +1669,18 @@ func TestFragment_Tanimoto(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, CacheTypeRanked) defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + src := NewRow(1, 2, 3) // Set bits on the rows 100, 101, & 102. - f.mustSetBits(100, 1, 3, 2, 200) - f.mustSetBits(101, 1, 3) - f.mustSetBits(102, 1, 2, 10, 12) + f.mustSetBits(tx, 100, 1, 3, 2, 200) + f.mustSetBits(tx, 101, 1, 3) + f.mustSetBits(tx, 102, 1, 2, 10, 12) f.RecalculateCache() - if pairs, err := f.top(topOptions{TanimotoThreshold: 50, Src: src}); err != nil { + if pairs, err := f.top(tx, topOptions{TanimotoThreshold: 50, Src: src}); err != nil { t.Fatal(err) } else if len(pairs) != 2 { t.Fatalf("unexpected count: %d", len(pairs)) @@ -1550,15 +1695,18 @@ func TestFragment_Zero_Tanimoto(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, CacheTypeRanked) defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + src := NewRow(1, 2, 3) // Set bits on the rows 100, 101, & 102. - f.mustSetBits(100, 1, 3, 2, 200) - f.mustSetBits(101, 1, 3) - f.mustSetBits(102, 1, 2, 10, 12) + f.mustSetBits(tx, 100, 1, 3, 2, 200) + f.mustSetBits(tx, 101, 1, 3) + f.mustSetBits(tx, 102, 1, 2, 10, 12) f.RecalculateCache() - if pairs, err := f.top(topOptions{TanimotoThreshold: 0, Src: src}); err != nil { + if pairs, err := f.top(tx, topOptions{TanimotoThreshold: 0, Src: src}); err != nil { t.Fatal(err) } else if len(pairs) != 3 { t.Fatalf("unexpected count: %d", len(pairs)) @@ -1575,9 +1723,12 @@ func TestFragment_Snapshot_Run(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set bits on the fragment. for i := uint64(1); i < 3; i++ { - if _, err := f.setBit(1000, i); err != nil { + if _, err := f.setBit(tx, 1000, i); err != nil { t.Fatal(err) } } @@ -1585,14 +1736,14 @@ func TestFragment_Snapshot_Run(t *testing.T) { // Snapshot bitmap and verify data. if err := f.Snapshot(); err != nil { t.Fatal(err) - } else if n := f.row(1000).Count(); n != 2 { + } else if n := f.mustRow(tx, 1000).Count(); n != 2 { t.Fatalf("unexpected count: %d", n) } // Close and reopen the fragment & verify the data. if err := f.Reopen(); err != nil { t.Fatal(err) - } else if n := f.row(1000).Count(); n != 2 { + } else if n := f.mustRow(tx, 1000).Count(); n != 2 { t.Fatalf("unexpected count (reopen): %d", n) } } @@ -1602,28 +1753,31 @@ func TestFragment_SetMutex(t *testing.T) { f := mustOpenMutexFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + var cols []uint64 // Set a value on column 100. - if _, err := f.setBit(1, 100); err != nil { + if _, err := f.setBit(tx, 1, 100); err != nil { t.Fatal(err) } // Verify the value was set. - cols = f.row(1).Columns() + cols = f.mustRow(tx, 1).Columns() if !reflect.DeepEqual(cols, []uint64{100}) { t.Fatalf("mutex unexpected columns: %v", cols) } // Set a different value on column 100. - if _, err := f.setBit(2, 100); err != nil { + if _, err := f.setBit(tx, 2, 100); err != nil { t.Fatal(err) } // Verify that value (row 1) was replaced (by row 2). - cols = f.row(1).Columns() + cols = f.mustRow(tx, 1).Columns() if !reflect.DeepEqual(cols, []uint64{}) { t.Fatalf("mutex unexpected columns: %v", cols) } - cols = f.row(2).Columns() + cols = f.mustRow(tx, 2).Columns() if !reflect.DeepEqual(cols, []uint64{100}) { t.Fatalf("mutex unexpected columns: %v", cols) } @@ -1716,29 +1870,32 @@ func TestFragment_ImportSet(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set import. - err := f.bulkImport(test.setRowIDs, test.setColIDs, &ImportOptions{}) + err := f.bulkImport(tx, test.setRowIDs, test.setColIDs, &ImportOptions{}) if err != nil { t.Fatalf("bulk importing ids: %v", err) } // Check for expected results. for k, v := range test.setExp { - cols := f.row(k).Columns() + cols := f.mustRow(tx, k).Columns() if !reflect.DeepEqual(cols, v) { t.Fatalf("expected: %v, but got: %v", v, cols) } } // Clear import. - err = f.bulkImport(test.clearRowIDs, test.clearColIDs, &ImportOptions{Clear: true}) + err = f.bulkImport(tx, test.clearRowIDs, test.clearColIDs, &ImportOptions{Clear: true}) if err != nil { t.Fatalf("bulk clearing ids: %v", err) } // Check for expected results. for k, v := range test.clearExp { - cols := f.row(k).Columns() + cols := f.mustRow(tx, k).Columns() if !reflect.DeepEqual(cols, v) { t.Fatalf("expected: %v, but got: %v", v, cols) } @@ -1752,9 +1909,12 @@ func TestFragment_ConcurrentImport(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + eg := errgroup.Group{} - eg.Go(func() error { return f.bulkImportStandard([]uint64{1, 2}, []uint64{1, 2}, &ImportOptions{}) }) - eg.Go(func() error { return f.bulkImportStandard([]uint64{3, 4}, []uint64{3, 4}, &ImportOptions{}) }) + eg.Go(func() error { return f.bulkImportStandard(tx, []uint64{1, 2}, []uint64{1, 2}, &ImportOptions{}) }) + eg.Go(func() error { return f.bulkImportStandard(tx, []uint64{3, 4}, []uint64{3, 4}, &ImportOptions{}) }) err := eg.Wait() if err != nil { t.Fatalf("importing data to fragment: %v", err) @@ -1849,29 +2009,32 @@ func TestFragment_ImportMutex(t *testing.T) { f := mustOpenMutexFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set import. - err := f.bulkImport(test.setRowIDs, test.setColIDs, &ImportOptions{}) + err := f.bulkImport(tx, test.setRowIDs, test.setColIDs, &ImportOptions{}) if err != nil { t.Fatalf("bulk importing ids: %v", err) } // Check for expected results. for k, v := range test.setExp { - cols := f.row(k).Columns() + cols := f.mustRow(tx, k).Columns() if !reflect.DeepEqual(cols, v) { t.Fatalf("row: %d, expected: %v, but got: %v", k, v, cols) } } // Clear import. - err = f.bulkImport(test.clearRowIDs, test.clearColIDs, &ImportOptions{Clear: true}) + err = f.bulkImport(tx, test.clearRowIDs, test.clearColIDs, &ImportOptions{Clear: true}) if err != nil { t.Fatalf("bulk clearing ids: %v", err) } // Check for expected results. for k, v := range test.clearExp { - cols := f.row(k).Columns() + cols := f.mustRow(tx, k).Columns() if !reflect.DeepEqual(cols, v) { t.Fatalf("row: %d expected: %v, but got: %v", k, v, cols) } @@ -1968,29 +2131,32 @@ func TestFragment_ImportBool(t *testing.T) { f := mustOpenBoolFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Set import. - err := f.bulkImport(test.setRowIDs, test.setColIDs, &ImportOptions{}) + err := f.bulkImport(tx, test.setRowIDs, test.setColIDs, &ImportOptions{}) if err != nil { t.Fatalf("bulk importing ids: %v", err) } // Check for expected results. for k, v := range test.setExp { - cols := f.row(k).Columns() + cols := f.mustRow(tx, k).Columns() if !reflect.DeepEqual(cols, v) { t.Fatalf("expected: %v, but got: %v", v, cols) } } // Clear import. - err = f.bulkImport(test.clearRowIDs, test.clearColIDs, &ImportOptions{Clear: true}) + err = f.bulkImport(tx, test.clearRowIDs, test.clearColIDs, &ImportOptions{Clear: true}) if err != nil { t.Fatalf("bulk importing ids: %v", err) } // Check for expected results. for k, v := range test.clearExp { - cols := f.row(k).Columns() + cols := f.mustRow(tx, k).Columns() if !reflect.DeepEqual(cols, v) { t.Fatalf("expected: %v, but got: %v", v, cols) } @@ -2006,7 +2172,7 @@ func BenchmarkFragment_Snapshot(b *testing.B) { b.ReportAllocs() // Open the fragment specified by the path. - f := newFragment(*FragmentPath, "i", "f", viewStandard, 0, 0) + f := newFragment(NewHolder(DefaultPartitionN), *FragmentPath, "i", "f", viewStandard, 0, 0) if err := f.Open(); err != nil { b.Fatal(err) } @@ -2027,6 +2193,10 @@ func BenchmarkFragment_Snapshot(b *testing.B) { func BenchmarkFragment_FullSnapshot(b *testing.B) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(b) + + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // Generate some intersecting data. maxX := ShardWidth / 2 sz := maxX @@ -2044,7 +2214,7 @@ func BenchmarkFragment_FullSnapshot(b *testing.B) { val += 2 i++ } - if err := f.bulkImport(rows, cols, options); err != nil { + if err := f.bulkImport(tx, rows, cols, options); err != nil { b.Fatalf("Error Building Sample: %s", err) } if row > max { @@ -2089,8 +2259,10 @@ func BenchmarkFragment_Import(b *testing.B) { copy(rowsUse, rows) copy(colsUse, cols) f := mustOpenFragment("i", "f", viewStandard, 0, "") + // Obtain transaction. + tx := &RoaringTx{fragment: f} b.StartTimer() - if err := f.bulkImport(rowsUse, colsUse, options); err != nil { + if err := f.bulkImport(tx, rowsUse, colsUse, options); err != nil { b.Errorf("Error Building Sample: %s", err) } b.StopTimer() @@ -2121,7 +2293,7 @@ func BenchmarkImportRoaring(b *testing.B) { // care whether this succeeds, // but if it's happening we want // it to be done. - _ = f.snapshotQueue.Await(f) + _ = defaultSnapshotQueue.Await(f) f.Clean(b) b.Fatalf("import error: %v", err) } @@ -2162,7 +2334,7 @@ func BenchmarkImportRoaringConcurrent(b *testing.B) { err := frags[j].importRoaringT(data[j], false) // error unimportant if it happened, but we want // any snapshots to have finished. - _ = frags[j].snapshotQueue.Await(frags[j]) + _ = defaultSnapshotQueue.Await(frags[j]) return err }) } @@ -2196,6 +2368,7 @@ func BenchmarkImportRoaringUpdateConcurrent(b *testing.B) { for i := 0; i < b.N; i++ { for j := 0; j < concurrency; j++ { frags[j] = mustOpenFragment("i", "f", viewStandard, uint64(j), cacheType) + // the cost of actually doing the op log for the large initial data set // is excessive. force storage into snapshotted state, then use import // to generate an op log and/or snapshot. @@ -2203,7 +2376,7 @@ func BenchmarkImportRoaringUpdateConcurrent(b *testing.B) { if err != nil { b.Fatalf("importing roaring: %v", err) } - err = frags[j].snapshotQueue.Immediate(frags[j]) + err = defaultSnapshotQueue.Immediate(frags[j]) if err != nil { b.Fatalf("snapshot after import: %v", err) } @@ -2214,7 +2387,7 @@ func BenchmarkImportRoaringUpdateConcurrent(b *testing.B) { j := j eg.Go(func() error { err := frags[j].importRoaringT(updata, false) - err2 := frags[j].snapshotQueue.Await(frags[j]) + err2 := defaultSnapshotQueue.Await(frags[j]) if err == nil { err = err2 } @@ -2248,8 +2421,12 @@ func BenchmarkImportStandard(b *testing.B) { copy(rowIDs, rowIDsOrig) copy(columnIDs, columnIDsOrig) f := mustOpenFragment("i", fmt.Sprintf("r%dc%s", numRows, cacheType), viewStandard, 0, cacheType) + + // Obtain transaction. + tx := &RoaringTx{fragment: f} + b.StartTimer() - err := f.bulkImport(rowIDs, columnIDs, &ImportOptions{}) + err := f.bulkImport(tx, rowIDs, columnIDs, &ImportOptions{}) if err != nil { b.Errorf("import error: %v", err) } @@ -2275,6 +2452,7 @@ func BenchmarkImportRoaringUpdate(b *testing.B) { b.StopTimer() for i := 0; i < b.N; i++ { f := mustOpenFragment("i", fmt.Sprintf("r%dc%dcache_%s", numRows, numCols, cacheType), viewStandard, 0, cacheType) + // the cost of actually doing the op log for the large initial data set // is excessive. force storage into snapshotted state, then use import // to generate an op log and/or snapshot. @@ -2282,7 +2460,7 @@ func BenchmarkImportRoaringUpdate(b *testing.B) { if err != nil { b.Errorf("import error: %v", err) } - err = f.snapshotQueue.Immediate(f) + err = defaultSnapshotQueue.Immediate(f) if err != nil { b.Errorf("snapshot after import error: %v", err) } @@ -2292,7 +2470,7 @@ func BenchmarkImportRoaringUpdate(b *testing.B) { f.Clean(b) b.Errorf("import error: %v", err) } - err = f.snapshotQueue.Await(f) + err = defaultSnapshotQueue.Await(f) if err != nil { b.Errorf("snapshot after import error: %v", err) } @@ -2391,15 +2569,19 @@ func BenchmarkImportIntoLargeFragment(b *testing.B) { } origF.Close() fi.Close() - nf := newFragment(fi.Name(), "i", "f", viewStandard, 0, 0) + nf := newFragment(NewHolder(DefaultPartitionN), fi.Name(), "i", "f", viewStandard, 0, 0) err = nf.Open() if err != nil { b.Fatalf("opening fragment: %v", err) } + + // Obtain transaction. + tx := &RoaringTx{fragment: nf} + copy(rows, rowsOrig) copy(cols, colsOrig) b.StartTimer() - err = nf.bulkImport(rows, cols, opts) + err = nf.bulkImport(tx, rows, cols, opts) b.StopTimer() if err != nil { b.Fatalf("bulkImport: %v", err) @@ -2428,7 +2610,7 @@ func BenchmarkImportRoaringIntoLargeFragment(b *testing.B) { } origF.Close() fi.Close() - nf := newFragment(fi.Name(), "i", "f", viewStandard, 0, 0) + nf := newFragment(NewHolder(DefaultPartitionN), fi.Name(), "i", "f", viewStandard, 0, 0) err = nf.Open() if err != nil { b.Fatalf("opening fragment: %v", err) @@ -2446,17 +2628,23 @@ func BenchmarkImportRoaringIntoLargeFragment(b *testing.B) { func TestGetZipfRowsSliceRoaring(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, DefaultCacheType) + + // Obtain transaction. + tx := &RoaringTx{fragment: f} + data := getZipfRowsSliceRoaring(10, 1, 0, ShardWidth) err := f.importRoaringT(data, false) if err != nil { t.Fatalf("importing roaring: %v", err) } - rows := f.rows(context.Background(), 0) - if !reflect.DeepEqual(rows, []uint64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) { + rows, err := f.rows(context.Background(), tx, 0) + if err != nil { + t.Fatal(err) + } else if !reflect.DeepEqual(rows, []uint64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) { t.Fatalf("unexpected rows: %v", rows) } for i := uint64(1); i < 10; i++ { - if f.row(i).Count() >= f.row(i-1).Count() { + if f.mustRow(tx, i).Count() >= f.mustRow(tx, i-1).Count() { t.Fatalf("suspect distribution from getZipfRowsSliceRoaring") } } @@ -2600,6 +2788,7 @@ func (f *fragment) sanityCheck(t testing.TB) { if err != nil { t.Fatalf("sanityCheck couldn't unmarshal fragment %s: %v", f.path, err) } + // Refactor fragment.storage if equal, reason := newBM.BitwiseEqual(f.storage); !equal { t.Fatalf("fragment %s: unmarshalled bitmap different: %v", f.path, reason) } @@ -2607,17 +2796,23 @@ func (f *fragment) sanityCheck(t testing.TB) { func (f *fragment) Clean(t testing.TB) { f.mu.Lock() - err := f.snapshotQueue.Await(f) - f.mu.Unlock() - if err != nil { - t.Fatalf("snapshot failed before sanity check: %v", err) - } - f.sanityCheck(t) - if f.storage != nil && f.storage.Source != nil { - if f.storage.Source.Dead() { - t.Fatalf("cleaning up fragment %s, source %s, source already dead", f.path, f.storage.Source.ID()) + // we need to ensure that we unlock the mutex before terminating + // the clean operation, but we need it held during the sanity + // check or else, in some cases, the background snapshot queue + // can decide to pick it up. + func() { + defer f.mu.Unlock() + err := defaultSnapshotQueue.Await(f) + if err != nil { + t.Fatalf("snapshot failed before sanity check: %v", err) } - } + f.sanityCheck(t) + if f.storage != nil && f.storage.Source != nil { + if f.storage.Source.Dead() { + t.Fatalf("cleaning up fragment %s, source %s, source already dead", f.path, f.storage.Source.ID()) + } + } + }() errc := f.Close() // prevent double-closes of generation during testing. f.gen = nil @@ -2626,10 +2821,6 @@ func (f *fragment) Clean(t testing.TB) { if errc != nil || errf != nil { t.Fatal("cleaning up fragment: ", errc, errf, errp) } - if f.snapshotQueue != nil { - f.snapshotQueue.Stop() - f.snapshotQueue = nil - } // not all fragments have cache files if errp != nil && !os.IsNotExist(errp) { t.Fatalf("cleaning up fragment cache: %v", errp) @@ -2649,10 +2840,6 @@ func (f *fragment) CleanKeep(t testing.TB) { if errc != nil { t.Fatal("closing fragment: ", errc, errp) } - if f.snapshotQueue != nil { - f.snapshotQueue.Stop() - f.snapshotQueue = nil - } // not all fragments have cache files if errp != nil && !os.IsNotExist(errp) { t.Fatalf("cleaning up fragment cache: %v", errp) @@ -2668,6 +2855,12 @@ func mustOpenBSIFragment(index, field, view string, shard uint64) *fragment { return mustOpenFragmentFlags(index, field, view, shard, "", 1) } +var testHolder = NewHolder(DefaultPartitionN) + +func init() { + testHolder.SnapshotQueue = newSnapshotQueue(1, 1, nil) +} + // mustOpenFragment returns a new instance of Fragment with a temporary path. func mustOpenFragmentFlags(index, field, view string, shard uint64, cacheType string, flags byte) *fragment { file, err := ioutil.TempFile(*TempDir, "pilosa-fragment-") @@ -2680,12 +2873,12 @@ func mustOpenFragmentFlags(index, field, view string, shard uint64, cacheType st cacheType = DefaultCacheType } - f := newFragment(file.Name(), index, field, view, shard, flags) + f := newFragment(testHolder, file.Name(), index, field, view, shard, flags) + f.CacheType = cacheType f.RowAttrStore = &memAttrStore{ store: make(map[uint64]map[string]interface{}), } - f.snapshotQueue = newSnapshotQueue(1, 1, nil) if err := f.Open(); err != nil { panic(err) @@ -2720,9 +2913,9 @@ func (f *fragment) Reopen() error { // mustSetBits sets columns on a row. Panic on error. // This function does not accept a timestamp or quantum. -func (f *fragment) mustSetBits(rowID uint64, columnIDs ...uint64) { +func (f *fragment) mustSetBits(tx Tx, rowID uint64, columnIDs ...uint64) { for _, columnID := range columnIDs { - if _, err := f.setBit(rowID, columnID); err != nil { + if _, err := f.setBit(tx, rowID, columnID); err != nil { panic(err) } } @@ -2741,11 +2934,12 @@ func TestFragment_RowsIteration(t *testing.T) { t.Run("firstContainer", func(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + tx := &RoaringTx{fragment: f} expectedAll := make([]uint64, 0) expectedOdd := make([]uint64, 0) for i := uint64(100); i < uint64(200); i++ { - if _, err := f.setBit(i, i%2); err != nil { + if _, err := f.setBit(tx, i, i%2); err != nil { t.Fatal(err) } expectedAll = append(expectedAll, i) @@ -2754,13 +2948,17 @@ func TestFragment_RowsIteration(t *testing.T) { } } - ids := f.rows(context.Background(), 0) - if !reflect.DeepEqual(expectedAll, ids) { + ids, err := f.rows(context.Background(), tx, 0) + if err != nil { + t.Fatal(err) + } else if !reflect.DeepEqual(expectedAll, ids) { t.Fatalf("Do not match %v %v", expectedAll, ids) } - ids = f.rows(context.Background(), 0, filterColumn(1)) - if !reflect.DeepEqual(expectedOdd, ids) { + ids, err = f.rows(context.Background(), tx, 0, filterColumn(1)) + if err != nil { + t.Fatal(err) + } else if !reflect.DeepEqual(expectedOdd, ids) { t.Fatalf("Do not match %v %v", expectedOdd, ids) } }) @@ -2768,23 +2966,28 @@ func TestFragment_RowsIteration(t *testing.T) { t.Run("secondRow", func(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + tx := &RoaringTx{fragment: f} expected := []uint64{1, 2} - if _, err := f.setBit(1, 66000); err != nil { + if _, err := f.setBit(tx, 1, 66000); err != nil { t.Fatal(err) - } else if _, err := f.setBit(2, 66000); err != nil { + } else if _, err := f.setBit(tx, 2, 66000); err != nil { t.Fatal(err) - } else if _, err := f.setBit(2, 166000); err != nil { + } else if _, err := f.setBit(tx, 2, 166000); err != nil { t.Fatal(err) } - ids := f.rows(context.Background(), 0) - if !reflect.DeepEqual(expected, ids) { + ids, err := f.rows(context.Background(), tx, 0) + if err != nil { + t.Fatal(err) + } else if !reflect.DeepEqual(expected, ids) { t.Fatalf("Do not match %v %v", expected, ids) } - ids = f.rows(context.Background(), 0, filterColumn(66000)) - if !reflect.DeepEqual(expected, ids) { + ids, err = f.rows(context.Background(), tx, 0, filterColumn(66000)) + if err != nil { + t.Fatal(err) + } else if !reflect.DeepEqual(expected, ids) { t.Fatalf("Do not match %v %v", expected, ids) } }) @@ -2792,21 +2995,26 @@ func TestFragment_RowsIteration(t *testing.T) { t.Run("combinations", func(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + tx := &RoaringTx{fragment: f} expectedRows := make([]uint64, 0) for r := uint64(1); r < uint64(10000); r += 250 { expectedRows = append(expectedRows, r) for c := uint64(1); c < uint64(ShardWidth-1); c += (ShardWidth >> 5) { - if _, err := f.setBit(r, c); err != nil { + if _, err := f.setBit(tx, r, c); err != nil { t.Fatal(err) } - ids := f.rows(context.Background(), 0) - if !reflect.DeepEqual(expectedRows, ids) { + ids, err := f.rows(context.Background(), tx, 0) + if err != nil { + t.Fatal(err) + } else if !reflect.DeepEqual(expectedRows, ids) { t.Fatalf("Do not match %v %v", expectedRows, ids) } - ids = f.rows(context.Background(), 0, filterColumn(c)) - if !reflect.DeepEqual(expectedRows, ids) { + ids, err = f.rows(context.Background(), tx, 0, filterColumn(c)) + if err != nil { + t.Fatal(err) + } else if !reflect.DeepEqual(expectedRows, ids) { t.Fatalf("Do not match %v %v", expectedRows, ids) } } @@ -2839,6 +3047,8 @@ func TestFragment_RoaringImport(t *testing.T) { t.Run(fmt.Sprintf("importroaring%d", i), func(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") defer f.Clean(t) + tx := &RoaringTx{fragment: f} + for num, input := range test { buf := &bytes.Buffer{} bm := roaring.NewBitmap(input...) @@ -2852,7 +3062,7 @@ func TestFragment_RoaringImport(t *testing.T) { } exp := calcExpected(test[:num+1]...) for row, expCols := range exp { - cols := f.row(uint64(row)).Columns() + cols := f.mustRow(tx, uint64(row)).Columns() t.Logf("\nrow: %d\n exp:%v\n got:%v", row, expCols, cols) if !reflect.DeepEqual(cols, expCols) { t.Fatalf("input%d, row %d\n exp:%v\n got:%v", num, row, expCols, cols) @@ -2885,14 +3095,15 @@ func TestFragment_RoaringImportTopN(t *testing.T) { t.Run(fmt.Sprintf("importroaring%d", i), func(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, CacheTypeRanked) defer f.Clean(t) + tx := &RoaringTx{fragment: f} options := &ImportOptions{} - err := f.bulkImport(test.rowIDs, test.colIDs, options) + err := f.bulkImport(tx, test.rowIDs, test.colIDs, options) if err != nil { t.Fatalf("bulk importing ids: %v", err) } expPairs := calcTop(test.rowIDs, test.colIDs) - pairs, err := f.top(topOptions{}) + pairs, err := f.top(tx, topOptions{}) if err != nil { t.Fatalf("executing top after bulk import: %v", err) } @@ -2900,14 +3111,14 @@ func TestFragment_RoaringImportTopN(t *testing.T) { t.Fatalf("post bulk import:\n exp: %v\n got: %v\n", expPairs, pairs) } - err = f.bulkImport(test.rowIDs2, test.colIDs2, options) + err = f.bulkImport(tx, test.rowIDs2, test.colIDs2, options) if err != nil { t.Fatalf("bulk importing ids: %v", err) } test.rowIDs = append(test.rowIDs, test.rowIDs2...) test.colIDs = append(test.colIDs, test.colIDs2...) expPairs = calcTop(test.rowIDs, test.colIDs) - pairs, err = f.top(topOptions{}) + pairs, err = f.top(tx, topOptions{}) if err != nil { t.Fatalf("executing top after bulk import: %v", err) } @@ -2927,7 +3138,7 @@ func TestFragment_RoaringImportTopN(t *testing.T) { } rows, cols := toRowsCols(test.roaring) expPairs = calcTop(append(test.rowIDs, rows...), append(test.colIDs, cols...)) - pairs, err = f.top(topOptions{}) + pairs, err = f.top(tx, topOptions{}) if err != nil { t.Fatalf("executing top after roaring import: %v", err) } @@ -3022,14 +3233,22 @@ func TestFragmentRowIterator(t *testing.T) { t.Run("basic", func(t *testing.T) { f := mustOpenFragment("i", "f", "v", 0, CacheTypeRanked) defer f.Clean(t) - f.mustSetBits(0, 0) - f.mustSetBits(1, 0) - f.mustSetBits(2, 0) - f.mustSetBits(3, 0) + tx := &RoaringTx{fragment: f} - iter := f.rowIterator(false) + f.mustSetBits(tx, 0, 0) + f.mustSetBits(tx, 1, 0) + f.mustSetBits(tx, 2, 0) + f.mustSetBits(tx, 3, 0) + + iter, err := f.rowIterator(tx, false) + if err != nil { + t.Fatal(err) + } for i := uint64(0); i < 4; i++ { - row, id, _, wrapped := iter.Next() + row, id, _, wrapped, err := iter.Next() + if err != nil { + t.Fatal(err) + } if id != i { t.Fatalf("expected row %d but got %d", i, id) } @@ -3040,7 +3259,10 @@ func TestFragmentRowIterator(t *testing.T) { t.Fatalf("got wrong columns back on iteration %d - should just be 0 but %v", i, row.Columns()) } } - row, id, _, wrapped := iter.Next() + row, id, _, wrapped, err := iter.Next() + if err != nil { + t.Fatal(err) + } if row != nil { t.Fatalf("row should be nil after iterator is exhausted, got %v", row.Columns()) } @@ -3055,14 +3277,22 @@ func TestFragmentRowIterator(t *testing.T) { t.Run("skipped rows", func(t *testing.T) { f := mustOpenFragment("i", "f", "v", 0, CacheTypeRanked) defer f.Clean(t) - f.mustSetBits(1, 0) - f.mustSetBits(3, 0) - f.mustSetBits(5, 0) - f.mustSetBits(7, 0) + tx := &RoaringTx{fragment: f} - iter := f.rowIterator(false) + f.mustSetBits(tx, 1, 0) + f.mustSetBits(tx, 3, 0) + f.mustSetBits(tx, 5, 0) + f.mustSetBits(tx, 7, 0) + + iter, err := f.rowIterator(tx, false) + if err != nil { + t.Fatal(err) + } for i := uint64(1); i < 8; i += 2 { - row, id, _, wrapped := iter.Next() + row, id, _, wrapped, err := iter.Next() + if err != nil { + t.Fatal(err) + } if id != i { t.Fatalf("expected row %d but got %d", i, id) } @@ -3073,7 +3303,10 @@ func TestFragmentRowIterator(t *testing.T) { t.Fatalf("got wrong columns back on iteration %d - should just be 0 but %v", i, row.Columns()) } } - row, id, _, wrapped := iter.Next() + row, id, _, wrapped, err := iter.Next() + if err != nil { + t.Fatal(err) + } if row != nil { t.Fatalf("row should be nil after iterator is exhausted, got %v", row.Columns()) } @@ -3088,14 +3321,22 @@ func TestFragmentRowIterator(t *testing.T) { t.Run("basic wrapped", func(t *testing.T) { f := mustOpenFragment("i", "f", "v", 0, CacheTypeRanked) defer f.Clean(t) - f.mustSetBits(0, 0) - f.mustSetBits(1, 0) - f.mustSetBits(2, 0) - f.mustSetBits(3, 0) + tx := &RoaringTx{fragment: f} - iter := f.rowIterator(true) + f.mustSetBits(tx, 0, 0) + f.mustSetBits(tx, 1, 0) + f.mustSetBits(tx, 2, 0) + f.mustSetBits(tx, 3, 0) + + iter, err := f.rowIterator(tx, true) + if err != nil { + t.Fatal(err) + } for i := uint64(0); i < 5; i++ { - row, id, _, wrapped := iter.Next() + row, id, _, wrapped, err := iter.Next() + if err != nil { + t.Fatal(err) + } if id != i%4 { t.Fatalf("expected row %d but got %d", i%4, id) } @@ -3113,14 +3354,22 @@ func TestFragmentRowIterator(t *testing.T) { t.Run("skipped rows wrapped", func(t *testing.T) { f := mustOpenFragment("i", "f", "v", 0, CacheTypeRanked) defer f.Clean(t) - f.mustSetBits(1, 0) - f.mustSetBits(3, 0) - f.mustSetBits(5, 0) - f.mustSetBits(7, 0) + tx := &RoaringTx{fragment: f} - iter := f.rowIterator(true) + f.mustSetBits(tx, 1, 0) + f.mustSetBits(tx, 3, 0) + f.mustSetBits(tx, 5, 0) + f.mustSetBits(tx, 7, 0) + + iter, err := f.rowIterator(tx, true) + if err != nil { + t.Fatal(err) + } for i := uint64(1); i < 10; i += 2 { - row, id, _, wrapped := iter.Next() + row, id, _, wrapped, err := iter.Next() + if err != nil { + t.Fatal(err) + } if id != i%8 { t.Errorf("expected row %d but got %d", i%8, id) } @@ -3142,6 +3391,7 @@ func TestUnionInPlaceMapped(t *testing.T) { // the lock *not* held, because it is sometimes so it has to grab the // lock... defer f.Clean(t) + f.mu.Lock() defer f.mu.Unlock() r0 := rand.New(rand.NewSource(2)) @@ -3173,13 +3423,14 @@ func TestUnionInPlaceMapped(t *testing.T) { f.storage.UnionInPlace(setBM1) countUnion := f.storage.Count() + // UnionInPlace produces no ops log, we have to make it snapshot, to // ensure that the on-disk representation is correct. Note, UIP is // not used for things that are modifying real fragments, usually; // it's used only in computation of things that usually don't go to // disk, which is why we handle this specially in testing and not // generically. - err = f.snapshotQueue.Immediate(f) + err = defaultSnapshotQueue.Immediate(f) if err != nil { t.Fatalf("snapshot after union-in-place: %v", err) } @@ -3295,12 +3546,15 @@ func TestIntLTRegression(t *testing.T) { f := mustOpenFragment("i", "f", "v", 0, CacheTypeNone) defer f.Clean(t) - _, err := f.setValue(1, 6, 33) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + + _, err := f.setValue(tx, 1, 6, 33) if err != nil { t.Fatalf("setting value: %v", err) } - row, err := f.rangeOp(pql.LT, 6, 33) + row, err := f.rangeOp(tx, pql.LT, 6, 33) if err != nil { t.Fatalf("doing range of: %v", err) } @@ -3332,7 +3586,6 @@ func TestImportClearRestart(t *testing.T) { cols: []uint64{1, 1, 1, 1, 1, 1}, }, } - for i, test := range tests { for _, maxOpN := range []int{0, 10000} { t.Run(fmt.Sprintf("%dMaxOpN%d", i, maxOpN), func(t *testing.T) { @@ -3360,7 +3613,11 @@ func TestImportClearRestart(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") f.MaxOpN = maxOpN - err := f.bulkImport(testrows, testcols, &ImportOptions{}) + + // Obtain transaction. + tx := &RoaringTx{fragment: f} + + err := f.bulkImport(tx, testrows, testcols, &ImportOptions{}) if err != nil { t.Fatalf("initial small import: %v", err) } @@ -3385,7 +3642,7 @@ func TestImportClearRestart(t *testing.T) { check(t, f, exp) - f2 := newFragment(f.path, "i", "f", viewStandard, 0, 0) + f2 := newFragment(NewHolder(DefaultPartitionN), f.path, "i", "f", viewStandard, 0, 0) f2.MaxOpN = maxOpN f2.CacheType = f.CacheType @@ -3407,7 +3664,7 @@ func TestImportClearRestart(t *testing.T) { copy(testrows, test.rows) copy(testcols, test.cols) - err = f2.bulkImport(testrows, testcols, &ImportOptions{Clear: true}) + err = f2.bulkImport(tx, testrows, testcols, &ImportOptions{Clear: true}) if err != nil { t.Fatalf("clearing imported data: %v", err) } @@ -3419,7 +3676,7 @@ func TestImportClearRestart(t *testing.T) { check(t, f2, exp) - f3 := newFragment(f2.path, "i", "f", viewStandard, 0, 0) + f3 := newFragment(NewHolder(DefaultPartitionN), f2.path, "i", "f", viewStandard, 0, 0) f3.MaxOpN = maxOpN f3.CacheType = f.CacheType @@ -3443,8 +3700,10 @@ func TestImportClearRestart(t *testing.T) { } func check(t *testing.T, f *fragment, exp map[uint64]map[uint64]struct{}) { + tx := &RoaringTx{fragment: f} + for rowID, colsExp := range exp { - colsAct := f.row(rowID).Columns() + colsAct := f.mustRow(tx, rowID).Columns() if len(colsAct) != len(colsExp) { t.Errorf("row %d len mismatch got: %d exp:%d", rowID, len(colsAct), len(colsExp)) } @@ -3476,8 +3735,9 @@ func TestImportValueConcurrent(t *testing.T) { for i := 0; i < 4; i++ { i := i eg.Go(func() error { + tx := &RoaringTx{fragment: f} for j := uint64(0); j < 10; j++ { - err := f.importValue([]uint64{j}, []int64{int64(rand.Int63n(1000))}, 10, i%2 == 0) + err := f.importValue(tx, []uint64{j}, []int64{int64(rand.Int63n(1000))}, 10, i%2 == 0) if err != nil { return err } @@ -3514,14 +3774,18 @@ func TestImportMultipleValues(t *testing.T) { f := mustOpenBSIFragment("i", "f", viewBSIGroupPrefix+"foo", 0) f.MaxOpN = maxOpN defer f.Clean(t) - err := f.importValue(test.cols, test.vals, test.depth, false) + + // Obtain transaction. + tx := &RoaringTx{fragment: f} + + err := f.importValue(tx, test.cols, test.vals, test.depth, false) if err != nil { t.Fatalf("importing values: %v", err) } for i := range test.checkCols { cc, cv := test.checkCols[i], test.checkVals[i] - n, exists, err := f.value(cc, test.depth) + n, exists, err := f.value(tx, cc, test.depth) if err != nil { t.Fatalf("getting value: %v", err) } @@ -3572,23 +3836,26 @@ func TestImportValueRowCache(t *testing.T) { f.MaxOpN = maxOpN defer f.Clean(t) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // First import (tc1) - if err := f.importValue(test.tc1.cols, test.tc1.vals, test.tc1.depth, false); err != nil { + if err := f.importValue(tx, test.tc1.cols, test.tc1.vals, test.tc1.depth, false); err != nil { t.Fatalf("importing values: %v", err) } - if r, err := f.rangeOp(pql.GT, test.tc1.depth, 0); err != nil { + if r, err := f.rangeOp(tx, pql.GT, test.tc1.depth, 0); err != nil { t.Error("getting range of values") } else if !reflect.DeepEqual(r.Columns(), test.tc1.checkCols) { t.Errorf("wrong column values. expected: %v, but got: %v", test.tc1.checkCols, r.Columns()) } // Second import (tc2) - if err := f.importValue(test.tc2.cols, test.tc2.vals, test.tc2.depth, false); err != nil { + if err := f.importValue(tx, test.tc2.cols, test.tc2.vals, test.tc2.depth, false); err != nil { t.Fatalf("importing values: %v", err) } - if r, err := f.rangeOp(pql.GT, test.tc2.depth, 0); err != nil { + if r, err := f.rangeOp(tx, pql.GT, test.tc2.depth, 0); err != nil { t.Error("getting range of values") } else if !reflect.DeepEqual(r.Columns(), test.tc2.checkCols) { t.Errorf("wrong column values. expected: %v, but got: %v", test.tc2.checkCols, r.Columns()) @@ -3604,8 +3871,11 @@ func TestFragmentConcurrentReadWrite(t *testing.T) { eg := &errgroup.Group{} eg.Go(func() error { + // Obtain transaction. + tx := &RoaringTx{fragment: f} + for i := uint64(0); i < 1000; i++ { - _, err := f.setBit(i%4, i) + _, err := f.setBit(tx, i%4, i) if err != nil { return errors.Wrap(err, "setting bit") } @@ -3613,9 +3883,12 @@ func TestFragmentConcurrentReadWrite(t *testing.T) { return nil }) + // Obtain transaction. + tx := &RoaringTx{fragment: f} + acc := uint64(0) for i := uint64(0); i < 100; i++ { - r := f.row(i % 4) + r := f.mustRow(tx, i%4) acc += r.Count() } if err := eg.Wait(); err != nil { @@ -3642,6 +3915,10 @@ func TestRemapCache(t *testing.T) { t.Fatalf("unexpected panic: %v", r) } }() + + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // create a container _, err := f.storage.Add(65537) if err != nil { @@ -3653,7 +3930,7 @@ func TestRemapCache(t *testing.T) { t.Fatalf("storage snapshot: %v", err) } // freeze the row - _ = f.row(0) + _ = f.mustRow(tx, 0) // add a bit that isn't in that container, so that container doesn't // change _, err = f.storage.Add(2) @@ -3661,7 +3938,7 @@ func TestRemapCache(t *testing.T) { t.Fatalf("storage add: %v", err) } // make the original container be the most recent, thus cached, container - _, err = f.bit(0, 65537) + _, err = f.bit(tx, 0, 65537) if err != nil { t.Fatalf("storage bit check: %v", err) } @@ -3673,7 +3950,7 @@ func TestRemapCache(t *testing.T) { // get rid of the old mapping runtime.GC() // try to read that container again - _, err = f.bit(0, 65537) + _, err = f.bit(tx, 0, 65537) if err != nil { t.Fatalf("storage bit check: %v", err) } @@ -3682,6 +3959,9 @@ func TestRemapCache(t *testing.T) { func TestFragment_Bug_Q2DoubleDelete(t *testing.T) { f := mustOpenFragment("i", "f", viewStandard, 0, "") + // Obtain transaction. + tx := &RoaringTx{fragment: f} + // byShardWidth is a map of the same roaring (fragment) data generated // with different shard widths. // TODO: a better approach may be to generate this in the test based @@ -3702,17 +3982,17 @@ func TestFragment_Bug_Q2DoubleDelete(t *testing.T) { t.Fatalf("importing roaring: %v", err) } //check the bit - res := f.row(1).Columns() - if len(res) < 1 || f.row(1).Columns()[0] != 1 { + res := f.mustRow(tx, 1).Columns() + if len(res) < 1 || f.mustRow(tx, 1).Columns()[0] != 1 { t.Fatalf("expecting 1 got: %v", res) } //clear the bit - changed, _ := f.clearBit(1, 1) + changed, _ := f.clearBit(tx, 1, 1) if !changed { t.Fatalf("expected change got %v", changed) } //check missing - res = f.row(1).Columns() + res = f.mustRow(tx, 1).Columns() if len(res) != 0 { t.Fatalf("expected nothing got %v", res) } @@ -3722,16 +4002,16 @@ func TestFragment_Bug_Q2DoubleDelete(t *testing.T) { t.Fatalf("importing roaring: %v", err) } //check - res = f.row(1).Columns() - if len(res) < 1 || f.row(1).Columns()[0] != 1 { + res = f.mustRow(tx, 1).Columns() + if len(res) < 1 || f.mustRow(tx, 1).Columns()[0] != 1 { t.Fatalf("again expecting 1 got: %v", res) } - changed, _ = f.clearBit(1, 1) + changed, _ = f.clearBit(tx, 1, 1) if !changed { t.Fatalf("again expected change got %v", changed) } //check missing - res = f.row(1).Columns() + res = f.mustRow(tx, 1).Columns() if len(res) != 0 { t.Fatalf("expected nothing got %v", res) } diff --git a/generation.go b/generation.go index 7c1361b1d..e9c4e93c5 100644 --- a/generation.go +++ b/generation.go @@ -20,7 +20,7 @@ import ( "io/ioutil" "os" "runtime" - "runtime/debug" + // "runtime/debug" "sync" "syscall" "time" @@ -169,29 +169,29 @@ func (m *mmapGeneration) Transaction(fileP *io.Writer, fn func() error) (transac } // We are done locking the generation itself for now. m.mu.Unlock() - wouldPanic := debug.SetPanicOnFault(true) - defer func() { - debug.SetPanicOnFault(wouldPanic) - if r := recover(); r != nil { - if err, ok := r.(error); ok { - // special case: if we caught a page fault, we diagnose that directly. sadly, - // we can't see the actual values that were used to generate this, probably. - if err.Error() == "runtime error: invalid memory address or nil pointer dereference" { - if transactionErr == nil { - transactionErr = errors.New("invalid memory access during transaction") - } else { - transactionErr = fmt.Errorf("invalid memory access during transaction, previous error %v", transactionErr) - } - return - } - } - if transactionErr == nil { - transactionErr = fmt.Errorf("panic during transaction: %v", r) - } else { - transactionErr = fmt.Errorf("panic during erroring transaction: panic %v, previous error %v", r, transactionErr) - } - } - }() + // wouldPanic := debug.SetPanicOnFault(true) + // defer func() { + // debug.SetPanicOnFault(wouldPanic) + // if r := recover(); r != nil { + // if err, ok := r.(error); ok { + // // special case: if we caught a page fault, we diagnose that directly. sadly, + // // we can't see the actual values that were used to generate this, probably. + // if err.Error() == "runtime error: invalid memory address or nil pointer dereference" { + // if transactionErr == nil { + // transactionErr = errors.New("invalid memory access during transaction") + // } else { + // transactionErr = fmt.Errorf("invalid memory access during transaction, previous error %v", transactionErr) + // } + // return + // } + // } + // if transactionErr == nil { + // transactionErr = fmt.Errorf("panic during transaction: %v", r) + // } else { + // transactionErr = fmt.Errorf("panic during erroring transaction: panic %v, previous error %v", r, transactionErr) + // } + // } + // }() return fn() } @@ -263,7 +263,7 @@ func (m *mmapGeneration) openFile() (shouldClose bool, err error) { } // do we actually want this in every openFile? I don't know. if err := syscall.Flock(int(m.file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { - m.file.Close() + _ = syswrap.CloseFile(m.file) m.file = nil return false, fmt.Errorf("flock: %s", err) } @@ -333,6 +333,7 @@ func newGeneration(existing generation, path string, readData bool, setup func([ m := mmapGeneration{path: path, logger: logger} if existing != nil { m.generation = existing.Generation() + 1 + m.retries = existing.(*mmapGeneration).retries // we might keep a previous generation around just for its generation count. if !existing.Dead() { defer existing.Done() diff --git a/generation_test.go b/generation_test.go index 75444fcf7..7df71fc98 100644 --- a/generation_test.go +++ b/generation_test.go @@ -39,14 +39,14 @@ func TestGenerationPanic(t *testing.T) { } prevData = f.gen.(*mmapGeneration).data f.mu.Lock() - _ = f.snapshotQueue.Immediate(f) + _ = defaultSnapshotQueue.Immediate(f) f.mu.Unlock() runtime.GC() for i := 0; i < (f.MaxOpN / 2); i++ { _, _ = f.setBit(0, uint64(i*32)+23) } f.mu.Lock() - f.snapshotQueue.Await(f) + defaultSnapshotQueue.Await(f) f.mu.Unlock() runtime.GC() newData := f.gen.(*mmapGeneration).data diff --git a/go.mod b/go.mod index 9d9ecd366..485e2a5be 100644 --- a/go.mod +++ b/go.mod @@ -6,8 +6,10 @@ require ( github.com/CAFxX/gcnotifier v0.0.0-20190112062741-224a280d589d github.com/DataDog/datadog-go v0.0.0-20180822151419-281ae9f2d895 github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect + github.com/benbjohnson/immutable v0.2.0 github.com/boltdb/bolt v1.3.1 github.com/cespare/xxhash v1.1.0 + github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd // indirect github.com/davecgh/go-spew v1.1.1 github.com/go-ole/go-ole v1.2.4 // indirect diff --git a/go.sum b/go.sum index 9da5feace..997603c23 100644 --- a/go.sum +++ b/go.sum @@ -14,6 +14,8 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da h1:8GUt8eRujhVEGZFFEjBj46YV4rDjvGrNxb0KMWYkL2I= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= +github.com/benbjohnson/immutable v0.2.0 h1:t0rW3lNFwfQ85IDO1mhMbumxdVSti4nnVaal4r45Oio= +github.com/benbjohnson/immutable v0.2.0/go.mod h1:uc6OHo6PN2++n98KHLxW8ef4W42ylHiQSENghE1ezxI= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0 h1:HWo1m869IqiPhD389kmkxeTalrjNbbJTC8LXupb+sl0= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= @@ -22,6 +24,8 @@ github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx2 github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e h1:fY5BOSpyZCqRo5OhCuC+XN+r/bBCmeuuJtjz+bCNIf8= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd h1:qMd81Ts1T2OTKmB4acZcyKaMtRnY5Y44NuXGX2GFJ1w= @@ -112,6 +116,7 @@ github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181 github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pilosa/memberlist v0.1.4-0.20190415211605-f6512523c021 h1:ERLyN4p3KS5Fk2ADsDENm2cq0+Lx6sF1sG8uwRlySpU= github.com/pilosa/memberlist v0.1.4-0.20190415211605-f6512523c021/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= +github.com/pilosa/pilosa v1.4.0 h1:nqHNIK4nDslFnem3yDp9R+6TgLdlkY9WdJD88Z83T8U= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -242,3 +247,4 @@ modernc.org/mathutil v1.0.0 h1:93vKjrJopTPrtTNpZ8XIovER7iCIH1QU7wNbOQXC60I= modernc.org/mathutil v1.0.0/go.mod h1:wU0vUrJsVWBZ4P6e7xtFJEhFSNsfRLJ8H458uRjg03k= modernc.org/strutil v1.0.0 h1:XVFtQwFVwc02Wk+0L/Z/zDDXO81r5Lhe6iMKmGX3KhE= modernc.org/strutil v1.0.0/go.mod h1:lstksw84oURvj9y3tn8lGvRxyRC1S2+g5uuIzNfIOBs= +vitess.io/vitess v2.1.1+incompatible h1:nuuGHiWYWpudD3gOCLeGzol2EJ25e/u5Wer2wV1O130= diff --git a/handler.go b/handler.go index 17156245b..bb5aa245d 100644 --- a/handler.go +++ b/handler.go @@ -287,3 +287,31 @@ type TranslateIDsRequest struct { type TranslateIDsResponse struct { Keys []string } + +// InspectRequestParams represents the parts of an InspectRequest that +// aren't generic holder filtering attributes. +type InspectRequestParams struct { + Containers bool // include container details + Checksum bool // perform checksums +} + +// InspectRequest represents a request for a possibly-partial +// holder inspection, using a provided holder filter and inspect-specific +// parameters. +type InspectRequest struct { + HolderFilterParams + InspectRequestParams +} + +// InspectResponse contains the structured results for an InspectRequest. +// It may some day be expanded to include metadata about views or indexes. +type InspectResponse struct { + Fragments []struct { + Index string + Field string + View string + Shard int64 + Path string + Info *FragmentInfo + } +} diff --git a/holder.go b/holder.go index de3cd0701..30fb7ede0 100644 --- a/holder.go +++ b/holder.go @@ -21,7 +21,9 @@ import ( "os" "path" "path/filepath" + "regexp" "sort" + "strconv" "strings" "sync" "syscall" @@ -77,9 +79,8 @@ type Holder struct { // The interval at which the cached row ids are persisted to disk. cacheFlushInterval time.Duration - Logger logger.Logger - - snapshotQueue snapshotQueue + Logger logger.Logger + SnapshotQueue SnapshotQueue // Instantiates new translation stores OpenTranslateStore OpenTranslateStoreFunc @@ -102,6 +103,18 @@ type Holder struct { // needs to be queued and completed after all indexes // have opened. opening bool + + Opts HolderOpts +} + +type HolderOpts struct { + // ReadOnly indicates that this holder's contents should not produce + // disk writes under any circumstances. It must be set before Open + // is called, and changing it is not supported. + ReadOnly bool + // If Inspect is set, we'll try to obtain additional information + // about fragments when opening them. + Inspect bool } func (h *Holder) StartTransaction(ctx context.Context, id string, timeout time.Duration, exclusive bool) (*Transaction, error) { @@ -169,9 +182,285 @@ func NewHolder(partitionN int) *Holder { translationSyncer: NopTranslationSyncer, Logger: logger.NopLogger, + + SnapshotQueue: defaultSnapshotQueue, } } +type HolderInfo struct { + FragmentInfo map[string]FragmentInfo + FragmentNames []string +} + +type regexpList []*regexp.Regexp + +func newRegexpList(regexes string) (results regexpList, err error) { + if regexes == "" { + return nil, nil + } + for _, sub := range strings.Split(regexes, ",") { + re, err := regexp.Compile(sub) + if err != nil { + return nil, err + } + results = append(results, re) + } + return results, nil +} + +func (rl regexpList) Match(haystack string) bool { + if rl == nil { + return true + } + for _, re := range rl { + if re.MatchString(haystack) { + return true + } + } + return false +} + +// shardRange represents a series of shards +type shardRange struct { + min, max uint64 +} + +type shardRangeList []shardRange + +func newShardRangeList(shards string) (results shardRangeList, err error) { + if shards == "" { + return nil, nil + } + for _, sub := range strings.Split(shards, ",") { + var sr shardRange + minMax := strings.Split(sub, "-") + if len(minMax) > 2 { + return nil, fmt.Errorf("invalid range %q", sub) + } + sr.min, err = strconv.ParseUint(minMax[0], 10, 64) + if err != nil { + return nil, err + } + sr.max = sr.min + if len(minMax) == 2 { + sr.max, err = strconv.ParseUint(minMax[0], 10, 64) + if err != nil { + return nil, err + } + } + if sr.max < sr.min { + return nil, fmt.Errorf("invalid range %q: max < min", sub) + } + results = append(results, sr) + } + return results, nil +} + +func (sl shardRangeList) Match(shard uint64) bool { + if sl == nil { + return true + } + for _, sr := range sl { + if shard >= sr.min && shard <= sr.max { + return true + } + } + return false +} + +// HolderFilter represents something that potentially filters out +// parts of a holder, indicating whether or not to process them, +// or recurse into them. It is permissible to recurse a thing +// without processing it, or process it without recursing it. +// For instance, something looking to accumulate statistics +// about views might return (true, false) from CheckView, +// while a fragment scanning operation would return (false, true) +// from everything above CheckFrag. +type HolderFilter interface { + CheckIndex(iname string) (process bool, recurse bool) + CheckField(iname, fname string) (process bool, recurse bool) + CheckView(iname, fname, vname string) (process bool, recurse bool) + CheckFragment(iname, fname, vname string, shard uint64) (process bool) +} + +// HolderFilterAll is a placeholder type which always returns true for the +// check functions. You can embed it to make a HolderOperator which processes +// everything. +type HolderFilterAll struct{} + +func (HolderFilterAll) CheckIndex(string) (bool, bool) { + return true, true +} + +func (HolderFilterAll) CheckField(string, string) (bool, bool) { + return true, true +} + +func (HolderFilterAll) CheckView(string, string, string) (bool, bool) { + return true, true +} + +func (HolderFilterAll) CheckFragment(string, string, string, uint64) bool { + return true +} + +// HolderProcessNone is a placeholder type which does nothing for the +// process functions. You can embed it to make a HolderOperator which +// does nothing, or embed it and provide your own ProcessFragment to +// do just that. +type HolderProcessNone struct{} + +func (HolderProcessNone) ProcessIndex(*Index) error { + return nil +} + +func (HolderProcessNone) ProcessField(*Field) error { + return nil +} + +func (HolderProcessNone) ProcessView(*view) error { + return nil +} + +func (HolderProcessNone) ProcessFragment(*fragment) error { + return nil +} + +// HolderProcess represents something that has operations which can be +// performed on indexes, fields, views, and/or fragments. +type HolderProcess interface { + ProcessIndex(*Index) error + ProcessField(*Field) error + ProcessView(*view) error + ProcessFragment(*fragment) error +} + +// HolderOperator is both a filter and a process. This is the general +// form of "I want to do something to some part of a holder." +type HolderOperator interface { + HolderFilter + HolderProcess +} + +var _ HolderOperator = (*holderInspector)(nil) + +type HolderFilterParams struct { + Indexes string + Fields string + Views string + Shards string +} + +type holderFilterFull struct { + HolderFilterParams + indexRegexps regexpList + fieldRegexps regexpList + viewRegexps regexpList + shardRanges shardRangeList +} + +type inspectRequestFull struct { + HolderFilter + params InspectRequestParams +} + +func (i *holderFilterFull) CheckIndex(iname string) (process, recurse bool) { + return true, i.indexRegexps.Match(iname) +} + +func (i *holderFilterFull) CheckField(iname, fname string) (process, recurse bool) { + return true, i.fieldRegexps.Match(fname) +} + +func (i *holderFilterFull) CheckView(iname, fname, vname string) (process, recurse bool) { + return true, i.viewRegexps.Match(vname) +} + +func (i *holderFilterFull) CheckFragment(iname, fname, vname string, shard uint64) (process bool) { + return i.shardRanges.Match(shard) +} + +func NewHolderFilter(params HolderFilterParams) (result HolderFilter, err error) { + filter := &holderFilterFull{ + HolderFilterParams: params, + } + filter.indexRegexps, err = newRegexpList(params.Indexes) + if err != nil { + return nil, err + } + filter.fieldRegexps, err = newRegexpList(params.Fields) + if err != nil { + return nil, err + } + filter.viewRegexps, err = newRegexpList(params.Views) + if err != nil { + return nil, err + } + filter.shardRanges, err = newShardRangeList(params.Shards) + if err != nil { + return nil, err + } + return filter, nil +} + +func expandInspectRequest(req *InspectRequest) (*inspectRequestFull, error) { + filter, err := NewHolderFilter(req.HolderFilterParams) + if err != nil { + return nil, err + } + irf := &inspectRequestFull{ + HolderFilter: filter, + params: req.InspectRequestParams, + } + return irf, nil +} + +type holderInspector struct { + *inspectRequestFull + pathParts [3]string + path string + hi *HolderInfo +} + +func (h *holderInspector) ProcessIndex(i *Index) error { + h.pathParts[0] = i.name + return nil +} + +func (h *holderInspector) ProcessField(f *Field) error { + h.pathParts[1] = f.name + return nil +} + +func (h *holderInspector) ProcessView(v *view) error { + h.pathParts[2] = v.name + h.path = strings.Join(h.pathParts[:], "/") + return nil +} + +func (h *holderInspector) ProcessFragment(f *fragment) error { + path := h.path + "/" + strconv.FormatUint(f.shard, 10) + h.hi.FragmentInfo[path] = f.inspect(h.inspectRequestFull.params) + h.hi.FragmentNames = append(h.hi.FragmentNames, path) + return nil +} + +func (h *Holder) Inspect(ctx context.Context, req *InspectRequest) (*HolderInfo, error) { + fullReq, err := expandInspectRequest(req) + if err != nil { + return nil, err + } + inspector := &holderInspector{ + inspectRequestFull: fullReq, + hi: &HolderInfo{ + FragmentInfo: make(map[string]FragmentInfo), + }, + } + err = h.Process(ctx, inspector) + sort.Strings(inspector.hi.FragmentNames) + return inspector.hi, err +} + // Open initializes the root data directory for the holder. func (h *Holder) Open() error { h.opening = true @@ -213,11 +502,6 @@ func (h *Holder) Open() error { return errors.Wrap(err, "reading directory") } - // Run snapshots asynchronously. The snapshotQueue will have a background - // task associated with it which flushes it and waits until this channel - // is closed, so we should always close this channel when done. - h.snapshotQueue = newSnapshotQueue(10, 2, h.Logger) - for _, fi := range fis { // Skip files or hidden directories. if !fi.IsDir() || strings.HasPrefix(fi.Name(), ".") { @@ -261,18 +545,25 @@ func (h *Holder) Open() error { h.Logger.Printf("open holder: complete") - // Periodically flush cache. - h.wg.Add(1) - go func() { defer h.wg.Done(); h.monitorCacheFlush() }() - h.Stats.Open() - h.snapshotQueue.ScanHolder(h) h.opened.Close() return nil } +// Activate runs the background tasks relevant to keeping a holder in a stable +// state, such as scanning it for needed snapshots, or flushing caches. This +// is separate from opening because, while a server would nearly always want +// to do this, other use cases (like consistency checks of a data directory) +// need to avoid it even getting started. +func (h *Holder) Activate() { + // Periodically flush cache. + h.wg.Add(2) + go func() { defer h.wg.Done(); h.monitorCacheFlush() }() + go func() { defer h.wg.Done(); h.SnapshotQueue.ScanHolder(h, h.closing) }() +} + // checkForeignIndex is a check before applying a foreign // index to a field; if the index is not yet available, // (because holder is still opening and may not have opened @@ -313,10 +604,6 @@ func (h *Holder) Close() error { return errors.Wrap(err, "closing index") } } - if h.snapshotQueue != nil { - h.snapshotQueue.Stop() - h.snapshotQueue = nil - } // Reset opened in case Holder needs to be reopened. h.opened.mu.Lock() @@ -326,6 +613,11 @@ func (h *Holder) Close() error { return nil } +// Begin starts a transaction on the holder. +func (h *Holder) Begin(writable bool) (Tx, error) { + return NewMultiTx(writable, h), nil +} + // HasData returns true if Holder contains at least one index. // This is used to determine if the rebalancing of data is necessary // when a node joins the cluster. @@ -587,19 +879,16 @@ func (h *Holder) createIndex(name string, opt IndexOptions) (*Index, error) { } func (h *Holder) newIndex(path, name string) (*Index, error) { - index, err := NewIndex(path, name, h.partitionN) + index, err := NewIndex(h, path, name) if err != nil { return nil, err } - index.logger = h.Logger index.Stats = h.Stats.WithTags(fmt.Sprintf("index:%s", index.Name())) index.broadcaster = h.broadcaster index.newAttrStore = h.NewAttrStore index.columnAttrs = h.NewAttrStore(filepath.Join(index.path, ".data")) - index.snapshotQueue = h.snapshotQueue index.OpenTranslateStore = h.OpenTranslateStore index.translationSyncer = h.translationSyncer - index.holder = h return index, nil } @@ -1368,3 +1657,132 @@ func uint64InSlice(i uint64, s []uint64) bool { } return false } + +// Process loops through a holder based on the Check functions in op, calling +// the Process functions in op when indicated. +func (h *Holder) Process(ctx context.Context, op HolderOperator) (err error) { + var indexNames, fieldNames, viewNames []string + var fragNums []uint64 + + h.mu.Lock() + for indexName := range h.indexes { + indexNames = append(indexNames, indexName) + } + h.mu.Unlock() + for _, indexName := range indexNames { + if err = ctx.Err(); err != nil { + return err + } + process, recurse := op.CheckIndex(indexName) + if !process && !recurse { + continue + } + h.mu.Lock() + index := h.indexes[indexName] + h.mu.Unlock() + if index == nil { + continue + } + if err = ctx.Err(); err != nil { + return err + } + if process { + err = op.ProcessIndex(index) + if err != nil { + return err + } + } + if !recurse { + continue + } + fieldNames = fieldNames[:0] + index.mu.Lock() + for fieldName := range index.fields { + fieldNames = append(fieldNames, fieldName) + } + index.mu.Unlock() + for _, fieldName := range fieldNames { + if err = ctx.Err(); err != nil { + return err + } + process, recurse := op.CheckField(indexName, fieldName) + if !process && !recurse { + continue + } + index.mu.Lock() + field := index.fields[fieldName] + index.mu.Unlock() + if field == nil { + continue + } + if err = ctx.Err(); err != nil { + return err + } + if process { + err = op.ProcessField(field) + if err != nil { + return err + } + } + if !recurse { + continue + } + viewNames = viewNames[:0] + field.mu.Lock() + for viewName := range field.viewMap { + viewNames = append(viewNames, viewName) + } + field.mu.Unlock() + for _, viewName := range viewNames { + if err = ctx.Err(); err != nil { + return err + } + process, recurse := op.CheckView(indexName, fieldName, viewName) + if !process && !recurse { + continue + } + field.mu.Lock() + view := field.viewMap[viewName] + field.mu.Unlock() + if view == nil { + continue + } + if err = ctx.Err(); err != nil { + return err + } + if process { + err = op.ProcessView(view) + if err != nil { + return err + } + } + if !recurse { + continue + } + fragNums := fragNums[:0] + view.mu.Lock() + for fragNum := range view.fragments { + fragNums = append(fragNums, fragNum) + } + view.mu.Unlock() + for _, fragNum := range fragNums { + if err = ctx.Err(); err != nil { + return err + } + process := op.CheckFragment(indexName, fieldName, viewName, fragNum) + if !process { + continue + } + view.mu.Lock() + frag := view.fragments[fragNum] + view.mu.Unlock() + err = op.ProcessFragment(frag) + if err != nil { + return err + } + } + } + } + } + return nil +} diff --git a/holder_internal_test.go b/holder_internal_test.go index ccc52c5b0..1a229858a 100644 --- a/holder_internal_test.go +++ b/holder_internal_test.go @@ -1,4 +1,4 @@ -// Copyright 2017 Pilosa Corp. +// Copyright 2020 Pilosa Corp. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,313 +15,172 @@ package pilosa import ( + "context" "io/ioutil" "os" - "path/filepath" - "reflect" - "strings" "testing" - "time" - - "github.com/pilosa/pilosa/v2/roaring" ) -type tHolder struct { - *Holder +type testHolderOperator struct { + indexSeen, indexProcessed int + fieldSeen, fieldProcessed int + viewSeen, viewProcessed int + fragmentSeen, fragmentProcessed int + waitHere chan struct{} } -// Close closes the holder and removes all underlying data. -func (h *tHolder) Close() error { - defer os.RemoveAll(h.Path) - return h.Holder.Close() +func (t *testHolderOperator) CheckIndex(string) (bool, bool) { + t.indexSeen++ + return true, true } -// Reopen instantiates and opens a new holder. -// Note that the holder must be Closed first. -func (h *tHolder) Reopen() error { - path, logger := h.Path, h.Holder.Logger - h.Holder = NewHolder(DefaultPartitionN) - h.Holder.Path = path - h.Holder.Logger = logger - return h.Holder.Open() +func (t *testHolderOperator) CheckField(string, string) (bool, bool) { + t.fieldSeen++ + return true, true } -func newHolder() *tHolder { - path, err := ioutil.TempDir(*TempDir, "pilosa-") +func (t *testHolderOperator) CheckView(string, string, string) (bool, bool) { + t.viewSeen++ + return true, true +} + +func (t *testHolderOperator) CheckFragment(string, string, string, uint64) bool { + t.fragmentSeen++ + return true +} + +func (t *testHolderOperator) ProcessIndex(*Index) error { + t.indexProcessed++ + return nil +} + +func (t *testHolderOperator) ProcessField(*Field) error { + t.fieldProcessed++ + return nil +} + +func (t *testHolderOperator) ProcessView(*view) error { + t.viewProcessed++ + return nil +} + +func (t *testHolderOperator) ProcessFragment(*fragment) error { + if t.waitHere != nil { + <-t.waitHere + } + t.fragmentProcessed++ + return nil +} + +func makeHolder() (*Holder, string, error) { + path, err := ioutil.TempDir("", "pilosa-") if err != nil { - panic(err) + return nil, "", err } - - h := &tHolder{Holder: NewHolder(DefaultPartitionN)} - h.Path = path - return h -} - -// MustCreateFieldIfNotExists returns a given field. Panic on error. -func (h *tHolder) MustCreateFieldIfNotExists(index, field string) *Field { - f, err := h.MustCreateIndexIfNotExists(index, IndexOptions{}).CreateFieldIfNotExists(field, OptFieldTypeDefault()) - if err != nil { - panic(err) - } - return f -} - -// MustCreateIndexIfNotExists returns a given index. Panic on error. -func (h *tHolder) MustCreateIndexIfNotExists(index string, opt IndexOptions) *Index { - idx, err := h.Holder.CreateIndexIfNotExists(index, opt) - if err != nil { - panic(err) - } - return idx -} - -// SetBit clears a bit on the given field. -func (h *tHolder) SetBit(index, field string, rowID, columnID uint64) { - f := h.MustCreateFieldIfNotExists(index, field) - _, err := f.SetBit(rowID, columnID, nil) - if err != nil { - panic(err) - } -} - -// Row returns a Row for a given field. -func (h *tHolder) Row(index, field string, rowID uint64) *Row { - f := h.MustCreateFieldIfNotExists(index, field) - row, err := f.Row(rowID) - if err != nil { - panic(err) - } - return row -} - -func TestHolder_Optn(t *testing.T) { - t.Run("ErrViewPermission", func(t *testing.T) { - if os.Geteuid() == 0 { - t.Skip("Skipping permissions test since user is root.") - } - availableShardFileFlushDuration.Set(100 * time.Millisecond) - h := newHolder() - defer h.Close() - - if idx, err := h.CreateIndex("foo", IndexOptions{}); err != nil { - t.Fatal(err) - } else if field, err := idx.CreateField("bar", OptFieldTypeDefault()); err != nil { - t.Fatal(err) - } else if _, err := field.createViewIfNotExists(viewStandard); err != nil { - t.Fatal(err) - } else if err := h.Holder.Close(); err != nil { - t.Fatal(err) - } else if err := os.Chmod(filepath.Join(h.Path, "foo", "bar", "views", "standard"), 0000); err != nil { - t.Fatal(err) - } - defer func() { - // we don't care about a failure here - _ = os.Chmod(filepath.Join(h.Path, "foo", "bar", "views", "standard"), 0755) - }() - if err := h.Reopen(); err == nil || !strings.Contains(err.Error(), "permission denied") { - t.Fatalf("unexpected error: %s", err) - } - }) - t.Run("ErrViewFragmentsMkdir", func(t *testing.T) { - if os.Geteuid() == 0 { - t.Skip("Skipping permissions test since user is root.") - } - h := newHolder() - defer h.Close() - - if idx, err := h.CreateIndex("foo", IndexOptions{}); err != nil { - t.Fatal(err) - } else if field, err := idx.CreateField("bar", OptFieldTypeDefault()); err != nil { - t.Fatal(err) - } else if _, err := field.createViewIfNotExists(viewStandard); err != nil { - t.Fatal(err) - } else if err := h.Holder.Close(); err != nil { - t.Fatal(err) - } else if err := os.Chmod(filepath.Join(h.Path, "foo", "bar", "views", "standard", "fragments"), 0000); err != nil { - t.Fatal(err) - } - defer func() { - // we don't care about a failure here - _ = os.Chmod(filepath.Join(h.Path, "foo", "bar", "views", "standard", "fragments"), 0755) - }() - - if err := h.Reopen(); err == nil || !strings.Contains(err.Error(), "permission denied") { - t.Fatalf("unexpected error: %s", err) - } - }) - - t.Run("ErrFragmentCachePermission", func(t *testing.T) { - if os.Geteuid() == 0 { - t.Skip("Skipping permissions test since user is root.") - } - h := newHolder() - defer h.Close() - - if idx, err := h.CreateIndex("foo", IndexOptions{}); err != nil { - t.Fatal(err) - } else if field, err := idx.CreateField("bar", OptFieldTypeDefault()); err != nil { - t.Fatal(err) - } else if view, err := field.createViewIfNotExists(viewStandard); err != nil { - t.Fatal(err) - } else if _, err := field.SetBit(0, 0, nil); err != nil { - t.Fatal(err) - } else if err := view.Fragment(0).FlushCache(); err != nil { - t.Fatal(err) - } else if err := h.Holder.Close(); err != nil { - t.Fatal(err) - } else if err := os.Chmod(filepath.Join(h.Path, "foo", "bar", "views", "standard", "fragments", "0.cache"), 0000); err != nil { - t.Fatal(err) - } - defer func() { - _ = os.Chmod(filepath.Join(h.Path, "foo", "bar", "views", "standard", "fragments", "0.cache"), 0644) - }() - if err := h.Reopen(); err == nil || !strings.Contains(err.Error(), "permission denied") { - t.Fatalf("unexpected error: %s", err) - } - }) - -} - -// Ensure holder can clean up orphaned fragments. -func TestHolderCleaner_CleanHolder(t *testing.T) { - availableShardFileFlushDuration.Set(100 * time.Millisecond) //shorten the default time to force a file write - cluster := NewTestCluster(2) - - // Create a local holder. - hldr0 := newHolder() - defer hldr0.Close() - - // Mock 2-node, fully replicated cluster. - cluster.ReplicaN = 2 - - cluster.nodes[0].URI = NewTestURIFromHostPort("localhost", 0) - - // Create fields on nodes. - for _, hldr := range []*tHolder{hldr0} { - hldr.MustCreateFieldIfNotExists("i", "f") - hldr.MustCreateFieldIfNotExists("i", "f0") - hldr.MustCreateFieldIfNotExists("y", "z") - } - - // Set data on the local holder. - hldr0.SetBit("i", "f", 0, 10) - hldr0.SetBit("i", "f", 0, 4000) - hldr0.SetBit("i", "f", 2, 20) - hldr0.SetBit("i", "f", 3, 10) - hldr0.SetBit("i", "f", 120, 10) - hldr0.SetBit("i", "f", 200, 4) - - hldr0.SetBit("i", "f0", 9, ShardWidth+5) - - hldr0.SetBit("y", "z", 10, (2*ShardWidth)+4) - hldr0.SetBit("y", "z", 10, (2*ShardWidth)+5) - hldr0.SetBit("y", "z", 10, (2*ShardWidth)+7) - - // Set highest shard. - err := hldr0.Field("i", "f").AddRemoteAvailableShards(roaring.NewBitmap(0, 1)) - if err != nil { - t.Fatalf("adding remote shards: %v", err) - } - err = hldr0.Field("y", "z").AddRemoteAvailableShards(roaring.NewBitmap(0, 1, 2)) - if err != nil { - t.Fatalf("adding remote shards: %v", err) - } - time.Sleep(2 * availableShardFileFlushDuration.Get()) - - // Keep replication the same and ensure we get the expected results. - cluster.ReplicaN = 2 - - // Set up cleaner for replication 2. - cleaner2 := holderCleaner{ - Node: cluster.nodes[0], - Holder: hldr0.Holder, - Cluster: cluster, - } - - if err := cleaner2.CleanHolder(); err != nil { - t.Fatal(err) - } - - // Verify data is the same on both nodes. - for i, hldr := range []*tHolder{hldr0} { - if a := hldr.Row("i", "f", 0).Columns(); !reflect.DeepEqual(a, []uint64{10, 4000}) { - t.Fatalf("unexpected columns(%d/0): %+v", i, a) - } else if a := hldr.Row("i", "f", 2).Columns(); !reflect.DeepEqual(a, []uint64{20}) { - t.Fatalf("unexpected columns(%d/2): %+v", i, a) - } else if a := hldr.Row("i", "f", 3).Columns(); !reflect.DeepEqual(a, []uint64{10}) { - t.Fatalf("unexpected columns(%d/3): %+v", i, a) - } else if a := hldr.Row("i", "f", 120).Columns(); !reflect.DeepEqual(a, []uint64{10}) { - t.Fatalf("unexpected columns(%d/120): %+v", i, a) - } else if a := hldr.Row("i", "f", 200).Columns(); !reflect.DeepEqual(a, []uint64{4}) { - t.Fatalf("unexpected columns(%d/200): %+v", i, a) - } - - if a := hldr.Row("i", "f0", 9).Columns(); !reflect.DeepEqual(a, []uint64{ShardWidth + 5}) { - t.Fatalf("unexpected columns(%d/d/f0): %+v", i, a) - } - - if a := hldr.Row("y", "z", 10).Columns(); !reflect.DeepEqual(a, []uint64{(2 * ShardWidth) + 4, (2 * ShardWidth) + 5, (2 * ShardWidth) + 7}) { - t.Fatalf("unexpected columns(%d/y/z): %+v", i, a) - } - } - - // Change replication factor to ensure we have fragments to remove. - cluster.ReplicaN = 1 - - // Set up cleaner for replication 1. - cleaner1 := holderCleaner{ - Node: cluster.nodes[0], - Holder: hldr0.Holder, - Cluster: cluster, - } - - if err := cleaner1.CleanHolder(); err != nil { - t.Fatal(err) - } - - // Verify data is the same on both nodes. - for i, hldr := range []*tHolder{hldr0} { - if a := hldr.Row("i", "f", 0).Columns(); !reflect.DeepEqual(a, []uint64{10, 4000}) { - t.Fatalf("unexpected columns(%d/0): %+v", i, a) - } else if a := hldr.Row("i", "f", 2).Columns(); !reflect.DeepEqual(a, []uint64{20}) { - t.Fatalf("unexpected columns(%d/2): %+v", i, a) - } else if a := hldr.Row("i", "f", 3).Columns(); !reflect.DeepEqual(a, []uint64{10}) { - t.Fatalf("unexpected columns(%d/3): %+v", i, a) - } else if a := hldr.Row("i", "f", 120).Columns(); !reflect.DeepEqual(a, []uint64{10}) { - t.Fatalf("unexpected columns(%d/120): %+v", i, a) - } else if a := hldr.Row("i", "f", 200).Columns(); !reflect.DeepEqual(a, []uint64{4}) { - t.Fatalf("unexpected columns(%d/200): %+v", i, a) - } - - f := hldr.fragment("i", "f0", viewStandard, 1) - if f != nil { - t.Fatalf("expected fragment to be deleted: (%d/i/f0): %+v", i, f) - } - - if a := hldr.Row("y", "z", 10).Columns(); !reflect.DeepEqual(a, []uint64{(2 * ShardWidth) + 4, (2 * ShardWidth) + 5, (2 * ShardWidth) + 7}) { - t.Fatalf("unexpected columns(%d/y/z): %+v", i, a) - } - } -} - -// Ensure holder can reopen. -func TestHolderCleaner_Reopen(t *testing.T) { h := NewHolder(DefaultPartitionN) - h.Path = "path" - err := h.Open() + + return h, path, nil +} + +func testSetBit(t *testing.T, h *Holder, index, field string, rowID, columnID uint64) { + tx, err := h.Begin(true) if err != nil { - t.Fatalf("couldn't open holder: %v", err) + t.Fatal(err) } - err = h.Close() + defer func() { _ = tx.Rollback() }() + + idx, err := h.CreateIndexIfNotExists(index, IndexOptions{}) if err != nil { - t.Fatalf("couldn't close holder: %v", err) + t.Fatalf("creating index: %v", err) } - err = h.Open() + f, err := idx.CreateFieldIfNotExists(field, OptFieldTypeDefault()) if err != nil { - t.Fatalf("couldn't open holder: %v", err) + t.Fatalf("setting bit: %v", err) } - err = h.Close() + _, err = f.SetBit(tx, rowID, columnID, nil) if err != nil { - t.Fatalf("couldn't close holder: %v", err) + t.Fatalf("setting bit: %v", err) + } + if err := tx.Commit(); err != nil { + t.Fatal(err) + } +} + +func TestHolderOperatorProcess(t *testing.T) { + h, path, err := makeHolder() + if err != nil { + t.Fatalf("creating holder: %v", err) + } + defer os.RemoveAll(path) + defer h.Close() + + // Write bits to separate indexes. + testSetBit(t, h, "i0", "f", 100, 200) + testSetBit(t, h, "i1", "f", 100, 200) + testSetBit(t, h, "i1", "f", 100, 12345678) + + testOp := testHolderOperator{} + ctx := context.Background() + err = h.Process(ctx, &testOp) + if err != nil { + t.Fatalf("processing holder: %v", err) + } + expected := testHolderOperator{ + indexSeen: 2, indexProcessed: 2, + fieldSeen: 2, fieldProcessed: 2, + viewSeen: 2, viewProcessed: 2, + fragmentSeen: 3, fragmentProcessed: 3, + } + if testOp != expected { + t.Fatalf("holder processor did not process as expected. expected %#v, got %#v", expected, testOp) + } +} + +func TestHolderOperatorCancel(t *testing.T) { + h, path, err := makeHolder() + if err != nil { + t.Fatalf("creating holder: %v", err) + } + defer os.RemoveAll(path) + defer h.Close() + + // Write bits to separate indexes. + testSetBit(t, h, "i0", "f", 100, 200) + testSetBit(t, h, "i1", "f", 100, 200) + testSetBit(t, h, "i1", "f", 100, 12345678) + + // Here, we want to ensure that the operation gets cancelled + // successfully. In practice we expect it to process one fragment, then + // end up blocked on the waitHere, then get cancelled... But the + // waitHere blockage isn't really something holder.Process can do + // anything about, so we close the channel, so two fragments are + // processed. But in theory you could end up with only one fragment + // processed if this goroutine managed to cancel before the processor + // gets to the next fragment. Point is, it shouldn't hit all three, + // because the checks against the cancellation should fire before it + // gets there. + testOp := testHolderOperator{waitHere: make(chan struct{})} + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + err = h.Process(ctx, &testOp) + close(done) + }() + testOp.waitHere <- struct{}{} + cancel() + close(testOp.waitHere) + <-done + if err != context.Canceled { + t.Fatalf("processing holder: expected context.Canceled, got %v", err) + } + testOp.waitHere = nil + expected := testHolderOperator{ + indexSeen: 2, indexProcessed: 2, + fieldSeen: 2, fieldProcessed: 2, + viewSeen: 2, viewProcessed: 2, + fragmentSeen: 3, fragmentProcessed: 3, + } + if testOp == expected { + t.Fatalf("holder processor did not cancel. expected something other than %#v", expected) } } diff --git a/holder_test.go b/holder_test.go index 42c010079..45df98852 100644 --- a/holder_test.go +++ b/holder_test.go @@ -162,11 +162,19 @@ func TestHolder_Open(t *testing.T) { h := test.MustOpenHolder() defer h.Close() + tx, err := h.Begin(true) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + if idx, err := h.CreateIndex("foo", pilosa.IndexOptions{}); err != nil { t.Fatal(err) } else if field, err := idx.CreateField("bar", pilosa.OptFieldTypeDefault()); err != nil { t.Fatal(err) - } else if _, err := field.SetBit(0, 0, nil); err != nil { + } else if _, err := field.SetBit(tx, 0, 0, nil); err != nil { + t.Fatal(err) + } else if err := tx.Commit(); err != nil { t.Fatal(err) } else if err := h.Holder.Close(); err != nil { t.Fatal(err) @@ -184,11 +192,19 @@ func TestHolder_Open(t *testing.T) { h := test.MustOpenHolder() defer h.Close() + tx, err := h.Begin(true) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + if idx, err := h.CreateIndex("foo", pilosa.IndexOptions{}); err != nil { t.Fatal(err) } else if field, err := idx.CreateField("bar", pilosa.OptFieldTypeDefault()); err != nil { t.Fatal(err) - } else if _, err := field.SetBit(0, 0, nil); err != nil { + } else if _, err := field.SetBit(tx, 0, 0, nil); err != nil { + t.Fatal(err) + } else if err := tx.Commit(); err != nil { t.Fatal(err) } else if err := h.Holder.Close(); err != nil { t.Fatal(err) @@ -204,11 +220,19 @@ func TestHolder_Open(t *testing.T) { h := test.MustOpenHolder() defer h.Close() + tx, err := h.Begin(true) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + if idx, err := h.CreateIndex("foo", pilosa.IndexOptions{}); err != nil { t.Fatal(err) } else if field, err := idx.CreateField("bar", pilosa.OptFieldTypeDefault()); err != nil { t.Fatal(err) - } else if _, err := field.SetBit(0, 0, nil); err != nil { + } else if _, err := field.SetBit(tx, 0, 0, nil); err != nil { + t.Fatal(err) + } else if err := tx.Commit(); err != nil { t.Fatal(err) } else if err := h.Holder.Close(); err != nil { t.Fatal(err) diff --git a/http/client_test.go b/http/client_test.go index fb5568658..ff543def5 100644 --- a/http/client_test.go +++ b/http/client_test.go @@ -777,7 +777,7 @@ func TestClient_ImportKeys(t *testing.T) { // Load bitmap into cache to ensure cache gets updated. index := hldr.MustCreateIndexIfNotExists("i", pilosa.IndexOptions{Keys: true}) - field, err := index.CreateFieldIfNotExists(fldName, pilosa.OptFieldTypeInt(-100, 100)) + _, err := index.CreateFieldIfNotExists(fldName, pilosa.OptFieldTypeInt(-100, 100)) if err != nil { t.Fatal(err) } @@ -792,15 +792,6 @@ func TestClient_ImportKeys(t *testing.T) { t.Fatal(err) } - // Verify Sum. - sum, cnt, err := field.Sum(nil, fldName) - if err != nil { - t.Fatal(err) - } - if sum != 50 || cnt != 3 { - t.Fatalf("unexpected values: got sum=%v, count=%v; expected sum=50, cnt=3", sum, cnt) - } - // Verify range. queryRequest := &pilosa.QueryRequest{ Query: fmt.Sprintf(`Row(%s>10)`, fldName), @@ -823,15 +814,6 @@ func TestClient_ImportKeys(t *testing.T) { t.Fatal(err) } - // Verify Sum. - sum, cnt, err = field.Sum(nil, fldName) - if err != nil { - t.Fatal(err) - } - if sum != 30 || cnt != 2 { - t.Fatalf("unexpected values: got sum=%v, count=%v; expected sum=30, cnt=2", sum, cnt) - } - // Verify Range. queryRequest = &pilosa.QueryRequest{ Query: fmt.Sprintf(`Row(%s>10)`, fldName), @@ -928,7 +910,7 @@ func TestClient_ImportValue(t *testing.T) { // Load bitmap into cache to ensure cache gets updated. index := hldr.MustCreateIndexIfNotExists("i", pilosa.IndexOptions{}) - field, err := index.CreateFieldIfNotExists(fldName, pilosa.OptFieldTypeInt(-100, 100)) + _, err := index.CreateFieldIfNotExists(fldName, pilosa.OptFieldTypeInt(-100, 100)) if err != nil { t.Fatal(err) } @@ -944,43 +926,21 @@ func TestClient_ImportValue(t *testing.T) { } // Verify Sum. - sum, cnt, err := field.Sum(nil, fldName) - if err != nil { + if resp, err := c.Query(context.Background(), "i", &pilosa.QueryRequest{Query: `Sum(field=f)`}); err != nil { t.Fatal(err) - } - if sum != 50 || cnt != 3 { - t.Fatalf("unexpected values: got sum=%v, count=%v; expected sum=50, cnt=3", sum, cnt) - } - - // Verify Min. - min, cnt, err := field.Min(nil, fldName) - if err != nil { - t.Fatal(err) - } - if min != -10 || cnt != 1 { - t.Fatalf("unexpected values: got min=%v, count=%v; expected min=-10, cnt=1", min, cnt) - } - - // Verify Min with Filter. - filter, err := field.Range(fldName, pql.GT, 40) - if err != nil { - t.Fatal(err) - } - min, cnt, err = field.Min(filter, fldName) - if err != nil { - t.Fatal(err) - } - if min != 0 || cnt != 0 { - t.Fatalf("unexpected values: got min=%v, count=%v; expected min=0, cnt=0", min, cnt) + } else if vc, ok := resp.Results[0].(pilosa.ValCount); !ok { + t.Fatalf("expected ValCount; got %T", resp.Results[0]) + } else if vc.Val != 50 || vc.Count != 3 { + t.Fatalf("unexpected values: got sum=%v, count=%v; expected sum=50, cnt=3", vc.Val, vc.Count) } // Verify Max. - max, cnt, err := field.Max(nil, fldName) - if err != nil { + if resp, err := c.Query(context.Background(), "i", &pilosa.QueryRequest{Query: `Max(field=f)`}); err != nil { t.Fatal(err) - } - if max != 40 || cnt != 1 { - t.Fatalf("unexpected values: got max=%v, count=%v; expected max=40, cnt=1", max, cnt) + } else if vc, ok := resp.Results[0].(pilosa.ValCount); !ok { + t.Fatalf("expected ValCount; got %T", resp.Results[0]) + } else if vc.Val != 40 || vc.Count != 1 { + t.Fatalf("unexpected values: got max=%v, count=%v; expected max=40, cnt=1", vc.Val, vc.Count) } // Send import request. @@ -992,34 +952,21 @@ func TestClient_ImportValue(t *testing.T) { } // Verify Sum. - sum, cnt, err = field.Sum(nil, fldName) - if err != nil { + if resp, err := c.Query(context.Background(), "i", &pilosa.QueryRequest{Query: `Sum(field=f)`}); err != nil { t.Fatal(err) - } - if sum != 20 || cnt != 1 { - t.Fatalf("unexpected values: got sum=%v, count=%v; expected sum=20, cnt=1", sum, cnt) - } - - // Verify Min with Filter. - filter, err = field.Range(fldName, pql.GT, 40) - if err != nil { - t.Fatal(err) - } - min, cnt, err = field.Min(filter, fldName) - if err != nil { - t.Fatal(err) - } - if min != 0 || cnt != 0 { - t.Fatalf("unexpected values: got min=%v, count=%v; expected min=0, cnt=0", min, cnt) + } else if vc, ok := resp.Results[0].(pilosa.ValCount); !ok { + t.Fatalf("expected ValCount; got %T", resp.Results[0]) + } else if vc.Val != 20 || vc.Count != 1 { + t.Fatalf("unexpected values: got sum=%v, count=%v; expected sum=20, cnt=1", vc.Val, vc.Count) } // Verify Max. - max, cnt, err = field.Max(nil, fldName) - if err != nil { + if resp, err := c.Query(context.Background(), "i", &pilosa.QueryRequest{Query: `Max(field=f)`}); err != nil { t.Fatal(err) - } - if max != 20 || cnt != 1 { - t.Fatalf("unexpected values: got max=%v, count=%v; expected max=20, cnt=1", max, cnt) + } else if vc, ok := resp.Results[0].(pilosa.ValCount); !ok { + t.Fatalf("expected ValCount; got %T", resp.Results[0]) + } else if vc.Val != 20 || vc.Count != 1 { + t.Fatalf("unexpected values: got max=%v, count=%v; expected max=20, cnt=1", vc.Val, vc.Count) } } @@ -1071,7 +1018,7 @@ func TestClient_ImportExistence(t *testing.T) { fldName := "fint" index := hldr.MustCreateIndexIfNotExists(idxName, pilosa.IndexOptions{TrackExistence: true}) - field, err := index.CreateFieldIfNotExists(fldName, pilosa.OptFieldTypeInt(-100, 100)) + _, err := index.CreateFieldIfNotExists(fldName, pilosa.OptFieldTypeInt(-100, 100)) if err != nil { t.Fatal(err) } @@ -1087,12 +1034,12 @@ func TestClient_ImportExistence(t *testing.T) { } // Verify Sum. - sum, cnt, err := field.Sum(nil, fldName) - if err != nil { + if resp, err := c.Query(context.Background(), idxName, &pilosa.QueryRequest{Query: fmt.Sprintf(`Sum(field=%s)`, fldName)}); err != nil { t.Fatal(err) - } - if sum != 50 || cnt != 3 { - t.Fatalf("unexpected values: got sum=%v, count=%v; expected sum=50, cnt=3", sum, cnt) + } else if vc, ok := resp.Results[0].(pilosa.ValCount); !ok { + t.Fatalf("expected ValCount; got %T", resp.Results[0]) + } else if vc.Val != 50 || vc.Count != 3 { + t.Fatalf("unexpected values: got sum=%v, count=%v; expected sum=50, cnt=3", vc.Val, vc.Count) } // Verify existence. diff --git a/http/handler.go b/http/handler.go index f6e0ac001..06a62ebd7 100644 --- a/http/handler.go +++ b/http/handler.go @@ -221,6 +221,8 @@ func (h *Handler) populateValidators() { h.validators["GetTransaction"] = queryValidationSpecRequired() h.validators["PostTransaction"] = queryValidationSpecRequired() h.validators["PostFinishTransaction"] = queryValidationSpecRequired() + h.validators["Inspect"] = queryValidationSpecRequired().Optional("indexes", "fields", "views", "shards", "checksum", "containers") + } type contextKeyQuery int @@ -252,14 +254,17 @@ func (h *Handler) queryArgValidator(next http.Handler) http.Handler { if validator, ok := h.validators[key]; ok { if err := validator.validate(r.URL.Query()); err != nil { - // TODO: Return the response depending on the Accept header - response := errorResponse{Error: err.Error()} - body, err := json.Marshal(response) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return + errText := err.Error() + if validHeaderAcceptJSON(r.Header) { + response := errorResponse{Error: errText} + data, err := json.Marshal(response) + if err != nil { + h.logger.Printf("failed to encode error %q as JSON: %v", errText, err) + } else { + errText = string(data) + } } - http.Error(w, string(body), http.StatusBadRequest) + http.Error(w, errText, http.StatusBadRequest) return } } @@ -349,6 +354,7 @@ func newRouter(handler *Handler) *mux.Router { router.HandleFunc("/index/{index}/field/{field}/import-roaring/{shard}", handler.handlePostImportRoaring).Methods("POST").Name("PostImportRoaring") router.HandleFunc("/index/{index}/query", handler.handlePostQuery).Methods("POST").Name("PostQuery") router.HandleFunc("/info", handler.handleGetInfo).Methods("GET").Name("GetInfo") + router.HandleFunc("/inspect", handler.handleInspect).Methods("GET").Name("Inspect") router.HandleFunc("/recalculate-caches", handler.handleRecalculateCaches).Methods("POST").Name("RecalculateCaches") router.HandleFunc("/schema", handler.handleGetSchema).Methods("GET").Name("GetSchema") router.HandleFunc("/schema", handler.handlePostSchema).Methods("POST").Name("PostSchema") @@ -587,6 +593,37 @@ func (h *Handler) handleGetInfo(w http.ResponseWriter, r *http.Request) { } } +func (h *Handler) handleInspect(w http.ResponseWriter, r *http.Request) { + if !validHeaderAcceptJSON(r.Header) { + http.Error(w, "JSON only acceptable response", http.StatusNotAcceptable) + return + } + q := r.URL.Query() + _, checksum := q["checksum"] + _, containers := q["containers"] + req := pilosa.InspectRequest{ + HolderFilterParams: pilosa.HolderFilterParams{ + Indexes: q.Get("indexes"), + Fields: q.Get("fields"), + Views: q.Get("views"), + Shards: q.Get("shards"), + }, + InspectRequestParams: pilosa.InspectRequestParams{ + Checksum: checksum, + Containers: containers, + }, + } + info, err := h.api.Inspect(r.Context(), &req) + if err != nil { + http.Error(w, fmt.Sprintf("inspect request: %v", err), http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(info); err != nil { + h.logger.Printf("write inspect response error: %s", err) + } +} + type getSchemaResponse struct { Indexes []*pilosa.IndexInfo `json:"indexes"` } @@ -1780,8 +1817,13 @@ func (h *Handler) handlePostClusterMessage(w http.ResponseWriter, r *http.Reques } err := h.api.ClusterMessage(r.Context(), r.Body) if err != nil { - // TODO this was the previous behavior, but perhaps not everything is a bad request - http.Error(w, err.Error(), http.StatusBadRequest) + switch err := err.(type) { + case pilosa.MessageProcessingError: + http.Error(w, err.Error(), http.StatusInternalServerError) + default: + http.Error(w, err.Error(), http.StatusBadRequest) + } + return } w.Header().Set("Content-Type", "application/json") @@ -2114,6 +2156,7 @@ func (h *Handler) handlePostTranslateKeys(w http.ResponseWriter, r *http.Request buf, err := h.api.TranslateKeys(r.Context(), r.Body) if err != nil { http.Error(w, fmt.Sprintf("translate keys: %v", err), http.StatusInternalServerError) + return } // Write response. diff --git a/index.go b/index.go index 481d22cf4..41dfeb645 100644 --- a/index.go +++ b/index.go @@ -27,7 +27,6 @@ import ( "github.com/gogo/protobuf/proto" "github.com/pilosa/pilosa/v2/internal" - "github.com/pilosa/pilosa/v2/logger" "github.com/pilosa/pilosa/v2/roaring" "github.com/pilosa/pilosa/v2/stats" "github.com/pkg/errors" @@ -36,19 +35,17 @@ import ( // Index represents a container for fields. type Index struct { - mu sync.RWMutex - createdAt int64 - path string - name string - keys bool // use string keys + mu sync.RWMutex + createdAt int64 + path string + name string + qualifiedName string + keys bool // use string keys // Existence tracking. trackExistence bool existenceFld *Field - // Partitions used by translation. - partitionN int - // Fields by name. fields map[string]*Field @@ -60,9 +57,6 @@ type Index struct { broadcaster broadcaster Stats stats.StatsClient - logger logger.Logger - snapshotQueue snapshotQueue - // Passed to field for foreign-index lookup. holder *Holder @@ -76,24 +70,23 @@ type Index struct { } // NewIndex returns a new instance of Index. -func NewIndex(path, name string, partitionN int) (*Index, error) { +func NewIndex(holder *Holder, path, name string) (*Index, error) { err := validateName(name) if err != nil { return nil, errors.Wrap(err, "validating name") } return &Index{ - path: path, - name: name, - partitionN: partitionN, - fields: make(map[string]*Field), + path: path, + name: name, + fields: make(map[string]*Field), newAttrStore: newNopAttrStore, columnAttrs: nopStore, broadcaster: NopBroadcaster, Stats: stats.NopStatsClient, - logger: logger.NopLogger, + holder: holder, trackExistence: true, translateStores: make(map[int]TranslateStore), @@ -114,6 +107,9 @@ func (i *Index) CreatedAt() int64 { // Name returns name of the index. func (i *Index) Name() string { return i.name } +// QualifiedName returns the qualified name of the index. +func (i *Index) QualifiedName() string { return i.qualifiedName } + // Path returns the path the index was initialized with. func (i *Index) Path() string { return i.path } @@ -155,18 +151,18 @@ func (i *Index) OpenWithTimestamp() error { return i.open(true) } func (i *Index) open(withTimestamp bool) (err error) { // Ensure the path exists. - i.logger.Debugf("ensure index path exists: %s", i.path) + i.holder.Logger.Debugf("ensure index path exists: %s", i.path) if err := os.MkdirAll(i.path, 0777); err != nil { return errors.Wrap(err, "creating directory") } // Read meta file. - i.logger.Debugf("load meta file for index: %s", i.name) + i.holder.Logger.Debugf("load meta file for index: %s", i.name) if err := i.loadMeta(); err != nil { return errors.Wrap(err, "loading meta file") } - i.logger.Debugf("open fields for index: %s", i.name) + i.holder.Logger.Debugf("open fields for index: %s", i.name) if err := i.openFields(withTimestamp); err != nil { return errors.Wrap(err, "opening fields") } @@ -181,15 +177,15 @@ func (i *Index) open(withTimestamp bool) (err error) { return errors.Wrap(err, "opening attrstore") } - i.logger.Debugf("open translate store for index: %s", i.name) + i.holder.Logger.Debugf("open translate store for index: %s", i.name) var g errgroup.Group var mu sync.Mutex - for partitionID := 0; partitionID < i.partitionN; partitionID++ { + for partitionID := 0; partitionID < i.holder.partitionN; partitionID++ { partitionID := partitionID g.Go(func() error { - store, err := i.OpenTranslateStore(i.TranslateStorePath(partitionID), i.name, "", partitionID, i.partitionN) + store, err := i.OpenTranslateStore(i.TranslateStorePath(partitionID), i.name, "", partitionID, i.holder.partitionN) if err != nil { return errors.Wrapf(err, "opening index translate store: partition=%d", partitionID) } @@ -239,7 +235,7 @@ fileLoop: defer func() { <-indexQueue }() - i.logger.Debugf("open field: %s", fi.Name()) + i.holder.Logger.Debugf("open field: %s", fi.Name()) mu.Lock() fld, err := i.newField(i.fieldPath(filepath.Base(fi.Name())), filepath.Base(fi.Name())) if withTimestamp { @@ -257,7 +253,7 @@ fileLoop: if err := fld.Open(); err != nil { return fmt.Errorf("open field: name=%s, err=%s", fld.Name(), err) } - i.logger.Debugf("add field to index.fields: %s", fi.Name()) + i.holder.Logger.Debugf("add field to index.fields: %s", fi.Name()) mu.Lock() i.fields[fld.Name()] = fld mu.Unlock() @@ -370,6 +366,12 @@ func (i *Index) AvailableShards() *roaring.Bitmap { return b } +// Begin starts a transaction on a shard of the index. +func (i *Index) Begin(writable bool, shard uint64) (Tx, error) { + // TODO(bbj): Check for underlying storage as RBF or roaring. + return &RoaringTx{Index: i}, nil +} + // fieldPath returns the path to a field in the index. func (i *Index) fieldPath(name string) string { return filepath.Join(i.path, name) } @@ -512,17 +514,13 @@ func (i *Index) createField(name string, opt *FieldOptions) (*Field, error) { } func (i *Index) newField(path, name string) (*Field, error) { - f, err := newField(path, i.name, name, OptFieldTypeDefault()) + f, err := newField(i.holder, path, i.name, name, OptFieldTypeDefault()) if err != nil { return nil, err } - f.logger = i.logger f.Stats = i.Stats f.broadcaster = i.broadcaster f.rowAttrStore = i.newAttrStore(filepath.Join(f.path, ".data")) - if i.snapshotQueue != nil { - f.snapshotQueue = i.snapshotQueue - } f.OpenTranslateStore = i.OpenTranslateStore return f, nil } @@ -617,3 +615,8 @@ type importValueData struct { ColumnIDs []uint64 Values []int64 } + +// FormatQualifiedIndexName generates a qualified name for the index to be used with Tx operations. +func FormatQualifiedIndexName(index string) string { + return fmt.Sprintf("%s\x00", index) +} diff --git a/index_internal_test.go b/index_internal_test.go index 026607da4..5b5a5b5a3 100644 --- a/index_internal_test.go +++ b/index_internal_test.go @@ -25,7 +25,7 @@ func mustOpenIndex(opt IndexOptions) *Index { if err != nil { panic(err) } - index, err := NewIndex(path, "i", DefaultPartitionN) + index, err := NewIndex(NewHolder(1), path, "i") if err != nil { panic(err) } diff --git a/index_test.go b/index_test.go index 63e9b6179..bfebee7f7 100644 --- a/index_test.go +++ b/index_test.go @@ -242,7 +242,7 @@ func TestIndex_InvalidName(t *testing.T) { if err != nil { panic(err) } - index, err := pilosa.NewIndex(path, "ABC", pilosa.DefaultPartitionN) + index, err := pilosa.NewIndex(pilosa.NewHolder(pilosa.DefaultPartitionN), path, "ABC") if err == nil { t.Fatalf("should have gotten an error on index name with caps") } diff --git a/license.exceptions b/license.exceptions index 9f453efc4..ef44dcacc 100644 --- a/license.exceptions +++ b/license.exceptions @@ -4,7 +4,6 @@ ./internal/private.pb.go ./internal/public.pb.go ./lru/lru.go -./enterprise/enterprise.go ./roaring/btree.go ./roaring/btree_test.go ./proto/pilosa.pb.go diff --git a/like.go b/like.go new file mode 100644 index 000000000..d3fbebe54 --- /dev/null +++ b/like.go @@ -0,0 +1,239 @@ +// Copyright 2020 Pilosa Corp. +// +// 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 pilosa + +import ( + "strings" + "unicode/utf8" +) + +// tokenizeLike turns a "like" pattern into a list of tokens. +// Every token is either a string to exactly match or a combination of % and _ placeholders. +func tokenizeLike(like string) []string { + var tokens []string + for like != "" { + var token string + i := strings.IndexAny(like, "%_") + switch i { + case 0: + // Generate a token of placeholders. + + // Iterate bytewise over the string to find the end of the token. + // The % and _ characters are ASCII, so we do not have to worry about Unicode right here. + j := 1 + for j < len(like) && (like[j] == '%' || like[j] == '_') { + j++ + } + token, like = like[:j], like[j:] + case -1: + // There are no more placeholders - generate the last token. + token, like = like, "" + default: + // Generate an exact match token. + token, like = like[:i], like[i:] + } + tokens = append(tokens, token) + } + return tokens +} + +// filterStepKind is a kind of step in a like filter. +type filterStepKind uint8 + +const ( + filterStepPrefix filterStepKind = iota // x... + filterStepSkipN // __... + filterStepSkipThrough // %x... + filterStepSuffix // %x + filterStepMinLength // _% +) + +// filterStep is a step in a like filter. +type filterStep struct { + // kind is the step kind. + kind filterStepKind + + // str is the substring for a prefix/skipthrough/suffix step. + str string + + // n is the number of underscores in the step (if relevant). + n int +} + +// planLike generates a filtering plan for a like pattern. +func planLike(like string) []filterStep { + // Tokenize the like pattern. + tokens := tokenizeLike(like) + + steps := make([]filterStep, 0, len(tokens)) + var merged bool + for i, t := range tokens { + if merged { + // The token was already merged into the previous step. + merged = false + continue + } + + // Convert the token to a step. + var step filterStep + hasPercent := strings.ContainsRune(t, '%') + underscores := strings.Count(t, "_") + switch { + case hasPercent && i+1 < len(tokens): + // Generate a step to skip through the next token. + step = filterStep{ + kind: filterStepSkipThrough, + str: tokens[i+1], + n: underscores, + } + merged = true + case hasPercent: + // Generate a terminating step to absorb the remainder of the string. + step = filterStep{ + kind: filterStepMinLength, + n: underscores, + } + case underscores > 0: + // Generate a step to absorb _ placeholders. + step = filterStep{ + kind: filterStepSkipN, + n: underscores, + } + default: + // Generate a step to process an exact match of the beginning of a string. + step = filterStep{ + kind: filterStepPrefix, + str: t, + } + } + steps = append(steps, step) + } + + // Optimize suffix matching. + if len(steps) > 0 && steps[len(steps)-1].kind == filterStepSkipThrough { + steps[len(steps)-1].kind = filterStepSuffix + } + + return steps +} + +// matchLike matches a string using a like plan. +func matchLike(key string, like ...filterStep) bool { + for i, step := range like { + switch step.kind { + case filterStepPrefix: + // Match a prefix. + if !strings.HasPrefix(key, step.str) { + return false + } + key = key[len(step.str):] + case filterStepSkipN: + // Skip some placeholders. + n := step.n + for j := 0; j < n; j++ { + _, len := utf8.DecodeRuneInString(key) + if len == 0 { + return false + } + key = key[len:] + } + case filterStepSkipThrough: + // Skip through a string. + + // Skip through placeholders. + var skipped int + for skipped < step.n { + j := strings.Index(key, step.str) + switch j { + case -1: + // There are no more matches. + return false + case 0: + // Skip a single rune to ensure forward progress. + // This is somewhat inefficient since we have to search the string again next time. + // This will hopefully not have to be used very frequently. + _, len := utf8.DecodeRuneInString(key) + key = key[len:] + skipped += len + default: + // Skip until the substring and count the skipped runes. + k := -1 + for k = range key[:j] { + } + skipped += k + 1 + + key = key[j:] + } + } + + // Iterate through the substring matches until the rest of the pattern matches. + remaining := like[i+1:] + for { + // Find the next substring match. + j := strings.Index(key, step.str) + switch { + case j == -1: + // There are no more matches. + return false + case j > 0: + // Skip the data before the substring. + key = key[j:] + } + + // Apply the rest of the filter. + if matchLike(key[len(step.str):], remaining...) { + // This instance matches, no need to search any more. + return true + } + + // Skip the first rune of the substring so we do not rescan this substring match. + _, len := utf8.DecodeRuneInString(key) + key = key[len:] + } + case filterStepSuffix: + // Match a suffix. + if !strings.HasSuffix(key, step.str) { + // Suffix not present. + return false + } + if step.n <= 0 { + // No skip length check necessary. + return true + } + + // Check length of the substring before the suffix. + key = key[:len(key)-len(step.str)] + fallthrough + case filterStepMinLength: + if len(key) < step.n { + // The string is definitely too short. + return false + } + + // Count the runes. + j := -1 + for j = range key { + } + + // Check if the string is long enough. + return j+1 >= step.n + default: + panic("invalid step") + } + } + + // If there is any unmatched data left, this is not a match. + return key == "" +} diff --git a/like_test.go b/like_test.go new file mode 100644 index 000000000..1382901ec --- /dev/null +++ b/like_test.go @@ -0,0 +1,248 @@ +// Copyright 2020 Pilosa Corp. +// +// 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 pilosa + +import ( + "reflect" + "testing" +) + +func TestPlanLike(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + like string + plan []filterStep + match, nonmatch []string + }{ + { + name: "Empty", + like: "", + plan: []filterStep{}, + match: []string{""}, + nonmatch: []string{"a", " "}, + }, + { + name: "Exact", + like: "x", + plan: []filterStep{ + { + kind: filterStepPrefix, + str: "x", + }, + }, + match: []string{"x"}, + nonmatch: []string{"", "y", "z", "xy", "yx"}, + }, + { + name: "Anything", + like: "%", + plan: []filterStep{ + { + kind: filterStepMinLength, + n: 0, + }, + }, + match: []string{"", "a", "b", "ab"}, + }, + { + name: "Prefix", + like: "x%", + plan: []filterStep{ + { + kind: filterStepPrefix, + str: "x", + }, + { + kind: filterStepMinLength, + n: 0, + }, + }, + match: []string{"xy", "xyz", "xyzzy"}, + nonmatch: []string{"plugh", "yx", ""}, + }, + { + name: "Suffix", + like: "%x", + plan: []filterStep{ + { + kind: filterStepSuffix, + str: "x", + }, + }, + match: []string{"x", "xx", "ax"}, + nonmatch: []string{"", "a", "x^"}, + }, + { + name: "Sandwich", + like: "x%y", + plan: []filterStep{ + { + kind: filterStepPrefix, + str: "x", + }, + { + kind: filterStepSuffix, + str: "y", + }, + }, + match: []string{"xy", "xzy", "xyzzy"}, + nonmatch: []string{"plugh", ".xy.", ".x.y", "x.y."}, + }, + { + name: "DoubleDeckerSandwich", + like: "x%y%z", + plan: []filterStep{ + { + kind: filterStepPrefix, + str: "x", + }, + { + kind: filterStepSkipThrough, + str: "y", + }, + { + kind: filterStepSuffix, + str: "z", + }, + }, + match: []string{"xyz", "xzyzz", "x.y.z", "x.y.y..z"}, + nonmatch: []string{"plugh", ".xyz.", ".x.y.z", "x.y.z."}, + }, + { + name: "Skips", + like: "a_b_%_c_%_%_d", + plan: []filterStep{ + { + kind: filterStepPrefix, + str: "a", + }, + { + kind: filterStepSkipN, + n: 1, + }, + { + kind: filterStepPrefix, + str: "b", + }, + { + kind: filterStepSkipThrough, + str: "c", + n: 2, + }, + { + kind: filterStepSuffix, + str: "d", + n: 3, + }, + }, + match: []string{"a1b234c5678d"}, + nonmatch: []string{"abcd", "a1b2345678d", "a1b2c5678d"}, + }, + { + name: "SingleRune", + like: "_", + plan: []filterStep{ + { + kind: filterStepSkipN, + n: 1, + }, + }, + match: []string{"a", "á", "☺"}, + nonmatch: []string{"ab", "á", "h̷", ""}, + }, + { + name: "DoubleRune", + like: "__", + plan: []filterStep{ + { + kind: filterStepSkipN, + n: 2, + }, + }, + match: []string{"ab", "á", "h̷"}, + nonmatch: []string{"a", "á", "☺", "abc"}, + }, + { + name: "MiddleBlank", + like: "x_y", + plan: []filterStep{ + { + kind: filterStepPrefix, + str: "x", + }, + { + kind: filterStepSkipN, + n: 1, + }, + { + kind: filterStepPrefix, + str: "y", + }, + }, + match: []string{"x.y", "xay", "x y", "x⊕y"}, + nonmatch: []string{"x++y", "", "a"}, + }, + { + name: "MinLength", + like: "_%_", + plan: []filterStep{ + { + kind: filterStepMinLength, + n: 2, + }, + }, + match: []string{"ab", "á", "abc", "pilosa"}, + nonmatch: []string{"h", "á", ".", "☺"}, + }, + } + t.Run("Plan", func(t *testing.T) { + t.Parallel() + + for _, c := range cases { + c := c + t.Run(c.name, func(t *testing.T) { + t.Parallel() + + plan := planLike(c.like) + if !reflect.DeepEqual(plan, c.plan) { + t.Errorf("incorrect plan: %v", plan) + } + }) + } + }) + t.Run("Match", func(t *testing.T) { + t.Parallel() + + for _, c := range cases { + c := c + t.Run(c.name, func(t *testing.T) { + t.Parallel() + + for _, m := range c.match { + if !matchLike(m, c.plan...) { + t.Errorf("key %q was not matched", m) + } + } + for _, nm := range c.nonmatch { + if matchLike(nm, c.plan...) { + t.Errorf("key %q was matched", nm) + } + } + }) + } + }) +} diff --git a/mmap_test.go b/mmap_test.go index 5ce157bc4..a41830fc5 100644 --- a/mmap_test.go +++ b/mmap_test.go @@ -35,8 +35,10 @@ func forceSnapshotsCheckMapping(t *testing.T) { f.Logger = logger.NewLogfLogger(t) defer f.Clean(t) + tx := &RoaringTx{fragment: f} + for i := 0; i < f.MaxOpN; i++ { - _, _ = f.setBit(0, uint64(i*32)) + _, _ = f.setBit(tx, 0, uint64(32*i)) } // force snapshot so we get a mmapped row... err := f.Snapshot() @@ -67,7 +69,7 @@ func forceSnapshotsCheckMapping(t *testing.T) { if i%5 == 0 { runtime.GC() } - err := f.importValue(cv.cols, cv.vals, depth, (i%3 == 1)) + err := f.importValue(tx, cv.cols, cv.vals, depth, (i%3 == 1)) if err != nil { t.Fatalf("importValue[%d]: %v", i, err) } diff --git a/pilosa b/pilosa new file mode 100755 index 000000000..1aca8c909 Binary files /dev/null and b/pilosa differ diff --git a/pilosa.go b/pilosa.go index 53733d9ce..f7eb33f43 100644 --- a/pilosa.go +++ b/pilosa.go @@ -33,9 +33,10 @@ var ( ErrForeignIndexNotFound = errors.New("foreign index not found") // ErrFieldRequired is returned when no field is specified. - ErrFieldRequired = errors.New("field required") - ErrFieldExists = errors.New("field already exists") - ErrFieldNotFound = errors.New("field not found") + ErrFieldRequired = errors.New("field required") + ErrColumnRequired = errors.New("column required") + ErrFieldExists = errors.New("field already exists") + ErrFieldNotFound = errors.New("field not found") ErrBSIGroupNotFound = errors.New("bsigroup not found") ErrBSIGroupExists = errors.New("bsigroup already exists") @@ -52,8 +53,7 @@ var ( ErrInvalidView = errors.New("invalid view") ErrInvalidCacheType = errors.New("invalid cache type") - ErrName = errors.New("invalid index or field name, must match [a-z][a-z0-9_-]* and contain at most 230 characters") - ErrLabel = errors.New("invalid row or column label, must match [A-Za-z0-9_-]") + ErrName = errors.New("invalid index or field name, must match [a-z][a-z0-9_-]* and contain at most 230 characters") // ErrFragmentNotFound is returned when a fragment does not exist. ErrFragmentNotFound = errors.New("fragment not found") diff --git a/pql/ast.go b/pql/ast.go index e93a2aaf5..9d65bb3c5 100644 --- a/pql/ast.go +++ b/pql/ast.go @@ -384,6 +384,7 @@ var callInfoByFunc = map[string]callInfo{ "previous": nil, "from": nil, "to": nil, + "like": "", }, }, "Shift": {allowUnknown: false, @@ -391,8 +392,9 @@ var callInfoByFunc = map[string]callInfo{ "n": int64(0), }, }, - "Union": {allowUnknown: false}, - "Xor": {allowUnknown: false}, + "Union": {allowUnknown: false}, + "UnionRows": {allowUnknown: false}, + "Xor": {allowUnknown: false}, // things that take _field "TopN": allowUnderField, @@ -662,6 +664,19 @@ func (c *Call) UintSliceArg(key string) ([]uint64, bool, error) { } } +func (c *Call) StringArg(key string) (string, bool, error) { + val, ok := c.Args[key] + if !ok { + return "", false, nil + } + switch tval := val.(type) { + case string: + return tval, true, nil + default: + return "", true, fmt.Errorf("unexpected type %T in StringArg, val %v", tval, tval) + } +} + // CallArg is for reading the value at key from call.Args as a Call. If the // key is not in Call.Args, the value of the returned value will be nil, and // the error will be nil. An error is returned if the value is not a Call. diff --git a/proto/pilosa.pb.go b/proto/pilosa.pb.go index c04b9805e..ee0b349e9 100644 --- a/proto/pilosa.pb.go +++ b/proto/pilosa.pb.go @@ -8,8 +8,6 @@ import ( fmt "fmt" proto "github.com/golang/protobuf/proto" grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" math "math" ) @@ -552,6 +550,7 @@ type InspectRequest struct { FilterFields []string `protobuf:"bytes,3,rep,name=filterFields,proto3" json:"filterFields,omitempty"` Limit uint64 `protobuf:"varint,4,opt,name=limit,proto3" json:"limit,omitempty"` Offset uint64 `protobuf:"varint,5,opt,name=offset,proto3" json:"offset,omitempty"` + Query string `protobuf:"bytes,6,opt,name=query,proto3" json:"query,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` @@ -617,6 +616,13 @@ func (m *InspectRequest) GetOffset() uint64 { return 0 } +func (m *InspectRequest) GetQuery() string { + if m != nil { + return m.Query + } + return "" +} + type Uint64Array struct { Vals []uint64 `protobuf:"varint,1,rep,packed,name=vals,proto3" json:"vals,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` @@ -793,59 +799,60 @@ func init() { func init() { proto.RegisterFile("pilosa.proto", fileDescriptor_ef0691a44d1e275c) } var fileDescriptor_ef0691a44d1e275c = []byte{ - // 677 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x55, 0xed, 0x6e, 0xd3, 0x3c, - 0x14, 0xae, 0x97, 0xac, 0x6d, 0x4e, 0xf6, 0xf1, 0xbe, 0xde, 0xfb, 0x8e, 0x68, 0x42, 0x10, 0xf2, - 0x87, 0x20, 0xd0, 0x34, 0x06, 0x03, 0x01, 0xe3, 0xc7, 0x36, 0x40, 0x9d, 0x00, 0xb1, 0x19, 0xb6, - 0xff, 0x6e, 0xe3, 0x8e, 0x08, 0x37, 0xee, 0xe2, 0x74, 0xa3, 0x37, 0xc0, 0x1d, 0x70, 0x07, 0x70, - 0x29, 0xdc, 0x17, 0xb2, 0x1d, 0xa7, 0xc9, 0xa4, 0x22, 0xb4, 0x7f, 0x3e, 0xe7, 0x79, 0xce, 0x57, - 0x1e, 0x1f, 0x07, 0x96, 0xc6, 0x29, 0x17, 0x92, 0x6e, 0x8e, 0x73, 0x51, 0x08, 0xdc, 0x36, 0x56, - 0xf4, 0x0c, 0x56, 0x8f, 0x27, 0x2c, 0x9f, 0x1e, 0x1d, 0xbf, 0x23, 0xec, 0x7c, 0xc2, 0x64, 0x81, - 0xff, 0x83, 0xc5, 0x34, 0x4b, 0xd8, 0xd7, 0x00, 0x85, 0x28, 0xf6, 0x88, 0x31, 0xf0, 0x3f, 0xe0, - 0x8c, 0xcf, 0x79, 0xb0, 0xa0, 0x7d, 0xea, 0x18, 0xbd, 0x00, 0xff, 0x63, 0x41, 0x8b, 0x89, 0x7c, - 0x9d, 0xe7, 0x22, 0xc7, 0x18, 0xdc, 0x03, 0x91, 0x30, 0x1d, 0xb5, 0x4c, 0xf4, 0x19, 0x07, 0xd0, - 0x79, 0xcf, 0xa4, 0xa4, 0x67, 0xac, 0x0c, 0xb4, 0x66, 0xf4, 0x03, 0x81, 0x4f, 0xc4, 0x25, 0x61, - 0x72, 0x2c, 0x32, 0xc9, 0xf0, 0x03, 0xe8, 0x7c, 0x66, 0x34, 0x61, 0xb9, 0x0c, 0x50, 0xe8, 0xc4, - 0xfe, 0x36, 0xde, 0x2c, 0xfb, 0x3d, 0x10, 0x7c, 0x32, 0xca, 0x0e, 0xb3, 0xa1, 0x20, 0x96, 0x82, - 0xb7, 0xa0, 0x33, 0xd0, 0x6e, 0x19, 0x2c, 0x68, 0xf6, 0x7a, 0x93, 0x6d, 0xd3, 0x12, 0x4b, 0xc3, - 0x3b, 0x8d, 0x66, 0x03, 0x27, 0x44, 0xb1, 0xbf, 0xbd, 0x66, 0xa3, 0x6a, 0x10, 0xa9, 0xf3, 0xa2, - 0xa7, 0xe0, 0x10, 0x71, 0x59, 0xaf, 0x87, 0xfe, 0xaa, 0x5e, 0xf4, 0x1d, 0xc1, 0xf2, 0x27, 0xda, - 0xe7, 0xec, 0x9a, 0x13, 0xde, 0x06, 0x37, 0x17, 0x97, 0x76, 0x3c, 0xdf, 0x52, 0xd5, 0x27, 0xd3, - 0xc0, 0x75, 0x07, 0xda, 0x05, 0x98, 0x95, 0x53, 0x9a, 0x65, 0x74, 0xc4, 0x4a, 0xa5, 0xf5, 0x19, - 0x6f, 0x40, 0x37, 0xa1, 0x05, 0x2d, 0xa6, 0x63, 0x2b, 0x5a, 0x65, 0x47, 0xdf, 0x1c, 0x58, 0x69, - 0x4e, 0x8c, 0x6f, 0x81, 0x27, 0x8b, 0x3c, 0xcd, 0xce, 0x4e, 0x29, 0x37, 0x79, 0x7a, 0x2d, 0x32, - 0x73, 0x29, 0x7c, 0x92, 0x66, 0xc5, 0x93, 0xc7, 0x0a, 0x57, 0xf9, 0x5c, 0x85, 0x57, 0x2e, 0x7c, - 0x13, 0xba, 0x15, 0xac, 0x86, 0x70, 0x7a, 0x2d, 0x52, 0x79, 0xf0, 0x06, 0x74, 0xfa, 0x42, 0x70, - 0x05, 0xba, 0x21, 0x8a, 0xbb, 0xbd, 0x16, 0xb1, 0x0e, 0x8d, 0x71, 0xd1, 0x57, 0xd8, 0x62, 0x88, - 0xe2, 0x25, 0x8d, 0x19, 0x07, 0x7e, 0x09, 0x2b, 0xa6, 0xc4, 0x5e, 0x9e, 0xd3, 0xa9, 0xa2, 0xb4, - 0x9b, 0x1f, 0xe8, 0x64, 0x86, 0xf6, 0x5a, 0xe4, 0x0a, 0x59, 0x85, 0x9b, 0x09, 0xaa, 0xf0, 0xce, - 0xd5, 0xef, 0x5b, 0xa1, 0x2a, 0xbc, 0x49, 0xc6, 0x21, 0xc0, 0x90, 0x0b, 0x5a, 0x4e, 0xd5, 0x0d, - 0x51, 0x8c, 0x7a, 0x2d, 0x52, 0xf3, 0xe1, 0x87, 0x00, 0x09, 0x1b, 0xa4, 0x23, 0xaa, 0x47, 0xf3, - 0x74, 0xf2, 0x55, 0x9b, 0xfc, 0x95, 0x41, 0x54, 0xc8, 0x8c, 0xb4, 0xef, 0x83, 0x67, 0x2e, 0xd7, - 0x29, 0xe5, 0xd1, 0x0e, 0x74, 0x4a, 0x96, 0x5a, 0xd7, 0x0b, 0xca, 0x27, 0x46, 0x44, 0x87, 0x18, - 0x43, 0x79, 0xe5, 0x80, 0x72, 0x23, 0xa1, 0x43, 0x8c, 0x11, 0xfd, 0x44, 0xb0, 0x72, 0x98, 0xc9, - 0x31, 0x1b, 0x14, 0x7f, 0xde, 0xf6, 0xfb, 0xf5, 0x05, 0x53, 0xcd, 0xfd, 0x6b, 0x9b, 0x3b, 0x4c, - 0xe4, 0x87, 0xfc, 0x2d, 0x9b, 0xca, 0xd9, 0x6e, 0x45, 0xb0, 0x34, 0x4c, 0x79, 0xc1, 0xf2, 0x37, - 0x29, 0xe3, 0x89, 0x0c, 0x9c, 0xd0, 0x89, 0x3d, 0xd2, 0xf0, 0xa9, 0x32, 0x3c, 0x1d, 0xa5, 0x85, - 0x96, 0xd1, 0x25, 0xc6, 0xc0, 0xeb, 0xd0, 0x16, 0xc3, 0xa1, 0x64, 0x85, 0x56, 0xd0, 0x25, 0xa5, - 0x15, 0xdd, 0x01, 0xbf, 0x26, 0x90, 0xba, 0xa6, 0x17, 0x94, 0x9b, 0xbd, 0x71, 0x89, 0x3e, 0x2b, - 0x4a, 0x4d, 0x84, 0x06, 0xc5, 0x2b, 0x29, 0x67, 0xe0, 0x55, 0xdd, 0xe2, 0xbb, 0xe0, 0xa4, 0x89, - 0xd4, 0x53, 0xce, 0xbd, 0x06, 0x8a, 0x81, 0xef, 0x81, 0xfb, 0x85, 0x4d, 0xed, 0xdc, 0x73, 0x14, - 0xd7, 0x94, 0xfd, 0x36, 0xb8, 0x6a, 0x2d, 0xb6, 0x7f, 0x21, 0x68, 0x1f, 0x69, 0x1a, 0xde, 0x85, - 0xae, 0x7d, 0x4f, 0xf1, 0x0d, 0x1b, 0x7b, 0xe5, 0x85, 0xdd, 0x58, 0xab, 0xaf, 0x73, 0xb9, 0x48, - 0x51, 0x6b, 0x0b, 0xe1, 0x3d, 0x58, 0xb6, 0xdc, 0x93, 0x8c, 0xe6, 0xd3, 0xf9, 0x29, 0xfe, 0xb7, - 0x40, 0xe3, 0x91, 0x89, 0x5a, 0xf8, 0x39, 0x74, 0x4a, 0x85, 0x71, 0xf5, 0x48, 0x35, 0x25, 0x9f, - 0x5b, 0xbe, 0xdf, 0xd6, 0xff, 0x86, 0x47, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0xce, 0xa2, 0x01, - 0xb8, 0x2b, 0x06, 0x00, 0x00, + // 690 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x55, 0xdd, 0x6e, 0xd4, 0x3a, + 0x10, 0x5e, 0x37, 0xe9, 0xee, 0x66, 0xd2, 0x9f, 0x73, 0xdc, 0x73, 0x4a, 0x54, 0x21, 0x08, 0xb9, + 0x21, 0x08, 0x54, 0x95, 0x42, 0x41, 0x40, 0xb9, 0x68, 0x0b, 0x68, 0x2b, 0x40, 0xb4, 0x86, 0xf6, + 0xde, 0xbb, 0xf1, 0x96, 0x08, 0x6f, 0xbc, 0x8d, 0xb3, 0x2d, 0xfb, 0x02, 0xbc, 0x01, 0x6f, 0xc0, + 0x5b, 0x70, 0xcd, 0x7b, 0x21, 0xdb, 0x71, 0x36, 0xa9, 0xb4, 0x08, 0xf5, 0x2e, 0x33, 0xdf, 0x37, + 0x33, 0x1e, 0x7f, 0x9e, 0x09, 0x2c, 0x8d, 0x53, 0x2e, 0x24, 0xdd, 0x1c, 0xe7, 0xa2, 0x10, 0xb8, + 0x6d, 0xac, 0xe8, 0x19, 0xac, 0x1e, 0x4f, 0x58, 0x3e, 0x3d, 0x3a, 0x7e, 0x47, 0xd8, 0xf9, 0x84, + 0xc9, 0x02, 0xff, 0x07, 0x8b, 0x69, 0x96, 0xb0, 0xaf, 0x01, 0x0a, 0x51, 0xec, 0x11, 0x63, 0xe0, + 0x7f, 0xc0, 0x19, 0x9f, 0xf3, 0x60, 0x41, 0xfb, 0xd4, 0x67, 0xf4, 0x02, 0xfc, 0x8f, 0x05, 0x2d, + 0x26, 0xf2, 0x75, 0x9e, 0x8b, 0x1c, 0x63, 0x70, 0x0f, 0x44, 0xc2, 0x74, 0xd4, 0x32, 0xd1, 0xdf, + 0x38, 0x80, 0xce, 0x7b, 0x26, 0x25, 0x3d, 0x63, 0x65, 0xa0, 0x35, 0xa3, 0x1f, 0x08, 0x7c, 0x22, + 0x2e, 0x09, 0x93, 0x63, 0x91, 0x49, 0x86, 0x1f, 0x40, 0xe7, 0x33, 0xa3, 0x09, 0xcb, 0x65, 0x80, + 0x42, 0x27, 0xf6, 0xb7, 0xf1, 0x66, 0x79, 0xde, 0x03, 0xc1, 0x27, 0xa3, 0xec, 0x30, 0x1b, 0x0a, + 0x62, 0x29, 0x78, 0x0b, 0x3a, 0x03, 0xed, 0x96, 0xc1, 0x82, 0x66, 0xaf, 0x37, 0xd9, 0x36, 0x2d, + 0xb1, 0x34, 0xbc, 0xd3, 0x38, 0x6c, 0xe0, 0x84, 0x28, 0xf6, 0xb7, 0xd7, 0x6c, 0x54, 0x0d, 0x22, + 0x75, 0x5e, 0xf4, 0x14, 0x1c, 0x22, 0x2e, 0xeb, 0xf5, 0xd0, 0x5f, 0xd5, 0x8b, 0xbe, 0x23, 0x58, + 0xfe, 0x44, 0xfb, 0x9c, 0x5d, 0xb3, 0xc3, 0xdb, 0xe0, 0xe6, 0xe2, 0xd2, 0xb6, 0xe7, 0x5b, 0xaa, + 0xba, 0x32, 0x0d, 0x5c, 0xb7, 0xa1, 0x5d, 0x80, 0x59, 0x39, 0xa5, 0x59, 0x46, 0x47, 0xac, 0x54, + 0x5a, 0x7f, 0xe3, 0x0d, 0xe8, 0x26, 0xb4, 0xa0, 0xc5, 0x74, 0x6c, 0x45, 0xab, 0xec, 0xe8, 0x9b, + 0x03, 0x2b, 0xcd, 0x8e, 0xf1, 0x2d, 0xf0, 0x64, 0x91, 0xa7, 0xd9, 0xd9, 0x29, 0xe5, 0x26, 0x4f, + 0xaf, 0x45, 0x66, 0x2e, 0x85, 0x4f, 0xd2, 0xac, 0x78, 0xf2, 0x58, 0xe1, 0x2a, 0x9f, 0xab, 0xf0, + 0xca, 0x85, 0x6f, 0x42, 0xb7, 0x82, 0x55, 0x13, 0x4e, 0xaf, 0x45, 0x2a, 0x0f, 0xde, 0x80, 0x4e, + 0x5f, 0x08, 0xae, 0x40, 0x37, 0x44, 0x71, 0xb7, 0xd7, 0x22, 0xd6, 0xa1, 0x31, 0x2e, 0xfa, 0x0a, + 0x5b, 0x0c, 0x51, 0xbc, 0xa4, 0x31, 0xe3, 0xc0, 0x2f, 0x61, 0xc5, 0x94, 0xd8, 0xcb, 0x73, 0x3a, + 0x55, 0x94, 0x76, 0xf3, 0x82, 0x4e, 0x66, 0x68, 0xaf, 0x45, 0xae, 0x90, 0x55, 0xb8, 0xe9, 0xa0, + 0x0a, 0xef, 0x5c, 0xbd, 0xdf, 0x0a, 0x55, 0xe1, 0x4d, 0x32, 0x0e, 0x01, 0x86, 0x5c, 0xd0, 0xb2, + 0xab, 0x6e, 0x88, 0x62, 0xd4, 0x6b, 0x91, 0x9a, 0x0f, 0x3f, 0x04, 0x48, 0xd8, 0x20, 0x1d, 0x51, + 0xdd, 0x9a, 0xa7, 0x93, 0xaf, 0xda, 0xe4, 0xaf, 0x0c, 0xa2, 0x42, 0x66, 0xa4, 0x7d, 0x1f, 0x3c, + 0xf3, 0xb8, 0x4e, 0x29, 0x8f, 0x76, 0xa0, 0x53, 0xb2, 0xd4, 0xb8, 0x5e, 0x50, 0x3e, 0x31, 0x22, + 0x3a, 0xc4, 0x18, 0xca, 0x2b, 0x07, 0x94, 0x1b, 0x09, 0x1d, 0x62, 0x8c, 0xe8, 0x27, 0x82, 0x95, + 0xc3, 0x4c, 0x8e, 0xd9, 0xa0, 0xf8, 0xf3, 0xb4, 0xdf, 0xaf, 0x0f, 0x98, 0x3a, 0xdc, 0xbf, 0xf6, + 0x70, 0x87, 0x89, 0xfc, 0x90, 0xbf, 0x65, 0x53, 0x39, 0x9b, 0xad, 0x08, 0x96, 0x86, 0x29, 0x2f, + 0x58, 0xfe, 0x26, 0x65, 0x3c, 0x91, 0x81, 0x13, 0x3a, 0xb1, 0x47, 0x1a, 0x3e, 0x55, 0x86, 0xa7, + 0xa3, 0xb4, 0xd0, 0x32, 0xba, 0xc4, 0x18, 0x78, 0x1d, 0xda, 0x62, 0x38, 0x94, 0xac, 0xd0, 0x0a, + 0xba, 0xa4, 0xb4, 0x14, 0xfb, 0x5c, 0x6d, 0x25, 0xad, 0x9a, 0x47, 0x8c, 0x11, 0xdd, 0x01, 0xbf, + 0x26, 0x9b, 0x7a, 0xbc, 0x17, 0x94, 0x9b, 0x69, 0x72, 0x89, 0xfe, 0x56, 0x94, 0x9a, 0x34, 0x0d, + 0x8a, 0x57, 0x52, 0xce, 0xc0, 0xab, 0x7a, 0xc0, 0x77, 0xc1, 0x49, 0x13, 0xa9, 0x7b, 0x9f, 0xfb, + 0x38, 0x14, 0x03, 0xdf, 0x03, 0xf7, 0x0b, 0x9b, 0xda, 0xdb, 0x98, 0xf3, 0x0e, 0x34, 0x65, 0xbf, + 0x0d, 0xae, 0x1a, 0x96, 0xed, 0x5f, 0x08, 0xda, 0x47, 0x9a, 0x86, 0x77, 0xa1, 0x6b, 0xb7, 0x2c, + 0xbe, 0x61, 0x63, 0xaf, 0xec, 0xdd, 0x8d, 0xb5, 0xfa, 0x90, 0x97, 0xe3, 0x15, 0xb5, 0xb6, 0x10, + 0xde, 0x83, 0x65, 0xcb, 0x3d, 0xc9, 0x68, 0x3e, 0x9d, 0x9f, 0xe2, 0x7f, 0x0b, 0x34, 0x56, 0x4f, + 0xd4, 0xc2, 0xcf, 0xa1, 0x53, 0xea, 0x8e, 0xab, 0xd5, 0xd5, 0x7c, 0x08, 0x73, 0xcb, 0xf7, 0xdb, + 0xfa, 0x8f, 0xf1, 0xe8, 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0xc5, 0x01, 0x62, 0x15, 0x41, 0x06, + 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context -var _ grpc.ClientConnInterface +var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion6 +const _ = grpc.SupportPackageIsVersion4 // PilosaClient is the client API for Pilosa service. // @@ -857,10 +864,10 @@ type PilosaClient interface { } type pilosaClient struct { - cc grpc.ClientConnInterface + cc *grpc.ClientConn } -func NewPilosaClient(cc grpc.ClientConnInterface) PilosaClient { +func NewPilosaClient(cc *grpc.ClientConn) PilosaClient { return &pilosaClient{cc} } @@ -944,20 +951,6 @@ type PilosaServer interface { Inspect(*InspectRequest, Pilosa_InspectServer) error } -// UnimplementedPilosaServer can be embedded to have forward compatible implementations. -type UnimplementedPilosaServer struct { -} - -func (*UnimplementedPilosaServer) QueryPQL(req *QueryPQLRequest, srv Pilosa_QueryPQLServer) error { - return status.Errorf(codes.Unimplemented, "method QueryPQL not implemented") -} -func (*UnimplementedPilosaServer) QueryPQLUnary(ctx context.Context, req *QueryPQLRequest) (*TableResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryPQLUnary not implemented") -} -func (*UnimplementedPilosaServer) Inspect(req *InspectRequest, srv Pilosa_InspectServer) error { - return status.Errorf(codes.Unimplemented, "method Inspect not implemented") -} - func RegisterPilosaServer(s *grpc.Server, srv PilosaServer) { s.RegisterService(&_Pilosa_serviceDesc, srv) } diff --git a/proto/pilosa.proto b/proto/pilosa.proto index ff25a5fb9..524c247be 100644 --- a/proto/pilosa.proto +++ b/proto/pilosa.proto @@ -57,6 +57,7 @@ message InspectRequest { repeated string filterFields = 3; uint64 limit = 4; uint64 offset = 5; + string query = 6; } message Uint64Array { diff --git a/rbf/README.md b/rbf/README.md new file mode 100644 index 000000000..77251457a --- /dev/null +++ b/rbf/README.md @@ -0,0 +1,110 @@ +Roaring B-tree Format +===================== + +The RBF format represents a Roaring bitmap whose containers are stored in the +leafs of a b-tree. This allows the bitmap to be efficiently queried & updated. + + +## File Format + +The RBF file is divided into equal 8KB pages. Each page after the meta page +is numbered incrementally from 1 to 1^31. + +Pages can be one of the following types: + +- Meta page: contains header information. +- Branch page: contains pointers to lower branch & leaf pages. +- Leaf page: contains array and RLE container data. +- Bitmap page: contains bitmap container data. + +All integer values are little endian encoded. + + +## Page header + +Every page type except the bitmap page contains the following header: + + +### Meta page + +The meta page contains the following header: + + [4] magic (\xFFRBF) + [4] flags + [4] page count + [8] wal ID + [4] root records pgno + [4] freelist pgno + + +### Root Records page + +A list of all b-tree names & their respective root page numbers are stored in +root record pages. Once a bitmap root is created, it is never moved so the +root record pages only need to be rewritten when creating, renaming, or deleting +a b-tree. If records exceed the size of a page then they are overflowed to +additional pages. + + [4] page number + [4] flags + [4] overflow pgno + [*] bitmap records + +Each bitmap record is represented as: + + [4] pgno + [2] name size + [*] name + +All bitmap records are loaded into memory when the file is opened. + + +### Branch page + +The branch page contains the following header: + + [4] page number + [4] flags + [2] cell count + [*] cell index (2 * cell count) + [*] padding for 4-byte alignment + +Each cell is formatted as: + + [8] highbits + [4] flags + [4] page number + + +### Leaf page + +The leaf page contains the following header: + + [4] page number + [4] flags + [2] cell count + [*] cell index (2 * cell count) + + +The leaf page contains a series of cells with the header of: + + [8] highbits + [4] flag + [4] child count + [*] array or RLE data + + +### Bitmap page + +The data for the bitmap page takes up the entire 8KB. + + +## Proof of Concept Notes + +The following are notes made that are temporary for the RBF format. This will +change as development progresses: + +- Transaction support is deferred +- WAL support is deferred + + diff --git a/rbf/array.go b/rbf/array.go new file mode 100644 index 000000000..a7753db90 --- /dev/null +++ b/rbf/array.go @@ -0,0 +1,69 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf + +import ( + "unsafe" + + "github.com/pilosa/pilosa/v2/roaring" +) + +// toArray16 converts a byte slice into a slice of uint16 values using unsafe. +func toArray16(a []byte) []uint16 { + return (*[4096]uint16)(unsafe.Pointer(&a[0]))[: len(a)/2 : len(a)/2] +} + +// fromArray16 converts a slice of uint16 values into a byte slice using unsafe. +func fromArray16(a []uint16) []byte { + return (*[8192]byte)(unsafe.Pointer(&a[0]))[: len(a)*2 : len(a)*2] +} + +// arrayIndex returns the insertion index of v in a. Returns true if exact match. +func arrayIndex(a []uint16, v uint16) (int, bool) { + return search(len(a), func(i int) int { + if a[i] == v { + return 0 + } else if v < a[i] { + return -1 + } + return 1 + }) +} + +// toArray64 converts a byte slice into a slice of uint64 values using unsafe. +func toArray64(a []byte) []uint64 { + return (*[1024]uint64)(unsafe.Pointer(&a[0]))[:1024:1024] +} + +// fromArray64 converts a slice of uint64 values into a byte slice using unsafe. +func fromArray64(a []uint64) []byte { + return (*[8192]byte)(unsafe.Pointer(&a[0]))[:8192:8192] +} + +func cloneArray64(a []uint64) []uint64 { + other := make([]uint64, len(a)) + copy(other, a) + return other +} + +// toArray16 converts a byte slice into a slice of uint16 values using unsafe. +func toInterval16(a []byte) []roaring.Interval16 { + return (*[2048]roaring.Interval16)(unsafe.Pointer(&a[0]))[: len(a)/4 : len(a)/4] +} + +// fromArray16 converts a slice of uint16 values into a byte slice using unsafe. +func fromInterval16(a []roaring.Interval16) []byte { + return (*[8192]byte)(unsafe.Pointer(&a[0]))[: len(a)*4 : len(a)*4] +} diff --git a/rbf/cursor.go b/rbf/cursor.go new file mode 100644 index 000000000..8d2479164 --- /dev/null +++ b/rbf/cursor.go @@ -0,0 +1,1178 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf + +import ( + "fmt" + "io" + "math/bits" + "sort" + "unsafe" + + "github.com/pilosa/pilosa/v2/roaring" +) + +const ( + bitmapN = (1 << 16) / 64 +) + +type Cursor struct { + tx *Tx + buffered bool + + // buffers + leafPage []byte + array [ArrayMaxSize + 1]uint16 + rle [RLEMaxSize + 1]roaring.Interval16 + leafCells [PageSize / 8]leafCell + + stack struct { + index int + elems [32]stackElem + } +} + +func runAdd(runs []roaring.Interval16, v uint16) ([]roaring.Interval16, bool) { + i := sort.Search(len(runs), + func(i int) bool { return runs[i].Last >= v }) + + if i == len(runs) { + i-- + } + + iv := runs[i] + if v >= iv.Start && iv.Last >= v { + return nil, false + } + + if iv.Last < v { + if iv.Last == v-1 { + runs[i].Last++ + } else { + runs = append(runs, roaring.Interval16{Start: v, Last: v}) + } + } else if v+1 == iv.Start { + // combining two intervals + if i > 0 && runs[i-1].Last == v-1 { + runs[i-1].Last = iv.Last + runs = append(runs[:i], runs[i+1:]...) + //TODO check if to big + return runs, true + } + // just before an interval + runs[i].Start-- + } else if i > 0 && v-1 == runs[i-1].Last { + // just after an interval + runs[i-1].Last++ + } else { + // alone + newIv := roaring.Interval16{Start: v, Last: v} + runs = append(runs[:i], append([]roaring.Interval16{newIv}, runs[i:]...)...) + } + return runs, true +} +func checkRun(runs []roaring.Interval16, key uint64) leafCell { + if len(runs) >= RLEMaxSize { + //convertToBitmap + bitmap := make([]uint64, bitmapN) + for _, iv := range runs { + w1, w2 := iv.Start/64, iv.Last/64 + b1, b2 := iv.Start&63, iv.Last&63 + // a mask for everything under bit X looks like + // (1 << x) - 1. Say b1 is 4; our mask will want + // to have the bottom 4 bits be zero, so we shift + // left 4, getting 10000, then subtract 1, and + // get 01111, which is the mask to *remove*. + m1 := (uint64(1) << b1) - 1 + // inclusive mask: same thing, then shift left 1 and + // or in 1. So for 4, we'd get 011111, which is the + // mask to *keep*. + m2 := (((uint64(1) << b2) - 1) << 1) | 1 + if w1 == w2 { + // If we only had bit 4 in the range, this would + // end up being 011111 &^ 01111, or 010000. + bitmap[w1] |= (m2 &^ m1) + continue + } + // for w2, the "To" field, we want to set the bottom N + // bits. For w1, the "From" word, we want to set all *but* + // the bottom N bits. + bitmap[w2] |= m2 + bitmap[w1] |= ^m1 + words := bitmap[w1+1 : w2] + // set every bit between them + for i := range words { + words[i] = ^uint64(0) + } + } + n := uint64(0) + for _, v := range bitmap { + n += popcount(v) + } + + return leafCell{Key: key, N: int(n), Type: ContainerTypeBitmap, Data: fromArray64(bitmap)} + } + return leafCell{Key: key, N: len(runs), Type: ContainerTypeRLE, Data: fromInterval16(runs)} +} + +// Add sets a bit on the underlying bitmap. +func (c *Cursor) Add(v uint64) (changed bool, err error) { + hi, lo := highbits(v), lowbits(v) + // Move cursor to the key of the container. + // Insert new container if it doesn't exist. + if exact, err := c.Seek(hi); err != nil { + return false, err + } else if !exact { + return true, c.putLeafCell(leafCell{Key: hi, Type: ContainerTypeArray, N: 1, Data: fromArray16([]uint16{lo})}) + } + + // If the container exists and bit is not set then update the page. + cell := c.cell() + switch cell.Type { + case ContainerTypeArray: + // Exit if value exists in array container. + a := toArray16(cell.Data) + i, ok := arrayIndex(a, lo) + if ok { + return false, nil + } + + // Copy container data and insert new value. + other := c.array[:len(a)+1] + copy(other, a[:i]) + other[i] = lo + copy(other[i+1:], a[i:]) + return true, c.putLeafCell(leafCell{Key: cell.Key, Type: ContainerTypeArray, N: len(other), Data: fromArray16(other)}) + + case ContainerTypeRLE: + runs := toInterval16(cell.Data) + //TODO Look at this again with fresh eyes + copy(c.rle[:], runs) + run, added := runAdd(c.rle[:len(runs)], lo) + if added { + leaf := checkRun(run, cell.Key) + return true, c.putLeafCell(leaf) + } + return false, nil + case ContainerTypeBitmap: + // Exit if bit set in bitmap container. + a := cloneArray64(toArray64(cell.Data)) + if a[lo/64]&(1<= lo })) + if i < int32(len(a)) { + return (lo >= a[i].Start) && (lo <= a[i].Last), nil + } + return false, nil + case ContainerTypeBitmap: + a := toArray64(cell.Data) + return a[lo/64]&(1<= len(cells) || c.Key() != cell.Key { + cells = append(cells, leafCell{}) + copy(cells[elem.index+1:], cells[elem.index:]) + } + cells[elem.index] = cell + + // Split into multiple pages if page size is exceeded. + groups := [][]leafCell{cells} + if leafCellsPageSize(cells) >= PageSize { + groups = splitLeafCells(cells) + } + // Write each group to a separate page. + var hasBitmap bool + + for _, group := range groups { + if len(group) == 1 && (group[0].Type == ContainerTypeBitmap || group[0].N > ArrayMaxSize) && (group[0].Type != ContainerTypeRLE) { + hasBitmap = true + } + } + + var parents []branchCell + origPgno := elem.pgno + + newRoot := (len(groups) > 1 || hasBitmap) && c.stack.index == 0 + for i, group := range groups { + // First page should overwrite the original. + // Subsequent pages should allocate new pages. + parent := branchCell{Key: group[0].Key} + if i == 0 && !newRoot { + parent.Pgno = origPgno + } else { + if parent.Pgno, err = c.tx.allocate(); err != nil { + return fmt.Errorf("cannot allocate leaf: %w", err) + } + } + + // If cell exceeds threshold then write out bitmap page. + // Otherwise encode leaf page normally. + var buf [PageSize]byte + if len(group) == 1 && (group[0].Type == ContainerTypeBitmap || group[0].N > ArrayMaxSize) && (group[0].Type != ContainerTypeRLE) { + + hasBitmap = true + parent.Flags |= ContainerTypeBitmap + copy(buf[:], fromArray64(cell.Bitmap())) + + if err := c.tx.writeBitmapPage(parent.Pgno, buf[:]); err != nil { + return err + } + } else { + // Write cells to page. + writePageNo(buf[:], parent.Pgno) + writeFlags(buf[:], PageTypeLeaf) + writeCellN(buf[:], len(group)) + + offset := dataOffset(len(group)) + for j, cell := range group { + writeLeafCell(buf[:], j, offset, cell) + offset += align8(cell.Size()) + } + + if err := c.tx.writePage(buf[:]); err != nil { + return err + } + } + + parents = append(parents, parent) + } + + // TODO(BBJ): Update page in buffer & cursor stack. + + // If this is not a split and we have no bitmap containers, then exit now. + // Bitmap containers require a parent and the parent's flag must be set. + if len(groups) == 1 && !hasBitmap { + return nil + } + + // Initialize a new root if we are currently the root page. + if c.stack.index == 0 { + assert(newRoot) + return c.writeRoot(origPgno, parents) + } + assert(!newRoot) + + // Otherwise update existing parent. + return c.putBranchCells(c.stack.index-1, parents) +} + +// deleteLeafCell removes a cell from the currently positioned page & index. +func (c *Cursor) deleteLeafCell(key uint64) (err error) { + elem := &c.stack.elems[c.stack.index] + cells := readLeafCells(c.leafPage, elem.isBitmap, c.leafCells[:]) + oldPageKey := cells[0].Key + + // If no more cells exist and we have a parent, remove from parent. + if c.stack.index > 0 && len(cells) == 1 { + if err := c.tx.deallocate(elem.pgno); err != nil { + return err + } + return c.deleteBranchCell(c.stack.index-1, cells[0].Key) + } + + // Remove matching cell from list. + copy(cells[elem.index:], cells[elem.index+1:]) + cells[len(cells)-1] = leafCell{} + cells = cells[:len(cells)-1] + + // Write cells to page. + buf := make([]byte, PageSize) + writePageNo(buf[:], elem.pgno) + writeFlags(buf[:], PageTypeLeaf) + writeCellN(buf[:], len(cells)) + + offset := dataOffset(len(cells)) + for j, cell := range cells { + writeLeafCell(buf[:], j, offset, cell) + offset += align8(cell.Size()) + } + if err := c.tx.writePage(buf[:]); err != nil { + return err + } + + // Update the parent's reference key if it's changed. + if c.stack.index > 0 && oldPageKey != cells[0].Key { + return c.updateBranchCell(c.stack.index-1, cells[0].Key) + } + return nil +} + +// putBranchCells updates a branch page with one or more cells. +func (c *Cursor) putBranchCells(stackIndex int, newCells []branchCell) (err error) { + elem := &c.stack.elems[stackIndex] + + // Read branch page from disk. The current buffer is the leaf page. + page, err := c.tx.readPage(elem.pgno) + if err != nil { + return err + } + cells := readBranchCells(page) + + // Update current cell & insert additional cells after it. + cells[elem.index] = newCells[0] + if len(newCells) > 1 { + cells = append(cells, make([]branchCell, len(newCells)-1)...) + copy(cells[elem.index+len(newCells):], cells[elem.index+1:]) + copy(cells[elem.index+1:], newCells[1:]) + } + + // Split into multiple pages if page size is exceeded. + groups := [][]branchCell{cells} + if branchCellsPageSize(cells) > PageSize { + groups = splitBranchCells(cells) + } + + // Write each group to a separate page. + var parents []branchCell + origPgno := readPageNo(page) + newRoot := len(groups) > 1 && stackIndex == 0 + for i, group := range groups { + // First page should overwrite the original. + // Subsequent pages should allocate new pages. + parent := branchCell{Key: group[0].Key} + if i == 0 && !newRoot { + parent.Pgno = origPgno + } else { + if parent.Pgno, err = c.tx.allocate(); err != nil { + return fmt.Errorf("cannot allocate leaf: %w", err) + } + } + parents = append(parents, parent) + + // Write cells to page. + var buf [PageSize]byte + writePageNo(buf[:], parents[i].Pgno) + writeFlags(buf[:], PageTypeBranch) + writeCellN(buf[:], len(group)) + + offset := dataOffset(len(group)) + for j, cell := range group { + writeBranchCell(buf[:], j, offset, cell) + offset += align8(branchCellSize) + } + + if err := c.tx.writePage(buf[:]); err != nil { + return err + } + } + + // TODO(BBJ): Update page in buffer & cursor stack. + + // If this is not a split, then exit now. + if len(groups) == 1 { + return nil + } + + // Initialize a new root if we are currently the root page. + if stackIndex == 0 { + assert(newRoot) + return c.writeRoot(origPgno, parents) + } + assert(!newRoot) + + // Otherwise update existing parent. + return c.putBranchCells(stackIndex-1, parents) +} + +// updateBranchCell updates the key for cell in the branch. +func (c *Cursor) updateBranchCell(stackIndex int, newKey uint64) (err error) { + elem := &c.stack.elems[stackIndex] + + // Read branch page from disk. The current buffer is the leaf page. + page, err := c.tx.readPage(elem.pgno) + if err != nil { + return err + } + cells := readBranchCells(page) + oldPageKey := cells[0].Key + + // Update key in branch cell. + cells[elem.index].Key = newKey + + // Write cells to page. + var buf [PageSize]byte + writePageNo(buf[:], elem.pgno) + writeFlags(buf[:], PageTypeBranch) + writeCellN(buf[:], len(cells)) + + offset := dataOffset(len(cells)) + for j, cell := range cells { + writeBranchCell(buf[:], j, offset, cell) + offset += align8(branchCellSize) + } + if err := c.tx.writePage(buf[:]); err != nil { + return err + } + + if stackIndex > 0 && oldPageKey != cells[0].Key { + return c.updateBranchCell(stackIndex-1, cells[0].Key) + } + return nil +} + +// deleteBranchCell removes a cell from a branch page. +func (c *Cursor) deleteBranchCell(stackIndex int, key uint64) (err error) { + elem := &c.stack.elems[stackIndex] + + // Read branch page from disk. The current buffer is the leaf page. + page, err := c.tx.readPage(elem.pgno) + if err != nil { + return err + } + cells := readBranchCells(page) + oldPageKey := cells[0].Key + + // Remove cell from branch. + copy(cells[elem.index:], cells[elem.index+1:]) + cells[len(cells)-1] = branchCell{} + cells = cells[:len(cells)-1] + + // If the root only has one node, replace it with its child. + if stackIndex == 0 && len(cells) == 1 { + target, err := c.tx.readPage(cells[0].Pgno) + if err != nil { + return err + } + + buf := make([]byte, PageSize) + copy(buf, target) + writePageNo(buf[:], elem.pgno) + + if err := c.tx.deallocate(cells[0].Pgno); err != nil { + return err + } + return c.tx.writePage(buf[:]) + } + + // Write cells to page. + var buf [PageSize]byte + writePageNo(buf[:], elem.pgno) + writeFlags(buf[:], PageTypeBranch) + writeCellN(buf[:], len(cells)) + + offset := dataOffset(len(cells)) + for j, cell := range cells { + writeBranchCell(buf[:], j, offset, cell) + offset += align8(branchCellSize) + } + if err := c.tx.writePage(buf[:]); err != nil { + return err + } + + if stackIndex > 0 && oldPageKey != cells[0].Key { + return c.updateBranchCell(stackIndex-1, cells[0].Key) + } + return nil +} + +// writeRoot writes a new branch page at the root with the given cells. +func (c *Cursor) writeRoot(pgno uint32, cells []branchCell) error { + var buf [PageSize]byte + writePageNo(buf[:], pgno) + writeFlags(buf[:], PageTypeBranch) + writeCellN(buf[:], len(cells)) + + offset := dataOffset(len(cells)) + for i := range cells { + writeBranchCell(buf[:], i, offset, cells[i]) + offset += align8(branchCellSize) + } + return c.tx.writePage(buf[:]) +} + +// splitLeafCells splits cells into roughly equal parts. It's a naive +// implementation that splits cells whenever a page is 60% full. +func splitLeafCells(cells []leafCell) [][]leafCell { + slices := make([][]leafCell, 1, 2) + + var dataSize int + for _, cell := range cells { + // Determine number of cells on current slice & cell size. + cellN := len(slices[len(slices)-1]) + sz := align8(leafCellHeaderSize + len(cell.Data)) + + // If there is at least one cell on the slice & we've exceeded + // half a page then create a new group of cells. + if cellN != 0 && (dataOffset(cellN+1)+dataSize+sz) > (PageSize*60)/100 { + slices, dataSize = append(slices, nil), 0 + } + + // Append to current slice & increase total cell data size. + slices[len(slices)-1] = append(slices[len(slices)-1], cell) + dataSize += sz + } + + return slices +} + +// splitBranchCells splits cells into roughly equal parts. It's a naive +// implementation that splits cells whenever a page is 60% full. +func splitBranchCells(cells []branchCell) [][]branchCell { + slices := make([][]branchCell, 1, 2) + + var dataSize int + for _, cell := range cells { + // Determine number of cells on current slice & cell size. + cellN := len(slices[len(slices)-1]) + sz := align8(branchCellSize) + + // If there is at least one cell on the slice & we've exceeded + // half a page then create a new group of cells. + if cellN != 0 && (dataOffset(cellN+1)+dataSize+sz) > (PageSize*60)/100 { + slices, dataSize = append(slices, nil), 0 + } + + // Append to current slice & increase total cell data size. + slices[len(slices)-1] = append(slices[len(slices)-1], cell) + dataSize += sz + } + + return slices +} + +// Key returns the key that the cursor is currently positioned over. +func (c *Cursor) Key() uint64 { + elem := &c.stack.elems[c.stack.index] + if elem.isBitmap { + return elem.key + } + offset := readCellOffset(c.leafPage, elem.index) + return *(*uint64)(unsafe.Pointer(&c.leafPage[offset])) +} + +func (c *Cursor) cell() leafCell { + elem := &c.stack.elems[c.stack.index] + if elem.isBitmap { + return leafCell{Type: ContainerTypeBitmap, Key: elem.key, Data: c.leafPage[:]} + } + return readLeafCell(c.leafPage[:], elem.index) +} + +// First moves to the first element of the btree. +func (c *Cursor) First() error { + c.buffered = true + + for c.stack.index = 0; ; c.stack.index++ { + elem := &c.stack.elems[c.stack.index] + + buf, err := c.tx.readPage(elem.pgno) + if err != nil { + return err + } + + switch typ := readFlags(buf); typ { + case PageTypeBranch: + elem.index = 0 + + // Read cell pgno into the next stack level. + cell := readBranchCell(buf, elem.index) + isBitmap := cell.Flags&ContainerTypeBitmap != 0 + + c.stack.elems[c.stack.index+1] = stackElem{ + pgno: cell.Pgno, + key: cell.Key, + isBitmap: isBitmap, + } + + // If cell points at a bitmap page then increment stack but exit immediately. + if isBitmap { + c.stack.index++ + if c.leafPage, err = c.tx.readPage(cell.Pgno); err != nil { + return err + } + return nil + } + + case PageTypeLeaf: + c.leafPage = buf + elem.index = 0 + if readCellN(buf) == 0 { + return io.EOF // root leaf with no elements + } + return nil + default: + return fmt.Errorf("rbf.Cursor.First(): invalid page type: pgno=%d type=%d", elem.pgno, typ) + } + } +} + +// Last moves to the last element of the btree. +func (c *Cursor) Last() error { + // c.stack.elems[0].pgno = c.root + c.buffered = true + + for c.stack.index = 0; ; c.stack.index++ { + elem := &c.stack.elems[c.stack.index] + + buf, err := c.tx.readPage(elem.pgno) + if err != nil { + return err + } + + switch typ := readFlags(buf); typ { + case PageTypeBranch: + elem.index = readCellN(buf) - 1 + + // Read cell pgno into the next stack level. + cell := readBranchCell(buf, elem.index) + isBitmap := cell.Flags&ContainerTypeBitmap != 0 + + c.stack.elems[c.stack.index+1] = stackElem{ + pgno: cell.Pgno, + key: cell.Key, + isBitmap: isBitmap, + } + + // If cell points at a bitmap page then increment stack but exit immediately. + if isBitmap { + c.stack.index++ + if c.leafPage, err = c.tx.readPage(cell.Pgno); err != nil { + return err + } + return nil + } + + case PageTypeLeaf: + elem.index = readCellN(buf) - 1 + c.leafPage = buf + if readCellN(buf) == 0 { + return io.EOF // root leaf with no elements + } + return nil + default: + return fmt.Errorf("rbf.Cursor.Last(): invalid page type: pgno=%d type=%d", elem.pgno, typ) + } + } +} + +// Seek moves to the specified container of the btree. +// If the container does not exist then it moves to the next container after the key. +func (c *Cursor) Seek(key uint64) (exact bool, err error) { + // c.stack.elems[0].pgno = c.bitmap.root + c.buffered = true + for c.stack.index = 0; ; c.stack.index++ { + elem := &c.stack.elems[c.stack.index] + assert(elem.pgno != 0) + + buf, err := c.tx.readPage(elem.pgno) + if err != nil { + return false, err + } + switch typ := readFlags(buf); typ { + case PageTypeBranch: + n := readCellN(buf) + index, ok := search(n, func(i int) int { + if v := readBranchCellKey(buf, i); key == v { + return 0 + } else if key < v { + return -1 + } + return 1 + }) + if !ok && index > 0 { + index-- + } + elem.index = index + + // Read cell pgno into the next stack level. + + cell := readBranchCell(buf, elem.index) + isBitmap := cell.Flags&ContainerTypeBitmap != 0 + + c.stack.elems[c.stack.index+1] = stackElem{ + pgno: cell.Pgno, + key: cell.Key, + isBitmap: isBitmap, + } + + // If cell points at a bitmap page then increment stack but exit immediately. + if isBitmap { + c.stack.index++ + if c.leafPage, err = c.tx.readPage(cell.Pgno); err != nil { + return false, err + } + return ok, nil + } + + case PageTypeLeaf: + n := readCellN(buf) + index, ok := search(n, func(i int) int { + if v := readLeafCellKey(buf, i); key == v { + return 0 + } else if key < v { + return -1 + } + return 1 + }) + elem.index = index + c.leafPage = buf + return ok, nil + + default: + return false, fmt.Errorf("rbf.Cursor.Seek(): invalid page type: pgno=%d type=%d", elem.pgno, typ) + } + } +} + +// Next moves to the next element of the btree. Returns EOF if no more elements exist. +func (c *Cursor) Next() error { + if c.buffered { + c.buffered = false + return nil + } + + // Move forward to the next leaf element if available. + if elem := &c.stack.elems[c.stack.index]; !elem.isBitmap && elem.index < readCellN(c.leafPage)-1 { + elem.index++ + return nil + } + return c.goNextPage() +} + +// Prev moves to the previous element of the btree. +func (c *Cursor) Prev() error { + if c.buffered { + c.buffered = false + return nil + } + + // Move forward to the next leaf element if available. + if elem := &c.stack.elems[c.stack.index]; !elem.isBitmap && elem.index > 0 { + elem.index-- + return nil + } + + // Move up the stack until we can move forward one element. + for c.stack.index--; c.stack.index >= 0; c.stack.index-- { + elem := &c.stack.elems[c.stack.index] + if elem.index > 0 { + elem.index-- + break + } + } + + // No more elements, return EOF. + if c.stack.index == -1 { + c.stack.index = 0 + return io.EOF + } + + // Traverse back down the stack to find the first element in each page. + for ; ; c.stack.index++ { + elem := &c.stack.elems[c.stack.index] + + buf, err := c.tx.readPage(elem.pgno) + if err != nil { + return err + } + + switch typ := readFlags(buf); typ { + case PageTypeBranch: + cell := readBranchCell(buf, elem.index) + isBitmap := cell.Flags&ContainerTypeBitmap != 0 + + c.stack.elems[c.stack.index+1] = stackElem{ + pgno: cell.Pgno, + key: cell.Key, + isBitmap: isBitmap, + } + + // If cell points at a bitmap page then increment stack but exit immediately. + if isBitmap { + c.stack.index++ + if c.leafPage, err = c.tx.readPage(cell.Pgno); err != nil { + return err + } + return nil + } + + case PageTypeLeaf: + elem.index = readCellN(buf) - 1 + c.leafPage = buf + return nil + default: + return fmt.Errorf("rbf.Cursor.Prev(): invalid page type: pgno=%d type=%d", elem.pgno, typ) + } + } +} + +// Union performs a bitwise OR operation on row and a given row id in the bitmap. +func (c *Cursor) Union(rowID uint64, row []uint64) error { + base := rowID * ShardWidth + + if _, err := c.Seek(base >> 16); err != nil { + return err + } + for { + err := c.Next() + if err == io.EOF { + return nil + } else if err != nil { + return err + } + + cell := c.cell() + key := cell.Key << 16 + if key >= base+ShardWidth { + return nil + } + offset := key - base + switch cell.Type { + case ContainerTypeArray: + for _, v := range toArray16(cell.Data) { + row[(offset+uint64(v))/64] |= 1 << uint64(v%64) + } + case ContainerTypeRLE: + panic("TODO(BBJ): rbf.Bitmap.Union() RLE support") + case ContainerTypeBitmap: + for i, v := range toArray64(cell.Data) { + row[(offset/64)+uint64(i)] |= v + } + default: + return fmt.Errorf("rbf.Bitmap.Union(): invalid container type: %d", cell.Type) + } + } +} + +// Intersect performs a bitwise AND operation on row and a given row id in the bitmap. +func (c *Cursor) Intersect(rowID uint64, row []uint64) error { + base := rowID * ShardWidth + c.stack.index = 0 + + keyExists := make([]bool, ShardWidth/(1<<16)) + + if _, err := c.Seek(base >> 16); err != nil { + return err + } + for { + err := c.Next() + if err == io.EOF { + break + } else if err != nil { + return err + } + + cell := c.cell() + key := cell.Key << 16 + if key >= base+ShardWidth { + return nil + } + offset := key - base + + keyExists[offset/(1<<16)] = true + + switch cell.Type { + case ContainerTypeArray: + for i, v := range cell.Bitmap() { + row[(offset/64)+uint64(i)] &= v + } + case ContainerTypeRLE: + panic("TODO(BBJ): rbf.Bitmap.Intersect() RLE support") + case ContainerTypeBitmap: + for i, v := range toArray64(cell.Data) { + row[(offset/64)+uint64(i)] &= v + } + default: + return fmt.Errorf("rbf.Bitmap.Intersect(): invalid container type: %d", cell.Type) + } + } + + // Clear any missing keys. + for i, ok := range keyExists { + if ok { + continue + } + for j := 0; j < (1 << 16); j += 64 { + row[((i*(1<<16))+j)/64] = 0 + } + } + return nil +} + +// Values returns the values for the container the cursor is currently pointing to. +func (c *Cursor) Values() []uint16 { + elem := &c.stack.elems[c.stack.index] + var cell leafCell + if elem.isBitmap { + cell = leafCell{Type: ContainerTypeBitmap, Key: elem.key, Data: c.leafPage} + } else { + cell = readLeafCell(c.leafPage[:], elem.index) + } + return cell.Values() +} + +// stackElem represents a single element on the cursor stack. +type stackElem struct { + pgno uint32 // current page number + index int // cell index + key uint64 // element key + isBitmap bool // if true, entire page is a bitmap +} + +func (c *Cursor) goNextPage() error { + for c.stack.index--; c.stack.index >= 0; c.stack.index-- { + elem := &c.stack.elems[c.stack.index] + if buf, err := c.tx.readPage(elem.pgno); err != nil { + return err + } else if n := readCellN(buf); elem.index+1 < n { + elem.index++ + break + } + } + + // No more elements, return EOF. + if c.stack.index == -1 { + c.stack.index = 0 + return io.EOF + } + + // Traverse back down the stack to find the first element in each page. + for ; ; c.stack.index++ { + elem := &c.stack.elems[c.stack.index] + buf, err := c.tx.readPage(elem.pgno) + if err != nil { + return err + } + + switch typ := readFlags(buf); typ { + case PageTypeBranch: + cell := readBranchCell(buf, elem.index) + isBitmap := cell.Flags&ContainerTypeBitmap != 0 + + c.stack.elems[c.stack.index+1] = stackElem{ + pgno: cell.Pgno, + key: cell.Key, + isBitmap: isBitmap, + } + + // If cell points at a bitmap page then increment stack but exit immediately. + if isBitmap { + c.stack.index++ + if c.leafPage, err = c.tx.readPage(cell.Pgno); err != nil { + return err + } + return nil + } + + case PageTypeLeaf: + elem.index = 0 + c.leafPage = buf + return nil + default: + return fmt.Errorf("rbf.Cursor.Next(): invalid page type: pgno=%d type=%d", elem.pgno, typ) + } + } +} + +func ConvertToLeaf(key uint64, c *roaring.Container) (result leafCell) { + //TODO(twg) clean up roaring constant import export + result.Key = key + result.N = int(c.N()) + result.Type = ContainerTypeNone + if c.N() == 0 { + return + } + switch roaring.ContainerType(c) { + case 1: //array + a := roaring.AsArray(c) + if len(a) > ArrayMaxSize { + roaring.ConvertArrayToBitmap(c) + result.Type = ContainerTypeBitmap + result.Data = fromArray64(roaring.AsBitmap(c)) + return + } + result.Type = ContainerTypeArray + result.Data = fromArray16(a) + return + case 2: //bitmap + result.Type = ContainerTypeBitmap + result.Data = fromArray64(roaring.AsBitmap(c)) + return + case 3: //run + r := roaring.AsRuns(c) + if len(r) > RLEMaxSize { + roaring.ConvertRunToBitmap(c) + result.Type = ContainerTypeBitmap + result.Data = fromArray64(roaring.AsBitmap(c)) + } + result.N = len(r) //note RBF N is number of containers + result.Type = ContainerTypeRLE + result.Data = fromInterval16(r) + return + + } + return +} + +func (c *Cursor) merge(key uint64, data *roaring.Container) (bool, error) { + cell := c.cell() + var container *roaring.Container + switch cell.Type { + case ContainerTypeArray: + d := toArray16(cell.Data) + container = roaring.NewContainerArray(d) + case ContainerTypeBitmap: + d := toArray64(cell.Data) + container = roaring.NewContainerBitmap(cell.N, d) + case ContainerTypeRLE: + d := toInterval16(cell.Data) + container = roaring.NewContainerRun(d) + } + + res := roaring.Union(data, container) + if res.N() != data.N() { + leaf := ConvertToLeaf(key, res) + err := c.putLeafCell(leaf) + return true, err + } + + return false, nil +} + +func (c *Cursor) AddRoaring(bm *roaring.Bitmap) (changed bool, err error) { + itr, _ := bm.Containers.Iterator(0) + for itr.Next() { + hi, cont := itr.Value() + leaf := ConvertToLeaf(hi, cont) + if leaf.N == 0 { + continue + } + // Move cursor to the key of the container. + // Insert new container if it doesn't exist. + if exact, err := c.Seek(hi); err != nil { + return false, err + } else if !exact { + err = c.putLeafCell(leaf) + if err != nil { + return false, err + } + changed = true + continue + } + + // If the container exists and bit is not set then update the page. + u, err := c.merge(hi, cont) + if err != nil { + return false, err + } + if u { + changed = true + } + } + return changed, nil +} + +func popcount(x uint64) uint64 { + return uint64(bits.OnesCount64(x)) +} diff --git a/rbf/cursor_test.go b/rbf/cursor_test.go new file mode 100644 index 000000000..d918169ac --- /dev/null +++ b/rbf/cursor_test.go @@ -0,0 +1,799 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf_test + +import ( + "math/bits" + "math/rand" + "reflect" + "sort" + "testing" + + "github.com/pilosa/pilosa/v2/rbf" + "github.com/pilosa/pilosa/v2/roaring" +) + +func TestCursor_FirstNext(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", 0x00000001, 0x00000002, 0x00010003, 0x00030004); err != nil { + t.Fatal(err) + } + + c, err := tx.Cursor("x") + if err != nil { + t.Fatal(err) + } else if err := c.First(); err != nil { + t.Fatal(err) + } + + if err := c.Next(); err != nil { + t.Fatal(err) + } else if got, want := c.Key(), uint64(0); got != want { + t.Fatalf("Next()=%d, want %d", got, want) + } else if got, want := c.Values(), []uint16{1, 2}; !reflect.DeepEqual(got, want) { + t.Fatalf("Values()=%#v, want %#v", got, want) + } + + if err := c.Next(); err != nil { + t.Fatal(err) + } else if got, want := c.Key(), uint64(1); got != want { + t.Fatalf("Next()=%d, want %d", got, want) + } else if got, want := c.Values(), []uint16{3}; !reflect.DeepEqual(got, want) { + t.Fatalf("Values()=%#v, want %#v", got, want) + } + + if err := c.Next(); err != nil { + t.Fatal(err) + } else if got, want := c.Key(), uint64(3); got != want { + t.Fatalf("Next()=%d, want %d", got, want) + } else if got, want := c.Values(), []uint16{4}; !reflect.DeepEqual(got, want) { + t.Fatalf("Values()=%#v, want %#v", got, want) + } +} + +func TestCursor_FirstNext_Quick(t *testing.T) { + if testing.Short() { + t.Skip("-short enabled, skipping") + } else if is32Bit() { + t.Skip("32-bit build, skipping quick check tests") + } else if rbf.RaceEnabled { + t.Skip("race detection enabled, skipping") + } + + const n = 100000 + + QuickCheck(t, func(t *testing.T, rand *rand.Rand) { + t.Parallel() + + // Generate sorted list of values. + values := make([]uint64, rand.Intn(n)) + for i := range values { + values[i] = uint64(rand.Intn(rbf.ShardWidth)) + } + sort.Slice(values, func(i, j int) bool { return values[i] < values[j] }) + + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + + // Insert values in random order. + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + for _, i := range rand.Perm(len(values)) { + v := values[i] + if _, err := tx.Add("x", v); err != nil { + t.Fatalf("Add(%d) i=%d err=%q", v, i, err) + } + } + + // Generate unique bucketed values. + type Item struct { + key uint64 + values []uint16 + } + var items []Item + m := make(map[uint64]struct{}) + for _, v := range values { + if _, ok := m[v]; ok { + continue + } + m[v] = struct{}{} + + hi, lo := highbits(v), lowbits(v) + if len(items) == 0 || items[len(items)-1].key != hi { + items = append(items, Item{key: hi}) + } + + item := &items[len(items)-1] + item.values = append(item.values, lo) + } + + // Verify cursor returns correct value groups. + c, err := tx.Cursor("x") + if err != nil { + t.Fatal(err) + } else if err := c.First(); err != nil { + t.Fatal(err) + } + for _, item := range items { + if err := c.Next(); err != nil { + t.Fatal(err) + } else if got, want := c.Key(), item.key; got != want { + t.Fatalf("Key()=%d, want %d", got, want) + } else if got, want := c.Values(), item.values; !reflect.DeepEqual(got, want) { + t.Fatalf("len(Values())=%v, want %v", len(got), len(want)) + } + } + }) +} + +func TestCursor_LastPrev(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", 0x00000001, 0x00000002, 0x00010003, 0x00030004); err != nil { + t.Fatal(err) + } + + c, err := tx.Cursor("x") + if err != nil { + t.Fatal(err) + } else if err := c.Last(); err != nil { + t.Fatal(err) + } + + if err := c.Prev(); err != nil { + t.Fatal(err) + } else if got, want := c.Key(), uint64(3); got != want { + t.Fatalf("Prev()=%d, want %d", got, want) + } else if got, want := c.Values(), []uint16{4}; !reflect.DeepEqual(got, want) { + t.Fatalf("Values()=%#v, want %#v", got, want) + } + + if err := c.Prev(); err != nil { + t.Fatal(err) + } else if got, want := c.Key(), uint64(1); got != want { + t.Fatalf("Prev()=%d, want %d", got, want) + } else if got, want := c.Values(), []uint16{3}; !reflect.DeepEqual(got, want) { + t.Fatalf("Values()=%#v, want %#v", got, want) + } + + if err := c.Prev(); err != nil { + t.Fatal(err) + } else if got, want := c.Key(), uint64(0); got != want { + t.Fatalf("Prev()=%d, want %d", got, want) + } else if got, want := c.Values(), []uint16{1, 2}; !reflect.DeepEqual(got, want) { + t.Fatalf("Values()=%#v, want %#v", got, want) + } +} + +func TestCursor_LastPrev_Quick(t *testing.T) { + if testing.Short() { + t.Skip("-short enabled, skipping") + } else if is32Bit() { + t.Skip("32-bit build, skipping quick check tests") + } else if rbf.RaceEnabled { + t.Skip("race detection enabled, skipping") + } + + const n = 100000 + + QuickCheck(t, func(t *testing.T, rand *rand.Rand) { + t.Parallel() + + // Generate sorted list of values. + values := make([]uint64, n) + for i := range values { + values[i] = uint64(rand.Intn(rbf.ShardWidth)) + } + sort.Slice(values, func(i, j int) bool { return values[i] < values[j] }) + + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + + // Insert values in random order. + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + for _, i := range rand.Perm(len(values)) { + v := values[i] + if _, err := tx.Add("x", v); err != nil { + t.Fatalf("Add(%d) i=%d err=%q", v, i, err) + } + } + + // Generate unique bucketed values. + type Item struct { + key uint64 + values []uint16 + } + var items []Item + m := make(map[uint64]struct{}) + for _, v := range values { + if _, ok := m[v]; ok { + continue + } + m[v] = struct{}{} + + hi, lo := highbits(v), lowbits(v) + if len(items) == 0 || items[len(items)-1].key != hi { + items = append(items, Item{key: hi}) + } + + item := &items[len(items)-1] + item.values = append(item.values, lo) + } + + // Verify cursor returns correct value groups. + c, err := tx.Cursor("x") + if err != nil { + t.Fatal(err) + } else if err := c.Last(); err != nil { + t.Fatal(err) + } + for i := len(items) - 1; i >= 0; i-- { + if err := c.Prev(); err != nil { + t.Fatal(err) + } else if got, want := c.Key(), items[i].key; got != want { + t.Fatalf("Key()=%d, want %d", got, want) + } else if got, want := c.Values(), items[i].values; !reflect.DeepEqual(got, want) { + t.Fatalf("len(Values())=%v, want %v", len(got), len(want)) + } + } + }) +} + +func TestCursor_Union(t *testing.T) { + t.Run("OK", func(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + + row := make([]uint64, rbf.ShardWidth/64) + + if _, err := tx.Add("x", 1, 3); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", rbf.ShardWidth+1, rbf.ShardWidth+2, rbf.ShardWidth+7); err != nil { + t.Fatal(err) + } + + c, err := tx.Cursor("x") + if err != nil { + t.Fatal(err) + } + if err := c.Union(0, row); err != nil { + t.Fatal(err) + } else if row[0] != 0b00001010 { + t.Fatalf("unexpected row[0]: 0b%b", row[0]) + } + + if err := c.Union(1, row); err != nil { + t.Fatal(err) + } else if row[0] != 0b10001110 { + t.Fatalf("unexpected row[0]: 0b%b", row[0]) + } + }) + + t.Run("Quick", func(t *testing.T) { + if testing.Short() { + t.Skip("-short enabled, skipping") + } else if is32Bit() { + t.Skip("32-bit build, skipping quick check tests") + } else if rbf.RaceEnabled { + t.Skip("race detection enabled, skipping") + } + + QuickCheck(t, func(t *testing.T, rand *rand.Rand) { + t.Parallel() + + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + values := GenerateValues(rand, 100000) + rows := ToRows(values) + + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + MustAddRandom(t, rand, tx, "x", values...) + + // Iterate over rows and randomly choose another row to union. + for i, row0 := range rows { + row1 := rows[rand.Intn(len(rows))] + + bitmap := row0.Bitmap() + c, err := tx.Cursor("x") + if err != nil { + t.Fatal(err) + } else if err := c.Union(row1.ID, bitmap); err != nil { + return + } + + if got, want := len(rbf.RowValues(bitmap)), len(row0.Union(row1)); got != want { + t.Fatalf("%d. len()=%d, want %d", i, got, want) + } + } + }) + }) +} + +func TestCursor_Intersect(t *testing.T) { + t.Run("OK", func(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + + row := make([]uint64, rbf.ShardWidth/64) + + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + + if _, err := tx.Add("x", 1, 3); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", rbf.ShardWidth+1, rbf.ShardWidth+2, rbf.ShardWidth+7); err != nil { + t.Fatal(err) + } + + c, err := tx.Cursor("x") + if err != nil { + t.Fatal(err) + } + + if err := c.Union(0, row); err != nil { + t.Fatal(err) + } else if row[0] != 0b00001010 { + t.Fatalf("unexpected row[0]: %#v", row[0]) + } + + if err := c.Intersect(1, row); err != nil { + t.Fatal(err) + } else if row[0] != 0b00000010 { + t.Fatalf("unexpected row[0]: %#v", row[0]) + } + }) + + t.Run("Quick", func(t *testing.T) { + if testing.Short() { + t.Skip("-short enabled, skipping") + } else if is32Bit() { + t.Skip("32-bit build, skipping quick check tests") + } else if rbf.RaceEnabled { + t.Skip("race detection enabled, skipping") + } + + QuickCheck(t, func(t *testing.T, rand *rand.Rand) { + t.Parallel() + + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + values := GenerateValues(rand, rand.Intn(100000)) + rows := ToRows(values) + + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + MustAddRandom(t, rand, tx, "x", values...) + + // Iterate over rows and randomly choose another row to union. + for i, row0 := range rows { + row1 := rows[rand.Intn(len(rows))] + + bitmap := row0.Bitmap() + if c, err := tx.Cursor("x"); err != nil { + t.Fatal(err) + } else if err := c.Intersect(row1.ID, bitmap); err != nil { + t.Fatal(err) + } + + if got, want := len(rbf.RowValues(bitmap)), len(row0.Intersect(row1)); got != want { + t.Fatalf("%d. len()=%d, want %d", i, got, want) + } + } + }) + }) +} + +func makeBitmap(bit []uint16) (n int, ret []uint64) { + ret = make([]uint64, 1024) + for _, v := range bit { + ret[v/64] |= 1 << uint64(v%64) + } + n = 0 + for _, v := range ret { + n += bits.OnesCount64(v) + } + return +} + +func TestCursor_AddRoaring(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + tests := []struct { + name string + fieldview string + rb *roaring.Bitmap + wantChanged bool + wantErr bool + }{{ + name: "no view", + fieldview: "a/standard", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + return bm + }(), + wantChanged: false, + wantErr: true}, + { + name: "initial Array", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + bm.Put(0, roaring.NewContainerArray([]uint16{1, 2})) + return bm + }(), + wantChanged: true, + wantErr: false}, { + name: "initial RLE", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + bm.Put(1, roaring.NewContainerRun([]roaring.Interval16{{Start: 10, Last: 20000}})) + return bm + }(), + wantChanged: true, + wantErr: false}, + { + name: "initial Bitmap", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + bm.Put(3, roaring.NewContainerBitmap(makeBitmap([]uint16{4, 8, 12}))) + return bm + }(), + wantChanged: true, + wantErr: false}, + { + name: "merge Array exist", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + bm.Put(0, roaring.NewContainerArray([]uint16{1, 2})) + return bm + }(), + wantChanged: false, + wantErr: false}, { + name: "merge Array present", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + bm.Put(0, roaring.NewContainerArray([]uint16{3, 4})) + return bm + }(), + wantChanged: true, + wantErr: false}, + { + name: "merge Bitmap exist", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + bm.Put(3, roaring.NewContainerBitmap(makeBitmap([]uint16{4, 8, 12}))) + return bm + }(), + wantChanged: false, + wantErr: false}, + { + name: "merge Bitmap ", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + bm.Put(3, roaring.NewContainerBitmap(makeBitmap([]uint16{75}))) + return bm + }(), + wantChanged: true, + wantErr: false}, + { + name: "merge BitmapArray ", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + bm.Put(0, roaring.NewContainerBitmap(makeBitmap([]uint16{75}))) + return bm + }(), + wantChanged: true, + wantErr: false}, { + name: "too Big Array ", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + items := make([]uint16, rbf.ArrayMaxSize+2) + for i := 0; i < len(items); i++ { + items[i] = uint16(i) + } + bm.Put(10, roaring.NewContainerArray(items)) + return bm + }(), + wantChanged: true, + wantErr: false}, + { + name: "too Big RLE ", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + items := make([]roaring.Interval16, rbf.RLEMaxSize+2) + x := uint16(0) + for i := 0; i < len(items); i++ { + v := roaring.Interval16{Start: x, Last: x + 1} + x += 3 + items[i] = v + } + bm.Put(10, roaring.NewContainerRun(items)) + return bm + }(), + wantChanged: true, + wantErr: false}, { + name: "empty container ", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + bm.Put(11, roaring.NewContainerArray([]uint16{})) + return bm + }(), + wantChanged: false, + wantErr: false}, + { + name: "merge RLE", + fieldview: "x", + rb: func() *roaring.Bitmap { + bm := roaring.NewBitmap() + bm.Put(1, roaring.NewContainerRun([]roaring.Interval16{{Start: 1, Last: 12}})) + return bm + }(), + wantChanged: true, + wantErr: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotChanged, err := tx.AddRoaring(tt.fieldview, tt.rb) + if (err != nil) != tt.wantErr { + t.Errorf("Cursor.AddRoaring() error = %v, wantErr %v", err, tt.wantErr) + return + } + if gotChanged != tt.wantChanged { + t.Errorf("Cursor.AddRoaring() = %v, want %v", gotChanged, tt.wantChanged) + } + }) + } +} + +func TestCursor_RLETesting(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + //setup RLE + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + rb := func() *roaring.Bitmap { + bm := roaring.NewBitmap() + bm.Put(0, roaring.NewContainerRun([]roaring.Interval16{{Start: 10, Last: 11}})) + return bm + }() + _, err := tx.AddRoaring("x", rb) + if err != nil { + t.Errorf("Add Roaring Failed %v", err) + } + // + tests := []struct { + name string + args []uint64 + want []uint16 + wantChanged bool + wantErr bool + }{{ + name: "update run at Last", + args: []uint64{0x0000000c}, + want: []uint16{0x0000000a, 0x0000000b, 0x0000000c}, + wantChanged: true, + wantErr: false, + }, + { + name: "update run at begining", + args: []uint64{0x00000001, 0x00000002}, + want: []uint16{0x00000001, 0x00000002, 0x0000000a, 0x0000000b, 0x0000000c}, + wantChanged: true, + wantErr: false, + }, + { + name: "add run at end", + args: []uint64{0x0000000f}, + want: []uint16{0x00000001, 0x00000002, 0x0000000a, 0x0000000b, 0x0000000c, 0x0000000f}, + wantChanged: true, + wantErr: false, + }, + { + name: "no change", + args: []uint64{0x0000000b}, + want: []uint16{0x00000001, 0x00000002, 0x0000000a, 0x0000000b, 0x0000000c, 0x0000000f}, + wantChanged: false, + wantErr: false, + }, { + name: "update start", + args: []uint64{0x0000000e}, + want: []uint16{0x00000001, 0x00000002, 0x0000000a, 0x0000000b, 0x0000000c, 0x0000000e, 0x0000000f}, + wantChanged: true, + wantErr: false, + }, { + name: "combine", + args: []uint64{0x0000000d}, + want: []uint16{0x00000001, 0x00000002, 0x0000000a, 0x0000000b, 0x0000000c, 0x0000000d, 0x0000000e, 0x0000000f}, + wantChanged: true, + wantErr: false, + }, { + name: "add end", + args: []uint64{0x0000ffff}, + want: []uint16{0x00000001, 0x00000002, 0x0000000a, 0x0000000b, 0x0000000c, 0x0000000d, 0x0000000e, 0x0000000f, 0x0000ffff}, + wantChanged: true, + wantErr: false, + }, + { + name: "overflow container", + args: []uint64{0x00010000}, + want: []uint16{0x00000001, 0x00000002, 0x0000000a, 0x0000000b, 0x0000000c, 0x0000000d, 0x0000000e, 0x0000000f, 0x0000ffff}, + wantChanged: true, + wantErr: false, + }, + } + + c, err := tx.Cursor("x") + if err != nil { + t.Fatal(err) + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + changed, err := tx.Add("x", tt.args...) + if tt.wantErr && err == nil { + t.Errorf("No Error %v", err) + } else if tt.wantChanged && !changed { + t.Errorf("No Change %v", err) + } else if err != nil { + t.Fatal(err) + } else if err := c.First(); err != nil { + t.Fatal(err) + } + if got, want := c.Values(), tt.want; !reflect.DeepEqual(got, want) { + t.Fatalf("Values()=%#v, want %#v", got, want) + } + }) + } + + t.Run("overflow followup", func(t *testing.T) { + //verify than next container got created and is valid + if err := c.Next(); err != nil { //skip the buffered? + t.Fatal(err) + } + if err := c.Next(); err != nil { + t.Fatal(err) + } + + want := []uint16{0} + if got, want := c.Values(), want; !reflect.DeepEqual(got, want) { + t.Fatalf("Values()=%#v, want %#v", got, want) + } else if got, want := c.Key(), uint64(1); !reflect.DeepEqual(got, want) { + t.Fatalf("Key()=%#v, want %#v", got, want) + } + }) +} + +func TestCursor_RLEConversion(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + //setup RLE with full container + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + want := make([]uint16, 0, rbf.ArrayMaxSize) + rb := func() *roaring.Bitmap { + bm := roaring.NewBitmap() + runs := make([]roaring.Interval16, rbf.RLEMaxSize) + x := uint16(1) + for i := range runs { + runs[i] = roaring.Interval16{Start: x, Last: x + 1} + want = append(want, x) + want = append(want, x+1) + x += 3 + } + bm.Put(0, roaring.NewContainerRun(runs)) + return bm + }() + + _, err := tx.AddRoaring("x", rb) + if err != nil { + t.Errorf("Add Roaring Failed %v", err) + } + c, err := tx.Cursor("x") + if err != nil { + t.Fatal(err) + } else if err := c.First(); err != nil { + t.Fatal(err) + } + if c.CurrentPageType() != rbf.ContainerTypeRLE { + t.Fatalf("Should Be RLE but is: %v\n", c.CurrentPageType()) + } + exists, err := c.Contains(0x7) + if err != nil { + t.Fatalf("ERR:%v", err) + } + if !exists { + t.Fatalf("Should Contain %v", 0x7) + } + //add a few bits to create another run + _, err = tx.Add("x", + func() []uint64 { + r := make([]uint64, 0, 128) + for x := uint64(65408); x < 65536; x++ { + r = append(r, x) + want = append(want, uint16(x)) + } + return r + }()...) + if err != nil { + t.Fatalf("ERR adding bits: %v\n", err) + + } + + if err := c.First(); err != nil { + t.Fatal(err) + } + if got, want := c.Values(), want; !reflect.DeepEqual(got, want) { + t.Fatalf("Values()=%#v, want %#v", got, want) + } else if c.CurrentPageType() != rbf.ContainerTypeBitmap { + t.Fatalf("Should be bitmap but is %v", c.CurrentPageType()) + } + +} diff --git a/rbf/cursorx.go b/rbf/cursorx.go new file mode 100644 index 000000000..35d5818c2 --- /dev/null +++ b/rbf/cursorx.go @@ -0,0 +1,151 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf + +import ( + "bufio" + "fmt" + "io" + "math" + "os" + + "github.com/pilosa/pilosa/v2/roaring" +) + +//probably should just implement the container interface +// but for now i'll do it +func (c *Cursor) Rows() ([]uint64, error) { + shardVsContainerExponent := uint(4) //needs constant exported from roaring package + if err := c.First(); err != nil { + return nil, err + } + rows := make([]uint64, 0) + var err error + var lastRow uint64 = math.MaxUint64 + for { + err := c.Next() + if err != nil { + break + } + cell := c.cell() + vRow := cell.Key >> shardVsContainerExponent + if vRow == lastRow { + continue + } + rows = append(rows, vRow) + lastRow = vRow + } + return rows, err +} + +func (tx *Tx) FieldViews() []string { + r, _ := tx.rootRecords() + res := make([]string, len(r)) + for i := range r { + res[i] = r[i].Name + } + return res +} + +func (c *Cursor) DumpKeys() error { + if err := c.First(); err != nil { + return err + } + for { + err := c.Next() + if err == io.EOF { + return nil + } else if err != nil { + return err + } + cell := c.cell() + fmt.Println("key", cell.Key) + } +} + +func (c *Cursor) DumpStack() { + fmt.Println("STACK") + for i := c.stack.index; i >= 0; i-- { + fmt.Printf("%+v\n", c.stack.elems[i]) + } + fmt.Println() +} + +func (c *Cursor) Dump() { + bufStdout := bufio.NewWriter(os.Stdout) + defer bufStdout.Flush() + fmt.Fprintf(bufStdout, "digraph RBF{\n") + fmt.Fprintf(bufStdout, "rankdir=\"LR\"\n") + + fmt.Fprintf(bufStdout, "node [shape=record height=.1]\n") + dumpdot(c.tx, 0, " ", bufStdout) + fmt.Fprintf(bufStdout, "\n}") +} + +func (c *Cursor) Row(rowID uint64) (*roaring.Bitmap, error) { + base := rowID * ShardWidth + + offset := uint64(c.tx.db.Shard * ShardWidth) + off := highbits(offset) + hi0, hi1 := highbits(base), highbits((rowID+1)*ShardWidth) + c.stack.index = 0 + ok, err := c.Seek(hi0) + if err != nil { + return nil, err + } + if !ok { + elem := &c.stack.elems[c.stack.index] + n := readCellN(c.leafPage) + if elem.index >= n { + if err := c.goNextPage(); err != nil { + return nil, err + } + } + } + other := roaring.NewSliceBitmap() + for { + err := c.Next() + if err == io.EOF { + break + } else if err != nil { + return nil, err + } + + cell := c.cell() + if cell.Key >= hi1 { + break + } + other.Containers.Put(off+(cell.Key-hi0), toContainer(cell)) + } + return other, nil +} + +// CurrentPageType returns the type of the container currently pointed to by cursor used in testing +// sometimes the cursor needs to be positions prior to this call with First/Last etc. +func (c *Cursor) CurrentPageType() int { + cell := c.cell() + return cell.Type +} + +func toContainer(l leafCell) *roaring.Container { + switch l.Type { + case ContainerTypeArray: + return roaring.NewContainerArray(toArray16(l.Data)) + case ContainerTypeBitmap: + return roaring.NewContainerBitmap(l.N, toArray64(l.Data)) + case ContainerTypeRLE: + return roaring.NewContainerRun(toInterval16(l.Data)) + } + return nil +} diff --git a/rbf/db.go b/rbf/db.go new file mode 100644 index 000000000..2df0b31c9 --- /dev/null +++ b/rbf/db.go @@ -0,0 +1,637 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf + +import ( + "errors" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "sync" + "syscall" + + "github.com/benbjohnson/immutable" + "github.com/pilosa/pilosa/v2/syswrap" +) + +var ( + ErrClosed = errors.New("rbf: database closed") +) + +const ( + // Maximum size of a single WAL segment. + // May exceed by one page if last page is a bitmap header + bitmap. + MaxWALSegmentFileSize = 10 * (1 << 20) +) + +type DB struct { + data []byte // mmap data + file *os.File // file descriptor + segments []*WALSegment // write-ahead log + pageMap *immutable.Map // pgno-to-WALID mapping + txs map[*Tx]struct{} // active transactions + opened bool // true if open + + mu sync.RWMutex // general mutex + rwmu sync.Mutex // mutex for restricting single writer + + // Path represents the path to the database file. + Path string + + // The maximum allowed database size. Required by mmap. + MaxSize int64 + Shard int +} + +// NewDB returns a new instance of DB. +func NewDB(path string) *DB { + return NewDBWithShard(path, 0) +} +func NewDBWithShard(path string, shard int) *DB { + return &DB{ + txs: make(map[*Tx]struct{}), + pageMap: immutable.NewMap(&uint32Hasher{}), + Path: path, + MaxSize: DefaultMaxSize, + Shard: shard, + } +} + +// DataPath returns the path to the data file for the DB. +func (db *DB) DataPath() string { + return filepath.Join(db.Path, "data") +} + +// WALPath returns the path to the WAL directory. +func (db *DB) WALPath() string { + return filepath.Join(db.Path, "wal") +} + +func CreateDirIfNotExist(path string) { + dir := filepath.Dir(path) + if _, err := os.Stat(dir); os.IsNotExist(err) { + err = os.MkdirAll(dir, 0755) + if err != nil { + panic(err) + } + } +} + +// Open opens a database with the file specified in Path. +// Creates a new file if one does not already exist. +func (db *DB) Open() (err error) { + db.mu.Lock() + defer db.mu.Unlock() + + if err := os.MkdirAll(filepath.Dir(db.Path), 0755); err != nil { + return err + } else if db.file, err = os.OpenFile(db.DataPath(), os.O_WRONLY|os.O_CREATE, 0666); err != nil { + return fmt.Errorf("open file: %w", err) + } + + // Open read-only mmap. + if f, err := os.OpenFile(db.DataPath(), os.O_RDONLY, 0666); err != nil { + return fmt.Errorf("open mmap file: %w", err) + } else if db.data, err = syswrap.Mmap(int(f.Fd()), 0, int(db.MaxSize), syscall.PROT_READ, syscall.MAP_SHARED); err != nil { + f.Close() + return fmt.Errorf("open mmap file: %w", err) + } else if err := f.Close(); err != nil { + return fmt.Errorf("cannot close mmap file: %w", err) + } + + // Initialize file if it is too small. + if fi, err := db.file.Stat(); err != nil { + return fmt.Errorf("stat: %w", err) + } else if fi.Size() < PageSize { + if err := db.init(); err != nil { + return fmt.Errorf("init: %w", err) + } + } + + // TODO(BBJ): Obtain advisory lock on file. + + // Ensure WAL directory exists. + if err := os.MkdirAll(db.WALPath(), 0777); err != nil { + return fmt.Errorf("create wal dir: %w", err) + } + + // Open write-ahead log & checkpoint to the end since no transactions are open. + if err := db.openWALSegments(); err != nil { + return fmt.Errorf("wal open: %w", err) + } else if err := db.checkpoint(); err != nil { + return fmt.Errorf("checkpoint: %w", err) + } + + db.opened = true + + return nil +} + +func (db *DB) openWALSegments() error { + fis, err := ioutil.ReadDir(db.WALPath()) + if err != nil { + return fmt.Errorf("read dir: %w", err) + } + + // Open all WAL segments. + for _, fi := range fis { + if filepath.Ext(fi.Name()) != ".wal" { + continue + } + + segment := NewWALSegment(filepath.Join(db.WALPath(), fi.Name())) + if err := segment.Open(); err != nil { + _ = db.closeWALSegments() + return err + } + db.segments = append(db.segments, segment) + } + + // Truncate last WAL page if it is a bitmap header. + if segment := db.activeWALSegment(); segment != nil { + if err := segment.trimBitmapHeaderTrailer(); err != nil { + return err + } + } + + return nil +} + +// checkpoint copies pages from WAL segments into the main DB file. This can +// only copy pages that aren't in use by an active transaction. The page map +// is rebuilt as well for all WAL pages still in use. +func (db *DB) checkpoint() error { + if !db.opened { + return nil + } + + // Determine last checkpointed WAL ID. + page, err := db.readPage(nil, 0) + if err != nil { + return err + } + walID := readMetaWALID(page) + + // Determine the high water mark for WAL pages that can be copied. + minActiveWALID := db.minActiveWALID() + + // Loop over each transaction + walID++ + pageMap := immutable.NewMap(&uint32Hasher{}) + for { + // Determine last page of transaction. + metaWALID, metaFlags, err := db.findNextWALMetaPage(walID) + if err == io.EOF { + break + } else if err != nil { + return err + } + + // If transaction was rolled back, skip it. + if metaFlags&MetaPageFlagCommit == 0 { + walID = metaWALID + 1 + continue + } + + // Loop over pages in the tranasction. + for ; walID <= metaWALID; walID++ { + canCheckpoint := minActiveWALID == 0 || walID <= minActiveWALID + + page, err := db.readWALPage(walID) + if err != nil { + return err + } + isBitmapHeader := IsBitmapHeader(page) + + // Determine page number. Meta pages are always on zero & bitmap + // headers specify the page number of the next page in the WAL. + // All other pages have their page number in the page data. + var pgno uint32 + if isBitmapHeader { + pgno, walID = readPageNo(page), walID+1 // skip next page + } else if !IsMetaPage(page) { + pgno = readPageNo(page) + } + + // If we can no longer checkpoint, map the page number to the WAL page. + if !canCheckpoint { + pageMap = pageMap.Set(pgno, walID) + continue + } + + // Ensure we actually read the bitmap data in when we checkpoint. + // NOTE: The walID variable is incremented above in the pgno check. + if isBitmapHeader { + if page, err = db.readWALPage(walID); err != nil { + return err + } + } + + // Write page data into main db file. + if err := db.writePage(pgno, page); err != nil { + return err + } + } + } + + // Remove WAL segments that have been checkpointed. + for len(db.segments) > 1 { + segment := db.segments[0] + if minActiveWALID != 0 && segment.MaxWALID() >= minActiveWALID { + break + } + + if err := segment.Close(); err != nil { + return err + } + db.segments, db.segments[0] = db.segments[1:], nil + } + + db.pageMap = pageMap + return nil +} + +func (db *DB) findNextWALMetaPage(walID int64) (metaWALID int64, metaFlags uint32, err error) { + maxWALID := db.maxWALID() + + for ; walID <= maxWALID; walID++ { + // Read page data from WAL and return if it is a meta page (either commit or rollback) + page, err := db.readWALPage(walID) + if err != nil { + return walID, metaFlags, err + } else if IsMetaPage(page) { + return walID, readFlags(page), nil + } + + // Skip over next page if this is a bitmap header. + if IsBitmapHeader(page) { + walID++ + } + } + + return -1, 0, io.EOF +} + +// minActiveWALID returns the lowest WAL ID in use by any active transaction. +// Returns 0 if no transactions are active. +func (db *DB) minActiveWALID() int64 { + var walID int64 + for tx := range db.txs { + if walID == 0 || walID > tx.walID { + walID = tx.walID + } + } + return walID +} + +// ActiveWALSegment returns the most recent WAL segment. +func (db *DB) ActiveWALSegment() *WALSegment { + db.mu.RLock() + defer db.mu.RUnlock() + return db.activeWALSegment() +} + +func (db *DB) activeWALSegment() *WALSegment { + if len(db.segments) == 0 { + return nil + } + return db.segments[len(db.segments)-1] +} + +// MinWALID returns the lowest WAL ID available in the WAL. +func (db *DB) MinWALID() int64 { + db.mu.RLock() + defer db.mu.RUnlock() + return db.minWALID() +} + +func (db *DB) minWALID() int64 { + if len(db.segments) == 0 { + return 0 + } + return db.segments[0].MinWALID() +} + +// MaxWALID returns the highest WAL ID available in the WAL. +func (db *DB) MaxWALID() int64 { + db.mu.RLock() + defer db.mu.RUnlock() + return db.maxWALID() +} + +func (db *DB) maxWALID() int64 { + if len(db.segments) == 0 { + return 0 + } + s := db.segments[len(db.segments)-1] + return s.MaxWALID() +} + +// WALPageN returns the number of pages across all segments. +func (db *DB) WALPageN() int64 { + db.mu.RLock() + defer db.mu.RUnlock() + + var n int64 + for _, s := range db.segments { + n += int64(s.PageN()) + } + return n +} + +// SyncWAL flushes the active segment to disk. +func (db *DB) SyncWAL() error { + if s := db.ActiveWALSegment(); s != nil { + return s.Sync() + } + return nil +} + +// readWALPage reads a single page at the given WAL ID. +func (db *DB) readWALPage(walID int64) ([]byte, error) { + // TODO(BBJ): Binary search for segment. + for _, s := range db.segments { + if walID >= s.MinWALID() && walID <= s.MaxWALID() { + return s.ReadWALPage(walID) + } + } + return nil, fmt.Errorf("cannot find segment containing WAL page: %d", walID) +} + +func (db *DB) writeWALPage(page []byte, isMeta bool) (walID int64, err error) { + if err := db.ensureWritableWALSegment(); err != nil { + return 0, err + } + return db.activeWALSegment().WriteWALPage(page, isMeta) +} + +func (db *DB) writeBitmapPage(pgno uint32, page []byte) (walID int64, err error) { + if err := db.ensureWritableWALSegment(); err != nil { + return 0, err + } + + // Write header page for next bitmap page. + buf := make([]byte, PageSize) + writePageNo(buf[:], pgno) + writeFlags(buf[:], PageTypeBitmapHeader) + // TODO(BBJ): Write checksum. + if _, err := db.activeWALSegment().WriteWALPage(buf, false); err != nil { + return 0, fmt.Errorf("write bitmap header: %w", err) + } + + // Write the bitmap page and return its WALID. + return db.activeWALSegment().WriteWALPage(page, false) +} + +func (db *DB) ensureWritableWALSegment() error { + if s := db.activeWALSegment(); s != nil && s.Size() < MaxWALSegmentFileSize { + return nil + } + return db.addWALSegment() +} + +// addWALSegment appends a new, writable segment and closing an existing segments for write. +func (db *DB) addWALSegment() error { + // Close previous last segment for writes. + base := int64(1) + if s := db.activeWALSegment(); s != nil { + base = s.MaxWALID() + 1 + if err := s.CloseForWrite(); err != nil { + return err + } + } + + // Create new segment file. + s := NewWALSegment(filepath.Join(db.WALPath(), FormatWALSegmentPath(base))) + if err := s.Open(); err != nil { + return fmt.Errorf("add wal segment: %w", err) + } + db.segments = append(db.segments, s) + + return nil +} + +// Close closes the database. +func (db *DB) Close() (err error) { + // TODO(bbj): Add wait group to hang until last Tx is complete. + + db.mu.Lock() + defer db.mu.Unlock() + + // Wait for writer lock. + db.rwmu.Lock() + defer db.rwmu.Unlock() + + db.opened = false + + // Close mmap handle. + if db.data != nil { + if e := syswrap.Munmap(db.data); e != nil && err == nil { + err = e + } + db.data = nil + } + + // Close writer handler. + if db.file != nil { + if e := db.file.Close(); e != nil && err == nil { + err = e + } + db.file = nil + } + + if e := db.closeWALSegments(); e != nil && err == nil { + err = e + } + + return err +} + +// closeWALSegments closes the WAL and all its segments. +func (db *DB) closeWALSegments() (err error) { + for _, s := range db.segments { + if e := s.Close(); e != nil && err == nil { + err = e + } + } + return err +} + +// Size returns the size of the database & WAL, in bytes. +func (db *DB) Size() (int64, error) { + db.mu.RLock() + defer db.mu.RUnlock() + + fi, err := os.Stat(db.Path) + if err != nil { + return 0, err + } + return db.walSize() + fi.Size(), nil +} + +// WALSize returns the size of all WAL segments, in bytes. +func (db *DB) WALSize() int64 { + db.mu.RLock() + defer db.mu.RUnlock() + return db.walSize() +} + +func (db *DB) walSize() int64 { + var sz int64 + for _, s := range db.segments { + sz += s.Size() + } + return sz +} + +// WALSegments returns the WAL segments currently on the DB. +// This should only be used for debugging & testing purposes. +func (db *DB) WALSegments() []*WALSegment { + db.mu.RLock() + defer db.mu.RUnlock() + return db.segments +} + +// init initializes a new database file. +func (db *DB) init() error { + if err := db.initMetaPage(); err != nil { + return fmt.Errorf("meta: %w", err) + } else if err := db.initRootRecordPage(); err != nil { + return fmt.Errorf("root record page: %w", err) + } else if err := db.initFreelistPage(); err != nil { + return fmt.Errorf("freelist page: %w", err) + } + return nil +} + +// initMetaPage initializes the meta page. +func (db *DB) initMetaPage() error { + page := make([]byte, PageSize) + writeMetaMagic(page) + writeMetaPageN(page, 3) + writeMetaRootRecordPageNo(page, 1) + writeMetaFreelistPageNo(page, 2) + _, err := db.file.WriteAt(page, 0*PageSize) + return err +} + +// initRootRecordPage initializes the initial root record page. +func (db *DB) initRootRecordPage() error { + page := make([]byte, PageSize) + writePageNo(page, 1) + writeFlags(page, PageTypeRootRecord) + _, err := db.file.WriteAt(page, 1*PageSize) + return err +} + +// initFreelistPage initializes the initial freelist btree page. +func (db *DB) initFreelistPage() error { + page := make([]byte, PageSize) + writePageNo(page, 2) + writeFlags(page, PageTypeLeaf) + _, err := db.file.WriteAt(page, 2*PageSize) + return err +} + +// Begin starts a new transaction. +func (db *DB) Begin(writable bool) (_ *Tx, err error) { + // TODO(BBJ): Acquire write lock if writable. + + db.mu.Lock() + defer db.mu.Unlock() + + if !db.opened { + return nil, ErrClosed + } + + tx := &Tx{db: db, pageMap: db.pageMap, writable: writable} + + // Ensure only one writable transaction at a time. + if tx.writable { + db.rwmu.Lock() + } + + // Copy meta page into transaction's buffer. + // This page is only written at the end of a dirty transaction. + page, err := db.readPage(db.pageMap, 0) + if err != nil { + _ = tx.Rollback() + return nil, err + } + copy(tx.meta[:], page) + + // Attach starting WAL ID to transaction. + tx.walID = readMetaWALID(tx.meta[:]) + + // Track transaction with the DB. + db.txs[tx] = struct{}{} + + return tx, nil +} + +// removeTx removes an active transaction from the database. +func (db *DB) removeTx(tx *Tx) error { + // Release writer lock if tx is writable. + if tx.writable { + tx.db.rwmu.Unlock() + } + + db.mu.Lock() + defer db.mu.Unlock() + + // Write pages from WAL to DB. + // TODO(bbj): Move this to an async goroutine. + if err := db.checkpoint(); err != nil { + return err + } + + delete(tx.db.txs, tx) + + // Disassociate from db. + tx.db = nil + + return nil +} + +// Check performs an integrity check. +func (db *DB) Check() error { + tx, err := db.Begin(false) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + return tx.Check() +} + +// writePage writes a page to the data file. +func (db *DB) writePage(pgno uint32, page []byte) error { + _, err := db.file.WriteAt(page, int64(pgno)*PageSize) + return err +} + +func (db *DB) readPage(pageMap *immutable.Map, pgno uint32) ([]byte, error) { + // Check if page is currently in WAL. + if pageMap != nil { + if walID, ok := pageMap.Get(pgno); ok { + return db.readWALPage(walID.(int64)) + } + } + + // Otherwise read from the data file. + offset := int64(pgno) * PageSize + return db.data[offset : offset+PageSize], nil +} diff --git a/rbf/db_test.go b/rbf/db_test.go new file mode 100644 index 000000000..f68b0f26e --- /dev/null +++ b/rbf/db_test.go @@ -0,0 +1,132 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf_test + +import ( + "math/rand" + "os" + "testing" + + "github.com/pilosa/pilosa/v2/rbf" +) + +func TestDB_Open(t *testing.T) { + db := NewDB() + if err := db.Open(); err != nil { + t.Fatal(err) + } else if err := db.Close(); err != nil { + t.Fatal(err) + } +} + +func TestDB_Checkpoint(t *testing.T) { + if testing.Short() { + t.Skip("-short enabled, skipping") + } + + db := MustOpenDB(t) + defer MustCloseDB(t, db) + + // Create bitmap. + if tx, err := db.Begin(true); err != nil { + t.Fatal(err) + } else if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } else if err := tx.Commit(); err != nil { + t.Fatal(err) + } + + // Create a bunch of transactions to generate WAL segments. + rand := rand.New(rand.NewSource(0)) + for i := 0; i < 1000; i++ { + if tx, err := db.Begin(true); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", rand.Uint64()); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", rand.Uint64()); err != nil { + t.Fatal(err) + } else if err := tx.Commit(); err != nil { + t.Fatal(err) + } + } + + // Ensure there is no more than two WAL segments. + if n := len(db.WALSegments()); n > 2 { + t.Fatalf("expected two or fewer WAL segments, got %d", n) + } +} + +func TestDB_Recovery(t *testing.T) { + // Ensure a bitmap header written without a bitmap is truncated. + t.Run("TruncPartialWALBitmap", func(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + + a := make([]uint64, rbf.ArrayMaxSize+100) + for i := range a { + a[i] = uint64(i) + } + + // Create bitmap & generate enough values to create a bitmap container. + if tx, err := db.Begin(true); err != nil { + t.Fatal(err) + } else if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", a...); err != nil { + t.Fatal(err) + } else if err := tx.Commit(); err != nil { + t.Fatal(err) + } + + // Add one additional bit in a second transaction. + if tx, err := db.Begin(true); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", uint64(len(a))); err != nil { + t.Fatal(err) + } else if err := tx.Commit(); err != nil { + t.Fatal(err) + } + + // Close database & truncate WAL to remove commit page & bitmap data page. + segment := db.ActiveWALSegment() + if err := db.Close(); err != nil { + t.Fatal(err) + } else if err := os.Truncate(segment.Path(), segment.Size()-(2*rbf.PageSize)); err != nil { + t.Fatal(err) + } + + // Reopen database. + newDB := rbf.NewDB(db.Path) + if err := newDB.Open(); err != nil { + t.Fatal(err) + } + defer MustCloseDB(t, newDB) + + // Verify last insert was not added. + tx, err := newDB.Begin(true) + if err != nil { + t.Fatal(err) + } + defer MustRollback(t, tx) + + if exists, err := tx.Contains("x", uint64(len(a))); exists || err != nil { + t.Fatalf("Contains()=<%v,%#v>", exists, err) + } else if exists, err := tx.Contains("x", uint64(len(a)-1)); !exists || err != nil { + t.Fatalf("Contains()=<%v,%#v>", exists, err) + } else if err := tx.Rollback(); err != nil { + t.Fatal(err) + } + }) +} diff --git a/rbf/dot.go b/rbf/dot.go new file mode 100644 index 000000000..38b386234 --- /dev/null +++ b/rbf/dot.go @@ -0,0 +1,105 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf + +import ( + "fmt" + "io" +) + +func dotCell(b []byte, parent string, writer io.Writer) { + pgno := readPageNo(b) + if pgno == Magic32() { + fmt.Fprintf(writer, "==META\n") + return + } + + flags := readFlags(b) + cellN := readCellN(b) + + switch { + case flags&PageTypeLeaf != 0: + fmt.Fprintf(writer, "cell%d [ shape=none label=<\n", pgno) + fmt.Fprintf(writer, "\n") + for i := 0; i < cellN; i++ { + cell := readLeafCell(b, i) + switch cell.Type { + case ContainerTypeArray: + //fmt.Fprintf(os.Stderr, "[%d]: key=%d type=array n=%d elems=%v\n", i, cell.Key, cell.N, toArray16(cell.Data)) + fmt.Fprintf(writer, "\n", i, cell.Key, cell.N) + case ContainerTypeRLE: + fmt.Fprintf(writer, "\n", i, cell.Key, cell.N) + default: + fmt.Fprintf(writer, "\n", i, cell.Key, cell.Type, cell.N) + } + } + fmt.Fprintf(writer, "
CELL
[%d]: key=%d type=array n=%d
[%d]: key=%d type=rle n=%d
[%d]: key=%d type=unknown<%d> n=%d
>]\n") + fmt.Fprintf(writer, "%s -> cell%d\n", parent, pgno) + default: + //should not happen + fmt.Fprintf(writer, "==!PAGE %d flags=%d\n", pgno, flags) + } +} + +// dumpdot recursively writes the tree representation starting from a given page to STDERR. +func dumpdot(tx *Tx, pgno uint32, parent string, writer io.Writer) { + page, err := tx.readPage(pgno) + if err != nil { + panic(err) + } + + if IsMetaPage(page) { + //fmt.Fprintf(writer, "META(%d)\n", pgno) + //fmt.Fprintf(writer, "└── \n") + //treedump(tx, readMetaFreelistPageNo(page), indent+" ") + + visitor := func(pgno uint32, records []*RootRecord) { + rr := fmt.Sprintf("rr%d", pgno) + fmt.Fprintf(writer, "%s[label=\"ROOT RECORD(%d): n=%d\"]\n", rr, pgno, len(records)) + for _, record := range records { + root := fmt.Sprintf("root%d", record.Pgno) + fmt.Fprintf(writer, "%s[label=\"ROOT(%d)| %s\"]\n%s->%s\n", root, record.Pgno, record.Name, rr, root) + parent := fmt.Sprintf("root%d", record.Pgno) + dumpdot(tx, record.Pgno, parent, writer) + + } + } + rrdump(tx, readMetaRootRecordPageNo(page), visitor) + + return + } + + // Handle + switch typ := readFlags(page); typ { + case PageTypeBranch: + p := fmt.Sprintf("branch%d", pgno) + fmt.Fprintf(writer, "%s[label=\"BRANCH(%d)| n=%d\"]\n %s->%s\n", p, pgno, readCellN(page), parent, p) + for i, n := 0, readCellN(page); i < n; i++ { + cell := readBranchCell(page, i) + if cell.Flags&ContainerTypeBitmap == 0 { // leaf/branch child page + dumpdot(tx, cell.Pgno, p, writer) + } else { + b := fmt.Sprintf("bm%d", cell.Pgno) + fmt.Fprintf(writer, "%s[label=\"BITMAP(%d)\"]\n %s -> %s\n", b, cell.Pgno, p, b) + } + } + case PageTypeLeaf: + p := fmt.Sprintf("leaf%d", pgno) + fmt.Fprintf(writer, "%s[label=\"LEAF(%d)| n=%d\"]\n%s->%s\n", p, pgno, readCellN(page), parent, p) + dotCell(page, p, writer) + default: + panic(err) + } +} diff --git a/rbf/internal_test.go b/rbf/internal_test.go new file mode 100644 index 000000000..985642c0c --- /dev/null +++ b/rbf/internal_test.go @@ -0,0 +1,26 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf + +import "testing" + +// This function exists to mark debugging helper function as "used" by the linter. +func TestUsed(t *testing.T) { + t.Skip("This function is always skipped") + dump(nil) + hexdump(nil) + pagedump(nil, "", nil) + treedump(nil, 0, "", nil) +} diff --git a/rbf/os.go b/rbf/os.go new file mode 100644 index 000000000..7b2627f11 --- /dev/null +++ b/rbf/os.go @@ -0,0 +1,22 @@ +// Copyright 2017 Pilosa Corp. +// +// 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. + +// +build !386 + +package rbf + +// DefaultMaxSize is the default mmap size and therefore the maximum allowed +// size of the database. The size can be increased by updating the DB.MaxSize +// and reopening the database. This setting mainly affects virtual space usage. +const DefaultMaxSize = 100 * (1 << 30) // 100GB diff --git a/rbf/os_386.go b/rbf/os_386.go new file mode 100644 index 000000000..b23457dbb --- /dev/null +++ b/rbf/os_386.go @@ -0,0 +1,20 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf + +// DefaultMaxSize is the default mmap size and therefore the maximum allowed +// size of the database. The size can be increased by updating the DB.MaxSize +// and reopening the database. This setting mainly affects virtual space usage. +const DefaultMaxSize = 256 * (1 << 20) // 256MB diff --git a/rbf/rbf.go b/rbf/rbf.go new file mode 100644 index 000000000..1b5f4e8d6 --- /dev/null +++ b/rbf/rbf.go @@ -0,0 +1,620 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf implements the roaring b-tree file format. +package rbf + +import ( + "bytes" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "io" + "unsafe" + + "github.com/pilosa/pilosa/v2/shardwidth" +) + +const ( + // Magic is the first 4 bytes of the RBF file. + Magic = "\xFFRBF" + + // PageSize is the fixed size for every database page. + PageSize = 8192 + + // ShardWidth represents the number of bits per shard. + ShardWidth = 1 << shardwidth.Exponent + + // RowValueMask masks the low bits for a row. + RowValueMask = ShardWidth - 1 + + // ArrayMaxSize represents the maximum size of array containers. + // This is sligtly less than roaring to accommodate the page header. + ArrayMaxSize = 4080 + + // RLEMaxSize represents the maximum size of run length encoded containers. + RLEMaxSize = 2040 +) + +// Page types. +const ( + PageTypeRootRecord = 1 + PageTypeLeaf = 2 + PageTypeBranch = 4 + PageTypeBitmapHeader = 8 // Only used by the WAL for marking next page +) + +// Meta commit/rollback flags. +const ( + MetaPageFlagCommit = 1 + MetaPageFlagRollback = 2 +) + +// Container types. +const ( + ContainerTypeNone = iota + ContainerTypeArray + ContainerTypeRLE + ContainerTypeBitmap +) + +const ( + rootRecordPageHeaderSize = 12 + rootRecordHeaderSize = 4 + 2 // pgno, len(name) + leafCellHeaderSize = 8 + 4 + 4 // key, type, count + branchCellSize = 8 + 4 + 4 // key, flags, pgno +) + +var ( + ErrTxClosed = errors.New("transaction closed") + ErrTxNotWritable = errors.New("transaction not writable") + ErrBitmapNameRequired = errors.New("bitmap name required") +) + +// Debug is just a temporary flag used for debugging. +var Debug bool + +// Magic32 returns the magic bytes as a big endian encoded uint32. +func Magic32() uint32 { + return binary.BigEndian.Uint32([]byte(Magic)) +} + +// Meta page helpers + +// IsMetaPage returns true if page is a meta page. +func IsMetaPage(page []byte) bool { + return bytes.Equal(readMetaMagic(page), []byte(Magic)) +} + +func readMetaMagic(page []byte) []byte { return page[0:4] } +func writeMetaMagic(page []byte) { copy(page, Magic) } + +func readMetaPageN(page []byte) uint32 { return binary.BigEndian.Uint32(page[8:]) } +func writeMetaPageN(page []byte, n uint32) { binary.BigEndian.PutUint32(page[8:], n) } + +func readMetaWALID(page []byte) int64 { return int64(binary.BigEndian.Uint64(page[12:])) } +func writeMetaWALID(page []byte, walID int64) { binary.BigEndian.PutUint64(page[12:], uint64(walID)) } + +func readMetaRootRecordPageNo(page []byte) uint32 { return binary.BigEndian.Uint32(page[20:]) } +func writeMetaRootRecordPageNo(page []byte, pgno uint32) { binary.BigEndian.PutUint32(page[20:], pgno) } + +func readMetaFreelistPageNo(page []byte) uint32 { return binary.BigEndian.Uint32(page[24:]) } +func writeMetaFreelistPageNo(page []byte, pgno uint32) { binary.BigEndian.PutUint32(page[24:], pgno) } + +// func readMetaChecksum(page []byte) uint32 { +// return binary.BigEndian.Uint32(page[PageSize-4 : PageSize]) +// } + +// func writeMetaChecksum(page []byte, chksum uint32) { +// binary.BigEndian.PutUint32(page[PageSize-4:PageSize], chksum) +// } + +// Root record page helpers + +func readRootRecordOverflowPgno(page []byte) uint32 { return binary.BigEndian.Uint32(page[8:]) } +func writeRootRecordOverflowPgno(page []byte, pgno uint32) { + binary.BigEndian.PutUint32(page[8:], pgno) +} + +func readRootRecords(page []byte) (records []*RootRecord, err error) { + for data := page[rootRecordPageHeaderSize:]; ; { + var rec *RootRecord + if rec, data, err = ReadRootRecord(data); err != nil { + return records, err + } else if rec == nil { + return records, nil + } + records = append(records, rec) + } +} + +func writeRootRecords(page []byte, records []*RootRecord) (remaining []*RootRecord, err error) { + data := page[rootRecordPageHeaderSize:] + for i, rec := range records { + if data, err = WriteRootRecord(data, rec); err == io.ErrShortBuffer { + return records[i:], nil + } else if err != nil { + return records[i:], err + } + } + return nil, nil +} + +// Branch & leaf page helpers + +func readPageNo(page []byte) uint32 { return binary.BigEndian.Uint32(page[0:4]) } +func writePageNo(page []byte, v uint32) { binary.BigEndian.PutUint32(page[0:4], v) } + +func readFlags(page []byte) uint32 { return binary.BigEndian.Uint32(page[4:8]) } +func writeFlags(page []byte, v uint32) { binary.BigEndian.PutUint32(page[4:8], v) } + +func readCellN(page []byte) int { return int(binary.BigEndian.Uint16(page[8:10])) } +func writeCellN(page []byte, v int) { binary.BigEndian.PutUint16(page[8:10], uint16(v)) } + +func readCellOffset(page []byte, i int) int { + assert(i < readCellN(page)) + return int(binary.BigEndian.Uint16(page[10+(i*2):])) +} + +func writeCellOffset(page []byte, i int, v int) { + binary.BigEndian.PutUint16(page[10+(i*2):], uint16(v)) +} + +func dataOffset(n int) int { + return align8(10 + (n * 2)) +} + +func IsBitmapHeader(page []byte) bool { + // TODO(BBJ): Verify checksum. + return readFlags(page) == PageTypeBitmapHeader +} + +type RootRecord struct { + Name string + Pgno uint32 +} + +// ReadRootRecord reads the page number & name for a root record. +// If there is not enough space or the pgno is zero then a nil record is returned. +// Returns the remaining buffer. +func ReadRootRecord(data []byte) (rec *RootRecord, remaining []byte, err error) { + // Ensure there is enough space to read the pgno & name length. + if len(data) < rootRecordHeaderSize { + return nil, data, nil + } + + // Read root page number. + rec = &RootRecord{} + rec.Pgno = binary.BigEndian.Uint32(data) + if rec.Pgno == 0 { + return nil, data, nil + } + data = data[4:] + + // Read name length. + sz := int(binary.BigEndian.Uint16(data)) + data = data[2:] + if len(data) < sz { + return nil, data, fmt.Errorf("short root record buffer") + } + + // Read name and allocate as string on heap. + rec.Name, data = string(data[:sz]), data[sz:] + + return rec, data, nil +} + +// WriteRootRecord writes a root record with the pgno & name. +// Returns io.ErrShortBuffer if there is not enough space. +func WriteRootRecord(data []byte, rec *RootRecord) (remaining []byte, err error) { + // Ensure record data is valid. + if rec == nil { + return data, fmt.Errorf("root record required") + } else if rec.Name == "" { + return data, fmt.Errorf("root record name required") + } else if rec.Pgno == 0 { + return data, fmt.Errorf("invalid root record pgno: %d", rec.Pgno) + } + + // Ensure there is enough space to write the full record. + if len(data) < rootRecordHeaderSize+len(rec.Name) { + return data, io.ErrShortBuffer + } + + // Write root page number. + binary.BigEndian.PutUint32(data, rec.Pgno) + data = data[4:] + + // Write name length. + binary.BigEndian.PutUint16(data, uint16(len(rec.Name))) + data = data[2:] + + // Write name. + copy(data, rec.Name) + data = data[len(rec.Name):] + + return data, nil +} + +func align8(offset int) int { + if offset%8 == 0 { + return offset + } + return offset + (8 - (offset & 0x7)) +} + +// leafCell represents a leaf cell. +type leafCell struct { + Key uint64 + Type int + N int + Data []byte +} + +// Size returns the size of the leaf cell, in bytes. +func (c *leafCell) Size() int { + if c.Type == ContainerTypeBitmap { + return PageSize + } + return leafCellHeaderSize + len(c.Data) +} + +// Bitmap returns a bitmap representation of the cell data. +func (c *leafCell) Bitmap() []uint64 { + switch c.Type { + case ContainerTypeArray: + buf := make([]uint64, PageSize/8) + for _, v := range toArray16(c.Data) { + buf[v/64] |= 1 << uint64(v%64) + } + return buf + case ContainerTypeRLE: + buf := make([]uint64, PageSize/8) + for _, iv := range toInterval16(c.Data) { + w1, w2 := iv.Start/64, iv.Last/64 + b1, b2 := iv.Start&63, iv.Last&63 + m1 := (uint64(1) << b1) - 1 + m2 := (((uint64(1) << b2) - 1) << 1) | 1 + if w1 == w2 { + buf[w1] |= (m2 &^ m1) + continue + } + buf[w2] |= m2 + buf[w1] |= ^m1 + words := buf[w1+1 : w2] + for i := range words { + words[i] = ^uint64(0) + } + } + return buf + case ContainerTypeBitmap: + return toArray64(c.Data) + default: + panic(fmt.Sprintf("invalid container type: %d", c.Type)) + } +} + +// Values returns a slice of 16-bit values from a container. +func (c *leafCell) Values() []uint16 { + switch c.Type { + case ContainerTypeArray: + return toArray16(c.Data) + case ContainerTypeRLE: + //a := make([]uint16, c.N) + a := make([]uint16, ArrayMaxSize) + n := int32(0) + for _, r := range toInterval16(c.Data) { + for v := int(r.Start); v <= int(r.Last); v++ { + a[n] = uint16(v) + n++ + } + } + a = a[:n] + return a + case ContainerTypeBitmap: + a := make([]uint16, 0, ArrayMaxSize) + for i, v := range toArray64(c.Data) { + for j := uint(0); j < 64; j++ { + if v&(1<= 0) + + offset := readCellOffset(page, i) + var cell branchCell + cell.Key = *(*uint64)(unsafe.Pointer(&page[offset])) + cell.Flags = *(*uint32)(unsafe.Pointer(&page[offset+8])) + cell.Pgno = *(*uint32)(unsafe.Pointer(&page[offset+12])) + return cell +} + +func readBranchCells(page []byte) []branchCell { + n := readCellN(page) + cells := make([]branchCell, n, n+1) + for i := 0; i < n; i++ { + cells[i] = readBranchCell(page, i) + } + return cells +} + +func writeBranchCell(page []byte, i, offset int, cell branchCell) { + writeCellOffset(page, i, offset) + *(*uint64)(unsafe.Pointer(&page[offset+0])) = cell.Key + *(*uint32)(unsafe.Pointer(&page[offset+8])) = uint32(cell.Flags) + *(*uint32)(unsafe.Pointer(&page[offset+12])) = uint32(cell.Pgno) +} + +func highbits(v uint64) uint64 { return v >> 16 } +func lowbits(v uint64) uint16 { return uint16(v & 0xFFFF) } + +// search implements a binary search similar to sort.Search(), however, +// it returns the position as well as whether an exact match was made. +// +// The return value from f should be -1 for less than, 0 for equal, and 1 for +// greater than. +func search(n int, f func(int) int) (index int, exact bool) { + i, j := 0, n + for i < j { + h := int(uint(i+j) >> 1) + if cmp := f(h); cmp == 0 { + return h, true + } else if cmp > 0 { + i = h + 1 + } else { + j = h + } + } + return i, false +} + +func hexdump(b []byte) { println(hex.Dump(b)) } + +func pagedump(b []byte, indent string, writer io.Writer) { + pgno := readPageNo(b) + if pgno == Magic32() { + fmt.Fprintf(writer, "==META\n") + return + } + + flags := readFlags(b) + cellN := readCellN(b) + + // NOTE(BBJ): There's no way to tell if a page is a bitmap container with + // the page alone so this will output !PAGE for bitmap pages & invalid pages. + switch { + case flags&PageTypeLeaf != 0: + for i := 0; i < cellN; i++ { + cell := readLeafCell(b, i) + switch cell.Type { + case ContainerTypeArray: + //fmt.Fprintf(os.Stderr, "[%d]: key=%d type=array n=%d elems=%v\n", i, cell.Key, cell.N, toArray16(cell.Data)) + fmt.Fprintf(writer, "%s[%d]: key=%d type=array n=%d \n", indent, i, cell.Key, cell.N) + case ContainerTypeRLE: + fmt.Fprintf(writer, "%s[%d]: key=%d type=rle n=%d\n", indent, i, cell.Key, cell.N) + case ContainerTypeBitmap: + fmt.Fprintf(writer, "%s[%d]: key=%d type=bitmap n=%d\n", indent, i, cell.Key, cell.N) + default: + fmt.Fprintf(writer, "%s[%d]: key=%d type=unknown<%d> n=%d\n", indent, i, cell.Key, cell.Type, cell.N) + } + } + case flags&PageTypeBranch != 0: + fmt.Fprintf(writer, "==BRANCH pgno=%d flags=%d n=%d\n", pgno, flags, cellN) + for i := 0; i < cellN; i++ { + cell := readBranchCell(b, i) + fmt.Fprintf(writer, "[%d]: key=%d flags=%d pgno=%d\n", i, cell.Key, cell.Flags, cell.Pgno) + } + default: + fmt.Fprintf(writer, "==!PAGE %d flags=%d\n", pgno, flags) + } +} + +// treedump recursively writes the tree representation starting from a given page to STDERR. +func treedump(tx *Tx, pgno uint32, indent string, writer io.Writer) { + page, err := tx.readPage(pgno) + if err != nil { + panic(err) + } + + if IsMetaPage(page) { + fmt.Fprintf(writer, "META(%d)\n", pgno) + fmt.Fprintf(writer, "└── \n") + //treedump(tx, readMetaFreelistPageNo(page), indent+" ") + + visitor := func(pgno uint32, records []*RootRecord) { + fmt.Fprintf(writer, "└── ROOT RECORD(%d): n=%d\n", pgno, len(records)) + for _, record := range records { + fmt.Fprintf(writer, "└── ROOT(%q) %d\n", record.Name, record.Pgno) + treedump(tx, record.Pgno, indent+" ", writer) + + } + } + rrdump(tx, readMetaRootRecordPageNo(page), visitor) + + return + } + + // Handle + switch typ := readFlags(page); typ { + case PageTypeBranch: + fmt.Fprintf(writer, "%s BRANCH(%d) n=%d\n", fmtindent(indent), pgno, readCellN(page)) + + for i, n := 0, readCellN(page); i < n; i++ { + cell := readBranchCell(page, i) + if cell.Flags&ContainerTypeBitmap == 0 { // leaf/branch child page + treedump(tx, cell.Pgno, " "+indent, writer) + } else { + fmt.Fprintf(writer, "%s BITMAP(%d)\n", fmtindent(" "+indent), cell.Pgno) + } + } + case PageTypeLeaf: + fmt.Fprintf(writer, "%s LEAF(%d) n=%d\n", fmtindent(indent), pgno, readCellN(page)) + pagedump(page, fmtindent(" "+indent), writer) + default: + panic(err) + } +} + +func rrdump(tx *Tx, pgno uint32, v func(uint32, []*RootRecord)) { + for pgno := readMetaRootRecordPageNo(tx.meta[:]); pgno != 0; { + page, err := tx.readPage(pgno) + if err != nil { + panic(err) + } + + // Read all records on the page. + a, err := readRootRecords(page) + if err != nil { + panic(err) + } + v(pgno, a) + // Read next overflow page number. + pgno = readRootRecordOverflowPgno(page) + } +} + +func fmtindent(s string) string { + if s == "" { + return "" + } + return s + "└──" +} + +// RowValues returns a list of integer values from a row bitmap. +func RowValues(b []uint64) []uint64 { + a := make([]uint64, 0) + for i, v := range b { + for j := uint(0); j < 64; j++ { + if v&(1<> 16 } +func lowbits(v uint64) uint16 { return uint16(v & 0xFFFF) } + +// is32Bit returns true if the architecture is 32-bit. +func is32Bit() bool { return runtime.GOARCH == "386" } diff --git a/rbf/tx.go b/rbf/tx.go new file mode 100644 index 000000000..a8393c4e9 --- /dev/null +++ b/rbf/tx.go @@ -0,0 +1,672 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf + +import ( + "fmt" + "io" + "sort" + + "github.com/benbjohnson/immutable" + "github.com/pilosa/pilosa/v2/roaring" +) + +// Tx represents a transaction. +type Tx struct { + db *DB // parent db + meta [PageSize]byte // copy of current meta page + walID int64 // max WAL ID at start of tx + pageMap *immutable.Map // mapping of database pages to WAL IDs + writable bool // if true, tx can write + dirty bool // if true, changes have been made +} + +// Commit completes the transaction and persists data changes. +func (tx *Tx) Commit() error { + if tx.db == nil { + return ErrTxClosed + } + + // If any pages have been written, ensure we write a new meta page with + // the commit flag to mark the end of the transaction. + if tx.dirty { + if err := tx.writeMetaPage(MetaPageFlagCommit); err != nil { + return err + } else if err := tx.db.SyncWAL(); err != nil { + return err + } + tx.db.pageMap = tx.pageMap + } + + // Disconnect transaction from DB. + return tx.db.removeTx(tx) +} + +func (tx *Tx) Rollback() error { + if tx.db == nil { + return ErrTxClosed + } + + // If any pages have been written, ensure we write a new meta page with + // the rollback flag to mark the end of the transaction. This allows us to + // discard pages in the transaction during playback of the WAL on open. + if tx.dirty { + if err := tx.writeMetaPage(MetaPageFlagRollback); err != nil { + return err + } else if err := tx.db.SyncWAL(); err != nil { + return err + } + } + + // Disconnect transaction from DB. + return tx.db.removeTx(tx) +} + +// Root returns the root page number for a bitmap. Returns 0 if the bitmap does not exist. +func (tx *Tx) Root(name string) (uint32, error) { + records, err := tx.rootRecords() + if err != nil { + return 0, err + } + + i := sort.Search(len(records), func(i int) bool { return records[i].Name >= name }) + if i >= len(records) || records[i].Name != name { + return 0, fmt.Errorf("bitmap not found: %q", name) + } + return records[i].Pgno, nil +} + +// CreateBitmap creates a new empty bitmap with the given name. +// Returns an error if the bitmap already exists. +func (tx *Tx) CreateBitmap(name string) error { + if tx.db == nil { + return ErrTxClosed + } else if !tx.writable { + return ErrTxNotWritable + } else if name == "" { + return ErrBitmapNameRequired + } + + // Read list of root records. + records, err := tx.rootRecords() + if err != nil { + return err + } + + // Find btree by name. Exit if already exists. + index := sort.Search(len(records), func(i int) bool { return records[i].Name >= name }) + if index < len(records) && records[index].Name == name { + return fmt.Errorf("bitmap already exists: %q", name) + } + //fmt.Println("CREATE BITMAP", name, index) + + // Allocate new root page. + pgno, err := tx.allocate() + //fmt.Println("CREATE BITMAP @ PGNO", pgno) + if err != nil { + return err + } + + // Write root page. + page := make([]byte, PageSize) + writePageNo(page, pgno) + writeFlags(page, PageTypeLeaf) + writeCellN(page, 0) + if err := tx.writePage(page); err != nil { + return err + } + + // Insert into correct index. + records = append(records, nil) + copy(records[index+1:], records[index:]) + records[index] = &RootRecord{Name: name, Pgno: pgno} + if err := tx.writeRootRecordPages(records); err != nil { + return fmt.Errorf("write bitmaps: %w", err) + } + + return nil +} +func dump(r []*RootRecord) { + for _, i := range r { + fmt.Println("RECORD", i.Name, i.Pgno) + } + +} + +// DeleteBitmap removes a bitmap with the given name. +// Returns an error if the bitmap does not exist. +func (tx *Tx) DeleteBitmap(name string) error { + if tx.db == nil { + return ErrTxClosed + } else if !tx.writable { + return ErrTxNotWritable + } else if name == "" { + return ErrBitmapNameRequired + } + + // Read list of root records. + records, err := tx.rootRecords() + if err != nil { + return err + } + + // Find btree by name. Exit if it doesn't exist. + index := sort.Search(len(records), func(i int) bool { return records[i].Name >= name }) + if index >= len(records) || records[index].Name != name { + return fmt.Errorf("bitmap does not exist: %q", name) + } + pgno := records[index].Pgno + + // Deallocate all pages in the tree. + if err := tx.deallocateTree(pgno); err != nil { + return err + } + + // Delete from record list & rewrite record pages. + records = append(records[:index], records[index+1:]...) + if err := tx.writeRootRecordPages(records); err != nil { + return fmt.Errorf("write bitmaps: %w", err) + } + + return nil +} + +// RenameBitmap updates the name of an existing bitmap. +// Returns an error if the bitmap does not exist. +func (tx *Tx) RenameBitmap(oldname, newname string) error { + if tx.db == nil { + return ErrTxClosed + } else if !tx.writable { + return ErrTxNotWritable + } else if oldname == "" || newname == "" { + return ErrBitmapNameRequired + } + + // Read list of root records. + records, err := tx.rootRecords() + if err != nil { + return err + } + + // Find btree by name. Exit if it doesn't exist. + index := sort.Search(len(records), func(i int) bool { return records[i].Name >= oldname }) + if index >= len(records) || records[index].Name != oldname { + return fmt.Errorf("bitmap does not exist: %q", oldname) + } + + // Update record name & rewrite record pages. + records[index].Name = newname + if err := tx.writeRootRecordPages(records); err != nil { + return fmt.Errorf("write bitmaps: %w", err) + } + + return nil +} + +// rootRecords returns a list of root records. +func (tx *Tx) rootRecords() ([]*RootRecord, error) { + var records []*RootRecord + for pgno := readMetaRootRecordPageNo(tx.meta[:]); pgno != 0; { + page, err := tx.readPage(pgno) + if err != nil { + return nil, err + } + + // Read all records on the page. + a, err := readRootRecords(page) + if err != nil { + return nil, err + } + records = append(records, a...) + + // Read next overflow page number. + pgno = readRootRecordOverflowPgno(page) + } + return records, nil +} + +// writeRootRecordPages writes a list of root record pages. +func (tx *Tx) writeRootRecordPages(records []*RootRecord) (err error) { + // Release all existing root record pages. + for pgno := readMetaRootRecordPageNo(tx.meta[:]); pgno != 0; { + page, err := tx.readPage(pgno) + if err != nil { + return err + } + + if err := tx.deallocate(pgno); err != nil { + return err + } + pgno = readRootRecordOverflowPgno(page) + } + + // Exit early if no records exist. + if len(records) == 0 { + writeMetaRootRecordPageNo(tx.meta[:], 0) + return nil + } + + // Ensure records are in sorted order. + sort.Slice(records, func(i, j int) bool { return records[i].Name < records[j].Name }) + + // Allocate initial root record page. + pgno, err := tx.allocate() + if err != nil { + return err + } + writeMetaRootRecordPageNo(tx.meta[:], pgno) + + // Write new root record pages. + for i := 0; len(records) != 0; i++ { + // Initialize page & write as many records as will fit. + page := make([]byte, PageSize) + writePageNo(page, pgno) + writeFlags(page, PageTypeRootRecord) + if records, err = writeRootRecords(page, records); err != nil { + return err + } + + // Allocate next and write overflow if we have remaining records. + if len(records) != 0 { + if pgno, err = tx.allocate(); err != nil { + return err + } + writeRootRecordOverflowPgno(page, pgno) + } + + // Write page to disk. + if err := tx.writePage(page); err != nil { + return err + } + } + + return nil +} + +// Add sets a given bit on the bitmap. +func (tx *Tx) Add(name string, a ...uint64) (changed bool, err error) { + if tx.db == nil { + return false, ErrTxClosed + } else if !tx.writable { + return false, ErrTxNotWritable + } else if name == "" { + return false, ErrBitmapNameRequired + } + + c, err := tx.Cursor(name) + if err != nil { + return false, err + } + for _, v := range a { + if vchanged, err := c.Add(v); err != nil { + return changed, err + } else if vchanged { + changed = true + } + } + return changed, nil +} + +// Remove unsets a given bit on the bitmap. +func (tx *Tx) Remove(name string, a ...uint64) (changed bool, err error) { + if tx.db == nil { + return false, ErrTxClosed + } else if !tx.writable { + return false, ErrTxNotWritable + } else if name == "" { + return false, ErrBitmapNameRequired + } + + c, err := tx.Cursor(name) + if err != nil { + return false, err + } + for _, v := range a { + if vchanged, err := c.Remove(v); err != nil { + return changed, err + } else if vchanged { + changed = true + } + } + return changed, nil +} + +// Contains returns true if the given bit is set on the bitmap. +func (tx *Tx) Contains(name string, v uint64) (bool, error) { + if tx.db == nil { + return false, ErrTxClosed + } else if name == "" { + return false, ErrBitmapNameRequired + } + + c, err := tx.Cursor(name) + if err != nil { + return false, err + } + return c.Contains(v) +} + +// Cursor returns an instance of a cursor this bitmap. +func (tx *Tx) Cursor(name string) (*Cursor, error) { + if tx.db == nil { + return nil, ErrTxClosed + } else if name == "" { + return nil, ErrBitmapNameRequired + } + + root, err := tx.Root(name) + if err != nil { + return nil, err + } + + c := Cursor{tx: tx} + c.stack.elems[0] = stackElem{pgno: root} + return &c, nil +} + +// Check verifies the integrity of the database. +func (tx *Tx) Check() error { + if tx.db == nil { + return ErrTxClosed + } + + if err := tx.checkPageAllocations(); err != nil { + return fmt.Errorf("page allocations: %w", err) + } + return nil +} + +// checkPageAllocations ensures that all pages are either in-use or on the freelist. +func (tx *Tx) checkPageAllocations() error { + freePageSet, err := tx.freePageSet() + if err != nil { + return err + } + + inusePageSet, err := tx.inusePageSet() + if err != nil { + return err + } + + // Iterate over all pages and ensure they are either in-use or free. + // They should not be BOTH in-use or free or NEITHER in-use or free. + pageN := readMetaPageN(tx.meta[:]) + for pgno := uint32(1); pgno < pageN; pgno++ { + _, isInuse := inusePageSet[pgno] + _, isFree := freePageSet[pgno] + + if isInuse && isFree { + return fmt.Errorf("page in-use & free: pgno=%d", pgno) + } else if !isInuse && !isFree { + return fmt.Errorf("page not in-use & not free: pgno=%d", pgno) + } + } + + return nil +} + +// freePageSet returns the set of pages in the freelist. +func (tx *Tx) freePageSet() (map[uint32]struct{}, error) { + m := make(map[uint32]struct{}) + c := Cursor{tx: tx} + c.stack.elems[0] = stackElem{pgno: readMetaFreelistPageNo(tx.meta[:])} + if err := c.First(); err == io.EOF { + return m, nil + } else if err != nil { + return m, err + } + + for { + if err := c.Next(); err == io.EOF { + return m, nil + } else if err != nil { + return m, err + } + + cell := c.cell() + for _, v := range cell.Values() { + pgno := uint32((cell.Key << 16) & uint64(v)) + m[pgno] = struct{}{} + } + } +} + +// inusePageSet returns the set of pages in use by the root records or b-trees. +func (tx *Tx) inusePageSet() (map[uint32]struct{}, error) { + m := make(map[uint32]struct{}) + m[0] = struct{}{} // meta page + + // Traverse root record linked list and mark each page as in-use. + for pgno := readMetaRootRecordPageNo(tx.meta[:]); pgno != 0; { + m[pgno] = struct{}{} + + page, err := tx.readPage(pgno) + if err != nil { + return nil, err + } + pgno = readRootRecordOverflowPgno(page) + } + + // Traverse freelist and mark pages as in-use. + if err := tx.walkTree(readMetaFreelistPageNo(tx.meta[:]), func(pgno uint32) error { + m[pgno] = struct{}{} + return nil + }); err != nil { + return m, err + } + + // Traverse every b-tree and mark pages as in-use. + records, err := tx.rootRecords() + if err != nil { + return m, err + } + for _, record := range records { + if err := tx.walkTree(record.Pgno, func(pgno uint32) error { + m[pgno] = struct{}{} + return nil + }); err != nil { + return m, err + } + } + + return m, nil +} + +// walkTree recursively iterates over a page and all its children. +func (tx *Tx) walkTree(pgno uint32, fn func(uint32) error) error { + // Execute callback. + if err := fn(pgno); err != nil { + return err + } + + // Read page and iterate over children. + page, err := tx.readPage(pgno) + if err != nil { + return err + } + + switch typ := readFlags(page); typ { + case PageTypeBranch: + for i, n := 0, readCellN(page); i < n; i++ { + cell := readBranchCell(page, i) + if cell.Flags&ContainerTypeBitmap != 0 { // bitmap cell (cannot traverse into) + if err := fn(cell.Pgno); err != nil { + return err + } + } else { + if err := tx.walkTree(cell.Pgno, fn); err != nil { + return err + } + } + } + return nil + case PageTypeLeaf: + return nil + default: + return fmt.Errorf("rbf.Tx.forEachTreePage(): invalid page type: pgno=%d type=%d", pgno, typ) + } +} + +// allocate returns a page number for a new available page. This page may be +// pulled from the free list or, if no free pages are available, it will be +// created by extending the file size. +func (tx *Tx) allocate() (uint32, error) { + // Attempt to find page in freelist. + pgno, err := tx.nextFreelistPageNo() + + if err != nil { + return 0, err + } else if pgno != 0 { + c := Cursor{tx: tx} + c.stack.elems[0] = stackElem{pgno: readMetaFreelistPageNo(tx.meta[:])} + if changed, err := c.Remove(uint64(pgno)); err != nil { + return 0, err + } else if !changed { + panic(fmt.Sprintf("tx.Tx.allocate(): double alloc: %d", pgno)) + } + return pgno, nil + } + + // Increment the total page count by one and return the last page. + pgno = readMetaPageN(tx.meta[:]) + writeMetaPageN(tx.meta[:], pgno+1) + return pgno, nil +} + +func (tx *Tx) nextFreelistPageNo() (uint32, error) { + c := Cursor{tx: tx} + c.stack.elems[0] = stackElem{pgno: readMetaFreelistPageNo(tx.meta[:])} + if err := c.First(); err == io.EOF { + return 0, nil + } else if err != nil { + return 0, err + } + + cell := c.cell() + v := cell.firstValue() + + pgno := uint32((cell.Key << 16) | uint64(v)) + return pgno, nil +} + +// deallocate releases a page number to the freelist. +func (tx *Tx) deallocate(pgno uint32) error { + c := Cursor{tx: tx} + c.stack.elems[0] = stackElem{pgno: readMetaFreelistPageNo(tx.meta[:])} + + if changed, err := c.Add(uint64(pgno)); err != nil { + return err + } else if !changed { + panic(fmt.Sprintf("rbf.Tx.deallocate(): double free: %d", pgno)) + } + return nil +} + +// deallocateTree recursively all pages in a btree. +func (tx *Tx) deallocateTree(pgno uint32) error { + page, err := tx.readPage(pgno) + if err != nil { + return err + } + + switch typ := readFlags(page); typ { + case PageTypeBranch: + for i, n := 0, readCellN(page); i < n; i++ { + cell := readBranchCell(page, i) + if cell.Flags&ContainerTypeBitmap == 0 { // leaf/branch child page + if err := tx.deallocateTree(cell.Pgno); err != nil { + return err + } + } else { + if err := tx.deallocate(cell.Pgno); err != nil { // bitmap child page + return err + } + } + } + return nil + + case PageTypeLeaf: + return tx.deallocate(pgno) + default: + return fmt.Errorf("rbf.Tx.deallocateTree(): invalid page type: pgno=%d type=%d", pgno, typ) + } +} + +func (tx *Tx) readPage(pgno uint32) ([]byte, error) { + // fmt.Println("readPage", pgno) + // Meta page is always cached on the transaction. + if pgno == 0 { + return tx.meta[:], nil + } + + pageN := readMetaPageN(tx.meta[:]) + if pgno > pageN { + return nil, fmt.Errorf("rbf: page read out of bounds: pgno=%d max=%d", pgno, pageN) + } + return tx.db.readPage(tx.pageMap, pgno) +} + +func (tx *Tx) writePage(page []byte) error { + // fmt.Println("writePage", readPageNo(page)) + // Write page to WAL and obtain position in WAL. + walID, err := tx.db.writeWALPage(page, false) + if err != nil { + return err + } + + // Mark transaction as dirty so we write a meta page on commit/rollback. + tx.dirty = true + + // Update page map with WAL position. + tx.pageMap = tx.pageMap.Set(readPageNo(page), walID) + return nil +} + +func (tx *Tx) writeBitmapPage(pgno uint32, page []byte) error { + // Write bitmap to WAL and obtain WAL position of the actual page data (not the prefix page). + walID, err := tx.db.writeBitmapPage(pgno, page) + if err != nil { + return err + } + + // Mark transaction as dirty so we write a meta page on commit/rollback. + tx.dirty = true + + // Update page map with WAL position. + tx.pageMap = tx.pageMap.Set(pgno, walID) + return nil +} + +func (tx *Tx) writeMetaPage(flag uint32) error { + // Set meta flags. + writeFlags(tx.meta[:], flag) + + // Write page to WAL and obtain position in WAL. + walID, err := tx.db.writeWALPage(tx.meta[:], true) + if err != nil { + return err + } + tx.pageMap = tx.pageMap.Set(uint32(0), walID) + + return nil +} + +func (tx *Tx) AddRoaring(name string, bm *roaring.Bitmap) (changed bool, err error) { + c, err := tx.Cursor(name) + if err != nil { + return false, err + } + return c.AddRoaring(bm) +} diff --git a/rbf/tx_test.go b/rbf/tx_test.go new file mode 100644 index 000000000..fa758309c --- /dev/null +++ b/rbf/tx_test.go @@ -0,0 +1,465 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf_test + +import ( + "fmt" + "math/rand" + "testing" + "time" + + "github.com/pilosa/pilosa/v2/rbf" +) + +func TestTx_CommitRollback(t *testing.T) { + t.Run("NoReopen", func(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + + // Create bitmap in transaction but rollback. + if tx, err := db.Begin(true); err != nil { + t.Fatal(err) + } else if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } else if err := tx.Rollback(); err != nil { + t.Fatal(err) + } + + // Create bitmap in transaction again but commit. + if tx, err := db.Begin(true); err != nil { + t.Fatal(err) + } else if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } else if err := tx.Commit(); err != nil { + t.Fatal(err) + } + + // Create bitmap again but it should fail as it already exists. + if tx, err := db.Begin(true); err != nil { + t.Fatal(err) + } else if err := tx.CreateBitmap("x"); err == nil || err.Error() != `bitmap already exists: "x"` { + _ = tx.Rollback() + t.Fatal(err) + } else if err := tx.Commit(); err != nil { + t.Fatal(err) + } + }) + + t.Run("Reopen", func(t *testing.T) { + db := MustOpenDB(t) + defer func() { MustCloseDB(t, db) }() + + // Create bitmap in transaction but rollback. + if tx, err := db.Begin(true); err != nil { + t.Fatal(err) + } else if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } else if err := tx.Rollback(); err != nil { + t.Fatal(err) + } + db = MustReopenDB(t, db) + + // Create bitmap in transaction again but commit. + if tx, err := db.Begin(true); err != nil { + t.Fatal(err) + } else if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } else if err := tx.Commit(); err != nil { + t.Fatal(err) + } + db = MustReopenDB(t, db) + + // Create bitmap again but it should fail as it already exists. + if tx, err := db.Begin(true); err != nil { + t.Fatal(err) + } else if err := tx.CreateBitmap("x"); err == nil || err.Error() != `bitmap already exists: "x"` { + _ = tx.Rollback() + t.Fatal(err) + } else if err := tx.Commit(); err != nil { + t.Fatal(err) + } + }) + + t.Run("SingleWriter", func(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + + // Start write transaction. + ch0 := make(chan struct{}) + tx0 := MustBegin(t, db, true) + go func() { + <-ch0 + _ = tx0.Rollback() + }() + + // Start separate write transaction in different goroutine. + ch1 := make(chan struct{}) + go func() { + tx1 := MustBegin(t, db, true) + close(ch1) + _ = tx1.Commit() + }() + + // Ensure second tx doesn't start. + select { + case <-ch1: + t.Fatal("second tx started while first tx active") + case <-time.After(10 * time.Millisecond): + } + + // Finish first transaction. + close(ch0) + select { + case <-ch1: + case <-time.After(10 * time.Millisecond): + t.Fatal("second tx should have started after first tx closed") + } + }) +} + +func TestTx_Add(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + + if _, err := tx.Add("x", 1); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", 10); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", 3); err != nil { + t.Fatal(err) + } + + for _, v := range []uint64{1, 3, 10} { + if ok, err := tx.Contains("x", v); err != nil { + t.Fatal(err) + } else if !ok { + t.Fatalf("Tx.Contains(%d): expected true", v) + } + } + + if ok, err := tx.Contains("x", 2); err != nil { + t.Fatal(err) + } else if ok { + t.Fatal("Tx.Contains(): expected false") + } +} + +func TestTx_DeleteBitmap(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + + // Create bitmap & add value. + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", 1); err != nil { + t.Fatal(err) + } + + // Recreate bitmap & ensure value does not exist. + if err := tx.DeleteBitmap("x"); err != nil { + t.Fatal(err) + } else if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } else if ok, err := tx.Contains("x", 1); err != nil { + t.Fatal(err) + } else if ok { + t.Fatal("expected no value in recreated bitmap") + } +} + +func TestTx_RenameBitmap(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + + // Create bitmap & add value. + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } else if _, err := tx.Add("x", 1); err != nil { + t.Fatal(err) + } + + // Rename bitmap & ensure value still exists. + if err := tx.RenameBitmap("x", "y"); err != nil { + t.Fatal(err) + } else if ok, err := tx.Contains("y", 1); err != nil { + t.Fatal(err) + } else if !ok { + t.Fatal("expected value in renamed bitmap") + } +} + +func TestTx_Add_Quick(t *testing.T) { + if testing.Short() { + t.Skip("-short enabled, skipping") + } else if is32Bit() { + t.Skip("32-bit build, skipping quick check tests") + } else if rbf.RaceEnabled { + t.Skip("race detection enabled, skipping") + } + + QuickCheck(t, func(t *testing.T, rand *rand.Rand) { + t.Parallel() + + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + values := GenerateValues(rand, 100000) + + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + + // Insert values in random order. + for _, i := range rand.Perm(len(values)) { + v := values[i] + if _, err := tx.Add("x", v); err != nil { + t.Fatalf("Add(%d) i=%d err=%q", v, i, err) + } + } + + // Verify all bits are written. + for i, v := range values { + if ok, err := tx.Contains("x", v); !ok || err != nil { + t.Fatalf("Contains(%d)=(%v,%v) i=%d hi=%d lo=%d", v, ok, err, i, highbits(v), lowbits(v)) + } + } + }) +} + +func TestTx_AddRemove_Quick(t *testing.T) { + if testing.Short() { + t.Skip("-short enabled, skipping") + } else if is32Bit() { + t.Skip("32-bit build, skipping quick check tests") + } else if rbf.RaceEnabled { + t.Skip("race detection enabled, skipping") + } + + QuickCheck(t, func(t *testing.T, rand *rand.Rand) { + t.Parallel() + + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + values := GenerateValues(rand, 100000) + + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + + // Insert values in random order. + for _, i := range rand.Perm(len(values)) { + if _, err := tx.Add("x", values[i]); err != nil { + t.Fatalf("Add(%d) i=%d err=%q", values[i], i, err) + } + } + + // Remove half the values in random order. + for _, i := range rand.Perm(len(values)) { + if _, err := tx.Remove("x", values[i]); err != nil { + t.Fatalf("Remove(%d) i=%d err=%q", values[i], i, err) + } + } + + // Verify all bits are removed. + for i, v := range values { + if ok, err := tx.Contains("x", v); ok || err != nil { + t.Fatalf("Contains(%d)=(%v,%v) i=%d hi=%d lo=%d", v, ok, err, i, highbits(v), lowbits(v)) + } + } + + // Re-add those values back in. + for _, i := range rand.Perm(len(values)) { + if _, err := tx.Add("x", values[i]); err != nil { + t.Fatalf("Re-Add(%d) i=%d err=%q", values[i], i, err) + } + } + + // Verify all bits are written. + for i, v := range values { + if ok, err := tx.Contains("x", v); !ok || err != nil { + t.Fatalf("Contains(%d)=(%v,%v) i=%d hi=%d lo=%d", v, ok, err, i, highbits(v), lowbits(v)) + } + } + }) +} + +func TestTx_Multiple_CreateBitmap(t *testing.T) { + rand := rand.New(rand.NewSource(0)) + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + values := GenerateValues(rand, 2) + + if err := tx.CreateBitmap("x/1"); err != nil { + t.Fatal(err) + } + + // Insert values in random order. + for _, i := range rand.Perm(len(values)) { + if _, err := tx.Add("x/1", values[i]); err != nil { + t.Fatalf("Add(%d) i=%d err=%q", values[i], i, err) + } + } + if err := tx.Commit(); err != nil { + t.Fatalf("Commit 1 err=%q", err) + } + + tx1 := MustBegin(t, db, true) + defer func() { _ = tx1.Rollback() }() + + if err := tx1.CreateBitmap("x/2"); err != nil { + t.Fatal(err) + } + + // Insert values in random order. + for _, i := range rand.Perm(len(values)) { + if _, err := tx1.Add("x/2", values[i]); err != nil { + t.Fatalf("Add(%d) i=%d err=%q", values[i], i, err) + } + } + if err := tx1.Commit(); err != nil { + t.Fatalf("Commit 2 err=%q", err) + } +} + +func TestTx_CursorCrashArray(t *testing.T) { + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + c, err := tx.Cursor("x") + if err != nil { + t.Fatal(err) + } + //setArray(t, 0, 2379, c) + //setArray(t, 1, 2337, c) + setArray(t, 32, 1216, c) + setArray(t, 33, 1195, c) + setArray(t, 48, 1186, c) + setArray(t, 49, 1223, c) + setArray(t, 50, 1223, c) + +} + +func TestTx_CursorCrashBitmap(t *testing.T) { + if testing.Short() { + t.Skip("-short enabled, skipping") + } + + db := MustOpenDB(t) + defer MustCloseDB(t, db) + tx := MustBegin(t, db, true) + defer MustRollback(t, tx) + if err := tx.CreateBitmap("x"); err != nil { + t.Fatal(err) + } + c, err := tx.Cursor("x") + if err != nil { + t.Fatal(err) + } + setArray(t, 0, 22510, c) + setArray(t, 1, 23584, c) +} + +func setArray(tb testing.TB, key, num int, c *rbf.Cursor) { + for i := uint64(0); i < uint64(num); i++ { + v := i | (uint64(key) << 16) + if _, err := c.Add(v); err != nil { + tb.Fatal(err) + } + } +} + +func BenchmarkTx_Add(b *testing.B) { + for _, n := range []int{10000, 100000, 1000000} { + b.Run(fmt.Sprint(n), func(b *testing.B) { + rand := rand.New(rand.NewSource(0)) + + values := make([]uint64, n) + for i := range values { + values[i] = uint64(rand.Intn(rbf.ShardWidth)) + } + b.ResetTimer() + t := time.Now() + b.ReportAllocs() + + for i := 0; i < b.N; i++ { + func() { + db := MustOpenDB(b) + defer MustCloseDB(b, db) + tx := MustBegin(b, db, true) + defer MustRollback(b, tx) + + for _, v := range values { + if _, err := tx.Add("x", v); err != nil { + b.Fatalf("Add(%d) i=%d err=%q", v, i, err) + } + } + }() + } + + b.ReportMetric(float64(time.Since(t).Nanoseconds())/float64(n*b.N), "ns/op") + }) + } +} + +func BenchmarkTx_Contains(b *testing.B) { + for _, n := range []int{10000, 100000, 1000000} { + b.Run(fmt.Sprint(n), func(b *testing.B) { + rand := rand.New(rand.NewSource(0)) + + values := make([]uint64, n) + for i := range values { + values[i] = uint64(rand.Intn(rbf.ShardWidth)) + } + + db := MustOpenDB(b) + defer MustCloseDB(b, db) + tx := MustBegin(b, db, true) + defer MustRollback(b, tx) + + b.ResetTimer() + t := time.Now() + b.ReportAllocs() + + for i := 0; i < b.N; i++ { + for _, v := range values { + if _, err := tx.Contains("x", v); err != nil { + b.Fatalf("Contains(%d) i=%d err=%q", v, i, err) + } + } + } + + b.ReportMetric(float64(time.Since(t).Nanoseconds())/float64(n*b.N), "ns/op") + }) + } +} diff --git a/rbf/wal.go b/rbf/wal.go new file mode 100644 index 000000000..501b4f63c --- /dev/null +++ b/rbf/wal.go @@ -0,0 +1,241 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf + +import ( + "fmt" + "os" + "path/filepath" + "syscall" + + "github.com/pilosa/pilosa/v2/syswrap" +) + +// WALSegment represents a single file in the WAL. +type WALSegment struct { + minWALID int64 // base WALID; calculated from path + path string // path to file + w *os.File // write handle + data []byte // read-only mmap data + pageN int // number of written pages +} + +// NewWALSegment returns a new instance of WALSegment for a given path. +func NewWALSegment(path string) *WALSegment { + return &WALSegment{ + path: path, + } +} + +// Path returns the path the segment was initialized with. +func (s *WALSegment) Path() string { return s.path } + +// MinWALID returns the initial WAL ID of the segment. Only available after Open(). +func (s *WALSegment) MinWALID() int64 { return s.minWALID } + +// MaxWALID returns the maximum WAL ID of the segment. Only available after Open(). +func (s *WALSegment) MaxWALID() int64 { + return s.minWALID + int64(s.pageN) - 1 +} + +// PageN returns the number of pages in the segment. +func (s *WALSegment) PageN() int { return s.pageN } + +// Size returns the current size of the segment, in bytes. +func (s *WALSegment) Size() int64 { return int64(s.pageN) * PageSize } + +func (s *WALSegment) Open() (err error) { + // Extract base WAL ID and validate path. + if s.minWALID, err = ParseWALSegmentPath(s.path); err != nil { + return err + } + + // Determine file size & create if necessary. + var sz int64 + if fi, err := os.Stat(s.path); os.IsNotExist(err) { + if f, err := os.OpenFile(s.path, os.O_RDWR|os.O_CREATE, 0666); err != nil { + return fmt.Errorf("touch wal segment file: %w", err) + } else if err := f.Close(); err != nil { + return fmt.Errorf("close touched wal segment file: %w", err) + } + } else if err != nil { + return fmt.Errorf("stat wal segment file: %w", err) + } else { + sz = fi.Size() + } + + // Determine page count & truncate if a partial page is written. + s.pageN = int(sz / PageSize) + if sz%PageSize != 0 { + sz = int64(s.pageN * PageSize) + if err := os.Truncate(s.path, sz); err != nil { + return fmt.Errorf("truncate wal segment file: %w", err) + } + } + + // Default the mmap size to the max size plus a page of padding for bitmap pages. + // If the actual size is larger, then increase to that size. + mmapSize := int64(MaxWALSegmentFileSize + PageSize) + if sz > mmapSize { + mmapSize = sz + } + + // Open file as a read-only memory map. + if f, err := os.OpenFile(s.path, os.O_RDONLY, 0666); err != nil { + return fmt.Errorf("open wal segment file: %w", err) + } else if s.data, err = syswrap.Mmap(int(f.Fd()), 0, int(mmapSize), syscall.PROT_READ, syscall.MAP_SHARED); err != nil { + f.Close() + return fmt.Errorf("mmap wal segment: %w", err) + } else if err := f.Close(); err != nil { + return fmt.Errorf("close wal segment mmap file: %w", err) + } + + return nil +} + +// Close closes the write handle and the read-only mmap. +func (s *WALSegment) Close() error { + if err := s.CloseForWrite(); err != nil { + return err + } + if s.data != nil { + if err := syswrap.Munmap(s.data); err != nil { + return err + } + s.data = nil + } + return nil +} + +// CloseForWrite closes the write handle, if initialized. +func (s *WALSegment) CloseForWrite() error { + if s.w != nil { + if err := s.w.Close(); err != nil { + return err + } + s.w = nil + } + return nil +} + +// ReadWALPage reads a single page at the given WAL ID. +func (s *WALSegment) ReadWALPage(walID int64) ([]byte, error) { + // Ensure requested ID is contained in this file. + if walID < s.minWALID || walID > s.minWALID+int64(s.pageN) { + return nil, fmt.Errorf("wal segment page read out of range: id=%d base=%d pageN=%d", walID, s.minWALID, s.pageN) + } + + offset := (walID - s.minWALID) * PageSize + return s.data[offset : offset+PageSize], nil +} + +// WriteWALPage writes a single page to the WAL segment and returns its WAL identifier. +func (s *WALSegment) WriteWALPage(page []byte, isMeta bool) (walID int64, err error) { + assert(len(page) == PageSize) + + // Initialize write file handle if not yet initialized. + if s.w == nil { + if s.w, err = os.OpenFile(s.path, os.O_WRONLY, 0666); err != nil { + return 0, fmt.Errorf("open wal segment write handle: %w", err) + } + } + + // Determine current WAL position. + walID = s.minWALID + int64(s.pageN) + + // Write WAL ID if this is a meta page. + if isMeta { + writeMetaWALID(page, walID) + // TODO: Write meta page checksum + } + + // Write page at position & increment page count. + if _, err := s.w.WriteAt(page, int64(s.pageN*PageSize)); err != nil { + return 0, fmt.Errorf("wal segment write: %w", err) + } + s.pageN++ + + return walID, nil +} + +// Sync flushes all changes to disk. +func (s *WALSegment) Sync() error { + if s.w == nil { + return nil + } + return s.w.Sync() +} + +// trimBitmapHeaderTrailer removes the last page if the last page is a bitmap header. +// This should only be called on the last segment during recovery. A bitmap +// header write is a 2-page write so a partial write would corrupt the WAL. +func (s *WALSegment) trimBitmapHeaderTrailer() error { + // Skip if there are no pages in this segment. + if s.PageN() == 0 { + return nil + } + + // Skip if this is not a bitmap header page. + if page, err := s.ReadWALPage(s.MaxWALID()); err != nil { + return err + } else if !IsBitmapHeader(page) { + return nil + } + + // Truncate last page and reduce page count. + if err := os.Truncate(s.Path(), s.Size()-PageSize); err != nil { + return err + } + s.pageN-- + + return nil +} + +// FormatWALSegmentPath returns a path for a WAL segment using a WAL ID. +func FormatWALSegmentPath(walID int64) string { + return fmt.Sprintf("%016x.wal", walID) +} + +// ParseWALSegmentPath returns the WAL ID for a given WAL segment path. +func ParseWALSegmentPath(s string) (walID int64, err error) { + if _, err = fmt.Sscanf(filepath.Base(s), "%016x.wal", &walID); err != nil { + return 0, fmt.Errorf("invalid WAL path: %s", s) + } + return walID, nil +} + +// uint32Hasher implements Hasher for uint32 keys. +type uint32Hasher struct{} + +// Hash returns a hash for key. +func (h *uint32Hasher) Hash(key interface{}) uint32 { + return hashUint64(uint64(key.(uint32))) +} + +// Equal returns true if a is equal to b. Otherwise returns false. +// Panics if a and b are not ints. +func (h *uint32Hasher) Equal(a, b interface{}) bool { + return a.(uint32) == b.(uint32) +} + +// hashUint64 returns a 32-bit hash for a 64-bit value. +func hashUint64(value uint64) uint32 { + hash := value + for value > 0xffffffff { + value /= 0xffffffff + hash ^= value + } + return uint32(hash) +} diff --git a/rbf/wal_test.go b/rbf/wal_test.go new file mode 100644 index 000000000..53349c001 --- /dev/null +++ b/rbf/wal_test.go @@ -0,0 +1,138 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 rbf_test + +import ( + "bytes" + "encoding/hex" + "io/ioutil" + "math/rand" + "os" + "path/filepath" + "testing" + + "github.com/pilosa/pilosa/v2/rbf" +) + +func TestWALSegment_Open(t *testing.T) { + t.Run("OK", func(t *testing.T) { + s := MustOpenWALSegment(t, 10) + defer MustCloseWALSegment(t, s) + if got, want := s.MinWALID(), int64(10); got != want { + t.Fatalf("Base()=%d, want %d", got, want) + } else if got, want := s.PageN(), 0; got != want { + t.Fatalf("PageN()=%d, want %d", got, want) + } + }) + + // TODO(BBJ): Test open w/ partially written pages. +} + +func TestWALSegment_WritePage(t *testing.T) { + rand := rand.New(rand.NewSource(0)) + s := MustOpenWALSegment(t, 10) + defer MustCloseWALSegment(t, s) + + pages := [][]byte{ + make([]byte, rbf.PageSize), + make([]byte, rbf.PageSize), + } + rand.Read(pages[0]) + rand.Read(pages[1]) + + // Write first page. + if walID, err := s.WriteWALPage(pages[0], false); err != nil { + t.Fatal(err) + } else if got, want := walID, int64(10); got != want { + t.Fatalf("WALID=%d, want %d", got, want) + } else if got, want := s.PageN(), 1; got != want { + t.Fatalf("PageN()=%d, want %d", got, want) + } + + // Write second page. + if walID, err := s.WriteWALPage(pages[1], false); err != nil { + t.Fatal(err) + } else if got, want := walID, int64(11); got != want { + t.Fatalf("WALID=%d, want %d", got, want) + } else if got, want := s.PageN(), 2; got != want { + t.Fatalf("PageN()=%d, want %d", got, want) + } + + // Read & verify first page. + if buf, err := s.ReadWALPage(10); err != nil { + t.Fatal(err) + } else if !bytes.Equal(pages[0], buf) { + t.Fatalf("unexpected first page:\n%s", hex.Dump(buf)) + } + + // Read & verify second page. + if buf, err := s.ReadWALPage(11); err != nil { + t.Fatal(err) + } else if !bytes.Equal(pages[1], buf) { + t.Fatal("unexpected second page") + } +} + +func TestFormatWALSegmentPath(t *testing.T) { + if got, want := rbf.FormatWALSegmentPath(1234), "00000000000004d2.wal"; got != want { + t.Fatalf("FormatWALSegmentPath()=%q, want %q", got, want) + } +} + +func TestParseWALSegmentPath(t *testing.T) { + t.Run("OK", func(t *testing.T) { + if walID, err := rbf.ParseWALSegmentPath("/tmp/00000000000004d2.wal"); err != nil { + t.Fatal(err) + } else if got, want := walID, int64(1234); got != want { + t.Fatalf("ParseWALSegmentPath()=%q, want %q", got, want) + } + }) + + t.Run("ErrInvalidWALPath", func(t *testing.T) { + if _, err := rbf.ParseWALSegmentPath("/tmp/xyz"); err == nil || err.Error() != "invalid WAL path: /tmp/xyz" { + t.Fatalf("unexpected error: %#v", err) + } + }) +} + +// MustOpenWALSegment opens a WAL segment in a temporary path. Fails on error. +func MustOpenWALSegment(tb testing.TB, walID int64) *rbf.WALSegment { + tb.Helper() + + dir, err := ioutil.TempDir("", "") + if err != nil { + tb.Fatal(err) + } + path := filepath.Join(dir, rbf.FormatWALSegmentPath(walID)) + if err := ioutil.WriteFile(path, nil, 0666); err != nil { + tb.Fatal(err) + } + + s := rbf.NewWALSegment(path) + if err := s.Open(); err != nil { + tb.Fatal(err) + } + return s +} + +// MustCloseWALSegment closes s. Fails on error. +func MustCloseWALSegment(tb testing.TB, s *rbf.WALSegment) { + tb.Helper() + if err := s.Close(); err != nil { + tb.Fatal(err) + } else if err := os.Remove(s.Path()); err != nil { + tb.Fatal(err) + } +} diff --git a/roaring/btree_test.go b/roaring/btree_test.go index f0f528a7b..65f05d0c4 100644 --- a/roaring/btree_test.go +++ b/roaring/btree_test.go @@ -399,6 +399,7 @@ func BenchmarkBtreeSetSeq1e6(b *testing.B) { func benchmarkSetSeq(b *testing.B, n int) { b.ResetTimer() + b.ReportAllocs() for i := 0; i < b.N; i++ { b.StopTimer() r := treeNew() @@ -436,6 +437,7 @@ func benchmarkGetSeq(b *testing.B, n int) { } debug.FreeOSMemory() b.ResetTimer() + b.ReportAllocs() for i := 0; i < b.N; i++ { for j := 0; j < n; j++ { r.Get(uint64(j)) @@ -468,6 +470,7 @@ func benchmarkSetRnd(b *testing.B, n int) { a[i] = rng.Next() } b.ResetTimer() + b.ReportAllocs() c := getDummyC(1) for i := 0; i < b.N; i++ { b.StopTimer() @@ -512,6 +515,7 @@ func benchmarkGetRnd(b *testing.B, n int) { } debug.FreeOSMemory() b.ResetTimer() + b.ReportAllocs() for i := 0; i < b.N; i++ { for _, v := range a { r.Get(uint64(v)) diff --git a/roaring/container_stash.go b/roaring/container_stash.go index 89c63ac8f..3531a0317 100644 --- a/roaring/container_stash.go +++ b/roaring/container_stash.go @@ -16,8 +16,6 @@ package roaring import ( "fmt" - "reflect" - "runtime" "unsafe" ) @@ -47,35 +45,47 @@ type Container struct { type containerFlags uint8 +var containerFlagStrings = [...]string{ + "", + "mapped", + "frozen", + "frozen/mapped", + "pristine", + "pristine/mapped", + "pristine/frozen", + "pristine/frozen/mapped", +} + +func (f containerFlags) String() string { + return containerFlagStrings[f&7] +} + const ( flagMapped = containerFlags(1 << iota) flagFrozen + flagPristine ) func (c *Container) String() string { if c == nil { return "" } - froze := "" - switch c.flags { - case flagFrozen: - froze = "frozen " - case flagMapped: - froze = "mapped " - case flagFrozen | flagMapped: - froze = "frozen/mapped" + var space, froze string + if c.flags != 0 { + space = " " + froze = c.flags.String() } switch c.typeID { case containerArray: - return fmt.Sprintf("<%sarray container, N=%d>", froze, c.N()) + return fmt.Sprintf("<%s%sarray container, N=%d>", froze, space, c.N()) case containerBitmap: - return fmt.Sprintf("<%sbitmap container, N=%d, len %dx uint64>", - froze, c.N(), len(c.bitmap())) + return fmt.Sprintf("<%s%sbitmap container, N=%d>", + froze, space, c.N()) case containerRun: - return fmt.Sprintf("<%srun container, N=%d, len %dx interval>", - froze, c.N(), len(c.runs())) + return fmt.Sprintf("<%s%srun container, N=%d, len %dx interval>", + froze, space, c.N(), len(c.runs())) default: - return fmt.Sprintf("", froze, c.typeID, c.N()) + return fmt.Sprintf("", froze, space, c.typeID, c.N()) } } @@ -83,9 +93,7 @@ func (c *Container) String() string { // may later become more interesting. func NewContainer() *Container { statsHit("NewContainer") - c := &Container{typeID: containerArray, len: 0, cap: stashedArraySize} - c.pointer = (*uint16)(unsafe.Pointer(&c.data[0])) - return c + return NewContainerArray(nil) } // NewContainerBitmap makes a bitmap container using the provided bitmap, or @@ -97,14 +105,13 @@ func NewContainerBitmap(n int, bitmap []uint64) *Container { if bitmap == nil { return NewContainerBitmapN(nil, 0) } - // pad to required length - if len(bitmap) < bitmapN { - bm2 := make([]uint64, bitmapN) - copy(bm2, bitmap) - bitmap = bm2 - } c := &Container{typeID: containerBitmap} - c.setBitmap(bitmap) + if len(bitmap) != bitmapN { + // adjust to required length + c.setBitmapCopy(bitmap) + } else { + c.setBitmap(bitmap) + } // set n based on bitmap contents. if n < 0 { c.bitmapRepair() @@ -121,21 +128,20 @@ func NewContainerBitmapN(bitmap []uint64, n int32) *Container { if bitmap == nil { bitmap = make([]uint64, bitmapN) } - // pad to required length - if len(bitmap) < bitmapN { - bm2 := make([]uint64, bitmapN) - copy(bm2, bitmap) - bitmap = bm2 - } c := &Container{typeID: containerBitmap, n: n} - c.setBitmap(bitmap) + if len(bitmap) != bitmapN { + // adjust to required length + c.setBitmapCopy(bitmap) + } else { + c.setBitmap(bitmap) + } return c } // NewContainerArray returns an array container using the provided set of // values. It's okay if the slice is nil; that's a length of zero. func NewContainerArray(set []uint16) *Container { - c := &Container{typeID: containerArray, n: int32(len(set))} + c := &Container{typeID: containerArray} c.setArray(set) return c } @@ -144,44 +150,44 @@ func NewContainerArray(set []uint16) *Container { // values. It's okay if the slice is nil; that's a length of zero. It copies // the provided slice to new storage. func NewContainerArrayCopy(set []uint16) *Container { - c := &Container{typeID: containerArray, n: int32(len(set))} + c := &Container{typeID: containerArray} c.setArrayMaybeCopy(set, true) return c } // NewContainerArrayN returns an array container using the specified // set of values, but overriding n. +// This is deprecated. It never worked in the first place. +// The provided value of n is ignored and instead derived from the set length. func NewContainerArrayN(set []uint16, n int32) *Container { - c := &Container{typeID: containerArray, n: n} - c.setArray(set) - return c + return NewContainerArray(set) } // NewContainerRun creates a new run container using a provided (possibly nil) // slice of intervals. -func NewContainerRun(set []interval16) *Container { +func NewContainerRun(set []Interval16) *Container { c := &Container{typeID: containerRun} c.setRuns(set) for _, run := range set { - c.n += int32(run.last-run.start) + 1 + c.n += int32(run.Last-run.Start) + 1 } return c } // NewContainerRunCopy creates a new run container using a provided (possibly nil) // slice of intervals. It copies the provided slice to new storage. -func NewContainerRunCopy(set []interval16) *Container { +func NewContainerRunCopy(set []Interval16) *Container { c := &Container{typeID: containerRun} c.setRunsMaybeCopy(set, true) for _, run := range set { - c.n += int32(run.last-run.start) + 1 + c.n += int32(run.Last-run.Start) + 1 } return c } // NewContainerRunN creates a new run array using a provided (possibly nil) // slice of intervals. It overrides n using the provided value. -func NewContainerRunN(set []interval16, n int32) *Container { +func NewContainerRunN(set []Interval16, n int32) *Container { c := &Container{typeID: containerRun, n: n} c.setRuns(set) return c @@ -274,10 +280,8 @@ func (c *Container) Freeze() *Container { // Thaw returns a modifiable container identical to c. This may be c, or it // may be a new container with distinct backing store. func (c *Container) Thaw() *Container { - if roaringParanoia { - if c == nil { - panic("trying to thaw a nil container") - } + if c == nil { + panic("trying to thaw a nil container") } if c.flags&(flagFrozen|flagMapped) == 0 { return c @@ -287,54 +291,20 @@ func (c *Container) Thaw() *Container { func (c *Container) unmapOrClone() *Container { if c.flags&flagFrozen != 0 { - // Caqn't modify this container, therefore, we have to make a + // Can't modify this container, therefore, we have to make a // copy. return c.Clone() } c.flags &^= flagMapped + c.flags &^= flagPristine // mapped: we want to unmap the storage. switch c.typeID { case containerArray: - // mapped flag is wrong here - if c.pointer == (*uint16)(unsafe.Pointer(&c.data)) { - return c - } - // maybe it fits in storage - if c.len <= stashedArraySize { - copy(c.data[:stashedArraySize], c.array()) - c.pointer, c.cap = (*uint16)(unsafe.Pointer(&c.data)), stashedArraySize - return c - } - array := c.array() - tmp := make([]uint16, c.len) - copy(tmp, array) - h := (*reflect.SliceHeader)(unsafe.Pointer(&tmp)) - c.pointer, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Cap) - runtime.KeepAlive(&tmp) + c.setArrayMaybeCopy(c.array(), true) case containerRun: - // mapped flag is wrong here - if c.pointer == (*uint16)(unsafe.Pointer(&c.data)) { - return c - } - oldRuns := c.runs() - // maybe it fits in storage - if c.len <= stashedRunSize { - c.pointer, c.cap = (*uint16)(unsafe.Pointer(&c.data)), stashedRunSize - copy(c.runs(), oldRuns) - return c - } - tmp := make([]interval16, c.len) - copy(tmp, oldRuns) - h := (*reflect.SliceHeader)(unsafe.Pointer(&tmp)) - c.pointer, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Cap) - runtime.KeepAlive(&tmp) + c.setRunsMaybeCopy(c.runs(), true) case containerBitmap: - bitmap := c.bitmap() - tmp := make([]uint64, bitmapN) - copy(tmp, bitmap) - h := (*reflect.SliceHeader)(unsafe.Pointer(&tmp)) - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), bitmapN, bitmapN - runtime.KeepAlive(&tmp) + c.setBitmapCopy(c.bitmap()) default: panic(fmt.Sprintf("can't thaw invalid container, type %d", c.typeID)) } @@ -343,15 +313,15 @@ func (c *Container) unmapOrClone() *Container { // array yields the data viewed as a slice of uint16 values. func (c *Container) array() []uint16 { + if c == nil { + panic("attempt to read a nil container's array") + } if roaringParanoia { - if c == nil { - panic("attempt to read a nil container's array") - } if c.typeID != containerArray { panic("attempt to read non-array's array") } } - return *(*[]uint16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)})) + return (*[1 << 16]uint16)(unsafe.Pointer(c.pointer))[:c.len:c.cap] } // setArrayMaybeCopy stores a set of uint16s as data. c must not be frozen. @@ -366,36 +336,33 @@ func (c *Container) setArrayMaybeCopy(array []uint16, doCopy bool) { panic("attempt to write non-array's array") } } - // no array: start with our default 5-value array - if array == nil { - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedArraySize - c.n = c.len - return - } - h := (*reflect.SliceHeader)(unsafe.Pointer(&array)) - if h.Data == uintptr(unsafe.Pointer(c.pointer)) { - // nothing to do but update length - c.len = int32(h.Len) - c.n = c.len - return + if len(array) > 1<<16 { + panic("impossibly large array") } + c.flags &^= flagPristine // array we can fit in data store: if len(array) <= stashedArraySize { copy(c.data[:stashedArraySize], array) - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(len(array)), stashedArraySize + c.pointer, c.len, c.cap = &c.data[0], int32(len(array)), stashedArraySize c.n = c.len c.flags &^= flagMapped // this is no longer using a hypothetical mmapped input array return } + if &array[0] == c.pointer && !doCopy { + // nothing to do but update length + c.len = int32(len(array)) + c.n = c.len + return + } // copy the array if doCopy { - a2 := make([]uint16, len(array)) - copy(a2, array) - h = (*reflect.SliceHeader)(unsafe.Pointer(&a2)) + array = append([]uint16(nil), array...) } - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap) + if cap(array) > 1<<16 { + array = array[: len(array) : 1<<16] + } + c.pointer, c.len, c.cap = &array[0], int32(len(array)), int32(cap(array)) c.n = c.len - runtime.KeepAlive(&array) } // setArrayMaybeCopy stores a set of uint16s as data. c must not be frozen. @@ -405,15 +372,15 @@ func (c *Container) setArray(array []uint16) { // bitmap yields the data viewed as a slice of uint64s holding bits. func (c *Container) bitmap() []uint64 { + if c == nil { + panic("attempt to read nil container's bitmap") + } if roaringParanoia { - if c == nil { - panic("attempt to read nil container's bitmap") - } if c.typeID != containerBitmap { panic("attempt to read non-bitmap's bitmap") } } - return *(*[]uint64)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)})) + return (*[1024]uint64)(unsafe.Pointer(c.pointer))[:] } // AsBitmap yields a 65k-bit bitmap, storing it in the target if a target @@ -441,21 +408,64 @@ func (c *Container) AsBitmap(target []uint64) (out []uint64) { } if c.typeID == containerRun { runs := c.runs() + b := (*[1024]uint64)(unsafe.Pointer(&out[0])) for _, r := range runs { - splatRun(out, r) + splatRun(b, r) } return out } // in theory this shouldn't happen? - return out + panic("unreachable") } -func splatRun(into []uint64, from interval16) { - // TODO this can be ~64x faster for long runs by setting maxBitmap instead of single bits - //note v must be int or will overflow - for v := int(from.start); v <= int(from.last); v++ { - into[v/64] |= (uint64(1) << uint(v%64)) +// fillerBitmap is a bitmap full of filler. +var fillerBitmap = func() (a [1024]uint64) { + for i := range a { + a[i] = ^uint64(0) } + return a +}() + +func splatRun(into *[1024]uint64, from Interval16) { + // TODO this can be ~64x faster for long runs by setting maxBitmap instead of single bits + // note v must be int or will overflow + // for v := int(from.Start); v <= int(from.Last); v++ { + // into[v/64] |= (uint64(1) << uint(v%64)) + // } + + // Handle the case where the start and end fall within the same word. + if from.Start/64 == from.Last/64 { + highMask := ^uint64(0) >> (63 - (from.Last % 64)) + lowMask := ^uint64(0) << (from.Start % 64) + into[from.Start/64] |= highMask & lowMask + return + } + + // Calculate preliminary bulk fill bounds. + fillStart, fillEnd := from.Start/64, from.Last/64 + + // Handle run start. + if from.Start%64 != 0 { + into[from.Start/64] |= ^uint64(0) << (from.Start % 64) + fillStart++ + } + + // Handle run end. + if from.Last%64 != 63 { + into[from.Last/64] |= ^uint64(0) >> (63 - (from.Last % 64)) + fillEnd-- + } + + // Bulk fill everything inbetween. + // Sufficiently large runs will use AVX under the hood. + copy(into[fillStart:fillEnd+1], fillerBitmap[:]) +} + +// setBitmapCopy stores a copy of a bitmap as data. +func (c *Container) setBitmapCopy(bitmap []uint64) { + var bitmapCopy [bitmapN]uint64 + copy(bitmapCopy[:], bitmap) + c.setBitmap(bitmapCopy[:]) } // setBitmap stores a set of uint64s as data. @@ -468,32 +478,34 @@ func (c *Container) setBitmap(bitmap []uint64) { panic("attempt to write non-bitmap's bitmap") } } - h := (*reflect.SliceHeader)(unsafe.Pointer(&bitmap)) - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap) - runtime.KeepAlive(&bitmap) + if len(bitmap) != 1024 { + panic("illegal bitmap length") + } + c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&bitmap[0])), bitmapN, bitmapN + c.flags &^= flagPristine } // runs yields the data viewed as a slice of intervals. -func (c *Container) runs() []interval16 { +func (c *Container) runs() []Interval16 { + if c == nil { + panic("attempt to read nil container's runs") + } if roaringParanoia { - if c == nil { - panic("attempt to read nil container's runs") - } if c.typeID != containerRun { panic("attempt to read non-run's runs") } } - return *(*[]interval16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)})) + return (*[1 << 15]Interval16)(unsafe.Pointer(c.pointer))[:c.len:c.cap] } // setRuns stores a set of intervals as data. c must not be frozen. -func (c *Container) setRuns(runs []interval16) { +func (c *Container) setRuns(runs []Interval16) { c.setRunsMaybeCopy(runs, false) } // setRunsMaybeCopy stores a set of intervals as data. c must not be frozen. // If doCopy is set, the values will be copied to different storage. -func (c *Container) setRunsMaybeCopy(runs []interval16, doCopy bool) { +func (c *Container) setRunsMaybeCopy(runs []Interval16, doCopy bool) { if roaringParanoia { if c == nil || c.frozen() { panic("setRuns on nil or frozen container") @@ -502,33 +514,30 @@ func (c *Container) setRunsMaybeCopy(runs []interval16, doCopy bool) { panic("attempt to write non-run's runs") } } - // no array: start with our default 2-value array - if runs == nil { - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedRunSize - return + if len(runs) > 1<<15 { + panic("impossibly large run set") } - h := (*reflect.SliceHeader)(unsafe.Pointer(&runs)) - if h.Data == uintptr(unsafe.Pointer(c.pointer)) { - // nothing to do but update length - c.len = int32(h.Len) - return - } - + c.flags &^= flagPristine // array we can fit in data store: if len(runs) <= stashedRunSize { - newRuns := *(*[]interval16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(&c.data[0])), Len: stashedRunSize, Cap: stashedRunSize})) + newRuns := (*[stashedRunSize]Interval16)(unsafe.Pointer(&c.data))[:len(runs)] copy(newRuns, runs) - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(len(runs)), stashedRunSize + c.pointer, c.len, c.cap = &c.data[0], int32(len(newRuns)), int32(cap(newRuns)) c.flags &^= flagMapped // this is no longer using a hypothetical mmapped input array return } - if doCopy { - r2 := make([]interval16, len(runs)) - copy(r2, runs) - h = (*reflect.SliceHeader)(unsafe.Pointer(&r2)) + if &runs[0].Start == c.pointer && !doCopy { + // nothing to do but update length + c.len = int32(len(runs)) + return } - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap) - runtime.KeepAlive(&runs) + if doCopy { + runs = append([]Interval16(nil), runs...) + } + if cap(runs) > 1<<15 { + runs = runs[: len(runs) : 1<<15] + } + c.pointer, c.len, c.cap = &runs[0].Start, int32(len(runs)), int32(cap(runs)) } // UpdateOrMake updates the container, yielding a new container if necessary. @@ -555,9 +564,9 @@ func (c *Container) UpdateOrMake(typ byte, n int32, mapped bool) *Container { // we don't know that any existing slice is usable, so let's ditch it switch c.typeID { case containerArray: - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(0), stashedArraySize + c.pointer, c.len, c.cap = &c.data[0], 0, stashedArraySize case containerRun: - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedRunSize + c.pointer, c.len, c.cap = &c.data[0], 0, stashedRunSize default: c.pointer, c.len, c.cap = nil, 0, 0 } @@ -578,9 +587,9 @@ func (c *Container) Update(typ byte, n int32, mapped bool) { // we don't know that any existing slice is usable, so let's ditch it switch c.typeID { case containerArray: - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(0), stashedArraySize + c.pointer, c.len, c.cap = nil, 0, 0 case containerRun: - c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedRunSize + c.pointer, c.len, c.cap = nil, 0, 0 default: c.pointer, c.len, c.cap = nil, 0, 0 } @@ -588,30 +597,24 @@ func (c *Container) Update(typ byte, n int32, mapped bool) { // isArray returns true if the container is an array container. func (c *Container) isArray() bool { - if roaringParanoia { - if c == nil { - panic("calling isArray on nil container") - } + if c == nil { + panic("calling isArray on nil container") } return c.typeID == containerArray } // isBitmap returns true if the container is a bitmap container. func (c *Container) isBitmap() bool { - if roaringParanoia { - if c == nil { - panic("calling isBitmap on nil container") - } + if c == nil { + panic("calling isBitmap on nil container") } return c.typeID == containerBitmap } // isRun returns true if the container is a run-length-encoded container. func (c *Container) isRun() bool { - if roaringParanoia { - if c == nil { - panic("calling isRun on nil container") - } + if c == nil { + panic("calling isRun on nil container") } return c.typeID == containerRun } diff --git a/roaring/containers_btree.go b/roaring/containers_btree.go index 280fd5edc..257a756fa 100644 --- a/roaring/containers_btree.go +++ b/roaring/containers_btree.go @@ -68,32 +68,6 @@ func (btc *bTreeContainers) Put(key uint64, c *Container) { btc.tree.Set(key, c) } -func (u updater) update(oldV *Container, exists bool) (*Container, bool) { - // update the existing container - if exists { - oldV = oldV.UpdateOrMake(u.typ, u.n, u.mapped) - return oldV, true - } - cont := NewContainer() - cont.setTyp(u.typ) - cont.setN(u.n) - cont.setMapped(u.mapped) - return cont, true -} - -// this struct is added to prevent the closure locals from being escaped out to the heap -type updater struct { - key uint64 - n int32 - typ byte - mapped bool -} - -func (btc *bTreeContainers) PutContainerValues(key uint64, typ byte, n int, mapped bool) { - a := updater{key, int32(n), typ, mapped} - btc.tree.Put(key, a.update) -} - func (btc *bTreeContainers) Remove(key uint64) { btc.tree.Delete(key) if key == btc.lastKey { diff --git a/roaring/containers_slice.go b/roaring/containers_slice.go index 98fe91fd3..1eaa65cf0 100644 --- a/roaring/containers_slice.go +++ b/roaring/containers_slice.go @@ -47,29 +47,6 @@ func (sc *sliceContainers) Put(key uint64, c *Container) { sc.lastContainer = c } -func (sc *sliceContainers) PutContainerValues(key uint64, typ byte, n int, mapped bool) { - i := search64(sc.keys, key) - if i < 0 { - c := NewContainer() - c.setTyp(typ) - c.setN(int32(n)) - c.setMapped(mapped) - sc.insertAt(key, c, -i-1) - } else { - // if the container already exists, and is frozen, this may - // result in copying its data, which is sort of pointless - // because PutContainerValues almost always gets called - // because we're reading new data from a file -- but also - // that means this case probably never happens. - c := sc.containers[i].Thaw() - c.setTyp(typ) - c.setN(int32(n)) - c.setMapped(mapped) - sc.containers[i] = c - } - -} - func (sc *sliceContainers) Remove(key uint64) { statsHit("sliceContainers/Remove") i := search64(sc.keys, key) diff --git a/roaring/containers_test.go b/roaring/containers_test.go index 6cd950514..8e66854d0 100644 --- a/roaring/containers_test.go +++ b/roaring/containers_test.go @@ -15,6 +15,7 @@ package roaring import ( + "math/rand" "testing" ) @@ -185,3 +186,47 @@ func TestSliceContainers(t *testing.T) { } }) } + +func genRun(r *rand.Rand) Interval16 { +gen: + dat := r.Uint32() + start, end := uint16(dat>>16), uint16(dat) + if start > end { + goto gen + } + return Interval16{start, end} +} + +func splatRunNaive(into []uint64, from Interval16) { + for v := int(from.Start); v <= int(from.Last); v++ { + into[v/64] |= (uint64(1) << uint(v%64)) + } +} + +func TestSplat(t *testing.T) { + r := rand.New(rand.NewSource(42)) + for i := 0; i < 1024; i++ { + run := genRun(r) + + var a, b [1024]uint64 + splatRunNaive(a[:], run) + splatRun(&b, run) + if a != b { + t.Errorf("incorrect splat of run [%d, %d]", run.Start, run.Last) + } + } +} + +func benchSplat(b *testing.B, run Interval16) { + var buf [1024]uint64 + for i := 0; i < b.N; i++ { + splatRun(&buf, run) + } +} + +func BenchmarkSplatSingle(b *testing.B) { benchSplat(b, Interval16{42, 42}) } +func BenchmarkSplatPartword(b *testing.B) { benchSplat(b, Interval16{16, 31}) } +func BenchmarkSplatWord(b *testing.B) { benchSplat(b, Interval16{16, 31}) } +func BenchmarkSplatEdges(b *testing.B) { benchSplat(b, Interval16{15, 16}) } +func BenchmarkSplatMedium(b *testing.B) { benchSplat(b, Interval16{13, 65}) } +func BenchmarkSplatAll(b *testing.B) { benchSplat(b, Interval16{0, ^uint16(0)}) } diff --git a/roaring/roaring.go b/roaring/roaring.go index db63b0edd..fc75ef110 100644 --- a/roaring/roaring.go +++ b/roaring/roaring.go @@ -21,7 +21,6 @@ import ( "hash/fnv" "io" "math/bits" - "reflect" "sort" "unsafe" @@ -55,7 +54,7 @@ const ( // bitmapN is the number of values in a container.bitmap. bitmapN = (1 << 16) / 64 - maxContainerVal = 0xffff + MaxContainerVal = 0xffff // maxContainerKey is the key representing the last container in a full row. // It is the full bitmap space (2^64) divided by container width (2^16). @@ -76,7 +75,7 @@ var containerTypeNames = map[byte]string{ containerRun: "run", } -var fullContainer = NewContainerRun([]interval16{{start: 0, last: maxContainerVal}}).Freeze() +var fullContainer = NewContainerRun([]Interval16{{Start: 0, Last: MaxContainerVal}}).Freeze() // AdvisoryError is used for the special case where we probably want to *report* // an error reading a file, but don't want to actually count the file as not @@ -125,11 +124,6 @@ type Containers interface { // Put adds the container at key. Put(key uint64, c *Container) - // PutContainerValues updates an existing container at key. - // If a container does not exist for key, a new one is allocated. - // TODO(2.0) make n int32 - PutContainerValues(key uint64, typ byte, n int, mapped bool) - // Remove takes the container at key out. Remove(key uint64) @@ -236,8 +230,7 @@ func NewSliceBitmap(a ...uint64) *Bitmap { } // NewFileBitmap returns a Bitmap with an initial set of values, used for file storage. -// By default, this is a copy of NewBitmap, but is replaced with B+Tree in server/enterprise.go -var NewFileBitmap func(a ...uint64) *Bitmap = NewBTreeBitmap +var NewFileBitmap = NewBTreeBitmap // Clone returns a heap allocated copy of the bitmap. // Note: The OpWriter IS NOT copied to the new bitmap. @@ -296,6 +289,7 @@ func (b *Bitmap) Add(a ...uint64) (changed bool, err error) { // AddN adds values to the bitmap, appending them all to the op log in a batched // write. It returns the number of changed bits. +// The input slice may be reordered, and the set of changed bits will end up in a[:changed]. func (b *Bitmap) AddN(a ...uint64) (changed int, err error) { if len(a) == 0 { return 0, nil @@ -468,7 +462,7 @@ func (b *Bitmap) Count() (n uint64) { return b.Containers.Count() } -// Any returns "b.Count() > 0"... but faster than doing that. +// Any checks whether there are any set bits within the bitmap. func (b *Bitmap) Any() bool { iter, _ := b.Containers.Iterator(0) // TODO (jaffee) I'm not sure if it's possible/legal to have an empty @@ -530,7 +524,7 @@ func (b *Bitmap) CountRange(start, end uint64) (n uint64) { break } if k == skey { - n += uint64(c.countRange(int32(lowbits(start)), maxContainerVal+1)) + n += uint64(c.countRange(int32(lowbits(start)), MaxContainerVal+1)) continue } if k < ekey { @@ -574,21 +568,27 @@ func (b *Bitmap) SliceRange(start, end uint64) []uint64 { } // ForEach executes fn for each value in the bitmap. -func (b *Bitmap) ForEach(fn func(uint64)) { +func (b *Bitmap) ForEach(fn func(uint64) error) error { itr := b.Iterator() itr.Seek(0) for v, eof := itr.Next(); !eof; v, eof = itr.Next() { - fn(v) + if err := fn(v); err != nil { + return err + } } + return nil } // ForEachRange executes fn for each value in the bitmap between [start, end). -func (b *Bitmap) ForEachRange(start, end uint64, fn func(uint64)) { +func (b *Bitmap) ForEachRange(start, end uint64, fn func(uint64) error) error { itr := b.Iterator() itr.Seek(start) for v, eof := itr.Next(); !eof && v < end; v, eof = itr.Next() { - fn(v) + if err := fn(v); err != nil { + return err + } } + return nil } // OffsetRange returns a new bitmap with a containers offset by start. @@ -829,7 +829,7 @@ func (c *Container) intersectInPlace(other *Container) *Container { c = nil return c } - cFull, otherFull := (c.N() == maxContainerVal+1), (other.N() == maxContainerVal+1) + cFull, otherFull := (c.N() == MaxContainerVal+1), (other.N() == MaxContainerVal+1) if cFull && otherFull { return c } @@ -872,10 +872,7 @@ func (c *Container) intersectInPlace(other *Container) *Container { } } - if roaringParanoia { - panic(fmt.Sprintf("invalid intersect op: unknown types %d/%d", c.typ(), other.typ())) - } - return nil + panic(fmt.Errorf("invalid intersect op: unknown types %d/%d", c.typ(), other.typ())) } func (c *Container) copyInPlace(other *Container) *Container { @@ -883,19 +880,19 @@ func (c *Container) copyInPlace(other *Container) *Container { case containerArray: c.setTyp(containerArray) c.setArrayMaybeCopy(other.array(), true) - c.setN(other.N()) case containerBitmap: - bmp := make([]uint64, bitmapN) - copy(bmp, other.bitmap()) c.setTyp(containerBitmap) - c.setBitmap(bmp) + c.setBitmapCopy(other.bitmap()) c.setN(other.N()) case containerRun: c.setTyp(containerRun) c.setRunsMaybeCopy(other.runs(), true) c.setN(other.N()) + + default: + panic(fmt.Errorf("invalid container type: %v", c.typ())) } return c @@ -936,9 +933,9 @@ func intersectArrayRunInPlace(a, b *Container) *Container { n := 0 for i, j := 0, 0; i < an && j < bn; { va, vb := aa[i], br[j] - if va < vb.start { + if va < vb.Start { i++ - } else if va > vb.last { + } else if va > vb.Last { j++ } else { aa[n] = va @@ -987,6 +984,9 @@ func intersectBitmapBitmapInPlace(a, b *Container) *Container { n := int32(0) for i := 0; i < bitmapN; i += 4 { // unrolling is still effective in go + // TODO: the generated machine code is extremely bad here, because we are forcing the compiler to reload ab immediately after storing it + // The body of the loop has a total of 8 branches: 4 bounds checks + 4 feature checks. + // We could substantially improve this by converting the entire bitmap to [256][4]uint64. ptr := (*[4]uint64)(unsafe.Pointer(&bb[i])) ab[i] &= ptr[0] ab[i+1] &= ptr[1] @@ -1024,7 +1024,6 @@ func intersectBitmapArrayInPlace(a, b *Container) *Container { array = array[:n] a.setTyp(containerArray) a.setArray(array) - a.setN(n) return a } @@ -1040,26 +1039,26 @@ func intersectBitmapRunInPlace(a, b *Container) *Container { n := int32(0) for _, vb := range br { - i := vb.start >> 6 // index into a + i := vb.Start >> 6 // index into a vastart := i << 6 valast := vastart + 63 - for valast >= vb.start && vastart <= vb.last && int(i) < an { - if vastart >= vb.start && valast <= vb.last { // a within b + for valast >= vb.Start && vastart <= vb.Last && int(i) < an { + if vastart >= vb.Start && valast <= vb.Last { // a within b bitmap[i] = ab[i] n += int32(popcount(ab[i])) - } else if vb.start >= vastart && vb.last <= valast { // b within a - var mask uint64 = ((1 << (vb.last - vb.start + 1)) - 1) << (vb.start - vastart) + } else if vb.Start >= vastart && vb.Last <= valast { // b within a + var mask uint64 = ((1 << (vb.Last - vb.Start + 1)) - 1) << (vb.Start - vastart) bits := ab[i] & mask bitmap[i] |= bits n += int32(popcount(bits)) - } else if vastart < vb.start { // a overlaps front of b - offset := 64 - (1 + valast - vb.start) + } else if vastart < vb.Start { // a overlaps front of b + offset := 64 - (1 + valast - vb.Start) bits := (ab[i] >> offset) << offset bitmap[i] |= bits n += int32(popcount(bits)) - } else if vb.start < vastart { // b overlaps front of a - offset := 64 - (1 + vb.last - vastart) + } else if vb.Start < vastart { // b overlaps front of a + offset := 64 - (1 + vb.Last - vastart) bits := (ab[i] << offset) >> offset bitmap[i] |= bits n += int32(popcount(bits)) @@ -1083,42 +1082,42 @@ func intersectRunRunInPlace(a, b *Container) *Container { ar, br := a.runs(), b.runs() an, bn := len(ar), len(br) - var runs []interval16 + var runs []Interval16 if an > bn { - runs = make([]interval16, 0, an) + runs = make([]Interval16, 0, an) } else { - runs = make([]interval16, 0, bn) + runs = make([]Interval16, 0, bn) } n := int32(0) for i, j := 0, 0; i < an && j < bn; { va, vb := ar[i], br[j] - if va.last < vb.start { + if va.Last < vb.Start { // |--va--| |--vb--| i++ - } else if vb.last < va.start { + } else if vb.Last < va.Start { // |--vb--| |--va--| j++ - } else if va.last > vb.last && va.start >= vb.start { + } else if va.Last > vb.Last && va.Start >= vb.Start { // |--vb-|-|-va--| - runs = append(runs, interval16{start: va.start, last: vb.last}) - n += int32(vb.last-va.start) + 1 + runs = append(runs, Interval16{Start: va.Start, Last: vb.Last}) + n += int32(vb.Last-va.Start) + 1 j++ - } else if va.last > vb.last && va.start < vb.start { + } else if va.Last > vb.Last && va.Start < vb.Start { // |--va|--vb--|--| runs = append(runs, vb) - n += int32(vb.last-vb.start) + 1 + n += int32(vb.Last-vb.Start) + 1 j++ - } else if va.last <= vb.last && va.start >= vb.start { + } else if va.Last <= vb.Last && va.Start >= vb.Start { // |--vb|--va--|--| runs = append(runs, va) - n += int32(va.last-va.start) + 1 + n += int32(va.Last-va.Start) + 1 i++ - } else if va.last <= vb.last && va.start < vb.start { + } else if va.Last <= vb.Last && va.Start < vb.Start { // |--va-|-|-vb--| - runs = append(runs, interval16{start: vb.start, last: va.last}) - n += int32(va.last-vb.start) + 1 + runs = append(runs, Interval16{Start: vb.Start, Last: va.Last}) + n += int32(va.Last-vb.Start) + 1 i++ } } @@ -1139,9 +1138,9 @@ func intersectRunArrayInPlace(a, b *Container) *Container { n := 0 for i, j := 0, 0; i < an && j < bn; { va, vb := ar[i], ba[j] - if vb < va.start { + if vb < va.Start { j++ - } else if vb > va.last { + } else if vb > va.Last { i++ } else { array[n] = vb @@ -1363,7 +1362,7 @@ func (b *Bitmap) unionInPlace(others ...*Bitmap) { tContainer := target.Containers.Get(iKey) // if the target's full, short-circuit out. if tContainer != nil { - if tContainer.N() == maxContainerVal+1 { + if tContainer.N() == MaxContainerVal+1 { bitmapIters.markItersWithKeyAsHandled(i, iKey) continue } @@ -1534,6 +1533,9 @@ func (b *Bitmap) Xor(other *Bitmap) *Bitmap { } // Shift shifts the contents of b by 1. +// +// NOTE: This method is unsupported. See the `Shift()` +// method on `Row` in `row.go`. func (b *Bitmap) Shift(n int) (*Bitmap, error) { if n != 1 { return nil, errors.New("cannot shift by a value other than 1") @@ -1718,11 +1720,14 @@ func (b *Bitmap) writeToUnoptimized(w io.Writer) (n int64, err error) { // bitmap and yield information about containers, including type, size, and // the location of their data structures. type roaringIterator interface { + // Len reports the number of containers total. + Len() (count int64) // Next yields the information about the next container Next() (key uint64, cType byte, n int, length int, pointer *uint16, err error) // Remaining yields the bytes left over past the end of the roaring data, - // which is typically an ops log in our case. - Remaining() []byte + // which is typically an ops log in our case, and also its offset in case + // we need to talk about truncation. + Remaining() ([]byte, int64) } // baseRoaringIterator holds values used by both Pilosa and official Roaring @@ -1881,11 +1886,16 @@ func (r *baseRoaringIterator) Done(err error) { r.currentDataOffset = 0 } -func (r *baseRoaringIterator) Remaining() []byte { +// Len() indicates the total number of containers the iterator expects to have. +func (r *baseRoaringIterator) Len() int64 { + return r.keys +} + +func (r *baseRoaringIterator) Remaining() ([]byte, int64) { if r.lastDataOffset == 0 { - return nil + return nil, 0 } - return r.data[r.lastDataOffset:] + return r.data[r.lastDataOffset:], r.lastDataOffset } func (r *pilosaRoaringIterator) Next() (key uint64, cType byte, n int, length int, pointer *uint16, err error) { @@ -1992,11 +2002,11 @@ func (r *officialRoaringIterator) Next() (key uint64, cType byte, n int, length case containerRun: // official format stores runs as start/len, we want to convert, but since // they might be mmapped, we can't write to that memory - newRuns := make([]interval16, runCount) - oldRuns := (*[65536]interval16)(unsafe.Pointer(r.currentPointer))[:runCount:runCount] + newRuns := make([]Interval16, runCount) + oldRuns := (*[65536]Interval16)(unsafe.Pointer(r.currentPointer))[:runCount:runCount] copy(newRuns, oldRuns) for i := range newRuns { - newRuns[i].last += newRuns[i].start + newRuns[i].Last += newRuns[i].Start } r.currentPointer = (*uint16)(unsafe.Pointer(&newRuns[0])) r.currentLen = int(runCount) @@ -2173,7 +2183,7 @@ func (b *Bitmap) ImportRoaringBits(data []byte, clear bool, log bool, rowSize ui } else { importUpdater = func(oldC *Container, existed bool) (newC *Container, write bool) { existN := oldC.N() - if existN == maxContainerVal+1 { + if existN == MaxContainerVal+1 { return oldC, false } if existN == 0 { @@ -2386,20 +2396,16 @@ func BitmapsToRoaring(bitmaps []*Bitmap) []byte { binary.LittleEndian.PutUint16(header[10:12], uint16(n-1)) binary.LittleEndian.PutUint32(offset[0:4], uint32(dataOffset+int(offsetEnd))) nextData := data[dataOffset:] - switch c.typeID { + switch c.typeID { // TODO: make this work on big endian machines case containerArray: - asUint16 := *(*[]uint16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(&nextData[0])), Len: int(c.len), Cap: int(c.len)})) - copy(asUint16, c.array()) - dataOffset += 2 * int(c.len) + dataOffset += 2 * copy((*[1 << 16]uint16)(unsafe.Pointer(&nextData[0]))[:], c.array()) case containerBitmap: - asUint64 := *(*[]uint64)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(&nextData[0])), Len: 1024, Cap: 1024})) - copy(asUint64, c.bitmap()) + copy((*[1024]uint64)(unsafe.Pointer(&nextData[0]))[:], c.bitmap()) dataOffset += 8192 case containerRun: - asInterval16 := *(*[]interval16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(&nextData[2])), Len: int(c.len), Cap: int(c.len)})) - copy(asInterval16, c.runs()) binary.LittleEndian.PutUint16(nextData[0:2], uint16(c.len)) - dataOffset += int(4*c.len) + 2 + dataOffset += 2 + dataOffset += 4 * copy((*[1 << 15]Interval16)(unsafe.Pointer(&nextData[2]))[:], c.runs()) } } } @@ -2432,19 +2438,24 @@ func (b *Bitmap) roaringSize() (int64, int64) { } // Info returns stats for the bitmap. -func (b *Bitmap) Info() bitmapInfo { - info := bitmapInfo{ - OpN: b.opN, - Ops: b.ops, - Containers: make([]containerInfo, 0, b.Containers.Size()), +func (b *Bitmap) Info(includeContainers bool) BitmapInfo { + info := BitmapInfo{ + OpN: b.opN, + Ops: b.ops, + ContainerCount: b.Containers.Size(), + } + if includeContainers { + info.Containers = make([]ContainerInfo, 0, info.ContainerCount) } - citer, _ := b.Containers.Iterator(0) for citer.Next() { k, c := citer.Value() ci := c.info() ci.Key = k - info.Containers = append(info.Containers, ci) + info.BitCount += uint64(c.N()) + if includeContainers { + info.Containers = append(info.Containers, ci) + } } return info } @@ -2501,11 +2512,16 @@ func (b *Bitmap) Flip(start, end uint64) *Bitmap { return result } -// bitmapInfo represents a point-in-time snapshot of bitmap stats. -type bitmapInfo struct { - OpN int - Ops int - Containers []containerInfo +// BitmapInfo represents a point-in-time snapshot of bitmap stats. +type BitmapInfo struct { + OpN int + Ops int + OpDetails []OpInfo `json:"OpDetails,omitempty"` + BitCount uint64 + ContainerCount int + Containers []ContainerInfo `json:"Containers,omitempty"` // The containers found in the bitmap originally + OpContainers []ContainerInfo `json:"OpContainers,omitempty"` // The containers resulting from ops log changes. + From, To uintptr // if set, indicates the address range used when unpacking } // Iterator represents an iterator over a Bitmap. @@ -2576,7 +2592,7 @@ func (itr *Iterator) Seek(seek uint64) { j, contains := binSearchRuns(lb, itr.c.runs()) if contains { itr.j = j - itr.k = int32(lb) - int32(itr.c.runs()[j].start) - 1 + itr.k = int32(lb) - int32(itr.c.runs()[j].Start) - 1 return } // If seek is larger than all elements, return. @@ -2650,7 +2666,7 @@ func (itr *Iterator) Next() (v uint64, eof bool) { } r := itr.c.runs()[itr.j] - runLength := int32(r.last - r.start) + runLength := int32(r.Last - r.Start) if itr.k >= runLength { // Reached end of run, move to the next run. @@ -2720,7 +2736,7 @@ func (itr *Iterator) peek() uint64 { return itr.key<<16 | uint64(itr.c.array()[itr.j]) } if itr.c.isRun() { - return itr.key<<16 | uint64(itr.c.runs()[itr.j].start+uint16(itr.k)) + return itr.key<<16 | uint64(itr.c.runs()[itr.j].Start+uint16(itr.k)) } return itr.key<<16 | uint64(itr.j) } @@ -2731,19 +2747,19 @@ const ArrayMaxSize = 4096 // runMaxSize represents the maximum size of run length encoded containers. const runMaxSize = 2048 -type interval16 struct { - start uint16 - last uint16 +type Interval16 struct { + Start uint16 + Last uint16 } // runlen returns the count of integers in the interval. -func (iv interval16) runlen() int32 { - return 1 + int32(iv.last-iv.start) +func (iv Interval16) runlen() int32 { + return 1 + int32(iv.Last-iv.Start) } // count counts all bits in the container. func (c *Container) count() (n int32) { - return c.countRange(0, maxContainerVal+1) + return c.countRange(0, MaxContainerVal+1) } // countRange counts the number of bits set between [start, end). @@ -2827,28 +2843,28 @@ func (c *Container) runCountRange(start, end int32) (n int32) { runs := c.runs() for _, iv := range runs { // iv is before range - if int32(iv.last) < start { + if int32(iv.Last) < start { continue } // iv is after range - if end < int32(iv.start) { + if end < int32(iv.Start) { break } // iv is superset of range - if int32(iv.start) <= start && int32(iv.last) >= end { + if int32(iv.Start) <= start && int32(iv.Last) >= end { return end - start } // iv is subset of range - if int32(iv.start) >= start && int32(iv.last) <= end { + if int32(iv.Start) >= start && int32(iv.Last) <= end { n += iv.runlen() } // iv overlaps beginning of range without being a subset - if int32(iv.start) < start && int32(iv.last) < end { - n += int32(iv.last) - start + 1 + if int32(iv.Start) < start && int32(iv.Last) < end { + n += int32(iv.Last) - start + 1 } // iv overlaps end of range without being a subset - if int32(iv.start) > start && int32(iv.last) >= end { - n += end - int32(iv.start) + if int32(iv.Start) > start && int32(iv.Last) >= end { + n += end - int32(iv.Start) } } return n @@ -2924,49 +2940,49 @@ func (c *Container) runAdd(v uint16) (*Container, bool) { if len(runs) == 0 { c = c.Thaw() - c.setRuns([]interval16{{start: v, last: v}}) + c.setRuns([]Interval16{{Start: v, Last: v}}) c.setN(1) return c, true } i := sort.Search(len(runs), - func(i int) bool { return runs[i].last >= v }) + func(i int) bool { return runs[i].Last >= v }) if i == len(runs) { i-- } iv := runs[i] - if v >= iv.start && iv.last >= v { + if v >= iv.Start && iv.Last >= v { return c, false } c = c.Thaw() runs = c.runs() - if iv.last < v { - if iv.last == v-1 { - runs[i].last++ + if iv.Last < v { + if iv.Last == v-1 { + runs[i].Last++ } else { - runs = append(runs, interval16{start: v, last: v}) + runs = append(runs, Interval16{Start: v, Last: v}) } - } else if v+1 == iv.start { + } else if v+1 == iv.Start { // combining two intervals - if i > 0 && runs[i-1].last == v-1 { - runs[i-1].last = iv.last + if i > 0 && runs[i-1].Last == v-1 { + runs[i-1].Last = iv.Last runs = append(runs[:i], runs[i+1:]...) c.setRuns(runs) c.setN(c.N() + 1) return c, true } // just before an interval - runs[i].start-- - } else if i > 0 && v-1 == runs[i-1].last { + runs[i].Start-- + } else if i > 0 && v-1 == runs[i-1].Last { // just after an interval - runs[i-1].last++ + runs[i-1].Last++ } else { // alone - newIv := interval16{start: v, last: v} - runs = append(runs[:i], append([]interval16{newIv}, runs[i:]...)...) + newIv := Interval16{Start: v, Last: v} + runs = append(runs[:i], append([]Interval16{newIv}, runs[i:]...)...) } c.setRuns(runs) c.setN(c.N() + 1) @@ -3097,7 +3113,7 @@ func (c *Container) unionInPlace(other *Container) *Container { return c } // short-circuit the trivial cases - if c.N() == maxContainerVal+1 || other.N() == maxContainerVal+1 { + if c.N() == MaxContainerVal+1 || other.N() == MaxContainerVal+1 { return fullContainer } switch c.typ() { @@ -3131,14 +3147,10 @@ func (c *Container) unionInPlace(other *Container) *Container { c = c.runToBitmap() return unionBitmapArrayInPlace(c, other) case containerRun: - c = c.runToBitmap() - return unionBitmapRunInPlace(c, other) + return unionRunRunInPlace(c, other) } } - if roaringParanoia { - panic(fmt.Sprintf("invalid union op: unknown types %d/%d", c.typ(), other.typ())) - } - return c + panic(fmt.Errorf("invalid union op: unknown types %d/%d", c.typ(), other.typ())) } func (c *Container) arrayContains(v uint16) bool { @@ -3151,11 +3163,11 @@ func (c *Container) bitmapContains(v uint16) bool { // binSearchRuns returns the index of the run containing v, and true, when v is contained; // or the index of the next run starting after v, and false, when v is not contained. -func binSearchRuns(v uint16, a []interval16) (int32, bool) { +func binSearchRuns(v uint16, a []Interval16) (int32, bool) { i := int32(sort.Search(len(a), - func(i int) bool { return a[i].last >= v })) + func(i int) bool { return a[i].Last >= v })) if i < int32(len(a)) { - return i, (v >= a[i].start) && (v <= a[i].last) + return i, (v >= a[i].Start) && (v <= a[i].Last) } return i, false @@ -3238,18 +3250,18 @@ func (c *Container) runRemove(v uint16) (*Container, bool) { } c = c.Thaw() runs = c.runs() - if v == runs[i].last && v == runs[i].start { + if v == runs[i].Last && v == runs[i].Start { runs = append(runs[:i], runs[i+1:]...) - } else if v == runs[i].last { - runs[i].last-- - } else if v == runs[i].start { - runs[i].start++ - } else if v > runs[i].start { - last := runs[i].last - runs[i].last = v - 1 - runs = append(runs, interval16{}) + } else if v == runs[i].Last { + runs[i].Last-- + } else if v == runs[i].Start { + runs[i].Start++ + } else if v > runs[i].Start { + last := runs[i].Last + runs[i].Last = v - 1 + runs = append(runs, Interval16{}) copy(runs[i+2:], runs[i+1:]) - runs[i+1] = interval16{start: v + 1, last: last} + runs[i+1] = Interval16{Start: v + 1, Last: last} // runs = append(runs[:i+1], append([]interval16{{start: v + 1, last: last}}, runs[i+1:]...)...) } c.setN(c.N() - 1) @@ -3297,7 +3309,7 @@ func (c *Container) runMax() uint16 { if len(runs) == 0 { return 0 } - return runs[len(runs)-1].last + return runs[len(runs)-1].Last } // bitmapToArray converts from bitmap format to array format. @@ -3404,8 +3416,8 @@ func (c *Container) runToBitmap() *Container { } bitmap := make([]uint64, bitmapN) for _, iv := range c.runs() { - w1, w2 := iv.start/64, iv.last/64 - b1, b2 := iv.start&63, iv.last&63 + w1, w2 := iv.Start/64, iv.Last/64 + b1, b2 := iv.Start&63, iv.Last&63 // a mask for everything under bit X looks like // (1 << x) - 1. Say b1 is 4; our mask will want // to have the bottom 4 bits be zero, so we shift @@ -3466,7 +3478,7 @@ func (c *Container) bitmapToRun(numRuns int32) *Container { if numRuns == 0 { numRuns = bitmapCountRuns(bitmap) } - runs := make([]interval16, 0, numRuns) + runs := make([]Interval16, 0, numRuns) current := bitmap[0] var i, start, last uint16 @@ -3495,12 +3507,12 @@ func (c *Container) bitmapToRun(numRuns int32) *Container { if current == maxBitmap { // bitmap[1023] == maxBitmap - runs = append(runs, interval16{start, maxContainerVal}) + runs = append(runs, Interval16{start, MaxContainerVal}) break } currentLast := uint16(trailingZeroN(^current)) last = 64*i + currentLast - runs = append(runs, interval16{start, last - 1}) + runs = append(runs, Interval16{start, last - 1}) // pad LSBs with 0s current = current & (current + 1) @@ -3540,17 +3552,17 @@ func (c *Container) arrayToRun(numRuns int32) *Container { numRuns = arrayCountRuns(array) } - runs := make([]interval16, 0, numRuns) + runs := make([]Interval16, 0, numRuns) start := array[0] for i, v := range array[1:] { if v-array[i] > 1 { // if current-previous > 1, one run ends and another begins - runs = append(runs, interval16{start, array[i]}) + runs = append(runs, Interval16{start, array[i]}) start = v } } // append final run - runs = append(runs, interval16{start, array[c.N()-1]}) + runs = append(runs, Interval16{start, array[c.N()-1]}) if c.frozen() { return NewContainerRunN(runs, c.N()) } @@ -3585,7 +3597,7 @@ func (c *Container) runToArray() *Container { array := make([]uint16, c.N()) n := int32(0) for _, r := range runs { - for v := int(r.start); v <= int(r.last); v++ { + for v := int(r.Start); v <= int(r.Last); v++ { array[n] = uint16(v) n++ } @@ -3702,13 +3714,14 @@ func (c *Container) size() int { } // info returns the current stats about the container. -func (c *Container) info() containerInfo { - info := containerInfo{N: c.N()} +func (c *Container) info() ContainerInfo { + info := ContainerInfo{N: c.N(), Mapped: c.Mapped()} if c == nil { info.Type = "nil" info.Alloc = 0 return info } + info.Flags = c.flags.String() if c.isArray() { info.Type = "array" @@ -3720,17 +3733,7 @@ func (c *Container) info() containerInfo { info.Type = "bitmap" info.Alloc = len(c.bitmap()) * 8 // sizeof(uint64) } - - if c.Mapped() { - if c.isArray() { - info.Pointer = unsafe.Pointer(&c.array()[0]) - } else if c.isRun() { - info.Pointer = unsafe.Pointer(&c.runs()[0]) - } else { - info.Pointer = unsafe.Pointer(&c.bitmap()[0]) - } - } - + info.Pointer = uintptr(unsafe.Pointer(c.pointer)) return info } @@ -3747,12 +3750,12 @@ func (c *Container) check() error { a.Append(fmt.Errorf("array count mismatch: count=%d, n=%d", len(array), c.N())) } } else if c.isRun() { - n := c.runCountRange(0, maxContainerVal+1) + n := c.runCountRange(0, MaxContainerVal+1) if n != c.N() { a.Append(fmt.Errorf("run count mismatch: count=%d, n=%d", n, c.N())) } } else if c.isBitmap() { - if n := c.bitmapCountRange(0, maxContainerVal+1); n != c.N() { + if n := c.bitmapCountRange(0, MaxContainerVal+1); n != c.N() { a.Append(fmt.Errorf("bitmap count mismatch: count=%d, n=%d", n, c.N())) } } else { @@ -3796,13 +3799,15 @@ func (c *Container) bitmapRepair() { c.setN(n) } -// containerInfo represents a point-in-time snapshot of container stats. -type containerInfo struct { - Key uint64 // container key - Type string // container type (array, bitmap, or run) - N int32 // number of bits - Alloc int // memory used - Pointer unsafe.Pointer // offset within the mmap +// ContainerInfo represents a point-in-time snapshot of container stats. +type ContainerInfo struct { + Key uint64 // container key + Type string // container type (array, bitmap, or run) + Flags string // flag state + N int32 // number of bits + Alloc int // memory used + Pointer uintptr // address + Mapped bool // whether this container thinks it is mmapped } // flip returns a new container containing the inverse of all @@ -3847,10 +3852,10 @@ func flipRun(b *Container) *Container { } func intersectionCount(a, b *Container) int32 { - if a.N() == maxContainerVal+1 { + if a.N() == MaxContainerVal+1 { return b.N() } - if b.N() == maxContainerVal+1 { + if b.N() == MaxContainerVal+1 { return a.N() } if a.N() == 0 || b.N() == 0 { @@ -3912,12 +3917,12 @@ func intersectionCountArrayRun(a, b *Container) (n int32) { na, nb := len(array), len(runs) for i, j := 0, 0; i < na && j < nb; { va, vb := array[i], runs[j] - if va < vb.start { + if va < vb.Start { i++ - } else if va >= vb.start && va <= vb.last { + } else if va >= vb.Start && va <= vb.Last { i++ n++ - } else if va > vb.last { + } else if va > vb.Last { j++ } } @@ -3930,27 +3935,27 @@ func intersectionCountRunRun(a, b *Container) (n int32) { na, nb := len(ra), len(rb) for i, j := 0, 0; i < na && j < nb; { va, vb := ra[i], rb[j] - if va.last < vb.start { + if va.Last < vb.Start { // |--va--| |--vb--| i++ - } else if va.start > vb.last { + } else if va.Start > vb.Last { // |--vb--| |--va--| j++ - } else if va.last > vb.last && va.start >= vb.start { + } else if va.Last > vb.Last && va.Start >= vb.Start { // |--vb-|-|-va--| - n += 1 + int32(vb.last-va.start) + n += 1 + int32(vb.Last-va.Start) j++ - } else if va.last > vb.last && va.start < vb.start { + } else if va.Last > vb.Last && va.Start < vb.Start { // |--va|--vb--|--| - n += 1 + int32(vb.last-vb.start) + n += 1 + int32(vb.Last-vb.Start) j++ - } else if va.last <= vb.last && va.start >= vb.start { + } else if va.Last <= vb.Last && va.Start >= vb.Start { // |--vb|--va--|--| - n += 1 + int32(va.last-va.start) + n += 1 + int32(va.Last-va.Start) i++ - } else if va.last <= vb.last && va.start < vb.start { + } else if va.Last <= vb.Last && va.Start < vb.Start { // |--va-|-|-vb--| - n += 1 + int32(va.last-vb.start) + n += 1 + int32(va.Last-vb.Start) i++ } } @@ -3960,7 +3965,7 @@ func intersectionCountRunRun(a, b *Container) (n int32) { func intersectionCountBitmapRun(a, b *Container) (n int32) { statsHit("intersectionCount/BitmapRun") for _, iv := range b.runs() { - n += a.bitmapCountRange(int32(iv.start), int32(iv.last)+1) + n += a.bitmapCountRange(int32(iv.Start), int32(iv.Last)+1) } return n } @@ -3986,10 +3991,10 @@ func intersectionCountBitmapBitmap(a, b *Container) (n int32) { } func intersect(a, b *Container) *Container { - if a.N() == maxContainerVal+1 { + if a.N() == MaxContainerVal+1 { return b.Freeze() } - if b.N() == maxContainerVal+1 { + if b.N() == MaxContainerVal+1 { return a.Freeze() } if a.N() == 0 || b.N() == 0 { @@ -4051,9 +4056,9 @@ func intersectArrayRun(a, b *Container) *Container { var output []uint16 for i, j := 0, 0; i < na && j < nb; { va, vb := aa[i], rb[j] - if va < vb.start { + if va < vb.Start { i++ - } else if va > vb.last { + } else if va > vb.Last { j++ } else { output = append(output, va) @@ -4072,27 +4077,27 @@ func intersectRunRun(a, b *Container) *Container { n := int32(0) for i, j := 0, 0; i < na && j < nb; { va, vb := ra[i], rb[j] - if va.last < vb.start { + if va.Last < vb.Start { // |--va--| |--vb--| i++ - } else if vb.last < va.start { + } else if vb.Last < va.Start { // |--vb--| |--va--| j++ - } else if va.last > vb.last && va.start >= vb.start { + } else if va.Last > vb.Last && va.Start >= vb.Start { // |--vb-|-|-va--| - n += output.runAppendInterval(interval16{start: va.start, last: vb.last}) + n += output.runAppendInterval(Interval16{Start: va.Start, Last: vb.Last}) j++ - } else if va.last > vb.last && va.start < vb.start { + } else if va.Last > vb.Last && va.Start < vb.Start { // |--va|--vb--|--| n += output.runAppendInterval(vb) j++ - } else if va.last <= vb.last && va.start >= vb.start { + } else if va.Last <= vb.Last && va.Start >= vb.Start { // |--vb|--va--|--| n += output.runAppendInterval(va) i++ - } else if va.last <= vb.last && va.start < vb.start { + } else if va.Last <= vb.Last && va.Start < vb.Start { // |--va-|-|-vb--| - n += output.runAppendInterval(interval16{start: vb.start, last: va.last}) + n += output.runAppendInterval(Interval16{Start: vb.Start, Last: va.Last}) i++ } } @@ -4116,7 +4121,7 @@ func intersectBitmapRun(a, b *Container) *Container { // output is array container array := make([]uint16, 0, b.N()) for _, iv := range runs { - for i := iv.start; i <= iv.last; i++ { + for i := iv.Start; i <= iv.Last; i++ { if a.bitmapContains(i) { array = append(array, i) } @@ -4138,25 +4143,25 @@ func intersectBitmapRun(a, b *Container) *Container { n := int32(0) for j := 0; j < len(runs); j++ { vb := runs[j] - i := vb.start >> 6 // index into a + i := vb.Start >> 6 // index into a vastart := i << 6 valast := vastart + 63 - for valast >= vb.start && vastart <= vb.last && i < bitmapN { - if vastart >= vb.start && valast <= vb.last { // a within b + for valast >= vb.Start && vastart <= vb.Last && i < bitmapN { + if vastart >= vb.Start && valast <= vb.Last { // a within b bitmap[i] = aBitmap[i] n += int32(popcount(aBitmap[i])) - } else if vb.start >= vastart && vb.last <= valast { // b within a - var mask uint64 = ((1 << (vb.last - vb.start + 1)) - 1) << (vb.start - vastart) + } else if vb.Start >= vastart && vb.Last <= valast { // b within a + var mask uint64 = ((1 << (vb.Last - vb.Start + 1)) - 1) << (vb.Start - vastart) bits := aBitmap[i] & mask bitmap[i] |= bits n += int32(popcount(bits)) - } else if vastart < vb.start { // a overlaps front of b - offset := 64 - (1 + valast - vb.start) + } else if vastart < vb.Start { // a overlaps front of b + offset := 64 - (1 + valast - vb.Start) bits := (aBitmap[i] >> offset) << offset bitmap[i] |= bits n += int32(popcount(bits)) - } else if vb.start < vastart { // b overlaps front of a - offset := 64 - (1 + vb.last - vastart) + } else if vb.Start < vastart { // b overlaps front of a + offset := 64 - (1 + vb.Last - vastart) bits := (aBitmap[i] << offset) >> offset bitmap[i] |= bits n += int32(popcount(bits)) @@ -4208,7 +4213,7 @@ func intersectBitmapBitmap(a, b *Container) *Container { } func union(a, b *Container) *Container { - if a.N() == maxContainerVal+1 || b.N() == maxContainerVal+1 { + if a.N() == MaxContainerVal+1 || b.N() == MaxContainerVal+1 { return fullContainer } if a.isArray() { @@ -4237,7 +4242,9 @@ func union(a, b *Container) *Container { } } } +func Merge(a, b []uint16) { +} func unionArrayArray(a, b *Container) *Container { statsHit("union/ArrayArray") if a.N() == 0 { @@ -4346,7 +4353,7 @@ func unionArrayRun(a, b *Container) *Container { output := NewContainerRun(nil) aa, rb := a.array(), b.runs() na, nb := len(aa), len(rb) - var vb interval16 + var vb Interval16 var va uint16 n := int32(0) for i, j := 0, 0; i < na || j < nb; { @@ -4356,8 +4363,8 @@ func unionArrayRun(a, b *Container) *Container { if j < nb { vb = rb[j] } - if i < na && (j >= nb || va < vb.start) { - n += output.runAppendInterval(interval16{start: va, last: va}) + if i < na && (j >= nb || va < vb.Start) { + n += output.runAppendInterval(Interval16{Start: va, Last: va}) i++ } else { n += output.runAppendInterval(vb) @@ -4379,26 +4386,26 @@ func unionArrayRun(a, b *Container) *Container { // interval is earlier than the start of the last interval in the list of runs. // Its return value is the amount by which the cardinality of the container was // increased. -func (c *Container) runAppendInterval(v interval16) int32 { +func (c *Container) runAppendInterval(v Interval16) int32 { runs := c.runs() if len(runs) == 0 { runs = append(runs, v) c.setRuns(runs) - return int32(v.last-v.start) + 1 + return int32(v.Last-v.Start) + 1 } last := runs[len(runs)-1] - if last.last == maxContainerVal { //protect against overflow + if last.Last == MaxContainerVal { //protect against overflow return 0 } - if last.last+1 >= v.start && v.last > last.last { - runs[len(runs)-1].last = v.last + if last.Last+1 >= v.Start && v.Last > last.Last { + runs[len(runs)-1].Last = v.Last c.setRuns(runs) - return int32(v.last - last.last) - } else if last.last+1 < v.start { + return int32(v.Last - last.Last) + } else if last.Last+1 < v.Start { runs = append(runs, v) c.setRuns(runs) - return int32(v.last-v.start) + 1 + return int32(v.Last-v.Start) + 1 } return 0 } @@ -4407,8 +4414,8 @@ func unionRunRun(a, b *Container) *Container { statsHit("union/RunRun") ra, rb := a.runs(), b.runs() na, nb := len(ra), len(rb) - output := NewContainerRun(make([]interval16, 0, na+nb)) - var va, vb interval16 + output := NewContainerRun(make([]Interval16, 0, na+nb)) + var va, vb Interval16 n := int32(0) for i, j := 0, 0; i < na || j < nb; { if i < na { @@ -4417,7 +4424,7 @@ func unionRunRun(a, b *Container) *Container { if j < nb { vb = rb[j] } - if i < na && (j >= nb || va.start < vb.start) { + if i < na && (j >= nb || va.Start < vb.Start) { n += output.runAppendInterval(va) i++ } else { @@ -4436,7 +4443,7 @@ func unionBitmapRun(a, b *Container) *Container { statsHit("union/BitmapRun") output := a.Clone() for _, run := range b.runs() { - output.bitmapSetRange(uint64(run.start), uint64(run.last)+1) + output.bitmapSetRange(uint64(run.Start), uint64(run.Last)+1) } return output } @@ -4448,7 +4455,7 @@ func unionBitmapRunInPlace(a, b *Container) *Container { bitmap := a.bitmap() statsHit("union/BitmapRun") for _, run := range b.runs() { - bitmapSetRangeIgnoreN(bitmap, uint64(run.start), uint64(run.last)+1) + bitmapSetRangeIgnoreN(bitmap, uint64(run.Start), uint64(run.Last)+1) } return a } @@ -4575,15 +4582,15 @@ func compareArrayBitmap(a []uint16, b []uint64) error { // of the array's values in the run collection. the run collection // can't be empty; if it were, N would have been 0, and we wouldn't // have gotten here. -func compareArrayRuns(a []uint16, r []interval16) error { +func compareArrayRuns(a []uint16, r []Interval16) error { ri := 0 ru := r[ri] ri++ for _, v := range a { - if v < ru.start { + if v < ru.Start { return fmt.Errorf("value %d missing", v) } - if v > ru.last { + if v > ru.Last { if ri >= len(r) { return fmt.Errorf("value %d missing", v) } @@ -4591,7 +4598,7 @@ func compareArrayRuns(a []uint16, r []interval16) error { ri++ // if they're identical, the array value must be // the start of the next run. - if v != ru.start { + if v != ru.Start { return fmt.Errorf("value %d missing", v) } } @@ -4712,8 +4719,200 @@ func unionBitmapBitmapInPlace(a, b *Container) *Container { return a } +// unions run b into run a, mutating a in place. +func unionRunRunInPlace(a, b *Container) *Container { + statsHit("unionInPlace/RunRun") + + a = a.Thaw() + runs, n := unionInterval16InPlace(a.runs(), b.runs()) + + a.setRuns(runs) + a.setN(n) + return a +} + +// unionInterval16InPlace merges two slice of intervals in place (in a). +// The main concept is to go value by value (instead of interval by interval) +// and count `.start` and `.last` points. +// If we get the `state == 0` it means we just built a new interval (`val`), +// and we can set it in `a` at the possition `off` +func unionInterval16InPlace(a, b []Interval16) ([]Interval16, int32) { + n := int32(0) + an, bn := len(a), len(b) + + var ( + // ai - index of a, aii - subindex (0: a[ai].start, 1: a[ai].last). + ai, aii int = 0, 0 + + // bi - index of b, bii - subindex (0: b[bi].start, 1: b[bi].last). + bi, bii int = 0, 0 + + // Offset of a - next available index to set. + off int = 0 + // Value to set/append to a at off + val Interval16 + + // Current state - state equals 0 means we are clear (out of intervals) + // When we start a new interval we add +1 when we get out of interval we add -1. + state int + + // subindex (ii) to state mapping + // .start: [0] -> 1 + // .last: [1] -> -1 + iiMap = [2]int{1, -1} + + // If fromB is equal 2 it means that both val.start and val.last come from b, + // so we need to extend a, first + fromB int8 + + // eval functions evaluates global state and value + eval = func(arr [2]uint16, ii int, onlyB bool) { + if state == 0 && ii == 0 { + // we are clear and start a new interval + val.Start = arr[ii] + if onlyB { + fromB++ + } + } + + state += iiMap[ii] + + if state == 0 { + // we just got out of interval + // ii == 1 + val.Last = arr[ii] + if onlyB { + fromB++ + } + } + } + // eval2 function is a special variant for eval function + // it's only used when two interval endings are equal, e.g.: + // a: ------------------| + // b: -----------| + // the most important part is to change the global for both endings + // before we check if we're getting out of interval and start the new one. + eval2 = func(arr [2]uint16, i1, i2 int) { + if state == 0 && (i1 == 0 || i2 == 0) { + // we are clear and start a new interval + val.Start = arr[i1] + + } + + state += iiMap[i1] + state += iiMap[i2] + + if state == 0 { + // (i1 == 1 || i2 == 1) + // we just got out of interval + val.Last = arr[i1] + } + } + ) + + for { + // av, bv reflects a[ai] and b[bi] intervals as an array, + // so we can internally iterate over values (points). + var av, bv [2]uint16 + + if ai < an && bi < bn { + av[0], av[1] = a[ai].Start, a[ai].Last + bv[0], bv[1] = b[bi].Start, b[bi].Last + + if av[aii] < bv[bii] { + // a: |------------------- + // b: |------------------- + + eval(av, aii, false) + aii++ + } else if av[aii] == bv[bii] { + // a: |------------------- + // b: |------------------- + // or + // a: ------------------| + // b: |------------------- + // or + // a: ------------------| + // b: |------------| + // ... + + eval2(av, aii, bii) + aii++ + bii++ + } else { // bv[bii] < av[aii] + // a: |------------------- + // b: |------------------- + + eval(bv, bii, true) + bii++ + } + } else if ai < an { // only a left + av[0], av[1] = a[ai].Start, a[ai].Last + eval(av, aii, false) + aii++ + } else if bi < bn { // only b left + bv[0], bv[1] = b[bi].Start, b[bi].Last + eval(bv, bii, false) + bii++ + } else { + break + } + + if state == 0 { + if fromB == 2 { + // val.start and val.last come from b, so we need to extend a, first + a = append(a, Interval16{}) + copy(a[off+1:], a[off:]) + ai++ + an++ + } + fromB = 0 + a, off = appendInterval16At(a, val, off) + n += int32(val.Last) - int32(val.Start) + 1 + } + + if aii == 2 { + // move to the next a's interval + aii = 0 + ai++ + } + + if bii == 2 { + // move to the next b's interval + bii = 0 + bi++ + } + } + + if len(a) > 0 { + a = a[:off] + } + return a, n +} + +// appendInterval16At appends or sets val in a at off position +// The function returns modified a ([]interval16) and new offset (off) +func appendInterval16At(a []Interval16, val Interval16, off int) ([]Interval16, int) { + + if off > 0 && int32(val.Start)-int32(a[off-1].Last) <= 1 { + a[off-1].Last = val.Last + return a, off + } + + if off == len(a) { + a = append(a, val) + off++ + return a, off + } + + a[off] = val + off++ + + return a, off +} + func difference(a, b *Container) *Container { - if a.N() == 0 || b.N() == maxContainerVal+1 { + if a.N() == 0 || b.N() == MaxContainerVal+1 { return nil } if b.N() == 0 { @@ -4788,20 +4987,20 @@ func differenceArrayRun(a, b *Container) *Container { for i < len(aa) { // keep all array elements before beginning of runs - if aa[i] < rb[j].start { + if aa[i] < rb[j].Start { output = append(output, aa[i]) i++ continue } // if array element in run, skip it - if aa[i] >= rb[j].start && aa[i] <= rb[j].last { + if aa[i] >= rb[j].Start && aa[i] <= rb[j].Last { i++ continue } // if array element larger than current run, check next run - if aa[i] > rb[j].last { + if aa[i] > rb[j].Last { j++ if j == len(rb) { break @@ -4823,7 +5022,7 @@ func differenceBitmapRun(a, b *Container) *Container { statsHit("difference/BitmapRun") output := a.Clone() for _, run := range b.runs() { - output.bitmapZeroRange(uint64(run.start), uint64(run.last)+1) + output.bitmapZeroRange(uint64(run.Start), uint64(run.Last)+1) } return output } @@ -4833,22 +5032,22 @@ func differenceBitmapRun(a, b *Container) *Container { func differenceRunArray(a, b *Container) *Container { statsHit("difference/RunArray") ra, ab := a.runs(), b.array() - runs := make([]interval16, 0, len(ra)) + runs := make([]Interval16, 0, len(ra)) bidx := 0 vb := ab[bidx] RUNLOOP: for _, run := range ra { - start := run.start - for vb < run.start { + start := run.Start + for vb < run.Start { bidx++ if bidx >= len(ab) { break } vb = ab[bidx] } - for vb >= run.start && vb <= run.last { + for vb >= run.Start && vb <= run.Last { if vb == start { if vb == 65535 { // overflow break RUNLOOP @@ -4861,7 +5060,7 @@ RUNLOOP: vb = ab[bidx] continue } - runs = append(runs, interval16{start: start, last: vb - 1}) + runs = append(runs, Interval16{Start: start, Last: vb - 1}) if vb == 65535 { // overflow break RUNLOOP } @@ -4873,8 +5072,8 @@ RUNLOOP: vb = ab[bidx] } - if start <= run.last { - runs = append(runs, interval16{start: start, last: run.last}) + if start <= run.Last { + runs = append(runs, Interval16{Start: start, Last: run.Last}) } } output := NewContainerRun(runs) @@ -4887,38 +5086,38 @@ func differenceRunBitmap(a, b *Container) *Container { statsHit("difference/RunBitmap") ra := a.runs() // If a is full, difference is the flip of b. - if len(ra) > 0 && ra[0].start == 0 && ra[0].last == 65535 { + if len(ra) > 0 && ra[0].Start == 0 && ra[0].Last == 65535 { return flipBitmap(b) } bb := b.bitmap()[:1024] - runs := make([]interval16, 0, len(ra)) + runs := make([]Interval16, 0, len(ra)) for _, inputRun := range ra { run := inputRun add := true - for bit := inputRun.start; bit <= inputRun.last; bit++ { + for bit := inputRun.Start; bit <= inputRun.Last; bit++ { idx, exp := int(bit>>6), bit&63 if (bb[idx]>>exp)&1 != 0 { - if run.start == bit { + if run.Start == bit { if bit == 65535 { //overflow add = false } - run.start++ - } else if bit == run.last { - run.last-- + run.Start++ + } else if bit == run.Last { + run.Last-- } else { - run.last = bit - 1 - if run.last >= run.start { + run.Last = bit - 1 + if run.Last >= run.Start { if len(runs) >= runMaxSize { asBitmap := a.runToBitmap() return differenceBitmapBitmap(asBitmap, b) } runs = append(runs, run) } - run.start = bit + 1 - run.last = inputRun.last + run.Start = bit + 1 + run.Last = inputRun.Last } - if run.start > run.last { + if run.Start > run.Last { break } } @@ -4927,7 +5126,7 @@ func differenceRunBitmap(a, b *Container) *Container { break } } - if run.start <= run.last { + if run.Start <= run.Last { if add { if len(runs) >= runMaxSize { asBitmap := a.runToBitmap() @@ -4954,14 +5153,14 @@ func differenceRunRun(a, b *Container) *Container { ra, rb := a.runs(), b.runs() apos := 0 // current a-run index bpos := 0 // current b-run index - astart := ra[apos].start - alast := ra[apos].last - bstart := rb[bpos].start - blast := rb[bpos].last + astart := ra[apos].Start + alast := ra[apos].Last + bstart := rb[bpos].Start + blast := rb[bpos].Last alen := len(ra) blen := len(rb) - runs := make([]interval16, 0, alen+blen) // TODO allocate max then truncate? or something else + runs := make([]Interval16, 0, alen+blen) // TODO allocate max then truncate? or something else // cardinality upper bound: sum of number of runs // each B-run could split an A-run in two, up to len(b.runs) times @@ -4969,37 +5168,37 @@ func differenceRunRun(a, b *Container) *Container { switch { case alast < bstart: // current A-run entirely precedes current B-run: keep full A-run, advance to next A-run - runs = append(runs, interval16{start: astart, last: alast}) + runs = append(runs, Interval16{Start: astart, Last: alast}) apos++ if apos < alen { - astart = ra[apos].start - alast = ra[apos].last + astart = ra[apos].Start + alast = ra[apos].Last } case blast < astart: // current B-run entirely precedes current A-run: advance to next B-run bpos++ if bpos < blen { - bstart = rb[bpos].start - blast = rb[bpos].last + bstart = rb[bpos].Start + blast = rb[bpos].Last } default: // overlap if astart < bstart { - runs = append(runs, interval16{start: astart, last: bstart - 1}) + runs = append(runs, Interval16{Start: astart, Last: bstart - 1}) } if alast > blast { astart = blast + 1 } else { apos++ if apos < alen { - astart = ra[apos].start - alast = ra[apos].last + astart = ra[apos].Start + alast = ra[apos].Last } } } } if apos < alen { - runs = append(runs, interval16{start: astart, last: alast}) + runs = append(runs, Interval16{Start: astart, Last: alast}) apos++ if apos < alen { runs = append(runs, ra[apos:]...) @@ -5232,18 +5431,18 @@ func shiftRun(a *Container) (*Container, bool) { statsHit("shift/Run") carry := false ra := a.runs() - ro := make([]interval16, 0, len(ra)) + ro := make([]Interval16, 0, len(ra)) for _, v := range ra { - if v.start+1 == 0 { // final run was 1 bit on container edge + if v.Start+1 == 0 { // final run was 1 bit on container edge carry = true break - } else if v.last+1 == 0 { // final run ends on container edge - v.start++ + } else if v.Last+1 == 0 { // final run ends on container edge + v.Start++ carry = true } else { - v.start++ - v.last++ + v.Start++ + v.Last++ carry = false } ro = append(ro, v) @@ -5264,6 +5463,15 @@ const ( opTypeRemoveRoaring = opType(5) ) +var opTypes = []string{ + "add", + "remove", + "addN", + "removeN", + "addRoaring", + "removeRoaring", +} + // op represents an operation on the bitmap. type op struct { typ opType @@ -5273,6 +5481,24 @@ type op struct { roaring []byte } +// OpInfo is a description of an op. +type OpInfo struct { + Type string + OpN int + Size int +} + +func (op *op) info() (info OpInfo) { + if int(op.typ) < len(opTypes) { + info.Type = opTypes[op.typ] + } else { + info.Type = fmt.Sprintf("unknown-type-%d", op.typ) + } + info.OpN = op.opN + info.Size = op.size() + return info +} + // apply executes the operation against a bitmap. func (op *op) apply(b *Bitmap) (changed bool) { switch op.typ { @@ -5414,10 +5640,8 @@ func (op *op) size() int { case opTypeAddRoaring, opTypeRemoveRoaring: return 1 + 8 + 4 + 4 + len(op.roaring) } - if roaringParanoia { - panic(fmt.Sprintf("op size() called on unknown op type %d", op.typ)) - } - return 0 + + panic(fmt.Errorf("op size() called on unknown op type %d", op.typ)) } // size returns the size needed to encode the op, in bytes. for @@ -5433,10 +5657,8 @@ func (op *op) encodeSize() int { case opTypeAddRoaring, opTypeRemoveRoaring: return 1 + 8 + 4 + 4 } - if roaringParanoia { - panic(fmt.Sprintf("op encodeSize() called on unknown op type %d", op.typ)) - } - return 0 + + panic(fmt.Errorf("op encodeSize() called on unknown op type %d", op.typ)) } // count returns the number of bits the operation mutates. @@ -5449,7 +5671,7 @@ func (op *op) count() int { case 4, 5: return op.opN default: - panic(fmt.Sprintf("unknown operation type: %d", op.typ)) + panic(fmt.Errorf("unknown operation type: %d", op.typ)) } } @@ -5586,7 +5808,7 @@ func xorArrayRun(a, b *Container) *Container { output := NewContainerRun(nil) aa, rb := a.array(), b.runs() na, nb := len(aa), len(rb) - var vb interval16 + var vb Interval16 var va uint16 lastI, lastJ := -1, -1 n := int32((0)) @@ -5600,27 +5822,27 @@ func xorArrayRun(a, b *Container) *Container { lastI = i lastJ = j - if i < na && (j >= nb || va < vb.start) { //before - n += output.runAppendInterval(interval16{start: va, last: va}) + if i < na && (j >= nb || va < vb.Start) { //before + n += output.runAppendInterval(Interval16{Start: va, Last: va}) i++ - } else if j < nb && (i >= na || va > vb.last) { //after + } else if j < nb && (i >= na || va > vb.Last) { //after n += output.runAppendInterval(vb) j++ - } else if va > vb.start { - if va < vb.last { - n += output.runAppendInterval(interval16{start: vb.start, last: va - 1}) + } else if va > vb.Start { + if va < vb.Last { + n += output.runAppendInterval(Interval16{Start: vb.Start, Last: va - 1}) i++ - vb.start = va + 1 + vb.Start = va + 1 - if vb.start > vb.last { + if vb.Start > vb.Last { j++ } - } else if va > vb.last { + } else if va > vb.Last { n += output.runAppendInterval(vb) j++ } else { // va == vb.last - vb.last-- - if vb.start <= vb.last { + vb.Last-- + if vb.Start <= vb.Last { n += output.runAppendInterval(vb) } j++ @@ -5628,11 +5850,11 @@ func xorArrayRun(a, b *Container) *Container { } } else { // we know va == vb.start - if vb.start == maxContainerVal { // protect overflow + if vb.Start == MaxContainerVal { // protect overflow j++ } else { - vb.start++ - if vb.start > vb.last { + vb.Start++ + if vb.Start > vb.Last { j++ } } @@ -5649,7 +5871,7 @@ func xorArrayRun(a, b *Container) *Container { } // xorCompare computes first exclusive run between two runs. -func xorCompare(x *xorstm) (r1 interval16, hasData bool) { +func xorCompare(x *xorstm) (r1 Interval16, hasData bool) { hasData = false if !x.vaValid || !x.vbValid { if x.vbValid { @@ -5663,72 +5885,72 @@ func xorCompare(x *xorstm) (r1 interval16, hasData bool) { return r1, false } - if x.va.last < x.vb.start { //va before + if x.va.Last < x.vb.Start { //va before x.vaValid = false r1 = x.va hasData = true - } else if x.vb.last < x.va.start { //vb before + } else if x.vb.Last < x.va.Start { //vb before x.vbValid = false r1 = x.vb hasData = true - } else if x.va.start == x.vb.start && x.va.last == x.vb.last { // Equal + } else if x.va.Start == x.vb.Start && x.va.Last == x.vb.Last { // Equal x.vaValid = false x.vbValid = false - } else if x.va.start <= x.vb.start && x.va.last >= x.vb.last { //vb inside + } else if x.va.Start <= x.vb.Start && x.va.Last >= x.vb.Last { //vb inside x.vbValid = false - if x.va.start != x.vb.start { - r1 = interval16{start: x.va.start, last: x.vb.start - 1} + if x.va.Start != x.vb.Start { + r1 = Interval16{Start: x.va.Start, Last: x.vb.Start - 1} hasData = true } - if x.vb.last == maxContainerVal { // Check for overflow + if x.vb.Last == MaxContainerVal { // Check for overflow x.vaValid = false } else { - x.va.start = x.vb.last + 1 - if x.va.start > x.va.last { + x.va.Start = x.vb.Last + 1 + if x.va.Start > x.va.Last { x.vaValid = false } } - } else if x.vb.start <= x.va.start && x.vb.last >= x.va.last { //va inside + } else if x.vb.Start <= x.va.Start && x.vb.Last >= x.va.Last { //va inside x.vaValid = false - if x.vb.start != x.va.start { - r1 = interval16{start: x.vb.start, last: x.va.start - 1} + if x.vb.Start != x.va.Start { + r1 = Interval16{Start: x.vb.Start, Last: x.va.Start - 1} hasData = true } - if x.va.last == maxContainerVal { //check for overflow + if x.va.Last == MaxContainerVal { //check for overflow x.vbValid = false } else { - x.vb.start = x.va.last + 1 - if x.vb.start > x.vb.last { + x.vb.Start = x.va.Last + 1 + if x.vb.Start > x.vb.Last { x.vbValid = false } } - } else if x.va.start < x.vb.start && x.va.last <= x.vb.last { //va first overlap + } else if x.va.Start < x.vb.Start && x.va.Last <= x.vb.Last { //va first overlap x.vaValid = false - r1 = interval16{start: x.va.start, last: x.vb.start - 1} + r1 = Interval16{Start: x.va.Start, Last: x.vb.Start - 1} hasData = true - if x.va.last == maxContainerVal { // check for overflow + if x.va.Last == MaxContainerVal { // check for overflow x.vbValid = false } else { - x.vb.start = x.va.last + 1 - if x.vb.start > x.vb.last { + x.vb.Start = x.va.Last + 1 + if x.vb.Start > x.vb.Last { x.vbValid = false } } - } else if x.vb.start < x.va.start && x.vb.last <= x.va.last { //vb first overlap + } else if x.vb.Start < x.va.Start && x.vb.Last <= x.va.Last { //vb first overlap x.vbValid = false - r1 = interval16{start: x.vb.start, last: x.va.start - 1} + r1 = Interval16{Start: x.vb.Start, Last: x.va.Start - 1} hasData = true - if x.vb.last == maxContainerVal { // check for overflow + if x.vb.Last == MaxContainerVal { // check for overflow x.vaValid = false } else { - x.va.start = x.vb.last + 1 - if x.va.start > x.va.last { + x.va.Start = x.vb.Last + 1 + if x.va.Start > x.va.Last { x.vaValid = false } } @@ -5739,7 +5961,7 @@ func xorCompare(x *xorstm) (r1 interval16, hasData bool) { //stm is state machine used to "xor" iterate over runs. type xorstm struct { vaValid, vbValid bool - va, vb interval16 + va, vb Interval16 } // xorRunRun computes the exclusive or of two run containers. @@ -5795,7 +6017,7 @@ func xorBitmapRun(a, b *Container) *Container { output := a.Clone() for _, run := range b.runs() { - output.bitmapXorRange(uint64(run.start), uint64(run.last)+1) + output.bitmapXorRange(uint64(run.Start), uint64(run.Last)+1) } return output @@ -6033,9 +6255,9 @@ func (w handledIters) calculateSummaryStats(key uint64) containerUnionSummarySta summary.c++ summary.n += int64(currContainer.N()) - if currContainer.N() == maxContainerVal+1 { + if currContainer.N() == MaxContainerVal+1 { summary.hasMaxRange = true - summary.n = maxContainerVal + 1 + summary.n = MaxContainerVal + 1 return summary } } @@ -6250,7 +6472,7 @@ func differenceArrayRunInPlace(c, other *Container) { for i < len(aa) { // keep all array elements before beginning of runs - if aa[i] < rb[j].start { + if aa[i] < rb[j].Start { aa[n] = aa[i] n++ i++ @@ -6258,13 +6480,13 @@ func differenceArrayRunInPlace(c, other *Container) { } // if array element in run, skip it - if aa[i] >= rb[j].start && aa[i] <= rb[j].last { + if aa[i] >= rb[j].Start && aa[i] <= rb[j].Last { i++ continue } // if array element larger than current run, check next run - if aa[i] > rb[j].last { + if aa[i] > rb[j].Last { j++ if j == len(rb) { break @@ -6332,7 +6554,7 @@ func differenceBitmapRunInPlace(c, other *Container) { return } for _, run := range other.runs() { - c.bitmapZeroRange(uint64(run.start), uint64(run.last)+1) + c.bitmapZeroRange(uint64(run.Start), uint64(run.Last)+1) } } @@ -6342,21 +6564,21 @@ func differenceRunArrayInPlace(c, other *Container) { if len(ra) == 0 || len(ab) == 0 { return } - runs := make([]interval16, 0, len(ra)) + runs := make([]Interval16, 0, len(ra)) bidx := 0 vb := ab[bidx] RUNLOOP: for _, run := range ra { - start := run.start - for vb < run.start { + start := run.Start + for vb < run.Start { bidx++ if bidx >= len(ab) { break } vb = ab[bidx] } - for vb >= run.start && vb <= run.last { + for vb >= run.Start && vb <= run.Last { if vb == start { if vb == 65535 { // overflow break RUNLOOP @@ -6369,7 +6591,7 @@ RUNLOOP: vb = ab[bidx] continue } - runs = append(runs, interval16{start: start, last: vb - 1}) + runs = append(runs, Interval16{Start: start, Last: vb - 1}) if vb == 65535 { // overflow break RUNLOOP } @@ -6381,14 +6603,14 @@ RUNLOOP: vb = ab[bidx] } - if start <= run.last { - runs = append(runs, interval16{start: start, last: run.last}) + if start <= run.Last { + runs = append(runs, Interval16{Start: start, Last: run.Last}) } } c.setRuns(runs) c.n = 0 for _, run := range runs { - c.n += int32(run.last-run.start) + 1 + c.n += int32(run.Last-run.Start) + 1 } c.optimize() } @@ -6400,7 +6622,7 @@ func differenceRunBitmapInPlace(c, other *Container) { return } // If a is full, difference is the flip of b. - if len(ra) > 0 && ra[0].start == 0 && ra[0].last == 65535 { + if len(ra) > 0 && ra[0].Start == 0 && ra[0].Last == 65535 { clone := other.Clone() bitmap := clone.bitmap() for i, word := range other.bitmap() { @@ -6412,29 +6634,29 @@ func differenceRunBitmapInPlace(c, other *Container) { c.setN(c.count()) return } - runs := make([]interval16, 0, len(ra)) + runs := make([]Interval16, 0, len(ra)) for _, inputRun := range ra { run := inputRun add := true - for bit := inputRun.start; bit <= inputRun.last; bit++ { + for bit := inputRun.Start; bit <= inputRun.Last; bit++ { if other.bitmapContains(bit) { - if run.start == bit { + if run.Start == bit { if bit == 65535 { //overflow add = false } - run.start++ - } else if bit == run.last { - run.last-- + run.Start++ + } else if bit == run.Last { + run.Last-- } else { - run.last = bit - 1 - if run.last >= run.start { + run.Last = bit - 1 + if run.Last >= run.Start { runs = append(runs, run) } - run.start = bit + 1 - run.last = inputRun.last + run.Start = bit + 1 + run.Last = inputRun.Last } - if run.start > run.last { + if run.Start > run.Last { break } } @@ -6443,7 +6665,7 @@ func differenceRunBitmapInPlace(c, other *Container) { break } } - if run.start <= run.last { + if run.Start <= run.Last { if add { runs = append(runs, run) } @@ -6453,7 +6675,7 @@ func differenceRunBitmapInPlace(c, other *Container) { c.setRuns(runs) c.n = 0 for _, run := range runs { - c.n += int32(run.last-run.start) + 1 + c.n += int32(run.Last-run.Start) + 1 } if c.N() < ArrayMaxSize && int32(len(runs)) > c.N()/2 { c.runToArray() @@ -6471,14 +6693,14 @@ func differenceRunRunInPlace(c, other *Container) { } apos := 0 // current a-run index bpos := 0 // current b-run index - astart := ra[apos].start - alast := ra[apos].last - bstart := rb[bpos].start - blast := rb[bpos].last + astart := ra[apos].Start + alast := ra[apos].Last + bstart := rb[bpos].Start + blast := rb[bpos].Last alen := len(ra) blen := len(rb) - runs := make([]interval16, 0, alen+blen) // TODO allocate max then truncate? or something else + runs := make([]Interval16, 0, alen+blen) // TODO allocate max then truncate? or something else // cardinality upper bound: sum of number of runs // each B-run could split an A-run in two, up to len(b.runs) times @@ -6486,37 +6708,37 @@ func differenceRunRunInPlace(c, other *Container) { switch { case alast < bstart: // current A-run entirely precedes current B-run: keep full A-run, advance to next A-run - runs = append(runs, interval16{start: astart, last: alast}) + runs = append(runs, Interval16{Start: astart, Last: alast}) apos++ if apos < alen { - astart = ra[apos].start - alast = ra[apos].last + astart = ra[apos].Start + alast = ra[apos].Last } case blast < astart: // current B-run entirely precedes current A-run: advance to next B-run bpos++ if bpos < blen { - bstart = rb[bpos].start - blast = rb[bpos].last + bstart = rb[bpos].Start + blast = rb[bpos].Last } default: // overlap if astart < bstart { - runs = append(runs, interval16{start: astart, last: bstart - 1}) + runs = append(runs, Interval16{Start: astart, Last: bstart - 1}) } if alast > blast { astart = blast + 1 } else { apos++ if apos < alen { - astart = ra[apos].start - alast = ra[apos].last + astart = ra[apos].Start + alast = ra[apos].Last } } } } if apos < alen { - runs = append(runs, interval16{start: astart, last: alast}) + runs = append(runs, Interval16{Start: astart, Last: alast}) apos++ if apos < alen { runs = append(runs, ra[apos:]...) @@ -6525,6 +6747,39 @@ func differenceRunRunInPlace(c, other *Container) { c.setRuns(runs) c.n = 0 for _, run := range runs { - c.n += int32(run.last-run.start) + 1 + c.n += int32(run.Last-run.Start) + 1 } } + +//RBF exports to be reconsidered as we progress + +func (b *Bitmap) Put(key uint64, c *Container) { + b.Containers.Put(key, c) +} +func AsBitmap(c *Container) []uint64 { + return c.bitmap() +} +func AsArray(c *Container) []uint16 { + return c.array() +} +func ContainerType(c *Container) byte { + return c.typ() +} + +func AsRuns(c *Container) []Interval16 { + return c.runs() +} + +func ConvertArrayToBitmap(c *Container) { + c.arrayToBitmap() +} +func ConvertRunToBitmap(c *Container) { + c.runToBitmap() +} + +func Optimize(c *Container) { + c.optimize() +} +func Union(a, b *Container) *Container { + return union(a, b) +} diff --git a/roaring/roaring_helpers_test.go b/roaring/roaring_helpers_test.go index f8de764fb..6d1b67598 100644 --- a/roaring/roaring_helpers_test.go +++ b/roaring/roaring_helpers_test.go @@ -175,65 +175,65 @@ func bitmapEvenBitsSet() []uint64 { } ////////////////// run -func runEmpty() []interval16 { - return make([]interval16, 0) +func runEmpty() []Interval16 { + return make([]Interval16, 0) } -func runFull() []interval16 { - run := make([]interval16, 0) - run = append(run, interval16{start: 0, last: 65535}) +func runFull() []Interval16 { + run := make([]Interval16, 0) + run = append(run, Interval16{Start: 0, Last: 65535}) return run } -func runFirstBitSet() []interval16 { - run := make([]interval16, 0) - run = append(run, interval16{start: 0, last: 0}) +func runFirstBitSet() []Interval16 { + run := make([]Interval16, 0) + run = append(run, Interval16{Start: 0, Last: 0}) return run } -func runLastBitSet() []interval16 { - run := make([]interval16, 0) - run = append(run, interval16{start: 65535, last: 65535}) +func runLastBitSet() []Interval16 { + run := make([]Interval16, 0) + run = append(run, Interval16{Start: 65535, Last: 65535}) return run } -func runFirstBitUnset() []interval16 { - run := make([]interval16, 0) - run = append(run, interval16{start: 1, last: 65535}) +func runFirstBitUnset() []Interval16 { + run := make([]Interval16, 0) + run = append(run, Interval16{Start: 1, Last: 65535}) return run } -func runLastBitUnset() []interval16 { - run := make([]interval16, 0) - run = append(run, interval16{start: 0, last: 65534}) +func runLastBitUnset() []Interval16 { + run := make([]Interval16, 0) + run = append(run, Interval16{Start: 0, Last: 65534}) return run } -func runInnerBitsSet() []interval16 { - run := make([]interval16, 0) - run = append(run, interval16{start: 1, last: 65534}) +func runInnerBitsSet() []Interval16 { + run := make([]Interval16, 0) + run = append(run, Interval16{Start: 1, Last: 65534}) return run } -func runOuterBitsSet() []interval16 { - run := make([]interval16, 0) - run = append(run, interval16{start: 0, last: 0}) - run = append(run, interval16{start: 65535, last: 65535}) +func runOuterBitsSet() []Interval16 { + run := make([]Interval16, 0) + run = append(run, Interval16{Start: 0, Last: 0}) + run = append(run, Interval16{Start: 65535, Last: 65535}) return run } -func runOddBitsSet() []interval16 { - run := make([]interval16, containerWidth/2) +func runOddBitsSet() []Interval16 { + run := make([]Interval16, containerWidth/2) for i := 0; i < int(containerWidth/2); i++ { - run[i] = interval16{start: uint16(2*i + 1), last: uint16(2*i + 1)} + run[i] = Interval16{Start: uint16(2*i + 1), Last: uint16(2*i + 1)} } return run } -func runEvenBitsSet() []interval16 { - run := make([]interval16, containerWidth/2) +func runEvenBitsSet() []Interval16 { + run := make([]Interval16, containerWidth/2) for i := 0; i < int(containerWidth/2); i++ { - run[i] = interval16{start: uint16(2 * i), last: uint16(2 * i)} + run[i] = Interval16{Start: uint16(2 * i), Last: uint16(2 * i)} } return run } @@ -258,7 +258,7 @@ func doContainer(typ byte, data interface{}) *Container { c := NewContainerBitmap(-1, data.([]uint64)) return c case containerRun: - return NewContainerRun(data.([]interval16)) + return NewContainerRun(data.([]Interval16)) } return nil } diff --git a/roaring/roaring_internal_test.go b/roaring/roaring_internal_test.go index 3a0749cc8..fdb2db790 100644 --- a/roaring/roaring_internal_test.go +++ b/roaring/roaring_internal_test.go @@ -30,35 +30,35 @@ import ( ) // String produces a human viewable string of the contents. -func (iv interval16) String() string { - return fmt.Sprintf("[%d, %d]", iv.start, iv.last) +func (iv Interval16) String() string { + return fmt.Sprintf("[%d, %d]", iv.Start, iv.Last) } func TestRunAppendInterval(t *testing.T) { a := NewContainerRun(nil) tests := []struct { - base []interval16 - app interval16 + base []Interval16 + app Interval16 exp int32 }{ { - base: []interval16{}, - app: interval16{start: 22, last: 25}, + base: []Interval16{}, + app: Interval16{Start: 22, Last: 25}, exp: 4, }, { - base: []interval16{{start: 20, last: 23}}, - app: interval16{start: 22, last: 25}, + base: []Interval16{{Start: 20, Last: 23}}, + app: Interval16{Start: 22, Last: 25}, exp: 2, }, { - base: []interval16{{start: 20, last: 23}}, - app: interval16{start: 21, last: 22}, + base: []Interval16{{Start: 20, Last: 23}}, + app: Interval16{Start: 21, Last: 22}, exp: 0, }, { - base: []interval16{{start: 20, last: 23}}, - app: interval16{start: 19, last: 25}, + base: []Interval16{{Start: 20, Last: 23}}, + app: Interval16{Start: 19, Last: 25}, exp: 2, // runAppendInterval explicitly does not support intervals whose start is < c.runs[-1].start }, } @@ -73,11 +73,11 @@ func TestRunAppendInterval(t *testing.T) { } func TestInterval16RunLen(t *testing.T) { - iv := interval16{start: 7, last: 9} + iv := Interval16{Start: 7, Last: 9} if iv.runlen() != 3 { t.Fatalf("should be 3") } - iv = interval16{start: 7, last: 7} + iv = Interval16{Start: 7, Last: 7} if iv.runlen() != 1 { t.Fatalf("should be 1") } @@ -87,17 +87,17 @@ func TestContainerRunAdd(t *testing.T) { c := NewContainerRun(nil) tests := []struct { op uint16 - exp []interval16 + exp []Interval16 }{ - {1, []interval16{{start: 1, last: 1}}}, - {2, []interval16{{start: 1, last: 2}}}, - {4, []interval16{{start: 1, last: 2}, {start: 4, last: 4}}}, - {3, []interval16{{start: 1, last: 4}}}, - {10, []interval16{{start: 1, last: 4}, {start: 10, last: 10}}}, - {7, []interval16{{start: 1, last: 4}, {start: 7, last: 7}, {start: 10, last: 10}}}, - {6, []interval16{{start: 1, last: 4}, {start: 6, last: 7}, {start: 10, last: 10}}}, - {0, []interval16{{start: 0, last: 4}, {start: 6, last: 7}, {start: 10, last: 10}}}, - {8, []interval16{{start: 0, last: 4}, {start: 6, last: 8}, {start: 10, last: 10}}}, + {1, []Interval16{{Start: 1, Last: 1}}}, + {2, []Interval16{{Start: 1, Last: 2}}}, + {4, []Interval16{{Start: 1, Last: 2}, {Start: 4, Last: 4}}}, + {3, []Interval16{{Start: 1, Last: 4}}}, + {10, []Interval16{{Start: 1, Last: 4}, {Start: 10, Last: 10}}}, + {7, []Interval16{{Start: 1, Last: 4}, {Start: 7, Last: 7}, {Start: 10, Last: 10}}}, + {6, []Interval16{{Start: 1, Last: 4}, {Start: 6, Last: 7}, {Start: 10, Last: 10}}}, + {0, []Interval16{{Start: 0, Last: 4}, {Start: 6, Last: 7}, {Start: 10, Last: 10}}}, + {8, []Interval16{{Start: 0, Last: 4}, {Start: 6, Last: 8}, {Start: 10, Last: 10}}}, } for _, test := range tests { c.setMapped(true) @@ -120,7 +120,7 @@ func TestContainerRunAdd2(t *testing.T) { if !ret { t.Fatalf("result of adding new bit should be true: %v", c.runs()) } - if !reflect.DeepEqual(c.runs(), []interval16{{start: 0, last: 0}}) { + if !reflect.DeepEqual(c.runs(), []Interval16{{Start: 0, Last: 0}}) { t.Fatalf("should have 1 run of length 1, but have %v", c.runs()) } c, ret = c.add(0) @@ -249,20 +249,20 @@ func TestBitmapCountRange(t *testing.T) { tests := []struct { start int32 end int32 - bitmap []uint64 + bitmap [bitmapN]uint64 exp int32 }{ - {start: 0, end: 1, bitmap: []uint64{1}, exp: 1}, - {start: 2, end: 7, bitmap: []uint64{0xFFFFFFFFFFFFFF18}, exp: 2}, - {start: 67, end: 68, bitmap: []uint64{0, 0x8}, exp: 1}, - {start: 1, end: 68, bitmap: []uint64{0x3, 0x8, 0xF}, exp: 2}, - {start: 1, end: 258, bitmap: []uint64{0xF, 0x8, 0xA, 0x4, 0xFFFFFFFFFFFFFFFF}, exp: 9}, - {start: 66, end: 71, bitmap: []uint64{0xF, 0xFFFFFFFFFFFFFF18}, exp: 2}, - {start: 63, end: 64, bitmap: []uint64{0x8000000000000000}, exp: 1}, + {start: 0, end: 1, bitmap: [bitmapN]uint64{1}, exp: 1}, + {start: 2, end: 7, bitmap: [bitmapN]uint64{0xFFFFFFFFFFFFFF18}, exp: 2}, + {start: 67, end: 68, bitmap: [bitmapN]uint64{0, 0x8}, exp: 1}, + {start: 1, end: 68, bitmap: [bitmapN]uint64{0x3, 0x8, 0xF}, exp: 2}, + {start: 1, end: 258, bitmap: [bitmapN]uint64{0xF, 0x8, 0xA, 0x4, 0xFFFFFFFFFFFFFFFF}, exp: 9}, + {start: 66, end: 71, bitmap: [bitmapN]uint64{0xF, 0xFFFFFFFFFFFFFF18}, exp: 2}, + {start: 63, end: 64, bitmap: [bitmapN]uint64{0x8000000000000000}, exp: 1}, } for i, test := range tests { - c.setBitmap(test.bitmap) + c.setBitmap(test.bitmap[:]) if ret := c.bitmapCountRange(test.start, test.end); ret != test.exp { t.Fatalf("test #%v count of %v from %v to %v should be %v but got %v", i, test.bitmap, test.start, test.end, test.exp, ret) } @@ -270,23 +270,23 @@ func TestBitmapCountRange(t *testing.T) { } func TestIntersectionCountArrayBitmap3(t *testing.T) { - a, b := NewContainerBitmapN(getFullBitmap(), maxContainerVal+1), NewContainerBitmapN(getFullBitmap(), maxContainerVal+1) + a, b := NewContainerBitmapN(getFullBitmap(), MaxContainerVal+1), NewContainerBitmapN(getFullBitmap(), MaxContainerVal+1) res := intersectBitmapBitmap(a, b) - if res.N() != res.count() || res.N() != maxContainerVal+1 { - t.Fatalf("test #1 intersectCountBitmapBitmap fail orig: %v new: %v exp: %v", res.N(), res.count(), maxContainerVal+1) + if res.N() != res.count() || res.N() != MaxContainerVal+1 { + t.Fatalf("test #1 intersectCountBitmapBitmap fail orig: %v new: %v exp: %v", res.N(), res.count(), MaxContainerVal+1) } a = a.bitmapToRun(0) res = intersectBitmapRun(b, a) - if res.N() != res.count() || res.N() != maxContainerVal+1 { - t.Fatalf("test #2 intersectCountBitmapRun fail orig: %v new: %v exp: %v", res.N(), res.count(), maxContainerVal+1) + if res.N() != res.count() || res.N() != MaxContainerVal+1 { + t.Fatalf("test #2 intersectCountBitmapRun fail orig: %v new: %v exp: %v", res.N(), res.count(), MaxContainerVal+1) } b.bitmapToRun(0) res = intersectRunRun(a, b) n := intersectionCountRunRun(a, b) - if res.N() != res.count() || res.N() != maxContainerVal+1 || res.N() != int32(n) { - t.Fatalf("test #3 intersectCountRunRun fail orig: %v new: %v exp: %v", res.N(), res.count(), maxContainerVal+1) + if res.N() != res.count() || res.N() != MaxContainerVal+1 || res.N() != int32(n) { + t.Fatalf("test #3 intersectCountRunRun fail orig: %v new: %v exp: %v", res.N(), res.count(), MaxContainerVal+1) } } @@ -294,39 +294,39 @@ func TestIntersectionCountArrayBitmap2(t *testing.T) { a, b := NewContainerArray(nil), NewContainerBitmap(0, nil) tests := []struct { array []uint16 - bitmap []uint64 + bitmap [bitmapN]uint64 exp int32 }{ { array: []uint16{0}, - bitmap: []uint64{1}, + bitmap: [bitmapN]uint64{1}, exp: 1, }, { array: []uint16{0, 1}, - bitmap: []uint64{3}, + bitmap: [bitmapN]uint64{3}, exp: 2, }, { array: []uint16{64, 128, 129, 2000}, - bitmap: []uint64{932421, 2}, + bitmap: [bitmapN]uint64{932421, 2}, exp: 0, }, { array: []uint16{0, 65, 130, 195}, - bitmap: []uint64{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, + bitmap: [bitmapN]uint64{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, exp: 4, }, { array: []uint16{63, 120, 543, 639, 12000}, - bitmap: []uint64{0x8000000000000000, 0, 0, 0, 0, 0, 0, 0, 0, 0x8000000000000000}, + bitmap: [bitmapN]uint64{0x8000000000000000, 0, 0, 0, 0, 0, 0, 0, 0, 0x8000000000000000}, exp: 2, }, } for i, test := range tests { a.setArray(test.array) - b.setBitmap(test.bitmap) + b.setBitmap(test.bitmap[:]) ret := intersectionCountArrayBitmap(a, b) if ret != test.exp { t.Fatalf("test #%v intersectCountArrayBitmap fail received: %v exp: %v", i, ret, test.exp) @@ -335,22 +335,22 @@ func TestIntersectionCountArrayBitmap2(t *testing.T) { } func TestRunRemove(t *testing.T) { - c := NewContainerRun([]interval16{{start: 2, last: 10}, {start: 12, last: 13}, {start: 15, last: 16}}) + c := NewContainerRun([]Interval16{{Start: 2, Last: 10}, {Start: 12, Last: 13}, {Start: 15, Last: 16}}) tests := []struct { op uint16 - exp []interval16 + exp []Interval16 expRet bool }{ - {2, []interval16{{start: 3, last: 10}, {start: 12, last: 13}, {start: 15, last: 16}}, true}, - {10, []interval16{{start: 3, last: 9}, {start: 12, last: 13}, {start: 15, last: 16}}, true}, - {12, []interval16{{start: 3, last: 9}, {start: 13, last: 13}, {start: 15, last: 16}}, true}, - {13, []interval16{{start: 3, last: 9}, {start: 15, last: 16}}, true}, - {16, []interval16{{start: 3, last: 9}, {start: 15, last: 15}}, true}, - {6, []interval16{{start: 3, last: 5}, {start: 7, last: 9}, {start: 15, last: 15}}, true}, - {8, []interval16{{start: 3, last: 5}, {start: 7, last: 7}, {start: 9, last: 9}, {start: 15, last: 15}}, true}, - {8, []interval16{{start: 3, last: 5}, {start: 7, last: 7}, {start: 9, last: 9}, {start: 15, last: 15}}, false}, - {1, []interval16{{start: 3, last: 5}, {start: 7, last: 7}, {start: 9, last: 9}, {start: 15, last: 15}}, false}, - {44, []interval16{{start: 3, last: 5}, {start: 7, last: 7}, {start: 9, last: 9}, {start: 15, last: 15}}, false}, + {2, []Interval16{{Start: 3, Last: 10}, {Start: 12, Last: 13}, {Start: 15, Last: 16}}, true}, + {10, []Interval16{{Start: 3, Last: 9}, {Start: 12, Last: 13}, {Start: 15, Last: 16}}, true}, + {12, []Interval16{{Start: 3, Last: 9}, {Start: 13, Last: 13}, {Start: 15, Last: 16}}, true}, + {13, []Interval16{{Start: 3, Last: 9}, {Start: 15, Last: 16}}, true}, + {16, []Interval16{{Start: 3, Last: 9}, {Start: 15, Last: 15}}, true}, + {6, []Interval16{{Start: 3, Last: 5}, {Start: 7, Last: 9}, {Start: 15, Last: 15}}, true}, + {8, []Interval16{{Start: 3, Last: 5}, {Start: 7, Last: 7}, {Start: 9, Last: 9}, {Start: 15, Last: 15}}, true}, + {8, []Interval16{{Start: 3, Last: 5}, {Start: 7, Last: 7}, {Start: 9, Last: 9}, {Start: 15, Last: 15}}, false}, + {1, []Interval16{{Start: 3, Last: 5}, {Start: 7, Last: 7}, {Start: 9, Last: 9}, {Start: 15, Last: 15}}, false}, + {44, []Interval16{{Start: 3, Last: 5}, {Start: 7, Last: 7}, {Start: 9, Last: 9}, {Start: 15, Last: 15}}, false}, } for i, test := range tests { @@ -370,7 +370,7 @@ func TestRunRemove(t *testing.T) { } func TestRunMax(t *testing.T) { - c := NewContainerRun([]interval16{{start: 2, last: 10}, {start: 12, last: 13}, {start: 15, last: 16}}) + c := NewContainerRun([]Interval16{{Start: 2, Last: 10}, {Start: 12, Last: 13}, {Start: 15, Last: 16}}) max := c.max() if max != 16 { t.Fatalf("max for %v should be 16", c.runs()) @@ -385,7 +385,7 @@ func TestRunMax(t *testing.T) { func TestIntersectionCountArrayRun(t *testing.T) { a := NewContainerArray([]uint16{1, 5, 10, 11, 12}) - b := NewContainerRun([]interval16{{start: 2, last: 10}, {start: 12, last: 13}, {start: 15, last: 16}}) + b := NewContainerRun([]Interval16{{Start: 2, Last: 10}, {Start: 12, Last: 13}, {Start: 15, Last: 16}}) ret := intersectionCountArrayRun(a, b) if ret != 3 { @@ -397,7 +397,7 @@ func TestIntersectionCountBitmapRun(t *testing.T) { ob := make([]uint64, bitmapN) ob[0] = 1 << 63 a := NewContainerBitmap(1, ob) - b := NewContainerRun([]interval16{{start: 63, last: 64}}) + b := NewContainerRun([]Interval16{{Start: 63, Last: 64}}) ret := intersectionCountBitmapRun(a, b) if ret != 1 { @@ -405,7 +405,7 @@ func TestIntersectionCountBitmapRun(t *testing.T) { } a = NewContainerBitmap(-1, []uint64{0xF0000001, 0xFF00000000000000, 0xFF000000000000F0, 0x0F0000}) - b = NewContainerRun([]interval16{{start: 29, last: 31}, {start: 125, last: 134}, {start: 191, last: 197}, {start: 200, last: 300}}) + b = NewContainerRun([]Interval16{{Start: 29, Last: 31}, {Start: 125, Last: 134}, {Start: 191, Last: 197}, {Start: 200, Last: 300}}) ret = intersectionCountBitmapRun(a, b) if ret != 14 { @@ -415,40 +415,40 @@ func TestIntersectionCountBitmapRun(t *testing.T) { func TestIntersectionCountRunRun(t *testing.T) { tests := []struct { - aruns []interval16 - bruns []interval16 + aruns []Interval16 + bruns []Interval16 exp int32 }{ { - aruns: []interval16{}, - bruns: []interval16{{start: 3, last: 8}}, exp: 0}, + aruns: []Interval16{}, + bruns: []Interval16{{Start: 3, Last: 8}}, exp: 0}, { - aruns: []interval16{{start: 2, last: 10}}, - bruns: []interval16{{start: 3, last: 8}}, exp: 6}, + aruns: []Interval16{{Start: 2, Last: 10}}, + bruns: []Interval16{{Start: 3, Last: 8}}, exp: 6}, { - aruns: []interval16{{start: 2, last: 10}}, - bruns: []interval16{{start: 1, last: 11}}, exp: 9}, + aruns: []Interval16{{Start: 2, Last: 10}}, + bruns: []Interval16{{Start: 1, Last: 11}}, exp: 9}, { - aruns: []interval16{{start: 2, last: 10}}, - bruns: []interval16{{start: 0, last: 2}}, exp: 1}, + aruns: []Interval16{{Start: 2, Last: 10}}, + bruns: []Interval16{{Start: 0, Last: 2}}, exp: 1}, { - aruns: []interval16{{start: 2, last: 10}}, - bruns: []interval16{{start: 1, last: 10}}, exp: 9}, + aruns: []Interval16{{Start: 2, Last: 10}}, + bruns: []Interval16{{Start: 1, Last: 10}}, exp: 9}, { - aruns: []interval16{{start: 2, last: 10}}, - bruns: []interval16{{start: 5, last: 12}}, exp: 6}, + aruns: []Interval16{{Start: 2, Last: 10}}, + bruns: []Interval16{{Start: 5, Last: 12}}, exp: 6}, { - aruns: []interval16{{start: 2, last: 10}}, - bruns: []interval16{{start: 10, last: 99}}, exp: 1}, + aruns: []Interval16{{Start: 2, Last: 10}}, + bruns: []Interval16{{Start: 10, Last: 99}}, exp: 1}, { - aruns: []interval16{{start: 2, last: 10}, {start: 44, last: 99}}, - bruns: []interval16{{start: 12, last: 14}}, exp: 0}, + aruns: []Interval16{{Start: 2, Last: 10}, {Start: 44, Last: 99}}, + bruns: []Interval16{{Start: 12, Last: 14}}, exp: 0}, { - aruns: []interval16{{start: 2, last: 10}, {start: 12, last: 13}}, - bruns: []interval16{{start: 2, last: 10}, {start: 12, last: 13}}, exp: 11}, + aruns: []Interval16{{Start: 2, Last: 10}, {Start: 12, Last: 13}}, + bruns: []Interval16{{Start: 2, Last: 10}, {Start: 12, Last: 13}}, exp: 11}, { - aruns: []interval16{{start: 8, last: 12}, {start: 15, last: 19}}, - bruns: []interval16{{start: 9, last: 9}, {start: 11, last: 17}}, exp: 6}, + aruns: []Interval16{{Start: 8, Last: 12}, {Start: 15, Last: 19}}, + bruns: []Interval16{{Start: 9, Last: 9}, {Start: 11, Last: 17}}, exp: 6}, } for i, test := range tests { a := NewContainerRun(test.aruns) @@ -465,27 +465,27 @@ func TestIntersectArrayRun(t *testing.T) { b := NewContainerRun(nil) tests := []struct { array []uint16 - runs []interval16 + runs []Interval16 exp []uint16 }{ { array: []uint16{1, 4, 5, 7, 10, 11, 12}, - runs: []interval16{{start: 5, last: 10}}, + runs: []Interval16{{Start: 5, Last: 10}}, exp: []uint16{5, 7, 10}, }, { array: []uint16{}, - runs: []interval16{{start: 5, last: 10}}, + runs: []Interval16{{Start: 5, Last: 10}}, exp: []uint16(nil), }, { array: []uint16{1, 4, 5, 7, 10, 11, 12}, - runs: []interval16{}, + runs: []Interval16{}, exp: []uint16(nil), }, { array: []uint16{0, 1, 4, 5, 7, 10, 11, 12}, - runs: []interval16{{start: 0, last: 5}, {start: 7, last: 7}}, + runs: []Interval16{{Start: 0, Last: 5}, {Start: 7, Last: 7}}, exp: []uint16{0, 1, 4, 5, 7}, }, } @@ -508,45 +508,45 @@ func TestIntersectRunRun(t *testing.T) { a := NewContainerRun(nil) b := NewContainerRun(nil) tests := []struct { - aruns []interval16 - bruns []interval16 - exp []interval16 + aruns []Interval16 + bruns []Interval16 + exp []Interval16 expN int32 }{ { - aruns: []interval16{}, - bruns: []interval16{{start: 5, last: 10}}, - exp: []interval16(nil), + aruns: []Interval16{}, + bruns: []Interval16{{Start: 5, Last: 10}}, + exp: []Interval16(nil), expN: 0, }, { - aruns: []interval16{{start: 5, last: 12}}, - bruns: []interval16{{start: 5, last: 10}}, - exp: []interval16{{start: 5, last: 10}}, + aruns: []Interval16{{Start: 5, Last: 12}}, + bruns: []Interval16{{Start: 5, Last: 10}}, + exp: []Interval16{{Start: 5, Last: 10}}, expN: 6, }, { - aruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 8}, {start: 9, last: 12}}, - bruns: []interval16{{start: 5, last: 10}}, - exp: []interval16{{start: 5, last: 5}, {start: 7, last: 10}}, + aruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 8}, {Start: 9, Last: 12}}, + bruns: []Interval16{{Start: 5, Last: 10}}, + exp: []Interval16{{Start: 5, Last: 5}, {Start: 7, Last: 10}}, expN: 5, }, { - aruns: []interval16{{start: 20, last: 30}}, - bruns: []interval16{{start: 5, last: 10}, {start: 19, last: 21}}, - exp: []interval16{{start: 20, last: 21}}, + aruns: []Interval16{{Start: 20, Last: 30}}, + bruns: []Interval16{{Start: 5, Last: 10}, {Start: 19, Last: 21}}, + exp: []Interval16{{Start: 20, Last: 21}}, expN: 2, }, { - aruns: []interval16{{start: 5, last: 10}}, - bruns: []interval16{{start: 7, last: 12}}, - exp: []interval16{{start: 7, last: 10}}, + aruns: []Interval16{{Start: 5, Last: 10}}, + bruns: []Interval16{{Start: 7, Last: 12}}, + exp: []Interval16{{Start: 7, Last: 10}}, expN: 4, }, { - aruns: []interval16{{start: 5, last: 12}}, - bruns: []interval16{{start: 7, last: 10}}, - exp: []interval16{{start: 7, last: 10}}, + aruns: []Interval16{{Start: 5, Last: 12}}, + bruns: []Interval16{{Start: 7, Last: 10}}, + exp: []Interval16{{Start: 7, Last: 10}}, expN: 4, }, } @@ -570,37 +570,37 @@ func TestIntersectRunRun(t *testing.T) { func TestIntersectBitmapRunBitmap(t *testing.T) { tests := []struct { bitmap []uint64 - runs []interval16 + runs []Interval16 exp []uint64 expN int32 }{ { bitmap: []uint64{1}, - runs: []interval16{{start: 0, last: 0}, {start: 2, last: 5}, {start: 62, last: 71}, {start: 77, last: 4096}}, + runs: []Interval16{{Start: 0, Last: 0}, {Start: 2, Last: 5}, {Start: 62, Last: 71}, {Start: 77, Last: 4096}}, exp: []uint64{1}, expN: 1, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFFF}, - runs: []interval16{{start: 1, last: 1}}, + runs: []Interval16{{Start: 1, Last: 1}}, exp: []uint64{2}, expN: 1, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFFF}, - runs: []interval16{{start: 1, last: 1}, {start: 10, last: 12}, {start: 61, last: 77}}, + runs: []Interval16{{Start: 1, Last: 1}, {Start: 10, Last: 12}, {Start: 61, Last: 77}}, exp: []uint64{0xe000000000001C02}, expN: 7, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}, - runs: []interval16{{start: 1, last: 1}, {start: 61, last: 77}}, + runs: []Interval16{{Start: 1, Last: 1}, {Start: 61, Last: 77}}, exp: []uint64{0xE000000000000002, 0x00000000000003FFF}, expN: 18, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFFF, 1, 1, 1, 0xA, 1, 1, 0, 1}, - runs: []interval16{{start: 63, last: 10000}}, + runs: []Interval16{{Start: 63, Last: 10000}}, exp: []uint64{0x8000000000000000, 1, 1, 1, 0xA, 1, 1, 0, 1}, expN: 9, }, @@ -630,37 +630,37 @@ func TestIntersectBitmapRunArray(t *testing.T) { b := NewContainerRun(nil) tests := []struct { bitmap []uint64 - runs []interval16 + runs []Interval16 exp []uint16 expN int32 }{ { bitmap: []uint64{1}, - runs: []interval16{{start: 0, last: 0}, {start: 2, last: 5}, {start: 62, last: 71}, {start: 77, last: 4096}}, + runs: []Interval16{{Start: 0, Last: 0}, {Start: 2, Last: 5}, {Start: 62, Last: 71}, {Start: 77, Last: 4096}}, exp: []uint16{0}, expN: 1, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFFF}, - runs: []interval16{{start: 1, last: 1}}, + runs: []Interval16{{Start: 1, Last: 1}}, exp: []uint16{1}, expN: 1, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFFF}, - runs: []interval16{{start: 1, last: 1}, {start: 10, last: 12}, {start: 61, last: 77}}, + runs: []Interval16{{Start: 1, Last: 1}, {Start: 10, Last: 12}, {Start: 61, Last: 77}}, exp: []uint16{1, 10, 11, 12, 61, 62, 63}, expN: 7, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}, - runs: []interval16{{start: 1, last: 1}, {start: 61, last: 68}}, + runs: []Interval16{{Start: 1, Last: 1}, {Start: 61, Last: 68}}, exp: []uint16{1, 61, 62, 63, 64, 65, 66, 67, 68}, expN: 9, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFFF, 1, 1, 1, 0xA, 1, 1, 0, 1}, - runs: []interval16{{start: 63, last: 10000}, {start: 65000, last: 65535}}, + runs: []Interval16{{Start: 63, Last: 10000}, {Start: 65000, Last: 65535}}, exp: []uint16{63, 64, 128, 192, 257, 259, 320, 384, 512}, expN: 9, }, @@ -688,7 +688,7 @@ func TestUnionMixed(t *testing.T) { b := NewContainerBitmap(2, []uint64{0x3}) // run container - r := NewContainerRun([]interval16{{start: 5, last: 10}}) + r := NewContainerRun([]Interval16{{Start: 5, Last: 10}}) t.Run("various container Unions", func(t *testing.T) { tests := []struct { @@ -721,8 +721,190 @@ func TestUnionMixed(t *testing.T) { }) } +func TestUnionInterval16InPlace(t *testing.T) { + tests := []struct { + name string + a []Interval16 + b []Interval16 + expected []Interval16 + expectedN int32 + }{ + { + name: "firstBitUnset lastBitSet", + a: []Interval16{Interval16{1, 10}}, + b: []Interval16{Interval16{10, 10}}, + expected: []Interval16{Interval16{1, 10}}, + expectedN: 10, + }, + { + name: "single overlap", + a: []Interval16{Interval16{1, 10}, Interval16{21, 28}}, + b: []Interval16{Interval16{8, 12}}, + expected: []Interval16{Interval16{1, 12}, Interval16{21, 28}}, + expectedN: 20, + }, + { + name: "nested intervals", + a: []Interval16{Interval16{3, 13}, Interval16{17, 20}}, + b: []Interval16{Interval16{1, 4}, Interval16{6, 7}, Interval16{8, 9}, Interval16{10, 11}, Interval16{14, 17}}, + expected: []Interval16{Interval16{1, 20}}, + expectedN: 20, + }, + { + name: "no overlap", + a: []Interval16{Interval16{3, 4}, Interval16{7, 8}}, + b: []Interval16{Interval16{1, 2}, Interval16{5, 6}, Interval16{9, 10}}, + expected: []Interval16{Interval16{1, 10}}, + expectedN: 10, + }, + { + name: "b in a", + a: []Interval16{Interval16{1, 10}}, + b: []Interval16{Interval16{5, 7}}, + expected: []Interval16{Interval16{1, 10}}, + expectedN: 10, + }, + { + name: "a eq b", + a: []Interval16{Interval16{1, 10}}, + b: []Interval16{Interval16{1, 10}}, + expected: []Interval16{Interval16{1, 10}}, + expectedN: 10, + }, + { + name: "a in b", + a: []Interval16{Interval16{5, 7}}, + b: []Interval16{Interval16{1, 10}}, + expected: []Interval16{Interval16{1, 10}}, + expectedN: 10, + }, + { + name: "a ahead b", + a: []Interval16{Interval16{1, 2}, Interval16{3, 4}, Interval16{5, 7}}, + b: []Interval16{Interval16{10, 11}, Interval16{12, 13}, Interval16{14, 15}}, + expected: []Interval16{Interval16{1, 7}, Interval16{10, 15}}, + expectedN: 13, + }, + { + name: "b ahead a", + a: []Interval16{Interval16{10, 11}, Interval16{12, 13}, Interval16{14, 15}}, + b: []Interval16{Interval16{1, 2}, Interval16{3, 4}, Interval16{5, 7}}, + expected: []Interval16{Interval16{1, 7}, Interval16{10, 15}}, + expectedN: 13, + }, + { + name: "empty a and b", + a: []Interval16{}, + b: []Interval16{}, + expected: []Interval16{}, + expectedN: 0, + }, + { + name: "empty a", + a: []Interval16{}, + b: []Interval16{Interval16{1, 2}, Interval16{3, 4}, Interval16{5, 7}}, + expected: []Interval16{Interval16{1, 7}}, + expectedN: 7, + }, + { + name: "empty b", + a: []Interval16{Interval16{1, 2}, Interval16{3, 4}, Interval16{5, 7}}, + b: []Interval16{}, + expected: []Interval16{Interval16{1, 7}}, + expectedN: 7, + }, + { + name: "single a", + a: []Interval16{Interval16{1, 2}}, + b: []Interval16{}, + expected: []Interval16{Interval16{1, 2}}, + expectedN: 2, + }, + { + name: "single b", + a: []Interval16{}, + b: []Interval16{Interval16{1, 2}}, + expected: []Interval16{Interval16{1, 2}}, + expectedN: 2, + }, + { + name: "single a single b", + a: []Interval16{Interval16{3, 4}}, + b: []Interval16{Interval16{1, 2}}, + expected: []Interval16{Interval16{1, 4}}, + expectedN: 4, + }, + { + name: "oddBitsSet lastBitUnset", + a: []Interval16{Interval16{1, 1}, Interval16{3, 3}, Interval16{5, 5}}, + b: []Interval16{Interval16{0, 4}}, + expected: []Interval16{Interval16{0, 5}}, + expectedN: 6, + }, + { + name: "all bits", + a: []Interval16{Interval16{1, 1}, Interval16{3, 3}, Interval16{5, 5}}, + b: []Interval16{Interval16{0, 0}, Interval16{2, 2}, Interval16{4, 4}}, + expected: []Interval16{Interval16{0, 5}}, + expectedN: 6, + }, + { + name: "short a long b", + a: []Interval16{Interval16{5, 5}, Interval16{7, 7}, Interval16{9, 10}, Interval16{12, 12}, Interval16{15, 17}, Interval16{19, 20}}, + b: []Interval16{Interval16{1, 10}, Interval16{12, 12}, Interval16{14, 18}}, + expected: []Interval16{Interval16{1, 10}, Interval16{12, 12}, Interval16{14, 20}}, + expectedN: 18, + }, + { + name: "common endings", + a: []Interval16{Interval16{1, 5}, Interval16{15, 20}, Interval16{25, 35}}, + b: []Interval16{Interval16{1, 10}, Interval16{15, 20}, Interval16{30, 35}}, + expected: []Interval16{Interval16{1, 10}, Interval16{15, 20}, Interval16{25, 35}}, + expectedN: 27, + }, + { + name: "common endings and overlap", + a: []Interval16{Interval16{1, 5}, Interval16{10, 15}}, + b: []Interval16{Interval16{5, 10}, Interval16{12, 17}}, + expected: []Interval16{Interval16{1, 17}}, + expectedN: 17, + }, + { + name: "no common endings and overlap", + a: []Interval16{Interval16{5, 10}, Interval16{12, 17}}, + b: []Interval16{Interval16{0, 11}, Interval16{15, 20}}, + expected: []Interval16{Interval16{0, 20}}, + expectedN: 21, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + bb := make([]Interval16, len(tc.b)) + copy(bb, tc.b) + + runs, n := unionInterval16InPlace(tc.a, tc.b) + + for i, v := range tc.expected { + if runs[i] != v { + t.Fatalf("runs expected: %+v, got: %+v", tc.expected, runs) + } + } + if n != tc.expectedN { + t.Fatalf("N expected: %d, got: %d", tc.expectedN, n) + } + + for i, v := range bb { + if tc.b[i] != v { + t.Fatalf("b changed - runs expected: %+v, got: %+v", bb, tc.b) + } + } + }) + } +} + func TestIntersectMixed(t *testing.T) { - a := NewContainerRun([]interval16{{start: 5, last: 10}}) + a := NewContainerRun([]Interval16{{Start: 5, Last: 10}}) b := NewContainerArray([]uint16{1, 4, 5, 7, 10, 11, 12}) c := NewContainerBitmap(2, []uint64{0x60}) @@ -735,8 +917,8 @@ func TestIntersectMixed(t *testing.T) { t.Fatalf("test #1 expected %v, but got %v", []uint16{5, 7, 10}, res.array()) } res = intersect(a, a) - if !reflect.DeepEqual(res.runs(), []interval16{{start: 5, last: 10}}) { - t.Fatalf("test #3 expected %v, but got %v", []interval16{{start: 5, last: 10}}, res.runs()) + if !reflect.DeepEqual(res.runs(), []Interval16{{Start: 5, Last: 10}}) { + t.Fatalf("test #3 expected %v, but got %v", []Interval16{{Start: 5, Last: 10}}, res.runs()) } res = intersect(c, a) @@ -760,7 +942,7 @@ func TestIntersectMixed(t *testing.T) { } func TestDifferenceMixed(t *testing.T) { - a := NewContainerRun([]interval16{{start: 5, last: 10}}) + a := NewContainerRun([]Interval16{{Start: 5, Last: 10}}) b := NewContainerArray([]uint16{0, 2, 4, 6, 8, 10, 12}) @@ -780,7 +962,7 @@ func TestDifferenceMixed(t *testing.T) { } res = difference(a, a) - if !reflect.DeepEqual(res.runs(), []interval16{}) { + if !reflect.DeepEqual(res.runs(), []Interval16{}) { t.Fatalf("test #3 expected empty but got %v", res.runs()) } @@ -790,8 +972,8 @@ func TestDifferenceMixed(t *testing.T) { } res = difference(a, c) - if !reflect.DeepEqual(res.runs(), []interval16{{start: 7, last: 10}}) { - t.Fatalf("test #5 expected %v, but got %v", []interval16{{start: 7, last: 10}}, res.runs()) + if !reflect.DeepEqual(res.runs(), []Interval16{{Start: 7, Last: 10}}) { + t.Fatalf("test #5 expected %v, but got %v", []Interval16{{Start: 7, Last: 10}}, res.runs()) } res = difference(b, c) @@ -830,49 +1012,49 @@ func TestUnionRunRun(t *testing.T) { a := NewContainerRun(nil) b := NewContainerRun(nil) tests := []struct { - aruns []interval16 - bruns []interval16 - exp []interval16 + aruns []Interval16 + bruns []Interval16 + exp []Interval16 }{ { - aruns: []interval16{}, - bruns: []interval16{{start: 5, last: 10}}, - exp: []interval16{{start: 5, last: 10}}, + aruns: []Interval16{}, + bruns: []Interval16{{Start: 5, Last: 10}}, + exp: []Interval16{{Start: 5, Last: 10}}, }, { - aruns: []interval16{{start: 5, last: 12}}, - bruns: []interval16{{start: 5, last: 10}}, - exp: []interval16{{start: 5, last: 12}}, + aruns: []Interval16{{Start: 5, Last: 12}}, + bruns: []Interval16{{Start: 5, Last: 10}}, + exp: []Interval16{{Start: 5, Last: 12}}, }, { - aruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 8}, {start: 9, last: 12}}, - bruns: []interval16{{start: 5, last: 10}}, - exp: []interval16{{start: 1, last: 3}, {start: 5, last: 12}}, + aruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 8}, {Start: 9, Last: 12}}, + bruns: []Interval16{{Start: 5, Last: 10}}, + exp: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 12}}, }, { - aruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 8}, {start: 9, last: 12}}, - bruns: []interval16{{start: 2, last: 65535}}, - exp: []interval16{{start: 1, last: 65535}}, + aruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 8}, {Start: 9, Last: 12}}, + bruns: []Interval16{{Start: 2, Last: 65535}}, + exp: []Interval16{{Start: 1, Last: 65535}}, }, { - aruns: []interval16{{start: 2, last: 65535}}, - bruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 8}, {start: 9, last: 12}}, - exp: []interval16{{start: 1, last: 65535}}, + aruns: []Interval16{{Start: 2, Last: 65535}}, + bruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 8}, {Start: 9, Last: 12}}, + exp: []Interval16{{Start: 1, Last: 65535}}, }, { - aruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 8}, {start: 9, last: 12}}, - bruns: []interval16{{start: 0, last: 65535}}, - exp: []interval16{{start: 0, last: 65535}}, + aruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 8}, {Start: 9, Last: 12}}, + bruns: []Interval16{{Start: 0, Last: 65535}}, + exp: []Interval16{{Start: 0, Last: 65535}}, }, { - aruns: []interval16{{start: 0, last: 65535}}, - bruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 8}, {start: 9, last: 12}}, - exp: []interval16{{start: 0, last: 65535}}, + aruns: []Interval16{{Start: 0, Last: 65535}}, + bruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 8}, {Start: 9, Last: 12}}, + exp: []Interval16{{Start: 0, Last: 65535}}, }, { - aruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 9}, {start: 12, last: 22}}, - bruns: []interval16{{start: 2, last: 8}, {start: 16, last: 27}, {start: 33, last: 34}}, - exp: []interval16{{start: 1, last: 9}, {start: 12, last: 27}, {start: 33, last: 34}}, + aruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 9}, {Start: 12, Last: 22}}, + bruns: []Interval16{{Start: 2, Last: 8}, {Start: 16, Last: 27}, {Start: 33, Last: 34}}, + exp: []Interval16{{Start: 1, Last: 9}, {Start: 12, Last: 27}, {Start: 33, Last: 34}}, }, } for i, test := range tests { @@ -890,27 +1072,27 @@ func TestUnionArrayRun(t *testing.T) { b := NewContainerRun(nil) tests := []struct { array []uint16 - runs []interval16 + runs []Interval16 exp []uint16 }{ { array: []uint16{1, 4, 5, 7, 10, 11, 12}, - runs: []interval16{{start: 5, last: 10}}, + runs: []Interval16{{Start: 5, Last: 10}}, exp: []uint16{1, 4, 5, 6, 7, 8, 9, 10, 11, 12}, }, { array: []uint16{}, - runs: []interval16{{start: 5, last: 10}}, + runs: []Interval16{{Start: 5, Last: 10}}, exp: []uint16{5, 6, 7, 8, 9, 10}, }, { array: []uint16{1, 4, 5, 7, 10, 11, 12}, - runs: []interval16{}, + runs: []Interval16{}, exp: []uint16{1, 4, 5, 7, 10, 11, 12}, }, { array: []uint16{0, 1, 4, 5, 7, 10, 11, 12}, - runs: []interval16{{start: 0, last: 5}, {start: 7, last: 7}}, + runs: []Interval16{{Start: 0, Last: 5}, {Start: 7, Last: 7}}, exp: []uint16{0, 1, 2, 3, 4, 5, 7, 10, 11, 12}, }, } @@ -1013,27 +1195,27 @@ func TestBitmapToArray(t *testing.T) { func TestRunToBitmap(t *testing.T) { tests := []struct { - runs []interval16 + runs []Interval16 exp []uint64 }{ { - runs: []interval16{}, + runs: []Interval16{}, exp: []uint64{}, }, { - runs: []interval16{{start: 0, last: 0}}, + runs: []Interval16{{Start: 0, Last: 0}}, exp: []uint64{1}, }, { - runs: []interval16{{start: 0, last: 4}}, + runs: []Interval16{{Start: 0, Last: 4}}, exp: []uint64{31}, }, { - runs: []interval16{{start: 2, last: 2}, {start: 5, last: 7}, {start: 13, last: 14}, {start: 17, last: 17}}, + runs: []Interval16{{Start: 2, Last: 2}, {Start: 5, Last: 7}, {Start: 13, Last: 14}, {Start: 17, Last: 17}}, exp: []uint64{155876}, }, { - runs: []interval16{{start: 0, last: 3}, {start: 60, last: 67}}, + runs: []Interval16{{Start: 0, Last: 3}, {Start: 60, Last: 67}}, exp: []uint64{0xF00000000000000F, 0x000000000000000F}, }, } @@ -1065,55 +1247,55 @@ func getFullBitmap() []uint64 { func TestBitmapToRun(t *testing.T) { tests := []struct { bitmap []uint64 - exp []interval16 + exp []Interval16 }{ { // empty run bitmap: []uint64{}, - exp: []interval16{}, + exp: []Interval16{}, }, { // single-bit run bitmap: []uint64{1}, - exp: []interval16{{start: 0, last: 0}}, + exp: []Interval16{{Start: 0, Last: 0}}, }, { // single multi-bit run in one word bitmap: []uint64{31}, - exp: []interval16{{start: 0, last: 4}}, + exp: []Interval16{{Start: 0, Last: 4}}, }, { // multiple runs in one word bitmap: []uint64{155876}, - exp: []interval16{{start: 2, last: 2}, {start: 5, last: 7}, {start: 13, last: 14}, {start: 17, last: 17}}, + exp: []Interval16{{Start: 2, Last: 2}, {Start: 5, Last: 7}, {Start: 13, Last: 14}, {Start: 17, Last: 17}}, }, { // span two words, both mixed bitmap: []uint64{0xF00000000000000F, 0x000000000000000F}, - exp: []interval16{{start: 0, last: 3}, {start: 60, last: 67}}, + exp: []Interval16{{Start: 0, Last: 3}, {Start: 60, Last: 67}}, }, { // span two words, first = maxBitmap bitmap: []uint64{0xFFFFFFFFFFFFFFFF, 0xF}, - exp: []interval16{{start: 0, last: 67}}, + exp: []Interval16{{Start: 0, Last: 67}}, }, { // span two words, second = maxBitmap bitmap: []uint64{0xF000000000000000, 0xFFFFFFFFFFFFFFFF}, - exp: []interval16{{start: 60, last: 127}}, + exp: []Interval16{{Start: 60, Last: 127}}, }, { // span three words bitmap: []uint64{0xF000000000000000, 0xFFFFFFFFFFFFFFFF, 0xF}, - exp: []interval16{{start: 60, last: 131}}, + exp: []Interval16{{Start: 60, Last: 131}}, }, { bitmap: make([]uint64, bitmapN), - exp: []interval16{{start: 65408, last: 65535}}, + exp: []Interval16{{Start: 65408, Last: 65535}}, }, { bitmap: getFullBitmap(), - exp: []interval16{{start: 0, last: 65535}}, + exp: []Interval16{{Start: 0, Last: 65535}}, }, } tests[8].bitmap[1022] = 0xFFFFFFFFFFFFFFFF @@ -1136,23 +1318,23 @@ func TestBitmapToRun(t *testing.T) { func TestArrayToRun(t *testing.T) { tests := []struct { array []uint16 - exp []interval16 + exp []Interval16 }{ { array: []uint16{}, - exp: []interval16{}, + exp: []Interval16{}, }, { array: []uint16{0}, - exp: []interval16{{start: 0, last: 0}}, + exp: []Interval16{{Start: 0, Last: 0}}, }, { array: []uint16{0, 1, 2, 3, 4}, - exp: []interval16{{start: 0, last: 4}}, + exp: []Interval16{{Start: 0, Last: 4}}, }, { array: []uint16{2, 5, 6, 7, 13, 14, 17}, - exp: []interval16{{start: 2, last: 2}, {start: 5, last: 7}, {start: 13, last: 14}, {start: 17, last: 17}}, + exp: []Interval16{{Start: 2, Last: 2}, {Start: 5, Last: 7}, {Start: 13, Last: 14}, {Start: 17, Last: 17}}, }, } @@ -1167,23 +1349,23 @@ func TestArrayToRun(t *testing.T) { func TestRunToArray(t *testing.T) { tests := []struct { - runs []interval16 + runs []Interval16 exp []uint16 }{ { - runs: []interval16{}, + runs: []Interval16{}, exp: []uint16{}, }, { - runs: []interval16{{start: 0, last: 0}}, + runs: []Interval16{{Start: 0, Last: 0}}, exp: []uint16{0}, }, { - runs: []interval16{{start: 0, last: 4}}, + runs: []Interval16{{Start: 0, Last: 4}}, exp: []uint16{0, 1, 2, 3, 4}, }, { - runs: []interval16{{start: 2, last: 2}, {start: 5, last: 7}, {start: 13, last: 14}, {start: 17, last: 17}}, + runs: []Interval16{{Start: 2, Last: 2}, {Start: 5, Last: 7}, {Start: 13, Last: 14}, {Start: 17, Last: 17}}, exp: []uint16{2, 5, 6, 7, 13, 14, 17}, }, } @@ -1241,13 +1423,13 @@ func TestBitmapZeroRange(t *testing.T) { func TestUnionBitmapRun(t *testing.T) { tests := []struct { bitmap []uint64 - runs []interval16 + runs []Interval16 exp []uint64 expN int32 }{ { bitmap: []uint64{2}, - runs: []interval16{{start: 0, last: 0}, {start: 2, last: 5}, {start: 62, last: 71}, {start: 77, last: 78}}, + runs: []Interval16{{Start: 0, Last: 0}, {Start: 2, Last: 5}, {Start: 62, Last: 71}, {Start: 77, Last: 78}}, exp: []uint64{0xC00000000000003F, 0x60FF}, expN: 18, }, @@ -1363,12 +1545,12 @@ func TestArrayCountRuns(t *testing.T) { func TestDifferenceArrayRun(t *testing.T) { tests := []struct { array []uint16 - runs []interval16 + runs []Interval16 exp []uint16 }{ { array: []uint16{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, - runs: []interval16{{start: 5, last: 10}}, + runs: []Interval16{{Start: 5, Last: 10}}, exp: []uint16{0, 1, 2, 3, 4, 11, 12}, }, } @@ -1384,54 +1566,54 @@ func TestDifferenceArrayRun(t *testing.T) { func TestDifferenceRunArray(t *testing.T) { tests := []struct { - runs []interval16 + runs []Interval16 array []uint16 - exp []interval16 + exp []Interval16 }{ { - runs: []interval16{{start: 0, last: 12}}, + runs: []Interval16{{Start: 0, Last: 12}}, array: []uint16{5, 6, 7, 8, 9, 10}, - exp: []interval16{{start: 0, last: 4}, {start: 11, last: 12}}, + exp: []Interval16{{Start: 0, Last: 4}, {Start: 11, Last: 12}}, }, { - runs: []interval16{{start: 0, last: 12}}, + runs: []Interval16{{Start: 0, Last: 12}}, array: []uint16{0, 1, 2, 3}, - exp: []interval16{{start: 4, last: 12}}, + exp: []Interval16{{Start: 4, Last: 12}}, }, { - runs: []interval16{{start: 0, last: 12}}, + runs: []Interval16{{Start: 0, Last: 12}}, array: []uint16{9, 10, 11, 12, 13}, - exp: []interval16{{start: 0, last: 8}}, + exp: []Interval16{{Start: 0, Last: 8}}, }, { - runs: []interval16{{start: 1, last: 12}}, + runs: []Interval16{{Start: 1, Last: 12}}, array: []uint16{0, 9, 10, 11, 12, 13}, - exp: []interval16{{start: 1, last: 8}}, + exp: []Interval16{{Start: 1, Last: 8}}, }, { - runs: []interval16{{start: 1, last: 12}, {start: 14, last: 14}, {start: 18, last: 18}}, + runs: []Interval16{{Start: 1, Last: 12}, {Start: 14, Last: 14}, {Start: 18, Last: 18}}, array: []uint16{0, 9, 10, 11, 12, 13, 14, 17}, - exp: []interval16{{start: 1, last: 8}, {start: 18, last: 18}}, + exp: []Interval16{{Start: 1, Last: 8}, {Start: 18, Last: 18}}, }, { - runs: []interval16{{start: 1, last: 12}, {start: 14, last: 14}, {start: 18, last: 18}}, + runs: []Interval16{{Start: 1, Last: 12}, {Start: 14, Last: 14}, {Start: 18, Last: 18}}, array: []uint16{0, 9, 10, 11, 12, 13, 14, 17, 19}, - exp: []interval16{{start: 1, last: 8}, {start: 18, last: 18}}, + exp: []Interval16{{Start: 1, Last: 8}, {Start: 18, Last: 18}}, }, { - runs: []interval16{{start: 1, last: 12}, {start: 14, last: 17}, {start: 19, last: 28}}, + runs: []Interval16{{Start: 1, Last: 12}, {Start: 14, Last: 17}, {Start: 19, Last: 28}}, array: []uint16{0, 9, 10, 11, 12, 13, 14, 17, 19, 25, 27}, - exp: []interval16{{start: 1, last: 8}, {start: 15, last: 16}, {start: 20, last: 24}, {start: 26, last: 26}, {start: 28, last: 28}}, + exp: []Interval16{{Start: 1, Last: 8}, {Start: 15, Last: 16}, {Start: 20, Last: 24}, {Start: 26, Last: 26}, {Start: 28, Last: 28}}, }, { - runs: []interval16{{start: 0, last: 20}, {start: 65533, last: 65535}}, + runs: []Interval16{{Start: 0, Last: 20}, {Start: 65533, Last: 65535}}, array: []uint16{65533, 65534, 65535}, - exp: []interval16{{start: 0, last: 20}}, + exp: []Interval16{{Start: 0, Last: 20}}, }, { - runs: []interval16{{start: 0, last: 20}, {start: 65530, last: 65535}}, + runs: []Interval16{{Start: 0, Last: 20}, {Start: 65530, Last: 65535}}, array: []uint16{37, 65535}, - exp: []interval16{{start: 0, last: 20}, {start: 65530, last: 65534}}, + exp: []Interval16{{Start: 0, Last: 20}, {Start: 65530, Last: 65534}}, }, } for i, test := range tests { @@ -1457,49 +1639,49 @@ func MakeLastBitSet() []uint64 { func TestDifferenceRunBitmap(t *testing.T) { tests := []struct { - runs []interval16 + runs []Interval16 bitmap []uint64 - exp []interval16 + exp []Interval16 }{ { - runs: []interval16{{start: 0, last: 63}}, + runs: []Interval16{{Start: 0, Last: 63}}, bitmap: MakeBitmap([]uint64{0x0000FFFF000000F0}), - exp: []interval16{{start: 0, last: 3}, {start: 8, last: 31}, {start: 48, last: 63}}, + exp: []Interval16{{Start: 0, Last: 3}, {Start: 8, Last: 31}, {Start: 48, Last: 63}}, }, { - runs: []interval16{{start: 0, last: 63}}, + runs: []Interval16{{Start: 0, Last: 63}}, bitmap: MakeBitmap([]uint64{0x8000000000000000}), - exp: []interval16{{start: 0, last: 62}}, + exp: []Interval16{{Start: 0, Last: 62}}, }, { - runs: []interval16{{start: 0, last: 63}}, + runs: []Interval16{{Start: 0, Last: 63}}, bitmap: MakeBitmap([]uint64{0x0000000000000001}), - exp: []interval16{{start: 1, last: 63}}, + exp: []Interval16{{Start: 1, Last: 63}}, }, { - runs: []interval16{{start: 0, last: 63}}, + runs: []Interval16{{Start: 0, Last: 63}}, bitmap: MakeBitmap([]uint64{0x0, 0x0000000000000001}), - exp: []interval16{{start: 0, last: 63}}, + exp: []Interval16{{Start: 0, Last: 63}}, }, { - runs: []interval16{{start: 0, last: 65}}, + runs: []Interval16{{Start: 0, Last: 65}}, bitmap: MakeBitmap([]uint64{0x0, 0x0000000000000001}), - exp: []interval16{{start: 0, last: 63}, {start: 65, last: 65}}, + exp: []Interval16{{Start: 0, Last: 63}, {Start: 65, Last: 65}}, }, { - runs: []interval16{{start: 0, last: 65}}, + runs: []Interval16{{Start: 0, Last: 65}}, bitmap: MakeBitmap([]uint64{0x0, 0x8000000000000000}), - exp: []interval16{{start: 0, last: 65}}, + exp: []Interval16{{Start: 0, Last: 65}}, }, { - runs: []interval16{{start: 1, last: 65535}}, + runs: []Interval16{{Start: 1, Last: 65535}}, bitmap: MakeBitmap([]uint64{0x0000000000000001}), - exp: []interval16{{start: 1, last: 65535}}, + exp: []Interval16{{Start: 1, Last: 65535}}, }, { - runs: []interval16{{start: 0, last: 65533}, {start: 65535, last: 65535}}, + runs: []Interval16{{Start: 0, Last: 65533}, {Start: 65535, Last: 65535}}, bitmap: MakeLastBitSet(), - exp: []interval16{{start: 0, last: 65533}}, + exp: []Interval16{{Start: 0, Last: 65533}}, }, } for i, test := range tests { @@ -1515,67 +1697,66 @@ func TestDifferenceRunBitmap(t *testing.T) { func TestDifferenceBitmapRun(t *testing.T) { tests := []struct { bitmap []uint64 - runs []interval16 + runs []Interval16 exp []uint64 }{ { bitmap: []uint64{0xFFFFFFFFFFFFFFFF}, - runs: []interval16{{start: 4, last: 7}, {start: 32, last: 47}}, + runs: []Interval16{{Start: 4, Last: 7}, {Start: 32, Last: 47}}, exp: []uint64{0xFFFF0000FFFFFF0F}, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFBF}, - runs: []interval16{{start: 0, last: 5}, {start: 7, last: 63}}, + runs: []Interval16{{Start: 0, Last: 5}, {Start: 7, Last: 63}}, exp: []uint64{0x0000000000000000}, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFBF}, - runs: []interval16{{start: 0, last: 5}}, + runs: []Interval16{{Start: 0, Last: 5}}, exp: []uint64{0xFFFFFFFFFFFFFF80}, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFFF}, - runs: []interval16{{start: 60, last: 63}}, + runs: []Interval16{{Start: 60, Last: 63}}, exp: []uint64{0x0FFFFFFFFFFFFFFF}, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFFF}, - runs: []interval16{{start: 60, last: 65}}, + runs: []Interval16{{Start: 60, Last: 65}}, exp: []uint64{0x0FFFFFFFFFFFFFFF}, }, { bitmap: []uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}, - runs: []interval16{{start: 60, last: 65}, {start: 67, last: 72}, {start: 126, last: 130}}, + runs: []Interval16{{Start: 60, Last: 65}, {Start: 67, Last: 72}, {Start: 126, Last: 130}}, exp: []uint64{0x0FFFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFE04, 0xFFFFFFFFFFFFFFF8}, }, { bitmap: []uint64{0x0000000000000001}, - runs: []interval16{{start: 0, last: 0}}, + runs: []Interval16{{Start: 0, Last: 0}}, exp: []uint64{0x0000000000000000}, }, { bitmap: []uint64{0x8000000000000000}, - runs: []interval16{{start: 63, last: 63}}, + runs: []Interval16{{Start: 63, Last: 63}}, exp: []uint64{0x0000000000000000}, }, { bitmap: []uint64{0xC000000000000000, 0x0000000000000003}, - runs: []interval16{{start: 63, last: 64}}, + runs: []Interval16{{Start: 63, Last: 64}}, exp: []uint64{0x4000000000000000, 0x0000000000000002}, }, { bitmap: []uint64{0x0000000000000000}, - runs: []interval16{{start: 5, last: 7}}, + runs: []Interval16{{Start: 5, Last: 7}}, exp: []uint64{0x0000000000000000}, - }, - { + }, { bitmap: bitmapLastBitSet(), - runs: []interval16{{start: 65535, last: 65535}}, + runs: []Interval16{{Start: 65535, Last: 65535}}, exp: bitmapEmpty(), }, { bitmap: bitmapFull(), - runs: []interval16{{start: 0, last: 65535}}, + runs: []Interval16{{Start: 0, Last: 65535}}, exp: bitmapEmpty(), }, } @@ -1665,18 +1846,18 @@ func TestDifferenceBitmapBitmap(t *testing.T) { func TestDifferenceRunRun(t *testing.T) { tests := []struct { - aruns []interval16 - bruns []interval16 - exp []interval16 + aruns []Interval16 + bruns []Interval16 + exp []Interval16 expn int32 }{ { // this tests all six overlap combinations // A [ ] [ ] [ ] [ ] [ ] [ ] // B [ ] [ ] [ ] [ ] [ ] [ ] - aruns: []interval16{{start: 3, last: 6}, {start: 13, last: 16}, {start: 24, last: 26}, {start: 33, last: 38}, {start: 43, last: 46}, {start: 53, last: 56}}, - bruns: []interval16{{start: 1, last: 8}, {start: 11, last: 14}, {start: 21, last: 23}, {start: 35, last: 37}, {start: 44, last: 48}, {start: 57, last: 59}}, - exp: []interval16{{start: 15, last: 16}, {start: 24, last: 26}, {start: 33, last: 34}, {start: 38, last: 38}, {start: 43, last: 43}, {start: 53, last: 56}}, + aruns: []Interval16{{Start: 3, Last: 6}, {Start: 13, Last: 16}, {Start: 24, Last: 26}, {Start: 33, Last: 38}, {Start: 43, Last: 46}, {Start: 53, Last: 56}}, + bruns: []Interval16{{Start: 1, Last: 8}, {Start: 11, Last: 14}, {Start: 21, Last: 23}, {Start: 35, Last: 37}, {Start: 44, Last: 48}, {Start: 57, Last: 59}}, + exp: []Interval16{{Start: 15, Last: 16}, {Start: 24, Last: 26}, {Start: 33, Last: 34}, {Start: 38, Last: 38}, {Start: 43, Last: 43}, {Start: 53, Last: 56}}, expn: 13, }, } @@ -1769,7 +1950,7 @@ func TestWriteReadFullBitmap(t *testing.T) { } func TestWriteReadRun(t *testing.T) { - cr := NewContainerRun([]interval16{{start: 3, last: 13}, {start: 100, last: 109}}) + cr := NewContainerRun([]Interval16{{Start: 3, Last: 13}, {Start: 100, Last: 109}}) br := NewFileBitmap() br.Containers.Put(0, cr) br2 := NewFileBitmap() @@ -1795,19 +1976,19 @@ func TestXorArrayRun(t *testing.T) { }{ { a: NewContainerArray([]uint16{1, 5, 10, 11, 12}), - b: NewContainerRun([]interval16{{start: 2, last: 10}, {start: 12, last: 13}, {start: 15, last: 16}}), + b: NewContainerRun([]Interval16{{Start: 2, Last: 10}, {Start: 12, Last: 13}, {Start: 15, Last: 16}}), exp: NewContainerArray([]uint16{1, 2, 3, 4, 6, 7, 8, 9, 11, 13, 15, 16}), }, { a: NewContainerArray([]uint16{1, 5, 10, 11, 12, 13, 14}), - b: NewContainerRun([]interval16{{start: 2, last: 10}, {start: 12, last: 13}, {start: 15, last: 16}}), + b: NewContainerRun([]Interval16{{Start: 2, Last: 10}, {Start: 12, Last: 13}, {Start: 15, Last: 16}}), exp: NewContainerArray([]uint16{1, 2, 3, 4, 6, 7, 8, 9, 11, 14, 15, 16}), }, { a: NewContainerArray([]uint16{65535}), - b: NewContainerRun([]interval16{{start: 65534, last: 65535}}), + b: NewContainerRun([]Interval16{{Start: 65534, Last: 65535}}), exp: NewContainerArray([]uint16{65534}), }, { a: NewContainerArray([]uint16{65535}), - b: NewContainerRun([]interval16{{start: 65535, last: 65535}}), + b: NewContainerRun([]Interval16{{Start: 65535, Last: 65535}}), exp: NewContainerArray([]uint16{}), }, } @@ -1829,8 +2010,8 @@ func TestXorArrayRun(t *testing.T) { //special case that didn't fit the xorrunrun table testing below. func TestXorRunRun1(t *testing.T) { - a := NewContainerRun([]interval16{{start: 4, last: 10}}) - b := NewContainerRun([]interval16{{start: 5, last: 10}}) + a := NewContainerRun([]Interval16{{Start: 4, Last: 10}}) + b := NewContainerRun([]Interval16{{Start: 5, Last: 10}}) ret := xorRunRun(a, b) if !reflect.DeepEqual(ret.array(), []uint16{4}) { t.Fatalf("test #1 expected %v, but got %v", []uint16{4}, ret.array()) @@ -1845,84 +2026,84 @@ func TestXorRunRun(t *testing.T) { a := NewContainerRun(nil) b := NewContainerRun(nil) tests := []struct { - aruns []interval16 - bruns []interval16 - exp []interval16 + aruns []Interval16 + bruns []Interval16 + exp []Interval16 }{ { - aruns: []interval16{}, - bruns: []interval16{{start: 5, last: 10}}, - exp: []interval16{{start: 5, last: 10}}, + aruns: []Interval16{}, + bruns: []Interval16{{Start: 5, Last: 10}}, + exp: []Interval16{{Start: 5, Last: 10}}, }, { - aruns: []interval16{{start: 0, last: 4}}, - bruns: []interval16{{start: 6, last: 10}}, - exp: []interval16{{start: 0, last: 4}, {start: 6, last: 10}}, + aruns: []Interval16{{Start: 0, Last: 4}}, + bruns: []Interval16{{Start: 6, Last: 10}}, + exp: []Interval16{{Start: 0, Last: 4}, {Start: 6, Last: 10}}, }, { - aruns: []interval16{{start: 0, last: 6}}, - bruns: []interval16{{start: 4, last: 10}}, - exp: []interval16{{start: 0, last: 3}, {start: 7, last: 10}}, + aruns: []Interval16{{Start: 0, Last: 6}}, + bruns: []Interval16{{Start: 4, Last: 10}}, + exp: []Interval16{{Start: 0, Last: 3}, {Start: 7, Last: 10}}, }, { - aruns: []interval16{{start: 4, last: 10}}, - bruns: []interval16{{start: 0, last: 6}}, - exp: []interval16{{start: 0, last: 3}, {start: 7, last: 10}}, + aruns: []Interval16{{Start: 4, Last: 10}}, + bruns: []Interval16{{Start: 0, Last: 6}}, + exp: []Interval16{{Start: 0, Last: 3}, {Start: 7, Last: 10}}, }, { - aruns: []interval16{{start: 0, last: 10}}, - bruns: []interval16{{start: 0, last: 6}}, - exp: []interval16{{start: 7, last: 10}}, + aruns: []Interval16{{Start: 0, Last: 10}}, + bruns: []Interval16{{Start: 0, Last: 6}}, + exp: []Interval16{{Start: 7, Last: 10}}, }, { - aruns: []interval16{{start: 0, last: 6}}, - bruns: []interval16{{start: 0, last: 10}}, - exp: []interval16{{start: 7, last: 10}}, + aruns: []Interval16{{Start: 0, Last: 6}}, + bruns: []Interval16{{Start: 0, Last: 10}}, + exp: []Interval16{{Start: 7, Last: 10}}, }, { - aruns: []interval16{{start: 0, last: 6}}, - bruns: []interval16{{start: 0, last: 10}}, - exp: []interval16{{start: 7, last: 10}}, + aruns: []Interval16{{Start: 0, Last: 6}}, + bruns: []Interval16{{Start: 0, Last: 10}}, + exp: []Interval16{{Start: 7, Last: 10}}, }, { - aruns: []interval16{{start: 5, last: 12}}, - bruns: []interval16{{start: 5, last: 10}}, - exp: []interval16{{start: 11, last: 12}}, + aruns: []Interval16{{Start: 5, Last: 12}}, + bruns: []Interval16{{Start: 5, Last: 10}}, + exp: []Interval16{{Start: 11, Last: 12}}, }, { - aruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 12}}, - bruns: []interval16{{start: 5, last: 10}}, - exp: []interval16{{start: 1, last: 3}, {start: 6, last: 6}, {start: 11, last: 12}}, + aruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 12}}, + bruns: []Interval16{{Start: 5, Last: 10}}, + exp: []Interval16{{Start: 1, Last: 3}, {Start: 6, Last: 6}, {Start: 11, Last: 12}}, }, { - aruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 12}}, - bruns: []interval16{{start: 2, last: 65535}}, - exp: []interval16{{start: 1, last: 1}, {start: 4, last: 4}, {start: 6, last: 6}, {start: 13, last: 65535}}, + aruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 12}}, + bruns: []Interval16{{Start: 2, Last: 65535}}, + exp: []Interval16{{Start: 1, Last: 1}, {Start: 4, Last: 4}, {Start: 6, Last: 6}, {Start: 13, Last: 65535}}, }, { - aruns: []interval16{{start: 2, last: 65535}}, - bruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 12}}, - exp: []interval16{{start: 1, last: 1}, {start: 4, last: 4}, {start: 6, last: 6}, {start: 13, last: 65535}}, + aruns: []Interval16{{Start: 2, Last: 65535}}, + bruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 12}}, + exp: []Interval16{{Start: 1, Last: 1}, {Start: 4, Last: 4}, {Start: 6, Last: 6}, {Start: 13, Last: 65535}}, }, { - aruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 12}}, - bruns: []interval16{{start: 0, last: 65535}}, - exp: []interval16{{start: 0, last: 0}, {start: 4, last: 4}, {start: 6, last: 6}, {start: 13, last: 65535}}, + aruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 12}}, + bruns: []Interval16{{Start: 0, Last: 65535}}, + exp: []Interval16{{Start: 0, Last: 0}, {Start: 4, Last: 4}, {Start: 6, Last: 6}, {Start: 13, Last: 65535}}, }, { - aruns: []interval16{{start: 0, last: 65535}}, - bruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 12}}, - exp: []interval16{{start: 0, last: 0}, {start: 4, last: 4}, {start: 6, last: 6}, {start: 13, last: 65535}}, + aruns: []Interval16{{Start: 0, Last: 65535}}, + bruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 12}}, + exp: []Interval16{{Start: 0, Last: 0}, {Start: 4, Last: 4}, {Start: 6, Last: 6}, {Start: 13, Last: 65535}}, }, { - aruns: []interval16{{start: 1, last: 3}, {start: 5, last: 5}, {start: 7, last: 9}, {start: 12, last: 22}}, - bruns: []interval16{{start: 2, last: 8}, {start: 16, last: 27}, {start: 33, last: 34}}, - exp: []interval16{{start: 1, last: 1}, {start: 4, last: 4}, {start: 6, last: 6}, {start: 9, last: 9}, {start: 12, last: 15}, {start: 23, last: 27}, {start: 33, last: 34}}, + aruns: []Interval16{{Start: 1, Last: 3}, {Start: 5, Last: 5}, {Start: 7, Last: 9}, {Start: 12, Last: 22}}, + bruns: []Interval16{{Start: 2, Last: 8}, {Start: 16, Last: 27}, {Start: 33, Last: 34}}, + exp: []Interval16{{Start: 1, Last: 1}, {Start: 4, Last: 4}, {Start: 6, Last: 6}, {Start: 9, Last: 9}, {Start: 12, Last: 15}, {Start: 23, Last: 27}, {Start: 33, Last: 34}}, }, { - aruns: []interval16{{start: 65530, last: 65535}}, - bruns: []interval16{{start: 65532, last: 65535}}, - exp: []interval16{{start: 65530, last: 65531}}, + aruns: []Interval16{{Start: 65530, Last: 65535}}, + bruns: []Interval16{{Start: 65532, Last: 65535}}, + exp: []Interval16{{Start: 65530, Last: 65531}}, }, } for i, test := range tests { @@ -2006,12 +2187,12 @@ func TestBitmapXorRange(t *testing.T) { func TestXorBitmapRun(t *testing.T) { tests := []struct { bitmap []uint64 - runs []interval16 + runs []Interval16 exp []uint64 }{ { bitmap: []uint64{0x0, 0x0, 0x0}, - runs: []interval16{{start: 129, last: 131}}, + runs: []Interval16{{Start: 129, Last: 131}}, exp: []uint64{0x0, 0x0, 0x00000000000000E}, }, } @@ -2341,7 +2522,7 @@ func TestIteratorVarious(t *testing.T) { func TestRunBinSearchContains(t *testing.T) { tests := []struct { - runs []interval16 + runs []Interval16 index uint16 exp struct { index int32 @@ -2349,7 +2530,7 @@ func TestRunBinSearchContains(t *testing.T) { } }{ { - runs: []interval16{{start: 0, last: 10}}, + runs: []Interval16{{Start: 0, Last: 10}}, index: uint16(3), exp: struct { index int32 @@ -2357,7 +2538,7 @@ func TestRunBinSearchContains(t *testing.T) { }{index: 0, found: true}, }, { - runs: []interval16{{start: 0, last: 10}}, + runs: []Interval16{{Start: 0, Last: 10}}, index: uint16(13), exp: struct { index int32 @@ -2365,7 +2546,7 @@ func TestRunBinSearchContains(t *testing.T) { }{index: 0, found: false}, }, { - runs: []interval16{{start: 0, last: 10}, {start: 20, last: 30}}, + runs: []Interval16{{Start: 0, Last: 10}, {Start: 20, Last: 30}}, index: uint16(13), exp: struct { index int32 @@ -2373,7 +2554,7 @@ func TestRunBinSearchContains(t *testing.T) { }{index: 0, found: false}, }, { - runs: []interval16{{start: 0, last: 10}, {start: 20, last: 30}}, + runs: []Interval16{{Start: 0, Last: 10}, {Start: 20, Last: 30}}, index: uint16(36), exp: struct { index int32 @@ -2394,55 +2575,55 @@ func TestRunBinSearchContains(t *testing.T) { func TestRunBinSearch(t *testing.T) { tests := []struct { - runs []interval16 + runs []Interval16 search uint16 exp bool expi int32 }{ { - runs: []interval16{{2, 10}, {50, 60}, {80, 90}}, + runs: []Interval16{{2, 10}, {50, 60}, {80, 90}}, search: 1, exp: false, expi: 0, }, { - runs: []interval16{{2, 10}, {50, 60}, {80, 90}}, + runs: []Interval16{{2, 10}, {50, 60}, {80, 90}}, search: 2, exp: true, expi: 0, }, { - runs: []interval16{{2, 10}, {50, 60}, {80, 90}}, + runs: []Interval16{{2, 10}, {50, 60}, {80, 90}}, search: 5, exp: true, expi: 0, }, { - runs: []interval16{{2, 10}, {50, 60}, {80, 90}}, + runs: []Interval16{{2, 10}, {50, 60}, {80, 90}}, search: 10, exp: true, expi: 0, }, { - runs: []interval16{{2, 10}, {50, 60}, {80, 90}}, + runs: []Interval16{{2, 10}, {50, 60}, {80, 90}}, search: 20, exp: false, expi: 1, }, { - runs: []interval16{{2, 10}, {50, 60}, {80, 90}}, + runs: []Interval16{{2, 10}, {50, 60}, {80, 90}}, search: 55, exp: true, expi: 1, }, { - runs: []interval16{{2, 10}, {50, 60}, {80, 90}}, + runs: []Interval16{{2, 10}, {50, 60}, {80, 90}}, search: 70, exp: false, expi: 2, }, { - runs: []interval16{{2, 10}, {50, 60}, {80, 90}}, + runs: []Interval16{{2, 10}, {50, 60}, {80, 90}}, search: 100, exp: false, expi: 3, @@ -3569,15 +3750,17 @@ func TestContainerCombinations(t *testing.T) { for _, x := range containerTypes { for _, y := range containerTypes { desc := fmt.Sprintf("%s(%s/%s, %s/%s)", getFunctionName(testOp.f), containerTypeNames[x], testOp.x, containerTypeNames[y], testOp.y) - ret := runContainerFunc(testOp.f, cts[x][testOp.x], cts[y][testOp.y]) - exp := testOp.exp + t.Run(desc, func(t *testing.T) { + ret := runContainerFunc(testOp.f, cts[x][testOp.x], cts[y][testOp.y]) + exp := testOp.exp - // Convert to all container types and check result. - for _, ct := range containerTypes { - if err := ret.BitwiseCompare(cts[ct][exp]); err != nil { - t.Errorf("test %s: %v", desc, err) + // Convert to all container types and check result. + for _, ct := range containerTypes { + if err := ret.BitwiseCompare(cts[ct][exp]); err != nil { + t.Error(err) + } } - } + }) } } } @@ -3789,31 +3972,31 @@ func TestShiftBitmap(t *testing.T) { } func TestShiftRun(t *testing.T) { tests := []struct { - runs []interval16 + runs []Interval16 n int32 en int32 - exp []interval16 + exp []Interval16 carry bool }{ { - runs: []interval16{{start: 5, last: 10}}, + runs: []Interval16{{Start: 5, Last: 10}}, n: 5, en: 5, - exp: []interval16{{start: 6, last: 11}}, + exp: []Interval16{{Start: 6, Last: 11}}, carry: false, }, { - runs: []interval16{{start: 5, last: 65535}}, + runs: []Interval16{{Start: 5, Last: 65535}}, n: 65530, en: 65529, - exp: []interval16{{start: 6, last: 65535}}, + exp: []Interval16{{Start: 6, Last: 65535}}, carry: true, }, { - runs: []interval16{{start: 65535, last: 65535}}, + runs: []Interval16{{Start: 65535, Last: 65535}}, n: 1, en: 0, - exp: []interval16{}, + exp: []Interval16{}, carry: true, }, } @@ -4147,3 +4330,77 @@ func TestDifferenceInPlace_N(t *testing.T) { t.Error("expected difference of containers to have n=0") } } + +func BenchmarkUnionRunRunInPlace(bm *testing.B) { + bm.Skip("Skipping long running BenchmarkUnionRunRunInPlace") + + runs := []struct { + name string + fn func() []Interval16 + }{ + {"FirstBitSet", runFirstBitSet}, + {"LastBitSet", runLastBitSet}, + {"FirstBitUnset", runFirstBitUnset}, + {"LastBitUnset", runLastBitUnset}, + {"InnerBitsSet", runInnerBitsSet}, + {"OuterBitsSet", runOuterBitsSet}, + {"OddBitsSet", runOddBitsSet}, + {"EvenBitsSet", runEvenBitsSet}, + } + + for _, ar := range runs { + for _, br := range runs { + bm.Run("RunToBitmapRun-"+ar.name+"_"+br.name, func(bm *testing.B) { + for i := 0; i < bm.N; i++ { + arun := doContainer(containerRun, ar.fn()) + brun := doContainer(containerRun, br.fn()) + + abmp := arun.runToBitmap() + unionBitmapRunInPlace(abmp, brun) + } + }) + + bm.Run("RunRun-"+ar.name+"_"+br.name, func(bm *testing.B) { + for i := 0; i < bm.N; i++ { + arun := doContainer(containerRun, ar.fn()) + brun := doContainer(containerRun, br.fn()) + + unionRunRunInPlace(arun, brun) + } + }) + } + } +} + +func TestUnionRunRunInPlaceBitwiseCompare(t *testing.T) { + runs := []struct { + name string + run []Interval16 + }{ + {name: "FirstBitSet", run: runFirstBitSet()}, + {name: "LastBitSet", run: runLastBitSet()}, + {name: "FirstBitUnset", run: runFirstBitUnset()}, + {name: "LastBitUnset", run: runLastBitUnset()}, + {name: "InnerBitsSet", run: runInnerBitsSet()}, + {name: "OuterBitsSet", run: runOuterBitsSet()}, + {name: "OddBitsSet", run: runOddBitsSet()}, + {name: "EvenBitsSet", run: runEvenBitsSet()}, + } + + for _, a := range runs { + for _, b := range runs { + t.Run(a.name+"-"+b.name, func(t *testing.T) { + arun := doContainer(containerRun, a.run) + brun := doContainer(containerRun, b.run) + + out1 := unionBitmapRunInPlace(arun.runToBitmap(), brun) + out2 := unionRunRunInPlace(arun, brun) + + err := out1.BitwiseCompare(out2.runToBitmap()) + if err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/roaring/roaring_test.go b/roaring/roaring_test.go index 55395ea73..8a0d3ead4 100644 --- a/roaring/roaring_test.go +++ b/roaring/roaring_test.go @@ -315,8 +315,9 @@ func TestBitmap_SliceRange(t *testing.T) { // Ensure a bitmap can loop over a set of values. func TestBitmap_ForEach(t *testing.T) { var a []uint64 - roaring.NewFileBitmap(1, 2, 3).ForEach(func(v uint64) { + _ = roaring.NewFileBitmap(1, 2, 3).ForEach(func(v uint64) error { a = append(a, v) + return nil }) if !reflect.DeepEqual(a, []uint64{1, 2, 3}) { t.Fatalf("unexpected values: %+v", a) @@ -326,8 +327,9 @@ func TestBitmap_ForEach(t *testing.T) { // Ensure a bitmap can loop over a set of values in a range. func TestBitmap_ForEachRange(t *testing.T) { var a []uint64 - roaring.NewFileBitmap(1, 2, 3, 4).ForEachRange(2, 4, func(v uint64) { + _ = roaring.NewFileBitmap(1, 2, 3, 4).ForEachRange(2, 4, func(v uint64) error { a = append(a, v) + return nil }) if !reflect.DeepEqual(a, []uint64{2, 3}) { t.Fatalf("unexpected values: %+v", a) @@ -1733,7 +1735,7 @@ type benchmarkSampleData struct { var sampleData benchmarkSampleData func isAllType(b *roaring.Bitmap, typ string) bool { - bi := b.Info() + bi := b.Info(true) for _, c := range bi.Containers { if c.Type != typ { return false diff --git a/roaring/unmarshal_binary.go b/roaring/unmarshal_binary.go index c9071b1ca..53aff37ee 100644 --- a/roaring/unmarshal_binary.go +++ b/roaring/unmarshal_binary.go @@ -1,4 +1,4 @@ -// Copyright 2017 Pilosa Corp. +// Copyright 2019 Pilosa Corp. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,232 +15,238 @@ package roaring import ( - "encoding/binary" - "fmt" + "errors" + "io" "unsafe" - - "github.com/pkg/errors" ) -// UnmarshalBinary decodes b from a binary-encoded byte slice. data can be in -// either official roaring format or Pilosa's roaring format. -func (b *Bitmap) UnmarshalBinary(data []byte) error { +// UnmarshalBinary reads Pilosa's format, or upstream roaring (mostly; +// it may not handle some edge cases), and decodes them into the given +// bitmap, replacing the existing contents. +func (b *Bitmap) UnmarshalBinary(data []byte) (err error) { if data == nil { - // Nothing to unmarshal - return nil - } - statsHit("Bitmap/UnmarshalBinary") - // reset ops/opN since we're reading new data. - b.ops = 0 - b.opN = 0 - fileMagic := uint32(binary.LittleEndian.Uint16(data[0:2])) - if fileMagic == MagicNumber { // if pilosa roaring - return errors.Wrap(b.unmarshalPilosaRoaring(data), "unmarshaling as pilosa roaring") + return errors.New("no roaring bitmap provided") } + var itr roaringIterator + var itrKey uint64 + var itrCType byte + var itrN int + var itrLen int + var itrPointer *uint16 + var itrErr error - keyN, containerTyper, header, pos, haveRuns, err := readOfficialHeader(data) + itr, err = newRoaringIterator(data) if err != nil { - return errors.Wrap(err, "reading roaring header") + return err } - // Only the Pilosa roaring format has flags. The official Roaring format - // hasn't got space in its header for flags. - b.Flags = 0 - - b.Containers.ResetN(int(keyN)) - // Descriptive header section: Read container keys and cardinalities. - for i, buf := uint(0), data[header:]; i < uint(keyN); i, buf = i+1, buf[4:] { - card := int(binary.LittleEndian.Uint16(buf[2:4])) + 1 - b.Containers.PutContainerValues( - uint64(binary.LittleEndian.Uint16(buf[0:2])), - containerTyper(i, card), /// container type voodo with isRunBitmap - card, - true) + if itr == nil { + return errors.New("failed to create roaring iterator, but don't know why") } - // Read container offsets and attach data. - if haveRuns { - err := readWithRuns(b, data, pos, keyN) - if err != nil { - return errors.Wrap(err, "reading offsets from official roaring format") - } - } else { - err := readOffsets(b, data, pos, keyN) - if err != nil { - return errors.Wrap(err, "reading official roaring format") - } - } - return nil -} + b.Containers.Reset() -func readOffsets(b *Bitmap, data []byte, pos int, keyN uint32) error { - - citer, _ := b.Containers.Iterator(0) - for i, buf := 0, data[pos:]; i < int(keyN); i, buf = i+1, buf[4:] { - // Verify the offset is fully formed - if len(buf) < 4 { - return fmt.Errorf("insufficient data for offsets: len=%d", len(buf)) - } - offset := binary.LittleEndian.Uint32(buf[0:4]) - // Verify the offset is within the bounds of the input data. - if int(offset) >= len(data) { - return fmt.Errorf("offset out of bounds: off=%d, len=%d", offset, len(data)) - } - - // Map byte slice directly to the container data. - citer.Next() - k, c := citer.Value() - if !c.Mapped() { - fmt.Printf("inexplicable: container %d (%d/%d) doesn't think it's mapped. fixing that.\n", - k, i, keyN) - c.setMapped(true) - } - switch c.typ() { + itrKey, itrCType, itrN, itrLen, itrPointer, itrErr = itr.Next() + for itrErr == nil { + var newC *Container + switch itrCType { case containerArray: - c.setArray((*[0xFFFFFFF]uint16)(unsafe.Pointer(&data[offset]))[:c.N():c.N()]) + newC = NewContainerArray((*[4096]uint16)(unsafe.Pointer(itrPointer))[:itrLen:itrLen]) + case containerRun: + newC = NewContainerRunN((*[2048]Interval16)(unsafe.Pointer(itrPointer))[:itrLen:itrLen], int32(itrN)) case containerBitmap: - c.setBitmap((*[0xFFFFFFF]uint64)(unsafe.Pointer(&data[offset]))[:bitmapN:bitmapN]) + newC = NewContainerBitmapN((*[1024]uint64)(unsafe.Pointer(itrPointer))[:1024:itrLen], int32(itrN)) default: - return fmt.Errorf("unsupported container type %d", c.typ()) + panic("invalid container type") } - } - return nil -} - -func readWithRuns(b *Bitmap, data []byte, pos int, keyN uint32) error { - if len(data) < pos+runCountHeaderSize { - return fmt.Errorf("insufficient data for offsets(run): len=%d", len(data)) - } - citer, _ := b.Containers.Iterator(0) - for i := 0; i < int(keyN); i++ { - citer.Next() - k, c := citer.Value() - if !c.Mapped() { - fmt.Printf("inexplicable: container %d (%d/%d) doesn't think it's mapped. fixing that.\n", - k, i, keyN) - c.setMapped(true) - } - switch c.typ() { - case containerRun: - runCount := binary.LittleEndian.Uint16(data[pos : pos+runCountHeaderSize]) - c.setRuns((*[0xFFFFFFF]interval16)(unsafe.Pointer(&data[pos+runCountHeaderSize]))[:runCount:runCount]) - runs := c.runs() - - for o := range runs { // must convert from start:length to start:end :( - runs[o].last = runs[o].start + runs[o].last - } - pos += int((runCount * interval16Size) + runCountHeaderSize) - case containerArray: - c.setArray((*[0xFFFFFFF]uint16)(unsafe.Pointer(&data[pos]))[:c.N():c.N()]) - pos += int(c.N() * 2) - case containerBitmap: - c.setBitmap((*[0xFFFFFFF]uint64)(unsafe.Pointer(&data[pos]))[:bitmapN:bitmapN]) - pos += bitmapN * 8 + newC.setMapped(true) + if !b.preferMapping { + newC.unmapOrClone() } + b.Containers.Put(itrKey, newC) + itrKey, itrCType, itrN, itrLen, itrPointer, itrErr = itr.Next() } - return nil -} - -func (b *Bitmap) unmarshalPilosaRoaring(data []byte) error { - if len(data) < headerBaseSize { - return errors.New("data too small") - } - - // Verify the first two bytes are a valid MagicNumber, and second two bytes match current storageVersion. - fileMagic := uint32(binary.LittleEndian.Uint16(data[0:2])) - fileVersion := uint32(data[2]) - b.Flags = data[3] - if fileMagic != MagicNumber { - return fmt.Errorf("invalid roaring file, magic number %v is incorrect", fileMagic) - } - - if fileVersion != storageVersion { - return fmt.Errorf("wrong roaring version, file is v%d, server requires v%d", fileVersion, storageVersion) - } - - // Read key count in bytes sizeof(cookie)+sizeof(flag):(sizeof(cookie)+sizeof(uint32)). - keyN := binary.LittleEndian.Uint32(data[3+1 : 8]) - if int64(len(data)) < headerBaseSize+int64(keyN)*12 { - return fmt.Errorf("insufficient data for header + offsets: key-cardinality not provided for %d containers", keyN) - } - - headerSize := headerBaseSize - b.Containers.ResetN(int(keyN)) - // Descriptive header section: Read container keys and cardinalities. - for i, buf := 0, data[headerSize:]; i < int(keyN); i, buf = i+1, buf[12:] { - b.Containers.PutContainerValues( - binary.LittleEndian.Uint64(buf[0:8]), - byte(binary.LittleEndian.Uint16(buf[8:10])), - int(binary.LittleEndian.Uint16(buf[10:12]))+1, - true) - } - opsOffset := int64(headerSize) + int64(keyN)*12 - - // Read container offsets and attach data. - citer, _ := b.Containers.Iterator(0) - // if you have enough containers that the *headers alone* exceed 4GB, we - // need to start with a higher cycle offset. - cycleOffset := opsOffset &^ ((1 << 32) - 1) - prevOffset32 := uint32(opsOffset) - for i, buf := 0, data[opsOffset:]; i < int(keyN); i, buf = i+1, buf[4:] { - offset32 := binary.LittleEndian.Uint32(buf[0:4]) - if offset32 < prevOffset32 { - cycleOffset += (1 << 32) - } - prevOffset32 = offset32 - offset := int64(offset32) + cycleOffset - // Verify the offset is within the bounds of the input data. - if offset >= int64(len(data)) { - return fmt.Errorf("offset out of bounds: off=%d, len=%d", offset, len(data)) - } - - // Map byte slice directly to the container data. - citer.Next() - k, c := citer.Value() - - // this shouldn't happen, since we don't normally store nils. - if c == nil { - continue - } - if !c.Mapped() { - fmt.Printf("inexplicable: container %d (%d/%d) doesn't think it's mapped. fixing that.\n", - k, i, keyN) - c.setMapped(true) - } - switch c.typ() { - case containerRun: - runCount := binary.LittleEndian.Uint16(data[offset : offset+runCountHeaderSize]) - c.setRuns((*[0xFFFFFFF]interval16)(unsafe.Pointer(&data[offset+runCountHeaderSize]))[:runCount:runCount]) - opsOffset = offset + runCountHeaderSize + int64(len(c.runs()))*interval16Size - case containerArray: - c.setArray((*[0xFFFFFFF]uint16)(unsafe.Pointer(&data[offset]))[:c.N():c.N()]) - opsOffset = offset + int64(len(c.array()))*2 // sizeof(uint32) - case containerBitmap: - c.setBitmap((*[0xFFFFFFF]uint64)(unsafe.Pointer(&data[offset]))[:bitmapN:bitmapN]) - opsOffset = offset + int64(len(c.bitmap()))*8 // sizeof(uint64) - } + // note: if we get a non-EOF err, it's possible that we made SOME + // changes but didn't log them. I don't have a good solution to this. + if itrErr != io.EOF { + return itrErr } // Read ops log until the end of the file. - buf := data[opsOffset:] - + b.ops = 0 + b.opN = 0 + buf, lastValidOffset := itr.Remaining() for { // Exit when there are no more ops to parse. if len(buf) == 0 { break } + // Unmarshal the op and apply it. var opr op if err := opr.UnmarshalBinary(buf); err != nil { - return newFileShouldBeTruncatedError(err, int64(opsOffset)) + return newFileShouldBeTruncatedError(err, int64(lastValidOffset)) } + opr.apply(b) + // Increase the op count. b.ops++ b.opN += opr.count() - opsOffset += int64(opr.size()) - // Move the buffer forward. - buf = data[opsOffset:] - } + // Move the buffer forward. + opSize := opr.size() + buf = buf[opSize:] + lastValidOffset += int64(opSize) + } return nil } + +// InspectBinary reads a roaring bitmap, plus a possible ops log, +// and reports back on the contents, including distinguishing between +// the original ops log and the post-ops-log contents. +func InspectBinary(data []byte, mapped bool, info *BitmapInfo) (b *Bitmap, mappedAny bool, err error) { + b = NewFileBitmap() + b.PreferMapping(mapped) + if data == nil { + return b, mappedAny, errors.New("no roaring bitmap provided") + } + var itr roaringIterator + var itrKey uint64 + var itrCType byte + var itrN int + var itrLen int + var itrPointer *uint16 + var itrErr error + + itr, err = newRoaringIterator(data) + if err != nil { + return b, mappedAny, err + } + if itr == nil { + return b, mappedAny, errors.New("failed to create roaring iterator, but don't know why") + } + keys := itr.Len() + info.Containers = make([]ContainerInfo, 0, keys) + + itrKey, itrCType, itrN, itrLen, itrPointer, itrErr = itr.Next() + for itrErr == nil { + var size int + switch itrCType { + case containerArray: + size = int(itrN) * 2 + case containerBitmap: + size = 8192 + case containerRun: + size = itrLen*interval16Size + runCountHeaderSize + } + var newC *Container + switch itrCType { + case containerArray: + newC = NewContainerArray((*[4096]uint16)(unsafe.Pointer(itrPointer))[:itrLen:itrLen]) + case containerRun: + newC = NewContainerRunN((*[2048]Interval16)(unsafe.Pointer(itrPointer))[:itrLen:itrLen], int32(itrN)) + case containerBitmap: + newC = NewContainerBitmapN((*[1024]uint64)(unsafe.Pointer(itrPointer))[:1024:itrLen], int32(itrN)) + default: + panic("invalid container type") + } + newC.setMapped(true) + if !mapped { + newC.unmapOrClone() + } + newC.flags |= flagPristine + if newC.flags&flagMapped != 0 { + mappedAny = true + } + info.Containers = append(info.Containers, ContainerInfo{ + N: newC.n, + Mapped: newC.flags&flagMapped != 0, + Type: containerTypeNames[itrCType], + Alloc: size, + Pointer: uintptr(unsafe.Pointer(newC.pointer)), + Key: itrKey, + Flags: newC.flags.String(), + }) + info.ContainerCount++ + info.BitCount += uint64(newC.n) + itrKey, itrCType, itrN, itrLen, itrPointer, itrErr = itr.Next() + } + // note: if we get a non-EOF err, it's possible that we made SOME + // changes but didn't log them. I don't have a good solution to this. + if itrErr != io.EOF { + return b, mappedAny, itrErr + } + // stash pointer ranges + info.From = uintptr(unsafe.Pointer(&data[0])) + info.To = info.From + uintptr(len(data)) + + // Read ops log until the end of the file. + b.ops = 0 + b.opN = 0 + buf, lastValidOffset := itr.Remaining() + // if there's no ops log, we're done and can just return the + // info so far. + if len(buf) == 0 { + return b, mappedAny, err + } + for { + // Exit when there are no more ops to parse. + if len(buf) == 0 { + break + } + + // Unmarshal the op and apply it. + var opr op + if err = opr.UnmarshalBinary(buf); err != nil { + // we break out here, but we continue on to + // return the bitmap as-is, along with data about + // it, and the error. this lets us share the + // "is anything mapped" check with that code. + break + } + opr.apply(b) + + // Increase the op count. + if info != nil { + info.Ops++ + info.OpN += opr.count() + info.OpDetails = append(info.OpDetails, opr.info()) + } + // Move the buffer forward. + opSize := opr.size() + buf = buf[opSize:] + lastValidOffset += int64(opSize) + } + citer, _ := b.Containers.Iterator(0) + // it's possible the ops log unmapped every mapped container, so we recheck. + mappedAny = false + if info == nil { + for citer.Next() { + _, c := citer.Value() + if c.Mapped() { + mappedAny = true + break + } + } + return b, mappedAny, err + } + // now we want to compute the actual container and bit counts after + // ops, and create a report of just the containers which got changed. + info.ContainerCount = 0 + info.BitCount = 0 + for citer.Next() { + k, c := citer.Value() + if c.Mapped() { + mappedAny = true + } + info.ContainerCount++ + info.BitCount += uint64(c.N()) + if c.flags&flagPristine != 0 { + continue + } + ci := c.info() + ci.Key = k + info.OpContainers = append(info.OpContainers, ci) + } + return b, mappedAny, err +} diff --git a/row.go b/row.go index eea6871f0..d76dcc73c 100644 --- a/row.go +++ b/row.go @@ -387,6 +387,23 @@ func (r *Row) GenericUnaryOp(op ext.GenericBitmapOpBitmap, args map[string]inter // Shift returns the bitwise shift of r by n bits. // Currently only positive shift values are supported. +// +// NOTE: the Shift method is currently unsupported, and +// is considerred to be incorrect. Please DO NOT use it. +// We are leaving it here in case someone internally wants +// to use it with the understanding that the results may +// be incorrect. +// +// Why unsupported? For a full description, see: +// https://github.com/molecula/pilosa/issues/403. +// In short, the current implementation will shift a bit +// at the edge of a shard out of the shard and into a +// container which is assumed to be an invalid container +// for the shard. So for example, shifting the last bit +// of shard 0 (containers 0-15) will shift that bit out +// to container 16. While this "sort of" works, it +// breaks an assumption about containers, and might stop +// working in the future if that assumption is enforced. func (r *Row) Shift(n int64) (*Row, error) { if n < 0 { return nil, errors.New("cannot shift by negative values") diff --git a/server.go b/server.go index 131a6971c..0afd2fa43 100644 --- a/server.go +++ b/server.go @@ -66,9 +66,10 @@ type Server struct { // nolint: maligned extensions []*ext.ExtensionInfo // External - systemInfo SystemInfo - gcNotifier GCNotifier - logger logger.Logger + systemInfo SystemInfo + gcNotifier GCNotifier + logger logger.Logger + snapshotQueue SnapshotQueue nodeID string uri URI @@ -533,6 +534,9 @@ func (s *Server) UpAndDown() error { func (s *Server) Open() error { s.logger.Printf("open server") + // Start background monitoring. + s.snapshotQueue = newSnapshotQueue(10, 2, s.logger) + // Log startup err := s.holder.logStartup() if err != nil { @@ -560,6 +564,9 @@ func (s *Server) Open() error { if err := s.holder.Open(); err != nil { return errors.Wrap(err, "opening Holder") } + // bring up the background tasks for the holder. + s.holder.SnapshotQueue = s.snapshotQueue + s.holder.Activate() if err := s.cluster.setNodeState(nodeStateReady); err != nil { return errors.Wrap(err, "setting nodeState") } @@ -571,7 +578,6 @@ func (s *Server) Open() error { // buffered channel. s.cluster.listenForJoins() - // Start background monitoring. s.wg.Add(3) go func() { defer s.wg.Done(); s.monitorAntiEntropy() }() go func() { defer s.wg.Done(); s.monitorRuntime() }() @@ -596,6 +602,11 @@ func (s *Server) Close() error { if s.holder != nil { errh = s.holder.Close() } + if s.snapshotQueue != nil { + s.holder.SnapshotQueue = nil + s.snapshotQueue.Stop() + s.snapshotQueue = nil + } // prefer to return holder error over cluster // error. This order is somewhat arbitrary. It would be better if we had // some way to combine all the errors, but probably not important enough to diff --git a/server/config.go b/server/config.go index 2e59ed314..6d0181756 100644 --- a/server/config.go +++ b/server/config.go @@ -29,6 +29,11 @@ import ( "github.com/pkg/errors" ) +const ( + defaultBindPort = "10101" + defaultBindGRPCPort = "20101" +) + // TLSConfig contains TLS configuration type TLSConfig struct { // CertificatePath contains the path to the certificate (.crt or .pem file) @@ -60,6 +65,11 @@ type Config struct { // route to an interface that Bind is listening on. Advertise string `toml:"advertise"` + // AdvertiseGRPC is the address advertised by the server to other nodes + // in the cluster. It should be reachable by all other nodes and should + // route to an interface that BindGRPC is listening on. + AdvertiseGRPC string `toml:"advertise-grpc"` + // MaxWritesPerRequest limits the number of mutating commands that can be in // a single request to the server. This includes Set, Clear, // SetRowAttrs & SetColumnAttrs. @@ -162,8 +172,8 @@ type Config struct { func NewConfig() *Config { c := &Config{ DataDir: "~/.pilosa", - Bind: ":10101", - BindGRPC: ":20101", + Bind: ":" + defaultBindPort, + BindGRPC: ":" + defaultBindGRPCPort, MaxWritesPerRequest: 5000, // We default these Max File/Map counts very high. This is basically a @@ -223,25 +233,32 @@ func NewConfig() *Config { // indicate it's left unspecified. func (cfg *Config) validateAddrs(ctx context.Context) error { // Validate the advertise address. - advScheme, advHost, advPort, err := validateAdvertiseAddr(ctx, cfg.Advertise, cfg.Bind) + advScheme, advHost, advPort, err := validateAdvertiseAddr(ctx, cfg.Advertise, cfg.Bind, defaultBindPort) if err != nil { return errors.Wrapf(err, "validating advertise address") } cfg.Advertise = schemeHostPortString(advScheme, advHost, advPort) // Validate the listen address. - listenScheme, listenHost, listenPort, err := validateListenAddr(ctx, cfg.Bind) + listenScheme, listenHost, listenPort, err := validateListenAddr(ctx, cfg.Bind, defaultBindPort) if err != nil { return errors.Wrap(err, "validating listen address") } cfg.Bind = schemeHostPortString(listenScheme, listenHost, listenPort) + // Validate the gRPC advertise address. + _, grpcAdvHost, grpcAdvPort, err := validateAdvertiseAddr(ctx, cfg.AdvertiseGRPC, cfg.BindGRPC, defaultBindGRPCPort) + if err != nil { + return errors.Wrapf(err, "validating grpc advertise address") + } + cfg.AdvertiseGRPC = schemeHostPortString("grpc", grpcAdvHost, grpcAdvPort) + // Validate the gRPC listen address. - grpcListenScheme, grpcListenHost, grpcListenPort, err := validateListenAddr(ctx, cfg.BindGRPC) + _, grpcListenHost, grpcListenPort, err := validateListenAddr(ctx, cfg.BindGRPC, defaultBindGRPCPort) if err != nil { return errors.Wrap(err, "validating grpc listen address") } - cfg.BindGRPC = schemeHostPortString(grpcListenScheme, grpcListenHost, grpcListenPort) + cfg.BindGRPC = schemeHostPortString("grpc", grpcListenHost, grpcListenPort) return nil } @@ -251,8 +268,8 @@ func (cfg *Config) validateAddrs(ctx context.Context) error { // the configured listen address if any, otherwise it makes a best // guess at the outbound IP address. // Returns scheme, host, port as strings. -func validateAdvertiseAddr(ctx context.Context, advAddr, listenAddr string) (string, string, string, error) { - listenScheme, listenHost, listenPort, err := splitAddr(listenAddr) +func validateAdvertiseAddr(ctx context.Context, advAddr, listenAddr, defaultPort string) (string, string, string, error) { + listenScheme, listenHost, listenPort, err := splitAddr(listenAddr, defaultPort) if err != nil { return "", "", "", errors.Wrap(err, "getting listen address") } @@ -318,8 +335,8 @@ func outboundIP() net.IP { // the default (localhost) should be used. Rresolves host names to IP // addresses. // Returns scheme, host, port as strings. -func validateListenAddr(ctx context.Context, addr string) (string, string, string, error) { - scheme, host, port, err := splitAddr(addr) +func validateListenAddr(ctx context.Context, addr, defaultPort string) (string, string, string, error) { + scheme, host, port, err := splitAddr(addr, defaultPort) if err != nil { return "", "", "", errors.Wrap(err, "getting listen address") } @@ -348,7 +365,7 @@ func schemeHostPortString(scheme, host, port string) string { } // splitAddr returns scheme, host, port as strings. -func splitAddr(addr string) (string, string, string, error) { +func splitAddr(addr string, defaultPort string) (string, string, string, error) { scheme, hostPort := splitScheme(addr) host, port := "", "" if hostPort != "" { @@ -362,7 +379,7 @@ func splitAddr(addr string) (string, string, string, error) { // results in a port of 0, which causes Pilosa to listen on // a random port. if port == "" { - port = "10101" + port = defaultPort } return scheme, host, port, nil } diff --git a/server/config_internal_test.go b/server/config_internal_test.go index ca7548895..09d423e98 100644 --- a/server/config_internal_test.go +++ b/server/config_internal_test.go @@ -26,7 +26,6 @@ import ( type addrs struct{ bind, advertise string } func TestConfig_validateAddrs(t *testing.T) { - // Prepare some reference strings that will be checked in the // test below. outboundAddr := outboundIP().String() @@ -104,8 +103,9 @@ func TestConfig_validateAddrs(t *testing.T) { {"", addrs{"0.0.0.0:1234", ""}, addrs{"0.0.0.0:1234", outboundAddr + ":1234"}}, - // Expected errors. + // Expected errors. + // // Missing port number. {"missing port in address", addrs{"localhost", ""}, @@ -139,11 +139,10 @@ func TestConfig_validateAddrs(t *testing.T) { } else if err == nil && test.expErr != "" { t.Fatalf("expected error string to contain %s, but got no error", test.expErr) } else if err != nil && test.expErr != "" { - if strings.Contains(err.Error(), test.expErr) { - return - } else { + if !strings.Contains(err.Error(), test.expErr) { t.Fatalf("expected error string to contain %s, but got %s", test.expErr, err.Error()) } + return } if c.Bind != test.exp.bind { @@ -154,3 +153,132 @@ func TestConfig_validateAddrs(t *testing.T) { }) } } + +func TestConfig_validateAddrsGRPC(t *testing.T) { + // Prepare some reference strings that will be checked in the + // test below. + outboundAddr := outboundIP().String() + hostname, err := os.Hostname() + if err != nil { + t.Fatal(err) + } + hostAddr, err := lookupAddr(context.Background(), net.DefaultResolver, hostname) + if err != nil { + t.Fatal(err) + } + if strings.Contains(hostAddr, ":") { + hostAddr = "[" + hostAddr + "]" + } + + tests := []struct { + expErr string + in addrs + exp addrs + }{ + // Default values; addresses set empty. + {"", + addrs{"", ""}, + addrs{"grpc://:20101", "grpc://:20101"}}, + {"", + addrs{":", ""}, + addrs{"grpc://:20101", "grpc://:20101"}}, + {"", + addrs{"", ":"}, + addrs{"grpc://:20101", "grpc://:20101"}}, + {"", + addrs{":", ":"}, + addrs{"grpc://:20101", "grpc://:20101"}}, + // Listener :port. + {"", + addrs{":1234", ""}, + addrs{"grpc://:1234", "grpc://:1234"}}, + // Listener with host:port. + {"", + addrs{hostAddr + ":20101", ""}, + addrs{"grpc://" + hostAddr + ":20101", "grpc://" + hostAddr + ":20101"}}, + // Listener with host:. + {"", + addrs{hostAddr + ":", ""}, + addrs{"grpc://" + hostAddr + ":20101", "grpc://" + hostAddr + ":20101"}}, + // Listener with scheme:. + {"", + addrs{"http://" + hostAddr + ":", ""}, + addrs{"grpc://" + hostAddr + ":20101", "grpc://" + hostAddr + ":20101"}}, + // Listener with localhost:port. + {"", + addrs{"localhost:1234", ""}, + addrs{"grpc://localhost:1234", "grpc://localhost:1234"}}, + // Listener with localhost:. + {"", + addrs{"localhost:", ""}, + addrs{"grpc://localhost:20101", "grpc://localhost:20101"}}, + // Listener and advertise addresses. + {"", + addrs{hostAddr + ":1234", hostAddr + ":"}, + addrs{"grpc://" + hostAddr + ":1234", "grpc://" + hostAddr + ":1234"}}, + // Explicit port number in advertise addr. + {"", + addrs{hostAddr + ":1234", hostAddr + ":7890"}, + addrs{"grpc://" + hostAddr + ":1234", "grpc://" + hostAddr + ":7890"}}, + // Use a non-numeric port number. + {"", + addrs{":postgresql", ""}, + addrs{"grpc://:5432", "grpc://:5432"}}, + // Advertise port 0 means reuse listen port. + {"", + addrs{":1234", ":0"}, + addrs{"grpc://:1234", "grpc://:1234"}}, + // Listen on all interfaces. Determine advertise address. + {"", + addrs{"0.0.0.0:1234", ""}, + addrs{"grpc://0.0.0.0:1234", "grpc://" + outboundAddr + ":1234"}}, + + // Expected errors. + // + // Missing port number. + {"missing port in address", + addrs{"localhost", ""}, + addrs{}}, + {"missing port in address", + addrs{":1234", "localhost"}, + addrs{}}, + // Invalid port number. + {"invalid port", + addrs{"localhost:-1234", ""}, + addrs{}}, + {"validating grpc advertise address", + addrs{"localhost:foo", ""}, + addrs{}}, + {"no such host", + addrs{"333.333.333.333:1234", ""}, + addrs{}}, + } + + for i, test := range tests { + t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { + c := NewConfig() + + c.BindGRPC = test.in.bind + c.AdvertiseGRPC = test.in.advertise + + err := c.validateAddrs(context.Background()) + + if err != nil && test.expErr == "" { + t.Fatal(err) + } else if err == nil && test.expErr != "" { + t.Fatalf("expected error string to contain %s, but got no error", test.expErr) + } else if err != nil && test.expErr != "" { + if !strings.Contains(err.Error(), test.expErr) { + t.Fatalf("expected error string to contain %s, but got %s", test.expErr, err.Error()) + } + return + } + + if c.BindGRPC != test.exp.bind { + t.Fatalf("bind address: expected %s, but got %s", test.exp.bind, c.BindGRPC) + } else if c.AdvertiseGRPC != test.exp.advertise { + t.Fatalf("advertise address: expected %s, but got %s", test.exp.advertise, c.AdvertiseGRPC) + } + }) + } +} diff --git a/server/grpc.go b/server/grpc.go index 70df01429..7be572d0b 100644 --- a/server/grpc.go +++ b/server/grpc.go @@ -272,6 +272,9 @@ func (h *GRPCHandler) Inspect(req *pb.InspectRequest, stream pb.Pilosa_InspectSe return errToStatusError(err) } + // Obtain transaction. + tx := pilosa.NewMultiTxWithIndex(true, index) + var fields []*pilosa.Field for _, field := range index.Fields() { // exclude internal fields (starting with "_") @@ -291,6 +294,54 @@ func (h *GRPCHandler) Inspect(req *pb.InspectRequest, stream pb.Pilosa_InspectSe } } + if req.Query != "" { + // Execute the query and use it to select columns. + if req.Columns != nil && req.Columns.Type != nil { + l := 0 + switch v := req.Columns.Type.(type) { + case *pb.IdsOrKeys_Ids: + l = len(v.Ids.Vals) + case *pb.IdsOrKeys_Keys: + l = len(v.Keys.Vals) + } + if l > 0 { + return errors.New("found a list of columns in a query-based inspect call") + } + } + query := pilosa.QueryRequest{ + Index: req.Index, + Query: req.Query, + } + resp, err := h.api.Query(stream.Context(), &query) + if err != nil { + return errors.Wrapf(err, "querying for columns with %q", req.Query) + } + if len(resp.Results) != 1 { + return errors.Errorf("expected 1 result for inspect query; got %d from %q", len(resp.Results), req.Query) + } + row, ok := resp.Results[0].(*pilosa.Row) + if !ok { + return errors.Errorf("incorrect query result type %T for query %q", resp.Results[0], req.Query) + } + if len(row.Keys) > 0 { + req.Columns = &pb.IdsOrKeys{ + Type: &pb.IdsOrKeys_Keys{ + Keys: &pb.StringArray{Vals: row.Keys}, + }, + } + } else { + req.Columns = &pb.IdsOrKeys{ + Type: &pb.IdsOrKeys_Ids{ + Ids: &pb.Uint64Array{Vals: row.Columns()}, + }, + } + } + if !row.Any() { + // No columns were matched. + return nil + } + } + limit := req.Limit if limit == 0 { limit = defaultLimit @@ -440,7 +491,7 @@ func (h *GRPCHandler) Inspect(req *pb.InspectRequest, stream pb.Pilosa_InspectSe } } } else { - value, exists, err = field.StringValue(col) + value, exists, err = field.StringValue(tx, col) if err != nil { return errors.Wrap(err, "getting string field value for column") } @@ -689,7 +740,7 @@ func (h *GRPCHandler) Inspect(req *pb.InspectRequest, stream pb.Pilosa_InspectSe } } } else { - value, exists, err = field.StringValue(id) + value, exists, err = field.StringValue(tx, id) if err != nil { return errors.Wrap(err, "getting string field value for column") } diff --git a/server/handler_test.go b/server/handler_test.go index 479856fad..e893aa371 100644 --- a/server/handler_test.go +++ b/server/handler_test.go @@ -173,22 +173,32 @@ func TestHandler_Endpoints(t *testing.T) { } }) + tx, err := holder.Begin(true) + if err != nil { + t.Fatal(err) + } + defer func() { _ = tx.Rollback() }() + i0 := hldr.MustCreateIndexIfNotExists("i0", pilosa.IndexOptions{}) i1 := hldr.MustCreateIndexIfNotExists("i1", pilosa.IndexOptions{}) if f, err := i0.CreateFieldIfNotExists("f1", pilosa.OptFieldTypeDefault()); err != nil { t.Fatal(err) - } else if _, err := f.SetBit(0, 0, nil); err != nil { + } else if _, err := f.SetBit(tx, 0, 0, nil); err != nil { t.Fatal(err) } if f, err := i1.CreateFieldIfNotExists("f0", pilosa.OptFieldTypeDefault()); err != nil { t.Fatal(err) - } else if _, err := f.SetBit(0, 0, nil); err != nil { + } else if _, err := f.SetBit(tx, 0, 0, nil); err != nil { t.Fatal(err) } if _, err := i0.CreateFieldIfNotExists("f0", pilosa.OptFieldTypeDefault()); err != nil { t.Fatal(err) } + if err := tx.Commit(); err != nil { + t.Fatal(err) + } + t.Run("Schema", func(t *testing.T) { w := httptest.NewRecorder() h.ServeHTTP(w, test.MustNewHTTPRequest("GET", "/schema", nil)) diff --git a/server/server.go b/server/server.go index 614cfd1ab..902abf472 100644 --- a/server/server.go +++ b/server/server.go @@ -238,11 +238,7 @@ func (m *Command) SetupServer() error { return errors.Wrap(err, "setting up logger") } - productName := "Pilosa" - if pilosa.EnterpriseEnabled { - productName += " Enterprise" - } - m.logger.Printf("%s %s, build time %s\n", productName, pilosa.Version, pilosa.BuildTime) + m.logger.Printf("%s", pilosa.VersionInfo()) // validateAddrs sets the appropriate values for Bind and Advertise // based on the inputs. It is not responsible for applying defaults, although @@ -274,15 +270,6 @@ func (m *Command) SetupServer() error { grpcURI.SetPort(uint16(m.grpcLn.Addr().(*net.TCPAddr).Port)) } - if grpcURI.Scheme == "http" { - grpcURI.Scheme = "grpc" - } - - // discover the address if not specified - if grpcURI.Host == "0.0.0.0" { - grpcURI.Host = outboundIP().String() - } - // Setup TLS if uri.Scheme == "https" { m.tlsConfig, err = GetTLSConfig(&m.Config.TLS, m.logger.Logger()) @@ -325,6 +312,15 @@ func (m *Command) SetupServer() error { advertiseURI.SetPort(uri.Port) } + // Get grpc advertise address as uri. + advertiseGRPCURI, err := pilosa.NewURIFromAddress(m.Config.AdvertiseGRPC) + if err != nil { + return errors.Wrap(err, "processing grpc advertise address") + } + if advertiseGRPCURI.Port == 0 { + advertiseGRPCURI.SetPort(grpcURI.Port) + } + // Primary store configuration is handled automatically now. if m.Config.Translation.PrimaryURL != "" { m.logger.Printf("DEPRECATED: The primary-url configuration option is no longer used.") @@ -353,7 +349,7 @@ func (m *Command) SetupServer() error { pilosa.OptServerGCNotifier(gcnotify.NewActiveGCNotifier()), pilosa.OptServerStatsClient(statsClient), pilosa.OptServerURI(advertiseURI), - pilosa.OptServerGRPCURI(grpcURI), + pilosa.OptServerGRPCURI(advertiseGRPCURI), pilosa.OptServerInternalClient(http.NewInternalClientFromURI(uri, c)), pilosa.OptServerClusterDisabled(m.Config.Cluster.Disabled, m.Config.Cluster.Hosts), pilosa.OptServerSerializer(proto.Serializer{}), diff --git a/snapshotqueue.go b/snapshotqueue.go index 373e5c538..1bdcdb7a9 100644 --- a/snapshotqueue.go +++ b/snapshotqueue.go @@ -15,7 +15,10 @@ package pilosa import ( + "context" "fmt" + "io" + "math/bits" "os" "sync" "sync/atomic" @@ -39,12 +42,22 @@ import ( // Await, Enqueue, and Immediate should be called only with the fragment lock // held. // -// ScanHolder spawns a new goroutine. You don't need to use `go` on it. -type snapshotQueue interface { +// If you create a queue, it should get stopped at some point. The +// atomicSnapshotQueue implementation used as defaultSnapshotQueue has +// a Start function which will tell you whether it actually started a +// queue. This logic exists because in a normal server case, you probably +// want the queue to be shut down as part of server shutdown, but if you're +// running cluster tests, you probably want to start and shop the queue as +// part of the test, not stop it when any server terminates. +// +// It's less likely to be desireable to start/stop individual queues, +// because fragments use the defaultSnapshotQueue anyway. This design +// needs revisiting. +type SnapshotQueue interface { Immediate(*fragment) error Enqueue(*fragment) Await(*fragment) error - ScanHolder(*Holder) + ScanHolder(*Holder, chan struct{}) Stop() } @@ -53,7 +66,8 @@ type snapshotQueue interface { type queuelessSnapshotQueue struct{} func (q *queuelessSnapshotQueue) Enqueue(f *fragment) { - _ = f.snapshot() + // We don't actually try to enqueue the snapshot; it breaks things + // if a snapshot gets caused during a transaction. } func (q *queuelessSnapshotQueue) Await(f *fragment) error { @@ -64,20 +78,27 @@ func (q *queuelessSnapshotQueue) Immediate(f *fragment) error { return f.snapshot() } -func (q *queuelessSnapshotQueue) ScanHolder(h *Holder) { +func (q *queuelessSnapshotQueue) ScanHolder(h *Holder, done chan struct{}) { } func (q *queuelessSnapshotQueue) Stop() { } -// defaultSnapshotQueue is the fallback to use if none is available, -// and currently uses queueless -- it runs all snapshots immediately. -var defaultSnapshotQueue *queuelessSnapshotQueue +var defaultSnapshotQueue = &queuelessSnapshotQueue{} // newSnapshotQueue makes a new snapshot queue, of depth N, with // w worker threads. -func newSnapshotQueue(n int, w int, l logger.Logger) snapshotQueue { - sq := prioritySnapshotQueue{normal: make(chan snapshotRequest, n), urgent: make(chan snapshotRequest), background: make(chan snapshotRequest), done: make(chan struct{}), logger: l} +func newSnapshotQueue(n int, w int, l logger.Logger) SnapshotQueue { + ctx, cancel := context.WithCancel(context.Background()) + sq := prioritySnapshotQueue{ + normal: make(chan snapshotRequest, n), + urgent: make(chan snapshotRequest), + background: make(chan snapshotRequest), + ctx: ctx, + cancel: cancel, + maxOpN: 10000, + logger: l, + } if sq.logger == nil { sq.logger = logger.NewStandardLogger(os.Stderr) } @@ -105,50 +126,52 @@ type prioritySnapshotQueue struct { urgent chan snapshotRequest normal chan snapshotRequest background chan snapshotRequest - done chan struct{} + ctx context.Context + cancel context.CancelFunc mu sync.RWMutex scanWG, workerWG sync.WaitGroup + maxOpN int + observedOpN [16]uint32 stats struct { - enqueued uint64 - skipped uint64 + enqueued uint32 + skipped uint32 } } func (sq *prioritySnapshotQueue) spawnWorkers(w int) { sq.mu.Lock() defer sq.mu.Unlock() - if sq.done == nil { - sq.logger.Printf("prioritySnapshotQueue worker: no done channel, already done?") + if sq.ctx.Err() != nil { + sq.logger.Printf("prioritySnapshotQueue worker: already done") return } sq.workerWG.Add(w) for i := 0; i < w; i++ { - go sq.worker(sq.urgent, sq.normal, sq.background, sq.done) + go sq.worker(sq.ctx, sq.urgent, sq.normal, sq.background) } } -func (sq *prioritySnapshotQueue) worker(urgent, normal, background chan snapshotRequest, done chan struct{}) { - // We don't want a race condition on these. If they're non-nil when - // we get them, they should get closed at some point. If done is - // already nil, we shouldn't do anything. +func (sq *prioritySnapshotQueue) worker(ctx context.Context, urgent, normal, background chan snapshotRequest) { defer sq.workerWG.Done() + done := ctx.Done() ok := true var req snapshotRequest for ok { req.frag = nil - select { + case _, ok = <-done: case req, ok = <-urgent: default: select { + case _, ok = <-done: case req, ok = <-urgent: case req, ok = <-normal: default: select { + case _, ok = <-done: case req, ok = <-urgent: case req, ok = <-normal: case req, ok = <-background: - case _, ok = <-done: } } } @@ -182,17 +205,18 @@ func (sq *prioritySnapshotQueue) process(req snapshotRequest) { func (sq *prioritySnapshotQueue) Stop() { sq.mu.Lock() defer sq.mu.Unlock() - close(sq.done) + sq.cancel() // scanners need to be done before we close the other channels. sq.scanWG.Wait() - sq.done = nil close(sq.normal) sq.normal = nil close(sq.urgent) sq.urgent = nil close(sq.background) sq.background = nil - if sq.stats.skipped > 0 || sq.stats.enqueued > 1 { + enqueued := atomic.LoadUint32(&sq.stats.enqueued) + skipped := atomic.LoadUint32(&sq.stats.skipped) + if skipped > 0 || enqueued > 1 { sq.logger.Printf("snapshot queue: enqueued %d, skipped %d\n", sq.stats.enqueued, sq.stats.skipped) } } @@ -203,6 +227,7 @@ func (sq *prioritySnapshotQueue) Enqueue(f *fragment) { if f.snapshotPending { return } + sq.observeOpN(uint32(f.opN)) sq.mu.RLock() defer sq.mu.RUnlock() if sq.normal == nil { @@ -217,10 +242,10 @@ func (sq *prioritySnapshotQueue) Enqueue(f *fragment) { // try to enqueue snapshot select { case sq.normal <- snapshotRequest{frag: f, when: time.Now()}: - atomic.AddUint64(&sq.stats.enqueued, 1) + atomic.AddUint32(&sq.stats.enqueued, 1) return default: - atomic.AddUint64(&sq.stats.skipped, 1) + atomic.AddUint32(&sq.stats.skipped, 1) f.snapshotPending = false return } @@ -230,6 +255,11 @@ func (sq *prioritySnapshotQueue) Enqueue(f *fragment) { // held. Await waits on a condition variable inside f, associated with the // fragment's lock, so this does not conflict with the lock being used for // snapshots. +// +// Note that workers don't stop just because the queue's been stopped; only +// the background scanner is stopped. So an Await shouldn't block forever +// even if the queue gets shut down. If you're reading this, possibly that +// analysis is incorrect. func (sq *prioritySnapshotQueue) Await(f *fragment) (err error) { for f.snapshotPending { f.snapshotCond.Wait() @@ -252,6 +282,7 @@ func (sq *prioritySnapshotQueue) Immediate(f *fragment) error { return errors.New("requested immediate snapshot after snapshot queue was closed") } f.snapshotPending = true + sq.observeOpN(uint32(f.opN)) req := snapshotRequest{frag: f, when: time.Now()} // if the fragment was already in the work queue, it's *possible* // that the only available worker just picked it off the queue, and @@ -268,141 +299,202 @@ func (sq *prioritySnapshotQueue) Immediate(f *fragment) error { return sq.Await(f) } -// needsSnapshot determines whether a fragment probably wants snapshotting. -// Specifically, it looks for fragments not already marked to receive -// snapshots, but which have a high enough opN to justify a snapshot. This -// is only used from the background scan. -func (sq *prioritySnapshotQueue) needsSnapshot(f *fragment) bool { - if f == nil { - return false - } - f.mu.Lock() - defer f.mu.Unlock() - if f.snapshotPending { - return false - } - if f.opN > f.MaxOpN { - return true - } - return false -} - // ScanHolder spawns a goroutine which iterates through the holder's // indexes/fields/views/fragments, looking for fragments which have OpN // high enough to justify a snapshot but don't seem to have one pending. // It then dumps these in the low priority background queue. -func (sq *prioritySnapshotQueue) ScanHolder(h *Holder) { +func (sq *prioritySnapshotQueue) ScanHolder(h *Holder, done chan struct{}) { sq.mu.Lock() sq.scanWG.Add(1) - go sq.scanHolderWorker(h, sq.background, sq.done) + go sq.scanHolderWorker(h, sq.background, done) sq.mu.Unlock() } +// observeOpN reports that a given value of opN was "observed", meaning, +// we encountered a fragment which had that value. This happens for every +// enqueue/immediate, including enqueue attempts which fail to actually +// enter the queue, and it also happens for fragments noticed by the background +// scan but which don't have high enough opN to trigger a snapshot. +func (sq *prioritySnapshotQueue) observeOpN(n uint32) { + // aka "log2(n) + 1", or 0 for n==0 + pow2 := 32 - bits.LeadingZeros32(n) + // 15 == 16384. Our usual fragment maxOpN is 10k, so most fragments + // should end up in the 8k-16k bucket, rather than the 16k+ bucket, + // unless we've got a lot of ingests with large batches going on, + // in which case the 16k bucket will win. + if pow2 > 15 { + pow2 = 15 + } + // store in inverse order so the lowest slot in the array is the + // highest cardinality + atomic.AddUint32(&sq.observedOpN[15-pow2], 1) +} + +// computeMaxOpN tries to pick a reasonable new maxOpN for the background +// scan to use. On a quiet system, we want to gradually lower opN, picking +// the fragments with the highest opN values first, because those offer the +// largest benefit. So, whenever we check a fragment in the background, if we +// *don't* snapshot it, we'll "observe" its OpN value, and then we pick a +// value which picks up at least 1/4 of them. +// +// If there's ingest activity, the Immediate and Enqueue operations will +// "observe" the OpN of fragments submitted to them. This can drive OpN back +// up, if those fragments frequently have very high opN values, which reflects +// the fact that we have enough of that activity that we don't need the +// background scanner adding more. +// +// If we have enough ingest activity that the background scanner never actually +// gets to submit work, we'll rarely get here, because the background scanner +// will block until there's no snapshots pending for the normal workload. +// When we do, we'll probably pick a MaxOpN which is dominated by the ingest +// workload's opN values. So for instance, if everything coming in from the +// ingest workload has 10k or more items, because that's the default fragment +// maxOpN, that will probably set the background snapshot queue value to 8k. +func (sq *prioritySnapshotQueue) computeMaxOpN() { + sq.logger.Debugf("observedOpN by power of 2: %d\n", sq.observedOpN[:]) + total := uint32(0) + for i := range sq.observedOpN { + total += atomic.LoadUint32(&sq.observedOpN[i]) + } + target := (total / 4) + 1 + subTotal := uint32(0) + for i := range sq.observedOpN { + v := atomic.LoadUint32(&sq.observedOpN[i]) + subTotal += v + if subTotal >= target { + prevMaxOpN := sq.maxOpN + sq.maxOpN = (1 << (15 - uint(i))) / 2 + if sq.maxOpN > 0 { + sq.maxOpN-- + } + if prevMaxOpN != sq.maxOpN { + sq.logger.Printf("background scan: %d/%d fragments considered have opN %d or higher\n", + subTotal, total, sq.maxOpN) + } + break + } + } + // It's conceptually possible that we'll miss a couple of observations + // here but that's not really important. This is all pretty approximate. + for i := range sq.observedOpN { + atomic.StoreUint32(&sq.observedOpN[i], 0) + } +} + +// prioritySnapshotQueueScanner is the data type that implements HolderOperator +// and represents a single scan of a holder, with a given maxOpN. +type prioritySnapshotQueueScanner struct { + HolderFilterAll + HolderProcessNone + sq *prioritySnapshotQueue + holder *Holder + queue chan snapshotRequest + ctx context.Context + maxOpN int + seen, hits, counter int +} + +func (s *prioritySnapshotQueueScanner) ProcessFragment(f *fragment) error { + if f == nil { + return nil + } + s.seen++ + // we can't defer this reasonably, because otherwise we'll keep + // the fragment locked forever if we end up trying to send it + // to the queue, but the workers are busy on other fragments. + f.mu.Lock() + open := f.open + snapshotPending, opN := f.snapshotPending, f.opN + f.mu.Unlock() + + // a pending snapshot is one that is either in the normal or + // immediate queue, or is trying to get into the normal queue + // and about to fail, but either way, it already got observed + // there, so we don't need to observe it here. A closed fragment + // doesn't matter to us -- it should be a transient state that + // happens during a shutdown, or shouldn't happen, but we don't + // care about it. + if snapshotPending || !open { + return nil + } + if opN <= s.maxOpN { + // observe the value but don't do a snapshot + s.sq.observeOpN(uint32(opN)) + s.counter++ + if s.counter == 1000 { + select { + case <-time.After(1 * time.Second): + case <-s.ctx.Done(): + return io.EOF + } + s.counter = 0 + } + return nil + } + // we don't observe values when we decide to trigger a snapshot, + // because those values will be changing anyway. we could also + // observe them as zero, but that's also sort of wrong. + s.hits++ + select { + case s.queue <- snapshotRequest{frag: f, when: time.Now()}: + s.sq.logger.Debugf("found fragment needing snapshot: %s\n", f.path) + case <-s.ctx.Done(): + return io.EOF + } + return nil + +} + +func contextMergedWithStructChan(ctx context.Context, ch chan struct{}) (context.Context, context.CancelFunc) { + canCancel, cancel := context.WithCancel(ctx) + go func() { + select { + case <-ctx.Done(): + cancel() + case <-ch: + cancel() + case <-canCancel.Done(): + // don't need to cancel, but do need to exit this + // function + } + }() + return canCancel, cancel +} + // scanHolderWorker is a background task that scans a holder looking for // fragments which need snapshots taken. It's the cleanup task for snapshots // that would have been requested by Enqueue, but the queue was full. func (sq *prioritySnapshotQueue) scanHolderWorker(h *Holder, background chan snapshotRequest, done chan struct{}) { defer sq.scanWG.Done() - var indexNames, fieldNames, viewNames []string - var fragNums []uint64 + ctx, cancel := contextMergedWithStructChan(sq.ctx, done) + defer cancel() + scanner := &prioritySnapshotQueueScanner{ + sq: sq, + holder: h, + queue: background, + ctx: sq.ctx, + maxOpN: sq.maxOpN, + } for { - // To avoid abusing things, cap activity rate; every time we finish - // the holder, or every couple hundred fragments considered, we - // pause for a bit. - counter := 0 - hits := 0 - h.mu.Lock() - indexNames = indexNames[:0] - for indexName := range h.indexes { - indexNames = append(indexNames, indexName) + err := h.Process(ctx, scanner) + if err != nil { + return } - h.mu.Unlock() - for _, indexName := range indexNames { - h.mu.Lock() - index := h.indexes[indexName] - h.mu.Unlock() - if index == nil { - continue - } - fieldNames = fieldNames[:0] - index.mu.Lock() - for fieldName := range index.fields { - fieldNames = append(fieldNames, fieldName) - } - index.mu.Unlock() - for _, fieldName := range fieldNames { - index.mu.Lock() - field := index.fields[fieldName] - index.mu.Unlock() - if field == nil { - continue - } - viewNames = viewNames[:0] - field.mu.Lock() - for viewName := range field.viewMap { - viewNames = append(viewNames, viewName) - } - field.mu.Unlock() - for _, viewName := range viewNames { - field.mu.Lock() - view := field.viewMap[viewName] - field.mu.Unlock() - if view == nil { - continue - } - fragNums := fragNums[:0] - view.mu.Lock() - for fragNum := range view.fragments { - fragNums = append(fragNums, fragNum) - } - view.mu.Unlock() - for _, fragNum := range fragNums { - view.mu.Lock() - frag := view.fragments[fragNum] - view.mu.Unlock() - if sq.needsSnapshot(frag) { - hits++ - select { - case background <- snapshotRequest{frag: frag, when: time.Now()}: - sq.logger.Debugf("found fragment needing snapshot: %s\n", frag.path) - case <-done: - return - } - } else { - // Count fragments examined *without* finding anything that - // needed a snapshot. When we find things that need snapshots, - // the time it takes the workers to respond to us is enough - // of a delay to keep us from eating every CPU. So, if a lot - // of things need snapshots, and the workers aren't doing - // anything else, ScanHolder will mostly keep them saturated. - // If they're busy, we'll block forever in the write to the - // background queue. If there's nothing that needs snapshots, - // we pause frequently for a second or so at a time. - counter++ - if counter == 100 { - select { - case <-time.After(1 * time.Second): - case <-done: - return - } - counter = 0 - } - } - } - } - } - } - if hits > 0 { - sq.logger.Printf("background scan: %d fragments needed snapshots\n", hits) - hits = 0 + + if scanner.hits > 0 { + sq.logger.Printf("background scan: %d/%d fragments needed snapshots\n", scanner.hits, scanner.seen) + scanner.hits = 0 } else { sq.logger.Debugf("background scan: no fragments needed snapshots, waiting\n") // No reason to be active if we're not finding anything. select { case <-time.After(60 * time.Second): - case <-done: + case <-ctx.Done(): return } } + scanner.seen = 0 + sq.computeMaxOpN() + scanner.maxOpN = sq.maxOpN } } diff --git a/test/field.go b/test/field.go index b95e4f88b..f56672834 100644 --- a/test/field.go +++ b/test/field.go @@ -33,7 +33,7 @@ func newField(opts pilosa.FieldOption) *Field { if err != nil { panic(err) } - field, err := pilosa.NewField(path, "i", "f", opts) + field, err := pilosa.NewField(pilosa.NewHolder(pilosa.DefaultPartitionN), path, "i", "f", opts) if err != nil { panic(err) } @@ -63,7 +63,7 @@ func (f *Field) reopen() error { } path, index, name := f.Path(), f.Index(), f.Name() - f.Field, err = pilosa.NewField(path, index, name, pilosa.OptFieldTypeDefault()) + f.Field, err = pilosa.NewField(pilosa.NewHolder(pilosa.DefaultPartitionN), path, index, name, pilosa.OptFieldTypeDefault()) if err != nil { return err } diff --git a/test/holder.go b/test/holder.go index 3d73a0bf0..b48016f9f 100644 --- a/test/holder.go +++ b/test/holder.go @@ -86,7 +86,9 @@ func (h *Holder) Row(index, field string, rowID uint64) *pilosa.Row { if err != nil { panic(err) } - row, err := f.Row(rowID) + tx := &pilosa.RoaringTx{Index: idx.Index} + + row, err := f.Row(tx, rowID) if err != nil { panic(err) } @@ -100,7 +102,9 @@ func (h *Holder) ReadRow(index, field string, rowID uint64) *pilosa.Row { if f == nil { panic(pilosa.ErrFieldNotFound) } - row, err := f.Row(rowID) + tx := &pilosa.RoaringTx{Field: f} + + row, err := f.Row(tx, rowID) if err != nil { panic(err) } @@ -122,7 +126,9 @@ func (h *Holder) RowTime(index, field string, rowID uint64, t time.Time, quantum if err != nil { panic(err) } - row, err := f.RowTime(rowID, t, quantum) + tx := &pilosa.RoaringTx{Index: idx.Index} + + row, err := f.RowTime(tx, rowID, t, quantum) if err != nil { panic(err) } @@ -141,7 +147,9 @@ func (h *Holder) SetBitTime(index, field string, rowID, columnID uint64, t *time if err != nil { panic(err) } - _, err = f.SetBit(rowID, columnID, t) + tx := &pilosa.RoaringTx{Index: idx.Index} + + _, err = f.SetBit(tx, rowID, columnID, t) if err != nil { panic(err) } @@ -154,7 +162,9 @@ func (h *Holder) ClearBit(index, field string, rowID, columnID uint64) { if err != nil { panic(err) } - _, err = f.ClearBit(rowID, columnID) + tx := &pilosa.RoaringTx{Index: idx.Index} + + _, err = f.ClearBit(tx, rowID, columnID) if err != nil { panic(err) } @@ -175,7 +185,9 @@ func (h *Holder) SetValue(index, field string, columnID uint64, value int64) { if err != nil { panic(err) } - _, err = f.SetValue(columnID, value) + tx := &pilosa.RoaringTx{Index: idx.Index} + + _, err = f.SetValue(tx, columnID, value) if err != nil { panic(err) } @@ -188,7 +200,9 @@ func (h *Holder) Value(index, field string, columnID uint64) (int64, bool) { if err != nil { panic(err) } - val, exists, err := f.Value(columnID) + tx := &pilosa.RoaringTx{Index: idx.Index} + + val, exists, err := f.Value(tx, columnID) if err != nil { panic(err) } @@ -203,7 +217,9 @@ func (h *Holder) Range(index, field string, op pql.Token, predicate int64) *pilo if err != nil { panic(err) } - row, err := f.Range(field, op, predicate) + tx := &pilosa.RoaringTx{Index: idx.Index} + + row, err := f.Range(tx, field, op, predicate) if err != nil { panic(err) } diff --git a/test/index.go b/test/index.go index bf65c6ae2..b90702ae2 100644 --- a/test/index.go +++ b/test/index.go @@ -32,7 +32,7 @@ func newIndex() *Index { if err != nil { panic(err) } - index, err := pilosa.NewIndex(path, "i", pilosa.DefaultPartitionN) + index, err := pilosa.NewIndex(pilosa.NewHolder(pilosa.DefaultPartitionN), path, "i") if err != nil { panic(err) } @@ -62,7 +62,7 @@ func (i *Index) Reopen() error { } path, name := i.Path(), i.Name() - i.Index, err = pilosa.NewIndex(path, name, pilosa.DefaultPartitionN) + i.Index, err = pilosa.NewIndex(pilosa.NewHolder(pilosa.DefaultPartitionN), path, name) if err != nil { return err } diff --git a/testdata/timeRegressionSchema.json b/testdata/timeRegressionSchema.json new file mode 100644 index 000000000..bc131015d --- /dev/null +++ b/testdata/timeRegressionSchema.json @@ -0,0 +1,32 @@ +{ + "indexes": [ + { + "name": "repository", + "options": { + "keys": false, + "trackExistence": true + }, + "fields": [ + { + "name": "language", + "options": { + "type": "set", + "cacheType": "ranked", + "cacheSize": 50000, + "keys": false + } + }, + { + "name": "stargazer", + "options": { + "type": "time", + "timeQuantum": "YMD", + "keys": false, + "noStandardView": false + } + } + ], + "shardWidth": 1048576 + } + ] +} \ No newline at end of file diff --git a/transaction.go b/transaction.go index ba7063907..2af2c76df 100644 --- a/transaction.go +++ b/transaction.go @@ -17,6 +17,7 @@ package pilosa import ( "context" "encoding/json" + "regexp" "sync" "time" @@ -24,6 +25,8 @@ import ( "github.com/pkg/errors" ) +var txIDRegexp = regexp.MustCompile("^[A-Za-z0-9_-]*$") + // Transaction contains information related to a block of work that // needs to be tracked and spans multiple API calls. type Transaction struct { @@ -93,6 +96,10 @@ func (tm *TransactionManager) Start(ctx context.Context, id string, timeout time tm.mu.Lock() defer tm.mu.Unlock() + if !txIDRegexp.Match([]byte(id)) { + return nil, errors.New("invalid transaction ID, must match [A-Za-z0-9_-]") + } + trnsMap, err := tm.store.List() if err != nil { return nil, errors.Wrap(err, "listing transactions in Start") diff --git a/transaction_test.go b/transaction_test.go index 171d1bbab..50998cd0d 100644 --- a/transaction_test.go +++ b/transaction_test.go @@ -63,8 +63,8 @@ func TestTransactionManager(t *testing.T) { test.CompareTransactions(t, trnsMap["b"], trns2) // can submit an exclusive transaction - trnsE := mustStart(t, tm, "ce", time.Millisecond*5, true) - test.CompareTransactions(t, &pilosa.Transaction{ID: "ce", Active: false, Exclusive: true, Timeout: time.Millisecond * 5, Deadline: time.Now().Add(time.Millisecond * 5)}, trnsE) + trnsE := mustStart(t, tm, "ce", 100*time.Millisecond, true) + test.CompareTransactions(t, &pilosa.Transaction{ID: "ce", Active: false, Exclusive: true, Timeout: 100 * time.Millisecond, Deadline: time.Now().Add(100 * time.Millisecond)}, trnsE) // can't start new transactions while an exclusive transaction is pending if _, err := tm.Start(ctx, "d", time.Millisecond, false); err != pilosa.ErrTransactionExclusive { @@ -78,7 +78,7 @@ func TestTransactionManager(t *testing.T) { // exclusive transaction becomes active after deadlines expire for i := 0; true; i++ { - time.Sleep(time.Microsecond) + time.Sleep(time.Millisecond) trnsE, err := tm.Get(ctx, "ce") if err != nil { t.Errorf("error retrieving exclusive transaction: %v", err) @@ -86,7 +86,7 @@ func TestTransactionManager(t *testing.T) { if trnsE.Active { break } - if i > 100 { + if i > 10000 { t.Fatalf("exclusive transaction never became active: %+v", trnsE) } } @@ -103,7 +103,7 @@ func TestTransactionManager(t *testing.T) { // exclusive transaction gets expired after other transactions have attempted to start for i := 0; true; i++ { - time.Sleep(time.Millisecond * 2) + time.Sleep(time.Millisecond * 20) trnsE, err := tm.Get(ctx, "ce") if err == nil { if i > 10 { @@ -155,26 +155,26 @@ func TestTransactionManager(t *testing.T) { mustFinish(t, tm, "le") // can start normal transaction to test deadline reset - trnsM := mustStart(t, tm, "m", time.Millisecond*4, false) - test.CompareTransactions(t, &pilosa.Transaction{ID: "m", Active: true, Timeout: time.Millisecond * 4, Deadline: time.Now().Add(time.Millisecond * 4)}, trnsM) + trnsM := mustStart(t, tm, "m", time.Millisecond*400, false) + test.CompareTransactions(t, &pilosa.Transaction{ID: "m", Active: true, Timeout: time.Millisecond * 400, Deadline: time.Now().Add(time.Millisecond * 400)}, trnsM) // start new exclusive transaction to trigger deadline check trnsNE := mustStart(t, tm, "ne", time.Hour, true) test.CompareTransactions(t, &pilosa.Transaction{ID: "ne", Exclusive: true, Timeout: time.Hour, Deadline: time.Now().Add(time.Hour)}, trnsNE) // sleep for most of the deadline - time.Sleep(time.Millisecond * 3) + time.Sleep(time.Millisecond * 300) // reset deadline trnsM_reset, err := tm.ResetDeadline(ctx, "m") if err != nil { t.Errorf("resetting deadline: %v", err) } - trnsM.Deadline = time.Now().Add(time.Millisecond * 4) + trnsM.Deadline = time.Now().Add(time.Millisecond * 400) test.CompareTransactions(t, trnsM, trnsM_reset) // sleep until past the original deadline - time.Sleep(time.Millisecond * 2) + time.Sleep(time.Millisecond * 200) // verify that trnsM still exists trnsM_again := mustGet(t, tm, "m") diff --git a/tx.go b/tx.go new file mode 100644 index 000000000..b8b74d427 --- /dev/null +++ b/tx.go @@ -0,0 +1,433 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 pilosa + +import ( + "fmt" + "sync" + + "github.com/pilosa/pilosa/v2/roaring" + "github.com/pkg/errors" +) + +type Tx interface { + Rollback() error + Commit() error + + RoaringBitmap(index, field, view string, shard uint64) (*roaring.Bitmap, error) + + Container(index, field, view string, shard uint64, key uint64) (*roaring.Container, error) + PutContainer(index, field, view string, shard uint64, key uint64, c *roaring.Container) error + RemoveContainer(index, field, view string, shard uint64, key uint64) error + + Add(index, field, view string, shard uint64, a ...uint64) (changed bool, err error) + Remove(index, field, view string, shard uint64, a ...uint64) (changed bool, err error) + Contains(index, field, view string, shard uint64, v uint64) (exists bool, err error) + + ContainerIterator(index, field, view string, shard uint64, key uint64) (citer roaring.ContainerIterator, found bool, err error) + ForEach(index, field, view string, shard uint64, fn func(i uint64) error) error + ForEachRange(index, field, view string, shard uint64, start, end uint64, fn func(uint64) error) error + + Count(index, field, view string, shard uint64) (uint64, error) + Max(index, field, view string, shard uint64) (uint64, error) + Min(index, field, view string, shard uint64) (uint64, bool, error) + UnionInPlace(index, field, view string, shard uint64, others ...*roaring.Bitmap) error + CountRange(index, field, view string, shard uint64, start, end uint64) (uint64, error) + OffsetRange(index, field, view string, shard uint64, offset, start, end uint64) (*roaring.Bitmap, error) +} + +// MultiTx implements the transaction interface to combine multiple transactions. +type MultiTx struct { + mu sync.Mutex + writable bool + holder *Holder + index *Index + txs map[multiTxKey]Tx +} + +// NewMultiTx returns a new instance of MultiTx for a Holder. +func NewMultiTx(writable bool, holder *Holder) *MultiTx { + return &MultiTx{ + writable: writable, + holder: holder, + txs: make(map[multiTxKey]Tx), + } +} + +// NewMultiTxWithIndex returns a new instance of MultiTx for a single index. +func NewMultiTxWithIndex(writable bool, index *Index) *MultiTx { + return &MultiTx{ + writable: writable, + index: index, + txs: make(map[multiTxKey]Tx), + } +} + +var _ Tx = (*MultiTx)(nil) + +// Rollback rolls back all underlying transactions. +func (mtx *MultiTx) Rollback() (err error) { + for _, tx := range mtx.txs { + if e := tx.Rollback(); e != nil && err == nil { + err = e + } + } + return err +} + +// Commit commits all underlying transactions. +func (mtx *MultiTx) Commit() (err error) { + for _, tx := range mtx.txs { + if e := tx.Commit(); e != nil && err == nil { + err = e + } + } + return err +} + +func (mtx *MultiTx) RoaringBitmap(index, field, view string, shard uint64) (*roaring.Bitmap, error) { + tx, err := mtx.tx(index, shard) + if err != nil { + return nil, err + } + return tx.RoaringBitmap(index, field, view, shard) +} + +func (mtx *MultiTx) Container(index, field, view string, shard uint64, key uint64) (*roaring.Container, error) { + tx, err := mtx.tx(index, shard) + if err != nil { + return nil, err + } + return tx.Container(index, field, view, shard, key) +} + +func (mtx *MultiTx) PutContainer(index, field, view string, shard uint64, key uint64, c *roaring.Container) error { + tx, err := mtx.tx(index, shard) + if err != nil { + return err + } + return tx.PutContainer(index, field, view, shard, key, c) +} + +func (mtx *MultiTx) RemoveContainer(index, field, view string, shard uint64, key uint64) error { + tx, err := mtx.tx(index, shard) + if err != nil { + return err + } + return tx.RemoveContainer(index, field, view, shard, key) +} + +func (mtx *MultiTx) Add(index, field, view string, shard uint64, a ...uint64) (changed bool, err error) { + tx, err := mtx.tx(index, shard) + if err != nil { + return false, err + } + return tx.Add(index, field, view, shard, a...) +} + +func (mtx *MultiTx) Remove(index, field, view string, shard uint64, a ...uint64) (changed bool, err error) { + tx, err := mtx.tx(index, shard) + if err != nil { + return false, err + } + return tx.Remove(index, field, view, shard, a...) +} + +func (mtx *MultiTx) Contains(index, field, view string, shard uint64, v uint64) (exists bool, err error) { + tx, err := mtx.tx(index, shard) + if err != nil { + return false, err + } + return tx.Contains(index, field, view, shard, v) +} + +func (mtx *MultiTx) ContainerIterator(index, field, view string, shard uint64, key uint64) (citer roaring.ContainerIterator, found bool, err error) { + tx, err := mtx.tx(index, shard) + if err != nil { + return nil, false, err + } + return tx.ContainerIterator(index, field, view, shard, key) +} + +func (mtx *MultiTx) ForEach(index, field, view string, shard uint64, fn func(i uint64) error) error { + tx, err := mtx.tx(index, shard) + if err != nil { + return err + } + return tx.ForEach(index, field, view, shard, fn) +} + +func (mtx *MultiTx) ForEachRange(index, field, view string, shard uint64, start, end uint64, fn func(uint64) error) error { + tx, err := mtx.tx(index, shard) + if err != nil { + return err + } + return tx.ForEachRange(index, field, view, shard, start, end, fn) +} + +func (mtx *MultiTx) Count(index, field, view string, shard uint64) (uint64, error) { + tx, err := mtx.tx(index, shard) + if err != nil { + return 0, err + } + return tx.Count(index, field, view, shard) +} + +func (mtx *MultiTx) Max(index, field, view string, shard uint64) (uint64, error) { + tx, err := mtx.tx(index, shard) + if err != nil { + return 0, err + } + return tx.Max(index, field, view, shard) +} + +func (mtx *MultiTx) Min(index, field, view string, shard uint64) (uint64, bool, error) { + tx, err := mtx.tx(index, shard) + if err != nil { + return 0, false, err + } + return tx.Min(index, field, view, shard) +} + +func (mtx *MultiTx) UnionInPlace(index, field, view string, shard uint64, others ...*roaring.Bitmap) error { + tx, err := mtx.tx(index, shard) + if err != nil { + return err + } + return tx.UnionInPlace(index, field, view, shard, others...) +} + +func (mtx *MultiTx) CountRange(index, field, view string, shard uint64, start, end uint64) (uint64, error) { + tx, err := mtx.tx(index, shard) + if err != nil { + return 0, err + } + return tx.CountRange(index, field, view, shard, start, end) +} + +func (mtx *MultiTx) OffsetRange(index, field, view string, shard uint64, offset, start, end uint64) (*roaring.Bitmap, error) { + tx, err := mtx.tx(index, shard) + if err != nil { + return nil, err + } + return tx.OffsetRange(index, field, view, shard, offset, start, end) +} + +// tx returns a transaction by index/shard. Reuses transaction if already open. +// Otherwise begins a new transaction. +func (mtx *MultiTx) tx(index string, shard uint64) (_ Tx, err error) { + mtx.mu.Lock() + defer mtx.mu.Unlock() + + // Lookup transaction from cache. + tx := mtx.txs[multiTxKey{index, shard}] + if tx != nil { + return tx, nil + } + + // If transaction doesn't exist, lookup the index. + idx := mtx.index + if mtx.holder != nil { + if idx = mtx.holder.Index(index); idx == nil { + return nil, ErrIndexNotFound + } + } + + // Begin tranaction & cache it. + if tx, err = idx.Begin(mtx.writable, shard); err != nil { + return nil, err + } + mtx.txs[multiTxKey{index, shard}] = tx + + return tx, nil +} + +type multiTxKey struct { + index string + shard uint64 +} + +// RoaringTx represents a fake transaction object for Roaring storage. +type RoaringTx struct { + Index *Index + Field *Field + fragment *fragment +} + +// Rollback is a no-op as Roaring does not support transactions. +func (tx *RoaringTx) Rollback() error { + return nil +} + +// Commit is a no-op as Roaring does not support transactions. +func (tx *RoaringTx) Commit() error { + return nil +} + +func (tx *RoaringTx) RoaringBitmap(index, field, view string, shard uint64) (*roaring.Bitmap, error) { + return tx.bitmap(field, view, shard) +} + +func (tx *RoaringTx) Container(index, field, view string, shard uint64, key uint64) (*roaring.Container, error) { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return nil, err + } + return b.Containers.Get(key), nil +} + +func (tx *RoaringTx) PutContainer(index, field, view string, shard uint64, key uint64, c *roaring.Container) error { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return err + } + b.Containers.Put(key, c) + return nil +} + +func (tx *RoaringTx) RemoveContainer(index, field, view string, shard uint64, key uint64) error { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return err + } + b.Containers.Remove(key) + return nil +} + +func (tx *RoaringTx) Add(index, field, view string, shard uint64, a ...uint64) (changed bool, err error) { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return false, err + } + return b.Add(a...) +} + +func (tx *RoaringTx) Remove(index, field, view string, shard uint64, a ...uint64) (changed bool, err error) { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return false, err + } + return b.Remove(a...) +} + +func (tx *RoaringTx) Contains(index, field, view string, shard uint64, v uint64) (exists bool, err error) { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return false, err + } + return b.Contains(v), nil +} + +func (tx *RoaringTx) ContainerIterator(index, field, view string, shard uint64, key uint64) (citer roaring.ContainerIterator, found bool, err error) { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return nil, false, err + } + citer, found = b.Containers.Iterator(key) + return citer, found, nil +} + +func (tx *RoaringTx) ForEach(index, field, view string, shard uint64, fn func(i uint64) error) error { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return err + } + return b.ForEach(fn) +} + +func (tx *RoaringTx) ForEachRange(index, field, view string, shard uint64, start, end uint64, fn func(uint64) error) error { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return err + } + return b.ForEachRange(start, end, fn) +} + +func (tx *RoaringTx) Count(index, field, view string, shard uint64) (uint64, error) { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return 0, err + } + return b.Count(), nil +} + +func (tx *RoaringTx) Max(index, field, view string, shard uint64) (uint64, error) { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return 0, err + } + return b.Max(), nil +} + +func (tx *RoaringTx) Min(index, field, view string, shard uint64) (uint64, bool, error) { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return 0, false, err + } + v, ok := b.Min() + return v, ok, nil +} + +func (tx *RoaringTx) UnionInPlace(index, field, view string, shard uint64, others ...*roaring.Bitmap) error { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return err + } + b.UnionInPlace(others...) + return nil +} + +func (tx *RoaringTx) CountRange(index, field, view string, shard uint64, start, end uint64) (uint64, error) { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return 0, err + } + return b.CountRange(start, end), nil +} + +func (tx *RoaringTx) OffsetRange(index, field, view string, shard uint64, offset, start, end uint64) (*roaring.Bitmap, error) { + b, err := tx.bitmap(field, view, shard) + if err != nil { + return nil, err + } + return b.OffsetRange(offset, start, end), nil +} + +func (tx *RoaringTx) bitmap(field, view string, shard uint64) (*roaring.Bitmap, error) { + // If a fragment is attached, always use it. + if tx.fragment != nil { + return tx.fragment.storage, nil + } + + // If a field is attached, start from there. + // Otherwise look up the field from the index. + f := tx.Field + if f == nil { + if f = tx.Index.Field(field); f == nil { + return nil, ErrFieldNotFound + } + } + + v := f.view(view) + if v == nil { + return nil, errors.Errorf("view not found: %q", view) + } + + frag := v.Fragment(shard) + if frag == nil { + panic(fmt.Sprintf("fragment not found: %q / %q / %d", field, view, shard)) + } + return frag.storage, nil +} diff --git a/utils_internal_test.go b/utils_internal_test.go index 83751f4bf..386282adb 100644 --- a/utils_internal_test.go +++ b/utils_internal_test.go @@ -133,8 +133,21 @@ func (t *ClusterCluster) SetBit(index, field string, rowID, colID uint64, x *tim if f == nil { return fmt.Errorf("index/field does not exist: %s/%s", index, field) } - _, err := f.SetBit(rowID, colID, x) - if err != nil { + + if err := func() error { + tx, err := c.holder.Begin(true) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + + if _, err := f.SetBit(tx, rowID, colID, x); err != nil { + return err + } else if err := tx.Commit(); err != nil { + return err + } + return nil + }(); err != nil { return err } } diff --git a/version.go b/version.go index 4164dee32..8671d683f 100644 --- a/version.go +++ b/version.go @@ -14,15 +14,39 @@ package pilosa -var Enterprise = "0" -var EnterpriseEnabled = false -var Version = "v0.0.0" -var BuildTime = "not recorded" +import "time" -// init sets the EnterpriseEnabled bool, based on the Enterprise string. -// This is needed because bools cannot be set with ldflags. -func init() { // nolint: gochecknoinits - if Enterprise == "1" { - EnterpriseEnabled = true +var Version string +var Commit string +var Variant string +var BuildTime string + +func VersionInfo() string { + var prefix string + if Variant != "" { + prefix = Variant + " " } + var suffix string + if Version != "" { + suffix = " " + Version + } else { + suffix = " v2.x" + } + buildTime := BuildTime + if buildTime != "" { + // Normalize the build time into a friendly format in the user's time zone. + if t, err := time.Parse("2006-01-02T15:04:05+0000", BuildTime); err == nil { + buildTime = t.Local().Format("Jan _2 2006 3:04PM") + } + } + switch { + case Commit != "" && buildTime != "": + suffix += " (" + buildTime + ", " + Commit + ")" + case Commit != "": + suffix += " (" + Commit + ")" + case buildTime != "": + suffix += " (" + buildTime + ")" + } + + return prefix + "Pilosa" + suffix } diff --git a/view.go b/view.go index a851b8653..12210a619 100644 --- a/view.go +++ b/view.go @@ -26,7 +26,6 @@ import ( "sync/atomic" "time" - "github.com/pilosa/pilosa/v2/logger" "github.com/pilosa/pilosa/v2/pql" "github.com/pilosa/pilosa/v2/roaring" "github.com/pilosa/pilosa/v2/stats" @@ -43,11 +42,14 @@ const ( // view represents a container for field data. type view struct { - mu sync.RWMutex - path string - index string - field string - name string + mu sync.RWMutex + path string + index string + field string + name string + qualifiedName string + + holder *Holder fieldType string cacheType string @@ -56,23 +58,24 @@ type view struct { // Fragments by shard. fragments map[uint64]*fragment - broadcaster broadcaster - stats stats.StatsClient - rowAttrStore AttrStore - logger logger.Logger - snapshotQueue snapshotQueue + broadcaster broadcaster + stats stats.StatsClient + rowAttrStore AttrStore knownShards *roaring.Bitmap knownShardsCopied uint32 } // newView returns a new instance of View. -func newView(path, index, field, name string, fieldOptions FieldOptions) *view { +func newView(holder *Holder, path, index, field, name string, fieldOptions FieldOptions) *view { return &view{ - path: path, - index: index, - field: field, - name: name, + path: path, + index: index, + field: field, + name: name, + qualifiedName: FormatQualifiedViewName(index, field, name), + + holder: holder, fieldType: fieldOptions.Type, cacheType: fieldOptions.CacheType, @@ -82,7 +85,6 @@ func newView(path, index, field, name string, fieldOptions FieldOptions) *view { broadcaster: NopBroadcaster, stats: stats.NopStatsClient, - logger: logger.NopLogger, knownShards: roaring.NewSliceBitmap(), } } @@ -133,14 +135,14 @@ func (v *view) open() error { if err := func() error { // Ensure the view's path exists. - v.logger.Debugf("ensure view path exists: %s", v.path) + v.holder.Logger.Debugf("ensure view path exists: %s", v.path) if err := os.MkdirAll(v.path, 0777); err != nil { return errors.Wrap(err, "creating view directory") } else if err := os.MkdirAll(filepath.Join(v.path, "fragments"), 0777); err != nil { return errors.Wrap(err, "creating fragments directory") } - v.logger.Debugf("open fragments for index/field/view: %s/%s/%s", v.index, v.field, v.name) + v.holder.Logger.Debugf("open fragments for index/field/view: %s/%s/%s", v.index, v.field, v.name) if err := v.openFragments(); err != nil { return errors.Wrap(err, "opening fragments") } @@ -151,7 +153,7 @@ func (v *view) open() error { return err } - v.logger.Debugf("successfully opened index/field/view: %s/%s/%s", v.index, v.field, v.name) + v.holder.Logger.Debugf("successfully opened index/field/view: %s/%s/%s", v.index, v.field, v.name) return nil } @@ -190,12 +192,12 @@ fileLoop: // Parse filename into integer. shard, err := strconv.ParseUint(filepath.Base(fi.Name()), 10, 64) if err != nil { - v.logger.Debugf("WARNING: couldn't use non-integer file as shard in index/field/view %s/%s/%s: %s", v.index, v.field, v.name, fi.Name()) + v.holder.Logger.Debugf("WARNING: couldn't use non-integer file as shard in index/field/view %s/%s/%s: %s", v.index, v.field, v.name, fi.Name()) continue } workQueue <- struct{}{} - v.logger.Debugf("open index/field/view/fragment: %s/%s/%s/%d", v.index, v.field, v.name, shard) + v.holder.Logger.Debugf("open index/field/view/fragment: %s/%s/%s/%d", v.index, v.field, v.name, shard) eg.Go(func() error { defer func() { <-workQueue @@ -205,7 +207,7 @@ fileLoop: return fmt.Errorf("open fragment: shard=%d, err=%s", frag.shard, err) } frag.RowAttrStore = v.rowAttrStore - v.logger.Debugf("add index/field/view/fragment to view.fragments: %s/%s/%s/%d", v.index, v.field, v.name, shard) + v.holder.Logger.Debugf("add index/field/view/fragment to view.fragments: %s/%s/%s/%d", v.index, v.field, v.name, shard) mu.Lock() v.fragments[frag.shard] = frag v.addKnownShard(frag.shard) @@ -342,7 +344,7 @@ func (v *view) notifyIfNewShard(shard uint64) { // Broadcast a message that a new max shard was just created. err := v.broadcaster.SendSync(msg) if err != nil { - v.logger.Printf("broadcasting create shard: %v", err) + v.holder.Logger.Printf("broadcasting create shard: %v", err) } close(broadcastChan) }() @@ -352,19 +354,15 @@ func (v *view) notifyIfNewShard(shard uint64) { select { case <-broadcastChan: case <-time.After(50 * time.Millisecond): - v.logger.Debugf("broadcasting create shard took >50ms") + v.holder.Logger.Debugf("broadcasting create shard took >50ms") } } func (v *view) newFragment(path string, shard uint64) *fragment { - frag := newFragment(path, v.index, v.field, v.name, shard, v.flags()) + frag := newFragment(v.holder, path, v.index, v.field, v.name, shard, v.flags()) frag.CacheType = v.cacheType frag.CacheSize = v.cacheSize - frag.Logger = v.logger frag.stats = v.stats - if v.snapshotQueue != nil { - frag.snapshotQueue = v.snapshotQueue - } if v.fieldType == FieldTypeMutex { frag.mutexVector = newRowsVector(frag) } else if v.fieldType == FieldTypeBool { @@ -382,7 +380,7 @@ func (v *view) deleteFragment(shard uint64) error { return ErrFragmentNotFound } - v.logger.Printf("delete fragment: (%s/%s/%s) %d", v.index, v.field, v.name, shard) + v.holder.Logger.Printf("delete fragment: (%s/%s/%s) %d", v.index, v.field, v.name, shard) // Close data files before deletion. if err := fragment.Close(); err != nil { @@ -396,7 +394,7 @@ func (v *view) deleteFragment(shard uint64) error { // Delete fragment cache file. if err := os.Remove(fragment.cachePath()); err != nil { - v.logger.Printf("no cache file to delete for shard %d", shard) + v.holder.Logger.Printf("no cache file to delete for shard %d", shard) } delete(v.fragments, shard) @@ -406,130 +404,76 @@ func (v *view) deleteFragment(shard uint64) error { } // row returns a row for a shard of the view. -func (v *view) row(rowID uint64) *Row { +func (v *view) row(tx Tx, rowID uint64) (*Row, error) { row := NewRow() for _, frag := range v.allFragments() { - fr := frag.row(rowID) - if fr == nil { + fr, err := frag.row(tx, rowID) + if err != nil { + return nil, err + } else if fr == nil { continue } row.Merge(fr) } - return row + return row, nil } // setBit sets a bit within the view. -func (v *view) setBit(rowID, columnID uint64) (changed bool, err error) { +func (v *view) setBit(tx Tx, rowID, columnID uint64) (changed bool, err error) { shard := columnID / ShardWidth frag, err := v.CreateFragmentIfNotExists(shard) if err != nil { return changed, err } - return frag.setBit(rowID, columnID) + return frag.setBit(tx, rowID, columnID) } // clearBit clears a bit within the view. -func (v *view) clearBit(rowID, columnID uint64) (changed bool, err error) { +func (v *view) clearBit(tx Tx, rowID, columnID uint64) (changed bool, err error) { shard := columnID / ShardWidth frag := v.Fragment(shard) if frag == nil { return false, nil } - return frag.clearBit(rowID, columnID) + return frag.clearBit(tx, rowID, columnID) } // value uses a column of bits to read a multi-bit value. -func (v *view) value(columnID uint64, bitDepth uint) (value int64, exists bool, err error) { +func (v *view) value(tx Tx, columnID uint64, bitDepth uint) (value int64, exists bool, err error) { shard := columnID / ShardWidth frag, err := v.CreateFragmentIfNotExists(shard) if err != nil { return value, exists, err } - return frag.value(columnID, bitDepth) + return frag.value(tx, columnID, bitDepth) } // setValue uses a column of bits to set a multi-bit value. -func (v *view) setValue(columnID uint64, bitDepth uint, value int64) (changed bool, err error) { +func (v *view) setValue(tx Tx, columnID uint64, bitDepth uint, value int64) (changed bool, err error) { shard := columnID / ShardWidth frag, err := v.CreateFragmentIfNotExists(shard) if err != nil { return changed, err } - return frag.setValue(columnID, bitDepth, value) + return frag.setValue(tx, columnID, bitDepth, value) } // clearValue removes a specific value assigned to columnID -func (v *view) clearValue(columnID uint64, bitDepth uint, value int64) (changed bool, err error) { +func (v *view) clearValue(tx Tx, columnID uint64, bitDepth uint, value int64) (changed bool, err error) { shard := columnID / ShardWidth frag := v.Fragment(shard) if frag == nil { return false, nil } - return frag.clearValue(columnID, bitDepth, value) -} - -// sum returns the sum & count of a field. -func (v *view) sum(filter *Row, bitDepth uint) (sum int64, count uint64, err error) { - for _, f := range v.allFragments() { - fsum, fcount, err := f.sum(filter, bitDepth) - if err != nil { - return sum, count, err - } - sum += fsum - count += fcount - } - return sum, count, nil -} - -// min returns the min and count of a field. -func (v *view) min(filter *Row, bitDepth uint) (min int64, count uint64, err error) { - var minHasValue bool - for _, f := range v.allFragments() { - fmin, fcount, err := f.min(filter, bitDepth) - if err != nil { - return min, count, err - } - // Don't consider a min based on zero columns. - if fcount == 0 { - continue - } - - if !minHasValue { - min = fmin - minHasValue = true - count += fcount - continue - } - - if fmin < min { - min = fmin - count += fcount - } - } - return min, count, nil -} - -// max returns the max and count of a field. -func (v *view) max(filter *Row, bitDepth uint) (max int64, count uint64, err error) { - for _, f := range v.allFragments() { - fmax, fcount, err := f.max(filter, bitDepth) - if err != nil { - return max, count, err - } - if fcount > 0 && fmax > max { - max = fmax - count += fcount - } - } - return max, count, nil + return frag.clearValue(tx, columnID, bitDepth, value) } // rangeOp returns rows with a field value encoding matching the predicate. -func (v *view) rangeOp(op pql.Token, bitDepth uint, predicate int64) (*Row, error) { +func (v *view) rangeOp(tx Tx, op pql.Token, bitDepth uint, predicate int64) (*Row, error) { r := NewRow() for _, frag := range v.allFragments() { - other, err := frag.rangeOp(op, bitDepth, predicate) + other, err := frag.rangeOp(tx, op, bitDepth, predicate) if err != nil { return nil, err } @@ -570,3 +514,8 @@ type viewInfoSlice []*ViewInfo func (p viewInfoSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p viewInfoSlice) Len() int { return len(p) } func (p viewInfoSlice) Less(i, j int) bool { return p[i].Name < p[j].Name } + +// FormatQualifiedViewName generates a qualified name for the view to be used with Tx operations. +func FormatQualifiedViewName(index, field, view string) string { + return fmt.Sprintf("%s\x00%s\x00%s\x00", index, field, view) +} diff --git a/view_internal_test.go b/view_internal_test.go index bb50003d2..bbb1a20f4 100644 --- a/view_internal_test.go +++ b/view_internal_test.go @@ -34,7 +34,7 @@ func mustOpenView(index, field, name string) *view { CacheSize: DefaultCacheSize, } - v := newView(path, index, field, name, fo) + v := newView(NewHolder(DefaultPartitionN), path, index, field, name, fo) if err := v.open(); err != nil { panic(err) } diff --git a/xrbrsupport.go b/xrbrsupport.go new file mode 100644 index 000000000..b06d94cc5 --- /dev/null +++ b/xrbrsupport.go @@ -0,0 +1,100 @@ +// Copyright 2017 Pilosa Corp. +// +// 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 pilosa + +import ( + "fmt" + + "github.com/pilosa/pilosa/v2/rbf" + "github.com/pilosa/pilosa/v2/roaring" +) + +type Converter interface { + Convert(index, field, view string, shard uint64, rb *roaring.Bitmap) error + Shutdown() +} + +type RBFConverter struct { + Dbs map[string]*rbf.DB + Base string +} + +func (rbc *RBFConverter) GetOrCreateDB(index string, shard uint64) (*rbf.DB, error) { + key := fmt.Sprintf("%s/%d", index, shard) + db, found := rbc.Dbs[key] + if found { + return db, nil + } + path := rbc.Base + "/" + key + db = rbf.NewDB(path) + err := db.Open() + if err != nil { + return nil, err + } + rbc.Dbs[key] = db + return db, nil +} +func (rbc *RBFConverter) Shutdown() { + for key, db := range rbc.Dbs { + fmt.Println("Shutdown", key) + db.Close() + + } + +} +func (rbc *RBFConverter) Convert(index, field, view string, shard uint64, rb *roaring.Bitmap) error { + fmt.Println("CONVERT", index, field, view, shard) + db, err := rbc.GetOrCreateDB(index, shard) + if err != nil { + return err + } + tx, err := db.Begin(true) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + + name := fmt.Sprintf("%s/%s", field, view) + err = tx.CreateBitmap(name) + if err != nil { + return err + } + _, err = tx.AddRoaring(name, rb) + if err != nil { + return err + } + return tx.Commit() +} + +func (h *Holder) ConvertToRBF(c Converter) { + /* + for idxname, idx := range h.indexes { + for fieldName, field := range idx.fields { + for _, view := range field.views() { + for shard, fragment := range view.fragments { + panic("NEED bitmap from storage") + junk := roaring.NewBitmap() + err := c.Convert(idxname, fieldName, view.name, shard, junk) + if err != nil { + fmt.Println("ERR", err, fragment.shard) //just added shard for compile + } + } + } + + } + + } + c.Shutdown() + */ +}