FSTLRUGarbageCollectorTests.mm 27 KB

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