FSTLRUGarbageCollectorTests.mm 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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. BOOL hasMutations = NO;
  191. return [FSTDocument documentWithData:value
  192. key:key
  193. version:testutil::Version(version)
  194. hasLocalMutations:hasMutations];
  195. }
  196. - (FSTDocument *)nextTestDocument {
  197. return [self nextTestDocumentWithValue:_testValue];
  198. }
  199. #pragma mark - tests
  200. - (void)testPickSequenceNumberPercentile {
  201. if ([self isTestBaseClass]) return;
  202. const int numTestCases = 5;
  203. struct Case {
  204. // number of queries to cache
  205. int queries;
  206. // number expected to be calculated as 10%
  207. int expected;
  208. };
  209. struct Case testCases[numTestCases] = {{0, 0}, {10, 1}, {9, 0}, {50, 5}, {49, 4}};
  210. for (int i = 0; i < numTestCases; i++) {
  211. // Fill the query cache.
  212. int numQueries = testCases[i].queries;
  213. int expectedTenthPercentile = testCases[i].expected;
  214. [self newTestResources];
  215. for (int j = 0; j < numQueries; j++) {
  216. [self addNextQuery];
  217. }
  218. int tenth = [self queryCountForPercentile:10];
  219. XCTAssertEqual(expectedTenthPercentile, tenth, @"Total query count: %i", numQueries);
  220. [_persistence shutdown];
  221. _persistence = nil;
  222. }
  223. }
  224. - (void)testSequenceNumberNoQueries {
  225. if ([self isTestBaseClass]) return;
  226. // No queries... should get invalid sequence number (-1)
  227. [self newTestResources];
  228. XCTAssertEqual(kFSTListenSequenceNumberInvalid, [self sequenceNumberForQueryCount:0]);
  229. [_persistence shutdown];
  230. }
  231. - (void)testSequenceNumberForFiftyQueries {
  232. if ([self isTestBaseClass]) return;
  233. // Add 50 queries sequentially, aim to collect 10 of them.
  234. // The sequence number to collect should be 10 past the initial sequence number.
  235. [self newTestResources];
  236. for (int i = 0; i < 50; i++) {
  237. [self addNextQuery];
  238. }
  239. XCTAssertEqual(_initialSequenceNumber + 10, [self sequenceNumberForQueryCount:10]);
  240. [_persistence shutdown];
  241. }
  242. - (void)testSequenceNumberForMultipleQueriesInATransaction {
  243. if ([self isTestBaseClass]) return;
  244. // 50 queries, 9 with one transaction, incrementing from there. Should get second sequence number.
  245. [self newTestResources];
  246. _persistence.run("9 queries in a batch", [&]() {
  247. for (int i = 0; i < 9; i++) {
  248. [self addNextQueryInTransaction];
  249. }
  250. });
  251. for (int i = 9; i < 50; i++) {
  252. [self addNextQuery];
  253. }
  254. XCTAssertEqual(2 + _initialSequenceNumber, [self sequenceNumberForQueryCount:10]);
  255. [_persistence shutdown];
  256. }
  257. // Ensure that even if all of the queries are added in a single transaction, we still
  258. // pick a sequence number and GC. In this case, the initial transaction contains all of the
  259. // targets that will get GC'd, since they account for more than the first 10 targets.
  260. - (void)testAllCollectedQueriesInSingleTransaction {
  261. if ([self isTestBaseClass]) return;
  262. // 50 queries, 11 with one transaction, incrementing from there. Should get first sequence number.
  263. [self newTestResources];
  264. _persistence.run("11 queries in a transaction", [&]() {
  265. for (int i = 0; i < 11; i++) {
  266. [self addNextQueryInTransaction];
  267. }
  268. });
  269. for (int i = 11; i < 50; i++) {
  270. [self addNextQuery];
  271. }
  272. // We expect to GC the targets from the first transaction, since they account for
  273. // at least the first 10 of the targets.
  274. XCTAssertEqual(1 + _initialSequenceNumber, [self sequenceNumberForQueryCount:10]);
  275. [_persistence shutdown];
  276. }
  277. - (void)testSequenceNumbersWithMutationAndSequentialQueries {
  278. if ([self isTestBaseClass]) return;
  279. // Remove a mutated doc reference, marking it as eligible for GC.
  280. // Then add 50 queries. Should get 10 past initial (9 queries).
  281. [self newTestResources];
  282. [self markADocumentEligibleForGC];
  283. for (int i = 0; i < 50; i++) {
  284. [self addNextQuery];
  285. }
  286. XCTAssertEqual(10 + _initialSequenceNumber, [self sequenceNumberForQueryCount:10]);
  287. [_persistence shutdown];
  288. }
  289. - (void)testSequenceNumbersWithMutationsInQueries {
  290. if ([self isTestBaseClass]) return;
  291. // Add mutated docs, then add one of them to a query target so it doesn't get GC'd.
  292. // Expect 3 past the initial value: the mutations not part of a query, and two queries
  293. [self newTestResources];
  294. FSTDocument *docInQuery = [self nextTestDocument];
  295. _persistence.run("mark mutations", [&]() {
  296. // Adding 9 doc keys in a transaction. If we remove one of them, we'll have room for two actual
  297. // queries.
  298. [self markDocumentEligibleForGCInTransaction:docInQuery.key];
  299. for (int i = 0; i < 8; i++) {
  300. [self markADocumentEligibleForGCInTransaction];
  301. }
  302. });
  303. for (int i = 0; i < 49; i++) {
  304. [self addNextQuery];
  305. }
  306. _persistence.run("query with mutation", [&]() {
  307. FSTQueryData *queryData = [self addNextQueryInTransaction];
  308. // This should keep the document from getting GC'd, since it is no longer orphaned.
  309. [self addDocument:docInQuery.key toTarget:queryData.targetID];
  310. });
  311. // This should catch the remaining 8 documents, plus the first two queries we added.
  312. XCTAssertEqual(3 + _initialSequenceNumber, [self sequenceNumberForQueryCount:10]);
  313. [_persistence shutdown];
  314. }
  315. - (void)testRemoveQueriesUpThroughSequenceNumber {
  316. if ([self isTestBaseClass]) return;
  317. [self newTestResources];
  318. NSMutableDictionary<NSNumber *, FSTQueryData *> *liveQueries = [[NSMutableDictionary alloc] init];
  319. for (int i = 0; i < 100; i++) {
  320. FSTQueryData *queryData = [self addNextQuery];
  321. // Mark odd queries as live so we can test filtering out live queries.
  322. if (queryData.targetID % 2 == 1) {
  323. liveQueries[@(queryData.targetID)] = queryData;
  324. }
  325. }
  326. // GC up through 20th query, which is 20%.
  327. // Expect to have GC'd 10 targets, since every other target is live
  328. int removed =
  329. [self removeQueriesThroughSequenceNumber:20 + _initialSequenceNumber liveQueries:liveQueries];
  330. XCTAssertEqual(10, removed);
  331. // Make sure we removed the even targets with targetID <= 20.
  332. _persistence.run("verify remaining targets are > 20 or odd", [&]() {
  333. [_queryCache enumerateTargetsUsingBlock:^(FSTQueryData *queryData, BOOL *stop) {
  334. XCTAssertTrue(queryData.targetID > 20 || queryData.targetID % 2 == 1);
  335. }];
  336. });
  337. [_persistence shutdown];
  338. }
  339. - (void)testRemoveOrphanedDocuments {
  340. if ([self isTestBaseClass]) return;
  341. [self newTestResources];
  342. // Track documents we expect to be retained so we can verify post-GC.
  343. // This will contain documents associated with targets that survive GC, as well
  344. // as any documents with pending mutations.
  345. std::unordered_set<DocumentKey, DocumentKeyHash> expectedRetained;
  346. // we add two mutations later, for now track them in an array.
  347. NSMutableArray *mutations = [NSMutableArray arrayWithCapacity:2];
  348. // Add a target and add two documents to it. The documents are expected to be
  349. // retained, since their membership in the target keeps them alive.
  350. _persistence.run("add a target and add two documents to it", [&]() {
  351. // Add two documents to first target, queue a mutation on the second document
  352. FSTQueryData *queryData = [self addNextQueryInTransaction];
  353. FSTDocument *doc1 = [self cacheADocumentInTransaction];
  354. [self addDocument:doc1.key toTarget:queryData.targetID];
  355. expectedRetained.insert(doc1.key);
  356. FSTDocument *doc2 = [self cacheADocumentInTransaction];
  357. [self addDocument:doc2.key toTarget:queryData.targetID];
  358. expectedRetained.insert(doc2.key);
  359. [mutations addObject:[self mutationForDocument:doc2.key]];
  360. });
  361. // Add a second query and register a third document on it
  362. _persistence.run("second query", [&]() {
  363. FSTQueryData *queryData = [self addNextQueryInTransaction];
  364. FSTDocument *doc3 = [self cacheADocumentInTransaction];
  365. expectedRetained.insert(doc3.key);
  366. [self addDocument:doc3.key toTarget:queryData.targetID];
  367. });
  368. // cache another document and prepare a mutation on it.
  369. _persistence.run("queue a mutation", [&]() {
  370. FSTDocument *doc4 = [self cacheADocumentInTransaction];
  371. [mutations addObject:[self mutationForDocument:doc4.key]];
  372. expectedRetained.insert(doc4.key);
  373. });
  374. // Insert the mutations. These operations don't have a sequence number, they just
  375. // serve to keep the mutated documents from being GC'd while the mutations are outstanding.
  376. _persistence.run("actually register the mutations", [&]() {
  377. FIRTimestamp *writeTime = [FIRTimestamp timestamp];
  378. [_mutationQueue addMutationBatchWithWriteTime:writeTime mutations:mutations];
  379. });
  380. // Mark 5 documents eligible for GC. This simulates documents that were mutated then ack'd.
  381. // Since they were ack'd, they are no longer in a mutation queue, and there is nothing keeping
  382. // them alive.
  383. std::unordered_set<DocumentKey, DocumentKeyHash> toBeRemoved;
  384. _persistence.run("add orphaned docs (previously mutated, then ack'd)", [&]() {
  385. for (int i = 0; i < 5; i++) {
  386. FSTDocument *doc = [self cacheADocumentInTransaction];
  387. toBeRemoved.insert(doc.key);
  388. [self markDocumentEligibleForGCInTransaction:doc.key];
  389. }
  390. });
  391. // We expect only the orphaned documents, those not in a mutation or a target, to be
  392. // removed.
  393. // use a large sequence number to remove as much as possible
  394. int removed = [self removeOrphanedDocumentsThroughSequenceNumber:1000];
  395. XCTAssertEqual(toBeRemoved.size(), removed);
  396. _persistence.run("verify", [&]() {
  397. for (const DocumentKey &key : toBeRemoved) {
  398. XCTAssertNil([_documentCache entryForKey:key]);
  399. XCTAssertFalse([_queryCache containsKey:key]);
  400. }
  401. for (const DocumentKey &key : expectedRetained) {
  402. XCTAssertNotNil([_documentCache entryForKey:key], @"Missing document %s",
  403. key.ToString().c_str());
  404. }
  405. });
  406. [_persistence shutdown];
  407. }
  408. // TODO(gsoltis): write a test that includes limbo documents
  409. - (void)testRemoveTargetsThenGC {
  410. if ([self isTestBaseClass]) return;
  411. // Create 3 targets, add docs to all of them
  412. // Leave oldest target alone, it is still live
  413. // Remove newest target
  414. // Blind write 2 documents
  415. // Add one of the blind write docs to oldest target (preserves it)
  416. // Remove some documents from middle target (bumps sequence number)
  417. // Add some documents from newest target to oldest target (preserves them)
  418. // Update a doc from middle target
  419. // Remove middle target
  420. // Do a blind write
  421. // GC up to but not including the removal of the middle target
  422. //
  423. // Expect:
  424. // All docs in oldest target are still around
  425. // One blind write is gone, the first one not added to oldest target
  426. // Documents removed from middle target are gone, except ones added to oldest target
  427. // Documents from newest target are gone, except
  428. [self newTestResources];
  429. // Through the various steps, track which documents we expect to be removed vs
  430. // documents we expect to be retained.
  431. std::unordered_set<DocumentKey, DocumentKeyHash> expectedRetained;
  432. std::unordered_set<DocumentKey, DocumentKeyHash> expectedRemoved;
  433. // Add oldest target, 5 documents, and add those documents to the target.
  434. // This target will not be removed, so all documents that are part of it will
  435. // be retained.
  436. FSTQueryData *oldestTarget =
  437. _persistence.run("Add oldest target and docs", [&]() -> FSTQueryData * {
  438. FSTQueryData *queryData = [self addNextQueryInTransaction];
  439. for (int i = 0; i < 5; i++) {
  440. FSTDocument *doc = [self cacheADocumentInTransaction];
  441. expectedRetained.insert(doc.key);
  442. [self addDocument:doc.key toTarget:queryData.targetID];
  443. }
  444. return queryData;
  445. });
  446. // Add middle target and docs. Some docs will be removed from this target later,
  447. // which we track here.
  448. DocumentKeySet middleDocsToRemove;
  449. // This will be the document in this target that gets an update later
  450. DocumentKey middleDocToUpdate;
  451. FSTQueryData *middleTarget =
  452. _persistence.run("Add middle target and docs", [&]() -> FSTQueryData * {
  453. FSTQueryData *middleTarget = [self addNextQueryInTransaction];
  454. // these docs will be removed from this target later, triggering a bump
  455. // to their sequence numbers. Since they will not be a part of the target, we
  456. // expect them to be removed.
  457. for (int i = 0; i < 2; i++) {
  458. FSTDocument *doc = [self cacheADocumentInTransaction];
  459. expectedRemoved.insert(doc.key);
  460. [self addDocument:doc.key toTarget:middleTarget.targetID];
  461. middleDocsToRemove = middleDocsToRemove.insert(doc.key);
  462. }
  463. // these docs stay in this target and only this target. There presence in this
  464. // target prevents them from being GC'd, so they are also expected to be retained.
  465. for (int i = 2; i < 4; i++) {
  466. FSTDocument *doc = [self cacheADocumentInTransaction];
  467. expectedRetained.insert(doc.key);
  468. [self addDocument:doc.key toTarget:middleTarget.targetID];
  469. }
  470. // This doc stays in this target, but gets updated.
  471. {
  472. FSTDocument *doc = [self cacheADocumentInTransaction];
  473. expectedRetained.insert(doc.key);
  474. [self addDocument:doc.key toTarget:middleTarget.targetID];
  475. middleDocToUpdate = doc.key;
  476. }
  477. return middleTarget;
  478. });
  479. // Add the newest target and add 5 documents to it. Some of those documents will
  480. // additionally be added to the oldest target, which will cause those documents to
  481. // be retained. The remaining documents are expected to be removed, since this target
  482. // will be removed.
  483. DocumentKeySet newestDocsToAddToOldest;
  484. _persistence.run("Add newest target and docs", [&]() {
  485. FSTQueryData *newestTarget = [self addNextQueryInTransaction];
  486. // These documents are only in this target. They are expected to be removed
  487. // because this target will also be removed.
  488. for (int i = 0; i < 3; i++) {
  489. FSTDocument *doc = [self cacheADocumentInTransaction];
  490. expectedRemoved.insert(doc.key);
  491. [self addDocument:doc.key toTarget:newestTarget.targetID];
  492. }
  493. // docs to add to the oldest target in addition to this target. They will be retained
  494. for (int i = 3; i < 5; i++) {
  495. FSTDocument *doc = [self cacheADocumentInTransaction];
  496. expectedRetained.insert(doc.key);
  497. [self addDocument:doc.key toTarget:newestTarget.targetID];
  498. newestDocsToAddToOldest = newestDocsToAddToOldest.insert(doc.key);
  499. }
  500. });
  501. // 2 doc writes, add one of them to the oldest target.
  502. _persistence.run("2 doc writes, add one of them to the oldest target", [&]() {
  503. // write two docs and have them ack'd by the server. can skip mutation queue
  504. // and set them in document cache. Add potentially orphaned first, also add one
  505. // doc to a target.
  506. FSTDocument *doc1 = [self cacheADocumentInTransaction];
  507. [self markDocumentEligibleForGCInTransaction:doc1.key];
  508. [self updateTargetInTransaction:oldestTarget];
  509. [self addDocument:doc1.key toTarget:oldestTarget.targetID];
  510. // doc1 should be retained by being added to oldestTarget.
  511. expectedRetained.insert(doc1.key);
  512. FSTDocument *doc2 = [self cacheADocumentInTransaction];
  513. [self markDocumentEligibleForGCInTransaction:doc2.key];
  514. // nothing is keeping doc2 around, it should be removed
  515. expectedRemoved.insert(doc2.key);
  516. });
  517. // Remove some documents from the middle target.
  518. _persistence.run("Remove some documents from the middle target", [&]() {
  519. [self updateTargetInTransaction:middleTarget];
  520. for (const DocumentKey &docKey : middleDocsToRemove) {
  521. [self removeDocument:docKey fromTarget:middleTarget.targetID];
  522. }
  523. });
  524. // Add a couple docs from the newest target to the oldest (preserves them past the point where
  525. // newest was removed)
  526. // upperBound is the sequence number right before middleTarget is updated, then removed.
  527. ListenSequenceNumber upperBound = _persistence.run(
  528. "Add a couple docs from the newest target to the oldest", [&]() -> ListenSequenceNumber {
  529. [self updateTargetInTransaction:oldestTarget];
  530. for (const DocumentKey &docKey : newestDocsToAddToOldest) {
  531. [self addDocument:docKey toTarget:oldestTarget.targetID];
  532. }
  533. return _persistence.currentSequenceNumber;
  534. });
  535. // Update a doc in the middle target
  536. _persistence.run("Update a doc in the middle target", [&]() {
  537. FSTTestSnapshotVersion version = 3;
  538. FSTDocument *doc = [FSTDocument documentWithData:_testValue
  539. key:middleDocToUpdate
  540. version:testutil::Version(version)
  541. hasLocalMutations:NO];
  542. [_documentCache addEntry:doc];
  543. [self updateTargetInTransaction:middleTarget];
  544. });
  545. // middleTarget removed here, no update needed
  546. // Write a doc and get an ack, not part of a target.
  547. _persistence.run("Write a doc and get an ack, not part of a target", [&]() {
  548. FSTDocument *doc = [self cacheADocumentInTransaction];
  549. // Mark it as eligible for GC, but this is after our upper bound for what we will collect.
  550. [self markDocumentEligibleForGCInTransaction:doc.key];
  551. // This should be retained, it's too new to get removed.
  552. expectedRetained.insert(doc.key);
  553. });
  554. // Finally, do the garbage collection, up to but not including the removal of middleTarget
  555. NSDictionary<NSNumber *, FSTQueryData *> *liveQueries =
  556. @{@(oldestTarget.targetID) : oldestTarget};
  557. int queriesRemoved = [self removeQueriesThroughSequenceNumber:upperBound liveQueries:liveQueries];
  558. XCTAssertEqual(1, queriesRemoved, @"Expected to remove newest target");
  559. int docsRemoved = [self removeOrphanedDocumentsThroughSequenceNumber:upperBound];
  560. XCTAssertEqual(expectedRemoved.size(), docsRemoved);
  561. _persistence.run("verify results", [&]() {
  562. for (const DocumentKey &key : expectedRemoved) {
  563. XCTAssertNil([_documentCache entryForKey:key], @"Did not expect to find %s in document cache",
  564. key.ToString().c_str());
  565. XCTAssertFalse([_queryCache containsKey:key], @"Did not expect to find %s in queryCache",
  566. key.ToString().c_str());
  567. [self expectSentinelRemoved:key];
  568. }
  569. for (const DocumentKey &key : expectedRetained) {
  570. XCTAssertNotNil([_documentCache entryForKey:key], @"Expected to find %s in document cache",
  571. key.ToString().c_str());
  572. }
  573. });
  574. [_persistence shutdown];
  575. }
  576. - (void)testGetsSize {
  577. if ([self isTestBaseClass]) return;
  578. [self newTestResources];
  579. size_t initialSize = [_gc byteSize];
  580. _persistence.run("fill cache", [&]() {
  581. // Simulate a bunch of ack'd mutations
  582. for (int i = 0; i < 50; i++) {
  583. FSTDocument *doc = [self cacheADocumentInTransaction];
  584. [self markDocumentEligibleForGCInTransaction:doc.key];
  585. }
  586. });
  587. size_t finalSize = [_gc byteSize];
  588. XCTAssertGreaterThan(finalSize, initialSize);
  589. [_persistence shutdown];
  590. }
  591. @end
  592. NS_ASSUME_NONNULL_END