FSTLRUGarbageCollectorTests.mm 29 KB

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