FSTLRUGarbageCollectorTests.mm 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. /*
  2. * Copyright 2018 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "Firestore/Example/Tests/Local/FSTLRUGarbageCollectorTests.h"
  17. #import <XCTest/XCTest.h>
  18. #include <unordered_set>
  19. #import "FIRTimestamp.h"
  20. #import "Firestore/Example/Tests/Util/FSTHelpers.h"
  21. #import "Firestore/Source/Local/FSTLRUGarbageCollector.h"
  22. #import "Firestore/Source/Local/FSTMutationQueue.h"
  23. #import "Firestore/Source/Local/FSTPersistence.h"
  24. #import "Firestore/Source/Model/FSTDocument.h"
  25. #import "Firestore/Source/Model/FSTFieldValue.h"
  26. #import "Firestore/Source/Model/FSTMutation.h"
  27. #import "Firestore/Source/Util/FSTClasses.h"
  28. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  29. #include "Firestore/core/src/firebase/firestore/local/query_cache.h"
  30. #include "Firestore/core/src/firebase/firestore/local/reference_set.h"
  31. #include "Firestore/core/src/firebase/firestore/local/remote_document_cache.h"
  32. #include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
  33. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  34. #include "Firestore/core/src/firebase/firestore/model/types.h"
  35. #include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
  36. #include "absl/strings/str_cat.h"
  37. namespace testutil = firebase::firestore::testutil;
  38. using firebase::firestore::auth::User;
  39. using firebase::firestore::local::LruParams;
  40. using firebase::firestore::local::LruResults;
  41. using firebase::firestore::local::QueryCache;
  42. using firebase::firestore::local::ReferenceSet;
  43. using firebase::firestore::local::RemoteDocumentCache;
  44. using firebase::firestore::model::DocumentKey;
  45. using firebase::firestore::model::DocumentKeyHash;
  46. using firebase::firestore::model::DocumentKeySet;
  47. using firebase::firestore::model::ListenSequenceNumber;
  48. using firebase::firestore::model::Precondition;
  49. using firebase::firestore::model::TargetId;
  50. NS_ASSUME_NONNULL_BEGIN
  51. @implementation FSTLRUGarbageCollectorTests {
  52. TargetId _previousTargetID;
  53. int _previousDocNum;
  54. FSTObjectValue *_testValue;
  55. FSTObjectValue *_bigObjectValue;
  56. id<FSTPersistence> _persistence;
  57. QueryCache *_queryCache;
  58. RemoteDocumentCache *_documentCache;
  59. id<FSTMutationQueue> _mutationQueue;
  60. id<FSTLRUDelegate> _lruDelegate;
  61. FSTLRUGarbageCollector *_gc;
  62. ListenSequenceNumber _initialSequenceNumber;
  63. User _user;
  64. ReferenceSet _additionalReferences;
  65. }
  66. - (void)setUp {
  67. [super setUp];
  68. _previousTargetID = 500;
  69. _previousDocNum = 10;
  70. _testValue = FSTTestObjectValue(@{@"baz" : @YES, @"ok" : @"fine"});
  71. NSString *bigString = [@"" stringByPaddingToLength:4096 withString:@"a" startingAtIndex:0];
  72. _bigObjectValue = FSTTestObjectValue(@{@"BigProperty" : bigString});
  73. _user = User("user");
  74. }
  75. - (BOOL)isTestBaseClass {
  76. return ([self class] == [FSTLRUGarbageCollectorTests class]);
  77. }
  78. - (void)newTestResourcesWithLruParams:(LruParams)lruParams {
  79. HARD_ASSERT(_persistence == nil, "Persistence already created");
  80. _persistence = [self newPersistenceWithLruParams:lruParams];
  81. [_persistence.referenceDelegate addInMemoryPins:&_additionalReferences];
  82. _queryCache = [_persistence queryCache];
  83. _documentCache = [_persistence remoteDocumentCache];
  84. _mutationQueue = [_persistence mutationQueueForUser:_user];
  85. _lruDelegate = (id<FSTLRUDelegate>)_persistence.referenceDelegate;
  86. _initialSequenceNumber = _persistence.run("start querycache", [&]() -> ListenSequenceNumber {
  87. [_mutationQueue start];
  88. _gc = _lruDelegate.gc;
  89. return _persistence.currentSequenceNumber;
  90. });
  91. }
  92. - (void)newTestResources {
  93. [self newTestResourcesWithLruParams:LruParams::Default()];
  94. }
  95. - (id<FSTPersistence>)newPersistenceWithLruParams:(LruParams)lruParams {
  96. @throw FSTAbstractMethodException(); // NOLINT
  97. }
  98. - (BOOL)sentinelExists:(const DocumentKey &)key {
  99. @throw FSTAbstractMethodException(); // NOLINT
  100. }
  101. - (void)expectSentinelRemoved:(const DocumentKey &)key {
  102. XCTAssertFalse([self sentinelExists:key]);
  103. }
  104. #pragma mark - helpers
  105. - (ListenSequenceNumber)sequenceNumberForQueryCount:(int)queryCount {
  106. return _persistence.run(
  107. "gc", [&]() -> ListenSequenceNumber { return [_gc sequenceNumberForQueryCount:queryCount]; });
  108. }
  109. - (int)queryCountForPercentile:(int)percentile {
  110. return _persistence.run("query count",
  111. [&]() -> int { return [_gc queryCountForPercentile:percentile]; });
  112. }
  113. - (int)removeQueriesThroughSequenceNumber:(ListenSequenceNumber)sequenceNumber
  114. liveQueries:(NSDictionary<NSNumber *, FSTQueryData *> *)liveQueries {
  115. return _persistence.run("gc", [&]() -> int {
  116. return [_gc removeQueriesUpThroughSequenceNumber:sequenceNumber liveQueries:liveQueries];
  117. });
  118. }
  119. // Removes documents that are not part of a target or a mutation and have a sequence number
  120. // less than or equal to the given sequence number.
  121. - (int)removeOrphanedDocumentsThroughSequenceNumber:(ListenSequenceNumber)sequenceNumber {
  122. return _persistence.run("gc", [&]() -> int {
  123. return [_gc removeOrphanedDocumentsThroughSequenceNumber:sequenceNumber];
  124. });
  125. }
  126. - (FSTQueryData *)nextTestQuery {
  127. TargetId targetID = ++_previousTargetID;
  128. ListenSequenceNumber listenSequenceNumber = _persistence.currentSequenceNumber;
  129. FSTQuery *query = FSTTestQuery(absl::StrCat("path", targetID));
  130. return [[FSTQueryData alloc] initWithQuery:query
  131. targetID:targetID
  132. listenSequenceNumber:listenSequenceNumber
  133. purpose:FSTQueryPurposeListen];
  134. }
  135. - (FSTQueryData *)addNextQueryInTransaction {
  136. FSTQueryData *queryData = [self nextTestQuery];
  137. _queryCache->AddTarget(queryData);
  138. return queryData;
  139. }
  140. - (void)updateTargetInTransaction:(FSTQueryData *)queryData {
  141. NSData *token = [@"hello" dataUsingEncoding:NSUTF8StringEncoding];
  142. FSTQueryData *updated =
  143. [queryData queryDataByReplacingSnapshotVersion:queryData.snapshotVersion
  144. resumeToken:token
  145. sequenceNumber:_persistence.currentSequenceNumber];
  146. _queryCache->UpdateTarget(updated);
  147. }
  148. - (FSTQueryData *)addNextQuery {
  149. return _persistence.run("adding query",
  150. [&]() -> FSTQueryData * { return [self addNextQueryInTransaction]; });
  151. }
  152. // Simulates a document being mutated and then having that mutation ack'd.
  153. // Since the document is not in a mutation queue any more, there is
  154. // potentially nothing keeping it live. We mark it with the current sequence number
  155. // so it can be collected later.
  156. - (DocumentKey)markADocumentEligibleForGC {
  157. DocumentKey key = [self nextTestDocKey];
  158. [self markDocumentEligibleForGC:key];
  159. return key;
  160. }
  161. - (void)markDocumentEligibleForGC:(const DocumentKey &)docKey {
  162. _persistence.run("Removing mutation reference",
  163. [&]() { [self markDocumentEligibleForGCInTransaction:docKey]; });
  164. }
  165. - (DocumentKey)markADocumentEligibleForGCInTransaction {
  166. DocumentKey key = [self nextTestDocKey];
  167. [self markDocumentEligibleForGCInTransaction:key];
  168. return key;
  169. }
  170. - (void)markDocumentEligibleForGCInTransaction:(const DocumentKey &)docKey {
  171. [_persistence.referenceDelegate removeMutationReference:docKey];
  172. }
  173. - (void)addDocument:(const DocumentKey &)docKey toTarget:(TargetId)targetId {
  174. _queryCache->AddMatchingKeys(DocumentKeySet{docKey}, targetId);
  175. }
  176. - (void)removeDocument:(const DocumentKey &)docKey fromTarget:(TargetId)targetId {
  177. _queryCache->RemoveMatchingKeys(DocumentKeySet{docKey}, targetId);
  178. }
  179. /**
  180. * Used to insert a document into the remote document cache. Use of this method should
  181. * be paired with some explanation for why it is in the cache, for instance:
  182. * - added to a target
  183. * - now has or previously had a pending mutation
  184. */
  185. - (FSTDocument *)cacheADocumentInTransaction {
  186. FSTDocument *doc = [self nextTestDocument];
  187. _documentCache->Add(doc);
  188. return doc;
  189. }
  190. - (FSTSetMutation *)mutationForDocument:(const DocumentKey &)docKey {
  191. return [[FSTSetMutation alloc] initWithKey:docKey
  192. value:_testValue
  193. precondition:Precondition::None()];
  194. }
  195. - (DocumentKey)nextTestDocKey {
  196. return testutil::Key("docs/doc_" + std::to_string(++_previousDocNum));
  197. }
  198. - (FSTDocument *)nextTestDocumentWithValue:(FSTObjectValue *)value {
  199. DocumentKey key = [self nextTestDocKey];
  200. FSTTestSnapshotVersion version = 2;
  201. return [FSTDocument documentWithData:value
  202. key:key
  203. version:testutil::Version(version)
  204. state:FSTDocumentStateSynced];
  205. }
  206. - (FSTDocument *)nextTestDocument {
  207. return [self nextTestDocumentWithValue:_testValue];
  208. }
  209. #pragma mark - tests
  210. - (void)testPickSequenceNumberPercentile {
  211. if ([self isTestBaseClass]) return;
  212. const int numTestCases = 5;
  213. struct Case {
  214. // number of queries to cache
  215. int queries;
  216. // number expected to be calculated as 10%
  217. int expected;
  218. };
  219. struct Case testCases[numTestCases] = {{0, 0}, {10, 1}, {9, 0}, {50, 5}, {49, 4}};
  220. for (int i = 0; i < numTestCases; i++) {
  221. // Fill the query cache.
  222. int numQueries = testCases[i].queries;
  223. int expectedTenthPercentile = testCases[i].expected;
  224. [self newTestResources];
  225. for (int j = 0; j < numQueries; j++) {
  226. [self addNextQuery];
  227. }
  228. int tenth = [self queryCountForPercentile:10];
  229. XCTAssertEqual(expectedTenthPercentile, tenth, @"Total query count: %i", numQueries);
  230. [_persistence shutdown];
  231. _persistence = nil;
  232. }
  233. }
  234. - (void)testSequenceNumberNoQueries {
  235. if ([self isTestBaseClass]) return;
  236. // No queries... should get invalid sequence number (-1)
  237. [self newTestResources];
  238. XCTAssertEqual(kFSTListenSequenceNumberInvalid, [self sequenceNumberForQueryCount:0]);
  239. [_persistence shutdown];
  240. }
  241. - (void)testSequenceNumberForFiftyQueries {
  242. if ([self isTestBaseClass]) return;
  243. // Add 50 queries sequentially, aim to collect 10 of them.
  244. // The sequence number to collect should be 10 past the initial sequence number.
  245. [self newTestResources];
  246. for (int i = 0; i < 50; i++) {
  247. [self addNextQuery];
  248. }
  249. XCTAssertEqual(_initialSequenceNumber + 10, [self sequenceNumberForQueryCount:10]);
  250. [_persistence shutdown];
  251. }
  252. - (void)testSequenceNumberForMultipleQueriesInATransaction {
  253. if ([self isTestBaseClass]) return;
  254. // 50 queries, 9 with one transaction, incrementing from there. Should get second sequence number.
  255. [self newTestResources];
  256. _persistence.run("9 queries in a batch", [&]() {
  257. for (int i = 0; i < 9; i++) {
  258. [self addNextQueryInTransaction];
  259. }
  260. });
  261. for (int i = 9; i < 50; i++) {
  262. [self addNextQuery];
  263. }
  264. XCTAssertEqual(2 + _initialSequenceNumber, [self sequenceNumberForQueryCount:10]);
  265. [_persistence shutdown];
  266. }
  267. // Ensure that even if all of the queries are added in a single transaction, we still
  268. // pick a sequence number and GC. In this case, the initial transaction contains all of the
  269. // targets that will get GC'd, since they account for more than the first 10 targets.
  270. - (void)testAllCollectedQueriesInSingleTransaction {
  271. if ([self isTestBaseClass]) return;
  272. // 50 queries, 11 with one transaction, incrementing from there. Should get first sequence number.
  273. [self newTestResources];
  274. _persistence.run("11 queries in a transaction", [&]() {
  275. for (int i = 0; i < 11; i++) {
  276. [self addNextQueryInTransaction];
  277. }
  278. });
  279. for (int i = 11; i < 50; i++) {
  280. [self addNextQuery];
  281. }
  282. // We expect to GC the targets from the first transaction, since they account for
  283. // at least the first 10 of the targets.
  284. XCTAssertEqual(1 + _initialSequenceNumber, [self sequenceNumberForQueryCount:10]);
  285. [_persistence shutdown];
  286. }
  287. - (void)testSequenceNumbersWithMutationAndSequentialQueries {
  288. if ([self isTestBaseClass]) return;
  289. // Remove a mutated doc reference, marking it as eligible for GC.
  290. // Then add 50 queries. Should get 10 past initial (9 queries).
  291. [self newTestResources];
  292. [self markADocumentEligibleForGC];
  293. for (int i = 0; i < 50; i++) {
  294. [self addNextQuery];
  295. }
  296. XCTAssertEqual(10 + _initialSequenceNumber, [self sequenceNumberForQueryCount:10]);
  297. [_persistence shutdown];
  298. }
  299. - (void)testSequenceNumbersWithMutationsInQueries {
  300. if ([self isTestBaseClass]) return;
  301. // Add mutated docs, then add one of them to a query target so it doesn't get GC'd.
  302. // Expect 3 past the initial value: the mutations not part of a query, and two queries
  303. [self newTestResources];
  304. FSTDocument *docInQuery = [self nextTestDocument];
  305. _persistence.run("mark mutations", [&]() {
  306. // Adding 9 doc keys in a transaction. If we remove one of them, we'll have room for two actual
  307. // queries.
  308. [self markDocumentEligibleForGCInTransaction:docInQuery.key];
  309. for (int i = 0; i < 8; i++) {
  310. [self markADocumentEligibleForGCInTransaction];
  311. }
  312. });
  313. for (int i = 0; i < 49; i++) {
  314. [self addNextQuery];
  315. }
  316. _persistence.run("query with mutation", [&]() {
  317. FSTQueryData *queryData = [self addNextQueryInTransaction];
  318. // This should keep the document from getting GC'd, since it is no longer orphaned.
  319. [self addDocument:docInQuery.key toTarget:queryData.targetID];
  320. });
  321. // This should catch the remaining 8 documents, plus the first two queries we added.
  322. XCTAssertEqual(3 + _initialSequenceNumber, [self sequenceNumberForQueryCount:10]);
  323. [_persistence shutdown];
  324. }
  325. - (void)testRemoveQueriesUpThroughSequenceNumber {
  326. if ([self isTestBaseClass]) return;
  327. [self newTestResources];
  328. NSMutableDictionary<NSNumber *, FSTQueryData *> *liveQueries = [[NSMutableDictionary alloc] init];
  329. for (int i = 0; i < 100; i++) {
  330. FSTQueryData *queryData = [self addNextQuery];
  331. // Mark odd queries as live so we can test filtering out live queries.
  332. if (queryData.targetID % 2 == 1) {
  333. liveQueries[@(queryData.targetID)] = queryData;
  334. }
  335. }
  336. // GC up through 20th query, which is 20%.
  337. // Expect to have GC'd 10 targets, since every other target is live
  338. int removed = [self removeQueriesThroughSequenceNumber:20 + _initialSequenceNumber
  339. liveQueries:liveQueries];
  340. XCTAssertEqual(10, removed);
  341. // Make sure we removed the even targets with targetID <= 20.
  342. _persistence.run("verify remaining targets are > 20 or odd", [&]() {
  343. _queryCache->EnumerateTargets(^(FSTQueryData *queryData, BOOL *stop) {
  344. XCTAssertTrue(queryData.targetID > 20 || queryData.targetID % 2 == 1);
  345. });
  346. });
  347. [_persistence shutdown];
  348. }
  349. - (void)testRemoveOrphanedDocuments {
  350. if ([self isTestBaseClass]) return;
  351. [self newTestResources];
  352. // Track documents we expect to be retained so we can verify post-GC.
  353. // This will contain documents associated with targets that survive GC, as well
  354. // as any documents with pending mutations.
  355. std::unordered_set<DocumentKey, DocumentKeyHash> expectedRetained;
  356. // we add two mutations later, for now track them in an array.
  357. NSMutableArray *mutations = [NSMutableArray arrayWithCapacity:2];
  358. // Add a target and add two documents to it. The documents are expected to be
  359. // retained, since their membership in the target keeps them alive.
  360. _persistence.run("add a target and add two documents to it", [&]() {
  361. // Add two documents to first target, queue a mutation on the second document
  362. FSTQueryData *queryData = [self addNextQueryInTransaction];
  363. FSTDocument *doc1 = [self cacheADocumentInTransaction];
  364. [self addDocument:doc1.key toTarget:queryData.targetID];
  365. expectedRetained.insert(doc1.key);
  366. FSTDocument *doc2 = [self cacheADocumentInTransaction];
  367. [self addDocument:doc2.key toTarget:queryData.targetID];
  368. expectedRetained.insert(doc2.key);
  369. [mutations addObject:[self mutationForDocument:doc2.key]];
  370. });
  371. // Add a second query and register a third document on it
  372. _persistence.run("second query", [&]() {
  373. FSTQueryData *queryData = [self addNextQueryInTransaction];
  374. FSTDocument *doc3 = [self cacheADocumentInTransaction];
  375. expectedRetained.insert(doc3.key);
  376. [self addDocument:doc3.key toTarget:queryData.targetID];
  377. });
  378. // cache another document and prepare a mutation on it.
  379. _persistence.run("queue a mutation", [&]() {
  380. FSTDocument *doc4 = [self cacheADocumentInTransaction];
  381. [mutations addObject:[self mutationForDocument:doc4.key]];
  382. expectedRetained.insert(doc4.key);
  383. });
  384. // Insert the mutations. These operations don't have a sequence number, they just
  385. // serve to keep the mutated documents from being GC'd while the mutations are outstanding.
  386. _persistence.run("actually register the mutations", [&]() {
  387. FIRTimestamp *writeTime = [FIRTimestamp timestamp];
  388. [_mutationQueue addMutationBatchWithWriteTime:writeTime mutations:mutations];
  389. });
  390. // Mark 5 documents eligible for GC. This simulates documents that were mutated then ack'd.
  391. // Since they were ack'd, they are no longer in a mutation queue, and there is nothing keeping
  392. // them alive.
  393. std::unordered_set<DocumentKey, DocumentKeyHash> toBeRemoved;
  394. _persistence.run("add orphaned docs (previously mutated, then ack'd)", [&]() {
  395. for (int i = 0; i < 5; i++) {
  396. FSTDocument *doc = [self cacheADocumentInTransaction];
  397. toBeRemoved.insert(doc.key);
  398. [self markDocumentEligibleForGCInTransaction:doc.key];
  399. }
  400. });
  401. // We expect only the orphaned documents, those not in a mutation or a target, to be
  402. // removed.
  403. // use a large sequence number to remove as much as possible
  404. int removed = [self removeOrphanedDocumentsThroughSequenceNumber:1000];
  405. XCTAssertEqual(toBeRemoved.size(), removed);
  406. _persistence.run("verify", [&]() {
  407. for (const DocumentKey &key : toBeRemoved) {
  408. XCTAssertNil(_documentCache->Get(key));
  409. XCTAssertFalse(_queryCache->Contains(key));
  410. }
  411. for (const DocumentKey &key : expectedRetained) {
  412. XCTAssertNotNil(_documentCache->Get(key), @"Missing document %s", key.ToString().c_str());
  413. }
  414. });
  415. [_persistence shutdown];
  416. }
  417. // TODO(gsoltis): write a test that includes limbo documents
  418. - (void)testRemoveTargetsThenGC {
  419. if ([self isTestBaseClass]) return;
  420. // Create 3 targets, add docs to all of them
  421. // Leave oldest target alone, it is still live
  422. // Remove newest target
  423. // Blind write 2 documents
  424. // Add one of the blind write docs to oldest target (preserves it)
  425. // Remove some documents from middle target (bumps sequence number)
  426. // Add some documents from newest target to oldest target (preserves them)
  427. // Update a doc from middle target
  428. // Remove middle target
  429. // Do a blind write
  430. // GC up to but not including the removal of the middle target
  431. //
  432. // Expect:
  433. // All docs in oldest target are still around
  434. // One blind write is gone, the first one not added to oldest target
  435. // Documents removed from middle target are gone, except ones added to oldest target
  436. // Documents from newest target are gone, except
  437. [self newTestResources];
  438. // Through the various steps, track which documents we expect to be removed vs
  439. // documents we expect to be retained.
  440. std::unordered_set<DocumentKey, DocumentKeyHash> expectedRetained;
  441. std::unordered_set<DocumentKey, DocumentKeyHash> expectedRemoved;
  442. // Add oldest target, 5 documents, and add those documents to the target.
  443. // This target will not be removed, so all documents that are part of it will
  444. // be retained.
  445. FSTQueryData *oldestTarget =
  446. _persistence.run("Add oldest target and docs", [&]() -> FSTQueryData * {
  447. FSTQueryData *queryData = [self addNextQueryInTransaction];
  448. for (int i = 0; i < 5; i++) {
  449. FSTDocument *doc = [self cacheADocumentInTransaction];
  450. expectedRetained.insert(doc.key);
  451. [self addDocument:doc.key toTarget:queryData.targetID];
  452. }
  453. return queryData;
  454. });
  455. // Add middle target and docs. Some docs will be removed from this target later,
  456. // which we track here.
  457. DocumentKeySet middleDocsToRemove;
  458. // This will be the document in this target that gets an update later
  459. DocumentKey middleDocToUpdate;
  460. FSTQueryData *middleTarget =
  461. _persistence.run("Add middle target and docs", [&]() -> FSTQueryData * {
  462. FSTQueryData *middleTarget = [self addNextQueryInTransaction];
  463. // these docs will be removed from this target later, triggering a bump
  464. // to their sequence numbers. Since they will not be a part of the target, we
  465. // expect them to be removed.
  466. for (int i = 0; i < 2; i++) {
  467. FSTDocument *doc = [self cacheADocumentInTransaction];
  468. expectedRemoved.insert(doc.key);
  469. [self addDocument:doc.key toTarget:middleTarget.targetID];
  470. middleDocsToRemove = middleDocsToRemove.insert(doc.key);
  471. }
  472. // these docs stay in this target and only this target. There presence in this
  473. // target prevents them from being GC'd, so they are also expected to be retained.
  474. for (int i = 2; i < 4; i++) {
  475. FSTDocument *doc = [self cacheADocumentInTransaction];
  476. expectedRetained.insert(doc.key);
  477. [self addDocument:doc.key toTarget:middleTarget.targetID];
  478. }
  479. // This doc stays in this target, but gets updated.
  480. {
  481. FSTDocument *doc = [self cacheADocumentInTransaction];
  482. expectedRetained.insert(doc.key);
  483. [self addDocument:doc.key toTarget:middleTarget.targetID];
  484. middleDocToUpdate = doc.key;
  485. }
  486. return middleTarget;
  487. });
  488. // Add the newest target and add 5 documents to it. Some of those documents will
  489. // additionally be added to the oldest target, which will cause those documents to
  490. // be retained. The remaining documents are expected to be removed, since this target
  491. // will be removed.
  492. DocumentKeySet newestDocsToAddToOldest;
  493. _persistence.run("Add newest target and docs", [&]() {
  494. FSTQueryData *newestTarget = [self addNextQueryInTransaction];
  495. // These documents are only in this target. They are expected to be removed
  496. // because this target will also be removed.
  497. for (int i = 0; i < 3; i++) {
  498. FSTDocument *doc = [self cacheADocumentInTransaction];
  499. expectedRemoved.insert(doc.key);
  500. [self addDocument:doc.key toTarget:newestTarget.targetID];
  501. }
  502. // docs to add to the oldest target in addition to this target. They will be retained
  503. for (int i = 3; i < 5; i++) {
  504. FSTDocument *doc = [self cacheADocumentInTransaction];
  505. expectedRetained.insert(doc.key);
  506. [self addDocument:doc.key toTarget:newestTarget.targetID];
  507. newestDocsToAddToOldest = newestDocsToAddToOldest.insert(doc.key);
  508. }
  509. });
  510. // 2 doc writes, add one of them to the oldest target.
  511. _persistence.run("2 doc writes, add one of them to the oldest target", [&]() {
  512. // write two docs and have them ack'd by the server. can skip mutation queue
  513. // and set them in document cache. Add potentially orphaned first, also add one
  514. // doc to a target.
  515. FSTDocument *doc1 = [self cacheADocumentInTransaction];
  516. [self markDocumentEligibleForGCInTransaction:doc1.key];
  517. [self updateTargetInTransaction:oldestTarget];
  518. [self addDocument:doc1.key toTarget:oldestTarget.targetID];
  519. // doc1 should be retained by being added to oldestTarget.
  520. expectedRetained.insert(doc1.key);
  521. FSTDocument *doc2 = [self cacheADocumentInTransaction];
  522. [self markDocumentEligibleForGCInTransaction:doc2.key];
  523. // nothing is keeping doc2 around, it should be removed
  524. expectedRemoved.insert(doc2.key);
  525. });
  526. // Remove some documents from the middle target.
  527. _persistence.run("Remove some documents from the middle target", [&]() {
  528. [self updateTargetInTransaction:middleTarget];
  529. for (const DocumentKey &docKey : middleDocsToRemove) {
  530. [self removeDocument:docKey fromTarget:middleTarget.targetID];
  531. }
  532. });
  533. // Add a couple docs from the newest target to the oldest (preserves them past the point where
  534. // newest was removed)
  535. // upperBound is the sequence number right before middleTarget is updated, then removed.
  536. ListenSequenceNumber upperBound = _persistence.run(
  537. "Add a couple docs from the newest target to the oldest", [&]() -> ListenSequenceNumber {
  538. [self updateTargetInTransaction:oldestTarget];
  539. for (const DocumentKey &docKey : newestDocsToAddToOldest) {
  540. [self addDocument:docKey toTarget:oldestTarget.targetID];
  541. }
  542. return _persistence.currentSequenceNumber;
  543. });
  544. // Update a doc in the middle target
  545. _persistence.run("Update a doc in the middle target", [&]() {
  546. FSTTestSnapshotVersion version = 3;
  547. FSTDocument *doc = [FSTDocument documentWithData:_testValue
  548. key:middleDocToUpdate
  549. version:testutil::Version(version)
  550. state:FSTDocumentStateSynced];
  551. _documentCache->Add(doc);
  552. [self updateTargetInTransaction:middleTarget];
  553. });
  554. // middleTarget removed here, no update needed
  555. // Write a doc and get an ack, not part of a target.
  556. _persistence.run("Write a doc and get an ack, not part of a target", [&]() {
  557. FSTDocument *doc = [self cacheADocumentInTransaction];
  558. // Mark it as eligible for GC, but this is after our upper bound for what we will collect.
  559. [self markDocumentEligibleForGCInTransaction:doc.key];
  560. // This should be retained, it's too new to get removed.
  561. expectedRetained.insert(doc.key);
  562. });
  563. // Finally, do the garbage collection, up to but not including the removal of middleTarget
  564. NSDictionary<NSNumber *, FSTQueryData *> *liveQueries =
  565. @{@(oldestTarget.targetID) : oldestTarget};
  566. int queriesRemoved = [self removeQueriesThroughSequenceNumber:upperBound liveQueries:liveQueries];
  567. XCTAssertEqual(1, queriesRemoved, @"Expected to remove newest target");
  568. int docsRemoved = [self removeOrphanedDocumentsThroughSequenceNumber:upperBound];
  569. XCTAssertEqual(expectedRemoved.size(), docsRemoved);
  570. _persistence.run("verify results", [&]() {
  571. for (const DocumentKey &key : expectedRemoved) {
  572. XCTAssertNil(_documentCache->Get(key), @"Did not expect to find %s in document cache",
  573. key.ToString().c_str());
  574. XCTAssertFalse(_queryCache->Contains(key), @"Did not expect to find %s in queryCache",
  575. key.ToString().c_str());
  576. [self expectSentinelRemoved:key];
  577. }
  578. for (const DocumentKey &key : expectedRetained) {
  579. XCTAssertNotNil(_documentCache->Get(key), @"Expected to find %s in document cache",
  580. key.ToString().c_str());
  581. }
  582. });
  583. [_persistence shutdown];
  584. }
  585. - (void)testGetsSize {
  586. if ([self isTestBaseClass]) return;
  587. [self newTestResources];
  588. size_t initialSize = [_gc byteSize];
  589. _persistence.run("fill cache", [&]() {
  590. // Simulate a bunch of ack'd mutations
  591. for (int i = 0; i < 50; i++) {
  592. FSTDocument *doc = [self cacheADocumentInTransaction];
  593. [self markDocumentEligibleForGCInTransaction:doc.key];
  594. }
  595. });
  596. size_t finalSize = [_gc byteSize];
  597. XCTAssertGreaterThan(finalSize, initialSize);
  598. [_persistence shutdown];
  599. }
  600. - (void)testDisabled {
  601. if ([self isTestBaseClass]) return;
  602. LruParams params = LruParams::Disabled();
  603. [self newTestResourcesWithLruParams:params];
  604. _persistence.run("fill cache", [&]() {
  605. // Simulate a bunch of ack'd mutations
  606. for (int i = 0; i < 500; i++) {
  607. FSTDocument *doc = [self cacheADocumentInTransaction];
  608. [self markDocumentEligibleForGCInTransaction:doc.key];
  609. }
  610. });
  611. LruResults results =
  612. _persistence.run("GC", [&]() -> LruResults { return [_gc collectWithLiveTargets:@{}]; });
  613. XCTAssertFalse(results.didRun);
  614. [_persistence shutdown];
  615. }
  616. - (void)testCacheTooSmall {
  617. if ([self isTestBaseClass]) return;
  618. LruParams params = LruParams::Default();
  619. [self newTestResourcesWithLruParams:params];
  620. _persistence.run("fill cache", [&]() {
  621. // Simulate a bunch of ack'd mutations
  622. for (int i = 0; i < 50; i++) {
  623. FSTDocument *doc = [self cacheADocumentInTransaction];
  624. [self markDocumentEligibleForGCInTransaction:doc.key];
  625. }
  626. });
  627. int cacheSize = (int)[_gc byteSize];
  628. // Verify that we don't have enough in our cache to warrant collection
  629. XCTAssertLessThan(cacheSize, params.minBytesThreshold);
  630. // Try collection and verify that it didn't run
  631. LruResults results =
  632. _persistence.run("GC", [&]() -> LruResults { return [_gc collectWithLiveTargets:@{}]; });
  633. XCTAssertFalse(results.didRun);
  634. [_persistence shutdown];
  635. }
  636. - (void)testGCRan {
  637. if ([self isTestBaseClass]) return;
  638. LruParams params = LruParams::Default();
  639. // Set a low threshold so we will definitely run
  640. params.minBytesThreshold = 100;
  641. [self newTestResourcesWithLruParams:params];
  642. // Add 100 targets and 10 documents to each
  643. for (int i = 0; i < 100; i++) {
  644. // Use separate transactions so that each target and associated documents get their own
  645. // sequence number.
  646. _persistence.run("Add a target and some documents", [&]() {
  647. FSTQueryData *queryData = [self addNextQueryInTransaction];
  648. for (int j = 0; j < 10; j++) {
  649. FSTDocument *doc = [self cacheADocumentInTransaction];
  650. [self addDocument:doc.key toTarget:queryData.targetID];
  651. }
  652. });
  653. }
  654. // Mark nothing as live, so everything is eligible.
  655. LruResults results =
  656. _persistence.run("GC", [&]() -> LruResults { return [_gc collectWithLiveTargets:@{}]; });
  657. // By default, we collect 10% of the sequence numbers. Since we added 100 targets,
  658. // that should be 10 targets with 10 documents each, for a total of 100 documents.
  659. XCTAssertTrue(results.didRun);
  660. XCTAssertEqual(10, results.targetsRemoved);
  661. XCTAssertEqual(100, results.documentsRemoved);
  662. [_persistence shutdown];
  663. }
  664. @end
  665. NS_ASSUME_NONNULL_END