FSTLRUGarbageCollectorTests.mm 30 KB

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