Skip to content

Firestore: Optimize local cache sync when resuming a query that had docs deleted #7229

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 59 commits into from
Apr 19, 2023
Merged
Show file tree
Hide file tree
Changes from 55 commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
0ccea52
Update proto to include BloomFilter (#6780)
milaGGL Nov 15, 2022
dd8b061
Merge branch 'master' into mila/BloomFilter
milaGGL Nov 18, 2022
d6c5756
Merge branch 'master' into mila/BloomFilter
milaGGL Nov 23, 2022
a2c1c24
Merge branch 'master' into mila/BloomFilter
milaGGL Nov 29, 2022
c17af51
add BloomFilter class (#6795)
milaGGL Nov 30, 2022
a3fb711
Add bloom filter to existence filter and watchFilters spec builder (#…
milaGGL Nov 30, 2022
4bd34f1
Merge branch 'master' into mila/BloomFilter
milaGGL Dec 5, 2022
eaef9da
Merge branch 'master' into mila/BloomFilter
milaGGL Dec 13, 2022
036849f
Merge branch 'master' into mila/BloomFilter
milaGGL Jan 6, 2023
9e49b4c
Add expectedCount to Target in listen request (#6854)
milaGGL Jan 6, 2023
dd66835
Merge branch 'master' into mila/BloomFilter
milaGGL Jan 13, 2023
5335e7a
Merge branch 'master' into mila/BloomFilter
milaGGL Jan 26, 2023
333aac9
apply bloomFilter while handling existence filter mismatch (#6897)
milaGGL Jan 27, 2023
7e2f069
Merge branch 'master' into mila/BloomFilter
milaGGL Jan 27, 2023
c128eaa
Merge branch 'master' into mila/BloomFilter
milaGGL Feb 2, 2023
dee7744
add "no-ios", "no-android" to invalid base64 bitmap spec test case
milaGGL Feb 3, 2023
277f8e1
Optimize bloom filter application (#6992)
milaGGL Feb 9, 2023
d66f4ca
Merge branch 'master' into mila/BloomFilter
milaGGL Feb 9, 2023
dbed11f
Merge remote-tracking branch 'origin/master' into HEAD
dconeybe Feb 10, 2023
a3cd73d
base64.ts: tweak the comment about why we're doing custom base64 leng…
dconeybe Feb 10, 2023
839ccf7
Merge remote-tracking branch 'origin/master' into HEAD
dconeybe Feb 11, 2023
b7072d1
Merge branch 'master' into mila/BloomFilter
milaGGL Feb 16, 2023
97ca3ee
Mila/bloom filter add integration test (#7045)
milaGGL Feb 17, 2023
5bd6142
Merge remote-tracking branch 'origin/master' into HEAD
dconeybe Feb 23, 2023
7b410e6
skip the integration test when using emulator
milaGGL Feb 24, 2023
8a5faad
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Feb 28, 2023
65e5452
Fix `expectedCount` encoding in grpc (#7087)
dconeybe Mar 3, 2023
a4ee560
Merge remote-tracking branch 'origin/master' into HEAD
dconeybe Mar 7, 2023
465e8df
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Mar 9, 2023
5c2ec00
Add 'existence-filter-mismatch-bloom' to listen request labels and te…
milaGGL Mar 9, 2023
7c20d7d
Update the integration test to verify that bloom filter averted full …
dconeybe Mar 10, 2023
272a6a6
Merge branch 'master' into mila/BloomFilter
milaGGL Mar 11, 2023
519c1ef
fix bloom filter specs
milaGGL Mar 11, 2023
a0e0432
Cleanup and improvements to the "complex" bloom filter integration te…
dconeybe Mar 16, 2023
e2afbf8
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Mar 17, 2023
a936b02
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Mar 20, 2023
ea44722
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Mar 24, 2023
e043119
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Apr 4, 2023
4778c99
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Apr 7, 2023
e73c52b
md5_integer_size_delta.txt added [delete this file before merging int…
dconeybe Apr 7, 2023
fc0fa73
query.test.ts: Remove check for `TARGET_BACKEND !== 'nightly'` since …
dconeybe Apr 11, 2023
9a5877f
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Apr 12, 2023
a3c7bb3
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Apr 14, 2023
5d907b8
Remove temp file md5_integer_size_delta.txt
dconeybe Apr 14, 2023
67c34c3
Merge branch 'master' into mila/BloomFilter
milaGGL Apr 14, 2023
85d3604
add changeset
milaGGL Apr 14, 2023
256cb3e
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Apr 17, 2023
bbc1944
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Apr 18, 2023
f6ef44c
[no ci]
dconeybe Apr 18, 2023
a3ccdeb
Format bloom filter golden test JSON files with prettier
dconeybe Apr 18, 2023
f30c45f
.changeset/swift-eels-change.md: update
dconeybe Apr 18, 2023
0c74eb0
Remove no-longer-needed exports of TargetBackend and TARGET_BACKEND
dconeybe Apr 18, 2023
c238fd2
bloom_filter_golden_test_data/README.md added
dconeybe Apr 18, 2023
b8066f1
Disable bloom filter spec tests on android and ios; enable them once …
dconeybe Apr 18, 2023
7681f05
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Apr 18, 2023
93dedd1
Further tweak the change log entry
dconeybe Apr 18, 2023
80fc46d
Merge remote-tracking branch 'origin/master' into mila/BloomFilter
dconeybe Apr 19, 2023
f795005
listen_spec.test.ts: withGCEnabled(false) -> ensureManualLruGC()
dconeybe Apr 19, 2023
787d523
Further tweak change log
dconeybe Apr 19, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/swift-eels-change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@firebase/webchannel-wrapper': minor
'@firebase/firestore': minor
'firebase': minor
---

Optimize local cache synchronization when resuming a query where documents were deleted on the server.
2 changes: 1 addition & 1 deletion packages/firestore/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"dev": "rollup -c -w",
"lint": "eslint -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'",
"lint:fix": "eslint --fix -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'",
"prettier": "prettier --write '*.js' '@(lite|src|test)/**/*.ts'",
"prettier": "prettier --write '*.js' '@(lite|src|test)/**/*.ts' 'test/unit/remote/bloom_filter_golden_test_data/*.json'",
"test:lite": "ts-node ./scripts/run-tests.ts --emulator --platform node_lite --main=lite/index.ts 'test/lite/**/*.test.ts'",
"test:lite:prod": "ts-node ./scripts/run-tests.ts --platform node_lite --main=lite/index.ts 'test/lite/**/*.test.ts'",
"test:lite:browser": "karma start --single-run --lite",
Expand Down
12 changes: 7 additions & 5 deletions packages/firestore/src/core/sync_engine_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ import { primitiveComparator } from '../util/misc';
import { ObjectMap } from '../util/obj_map';
import { Deferred } from '../util/promise';
import { SortedMap } from '../util/sorted_map';
import { SortedSet } from '../util/sorted_set';
import { BATCHID_UNKNOWN } from '../util/types';

import {
Expand Down Expand Up @@ -316,9 +315,6 @@ export async function syncEngineListen(
syncEngineImpl.localStore,
queryToTarget(query)
);
if (syncEngineImpl.isPrimaryClient) {
remoteStoreListen(syncEngineImpl.remoteStore, targetData);
}

const status = syncEngineImpl.sharedClientState.addLocalQueryTarget(
targetData.targetId
Expand All @@ -331,6 +327,10 @@ export async function syncEngineListen(
status === 'current',
targetData.resumeToken
);

if (syncEngineImpl.isPrimaryClient) {
remoteStoreListen(syncEngineImpl.remoteStore, targetData);
}
}

return viewSnapshot;
Expand Down Expand Up @@ -638,7 +638,9 @@ export async function syncEngineRejectListen(
const event = new RemoteEvent(
SnapshotVersion.min(),
/* targetChanges= */ new Map<TargetId, TargetChange>(),
/* targetMismatches= */ new SortedSet<TargetId>(primitiveComparator),
/* targetMismatches= */ new SortedMap<TargetId, TargetPurpose>(
primitiveComparator
),
documentUpdates,
resolvedLimboDocuments
);
Expand Down
2 changes: 1 addition & 1 deletion packages/firestore/src/local/local_store_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,7 @@ export function localStoreApplyRemoteEventToLocalCache(
let newTargetData = oldTargetData.withSequenceNumber(
txn.currentSequenceNumber
);
if (remoteEvent.targetMismatches.has(targetId)) {
if (remoteEvent.targetMismatches.get(targetId) !== null) {
newTargetData = newTargetData
.withResumeToken(
ByteString.EMPTY_BYTE_STRING,
Expand Down
42 changes: 37 additions & 5 deletions packages/firestore/src/local/target_data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,17 @@ export const enum TargetPurpose {
Listen,

/**
* The query target was used to refill a query after an existence filter mismatch.
* The query target was used to refill a query after an existence filter
* mismatch.
*/
ExistenceFilterMismatch,

/**
* The query target was used if the query is the result of a false positive in
* the bloom filter.
*/
ExistenceFilterMismatchBloom,

/** The query target was used to resolve a limbo document. */
LimboResolution
}
Expand Down Expand Up @@ -66,7 +73,13 @@ export class TargetData {
* matches the target. The resume token essentially identifies a point in
* time from which the server should resume sending results.
*/
readonly resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING
readonly resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,
/**
* The number of documents that last matched the query at the resume token or
* read time. Documents are counted only when making a listen request with
* resume token or read time, otherwise, keep it null.
*/
readonly expectedCount: number | null = null
) {}

/** Creates a new target data instance with an updated sequence number. */
Expand All @@ -78,7 +91,8 @@ export class TargetData {
sequenceNumber,
this.snapshotVersion,
this.lastLimboFreeSnapshotVersion,
this.resumeToken
this.resumeToken,
this.expectedCount
);
}

Expand All @@ -97,7 +111,24 @@ export class TargetData {
this.sequenceNumber,
snapshotVersion,
this.lastLimboFreeSnapshotVersion,
resumeToken
resumeToken,
/* expectedCount= */ null
);
}

/**
* Creates a new target data instance with an updated expected count.
*/
withExpectedCount(expectedCount: number): TargetData {
return new TargetData(
this.target,
this.targetId,
this.purpose,
this.sequenceNumber,
this.snapshotVersion,
this.lastLimboFreeSnapshotVersion,
this.resumeToken,
expectedCount
);
}

Expand All @@ -115,7 +146,8 @@ export class TargetData {
this.sequenceNumber,
this.snapshotVersion,
lastLimboFreeSnapshotVersion,
this.resumeToken
this.resumeToken,
this.expectedCount
);
}
}
11 changes: 11 additions & 0 deletions packages/firestore/src/protos/firestore_proto_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,15 @@ export declare namespace firestoreV1ApiClientInterfaces {
interface ExistenceFilter {
targetId?: number;
count?: number;
unchangedNames?: BloomFilter;
}
interface BloomFilter {
bits?: BitSequence;
hashCount?: number;
}
interface BitSequence {
bitmap?: string | Uint8Array;
padding?: number;
}
interface FieldFilter {
field?: FieldReference;
Expand Down Expand Up @@ -390,6 +399,7 @@ export declare namespace firestoreV1ApiClientInterfaces {
readTime?: Timestamp;
targetId?: number;
once?: boolean;
expectedCount?: number | { value: number };
}
interface TargetChange {
targetChangeType?: TargetChangeTargetChangeType;
Expand Down Expand Up @@ -454,6 +464,7 @@ export declare type BeginTransactionRequest =
firestoreV1ApiClientInterfaces.BeginTransactionRequest;
export declare type BeginTransactionResponse =
firestoreV1ApiClientInterfaces.BeginTransactionResponse;
export declare type BloomFilter = firestoreV1ApiClientInterfaces.BloomFilter;
export declare type CollectionSelector =
firestoreV1ApiClientInterfaces.CollectionSelector;
export declare type CommitRequest =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Copyright 2022 Google LLC
//
// 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.

syntax = "proto3";

package google.firestore.v1;

option csharp_namespace = "Google.Cloud.Firestore.V1";
option go_package = "google.golang.org/genproto/googleapis/firestore/v1;firestore";
option java_multiple_files = true;
option java_outer_classname = "BloomFilterProto";
option java_package = "com.google.firestore.v1";
option objc_class_prefix = "GCFS";
option php_namespace = "Google\\Cloud\\Firestore\\V1";
option ruby_package = "Google::Cloud::Firestore::V1";

// A sequence of bits, encoded in a byte array.
//
// Each byte in the `bitmap` byte array stores 8 bits of the sequence. The only
// exception is the last byte, which may store 8 _or fewer_ bits. The `padding`
// defines the number of bits of the last byte to be ignored as "padding". The
// values of these "padding" bits are unspecified and must be ignored.
//
// To retrieve the first bit, bit 0, calculate: (bitmap[0] & 0x01) != 0.
// To retrieve the second bit, bit 1, calculate: (bitmap[0] & 0x02) != 0.
// To retrieve the third bit, bit 2, calculate: (bitmap[0] & 0x04) != 0.
// To retrieve the fourth bit, bit 3, calculate: (bitmap[0] & 0x08) != 0.
// To retrieve bit n, calculate: (bitmap[n / 8] & (0x01 << (n % 8))) != 0.
//
// The "size" of a `BitSequence` (the number of bits it contains) is calculated
// by this formula: (bitmap.length * 8) - padding.
message BitSequence {
// The bytes that encode the bit sequence.
// May have a length of zero.
bytes bitmap = 1;

// The number of bits of the last byte in `bitmap` to ignore as "padding".
// If the length of `bitmap` is zero, then this value must be 0.
// Otherwise, this value must be between 0 and 7, inclusive.
int32 padding = 2;
}

// A bloom filter (https://en.wikipedia.org/wiki/Bloom_filter).
//
// The bloom filter hashes the entries with MD5 and treats the resulting 128-bit
// hash as 2 distinct 64-bit hash values, interpreted as unsigned integers
// using 2's complement encoding.
//
// These two hash values, named h1 and h2, are then used to compute the
// `hash_count` hash values using the formula, starting at i=0:
//
// h(i) = h1 + (i * h2)
//
// These resulting values are then taken modulo the number of bits in the bloom
// filter to get the bits of the bloom filter to test for the given entry.
message BloomFilter {
// The bloom filter data.
BitSequence bits = 1;

// The number of hashes used by the algorithm.
int32 hash_count = 2;
}
10 changes: 10 additions & 0 deletions packages/firestore/src/protos/google/firestore/v1/firestore.proto
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import "google/firestore/v1/query.proto";
import "google/firestore/v1/write.proto";
import "google/protobuf/empty.proto";
import "google/protobuf/timestamp.proto";
import "google/protobuf/wrappers.proto";
import "google/rpc/status.proto";

option csharp_namespace = "Google.Cloud.Firestore.V1";
Expand Down Expand Up @@ -857,6 +858,15 @@ message Target {

// If the target should be removed once it is current and consistent.
bool once = 6;

// The number of documents that last matched the query at the resume token or
// read time.
//
// This value is only relevant when a `resume_type` is provided. This value
// being present and greater than zero signals that the client wants
// `ExistenceFilter.unchanged_names` to be included in the response.
//
google.protobuf.Int32Value expected_count = 12;
}

// Targets being watched have changed.
Expand Down
15 changes: 15 additions & 0 deletions packages/firestore/src/protos/google/firestore/v1/write.proto
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ syntax = "proto3";

package google.firestore.v1;

import "google/firestore/v1/bloom_filter.proto";
import "google/firestore/v1/common.proto";
import "google/firestore/v1/document.proto";
import "google/protobuf/timestamp.proto";
Expand Down Expand Up @@ -261,4 +262,18 @@ message ExistenceFilter {
// If different from the count of documents in the client that match, the
// client must manually determine which documents no longer match the target.
int32 count = 2;

// A bloom filter that contains the UTF-8 byte encodings of the resource names
// of the documents that match [target_id][google.firestore.v1.ExistenceFilter.target_id], in the
// form `projects/{project_id}/databases/{database_id}/documents/{document_path}`
// that have NOT changed since the query results indicated by the resume token
// or timestamp given in `Target.resume_type`.
//
// This bloom filter may be omitted at the server's discretion, such as if it
// is deemed that the client will not make use of it or if it is too
// computationally expensive to calculate or transmit. Clients must gracefully
// handle this field being absent by falling back to the logic used before
// this field existed; that is, re-add the target without a resume token to
// figure out which documents in the client's cache are out of sync.
BloomFilter unchanged_names = 3;
}
32 changes: 32 additions & 0 deletions packages/firestore/src/protos/protos.json
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,30 @@
}
}
},
"BitSequence": {
"fields": {
"bitmap": {
"type": "bytes",
"id": 1
},
"padding": {
"type": "int32",
"id": 2
}
}
},
"BloomFilter": {
"fields": {
"bits": {
"type": "BitSequence",
"id": 1
},
"hashCount": {
"type": "int32",
"id": 2
}
}
},
"DocumentMask": {
"fields": {
"fieldPaths": {
Expand Down Expand Up @@ -2052,6 +2076,10 @@
"once": {
"type": "bool",
"id": 6
},
"expectedCount": {
"type": "google.protobuf.Int32Value",
"id": 12
}
},
"nested": {
Expand Down Expand Up @@ -2660,6 +2688,10 @@
"count": {
"type": "int32",
"id": 2
},
"unchangedNames": {
"type": "BloomFilter",
"id": 3
}
}
}
Expand Down
Loading