FSTLRUGarbageCollectorTests.mm 30 KB

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