FSTLRUGarbageCollectorTests.mm 26 KB

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