FSTLRUGarbageCollectorTests.mm 26 KB

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