FSTLRUGarbageCollectorTests.mm 30 KB

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