v8_detailed_memory_unittest.cc 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "components/performance_manager/public/v8_memory/v8_detailed_memory.h"
  5. #include "components/performance_manager/public/v8_memory/v8_detailed_memory_any_seq.h"
  6. #include <memory>
  7. #include <tuple>
  8. #include <utility>
  9. #include "base/barrier_closure.h"
  10. #include "base/bind.h"
  11. #include "base/callback.h"
  12. #include "base/command_line.h"
  13. #include "base/memory/scoped_refptr.h"
  14. #include "base/memory/weak_ptr.h"
  15. #include "base/run_loop.h"
  16. #include "base/task/single_thread_task_runner.h"
  17. #include "base/test/bind.h"
  18. #include "base/test/gmock_callback_support.h"
  19. #include "base/test/gtest_util.h"
  20. #include "base/test/test_timeouts.h"
  21. #include "base/time/time.h"
  22. #include "base/timer/timer.h"
  23. #include "build/build_config.h"
  24. #include "components/performance_manager/graph/frame_node_impl.h"
  25. #include "components/performance_manager/graph/page_node_impl.h"
  26. #include "components/performance_manager/graph/process_node_impl.h"
  27. #include "components/performance_manager/graph/worker_node_impl.h"
  28. #include "components/performance_manager/public/performance_manager.h"
  29. #include "components/performance_manager/public/render_process_host_id.h"
  30. #include "components/performance_manager/public/render_process_host_proxy.h"
  31. #include "components/performance_manager/test_support/graph_test_harness.h"
  32. #include "components/performance_manager/v8_memory/v8_memory_test_helpers.h"
  33. #include "content/public/browser/global_routing_id.h"
  34. #include "content/public/browser/render_frame_host.h"
  35. #include "content/public/browser/render_process_host.h"
  36. #include "content/public/browser/web_contents.h"
  37. #include "content/public/test/test_renderer_host.h"
  38. #include "testing/gmock/include/gmock/gmock.h"
  39. #include "testing/gtest/include/gtest/gtest.h"
  40. #include "third_party/blink/public/common/tokens/tokens.h"
  41. namespace performance_manager {
  42. namespace v8_memory {
  43. using ::testing::_;
  44. using ::testing::InSequence;
  45. using ::testing::Mock;
  46. using ::testing::StrictMock;
  47. constexpr uint64_t kDetachedBytes = 0xDEED;
  48. constexpr uint64_t kSharedBytes = 0xABBA;
  49. constexpr uint64_t kBlinkBytes = 0x1001;
  50. namespace {
  51. class LenientMockV8DetailedMemoryObserver : public V8DetailedMemoryObserver {
  52. public:
  53. MOCK_METHOD(void,
  54. OnV8MemoryMeasurementAvailable,
  55. (const ProcessNode* process_node,
  56. const V8DetailedMemoryProcessData* process_data),
  57. (override));
  58. void ExpectObservationOnProcess(const ProcessNode* process_node,
  59. uint64_t expected_shared_v8_bytes_used) {
  60. using ::testing::Eq;
  61. using ::testing::Property;
  62. EXPECT_CALL(*this,
  63. OnV8MemoryMeasurementAvailable(
  64. process_node,
  65. Property(&V8DetailedMemoryProcessData::shared_v8_bytes_used,
  66. Eq(expected_shared_v8_bytes_used))));
  67. }
  68. };
  69. using MockV8DetailedMemoryObserver =
  70. StrictMock<LenientMockV8DetailedMemoryObserver>;
  71. class LenientMockV8DetailedMemoryObserverAnySeq
  72. : public V8DetailedMemoryObserverAnySeq {
  73. public:
  74. MOCK_METHOD(void,
  75. OnV8MemoryMeasurementAvailable,
  76. (RenderProcessHostId render_process_host_id,
  77. const V8DetailedMemoryProcessData& process_data,
  78. const V8DetailedMemoryObserverAnySeq::FrameDataMap& frame_data),
  79. (override));
  80. };
  81. using MockV8DetailedMemoryObserverAnySeq =
  82. StrictMock<LenientMockV8DetailedMemoryObserverAnySeq>;
  83. // The mode enum used in the API.
  84. using MeasurementMode = V8DetailedMemoryRequest::MeasurementMode;
  85. // An arbitrary object used to test object lifetimes with WeakPtr.
  86. class LifetimeTestObject : public base::SupportsWeakPtr<LifetimeTestObject> {
  87. public:
  88. LifetimeTestObject() = default;
  89. ~LifetimeTestObject() = default;
  90. };
  91. constexpr base::TimeDelta kMinTimeBetweenRequests = base::Seconds(30);
  92. } // namespace
  93. class V8DetailedMemoryDecoratorTest : public GraphTestHarness,
  94. public V8MemoryTestBase {
  95. public:
  96. V8DetailedMemoryDecoratorTest() {
  97. GetGraphFeatures().EnableExecutionContextRegistry();
  98. }
  99. scoped_refptr<base::SingleThreadTaskRunner> GetMainThreadTaskRunner()
  100. override {
  101. return task_env().GetMainThreadTaskRunner();
  102. }
  103. };
  104. // kBounded mode and kEagerForTesting mode behave identically as far as
  105. // V8DetailedMemoryDecorator is concerned. (The differences are all on the
  106. // renderer side.) So mode tests hardcode kLazy mode and use a parameter to
  107. // choose which of the two to use for bounded mode.
  108. class V8DetailedMemoryDecoratorModeTest
  109. : public V8DetailedMemoryDecoratorTest,
  110. public ::testing::WithParamInterface<
  111. std::pair<MeasurementMode, ExpectedMode>> {
  112. public:
  113. V8DetailedMemoryDecoratorModeTest() {
  114. internal::SetEagerMemoryMeasurementEnabledForTesting(true);
  115. std::tie(bounded_mode_, expected_bounded_mode_) = GetParam();
  116. }
  117. ~V8DetailedMemoryDecoratorModeTest() override {
  118. internal::SetEagerMemoryMeasurementEnabledForTesting(false);
  119. }
  120. protected:
  121. // The mode that will be used for bounded requests.
  122. MeasurementMode bounded_mode_;
  123. // The expected mojo mode parameter for bounded requests.
  124. ExpectedMode expected_bounded_mode_;
  125. };
  126. class V8DetailedMemoryDecoratorSingleProcessModeTest
  127. : public V8DetailedMemoryDecoratorTest,
  128. public ::testing::WithParamInterface<MeasurementMode> {
  129. public:
  130. V8DetailedMemoryDecoratorSingleProcessModeTest()
  131. : single_process_mode_(GetParam()) {}
  132. protected:
  133. // The mode that will be used for single-process requests.
  134. MeasurementMode single_process_mode_;
  135. };
  136. using V8DetailedMemoryDecoratorDeathTest = V8DetailedMemoryDecoratorTest;
  137. using V8DetailedMemoryRequestAnySeqTest = V8MemoryPerformanceManagerTestHarness;
  138. TEST_F(V8DetailedMemoryDecoratorTest, InstantiateOnEmptyGraph) {
  139. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  140. MockV8DetailedMemoryReporter mock_reporter;
  141. auto data = NewPerProcessV8MemoryUsage(1);
  142. data->isolates[0]->detached_bytes_used = kDetachedBytes;
  143. data->isolates[0]->shared_bytes_used = kSharedBytes;
  144. data->isolates[0]->blink_bytes_used = kBlinkBytes;
  145. ExpectBindAndRespondToQuery(&mock_reporter, std::move(data));
  146. // Create a process node and validate that it gets a request.
  147. auto process = CreateNode<ProcessNodeImpl>(
  148. content::PROCESS_TYPE_RENDERER,
  149. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  150. // Data should not be available until the measurement is taken.
  151. EXPECT_FALSE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  152. // Run until idle to make sure the measurement isn't a hard loop.
  153. task_env().RunUntilIdle();
  154. EXPECT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  155. EXPECT_EQ(kDetachedBytes,
  156. V8DetailedMemoryProcessData::ForProcessNode(process.get())
  157. ->detached_v8_bytes_used());
  158. EXPECT_EQ(kSharedBytes,
  159. V8DetailedMemoryProcessData::ForProcessNode(process.get())
  160. ->shared_v8_bytes_used());
  161. EXPECT_EQ(kBlinkBytes,
  162. V8DetailedMemoryProcessData::ForProcessNode(process.get())
  163. ->blink_bytes_used());
  164. }
  165. TEST_F(V8DetailedMemoryDecoratorTest, InstantiateOnNonEmptyGraph) {
  166. // Instantiate the decorator with an existing process node and validate that
  167. // it gets a request.
  168. auto process = CreateNode<ProcessNodeImpl>(
  169. content::PROCESS_TYPE_RENDERER,
  170. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  171. MockV8DetailedMemoryReporter mock_reporter;
  172. auto data = NewPerProcessV8MemoryUsage(1);
  173. data->isolates[0]->detached_bytes_used = kDetachedBytes;
  174. data->isolates[0]->shared_bytes_used = kSharedBytes;
  175. ExpectBindAndRespondToQuery(&mock_reporter, std::move(data));
  176. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  177. // Data should not be available until the measurement is taken.
  178. EXPECT_FALSE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  179. // Run until idle to make sure the measurement isn't a hard loop.
  180. task_env().RunUntilIdle();
  181. EXPECT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  182. EXPECT_EQ(kDetachedBytes,
  183. V8DetailedMemoryProcessData::ForProcessNode(process.get())
  184. ->detached_v8_bytes_used());
  185. EXPECT_EQ(kSharedBytes,
  186. V8DetailedMemoryProcessData::ForProcessNode(process.get())
  187. ->shared_v8_bytes_used());
  188. }
  189. TEST_F(V8DetailedMemoryDecoratorTest, OnlyMeasureRenderers) {
  190. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  191. for (int type = content::PROCESS_TYPE_BROWSER;
  192. type < content::PROCESS_TYPE_CONTENT_END; ++type) {
  193. if (type == content::PROCESS_TYPE_RENDERER)
  194. continue;
  195. // Instantiate a non-renderer process node and validate that it causes no
  196. // bind requests.
  197. EXPECT_CALL(*this, BindReceiverWithProxyHost(_, _)).Times(0);
  198. auto process = CreateNode<ProcessNodeImpl>(
  199. static_cast<content::ProcessType>(type),
  200. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  201. task_env().RunUntilIdle();
  202. Mock::VerifyAndClearExpectations(this);
  203. }
  204. }
  205. TEST_F(V8DetailedMemoryDecoratorTest, OneShot) {
  206. // Create 2 renderer processes. Create one request that measures both of
  207. // them, and a one-shot request that measures only one.
  208. constexpr RenderProcessHostId kProcessId1 = RenderProcessHostId(0xFAB);
  209. auto process1 = CreateNode<ProcessNodeImpl>(
  210. content::PROCESS_TYPE_RENDERER,
  211. RenderProcessHostProxy::CreateForTesting(kProcessId1));
  212. constexpr RenderProcessHostId kProcessId2 = RenderProcessHostId(0xBAF);
  213. auto process2 = CreateNode<ProcessNodeImpl>(
  214. content::PROCESS_TYPE_RENDERER,
  215. RenderProcessHostProxy::CreateForTesting(kProcessId2));
  216. // Set the all process request to only send once within the test.
  217. V8DetailedMemoryRequest all_process_request(kMinTimeBetweenRequests * 100);
  218. all_process_request.StartMeasurement(graph());
  219. // Create a mock reporter for each process and expect a query and reply on
  220. // each.
  221. MockV8DetailedMemoryReporter mock_reporter1;
  222. {
  223. auto data = NewPerProcessV8MemoryUsage(1);
  224. data->isolates[0]->shared_bytes_used = 1ULL;
  225. ExpectBindAndRespondToQuery(&mock_reporter1, std::move(data), kProcessId1);
  226. }
  227. MockV8DetailedMemoryReporter mock_reporter2;
  228. {
  229. auto data = NewPerProcessV8MemoryUsage(1);
  230. data->isolates[0]->shared_bytes_used = 2ULL;
  231. ExpectBindAndRespondToQuery(&mock_reporter2, std::move(data), kProcessId2);
  232. }
  233. task_env().RunUntilIdle();
  234. Mock::VerifyAndClearExpectations(&mock_reporter1);
  235. Mock::VerifyAndClearExpectations(&mock_reporter2);
  236. // Create a one-shot request for process1 and expect the callback to be
  237. // called only for that process.
  238. {
  239. auto data = NewPerProcessV8MemoryUsage(1);
  240. data->isolates[0]->shared_bytes_used = 3ULL;
  241. ExpectQueryAndReply(&mock_reporter1, std::move(data));
  242. }
  243. uint64_t shared_v8_bytes_used = 0;
  244. V8DetailedMemoryRequestOneShot process1_request;
  245. process1_request.StartMeasurement(
  246. process1.get(), base::BindLambdaForTesting(
  247. [&shared_v8_bytes_used, &process1](
  248. const ProcessNode* process_node,
  249. const V8DetailedMemoryProcessData* process_data) {
  250. ASSERT_TRUE(process_data);
  251. EXPECT_EQ(process_node, process1.get());
  252. shared_v8_bytes_used =
  253. process_data->shared_v8_bytes_used();
  254. }));
  255. task_env().RunUntilIdle();
  256. Mock::VerifyAndClearExpectations(&mock_reporter1);
  257. Mock::VerifyAndClearExpectations(&mock_reporter2);
  258. EXPECT_EQ(shared_v8_bytes_used, 3ULL);
  259. }
  260. TEST_F(V8DetailedMemoryDecoratorTest, OneShotLifetime) {
  261. auto process = CreateNode<ProcessNodeImpl>(
  262. content::PROCESS_TYPE_RENDERER,
  263. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  264. MockV8DetailedMemoryReporter mock_reporter;
  265. {
  266. InSequence seq;
  267. ExpectBindReceiver(&mock_reporter);
  268. auto data = NewPerProcessV8MemoryUsage(1);
  269. data->isolates[0]->shared_bytes_used = 1ULL;
  270. ExpectQueryAndDelayReply(&mock_reporter, base::Seconds(10),
  271. std::move(data));
  272. }
  273. // Create a one-shot request, but delete it before the result arrives.
  274. auto doomed_request = std::make_unique<V8DetailedMemoryRequestOneShot>(
  275. process.get(),
  276. base::BindOnce([](const ProcessNode* process_node,
  277. const V8DetailedMemoryProcessData* process_data) {
  278. FAIL() << "Callback called after request deleted.";
  279. }));
  280. // Verify that the request is sent but the reply is not yet received.
  281. task_env().FastForwardBy(base::Seconds(5));
  282. Mock::VerifyAndClearExpectations(&mock_reporter);
  283. doomed_request.reset();
  284. task_env().FastForwardBy(base::Seconds(5));
  285. // Create a request that is deleted from within its own callback and make
  286. // sure nothing explodes.
  287. {
  288. auto data = NewPerProcessV8MemoryUsage(1);
  289. data->isolates[0]->shared_bytes_used = 2ULL;
  290. ExpectQueryAndReply(&mock_reporter, std::move(data));
  291. }
  292. uint64_t shared_v8_bytes_used = 0;
  293. doomed_request = std::make_unique<V8DetailedMemoryRequestOneShot>(
  294. process.get(), base::BindLambdaForTesting(
  295. [&](const ProcessNode* process_node,
  296. const V8DetailedMemoryProcessData* process_data) {
  297. doomed_request.reset();
  298. ASSERT_TRUE(process_data);
  299. shared_v8_bytes_used =
  300. process_data->shared_v8_bytes_used();
  301. }));
  302. task_env().RunUntilIdle();
  303. Mock::VerifyAndClearExpectations(&mock_reporter);
  304. EXPECT_EQ(shared_v8_bytes_used, 2ULL);
  305. // Ensure that resource-owning callbacks are freed when there is no response
  306. // because the process dies.
  307. {
  308. auto data = NewPerProcessV8MemoryUsage(1);
  309. data->isolates[0]->shared_bytes_used = 3ULL;
  310. ExpectQueryAndDelayReply(&mock_reporter, base::Seconds(10),
  311. std::move(data));
  312. }
  313. auto lifetime_test = std::make_unique<LifetimeTestObject>();
  314. auto weak_lifetime_test = lifetime_test->AsWeakPtr();
  315. V8DetailedMemoryRequestOneShot unfinished_request(
  316. process.get(),
  317. base::BindOnce(
  318. [](std::unique_ptr<LifetimeTestObject>, const ProcessNode*,
  319. const V8DetailedMemoryProcessData*) {
  320. FAIL() << "Callback called after process deleted.";
  321. },
  322. // Pass ownership to the callback. The object should be deleted if the
  323. // callback is not called.
  324. std::move(lifetime_test)));
  325. // Verify that requests are sent but reply is not yet received.
  326. task_env().FastForwardBy(base::Seconds(5));
  327. Mock::VerifyAndClearExpectations(&mock_reporter);
  328. ASSERT_TRUE(weak_lifetime_test);
  329. process.reset();
  330. task_env().FastForwardBy(base::Seconds(5));
  331. EXPECT_FALSE(weak_lifetime_test);
  332. }
  333. TEST_F(V8DetailedMemoryDecoratorTest, OneShotLifetimeAtExit) {
  334. auto process = CreateNode<ProcessNodeImpl>(
  335. content::PROCESS_TYPE_RENDERER,
  336. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  337. // Ensure that resource-owning callbacks are freed when there is no response
  338. // because the browser is exiting (simulated by destroying the decorator).
  339. MockV8DetailedMemoryReporter mock_reporter;
  340. {
  341. InSequence seq;
  342. ExpectBindReceiver(&mock_reporter);
  343. auto data = NewPerProcessV8MemoryUsage(1);
  344. data->isolates[0]->shared_bytes_used = 1ULL;
  345. ExpectQueryAndDelayReply(&mock_reporter, base::Seconds(10),
  346. std::move(data));
  347. }
  348. auto lifetime_test = std::make_unique<LifetimeTestObject>();
  349. auto weak_lifetime_test = lifetime_test->AsWeakPtr();
  350. V8DetailedMemoryRequestOneShot unfinished_request(
  351. process.get(),
  352. base::BindOnce(
  353. [](std::unique_ptr<LifetimeTestObject>, const ProcessNode*,
  354. const V8DetailedMemoryProcessData*) {
  355. FAIL() << "Callback called after measurements cancelled.";
  356. },
  357. // Pass ownership to the callback. The object should be deleted if the
  358. // callback is not called.
  359. std::move(lifetime_test)));
  360. // Verify that requests are sent but reply is not yet received.
  361. task_env().FastForwardBy(base::Seconds(5));
  362. Mock::VerifyAndClearExpectations(&mock_reporter);
  363. ASSERT_TRUE(weak_lifetime_test);
  364. internal::DestroyV8DetailedMemoryDecoratorForTesting(graph());
  365. task_env().FastForwardBy(base::Seconds(5));
  366. EXPECT_FALSE(weak_lifetime_test);
  367. }
  368. TEST_F(V8DetailedMemoryDecoratorTest, QueryRateIsLimited) {
  369. auto process = CreateNode<ProcessNodeImpl>(
  370. content::PROCESS_TYPE_RENDERER,
  371. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  372. MockV8DetailedMemoryReporter mock_reporter;
  373. {
  374. auto data = NewPerProcessV8MemoryUsage(1);
  375. // Response to request 1.
  376. data->isolates[0]->shared_bytes_used = 1;
  377. ExpectBindAndRespondToQuery(&mock_reporter, std::move(data));
  378. }
  379. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  380. // Run until idle to make sure the measurement isn't a hard loop.
  381. task_env().RunUntilIdle();
  382. EXPECT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  383. EXPECT_EQ(1u, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  384. ->shared_v8_bytes_used());
  385. // There shouldn't be an additional request this soon.
  386. task_env().FastForwardBy(kMinTimeBetweenRequests / 2);
  387. Mock::VerifyAndClearExpectations(&mock_reporter);
  388. // Set up another request and capture the callback for later invocation.
  389. MockV8DetailedMemoryReporter::GetV8MemoryUsageCallback callback;
  390. ExpectQuery(
  391. &mock_reporter,
  392. base::BindLambdaForTesting(
  393. [&callback](MockV8DetailedMemoryReporter::GetV8MemoryUsageCallback
  394. result_callback) {
  395. callback = std::move(result_callback);
  396. }));
  397. // Skip forward to when another request should be issued.
  398. task_env().FastForwardBy(kMinTimeBetweenRequests);
  399. ASSERT_FALSE(callback.is_null());
  400. // Skip forward a long while, and validate that no additional requests are
  401. // issued until the pending request has completed.
  402. task_env().FastForwardBy(10 * kMinTimeBetweenRequests);
  403. Mock::VerifyAndClearExpectations(&mock_reporter);
  404. EXPECT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  405. EXPECT_EQ(1u, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  406. ->shared_v8_bytes_used());
  407. // Expect another query once completing the query above.
  408. {
  409. auto data = NewPerProcessV8MemoryUsage(1);
  410. // Response to request 3.
  411. data->isolates[0]->shared_bytes_used = 3;
  412. ExpectQueryAndReply(&mock_reporter, std::move(data));
  413. }
  414. // Reply to the request above.
  415. {
  416. auto data = NewPerProcessV8MemoryUsage(1);
  417. // Response to request 2.
  418. data->isolates[0]->shared_bytes_used = 2;
  419. std::move(callback).Run(std::move(data));
  420. }
  421. task_env().RunUntilIdle();
  422. // This should have updated all the way to the third response.
  423. EXPECT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  424. EXPECT_EQ(3u, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  425. ->shared_v8_bytes_used());
  426. // Despite the long delay to respond to request 2, there shouldn't be another
  427. // request until kMinTimeBetweenRequests has expired.
  428. task_env().FastForwardBy(kMinTimeBetweenRequests / 2);
  429. Mock::VerifyAndClearExpectations(&mock_reporter);
  430. }
  431. TEST_F(V8DetailedMemoryDecoratorTest, MultipleProcessesHaveDistinctSchedules) {
  432. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  433. // Create a process node and validate that it gets a request.
  434. MockV8DetailedMemoryReporter reporter1;
  435. {
  436. auto data = NewPerProcessV8MemoryUsage(1);
  437. data->isolates[0]->shared_bytes_used = 1;
  438. ExpectBindAndRespondToQuery(&reporter1, std::move(data));
  439. }
  440. auto process1 = CreateNode<ProcessNodeImpl>(
  441. content::PROCESS_TYPE_RENDERER,
  442. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  443. task_env().FastForwardBy(kMinTimeBetweenRequests / 4);
  444. Mock::VerifyAndClearExpectations(&reporter1);
  445. // Create a second process node and validate that it gets a request.
  446. MockV8DetailedMemoryReporter reporter2;
  447. {
  448. auto data = NewPerProcessV8MemoryUsage(1);
  449. data->isolates[0]->shared_bytes_used = 2;
  450. ExpectBindAndRespondToQuery(&reporter2, std::move(data));
  451. }
  452. auto process2 = CreateNode<ProcessNodeImpl>(
  453. content::PROCESS_TYPE_RENDERER,
  454. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  455. task_env().RunUntilIdle();
  456. Mock::VerifyAndClearExpectations(&reporter2);
  457. EXPECT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process1.get()));
  458. EXPECT_EQ(1u, V8DetailedMemoryProcessData::ForProcessNode(process1.get())
  459. ->shared_v8_bytes_used());
  460. EXPECT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process2.get()));
  461. EXPECT_EQ(2u, V8DetailedMemoryProcessData::ForProcessNode(process2.get())
  462. ->shared_v8_bytes_used());
  463. // Capture the request time from each process.
  464. auto capture_time_lambda =
  465. [](base::TimeTicks* request_time,
  466. MockV8DetailedMemoryReporter::GetV8MemoryUsageCallback callback) {
  467. *request_time = base::TimeTicks::Now();
  468. std::move(callback).Run(NewPerProcessV8MemoryUsage(1));
  469. };
  470. base::TimeTicks process1_request_time;
  471. ExpectQuery(&reporter1,
  472. base::BindRepeating(capture_time_lambda,
  473. base::Unretained(&process1_request_time)));
  474. base::TimeTicks process2_request_time;
  475. ExpectQuery(&reporter2,
  476. base::BindRepeating(capture_time_lambda,
  477. base::Unretained(&process2_request_time)));
  478. task_env().FastForwardBy(kMinTimeBetweenRequests * 1.25);
  479. // Check that both processes got polled, and that process2 was polled after
  480. // process1.
  481. EXPECT_FALSE(process1_request_time.is_null());
  482. EXPECT_FALSE(process2_request_time.is_null());
  483. EXPECT_GT(process2_request_time, process1_request_time);
  484. }
  485. TEST_F(V8DetailedMemoryDecoratorTest, MultipleIsolatesInRenderer) {
  486. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  487. MockV8DetailedMemoryReporter reporter;
  488. auto process = CreateNode<ProcessNodeImpl>(
  489. content::PROCESS_TYPE_RENDERER,
  490. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  491. // Create a couple of frames with specified IDs.
  492. auto page = CreateNode<PageNodeImpl>();
  493. blink::LocalFrameToken frame1_id = blink::LocalFrameToken();
  494. auto frame1 = CreateNode<FrameNodeImpl>(process.get(), page.get(), nullptr,
  495. /*render_frame_id=*/1, frame1_id);
  496. blink::LocalFrameToken frame2_id = blink::LocalFrameToken();
  497. auto frame2 = CreateNode<FrameNodeImpl>(process.get(), page.get(), nullptr,
  498. /*render_frame_id=*/2, frame2_id);
  499. {
  500. auto data = NewPerProcessV8MemoryUsage(2);
  501. AddIsolateMemoryUsage(frame1_id, 1001u, data->isolates[0].get());
  502. AddIsolateMemoryUsage(frame2_id, 1002u, data->isolates[1].get());
  503. ExpectBindAndRespondToQuery(&reporter, std::move(data));
  504. }
  505. task_env().RunUntilIdle();
  506. Mock::VerifyAndClearExpectations(&reporter);
  507. ASSERT_TRUE(V8DetailedMemoryExecutionContextData::ForFrameNode(frame1.get()));
  508. EXPECT_EQ(1001u,
  509. V8DetailedMemoryExecutionContextData::ForFrameNode(frame1.get())
  510. ->v8_bytes_used());
  511. ASSERT_TRUE(V8DetailedMemoryExecutionContextData::ForFrameNode(frame2.get()));
  512. EXPECT_EQ(1002u,
  513. V8DetailedMemoryExecutionContextData::ForFrameNode(frame2.get())
  514. ->v8_bytes_used());
  515. }
  516. TEST_F(V8DetailedMemoryDecoratorTest, DataIsDistributed) {
  517. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  518. MockV8DetailedMemoryReporter reporter;
  519. {
  520. auto data = NewPerProcessV8MemoryUsage(1);
  521. // Add data for an unknown frame.
  522. AddIsolateMemoryUsage(blink::LocalFrameToken(), 1024u,
  523. data->isolates[0].get());
  524. ExpectBindAndRespondToQuery(&reporter, std::move(data));
  525. }
  526. auto process = CreateNode<ProcessNodeImpl>(
  527. content::PROCESS_TYPE_RENDERER,
  528. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  529. task_env().RunUntilIdle();
  530. Mock::VerifyAndClearExpectations(&reporter);
  531. // Since the frame was unknown, the usage should have accrued to detached.
  532. EXPECT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  533. EXPECT_EQ(1024u, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  534. ->detached_v8_bytes_used());
  535. // Create a couple of frames with specified IDs.
  536. auto page = CreateNode<PageNodeImpl>();
  537. blink::LocalFrameToken frame1_id = blink::LocalFrameToken();
  538. auto frame1 = CreateNode<FrameNodeImpl>(process.get(), page.get(), nullptr,
  539. /*render_frame_id=*/1, frame1_id);
  540. blink::LocalFrameToken frame2_id = blink::LocalFrameToken();
  541. auto frame2 = CreateNode<FrameNodeImpl>(process.get(), page.get(), nullptr,
  542. /*render_frame_id=*/2, frame2_id);
  543. {
  544. auto data = NewPerProcessV8MemoryUsage(1);
  545. AddIsolateMemoryUsage(frame1_id, 1001u, data->isolates[0].get());
  546. AddIsolateMemoryUsage(frame2_id, 1002u, data->isolates[0].get());
  547. ExpectQueryAndReply(&reporter, std::move(data));
  548. }
  549. task_env().FastForwardBy(kMinTimeBetweenRequests * 1.5);
  550. Mock::VerifyAndClearExpectations(&reporter);
  551. ASSERT_TRUE(V8DetailedMemoryExecutionContextData::ForFrameNode(frame1.get()));
  552. EXPECT_EQ(1001u,
  553. V8DetailedMemoryExecutionContextData::ForFrameNode(frame1.get())
  554. ->v8_bytes_used());
  555. ASSERT_TRUE(V8DetailedMemoryExecutionContextData::ForFrameNode(frame2.get()));
  556. EXPECT_EQ(1002u,
  557. V8DetailedMemoryExecutionContextData::ForFrameNode(frame2.get())
  558. ->v8_bytes_used());
  559. // Now verify that data is cleared for any frame that doesn't get an update,
  560. // plus verify that unknown frame data goes to detached bytes.
  561. {
  562. auto data = NewPerProcessV8MemoryUsage(1);
  563. AddIsolateMemoryUsage(frame1_id, 1003u, data->isolates[0].get());
  564. AddIsolateMemoryUsage(blink::LocalFrameToken(), 2233u,
  565. data->isolates[0].get());
  566. ExpectQueryAndReply(&reporter, std::move(data));
  567. }
  568. task_env().FastForwardBy(kMinTimeBetweenRequests);
  569. Mock::VerifyAndClearExpectations(&reporter);
  570. ASSERT_TRUE(V8DetailedMemoryExecutionContextData::ForFrameNode(frame1.get()));
  571. EXPECT_EQ(1003u,
  572. V8DetailedMemoryExecutionContextData::ForFrameNode(frame1.get())
  573. ->v8_bytes_used());
  574. EXPECT_FALSE(
  575. V8DetailedMemoryExecutionContextData::ForFrameNode(frame2.get()));
  576. ASSERT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  577. EXPECT_EQ(2233u, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  578. ->detached_v8_bytes_used());
  579. }
  580. TEST_P(V8DetailedMemoryDecoratorModeTest, LazyRequests) {
  581. constexpr base::TimeDelta kLazyRequestLength = base::Seconds(30);
  582. V8DetailedMemoryRequest lazy_request(kLazyRequestLength,
  583. MeasurementMode::kLazy, graph());
  584. MockV8DetailedMemoryReporter reporter;
  585. {
  586. auto data = NewPerProcessV8MemoryUsage(1);
  587. ExpectBindAndRespondToQuery(&reporter, std::move(data), kTestProcessID,
  588. ExpectedMode::LAZY);
  589. }
  590. auto process = CreateNode<ProcessNodeImpl>(
  591. content::PROCESS_TYPE_RENDERER,
  592. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  593. task_env().FastForwardBy(base::Seconds(1));
  594. Mock::VerifyAndClearExpectations(&reporter);
  595. // If a lazy request takes too long to respond it should be upgraded to a
  596. // bounded request if one is in the queue.
  597. constexpr base::TimeDelta kLongBoundedRequestLength = base::Seconds(45);
  598. V8DetailedMemoryRequest long_bounded_request(kLongBoundedRequestLength,
  599. bounded_mode_, graph());
  600. auto* decorator = V8DetailedMemoryDecorator::GetFromGraph(graph());
  601. ASSERT_TRUE(decorator);
  602. ASSERT_TRUE(decorator->GetNextRequest());
  603. EXPECT_EQ(decorator->GetNextRequest()->min_time_between_requests(),
  604. kLazyRequestLength);
  605. EXPECT_EQ(decorator->GetNextRequest()->mode(), MeasurementMode::kLazy);
  606. {
  607. // Next lazy request sent after 30 sec + 10 sec delay until reply = 40 sec
  608. // until reply arrives. kLongBoundedRequestLength > 40 sec so the reply
  609. // should arrive in time to prevent upgrading the request.
  610. auto data = NewPerProcessV8MemoryUsage(1);
  611. data->isolates[0]->shared_bytes_used = 1U;
  612. ExpectQueryAndDelayReply(&reporter, base::Seconds(10), std::move(data),
  613. ExpectedMode::LAZY);
  614. }
  615. // Wait long enough for the upgraded request to be sent, to verify that it
  616. // wasn't sent.
  617. task_env().FastForwardBy(kLongBoundedRequestLength);
  618. Mock::VerifyAndClearExpectations(&reporter);
  619. constexpr base::TimeDelta kUpgradeRequestLength = base::Seconds(40);
  620. V8DetailedMemoryRequest bounded_request_upgrade(kUpgradeRequestLength,
  621. bounded_mode_, graph());
  622. ASSERT_TRUE(decorator->GetNextRequest());
  623. EXPECT_EQ(decorator->GetNextRequest()->min_time_between_requests(),
  624. kLazyRequestLength);
  625. EXPECT_EQ(decorator->GetNextRequest()->mode(), MeasurementMode::kLazy);
  626. {
  627. InSequence seq;
  628. // Again, 40 sec total until reply arrives. kUpgradeRequestLength <= 40 sec
  629. // so a second upgraded request should be sent.
  630. auto data = NewPerProcessV8MemoryUsage(1);
  631. data->isolates[0]->shared_bytes_used = 2U;
  632. ExpectQueryAndDelayReply(&reporter, base::Seconds(10), std::move(data),
  633. ExpectedMode::LAZY);
  634. auto data2 = NewPerProcessV8MemoryUsage(1);
  635. data2->isolates[0]->shared_bytes_used = 3U;
  636. ExpectQueryAndReply(&reporter, std::move(data2), expected_bounded_mode_);
  637. }
  638. // Wait long enough for the upgraded request to be sent.
  639. task_env().FastForwardBy(kUpgradeRequestLength);
  640. Mock::VerifyAndClearExpectations(&reporter);
  641. EXPECT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  642. EXPECT_EQ(3u, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  643. ->shared_v8_bytes_used());
  644. // Bounded requests should be preferred over lazy requests with the same
  645. // min_time_between_requests.
  646. V8DetailedMemoryRequest short_bounded_request(kLazyRequestLength,
  647. bounded_mode_, graph());
  648. ASSERT_TRUE(decorator->GetNextRequest());
  649. EXPECT_EQ(decorator->GetNextRequest()->min_time_between_requests(),
  650. kLazyRequestLength);
  651. EXPECT_EQ(decorator->GetNextRequest()->mode(), bounded_mode_);
  652. }
  653. INSTANTIATE_TEST_SUITE_P(
  654. AllBoundedModes,
  655. V8DetailedMemoryDecoratorModeTest,
  656. ::testing::Values(std::make_pair(MeasurementMode::kBounded,
  657. ExpectedMode::DEFAULT),
  658. std::make_pair(MeasurementMode::kEagerForTesting,
  659. ExpectedMode::EAGER)));
  660. TEST_F(V8DetailedMemoryDecoratorTest, MeasurementRequestsSorted) {
  661. // Create some queries with different sample frequencies.
  662. constexpr base::TimeDelta kShortInterval(kMinTimeBetweenRequests);
  663. constexpr base::TimeDelta kMediumInterval(2 * kMinTimeBetweenRequests);
  664. constexpr base::TimeDelta kLongInterval(3 * kMinTimeBetweenRequests);
  665. // Create longer requests first to be sure they sort correctly.
  666. auto medium_memory_request =
  667. std::make_unique<V8DetailedMemoryRequest>(kMediumInterval, graph());
  668. auto short_memory_request =
  669. std::make_unique<V8DetailedMemoryRequest>(kShortInterval, graph());
  670. auto long_memory_request =
  671. std::make_unique<V8DetailedMemoryRequest>(kLongInterval, graph());
  672. auto* decorator = V8DetailedMemoryDecorator::GetFromGraph(graph());
  673. ASSERT_TRUE(decorator);
  674. // A single measurement should be taken immediately regardless of the overall
  675. // frequency.
  676. MockV8DetailedMemoryReporter mock_reporter;
  677. {
  678. auto data = NewPerProcessV8MemoryUsage(1);
  679. data->isolates[0]->shared_bytes_used = 1U;
  680. ExpectBindAndRespondToQuery(&mock_reporter, std::move(data));
  681. }
  682. auto process = CreateNode<ProcessNodeImpl>(
  683. content::PROCESS_TYPE_RENDERER,
  684. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  685. EXPECT_FALSE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  686. task_env().FastForwardBy(base::Seconds(1));
  687. // All the following FastForwardBy calls will place the clock 1 sec after a
  688. // measurement is expected.
  689. ASSERT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  690. EXPECT_EQ(1U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  691. ->shared_v8_bytes_used());
  692. // Another measurement should be taken after the shortest interval.
  693. ASSERT_TRUE(decorator->GetNextRequest());
  694. EXPECT_EQ(kShortInterval,
  695. decorator->GetNextRequest()->min_time_between_requests());
  696. {
  697. auto data = NewPerProcessV8MemoryUsage(1);
  698. data->isolates[0]->shared_bytes_used = 2U;
  699. ExpectQueryAndReply(&mock_reporter, std::move(data));
  700. task_env().FastForwardBy(kShortInterval);
  701. EXPECT_EQ(2U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  702. ->shared_v8_bytes_used());
  703. }
  704. // Remove the shortest request. Now a measurement should be taken after the
  705. // medium interval, which is twice the short interval.
  706. short_memory_request.reset();
  707. ASSERT_TRUE(decorator->GetNextRequest());
  708. EXPECT_EQ(kMediumInterval,
  709. decorator->GetNextRequest()->min_time_between_requests());
  710. {
  711. auto data = NewPerProcessV8MemoryUsage(1);
  712. data->isolates[0]->shared_bytes_used = 3U;
  713. ExpectQueryAndReply(&mock_reporter, std::move(data));
  714. task_env().FastForwardBy(kShortInterval);
  715. EXPECT_EQ(2U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  716. ->shared_v8_bytes_used());
  717. task_env().FastForwardBy(kShortInterval);
  718. EXPECT_EQ(3U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  719. ->shared_v8_bytes_used());
  720. }
  721. // Remove the longest request. A measurement should still be taken after the
  722. // medium interval.
  723. long_memory_request.reset();
  724. ASSERT_TRUE(decorator->GetNextRequest());
  725. EXPECT_EQ(kMediumInterval,
  726. decorator->GetNextRequest()->min_time_between_requests());
  727. {
  728. auto data = NewPerProcessV8MemoryUsage(1);
  729. data->isolates[0]->shared_bytes_used = 4U;
  730. ExpectQueryAndReply(&mock_reporter, std::move(data));
  731. task_env().FastForwardBy(kMediumInterval);
  732. EXPECT_EQ(4U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  733. ->shared_v8_bytes_used());
  734. }
  735. // Remove the medium request, making the queue empty.
  736. medium_memory_request.reset();
  737. EXPECT_FALSE(decorator->GetNextRequest());
  738. {
  739. auto data = NewPerProcessV8MemoryUsage(1);
  740. data->isolates[0]->shared_bytes_used = 5U;
  741. ExpectQueryAndReply(&mock_reporter, std::move(data));
  742. task_env().FastForwardBy(kLongInterval);
  743. EXPECT_EQ(4U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  744. ->shared_v8_bytes_used());
  745. }
  746. // Create another request. Since this is the first request in an empty queue
  747. // the measurement should be taken immediately.
  748. long_memory_request =
  749. std::make_unique<V8DetailedMemoryRequest>(kLongInterval, graph());
  750. ASSERT_TRUE(decorator->GetNextRequest());
  751. EXPECT_EQ(kLongInterval,
  752. decorator->GetNextRequest()->min_time_between_requests());
  753. task_env().FastForwardBy(base::Seconds(1));
  754. EXPECT_EQ(5U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  755. ->shared_v8_bytes_used());
  756. {
  757. auto data = NewPerProcessV8MemoryUsage(1);
  758. data->isolates[0]->shared_bytes_used = 6U;
  759. ExpectQueryAndReply(&mock_reporter, std::move(data));
  760. task_env().FastForwardBy(kLongInterval);
  761. EXPECT_EQ(6U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  762. ->shared_v8_bytes_used());
  763. }
  764. // Now there should be kLongInterval - 1 sec until the next measurement.
  765. // Make sure a shorter request replaces this (the new interval should cause a
  766. // measurement and the old interval should not).
  767. medium_memory_request =
  768. std::make_unique<V8DetailedMemoryRequest>(kMediumInterval, graph());
  769. ASSERT_TRUE(decorator->GetNextRequest());
  770. EXPECT_EQ(kMediumInterval,
  771. decorator->GetNextRequest()->min_time_between_requests());
  772. {
  773. auto data = NewPerProcessV8MemoryUsage(1);
  774. data->isolates[0]->shared_bytes_used = 7U;
  775. ExpectQueryAndReply(&mock_reporter, std::move(data));
  776. task_env().FastForwardBy(kMediumInterval);
  777. EXPECT_EQ(7U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  778. ->shared_v8_bytes_used());
  779. }
  780. {
  781. auto data = NewPerProcessV8MemoryUsage(1);
  782. data->isolates[0]->shared_bytes_used = 8U;
  783. ExpectQueryAndReply(&mock_reporter, std::move(data));
  784. constexpr base::TimeDelta kRestOfLongInterval =
  785. kLongInterval - kMediumInterval;
  786. task_env().FastForwardBy(kRestOfLongInterval);
  787. EXPECT_EQ(7U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  788. ->shared_v8_bytes_used());
  789. task_env().FastForwardBy(kMediumInterval - kRestOfLongInterval);
  790. EXPECT_EQ(8U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  791. ->shared_v8_bytes_used());
  792. }
  793. // Remove the medium request and add it back. The measurement interval should
  794. // not change.
  795. medium_memory_request.reset();
  796. ASSERT_TRUE(decorator->GetNextRequest());
  797. EXPECT_EQ(kLongInterval,
  798. decorator->GetNextRequest()->min_time_between_requests());
  799. medium_memory_request =
  800. std::make_unique<V8DetailedMemoryRequest>(kMediumInterval, graph());
  801. ASSERT_TRUE(decorator->GetNextRequest());
  802. EXPECT_EQ(kMediumInterval,
  803. decorator->GetNextRequest()->min_time_between_requests());
  804. {
  805. auto data = NewPerProcessV8MemoryUsage(1);
  806. data->isolates[0]->shared_bytes_used = 9U;
  807. ExpectQueryAndReply(&mock_reporter, std::move(data));
  808. task_env().FastForwardBy(kMediumInterval);
  809. EXPECT_EQ(9U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  810. ->shared_v8_bytes_used());
  811. }
  812. // Add another long request. There should still be requests after the medium
  813. // interval.
  814. auto long_memory_request2 =
  815. std::make_unique<V8DetailedMemoryRequest>(kLongInterval, graph());
  816. ASSERT_TRUE(decorator->GetNextRequest());
  817. EXPECT_EQ(kMediumInterval,
  818. decorator->GetNextRequest()->min_time_between_requests());
  819. {
  820. auto data = NewPerProcessV8MemoryUsage(1);
  821. data->isolates[0]->shared_bytes_used = 10U;
  822. ExpectQueryAndReply(&mock_reporter, std::move(data));
  823. task_env().FastForwardBy(kMediumInterval);
  824. EXPECT_EQ(10U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  825. ->shared_v8_bytes_used());
  826. }
  827. // Remove the medium request. Now there are 2 requests which should cause
  828. // measurements at the same interval. Make sure only 1 measurement is taken.
  829. medium_memory_request.reset();
  830. ASSERT_TRUE(decorator->GetNextRequest());
  831. EXPECT_EQ(kLongInterval,
  832. decorator->GetNextRequest()->min_time_between_requests());
  833. {
  834. auto data = NewPerProcessV8MemoryUsage(1);
  835. data->isolates[0]->shared_bytes_used = 11U;
  836. ExpectQueryAndReply(&mock_reporter, std::move(data));
  837. task_env().FastForwardBy(kLongInterval);
  838. EXPECT_EQ(11U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  839. ->shared_v8_bytes_used());
  840. }
  841. // Remove 1 of the 2 long requests. Measurements should not change.
  842. long_memory_request2.reset();
  843. ASSERT_TRUE(decorator->GetNextRequest());
  844. EXPECT_EQ(kLongInterval,
  845. decorator->GetNextRequest()->min_time_between_requests());
  846. {
  847. auto data = NewPerProcessV8MemoryUsage(1);
  848. data->isolates[0]->shared_bytes_used = 12U;
  849. ExpectQueryAndReply(&mock_reporter, std::move(data));
  850. task_env().FastForwardBy(kLongInterval);
  851. EXPECT_EQ(12U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  852. ->shared_v8_bytes_used());
  853. }
  854. }
  855. TEST_F(V8DetailedMemoryDecoratorTest, MeasurementRequestsWithDelay) {
  856. // Create some queries with different sample frequencies.
  857. constexpr base::TimeDelta kShortInterval(kMinTimeBetweenRequests);
  858. constexpr base::TimeDelta kMediumInterval(2 * kMinTimeBetweenRequests);
  859. constexpr base::TimeDelta kLongInterval(3 * kMinTimeBetweenRequests);
  860. // Make measurements take long enough that a second request could be sent.
  861. constexpr base::TimeDelta kMeasurementLength(1.5 * kShortInterval);
  862. constexpr base::TimeDelta kOneSecond = base::Seconds(1);
  863. auto long_memory_request =
  864. std::make_unique<V8DetailedMemoryRequest>(kLongInterval, graph());
  865. auto* decorator = V8DetailedMemoryDecorator::GetFromGraph(graph());
  866. ASSERT_TRUE(decorator);
  867. // Move past the first request since it's complicated to untangle the Bind
  868. // and QueryAndDelayReply expectations.
  869. MockV8DetailedMemoryReporter mock_reporter;
  870. {
  871. auto data = NewPerProcessV8MemoryUsage(1);
  872. data->isolates[0]->shared_bytes_used = 0U;
  873. ExpectBindAndRespondToQuery(&mock_reporter, std::move(data));
  874. }
  875. auto process = CreateNode<ProcessNodeImpl>(
  876. content::PROCESS_TYPE_RENDERER,
  877. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  878. task_env().FastForwardBy(kOneSecond);
  879. // All the following FastForwardBy calls will place the clock 1 sec after a
  880. // measurement is expected.
  881. // Advance to the middle of a measurement and create a new request. Should
  882. // update min_time_between_requests but not start a new measurement until the
  883. // existing measurement finishes.
  884. {
  885. auto data = NewPerProcessV8MemoryUsage(1);
  886. data->isolates[0]->shared_bytes_used = 1U;
  887. ExpectQueryAndDelayReply(&mock_reporter, kMeasurementLength,
  888. std::move(data));
  889. }
  890. task_env().FastForwardBy(kLongInterval);
  891. EXPECT_EQ(last_query_time(), task_env().NowTicks() - kOneSecond)
  892. << "Measurement didn't start when expected";
  893. EXPECT_EQ(0U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  894. ->shared_v8_bytes_used())
  895. << "Measurement ended early";
  896. base::TimeTicks measurement_start_time = last_query_time();
  897. auto medium_memory_request =
  898. std::make_unique<V8DetailedMemoryRequest>(kMediumInterval, graph());
  899. ASSERT_TRUE(decorator->GetNextRequest());
  900. EXPECT_EQ(kMediumInterval,
  901. decorator->GetNextRequest()->min_time_between_requests());
  902. task_env().FastForwardBy(kMeasurementLength);
  903. ASSERT_EQ(1U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  904. ->shared_v8_bytes_used())
  905. << "Measurement didn't end when expected";
  906. EXPECT_EQ(last_query_time(), measurement_start_time);
  907. // Next measurement should start kMediumInterval secs after the START of the
  908. // last measurement.
  909. {
  910. auto data = NewPerProcessV8MemoryUsage(1);
  911. data->isolates[0]->shared_bytes_used = 2U;
  912. ExpectQueryAndDelayReply(&mock_reporter, kMeasurementLength,
  913. std::move(data));
  914. }
  915. task_env().FastForwardBy(kMediumInterval - kMeasurementLength);
  916. EXPECT_EQ(last_query_time(), task_env().NowTicks() - kOneSecond)
  917. << "Measurement didn't start when expected";
  918. EXPECT_EQ(1U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  919. ->shared_v8_bytes_used())
  920. << "Measurement ended early";
  921. measurement_start_time = last_query_time();
  922. task_env().FastForwardBy(kMeasurementLength);
  923. EXPECT_EQ(2U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  924. ->shared_v8_bytes_used())
  925. << "Measurement didn't end when expected";
  926. EXPECT_EQ(last_query_time(), measurement_start_time);
  927. // Create a request that would be sent in the middle of a measurement. It
  928. // should start immediately after the measurement finishes.
  929. {
  930. auto data = NewPerProcessV8MemoryUsage(1);
  931. data->isolates[0]->shared_bytes_used = 3U;
  932. ExpectQueryAndDelayReply(&mock_reporter, kMeasurementLength,
  933. std::move(data));
  934. }
  935. task_env().FastForwardBy(kMediumInterval - kMeasurementLength);
  936. EXPECT_EQ(last_query_time(), task_env().NowTicks() - kOneSecond)
  937. << "Measurement didn't start when expected";
  938. EXPECT_EQ(2U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  939. ->shared_v8_bytes_used())
  940. << "Measurement ended early";
  941. measurement_start_time = last_query_time();
  942. auto short_memory_request =
  943. std::make_unique<V8DetailedMemoryRequest>(kShortInterval, graph());
  944. ASSERT_TRUE(decorator->GetNextRequest());
  945. EXPECT_EQ(kShortInterval,
  946. decorator->GetNextRequest()->min_time_between_requests());
  947. EXPECT_EQ(last_query_time(), measurement_start_time);
  948. {
  949. auto data = NewPerProcessV8MemoryUsage(1);
  950. data->isolates[0]->shared_bytes_used = 4U;
  951. ExpectQueryAndDelayReply(&mock_reporter, kMeasurementLength,
  952. std::move(data));
  953. }
  954. task_env().FastForwardBy(kMeasurementLength);
  955. EXPECT_EQ(last_query_time(), task_env().NowTicks() - kOneSecond)
  956. << "Measurement didn't start when expected";
  957. EXPECT_EQ(3U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  958. ->shared_v8_bytes_used())
  959. << "Measurement ended early";
  960. measurement_start_time = last_query_time();
  961. // Delete the short request. Should update min_time_between_requests but not
  962. // start a new measurement until the existing measurement finishes.
  963. short_memory_request.reset();
  964. ASSERT_TRUE(decorator->GetNextRequest());
  965. EXPECT_EQ(kMediumInterval,
  966. decorator->GetNextRequest()->min_time_between_requests());
  967. task_env().FastForwardBy(kMeasurementLength);
  968. EXPECT_EQ(4U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  969. ->shared_v8_bytes_used())
  970. << "Measurement didn't end when expected";
  971. EXPECT_EQ(last_query_time(), measurement_start_time);
  972. // Delete the last request while a measurement is in process. The
  973. // measurement should finish successfully but no more should be sent.
  974. {
  975. auto data = NewPerProcessV8MemoryUsage(1);
  976. data->isolates[0]->shared_bytes_used = 5U;
  977. ExpectQueryAndDelayReply(&mock_reporter, kMeasurementLength,
  978. std::move(data));
  979. }
  980. task_env().FastForwardBy(kMediumInterval - kMeasurementLength);
  981. EXPECT_EQ(last_query_time(), task_env().NowTicks() - kOneSecond)
  982. << "Measurement didn't start when expected";
  983. EXPECT_EQ(4U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  984. ->shared_v8_bytes_used())
  985. << "Measurement ended early";
  986. measurement_start_time = last_query_time();
  987. medium_memory_request.reset();
  988. long_memory_request.reset();
  989. EXPECT_FALSE(decorator->GetNextRequest());
  990. task_env().FastForwardBy(kMeasurementLength);
  991. EXPECT_EQ(5U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  992. ->shared_v8_bytes_used())
  993. << "Measurement didn't end when expected";
  994. EXPECT_EQ(last_query_time(), measurement_start_time);
  995. // No more requests should be sent.
  996. Mock::VerifyAndClearExpectations(this);
  997. task_env().FastForwardBy(kLongInterval);
  998. }
  999. TEST_F(V8DetailedMemoryDecoratorTest, MeasurementRequestOutlivesDecorator) {
  1000. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  1001. auto* decorator = V8DetailedMemoryDecorator::GetFromGraph(graph());
  1002. ASSERT_TRUE(decorator);
  1003. MockV8DetailedMemoryReporter mock_reporter;
  1004. {
  1005. auto data = NewPerProcessV8MemoryUsage(1);
  1006. data->isolates[0]->shared_bytes_used = 1U;
  1007. ExpectBindAndRespondToQuery(&mock_reporter, std::move(data));
  1008. }
  1009. auto process = CreateNode<ProcessNodeImpl>(
  1010. content::PROCESS_TYPE_RENDERER,
  1011. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  1012. task_env().FastForwardBy(base::Seconds(1));
  1013. ASSERT_EQ(1U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  1014. ->shared_v8_bytes_used())
  1015. << "First measurement didn't happen when expected";
  1016. graph()->TakeFromGraph(decorator);
  1017. // No request should be sent, and the decorator destructor should not DCHECK.
  1018. Mock::VerifyAndClearExpectations(this);
  1019. task_env().FastForwardBy(kMinTimeBetweenRequests);
  1020. }
  1021. TEST_F(V8DetailedMemoryDecoratorTest, NotifyObservers) {
  1022. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  1023. MockV8DetailedMemoryObserver observer1;
  1024. MockV8DetailedMemoryObserver observer2;
  1025. memory_request.AddObserver(&observer1);
  1026. memory_request.AddObserver(&observer2);
  1027. // Create a process node and validate that all observers are notified when a
  1028. // measurement is available for it.
  1029. MockV8DetailedMemoryReporter reporter1;
  1030. {
  1031. auto data = NewPerProcessV8MemoryUsage(1);
  1032. data->isolates[0]->shared_bytes_used = 1U;
  1033. ExpectBindAndRespondToQuery(&reporter1, std::move(data));
  1034. }
  1035. auto process1 = CreateNode<ProcessNodeImpl>(
  1036. content::PROCESS_TYPE_RENDERER,
  1037. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  1038. observer1.ExpectObservationOnProcess(process1.get(), 1U);
  1039. observer2.ExpectObservationOnProcess(process1.get(), 1U);
  1040. task_env().FastForwardBy(kMinTimeBetweenRequests / 2);
  1041. Mock::VerifyAndClearExpectations(&reporter1);
  1042. Mock::VerifyAndClearExpectations(&observer1);
  1043. Mock::VerifyAndClearExpectations(&observer2);
  1044. // Create a process node and validate that all observers are notified when
  1045. // any measurement is available. After fast-forwarding the first measurement
  1046. // for process2 and the second measurement for process1 will arrive.
  1047. MockV8DetailedMemoryReporter reporter2;
  1048. {
  1049. auto data = NewPerProcessV8MemoryUsage(1);
  1050. data->isolates[0]->shared_bytes_used = 2U;
  1051. ExpectBindAndRespondToQuery(&reporter2, std::move(data));
  1052. }
  1053. {
  1054. auto data = NewPerProcessV8MemoryUsage(1);
  1055. data->isolates[0]->shared_bytes_used = 3U;
  1056. ExpectQueryAndReply(&reporter1, std::move(data));
  1057. }
  1058. auto process2 = CreateNode<ProcessNodeImpl>(
  1059. content::PROCESS_TYPE_RENDERER,
  1060. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  1061. observer1.ExpectObservationOnProcess(process2.get(), 2U);
  1062. observer2.ExpectObservationOnProcess(process2.get(), 2U);
  1063. observer1.ExpectObservationOnProcess(process1.get(), 3U);
  1064. observer2.ExpectObservationOnProcess(process1.get(), 3U);
  1065. task_env().FastForwardBy(kMinTimeBetweenRequests / 2);
  1066. Mock::VerifyAndClearExpectations(&reporter1);
  1067. Mock::VerifyAndClearExpectations(&reporter2);
  1068. Mock::VerifyAndClearExpectations(&observer1);
  1069. Mock::VerifyAndClearExpectations(&observer2);
  1070. // Remove an observer and make sure the other is still notified after the
  1071. // next measurement.
  1072. {
  1073. auto data = NewPerProcessV8MemoryUsage(1);
  1074. data->isolates[0]->shared_bytes_used = 4U;
  1075. ExpectQueryAndReply(&reporter1, std::move(data));
  1076. }
  1077. {
  1078. auto data = NewPerProcessV8MemoryUsage(1);
  1079. data->isolates[0]->shared_bytes_used = 5U;
  1080. ExpectQueryAndReply(&reporter2, std::move(data));
  1081. }
  1082. memory_request.RemoveObserver(&observer1);
  1083. observer2.ExpectObservationOnProcess(process1.get(), 4U);
  1084. observer2.ExpectObservationOnProcess(process2.get(), 5U);
  1085. task_env().FastForwardBy(kMinTimeBetweenRequests);
  1086. Mock::VerifyAndClearExpectations(&reporter1);
  1087. Mock::VerifyAndClearExpectations(&reporter2);
  1088. Mock::VerifyAndClearExpectations(&observer1);
  1089. Mock::VerifyAndClearExpectations(&observer2);
  1090. // Must remove the observer before destroying the request to avoid a DCHECK
  1091. // from ObserverList.
  1092. memory_request.RemoveObserver(&observer2);
  1093. }
  1094. TEST_F(V8DetailedMemoryDecoratorTest, ObserverOutlivesDecorator) {
  1095. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  1096. MockV8DetailedMemoryObserver observer;
  1097. memory_request.AddObserver(&observer);
  1098. // Create a process node and move past the initial request to it.
  1099. MockV8DetailedMemoryReporter reporter;
  1100. {
  1101. auto data = NewPerProcessV8MemoryUsage(1);
  1102. data->isolates[0]->shared_bytes_used = 1U;
  1103. ExpectBindAndRespondToQuery(&reporter, std::move(data));
  1104. }
  1105. auto process = CreateNode<ProcessNodeImpl>(
  1106. content::PROCESS_TYPE_RENDERER,
  1107. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  1108. observer.ExpectObservationOnProcess(process.get(), 1U);
  1109. task_env().FastForwardBy(base::Seconds(1));
  1110. Mock::VerifyAndClearExpectations(&reporter);
  1111. Mock::VerifyAndClearExpectations(&observer);
  1112. // Start the next measurement.
  1113. {
  1114. auto data = NewPerProcessV8MemoryUsage(1);
  1115. data->isolates[0]->shared_bytes_used = 2U;
  1116. ExpectQueryAndDelayReply(&reporter, kMinTimeBetweenRequests,
  1117. std::move(data));
  1118. }
  1119. task_env().FastForwardBy(kMinTimeBetweenRequests);
  1120. // Destroy the decorator before the measurement completes. The observer
  1121. // should not be notified.
  1122. auto* decorator = V8DetailedMemoryDecorator::GetFromGraph(graph());
  1123. ASSERT_TRUE(decorator);
  1124. graph()->TakeFromGraph(decorator);
  1125. task_env().FastForwardBy(kMinTimeBetweenRequests);
  1126. // Must remove the observer before destroying the request to avoid a DCHECK
  1127. // from ObserverList.
  1128. memory_request.RemoveObserver(&observer);
  1129. }
  1130. TEST_F(V8DetailedMemoryDecoratorTest, SingleProcessRequest) {
  1131. // Create 2 renderer processes. Create one request that measures both of
  1132. // them, and one request that measures only one.
  1133. constexpr RenderProcessHostId kProcessId1 = RenderProcessHostId(0xFAB);
  1134. auto process1 = CreateNode<ProcessNodeImpl>(
  1135. content::PROCESS_TYPE_RENDERER,
  1136. RenderProcessHostProxy::CreateForTesting(kProcessId1));
  1137. constexpr RenderProcessHostId kProcessId2 = RenderProcessHostId(0xBAF);
  1138. auto process2 = CreateNode<ProcessNodeImpl>(
  1139. content::PROCESS_TYPE_RENDERER,
  1140. RenderProcessHostProxy::CreateForTesting(kProcessId2));
  1141. // Set the all process request to only send once within the test.
  1142. V8DetailedMemoryRequest all_process_request(kMinTimeBetweenRequests * 100);
  1143. all_process_request.StartMeasurement(graph());
  1144. auto process1_request =
  1145. std::make_unique<V8DetailedMemoryRequest>(kMinTimeBetweenRequests);
  1146. process1_request->StartMeasurementForProcess(process1.get());
  1147. MockV8DetailedMemoryReporter mock_reporter1;
  1148. MockV8DetailedMemoryReporter mock_reporter2;
  1149. {
  1150. // Response to initial request in process 1.
  1151. auto data = NewPerProcessV8MemoryUsage(1);
  1152. data->isolates[0]->shared_bytes_used = 1U;
  1153. ExpectBindAndRespondToQuery(&mock_reporter1, std::move(data), kProcessId1);
  1154. // Response to initial request in process 2.
  1155. data = NewPerProcessV8MemoryUsage(1);
  1156. data->isolates[0]->shared_bytes_used = 2U;
  1157. ExpectBindAndRespondToQuery(&mock_reporter2, std::move(data), kProcessId2);
  1158. }
  1159. // All the following FastForwardBy calls will place the clock 1 sec after a
  1160. // measurement is expected.
  1161. task_env().FastForwardBy(base::Seconds(1));
  1162. testing::Mock::VerifyAndClearExpectations(&mock_reporter1);
  1163. testing::Mock::VerifyAndClearExpectations(&mock_reporter2);
  1164. ASSERT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process1.get()));
  1165. EXPECT_EQ(1U, V8DetailedMemoryProcessData::ForProcessNode(process1.get())
  1166. ->shared_v8_bytes_used());
  1167. ASSERT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process2.get()));
  1168. EXPECT_EQ(2U, V8DetailedMemoryProcessData::ForProcessNode(process2.get())
  1169. ->shared_v8_bytes_used());
  1170. // After kMinTimeBetweenRequests another request should be sent to process1,
  1171. // but not process2.
  1172. {
  1173. auto data = NewPerProcessV8MemoryUsage(1);
  1174. data->isolates[0]->shared_bytes_used = 3U;
  1175. ExpectQueryAndDelayReply(&mock_reporter1, kMinTimeBetweenRequests,
  1176. std::move(data));
  1177. }
  1178. task_env().FastForwardBy(kMinTimeBetweenRequests);
  1179. testing::Mock::VerifyAndClearExpectations(&mock_reporter1);
  1180. testing::Mock::VerifyAndClearExpectations(&mock_reporter2);
  1181. // Delete process1 request while waiting for measurement result.
  1182. process1_request.reset();
  1183. task_env().FastForwardBy(kMinTimeBetweenRequests);
  1184. testing::Mock::VerifyAndClearExpectations(&mock_reporter1);
  1185. testing::Mock::VerifyAndClearExpectations(&mock_reporter2);
  1186. ASSERT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process1.get()));
  1187. EXPECT_EQ(3U, V8DetailedMemoryProcessData::ForProcessNode(process1.get())
  1188. ->shared_v8_bytes_used());
  1189. // Recreate process1 request. The new request will be sent immediately since
  1190. // enough time has passed since the last request.
  1191. {
  1192. auto data = NewPerProcessV8MemoryUsage(1);
  1193. data->isolates[0]->shared_bytes_used = 4U;
  1194. ExpectQueryAndReply(&mock_reporter1, std::move(data));
  1195. }
  1196. process1_request =
  1197. std::make_unique<V8DetailedMemoryRequest>(kMinTimeBetweenRequests);
  1198. process1_request->StartMeasurementForProcess(process1.get());
  1199. // Test observers of single-process requests.
  1200. MockV8DetailedMemoryObserver mock_observer;
  1201. process1_request->AddObserver(&mock_observer);
  1202. mock_observer.ExpectObservationOnProcess(process1.get(), 4U);
  1203. task_env().FastForwardBy(base::Seconds(1));
  1204. testing::Mock::VerifyAndClearExpectations(&mock_reporter1);
  1205. testing::Mock::VerifyAndClearExpectations(&mock_reporter2);
  1206. testing::Mock::VerifyAndClearExpectations(&mock_observer);
  1207. ASSERT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process1.get()));
  1208. EXPECT_EQ(4U, V8DetailedMemoryProcessData::ForProcessNode(process1.get())
  1209. ->shared_v8_bytes_used());
  1210. // Delete process1 while the request still exists. Nothing should crash.
  1211. process1.reset();
  1212. task_env().FastForwardBy(kMinTimeBetweenRequests);
  1213. testing::Mock::VerifyAndClearExpectations(&mock_reporter1);
  1214. testing::Mock::VerifyAndClearExpectations(&mock_reporter2);
  1215. testing::Mock::VerifyAndClearExpectations(&mock_observer);
  1216. // Clean up.
  1217. process1_request->RemoveObserver(&mock_observer);
  1218. }
  1219. TEST_P(V8DetailedMemoryDecoratorSingleProcessModeTest,
  1220. SingleProcessLazyRequest) {
  1221. // Create a single process node so both "all process" and "single process"
  1222. // requests will have a single expectation, which reduces boilerplate.
  1223. auto process = CreateNode<ProcessNodeImpl>(
  1224. content::PROCESS_TYPE_RENDERER,
  1225. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  1226. V8DetailedMemoryRequest lazy_request(kMinTimeBetweenRequests,
  1227. MeasurementMode::kLazy);
  1228. V8DetailedMemoryRequest bounded_request(kMinTimeBetweenRequests * 2,
  1229. MeasurementMode::kBounded);
  1230. if (single_process_mode_ == MeasurementMode::kLazy) {
  1231. // Test that lazy single-process requests can't starve bounded all-process
  1232. // requests.
  1233. lazy_request.StartMeasurementForProcess(process.get());
  1234. bounded_request.StartMeasurement(graph());
  1235. } else {
  1236. // Test that lazy all-process requests can't starve bounded single-process
  1237. // requests.
  1238. lazy_request.StartMeasurement(graph());
  1239. bounded_request.StartMeasurementForProcess(process.get());
  1240. }
  1241. MockV8DetailedMemoryReporter mock_reporter;
  1242. {
  1243. // Response to initial request which is sent immediately. This will use the
  1244. // LAZY mode from |lazy_request| because it has a lower frequency.
  1245. auto data = NewPerProcessV8MemoryUsage(1);
  1246. data->isolates[0]->shared_bytes_used = 1U;
  1247. ExpectBindAndRespondToQuery(&mock_reporter, std::move(data), kTestProcessID,
  1248. ExpectedMode::LAZY);
  1249. }
  1250. // All the following FastForwardBy calls will place the clock 1 sec after a
  1251. // measurement is expected.
  1252. task_env().FastForwardBy(base::Seconds(1));
  1253. testing::Mock::VerifyAndClearExpectations(&mock_reporter);
  1254. // Delay next lazy reply and expect |bounded_request| to be sent while
  1255. // waiting.
  1256. {
  1257. auto data = NewPerProcessV8MemoryUsage(1);
  1258. data->isolates[0]->shared_bytes_used = 3U;
  1259. ExpectQueryAndDelayReply(&mock_reporter, 2 * kMinTimeBetweenRequests,
  1260. std::move(data), ExpectedMode::LAZY);
  1261. }
  1262. task_env().FastForwardBy(kMinTimeBetweenRequests);
  1263. testing::Mock::VerifyAndClearExpectations(&mock_reporter);
  1264. // Lazy request sent, now 2*kMinTimeBetweenRequests until reply and
  1265. // 3*kMinTimeBetweenRequests until next lazy request. Advancing the clock
  1266. // should send |bounded_request| to both processes.
  1267. {
  1268. auto data = NewPerProcessV8MemoryUsage(1);
  1269. data->isolates[0]->shared_bytes_used = 4U;
  1270. ExpectQueryAndReply(&mock_reporter, std::move(data), ExpectedMode::DEFAULT);
  1271. }
  1272. task_env().FastForwardBy(kMinTimeBetweenRequests);
  1273. testing::Mock::VerifyAndClearExpectations(&mock_reporter);
  1274. ASSERT_TRUE(V8DetailedMemoryProcessData::ForProcessNode(process.get()));
  1275. EXPECT_EQ(4U, V8DetailedMemoryProcessData::ForProcessNode(process.get())
  1276. ->shared_v8_bytes_used());
  1277. }
  1278. INSTANTIATE_TEST_SUITE_P(SingleProcessLazyOrBounded,
  1279. V8DetailedMemoryDecoratorSingleProcessModeTest,
  1280. ::testing::Values(MeasurementMode::kLazy,
  1281. MeasurementMode::kBounded));
  1282. TEST_F(V8DetailedMemoryDecoratorDeathTest, MultipleStartMeasurement) {
  1283. EXPECT_DCHECK_DEATH({
  1284. V8DetailedMemoryRequest request(kMinTimeBetweenRequests);
  1285. request.StartMeasurement(graph());
  1286. request.StartMeasurement(graph());
  1287. });
  1288. EXPECT_DCHECK_DEATH({
  1289. V8DetailedMemoryRequest request(kMinTimeBetweenRequests, graph());
  1290. request.StartMeasurement(graph());
  1291. });
  1292. }
  1293. TEST_F(V8DetailedMemoryDecoratorDeathTest, EnforceObserversRemoved) {
  1294. // Declare the observers before the requests to ensure they're deleted
  1295. // afterwards.
  1296. EXPECT_DCHECK_DEATH({
  1297. MockV8DetailedMemoryObserver observer;
  1298. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests);
  1299. memory_request.AddObserver(&observer);
  1300. // Request should explode if it still has observers registered when it goes
  1301. // out of scope.
  1302. });
  1303. EXPECT_DCHECK_DEATH({
  1304. MockV8DetailedMemoryObserverAnySeq observer;
  1305. V8DetailedMemoryRequestAnySeq memory_request(kMinTimeBetweenRequests);
  1306. memory_request.AddObserver(&observer);
  1307. // Request should explode if it still has observers registered when it goes
  1308. // out of scope.
  1309. });
  1310. }
  1311. TEST_F(V8DetailedMemoryDecoratorDeathTest, InvalidEagerModeConfig) {
  1312. // Not allowed to use kEagerForTesting mode without calling
  1313. // SetEagerMemoryMeasurementEnabledForTesting.
  1314. EXPECT_DCHECK_DEATH({
  1315. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests,
  1316. MeasurementMode::kEagerForTesting);
  1317. });
  1318. EXPECT_DCHECK_DEATH({
  1319. V8DetailedMemoryRequestAnySeq memory_request(
  1320. kMinTimeBetweenRequests, MeasurementMode::kEagerForTesting);
  1321. });
  1322. }
  1323. TEST_F(V8DetailedMemoryDecoratorDeathTest, NonPositiveTimeDeltas) {
  1324. // Zero and negative.
  1325. EXPECT_DCHECK_DEATH({
  1326. base::TimeDelta zero;
  1327. V8DetailedMemoryRequestAnySeq memory_request(zero);
  1328. });
  1329. EXPECT_DCHECK_DEATH({
  1330. V8DetailedMemoryRequestAnySeq memory_request(kMinTimeBetweenRequests * -1);
  1331. });
  1332. }
  1333. TEST_F(V8DetailedMemoryDecoratorDeathTest, ExtremeTImeDeltas) {
  1334. // Infinite TimeDelta's are disallowed.
  1335. EXPECT_DCHECK_DEATH({
  1336. V8DetailedMemoryRequestAnySeq memory_request(base::TimeDelta::Min());
  1337. });
  1338. EXPECT_DCHECK_DEATH({
  1339. V8DetailedMemoryRequestAnySeq memory_request(base::TimeDelta::Max());
  1340. });
  1341. }
  1342. TEST_F(V8DetailedMemoryRequestAnySeqTest, RequestIsSequenceSafe) {
  1343. // Create some test data to return for a measurement request.
  1344. constexpr uint64_t kAssociatedBytes = 0x123;
  1345. const blink::LocalFrameToken frame_token(main_frame()->GetFrameToken());
  1346. const content::GlobalRenderFrameHostId frame_id(main_process_id().value(),
  1347. main_frame()->GetRoutingID());
  1348. V8DetailedMemoryProcessData expected_process_data;
  1349. expected_process_data.set_shared_v8_bytes_used(kSharedBytes);
  1350. V8DetailedMemoryObserverAnySeq::FrameDataMap expected_frame_data;
  1351. expected_frame_data[frame_id].set_v8_bytes_used(kAssociatedBytes);
  1352. MockV8DetailedMemoryReporter reporter;
  1353. {
  1354. auto data = NewPerProcessV8MemoryUsage(1);
  1355. data->isolates[0]->shared_bytes_used = kSharedBytes;
  1356. AddIsolateMemoryUsage(frame_token, kAssociatedBytes,
  1357. data->isolates[0].get());
  1358. ExpectBindAndRespondToQuery(&reporter, std::move(data), main_process_id());
  1359. }
  1360. // Decorator should not exist before creating a request.
  1361. PerformanceManager::CallOnGraph(
  1362. FROM_HERE, base::BindOnce([](Graph* graph) {
  1363. EXPECT_FALSE(V8DetailedMemoryDecorator::GetFromGraph(graph));
  1364. }));
  1365. // This object is created on the main sequence but should cause a
  1366. // V8DetailedMemoryRequest to be created on the graph sequence after the
  1367. // above task.
  1368. auto request =
  1369. std::make_unique<V8DetailedMemoryRequestAnySeq>(kMinTimeBetweenRequests);
  1370. MockV8DetailedMemoryObserverAnySeq observer;
  1371. request->AddObserver(&observer);
  1372. // Decorator now exists and has the request frequency set, proving that the
  1373. // V8DetailedMemoryRequest was created.
  1374. PerformanceManager::CallOnGraph(
  1375. FROM_HERE, base::BindOnce([](Graph* graph) {
  1376. auto* decorator = V8DetailedMemoryDecorator::GetFromGraph(graph);
  1377. ASSERT_TRUE(decorator);
  1378. ASSERT_TRUE(decorator->GetNextRequest());
  1379. EXPECT_EQ(kMinTimeBetweenRequests,
  1380. decorator->GetNextRequest()->min_time_between_requests());
  1381. }));
  1382. // The observer should be invoked on the main sequence when a measurement is
  1383. // available. Exit the RunLoop when this happens.
  1384. base::RunLoop run_loop;
  1385. EXPECT_CALL(observer, OnV8MemoryMeasurementAvailable(main_process_id(),
  1386. expected_process_data,
  1387. expected_frame_data))
  1388. .WillOnce([&]() {
  1389. run_loop.Quit();
  1390. ASSERT_TRUE(
  1391. this->GetMainThreadTaskRunner()->RunsTasksInCurrentSequence())
  1392. << "Observer invoked on wrong sequence";
  1393. // Verify that the notification parameters can be used to retrieve a
  1394. // RenderFrameHost and RenderProcessHost. This is safe on the main
  1395. // thread.
  1396. EXPECT_NE(nullptr, content::RenderProcessHost::FromID(
  1397. main_process_id().value()));
  1398. const content::GlobalRenderFrameHostId frame_id =
  1399. expected_frame_data.cbegin()->first;
  1400. EXPECT_NE(nullptr, content::RenderFrameHost::FromID(frame_id));
  1401. });
  1402. // Now execute all the above tasks.
  1403. run_loop.Run();
  1404. Mock::VerifyAndClearExpectations(this);
  1405. Mock::VerifyAndClearExpectations(&reporter);
  1406. Mock::VerifyAndClearExpectations(&observer);
  1407. // Destroying the object on the main sequence should cause the wrapped
  1408. // V8DetailedMemoryRequest to be destroyed on the graph sequence after any
  1409. // scheduled tasks, which resets the request frequency to zero.
  1410. PerformanceManager::CallOnGraph(
  1411. FROM_HERE, base::BindOnce([](Graph* graph) {
  1412. auto* decorator = V8DetailedMemoryDecorator::GetFromGraph(graph);
  1413. ASSERT_TRUE(decorator);
  1414. ASSERT_TRUE(decorator->GetNextRequest());
  1415. EXPECT_EQ(kMinTimeBetweenRequests,
  1416. decorator->GetNextRequest()->min_time_between_requests());
  1417. }));
  1418. // Must remove the observer before destroying the request to avoid a DCHECK
  1419. // from ObserverList.
  1420. request->RemoveObserver(&observer);
  1421. request.reset();
  1422. PerformanceManager::CallOnGraph(
  1423. FROM_HERE, base::BindOnce([](Graph* graph) {
  1424. auto* decorator = V8DetailedMemoryDecorator::GetFromGraph(graph);
  1425. ASSERT_TRUE(decorator);
  1426. EXPECT_FALSE(decorator->GetNextRequest());
  1427. }));
  1428. // Execute the above tasks and exit.
  1429. base::RunLoop run_loop2;
  1430. PerformanceManager::CallOnGraph(FROM_HERE, run_loop2.QuitClosure());
  1431. run_loop2.Run();
  1432. }
  1433. // TODO(crbug.com/1203439) Sometimes timing out on Windows.
  1434. #if BUILDFLAG(IS_WIN)
  1435. #define MAYBE_SingleProcessRequest DISABLED_SingleProcessRequest
  1436. #else
  1437. #define MAYBE_SingleProcessRequest SingleProcessRequest
  1438. #endif
  1439. TEST_F(V8DetailedMemoryRequestAnySeqTest, MAYBE_SingleProcessRequest) {
  1440. CreateCrossProcessChildFrame();
  1441. V8DetailedMemoryProcessData expected_process_data1;
  1442. expected_process_data1.set_shared_v8_bytes_used(1U);
  1443. V8DetailedMemoryProcessData expected_process_data2;
  1444. expected_process_data2.set_shared_v8_bytes_used(2U);
  1445. MockV8DetailedMemoryReporter mock_reporter1;
  1446. MockV8DetailedMemoryReporter mock_reporter2;
  1447. {
  1448. // Delay the main process response a little bit so that it will be
  1449. // scheduled *after* the event that adds |process1_query|, allowing it to
  1450. // satisfy both of these queries. Otherwise a second round of measurement
  1451. // will be started for this process.
  1452. {
  1453. InSequence seq;
  1454. ExpectBindReceiver(&mock_reporter1, main_process_id());
  1455. auto data = NewPerProcessV8MemoryUsage(1);
  1456. data->isolates[0]->shared_bytes_used = 1U;
  1457. ExpectQueryAndDelayReply(&mock_reporter1, base::Milliseconds(1),
  1458. std::move(data));
  1459. }
  1460. auto data = NewPerProcessV8MemoryUsage(1);
  1461. data->isolates[0]->shared_bytes_used = 2U;
  1462. ExpectBindAndRespondToQuery(&mock_reporter2, std::move(data),
  1463. child_process_id());
  1464. }
  1465. // Create one request that measures both processes, and one request that
  1466. // measures only one.
  1467. V8DetailedMemoryRequestAnySeq all_process_request(kMinTimeBetweenRequests);
  1468. MockV8DetailedMemoryObserverAnySeq all_process_observer;
  1469. all_process_request.AddObserver(&all_process_observer);
  1470. V8DetailedMemoryRequestAnySeq single_process_request(
  1471. kMinTimeBetweenRequests, MeasurementMode::kBounded, main_process_id());
  1472. MockV8DetailedMemoryObserverAnySeq single_process_observer;
  1473. single_process_request.AddObserver(&single_process_observer);
  1474. // When a measurement is available the all process observer should be invoked
  1475. // for both processes, and the single process observer only for process 1.
  1476. base::RunLoop run_loop;
  1477. auto barrier = base::BarrierClosure(3, run_loop.QuitClosure());
  1478. EXPECT_CALL(all_process_observer,
  1479. OnV8MemoryMeasurementAvailable(main_process_id(),
  1480. expected_process_data1, _))
  1481. .WillOnce(base::test::RunClosure(barrier));
  1482. EXPECT_CALL(all_process_observer,
  1483. OnV8MemoryMeasurementAvailable(child_process_id(),
  1484. expected_process_data2, _))
  1485. .WillOnce(base::test::RunClosure(barrier));
  1486. EXPECT_CALL(single_process_observer,
  1487. OnV8MemoryMeasurementAvailable(main_process_id(),
  1488. expected_process_data1, _))
  1489. .WillOnce(base::test::RunClosure(barrier));
  1490. // If all measurements don't arrive in a reasonable period, cancel the
  1491. // run loop. This ensures the test will fail with errors from the unfulfilled
  1492. // EXPECT_CALL statements, as expected, instead of timing out.
  1493. base::OneShotTimer timeout;
  1494. timeout.Start(FROM_HERE, TestTimeouts::action_timeout(),
  1495. run_loop.QuitClosure());
  1496. // Now execute all the above tasks.
  1497. run_loop.Run();
  1498. Mock::VerifyAndClearExpectations(&mock_reporter1);
  1499. Mock::VerifyAndClearExpectations(&mock_reporter2);
  1500. Mock::VerifyAndClearExpectations(&all_process_observer);
  1501. Mock::VerifyAndClearExpectations(&single_process_observer);
  1502. // Must remove the observer before destroying the request to avoid a DCHECK
  1503. // from ObserverList.
  1504. all_process_request.RemoveObserver(&all_process_observer);
  1505. single_process_request.RemoveObserver(&single_process_observer);
  1506. }
  1507. TEST_F(V8DetailedMemoryRequestAnySeqTest, OneShot) {
  1508. CreateCrossProcessChildFrame();
  1509. // Set the all process request to only send once within the test.
  1510. V8DetailedMemoryRequestAnySeq all_process_request(kMinTimeBetweenRequests *
  1511. 100);
  1512. // Create a mock reporter for each process and expect a query and reply on
  1513. // each.
  1514. MockV8DetailedMemoryReporter mock_reporter1;
  1515. {
  1516. auto data = NewPerProcessV8MemoryUsage(1);
  1517. data->isolates[0]->shared_bytes_used = 1ULL;
  1518. ExpectBindAndRespondToQuery(&mock_reporter1, std::move(data),
  1519. main_process_id());
  1520. }
  1521. MockV8DetailedMemoryReporter mock_reporter2;
  1522. {
  1523. auto data = NewPerProcessV8MemoryUsage(1);
  1524. data->isolates[0]->shared_bytes_used = 2ULL;
  1525. ExpectBindAndRespondToQuery(&mock_reporter2, std::move(data),
  1526. child_process_id());
  1527. }
  1528. task_environment()->RunUntilIdle();
  1529. Mock::VerifyAndClearExpectations(&mock_reporter1);
  1530. Mock::VerifyAndClearExpectations(&mock_reporter2);
  1531. // Create a one-shot request for process1 and expect the callback to be
  1532. // called only for that process.
  1533. {
  1534. auto data = NewPerProcessV8MemoryUsage(1);
  1535. data->isolates[0]->shared_bytes_used = 3ULL;
  1536. ExpectQueryAndReply(&mock_reporter1, std::move(data));
  1537. }
  1538. uint64_t shared_v8_bytes_used = 0;
  1539. V8DetailedMemoryRequestOneShotAnySeq process1_request;
  1540. process1_request.StartMeasurement(
  1541. main_process_id(),
  1542. base::BindLambdaForTesting(
  1543. [&](RenderProcessHostId process_id,
  1544. const V8DetailedMemoryProcessData& process_data,
  1545. const V8DetailedMemoryRequestOneShotAnySeq::FrameDataMap&
  1546. frame_data) {
  1547. EXPECT_EQ(process_id, main_process_id());
  1548. shared_v8_bytes_used = process_data.shared_v8_bytes_used();
  1549. }));
  1550. task_environment()->RunUntilIdle();
  1551. Mock::VerifyAndClearExpectations(&mock_reporter1);
  1552. Mock::VerifyAndClearExpectations(&mock_reporter2);
  1553. EXPECT_EQ(shared_v8_bytes_used, 3ULL);
  1554. }
  1555. TEST_F(V8DetailedMemoryRequestAnySeqTest, OneShotLifetime) {
  1556. // Measure a child frame so that it can be detached.
  1557. CreateCrossProcessChildFrame();
  1558. // Create a one-shot request, but delete it before the result arrives.
  1559. MockV8DetailedMemoryReporter mock_reporter;
  1560. {
  1561. InSequence seq;
  1562. ExpectBindReceiver(&mock_reporter, child_process_id());
  1563. auto data = NewPerProcessV8MemoryUsage(1);
  1564. data->isolates[0]->shared_bytes_used = 1ULL;
  1565. ExpectQueryAndDelayReply(&mock_reporter, base::Seconds(10),
  1566. std::move(data));
  1567. }
  1568. auto doomed_request = std::make_unique<V8DetailedMemoryRequestOneShotAnySeq>(
  1569. child_process_id(),
  1570. base::BindOnce(
  1571. [](RenderProcessHostId process_id,
  1572. const V8DetailedMemoryProcessData& process_data,
  1573. const V8DetailedMemoryRequestOneShotAnySeq::FrameDataMap&
  1574. frame_data) {
  1575. FAIL() << "Callback called after request deleted.";
  1576. }));
  1577. // Verify that requests are sent but reply is not received.
  1578. task_environment()->FastForwardBy(base::Seconds(5));
  1579. Mock::VerifyAndClearExpectations(&mock_reporter);
  1580. doomed_request.reset();
  1581. task_environment()->FastForwardBy(base::Seconds(5));
  1582. // Create a request that is deleted from within its own callback and make
  1583. // sure nothing explodes.
  1584. {
  1585. auto data = NewPerProcessV8MemoryUsage(1);
  1586. data->isolates[0]->shared_bytes_used = 2ULL;
  1587. ExpectQueryAndReply(&mock_reporter, std::move(data));
  1588. }
  1589. uint64_t shared_v8_bytes_used = 0;
  1590. doomed_request = std::make_unique<V8DetailedMemoryRequestOneShotAnySeq>(
  1591. child_process_id(),
  1592. base::BindLambdaForTesting(
  1593. [&](RenderProcessHostId process_id,
  1594. const V8DetailedMemoryProcessData& process_data,
  1595. const V8DetailedMemoryRequestOneShotAnySeq::FrameDataMap&
  1596. frame_data) {
  1597. doomed_request.reset();
  1598. shared_v8_bytes_used = process_data.shared_v8_bytes_used();
  1599. }));
  1600. task_environment()->RunUntilIdle();
  1601. Mock::VerifyAndClearExpectations(&mock_reporter);
  1602. EXPECT_EQ(shared_v8_bytes_used, 2ULL);
  1603. // Ensure that resource-owning callbacks are freed when there is no response
  1604. // because the process dies.
  1605. {
  1606. auto data = NewPerProcessV8MemoryUsage(1);
  1607. data->isolates[0]->shared_bytes_used = 3ULL;
  1608. ExpectQueryAndDelayReply(&mock_reporter, base::Seconds(10),
  1609. std::move(data));
  1610. }
  1611. auto lifetime_test = std::make_unique<LifetimeTestObject>();
  1612. auto weak_lifetime_test = lifetime_test->AsWeakPtr();
  1613. V8DetailedMemoryRequestOneShotAnySeq unfinished_request(
  1614. child_process_id(),
  1615. base::BindOnce(
  1616. [](std::unique_ptr<LifetimeTestObject>, RenderProcessHostId,
  1617. const V8DetailedMemoryProcessData&,
  1618. const V8DetailedMemoryRequestOneShotAnySeq::FrameDataMap&) {
  1619. FAIL() << "Callback called after process deleted.";
  1620. },
  1621. // Pass ownership to the callback. The object should be deleted if the
  1622. // callback is not called.
  1623. std::move(lifetime_test)));
  1624. // Verify that requests are sent but reply is not yet received.
  1625. task_environment()->FastForwardBy(base::Seconds(5));
  1626. Mock::VerifyAndClearExpectations(&mock_reporter);
  1627. ASSERT_TRUE(weak_lifetime_test);
  1628. content::RenderFrameHostTester::For(child_frame())->Detach();
  1629. task_environment()->FastForwardBy(base::Seconds(5));
  1630. EXPECT_FALSE(weak_lifetime_test);
  1631. }
  1632. TEST_F(V8DetailedMemoryRequestAnySeqTest, OneShotLifetimeAtExit) {
  1633. // Ensure that resource-owning callbacks are freed when there is no response
  1634. // because the browser is exiting (simulated by destroying the decorator).
  1635. MockV8DetailedMemoryReporter mock_reporter;
  1636. {
  1637. InSequence seq;
  1638. ExpectBindReceiver(&mock_reporter, main_process_id());
  1639. auto data = NewPerProcessV8MemoryUsage(1);
  1640. data->isolates[0]->shared_bytes_used = 1ULL;
  1641. ExpectQueryAndDelayReply(&mock_reporter, base::Seconds(10),
  1642. std::move(data));
  1643. }
  1644. auto lifetime_test = std::make_unique<LifetimeTestObject>();
  1645. auto weak_lifetime_test = lifetime_test->AsWeakPtr();
  1646. V8DetailedMemoryRequestOneShotAnySeq unfinished_request(
  1647. main_process_id(),
  1648. base::BindOnce(
  1649. [](std::unique_ptr<LifetimeTestObject>, RenderProcessHostId,
  1650. const V8DetailedMemoryProcessData&,
  1651. const V8DetailedMemoryRequestOneShotAnySeq::FrameDataMap&) {
  1652. FAIL() << "Callback called after measurements cancelled.";
  1653. },
  1654. // Pass ownership to the callback. The object should be deleted if the
  1655. // callback is not called.
  1656. std::move(lifetime_test)));
  1657. // Verify that requests are sent but reply is not yet received.
  1658. task_environment()->FastForwardBy(base::Seconds(5));
  1659. Mock::VerifyAndClearExpectations(&mock_reporter);
  1660. ASSERT_TRUE(weak_lifetime_test);
  1661. base::RunLoop run_loop;
  1662. PerformanceManager::CallOnGraph(
  1663. FROM_HERE,
  1664. base::BindOnce(&internal::DestroyV8DetailedMemoryDecoratorForTesting));
  1665. // Block in the run loop until the destroy task runs on the PM sequence.
  1666. PerformanceManager::CallOnGraph(FROM_HERE, run_loop.QuitClosure());
  1667. run_loop.Run();
  1668. task_environment()->FastForwardBy(base::Seconds(5));
  1669. EXPECT_FALSE(weak_lifetime_test);
  1670. }
  1671. TEST_F(V8DetailedMemoryDecoratorTest, DedicatedWorkers) {
  1672. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  1673. MockV8DetailedMemoryReporter reporter;
  1674. auto process = CreateNode<ProcessNodeImpl>(
  1675. content::PROCESS_TYPE_RENDERER,
  1676. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  1677. // Create a couple of frames with specified IDs.
  1678. auto page = CreateNode<PageNodeImpl>();
  1679. blink::LocalFrameToken frame_id = blink::LocalFrameToken();
  1680. auto frame = CreateNode<FrameNodeImpl>(process.get(), page.get(), nullptr,
  1681. /*render_frame_id=*/1, frame_id);
  1682. blink::DedicatedWorkerToken worker_id = blink::DedicatedWorkerToken();
  1683. auto worker = CreateNode<WorkerNodeImpl>(
  1684. WorkerNode::WorkerType::kDedicated, process.get(),
  1685. page->browser_context_id(), worker_id);
  1686. worker->AddClientFrame(frame.get());
  1687. {
  1688. auto data = NewPerProcessV8MemoryUsage(2);
  1689. AddIsolateMemoryUsage(frame_id, 1001u, data->isolates[0].get());
  1690. AddIsolateMemoryUsage(worker_id, 1002u, data->isolates[1].get());
  1691. ExpectBindAndRespondToQuery(&reporter, std::move(data));
  1692. }
  1693. task_env().RunUntilIdle();
  1694. Mock::VerifyAndClearExpectations(&reporter);
  1695. ASSERT_TRUE(V8DetailedMemoryExecutionContextData::ForFrameNode(frame.get()));
  1696. EXPECT_EQ(1001u,
  1697. V8DetailedMemoryExecutionContextData::ForFrameNode(frame.get())
  1698. ->v8_bytes_used());
  1699. ASSERT_TRUE(
  1700. V8DetailedMemoryExecutionContextData::ForWorkerNode(worker.get()));
  1701. EXPECT_EQ(1002u,
  1702. V8DetailedMemoryExecutionContextData::ForWorkerNode(worker.get())
  1703. ->v8_bytes_used());
  1704. worker->RemoveClientFrame(frame.get());
  1705. }
  1706. TEST_F(V8DetailedMemoryDecoratorTest, CanvasMemory) {
  1707. V8DetailedMemoryRequest memory_request(kMinTimeBetweenRequests, graph());
  1708. MockV8DetailedMemoryReporter reporter;
  1709. auto process = CreateNode<ProcessNodeImpl>(
  1710. content::PROCESS_TYPE_RENDERER,
  1711. RenderProcessHostProxy::CreateForTesting(kTestProcessID));
  1712. // Create a couple of frames with specified IDs.
  1713. auto page = CreateNode<PageNodeImpl>();
  1714. blink::LocalFrameToken frame_id = blink::LocalFrameToken();
  1715. auto frame = CreateNode<FrameNodeImpl>(process.get(), page.get(), nullptr,
  1716. /*render_frame_id=*/1, frame_id);
  1717. {
  1718. auto data = NewPerProcessV8MemoryUsage(1);
  1719. AddIsolateMemoryUsage(frame_id, 1001u, data->isolates[0].get());
  1720. AddIsolateCanvasMemoryUsage(frame_id, 2002u, data->isolates[0].get());
  1721. ExpectBindAndRespondToQuery(&reporter, std::move(data));
  1722. }
  1723. task_env().RunUntilIdle();
  1724. Mock::VerifyAndClearExpectations(&reporter);
  1725. ASSERT_TRUE(V8DetailedMemoryExecutionContextData::ForFrameNode(frame.get()));
  1726. EXPECT_EQ(1001u,
  1727. V8DetailedMemoryExecutionContextData::ForFrameNode(frame.get())
  1728. ->v8_bytes_used());
  1729. EXPECT_EQ(2002u,
  1730. V8DetailedMemoryExecutionContextData::ForFrameNode(frame.get())
  1731. ->canvas_bytes_used()
  1732. .value());
  1733. }
  1734. } // namespace v8_memory
  1735. } // namespace performance_manager