1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299
|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/performance_manager/freezing/freezing_policy.h"
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/numerics/safe_conversions.h"
#include "base/rand_util.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.h"
#include "components/performance_manager/freezing/freezer.h"
#include "components/performance_manager/graph/graph_impl.h"
#include "components/performance_manager/graph/page_node_impl.h"
#include "components/performance_manager/graph/process_node_impl.h"
#include "components/performance_manager/public/decorators/page_live_state_decorator.h"
#include "components/performance_manager/public/features.h"
#include "components/performance_manager/public/freezing/cannot_freeze_reason.h"
#include "components/performance_manager/public/freezing/freezing.h"
#include "components/performance_manager/public/graph/page_node.h"
#include "components/performance_manager/public/resource_attribution/origin_in_browsing_instance_context.h"
#include "components/performance_manager/public/resource_attribution/queries.h"
#include "components/performance_manager/public/resource_attribution/query_results.h"
#include "components/performance_manager/public/resource_attribution/resource_contexts.h"
#include "components/performance_manager/test_support/graph_test_harness.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/browser/browsing_instance_id.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace performance_manager {
namespace {
using FreezingType = FreezingPolicy::FreezingType;
using freezing::CannotFreezeReason;
using freezing::CannotFreezeReasonSet;
using ::testing::ElementsAre;
using ::testing::IsEmpty;
using ::testing::Mock;
class MockFreezingPolicy : public FreezingPolicy {
public:
explicit MockFreezingPolicy(
std::unique_ptr<freezing::Discarder> discarder,
std::unique_ptr<freezing::OptOutChecker> opt_out_checker = nullptr)
: FreezingPolicy(std::move(discarder), std::move(opt_out_checker)) {}
~MockFreezingPolicy() override = default;
base::TimeTicks GenerateRandomPeriodicUnfreezePhase() const override {
// Â Make the periodic unfreeze phase non-random for tests.
return base::TimeTicks();
}
MOCK_METHOD(void,
RecordFreezingEligibilityUKMForPage,
(ukm::SourceId source_id,
double highest_cpu_current_interval,
double highest_cpu_without_battery_saver_cannot_freeze,
CannotFreezeReasonSet cannot_freeze_reasons),
(override));
};
// Mock version of a Freezer.
class LenientMockFreezer : public Freezer {
public:
LenientMockFreezer() = default;
~LenientMockFreezer() override = default;
LenientMockFreezer(const LenientMockFreezer& other) = delete;
LenientMockFreezer& operator=(const LenientMockFreezer&) = delete;
MOCK_METHOD(void,
MaybeFreezePageNode,
(const PageNode* page_node),
(override));
MOCK_METHOD(void, UnfreezePageNode, (const PageNode* page_node), (override));
};
using MockFreezer = ::testing::StrictMock<LenientMockFreezer>;
class LenientMockDiscarder : public freezing::Discarder {
public:
LenientMockDiscarder() = default;
~LenientMockDiscarder() override = default;
LenientMockDiscarder(const LenientMockDiscarder& other) = delete;
LenientMockDiscarder& operator=(const LenientMockDiscarder&) = delete;
MOCK_METHOD(void,
DiscardPages,
(Graph * graph, std::vector<const PageNode*> page_nodes),
(override));
};
using MockDiscarder = ::testing::StrictMock<LenientMockDiscarder>;
} // namespace
class FreezingPolicyTest_BaseWithNoPage : public GraphTestHarness {
public:
FreezingPolicyTest_BaseWithNoPage()
: GraphTestHarness(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}
~FreezingPolicyTest_BaseWithNoPage() override = default;
FreezingPolicyTest_BaseWithNoPage(
const FreezingPolicyTest_BaseWithNoPage& other) = delete;
FreezingPolicyTest_BaseWithNoPage& operator=(
const FreezingPolicyTest_BaseWithNoPage&) = delete;
void OnGraphCreated(GraphImpl* graph) override {
// The freezing logic relies on the existence of the page live state data.
graph->PassToGraph(std::make_unique<PageLiveStateDecorator>());
auto discarder = std::make_unique<MockDiscarder>();
discarder_ = discarder.get();
// Create the policy and pass it to the graph.
auto policy = std::make_unique<MockFreezingPolicy>(
std::move(discarder), CreateTestOptOutChecker());
policy_ = policy.get();
auto freezer = std::make_unique<MockFreezer>();
freezer_ = freezer.get();
policy_->SetFreezerForTesting(std::move(freezer));
graph->PassToGraph(std::move(policy));
process_node_ = CreateNode<ProcessNodeImpl>();
}
// Override to create an OptOutChecker for the test.
virtual std::unique_ptr<freezing::OptOutChecker> CreateTestOptOutChecker() {
return nullptr;
}
// Reports private memory footprint for `context` to the freezing policy, with
// "now" as the measurement time.
void ReportMemoryUsage(resource_attribution::ResourceContext context,
int private_footprint_kb) {
resource_attribution::QueryResultMap memory_result_map;
memory_result_map[context] = resource_attribution::QueryResults{
.memory_summary_result = resource_attribution::MemorySummaryResult{
.metadata = resource_attribution::ResultMetadata(
/* measurement_time=*/base::TimeTicks::Now(),
resource_attribution::MeasurementAlgorithm::kSum),
.resident_set_size_kb = 0u,
.private_footprint_kb =
base::checked_cast<uint64_t>(private_footprint_kb)}};
resource_attribution::QueryResultObserver* observer = policy();
observer->OnResourceUsageUpdated(std::move(memory_result_map));
}
// Adds CPU usage for `context` to `cpu_result_map`, with "now" as the
// measurement time. `cumulative_background_cpu` is used as cumulative
// background CPU and `cumulative_cpu` is used as cumulative CPU
// (`cumulative_background_cpu` is used as cumulative CPU if `cumulative_cpu`
// is nullopt).
void AddCPUMeasurement(
resource_attribution::QueryResultMap& cpu_result_map,
resource_attribution::ResourceContext context,
base::TimeDelta cumulative_background_cpu,
std::optional<base::TimeDelta> cumulative_cpu = std::nullopt) {
cpu_result_map[context] = resource_attribution::QueryResults{
.cpu_time_result = resource_attribution::CPUTimeResult{
.metadata = resource_attribution::ResultMetadata(
/* measurement_time=*/base::TimeTicks::Now(),
resource_attribution::MeasurementAlgorithm::kSum),
.start_time = base::TimeTicks(),
.cumulative_cpu = cumulative_cpu.has_value()
? cumulative_cpu.value()
: cumulative_background_cpu,
.cumulative_background_cpu = cumulative_background_cpu}};
}
// Reports CPU usage for `context` to the the freezing policy, with "now" as
// the measurement time. `cumulative_background_cpu` is used as cumulative
// background CPU and `cumulative_cpu` is used as cumulative CPU
// (`cumulative_background_cpu` is used as cumulative CPU if `cumulative_cpu`
// is nullopt).
void ReportCumulativeCPUUsage(
resource_attribution::ResourceContext context,
base::TimeDelta cumulative_background_cpu,
std::optional<base::TimeDelta> cumulative_cpu = std::nullopt) {
resource_attribution::QueryResultMap cpu_result_map;
AddCPUMeasurement(cpu_result_map, context, cumulative_background_cpu,
cumulative_cpu);
resource_attribution::QueryResultObserver* observer = policy();
observer->OnResourceUsageUpdated(std::move(cpu_result_map));
}
std::pair<TestNodeWrapper<PageNodeImpl>, TestNodeWrapper<FrameNodeImpl>>
CreatePageAndFrameWithBrowsingInstanceId(
content::BrowsingInstanceId browsing_instance_id,
const std::string& browsing_context_id = "") {
auto page =
CreateNode<PageNodeImpl>(/*web_contents=*/nullptr, browsing_context_id);
page->SetType(PageType::kTab);
auto frame = CreateFrameNodeAutoId(process_node(), page.get(),
/* parent_frame_node=*/nullptr,
browsing_instance_id);
return std::make_pair(std::move(page), std::move(frame));
}
void VerifyFreezerExpectations() {
Mock::VerifyAndClearExpectations(freezer());
}
void VerifyDiscarderExpectations() {
Mock::VerifyAndClearExpectations(discarder());
}
// Expect that the `CannotFreezeReason`s applicable to `freezing_type` for
// `page_node` match `matcher`.
template <typename MatcherType>
void ExpectCannotFreezeReasons(
const PageNode* page_node,
FreezingType freezing_type,
MatcherType matcher,
const base::Location& location = base::Location::Current()) {
EXPECT_THAT(
base::Intersection(
policy()->GetCanFreezeDetails(page_node).cannot_freeze_reasons,
FreezingPolicy::CannotFreezeReasonsForType(freezing_type)),
matcher)
<< location.ToString();
}
// Expect that the `CannotFreezeReason`s applicable to `freezing_type` for
// pages connected to `page_node` match `matcher`.
template <typename MatcherType>
void ExpectConnectedCannotFreezeReasons(
const PageNode* page_node,
FreezingType freezing_type,
MatcherType matcher,
const base::Location& location = base::Location::Current()) {
EXPECT_THAT(base::Intersection(
policy()
->GetCanFreezeDetails(page_node)
.cannot_freeze_reasons_connected_pages,
FreezingPolicy::CannotFreezeReasonsForType(freezing_type)),
matcher)
<< location.ToString();
}
ProcessNodeImpl* process_node() { return process_node_.get(); }
MockFreezingPolicy* policy() { return policy_; }
MockFreezer* freezer() { return freezer_; }
MockDiscarder* discarder() { return discarder_; }
const content::BrowsingInstanceId kBrowsingInstanceA =
content::BrowsingInstanceId(1);
const content::BrowsingInstanceId kBrowsingInstanceB =
content::BrowsingInstanceId(2);
const content::BrowsingInstanceId kBrowsingInstanceC =
content::BrowsingInstanceId(3);
const resource_attribution::OriginInBrowsingInstanceContext kContext{
url::Origin(), kBrowsingInstanceA};
private:
TestNodeWrapper<ProcessNodeImpl> process_node_;
raw_ptr<MockFreezer> freezer_;
raw_ptr<MockDiscarder> discarder_;
raw_ptr<MockFreezingPolicy> policy_;
};
class FreezingPolicyTest : public FreezingPolicyTest_BaseWithNoPage {
public:
FreezingPolicyTest() = default;
~FreezingPolicyTest() override = default;
void OnGraphCreated(GraphImpl* graph) override {
FreezingPolicyTest_BaseWithNoPage::OnGraphCreated(graph);
std::tie(page_node_, frame_node_) =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
}
PageNodeImpl* page_node() { return page_node_.get(); }
private:
TestNodeWrapper<PageNodeImpl> page_node_;
TestNodeWrapper<FrameNodeImpl> frame_node_;
};
// A page with no `CannotFreezeReason` that is alone in its browsing instance is
// frozen when it has a freezing vote.
TEST_F(FreezingPolicyTest, Basic) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting, IsEmpty());
}
// Multiple connected pages in the same browsing instance with no
// `CannotFreezeReason` are frozen when they all have a freezing vote.
TEST_F(FreezingPolicyTest, ManyPagesSameBrowsingInstance) {
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
// Adding a freezing vote to each of the 2 pages in the browsing instance
// freezes all pages.
policy()->AddFreezeVote(page_node());
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page2.get()));
policy()->AddFreezeVote(page2.get());
VerifyFreezerExpectations();
// Adding a 3rd page (with no freezing vote yet) to the browsing instance
// unfreezes all pages.
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
EXPECT_CALL(*freezer(), UnfreezePageNode(page2.get()));
auto [page3, frame3] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page2.get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page3.get()));
policy()->AddFreezeVote(page3.get());
VerifyFreezerExpectations();
// Multiple votes on the same page don't change anything.
policy()->AddFreezeVote(page3.get());
policy()->AddFreezeVote(page3.get());
// Removing a freezing vote from one page unfreezes all pages.
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
EXPECT_CALL(*freezer(), UnfreezePageNode(page2.get()));
EXPECT_CALL(*freezer(), UnfreezePageNode(page3.get()));
policy()->RemoveFreezeVote(page_node());
VerifyFreezerExpectations();
policy()->RemoveFreezeVote(page2.get());
policy()->RemoveFreezeVote(page3.get());
policy()->RemoveFreezeVote(page3.get());
policy()->RemoveFreezeVote(page3.get());
}
// Similar to ManyPagesSameBrowsingInstance, except that the 1st and 3rd pages
// don't have frames in the same browsing instance (they're indirectly connected
// via the 2nd page).
TEST_F(FreezingPolicyTest, ConnectedPages) {
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
auto frame2b =
CreateFrameNodeAutoId(process_node(), page2.get(),
/* parent_frame_node=*/nullptr, kBrowsingInstanceB);
// Adding a freezing vote to the 2 connected pages freezes them.
policy()->AddFreezeVote(page_node());
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page2.get()));
policy()->AddFreezeVote(page2.get());
VerifyFreezerExpectations();
// Adding a 3rd page (with no freezing vote yet) to the set of connected pages
// unfreezes all pages.
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
EXPECT_CALL(*freezer(), UnfreezePageNode(page2.get()));
auto [page3, frame3] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceB);
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page2.get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page3.get()));
policy()->AddFreezeVote(page3.get());
VerifyFreezerExpectations();
// Multiple votes on the same page don't change anything.
policy()->AddFreezeVote(page3.get());
policy()->AddFreezeVote(page3.get());
// Removing a freezing vote from one page unfreezes all pages.
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
EXPECT_CALL(*freezer(), UnfreezePageNode(page2.get()));
EXPECT_CALL(*freezer(), UnfreezePageNode(page3.get()));
policy()->RemoveFreezeVote(page_node());
VerifyFreezerExpectations();
policy()->RemoveFreezeVote(page2.get());
policy()->RemoveFreezeVote(page3.get());
policy()->RemoveFreezeVote(page3.get());
policy()->RemoveFreezeVote(page3.get());
}
// A browsing instance with many pages that each have a freeze vote is unfrozen
// when one of the pages gets a `CannotFreezeReason`.
TEST_F(FreezingPolicyTest,
AddCannotFreezeReasonToBrowsingInstanceWithManyPages) {
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
policy()->AddFreezeVote(page_node());
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page2.get()));
policy()->AddFreezeVote(page2.get());
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting, IsEmpty());
ExpectConnectedCannotFreezeReasons(page_node(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(page2.get(), FreezingType::kVoting,
IsEmpty());
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
EXPECT_CALL(*freezer(), UnfreezePageNode(page2.get()));
page_node()->SetIsHoldingWebLockForTesting(true);
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting, IsEmpty());
ExpectConnectedCannotFreezeReasons(page_node(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(
page2.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
}
// Similar to AddCannotFreezeReasonToBrowsingInstanceWithManyPages, except that
// the 1st and 3rd pages don't have frames in the same browsing instance
// (they're indirectly connected via the 2nd page).
TEST_F(FreezingPolicyTest, AddCannotFreezeReasonToConnectedPages) {
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
auto frame2b =
CreateFrameNodeAutoId(process_node(), page2.get(),
/* parent_frame_node=*/nullptr, kBrowsingInstanceB);
auto [page3, frame3] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceB);
policy()->AddFreezeVote(page_node());
policy()->AddFreezeVote(page2.get());
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page2.get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page3.get()));
policy()->AddFreezeVote(page3.get());
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page3.get(), FreezingType::kVoting, IsEmpty());
ExpectConnectedCannotFreezeReasons(page_node(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(page2.get(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(page3.get(), FreezingType::kVoting,
IsEmpty());
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
EXPECT_CALL(*freezer(), UnfreezePageNode(page2.get()));
EXPECT_CALL(*freezer(), UnfreezePageNode(page3.get()));
page_node()->SetIsHoldingWebLockForTesting(true);
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page3.get(), FreezingType::kVoting, IsEmpty());
ExpectConnectedCannotFreezeReasons(page_node(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(
page2.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectConnectedCannotFreezeReasons(
page3.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
}
// A browsing instance with one page that has a `CannotFreezeReason` is not
// frozen when all its pages get a freeze vote.
TEST_F(FreezingPolicyTest,
AddFreezeVotesToBrowsingInstanceWithManyPagesAndCannotFreezeReason) {
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
page_node()->SetIsHoldingWebLockForTesting(true);
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting, IsEmpty());
ExpectConnectedCannotFreezeReasons(page_node(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(
page2.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
policy()->AddFreezeVote(page2.get());
VerifyFreezerExpectations();
}
// Similar to
// AddFreezeVotesToBrowsingInstanceWithManyPagesAndCannotFreezeReason, except
// that the 1st and 3rd pages don't have frames in the same browsing instance
// (they're indirectly connected via the 2nd page).
TEST_F(FreezingPolicyTest,
AddFreezeVotesToConnectedPagesWithCannotFreezeReason) {
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
auto frame2b =
CreateFrameNodeAutoId(process_node(), page2.get(),
/* parent_frame_node=*/nullptr, kBrowsingInstanceB);
auto [page3, frame3] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceB);
page_node()->SetIsHoldingWebLockForTesting(true);
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page3.get(), FreezingType::kVoting, IsEmpty());
ExpectConnectedCannotFreezeReasons(page_node(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(
page2.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectConnectedCannotFreezeReasons(
page3.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
policy()->AddFreezeVote(page2.get());
policy()->AddFreezeVote(page3.get());
VerifyFreezerExpectations();
}
// Verify that frozen state is correctly updated when a set of connected pages
// is broken in two by the deletion of a frame.
TEST_F(FreezingPolicyTest, BreakConnectedSet) {
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
auto frame2b =
CreateFrameNodeAutoId(process_node(), page2.get(),
/* parent_frame_node=*/nullptr, kBrowsingInstanceB);
auto [page3, frame3] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceB);
page_node()->SetIsHoldingWebLockForTesting(true);
policy()->AddFreezeVote(page_node());
policy()->AddFreezeVote(page2.get());
policy()->AddFreezeVote(page3.get());
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page3.get(), FreezingType::kVoting, IsEmpty());
ExpectConnectedCannotFreezeReasons(page_node(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(
page2.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectConnectedCannotFreezeReasons(
page3.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
// Deleting `frame2` puts `page_node()` in a different connected set than
// `page2` and `page3`. `page_node()` cannot be frozen because it has a
// `CannotFreezeReason`. `page2` and `page3` can be frozen because they have
// freeze votes and no `CannotFreezeReason`.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page2.get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page3.get()));
frame2.reset();
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page3.get(), FreezingType::kVoting, IsEmpty());
ExpectConnectedCannotFreezeReasons(page_node(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(page2.get(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(page3.get(), FreezingType::kVoting,
IsEmpty());
}
// Similar to BreakConnectedSet, but the connected set left by the page from
// which a page is deleted can be frozen.
TEST_F(FreezingPolicyTest, BreakConnectedSet_LeftSetIsFrozen) {
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
auto frame2b =
CreateFrameNodeAutoId(process_node(), page2.get(),
/* parent_frame_node=*/nullptr, kBrowsingInstanceB);
auto [page3, frame3] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceB);
page2->SetIsHoldingWebLockForTesting(true);
policy()->AddFreezeVote(page_node());
policy()->AddFreezeVote(page2.get());
policy()->AddFreezeVote(page3.get());
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectCannotFreezeReasons(page3.get(), FreezingType::kVoting, IsEmpty());
ExpectConnectedCannotFreezeReasons(
page_node(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectConnectedCannotFreezeReasons(page2.get(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(
page3.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
// Deleting `frame2` puts `page_node()` in a different connected set than
// `page2` and `page3`. `page_node()` cannot be frozen because it has a
// `CannotFreezeReason`. `page2` and `page3` can be frozen because they have
// freeze votes and no `CannotFreezeReason`.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
frame2.reset();
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
ExpectCannotFreezeReasons(page3.get(), FreezingType::kVoting, IsEmpty());
ExpectConnectedCannotFreezeReasons(page_node(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(page2.get(), FreezingType::kVoting,
IsEmpty());
ExpectConnectedCannotFreezeReasons(
page3.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kHoldingWebLock));
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenVisible) {
page_node()->SetIsVisible(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
}
TEST_F(FreezingPolicyTest, BecomesVisibleWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
page_node()->SetIsVisible(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenRecentlyVisible) {
page_node()->SetIsVisible(true);
page_node()->SetIsVisible(false);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after visible protection time.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
task_env().FastForwardBy(features::kFreezingVisibleProtectionTime.Get());
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, BecomesRecentlyVisibleWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
page_node()->SetIsVisible(true);
// Don't expect freezing, because the page is still "recently visible".
page_node()->SetIsVisible(false);
// Expect freezing after visible protection time.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
task_env().FastForwardBy(features::kFreezingVisibleProtectionTime.Get());
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenAudible) {
page_node()->SetIsAudible(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
}
TEST_F(FreezingPolicyTest, BecomesAudibleWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
page_node()->SetIsAudible(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenRecentlyAudible) {
page_node()->SetIsAudible(true);
page_node()->SetIsAudible(false);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after audio protection time.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
task_env().FastForwardBy(features::kFreezingAudioProtectionTime.Get());
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, BecomesRecentlyAudibleWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
page_node()->SetIsAudible(true);
// Don't expect freezing, because the page is still "recently audible".
page_node()->SetIsAudible(false);
// Expect freezing after audio protection time.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
task_env().FastForwardBy(features::kFreezingAudioProtectionTime.Get());
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWithOriginTrialOptOut) {
page_node()->SetHasFreezingOriginTrialOptOutForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after removing the origin trial opt-out.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
page_node()->SetHasFreezingOriginTrialOptOutForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, OriginTrialOptOutWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
page_node()->SetHasFreezingOriginTrialOptOutForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenHoldingWebLock) {
page_node()->SetIsHoldingWebLockForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after releasing the lock.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
page_node()->SetIsHoldingWebLockForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, AcquiresWebLockWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
page_node()->SetIsHoldingWebLockForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenHoldingBlockingIndexedDBLock) {
page_node()->SetIsHoldingBlockingIndexedDBLockForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after the transaction completes.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
page_node()->SetIsHoldingBlockingIndexedDBLockForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, AcquiresBlockingIndexedDBLockWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
page_node()->SetIsHoldingBlockingIndexedDBLockForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenConnectedToUSBDevice) {
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToUSBDeviceForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after disconnecting from USB device.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToUSBDeviceForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, ConnectedToUSBDeviceWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToUSBDeviceForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenConnectedToBluetoothDevice) {
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToBluetoothDeviceForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after disconnecting from Bluetooth device.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToBluetoothDeviceForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, ConnectedToBluetoothDeviceWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToBluetoothDeviceForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenConnectedToHidDevice) {
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToHidDeviceForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after disconnecting from HID device.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToHidDeviceForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, ConnectedToHidDeviceWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToHidDeviceForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenConnectedToSerialPort) {
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToSerialPortForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after disconnecting from HID device.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToSerialPortForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, ConnectedToSerialPortWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsConnectedToSerialPortForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenCapturingVideo) {
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingVideoForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after stopping capture.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingVideoForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, StartsCapturingVideoWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingAudioForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenCapturingAudio) {
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingAudioForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after stopping capture.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingAudioForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, StartsCapturingAudioWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingAudioForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenMirrored) {
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsBeingMirroredForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after mirroring stops.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsBeingMirroredForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, StartsBeingMirroredWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsBeingMirroredForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenCapturingWindow) {
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingWindowForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after stopping capture.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingWindowForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, StartsCapturingWindowWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingWindowForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenCapturingDisplay) {
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingDisplayForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after stopping capture.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingDisplayForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, StartsCapturingDisplayWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
PageLiveStateDecorator::Data::GetOrCreateForPageNode(page_node())
->SetIsCapturingDisplayForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenUsingWebRTC) {
page_node()->SetUsesWebRTCForTesting(true);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after stopping capture.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
page_node()->SetUsesWebRTCForTesting(false);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, StartsUsingWebRTCWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
page_node()->SetUsesWebRTCForTesting(true);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWithNotificationPermission) {
page_node()->OnNotificationPermissionStatusChange(
blink::mojom::PermissionStatus::GRANTED);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing if the permission is revoked.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
page_node()->OnNotificationPermissionStatusChange(
blink::mojom::PermissionStatus::DENIED);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, NotificationPermissionWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
page_node()->OnNotificationPermissionStatusChange(
blink::mojom::PermissionStatus::GRANTED);
VerifyFreezerExpectations();
// Changing to ASK removes the opt-out.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
page_node()->OnNotificationPermissionStatusChange(
blink::mojom::PermissionStatus::ASK);
VerifyFreezerExpectations();
// Changing to DENIED does nothing, since there is already no opt-out.
page_node()->OnNotificationPermissionStatusChange(
blink::mojom::PermissionStatus::DENIED);
// Changing to GRANTED adds the opt-out.
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
page_node()->OnNotificationPermissionStatusChange(
blink::mojom::PermissionStatus::GRANTED);
VerifyFreezerExpectations();
// Changing to DENIED removes the opt-out.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
page_node()->OnNotificationPermissionStatusChange(
blink::mojom::PermissionStatus::DENIED);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, FreezeVoteWhenLoading) {
page_node()->SetLoadingState(PageNode::LoadingState::kLoadedBusy);
// Don't expect freezing.
policy()->AddFreezeVote(page_node());
// Expect freezing after finishing loading.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
page_node()->SetLoadingState(PageNode::LoadingState::kLoadedIdle);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, StartsLoadingWhenFrozen) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
page_node()->SetLoadingState(PageNode::LoadingState::kLoadedBusy);
VerifyFreezerExpectations();
}
TEST_F(FreezingPolicyTest, DiscardGrowingPrivateMemory_Basic) {
base::test::ScopedFeatureList feature_list{
features::kDiscardFrozenBrowsingInstancesWithGrowingPMF};
const int growth_threshold_kb =
features::kFreezingMemoryGrowthThresholdToDiscardKb.Get();
// Pretend that the page is frozen.
page_node()->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// First memory measurement after freezing.
constexpr int kInitialPMFKb = 10;
ReportMemoryUsage(kContext, kInitialPMFKb);
// Another memory measurement, *not* crossing the growth threshold.
constexpr int kSecondPMFKb = 20;
ASSERT_LT(kSecondPMFKb - kInitialPMFKb, growth_threshold_kb);
ReportMemoryUsage(kContext, kSecondPMFKb);
// Another memory measurement, crossing the growth threshold. The page should
// be discarded.
EXPECT_CALL(*discarder(),
DiscardPages(testing::_, testing::ElementsAre(page_node())));
ReportMemoryUsage(kContext, kInitialPMFKb + growth_threshold_kb + 1);
VerifyDiscarderExpectations();
}
// Regression test for crbug.com/407522185: When a (non-frozen) page is added to
// a browsing instance in which all pages are frozen, the post-freezing memory
// estimates are cleared.
TEST_F(FreezingPolicyTest, DiscardGrowingPrivateMemory_PageAddedAfterFreezing) {
base::test::ScopedFeatureList feature_list{
features::kDiscardFrozenBrowsingInstancesWithGrowingPMF};
const int growth_threshold_kb =
features::kFreezingMemoryGrowthThresholdToDiscardKb.Get();
// Pretend that the page is frozen.
page_node()->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// First memory measurement after freezing.
constexpr int kInitialPMFKb = 10;
ReportMemoryUsage(kContext, kInitialPMFKb);
// Add a (non-frozen) page to the browsing instance.
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
// Memory measurement crossing the growth threshold. This should not result in
// discarding (or crash) since post-freezing memory estimates were cleared.
const int kSecondPMFKb = kInitialPMFKb + growth_threshold_kb + 1;
ReportMemoryUsage(kContext, kSecondPMFKb);
// Pretend that the new page is frozen.
page2->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// Memory measurement crossing the growth threshold. Should not result in
// discarding since it's the first measurement since the new page was added.
const int kThirdPMFKb = kSecondPMFKb + growth_threshold_kb + 1;
ReportMemoryUsage(kContext, kThirdPMFKb);
// Memory measurement crossing the growth threshold. This should result in
// discarding.
const int kFourthPMFKb = kThirdPMFKb + growth_threshold_kb + 1;
EXPECT_CALL(*discarder(),
DiscardPages(testing::_, testing::UnorderedElementsAre(
page_node(), page2.get())));
ReportMemoryUsage(kContext, kFourthPMFKb);
VerifyDiscarderExpectations();
}
TEST_F(FreezingPolicyTest, DiscardGrowingPrivateMemory_FeatureDisabled) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndDisableFeature(
features::kDiscardFrozenBrowsingInstancesWithGrowingPMF);
const int growth_threshold_kb =
features::kFreezingMemoryGrowthThresholdToDiscardKb.Get();
// Pretend that the page is frozen.
page_node()->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// First memory measurement after freezing.
constexpr int kInitialPMFKb = 10;
ReportMemoryUsage(kContext, kInitialPMFKb);
// Another memory measurement, crossing the growth threshold. The page should
// not be discarded since the feature is disabled.
ReportMemoryUsage(kContext, kInitialPMFKb + growth_threshold_kb + 1);
VerifyDiscarderExpectations();
}
TEST_F(FreezingPolicyTest,
DiscardGrowingPrivateMemory_MultipleFrozenPagesInBrowsingInstance) {
base::test::ScopedFeatureList feature_list{
features::kDiscardFrozenBrowsingInstancesWithGrowingPMF};
const int growth_threshold_kb =
features::kFreezingMemoryGrowthThresholdToDiscardKb.Get();
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
// Pretend that the pages are frozen.
page_node()->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
page2->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// First memory measurement after freezing.
constexpr int kInitialPMFKb = 10;
ReportMemoryUsage(kContext, kInitialPMFKb);
// Another memory measurement, crossing the growth threshold. The 2 pages
// should be discarded.
EXPECT_CALL(*discarder(),
DiscardPages(testing::_, testing::UnorderedElementsAre(
page_node(), page2.get())));
ReportMemoryUsage(kContext, kInitialPMFKb + growth_threshold_kb + 1);
VerifyDiscarderExpectations();
}
TEST_F(FreezingPolicyTest,
DiscardGrowingPrivateMemory_FrozenAndUnfrozenPagesInBrowsingInstance) {
base::test::ScopedFeatureList feature_list{
features::kDiscardFrozenBrowsingInstancesWithGrowingPMF};
const int growth_threshold_kb =
features::kFreezingMemoryGrowthThresholdToDiscardKb.Get();
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
// Pretend that the first page is frozen.
page_node()->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// First memory measurement after freezing the page (2nd page still unfrozen).
constexpr int kInitialPMFKb = 10;
ReportMemoryUsage(kContext, kInitialPMFKb);
// Pretend that the 2nd page is frozen.
page2->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// Another memory measurement, crossing the growth threshold since the first
// page was frozen (but not since *all* pages were frozen). No discarding
// expected.
ReportMemoryUsage(kContext, kInitialPMFKb + growth_threshold_kb + 1);
// Another memory measurement, crossing the growth threshold since all pages
// were frozen. The 2 pages should be discarded.
EXPECT_CALL(*discarder(),
DiscardPages(testing::_, testing::UnorderedElementsAre(
page_node(), page2.get())));
ReportMemoryUsage(kContext, kInitialPMFKb + 2 * (growth_threshold_kb + 1));
VerifyDiscarderExpectations();
}
TEST_F(FreezingPolicyTest, DiscardGrowingPrivateMemory_Unfreeze) {
base::test::ScopedFeatureList feature_list{
features::kDiscardFrozenBrowsingInstancesWithGrowingPMF};
const int growth_threshold_kb =
features::kFreezingMemoryGrowthThresholdToDiscardKb.Get();
// Pretend that the page is frozen.
page_node()->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// First memory measurement after freezing.
constexpr int kInitialPMFKb = 10;
ReportMemoryUsage(kContext, kInitialPMFKb);
// Pretend that the page is unfrozen and re-frozen.
page_node()->SetLifecycleStateForTesting(PageNode::LifecycleState::kRunning);
page_node()->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// Another memory measurement, crossing the growth threshold since the
// measurement taken before unfreezing. The page should not be discarded,
// because this is the first measurement since re-freezing.
ReportMemoryUsage(kContext, kInitialPMFKb + growth_threshold_kb + 1);
// Another memory measurement, crossing the growth threshold since the
// measurement taken after re-freezing. The page should be discarded.
EXPECT_CALL(*discarder(),
DiscardPages(testing::_, testing::ElementsAre(page_node())));
ReportMemoryUsage(kContext, kInitialPMFKb + 2 * (growth_threshold_kb + 1));
VerifyDiscarderExpectations();
}
TEST_F(
FreezingPolicyTest,
DiscardGrowingPrivateMemory_MeasurementForNewOrigin_BelowGrowthThreshold) {
base::test::ScopedFeatureList feature_list{
features::kDiscardFrozenBrowsingInstancesWithGrowingPMF};
const int growth_threshold_kb =
features::kFreezingMemoryGrowthThresholdToDiscardKb.Get();
const resource_attribution::OriginInBrowsingInstanceContext kOtherContext{
url::Origin(), kBrowsingInstanceA};
// Pretend that the page is frozen.
page_node()->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// First memory measurement after freezing.
constexpr int kInitialPMFKb = 10;
ReportMemoryUsage(kContext, kInitialPMFKb);
// A memory measurement below the growth threshold for an origin not seen in
// the first measurement. Nothing should happen.
ReportMemoryUsage(kOtherContext, growth_threshold_kb - 1);
VerifyDiscarderExpectations();
// A second memory measurement above the growth threshold for an origin not
// seen in the first measurement. The browsing instance should be discarded.
EXPECT_CALL(*discarder(),
DiscardPages(testing::_, testing::ElementsAre(page_node())));
ReportMemoryUsage(kOtherContext, growth_threshold_kb + 1);
VerifyDiscarderExpectations();
}
TEST_F(
FreezingPolicyTest,
DiscardGrowingPrivateMemory_MeasurementForNewOrigin_AboveGrowthThreshold) {
base::test::ScopedFeatureList feature_list{
features::kDiscardFrozenBrowsingInstancesWithGrowingPMF};
const int growth_threshold_kb =
features::kFreezingMemoryGrowthThresholdToDiscardKb.Get();
const resource_attribution::OriginInBrowsingInstanceContext kOtherContext{
url::Origin(), kBrowsingInstanceA};
// Pretend that the page is frozen.
page_node()->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// First memory measurement after freezing.
constexpr int kInitialPMFKb = 10;
ReportMemoryUsage(kContext, kInitialPMFKb);
// A memory measurement above the growth threshold for an origin not seen in
// the first measurement. The browsing instance should be discarded.
EXPECT_CALL(*discarder(),
DiscardPages(testing::_, testing::ElementsAre(page_node())));
ReportMemoryUsage(kOtherContext, growth_threshold_kb + 1);
VerifyDiscarderExpectations();
}
TEST_F(FreezingPolicyTest,
DiscardGrowingPrivateMemory_MeasurementForNewBrowsingInstance) {
base::test::ScopedFeatureList feature_list{
features::kDiscardFrozenBrowsingInstancesWithGrowingPMF};
const int growth_threshold_kb =
features::kFreezingMemoryGrowthThresholdToDiscardKb.Get();
const resource_attribution::OriginInBrowsingInstanceContext
kUnknownBrowsingInstanceContext{url::Origin(), kBrowsingInstanceB};
// Pretend that the page is frozen.
page_node()->SetLifecycleStateForTesting(PageNode::LifecycleState::kFrozen);
// Simulate memory usage growth above the threshold for a browsing instance
// not known to the `FreezingPolicy`. This should be gracefully ignored.
constexpr int kInitialPMFKb = 10;
ReportMemoryUsage(kUnknownBrowsingInstanceContext, kInitialPMFKb);
ReportMemoryUsage(kUnknownBrowsingInstanceContext,
kInitialPMFKb + growth_threshold_kb + 1);
}
namespace {
class FreezingPolicyBatterySaverTest : public FreezingPolicyTest {
public:
FreezingPolicyBatterySaverTest() = default;
private:
base::test::ScopedFeatureList scoped_feature_list_{
features::kFreezingOnBatterySaver};
};
} // namespace
TEST_F(FreezingPolicyBatterySaverTest, Basic) {
policy()->ToggleFreezingOnBatterySaverMode(true);
ReportCumulativeCPUUsage(kContext, base::Seconds(60));
AdvanceClock(base::Seconds(60));
// The page should be frozen when a browsing instance connected to it consumes
// >=25% CPU in background.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
ReportCumulativeCPUUsage(kContext, base::Seconds(75));
}
TEST_F(FreezingPolicyBatterySaverTest, RecordFreezingEligibilityUKM) {
base::test::ScopedFeatureList feature_list(
features::kRecordFreezingEligibilityUKM);
base::MetricsSubSampler::ScopedAlwaysSampleForTesting always_sample;
// page_node(), page2 and page3 are connected. page4 is disjoint.
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
auto frame2b =
CreateFrameNodeAutoId(process_node(), page2.get(),
/* parent_frame_node=*/nullptr, kBrowsingInstanceB);
auto [page3, frame3] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceB);
auto [page4, frame4] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceC);
page_node()->SetUkmSourceId(ukm::AssignNewSourceId());
page2->SetUkmSourceId(ukm::AssignNewSourceId());
page3->SetUkmSourceId(ukm::AssignNewSourceId());
page4->SetUkmSourceId(ukm::AssignNewSourceId());
// kContext affects page_node(), page2 and page3. kContext2 and kContext3
// affect page4.
const resource_attribution::OriginInBrowsingInstanceContext kContext2{
url::Origin(), kBrowsingInstanceC};
const resource_attribution::OriginInBrowsingInstanceContext kContext3{
url::Origin(), kBrowsingInstanceC};
// A `CannotFreezeReason` applicable at the beginning of the CPU measurement
// interval affects the UKM event.
page_node()->SetIsHoldingWebLockForTesting(true);
// Simulate initial CPU measurement.
{
resource_attribution::QueryResultMap cpu_result_map;
AddCPUMeasurement(cpu_result_map, kContext, base::Seconds(0));
AddCPUMeasurement(cpu_result_map, kContext2, base::Seconds(0));
AddCPUMeasurement(cpu_result_map, kContext3, base::Seconds(0));
resource_attribution::QueryResultObserver* observer = policy();
observer->OnResourceUsageUpdated(std::move(cpu_result_map));
}
AdvanceClock(base::Seconds(60));
page_node()->SetIsHoldingWebLockForTesting(false);
// A `CannotFreezeReason` applicable transiently during the CPU measurement
// interval affects the UKM event.
page_node()->SetIsHoldingBlockingIndexedDBLockForTesting(true);
page_node()->SetIsHoldingBlockingIndexedDBLockForTesting(false);
// Simulate 2nd CPU measurement. Expect UKM events to be reported.
{
CannotFreezeReasonSet expected_cannot_freeze_reasons{
CannotFreezeReason::kHoldingWebLock,
CannotFreezeReason::kHoldingBlockingIndexedDBLock};
EXPECT_CALL(*policy(),
RecordFreezingEligibilityUKMForPage(
page_node()->GetUkmSourceID(),
/*highest_cpu_current_interval=*/0.5,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
0, expected_cannot_freeze_reasons));
EXPECT_CALL(*policy(),
RecordFreezingEligibilityUKMForPage(
page2->GetUkmSourceID(),
/*highest_cpu_current_interval=*/0.5,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
0, expected_cannot_freeze_reasons));
EXPECT_CALL(*policy(),
RecordFreezingEligibilityUKMForPage(
page3->GetUkmSourceID(),
/*highest_cpu_current_interval=*/0.5,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
0, expected_cannot_freeze_reasons));
EXPECT_CALL(*policy(),
RecordFreezingEligibilityUKMForPage(
page4->GetUkmSourceID(),
/*highest_cpu_current_interval=*/1.0,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
1.0, CannotFreezeReasonSet{}));
resource_attribution::QueryResultMap cpu_result_map;
AddCPUMeasurement(cpu_result_map, kContext, base::Seconds(30)); // 50%
AddCPUMeasurement(cpu_result_map, kContext2, base::Seconds(45)); // 75%
AddCPUMeasurement(cpu_result_map, kContext3, base::Seconds(60)); // 100%
resource_attribution::QueryResultObserver* observer = policy();
observer->OnResourceUsageUpdated(std::move(cpu_result_map));
}
AdvanceClock(base::Seconds(60));
// Simulate 3rd CPU measurement (no applicable `CannotFreezeReason` this
// time). Expect UKM events to be reported.
{
EXPECT_CALL(*policy(),
RecordFreezingEligibilityUKMForPage(
page_node()->GetUkmSourceID(),
/*highest_cpu_current_interval=*/0.25,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
0.25, CannotFreezeReasonSet{}));
EXPECT_CALL(*policy(),
RecordFreezingEligibilityUKMForPage(
page2->GetUkmSourceID(),
/*highest_cpu_current_interval=*/0.25,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
0.25, CannotFreezeReasonSet{}));
EXPECT_CALL(*policy(),
RecordFreezingEligibilityUKMForPage(
page3->GetUkmSourceID(),
/*highest_cpu_current_interval=*/0.25,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
0.25, CannotFreezeReasonSet{}));
EXPECT_CALL(*policy(),
RecordFreezingEligibilityUKMForPage(
page4->GetUkmSourceID(),
/*highest_cpu_current_interval=*/0.75,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
1.0, CannotFreezeReasonSet{}));
resource_attribution::QueryResultMap cpu_result_map;
AddCPUMeasurement(cpu_result_map, kContext, base::Seconds(45)); // 25%
AddCPUMeasurement(cpu_result_map, kContext2, base::Seconds(90)); // 75%
AddCPUMeasurement(cpu_result_map, kContext3, base::Seconds(66)); // 10%
resource_attribution::QueryResultObserver* observer = policy();
observer->OnResourceUsageUpdated(std::move(cpu_result_map));
}
}
TEST_F(FreezingPolicyBatterySaverTest,
RecordFreezingEligibilityUKMForPageStatic) {
// No "opt-out" field is set.
// CPU usage is bucketed.
{
ukm::TestAutoSetUkmRecorder recorder;
FreezingPolicy::RecordFreezingEligibilityUKMForPageStatic(
ukm::SourceId(), /*highest_cpu_current_interval=*/0.1,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
0.2, CannotFreezeReasonSet{});
auto entries = recorder.GetEntriesByName(
ukm::builders::PerformanceManager_FreezingEligibility::kEntryName);
EXPECT_EQ(entries.size(), 1U);
auto& entry = entries.front();
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Audible", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "BeingMirrored", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Capturing", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "ConnectedToDevice", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(
entry, "HighestCPUAnyIntervalWithoutOptOut", 16);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "HighestCPUCurrentInterval",
8);
ukm::TestUkmRecorder::ExpectEntryMetric(entry,
"HoldingBlockingIndexedDBLock", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "HoldingWebLock", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Loading", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "NotificationPermission", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "OriginTrialOptOut", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "RecentlyAudible", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "RecentlyVisible", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Visible", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "WebRTC", 0);
}
// All "opt-out" fields are set.
// CPU usage is bucketed.
{
ukm::TestAutoSetUkmRecorder recorder;
FreezingPolicy::RecordFreezingEligibilityUKMForPageStatic(
ukm::SourceId(), /*highest_cpu_current_interval=*/0.16,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
0.32,
CannotFreezeReasonSet{
CannotFreezeReason::kAudible, CannotFreezeReason::kBeingMirrored,
CannotFreezeReason::kCapturingAudio,
CannotFreezeReason::kConnectedToBluetoothDevice,
CannotFreezeReason::kHoldingBlockingIndexedDBLock,
CannotFreezeReason::kHoldingWebLock, CannotFreezeReason::kLoading,
CannotFreezeReason::kNotificationPermission,
CannotFreezeReason::kFreezingOriginTrialOptOut,
CannotFreezeReason::kRecentlyAudible,
CannotFreezeReason::kRecentlyVisible, CannotFreezeReason::kVisible,
CannotFreezeReason::kWebRTC});
auto entries = recorder.GetEntriesByName(
ukm::builders::PerformanceManager_FreezingEligibility::kEntryName);
EXPECT_EQ(entries.size(), 1U);
auto& entry = entries.front();
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Audible", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "BeingMirrored", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Capturing", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "ConnectedToDevice", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(
entry, "HighestCPUAnyIntervalWithoutOptOut", 32);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "HighestCPUCurrentInterval",
16);
ukm::TestUkmRecorder::ExpectEntryMetric(entry,
"HoldingBlockingIndexedDBLock", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "HoldingWebLock", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Loading", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "NotificationPermission", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "OriginTrialOptOut", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "RecentlyAudible", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "RecentlyVisible", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Visible", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "WebRTC", 1);
}
// Opt-out fields from Audible -> Loading are set.
// CPU usage is zero.
{
ukm::TestAutoSetUkmRecorder recorder;
FreezingPolicy::RecordFreezingEligibilityUKMForPageStatic(
ukm::SourceId(), /*highest_cpu_current_interval=*/0.0,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
0.0,
CannotFreezeReasonSet{
CannotFreezeReason::kAudible, CannotFreezeReason::kBeingMirrored,
CannotFreezeReason::kCapturingVideo,
CannotFreezeReason::kConnectedToUsbDevice,
CannotFreezeReason::kHoldingBlockingIndexedDBLock,
CannotFreezeReason::kHoldingWebLock, CannotFreezeReason::kLoading});
auto entries = recorder.GetEntriesByName(
ukm::builders::PerformanceManager_FreezingEligibility::kEntryName);
EXPECT_EQ(entries.size(), 1U);
auto& entry = entries.front();
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Audible", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "BeingMirrored", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Capturing", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "ConnectedToDevice", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(
entry, "HighestCPUAnyIntervalWithoutOptOut", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "HighestCPUCurrentInterval",
0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry,
"HoldingBlockingIndexedDBLock", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "HoldingWebLock", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Loading", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "NotificationPermission", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "OriginTrialOptOut", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "RecentlyAudible", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "RecentlyVisible", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Visible", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "WebRTC", 0);
}
// Opt-out fields from Notification -> WebRTC are set.
// CPU usage is very low (bucketing has no effect at this level).
{
ukm::TestAutoSetUkmRecorder recorder;
FreezingPolicy::RecordFreezingEligibilityUKMForPageStatic(
ukm::SourceId(), /*highest_cpu_current_interval=*/0.01,
/*highest_cpu_without_battery_saver_cannot_freeze=*/
0.02,
CannotFreezeReasonSet{CannotFreezeReason::kNotificationPermission,
CannotFreezeReason::kFreezingOriginTrialOptOut,
CannotFreezeReason::kRecentlyAudible,
CannotFreezeReason::kRecentlyVisible,
CannotFreezeReason::kVisible,
CannotFreezeReason::kWebRTC});
auto entries = recorder.GetEntriesByName(
ukm::builders::PerformanceManager_FreezingEligibility::kEntryName);
EXPECT_EQ(entries.size(), 1U);
auto& entry = entries.front();
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Audible", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "BeingMirrored", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Capturing", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "ConnectedToDevice", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(
entry, "HighestCPUAnyIntervalWithoutOptOut", 2);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "HighestCPUCurrentInterval",
1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry,
"HoldingBlockingIndexedDBLock", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "HoldingWebLock", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Loading", 0);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "NotificationPermission", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "OriginTrialOptOut", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "RecentlyAudible", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "RecentlyVisible", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "Visible", 1);
ukm::TestUkmRecorder::ExpectEntryMetric(entry, "WebRTC", 1);
}
}
TEST_F(FreezingPolicyBatterySaverTest, ConnectedPages) {
auto [page2, frame2] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
auto frame2b =
CreateFrameNodeAutoId(process_node(), page2.get(),
/* parent_frame_node=*/nullptr, kBrowsingInstanceB);
auto [page3, frame3] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceB);
policy()->ToggleFreezingOnBatterySaverMode(true);
ReportCumulativeCPUUsage(kContext, base::Seconds(60));
AdvanceClock(base::Seconds(60));
// The page should be frozen when a browsing instance connected to it consumes
// >=25% CPU in background.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page2.get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page3.get()));
ReportCumulativeCPUUsage(kContext, base::Seconds(75));
}
TEST_F(FreezingPolicyBatterySaverTest, CannotFreeze) {
policy()->ToggleFreezingOnBatterySaverMode(true);
ReportCumulativeCPUUsage(kContext, base::Seconds(60));
AdvanceClock(base::Seconds(60));
// Add a `CannotFreezeReason`.
page_node()->SetIsHoldingWebLockForTesting(true);
// The page should not be frozen when a browsing instance connected to it
// consumes >=25% CPU in background, because it has a `CannotFreezeReason`.
ReportCumulativeCPUUsage(kContext, base::Seconds(75));
AdvanceClock(base::Seconds(60));
// Remove the `CannotFreezeReason`. This should not cause the page to be
// frozen, since there was a `CannotFreezeReason` when high CPU usage was
// measured.
page_node()->SetIsHoldingWebLockForTesting(false);
// The page should not be frozen when a browsing instance connected to it
// consumes >=25% CPU in background, because it transiently had a
// `CannotFreezeReason` during the measurement interval.
ReportCumulativeCPUUsage(kContext, base::Seconds(90));
AdvanceClock(base::Seconds(60));
// The page should be frozen when a browsing instance connected to it consumes
// >=25% CPU in background and there was no `CannotFreezeReason` at any point
// during the measurement interval.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
ReportCumulativeCPUUsage(kContext, base::Seconds(105));
}
TEST_F(FreezingPolicyBatterySaverTest, CannotFreezeTransient) {
policy()->ToggleFreezingOnBatterySaverMode(true);
ReportCumulativeCPUUsage(kContext, base::Seconds(60));
AdvanceClock(base::Seconds(60));
// Transiently add a `CannotFreezeReason`.
page_node()->SetIsHoldingWebLockForTesting(true);
page_node()->SetIsHoldingWebLockForTesting(false);
// The page should not be frozen when a browsing instance connected to it
// consumes >=25% CPU in background, because it transiently had a
// `CannotFreezeReason` during the measurement interval.
ReportCumulativeCPUUsage(kContext, base::Seconds(75));
}
TEST_F(FreezingPolicyBatterySaverTest, BatterySaverInactive) {
// Battery Saver is not active in this test.
ReportCumulativeCPUUsage(kContext, base::Seconds(60));
AdvanceClock(base::Seconds(60));
// The page should not be frozen when a browsing instance connected to it
// consumes >=25% CPU in background, because Battery Saver is not active.
ReportCumulativeCPUUsage(kContext, base::Seconds(75));
}
TEST_F(FreezingPolicyBatterySaverTest, ForegroundCPU) {
policy()->ToggleFreezingOnBatterySaverMode(true);
ReportCumulativeCPUUsage(kContext,
/*cumulative_background_cpu=*/base::Seconds(60),
/*cumulative_cpu=*/base::Seconds(60));
AdvanceClock(base::Seconds(60));
// The page should not be frozen when a browsing instance connected to it
// consumes >=25% CPU in foreground, but little CPU in background.
ReportCumulativeCPUUsage(kContext,
/*cumulative_background_cpu=*/base::Seconds(62),
/*cumulative_cpu=*/base::Seconds(90));
}
TEST_F(FreezingPolicyBatterySaverTest, DeactivateBatterySaver) {
policy()->ToggleFreezingOnBatterySaverMode(true);
ReportCumulativeCPUUsage(kContext, base::Seconds(60));
AdvanceClock(base::Seconds(60));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
ReportCumulativeCPUUsage(kContext, base::Seconds(75));
VerifyFreezerExpectations();
// The page should be unfrozen when Battery Saver becomes inactive.
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
policy()->ToggleFreezingOnBatterySaverMode(false);
}
TEST_F(FreezingPolicyBatterySaverTest, ActivateBatterySaverAfterHighCPU) {
// Battery Saver is not active at the beginning of this test.
// Report high background CPU usage.
ReportCumulativeCPUUsage(kContext, base::Seconds(60));
AdvanceClock(base::Seconds(60));
ReportCumulativeCPUUsage(kContext, base::Seconds(75));
// The page should be frozen when Battery Saver becomes active.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->ToggleFreezingOnBatterySaverMode(true);
}
namespace {
constexpr char kOptOutUrl1[] = "http://a.com/";
constexpr char kOptOutUrl2[] = "http://b.com/";
constexpr char kBrowsingContext1[] = "browsing-context-1";
constexpr char kBrowsingContext2[] = "browsing-context-2";
// A test implementation of OptOutChecker that opts out a single URL.
class TestOptOutChecker final : public freezing::OptOutChecker {
public:
TestOptOutChecker() = default;
~TestOptOutChecker() final = default;
TestOptOutChecker(const TestOptOutChecker&) = delete;
TestOptOutChecker& operator=(const TestOptOutChecker&) = delete;
// Sets the opted out url to `url`, and notifies `browser_contexts_to_notify`
// of the change.
void SetOptedOutUrl(
const std::string& url,
const std::vector<std::string>& browser_contexts_to_notify);
// OptOutChecker:
void SetOptOutPolicyChangedCallback(
OnPolicyChangedForBrowserContextCallback callback) final;
bool IsPageOptedOutOfFreezing(std::string_view browser_context_id,
const GURL& main_frame_url) final;
private:
OnPolicyChangedForBrowserContextCallback on_policy_changed_callback_;
GURL opted_out_url_;
};
void TestOptOutChecker::SetOptedOutUrl(
const std::string& url,
const std::vector<std::string>& browser_contexts_to_notify = {}) {
ASSERT_TRUE(on_policy_changed_callback_);
opted_out_url_ = GURL(url);
for (const std::string& browser_context_id : browser_contexts_to_notify) {
on_policy_changed_callback_.Run(browser_context_id);
}
}
void TestOptOutChecker::SetOptOutPolicyChangedCallback(
OnPolicyChangedForBrowserContextCallback callback) {
on_policy_changed_callback_ = std::move(callback);
}
bool TestOptOutChecker::IsPageOptedOutOfFreezing(
std::string_view browser_context_id,
const GURL& main_frame_url) {
return opted_out_url_.is_valid() && main_frame_url == opted_out_url_;
}
class FreezingPolicyOptOutTest : public FreezingPolicyTest {
public:
std::unique_ptr<freezing::OptOutChecker> CreateTestOptOutChecker() override {
auto opt_out_checker = std::make_unique<TestOptOutChecker>();
opt_out_checker_ = opt_out_checker.get();
return opt_out_checker;
}
void TearDown() override {
// Prevent dangling raw_ptr.
opt_out_checker_ = nullptr;
FreezingPolicyTest::TearDown();
}
void NavigateToUrl(PageNodeImpl* page_node, std::string_view url) {
page_node->OnMainFrameNavigationCommitted(
/*same_document=*/false, base::TimeTicks::Now(), next_navigation_id_++,
GURL(url), /*contents_mime_type=*/"",
/*notification_permission_status=*/std::nullopt);
}
protected:
raw_ptr<TestOptOutChecker> opt_out_checker_ = nullptr;
// page_node() navigates once when the GraphTestHarness is set up.
int next_navigation_id_ = 2;
};
} // namespace
TEST_F(FreezingPolicyOptOutTest, MainFrameUrlChanges) {
ASSERT_TRUE(opt_out_checker_.get());
opt_out_checker_->SetOptedOutUrl(kOptOutUrl1);
// Can freeze before an URL is set.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
policy()->AddFreezeVote(page_node());
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting, IsEmpty());
// Stays frozen when navigating to an URL that's not opted out.
NavigateToUrl(page_node(), kOptOutUrl2);
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting, IsEmpty());
// Unfreezes when navigating to an URL that's opted out.
EXPECT_CALL(*freezer(), UnfreezePageNode(page_node()));
NavigateToUrl(page_node(), kOptOutUrl1);
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kOptedOut));
// Navigating to the same URL does nothing.
NavigateToUrl(page_node(), kOptOutUrl1);
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kOptedOut));
// Freezes when navigating away from the opted out URL.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page_node()));
NavigateToUrl(page_node(), kOptOutUrl2);
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page_node(), FreezingType::kVoting, IsEmpty());
}
TEST_F(FreezingPolicyOptOutTest, OptOutPolicyChanges) {
ASSERT_TRUE(opt_out_checker_.get());
opt_out_checker_->SetOptedOutUrl(kOptOutUrl1);
// Give each page a unique browsing instance so that there are no connected
// pages. kBrowsingInstanceA is already used by page_node().
auto [page1, frame1] = CreatePageAndFrameWithBrowsingInstanceId(
content::BrowsingInstanceId(10), kBrowsingContext1);
auto [page2, frame2] = CreatePageAndFrameWithBrowsingInstanceId(
content::BrowsingInstanceId(11), kBrowsingContext1);
auto [page3, frame3] = CreatePageAndFrameWithBrowsingInstanceId(
content::BrowsingInstanceId(12), kBrowsingContext2);
// Each VerifyFreezerExpectations() call is inside a SCOPED_TRACE to help
// interpret StrictMock "unexpected function call" failures, which don't
// include line numbers. Also dump the PageNode pointers for each failure to
// help interpret the arguments of unexpected functions.
SCOPED_TRACE(::testing::Message()
<< "page1: " << page1.get() << ", page2: " << page2.get()
<< ", page3: " << page3.get());
NavigateToUrl(page1.get(), kOptOutUrl1);
NavigateToUrl(page2.get(), kOptOutUrl2);
NavigateToUrl(page3.get(), kOptOutUrl2);
// Only page1's URL is opted out.
{
SCOPED_TRACE("add freeze votes");
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page1.get())).Times(0);
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page2.get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page3.get()));
policy()->AddFreezeVote(page1.get());
policy()->AddFreezeVote(page2.get());
policy()->AddFreezeVote(page3.get());
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page1.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kOptedOut));
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page3.get(), FreezingType::kVoting, IsEmpty());
}
// Change which URL is opted out. Notify kBrowsingContext1 of the change.
{
SCOPED_TRACE("change opted out URL");
EXPECT_CALL(*freezer(), UnfreezePageNode(page2.get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page1.get()));
opt_out_checker_->SetOptedOutUrl(kOptOutUrl2, {kBrowsingContext1});
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page1.get(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kOptedOut));
ExpectCannotFreezeReasons(page3.get(), FreezingType::kVoting, IsEmpty());
}
// Now notify kBrowsingContext2.
{
SCOPED_TRACE("notify other context");
EXPECT_CALL(*freezer(), UnfreezePageNode(page3.get()));
opt_out_checker_->SetOptedOutUrl(kOptOutUrl2, {kBrowsingContext2});
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page1.get(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kOptedOut));
ExpectCannotFreezeReasons(page3.get(), FreezingType::kVoting,
ElementsAre(CannotFreezeReason::kOptedOut));
}
// Remove the opt out and notify both contexts. Every page should freeze.
{
SCOPED_TRACE("remove opt outs");
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page2.get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page3.get()));
opt_out_checker_->SetOptedOutUrl("",
{kBrowsingContext1, kBrowsingContext2});
VerifyFreezerExpectations();
ExpectCannotFreezeReasons(page1.get(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page2.get(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(page3.get(), FreezingType::kVoting, IsEmpty());
}
}
namespace {
class FreezingPolicyInfiniteTabsTest
: public FreezingPolicyTest_BaseWithNoPage {
protected:
FreezingPolicyInfiniteTabsTest() = default;
void OnGraphCreated(GraphImpl* graph) override {
FreezingPolicyTest_BaseWithNoPage::OnGraphCreated(graph);
// Start the test outside of the periodic unfreeze period.
AdvanceToAlignedTime(base::Minutes(1));
AdvanceClock(features::kInfiniteTabsFreezing_UnfreezeDuration.Get());
// Create "num protected tabs" hidden pages. All pages have their own
// browsing instance, which is not equal to `kBrowsingInstance(A|B|C)`.
for (int i = 0; i < features::kInfiniteTabsFreezing_NumProtectedTabs.Get();
++i) {
auto [page, frame] =
CreatePageAndFrameWithBrowsingInstanceId(content::BrowsingInstanceId(
kBrowsingInstanceC.GetUnsafeValue() + i + 1));
ASSERT_FALSE(page->IsVisible());
pages_.push_back(std::move(page));
frames_.push_back(std::move(frame));
AdvanceClock(base::Milliseconds(1));
}
}
// Advances the clock to a time aligned on `interval`.
void AdvanceToAlignedTime(base::TimeDelta interval) {
const base::TimeTicks now = base::TimeTicks::Now();
const base::TimeTicks next_aligned_time =
now.SnappedToNextTick(base::TimeTicks(), interval);
AdvanceClock(next_aligned_time - now);
}
std::vector<TestNodeWrapper<PageNodeImpl>> pages_;
std::vector<TestNodeWrapper<FrameNodeImpl>> frames_;
private:
base::test::ScopedFeatureList feature_list_{features::kInfiniteTabsFreezing};
};
} // namespace
// Verify that under "Infinite Tabs Freezing", tabs are frozen if not in the
// list of most recently used.
TEST_F(FreezingPolicyInfiniteTabsTest, MostRecentlyUsed) {
// Create a new page, which takes the spot of the `pages_[0]` in the list
// of most recently used pages. `pages_[0]` should be frozen.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[0].get()));
auto [page5, frame5] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
AdvanceClock(base::Milliseconds(1));
VerifyFreezerExpectations();
// Create a new page, which takes the spot of `pages_[1]` in the list
// of most recently used pages. `pages_[1]` should be frozen.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[1].get()));
auto [page6, frame6] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceB);
AdvanceClock(base::Milliseconds(1));
VerifyFreezerExpectations();
// Make `pages_[1]` visible. It should take the spot of `pages_[2]` in the
// list of most recently used pages. `pages_[2]` should be frozen.
EXPECT_CALL(*freezer(), UnfreezePageNode(pages_[1].get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[2].get()));
pages_[1]->SetIsVisible(true);
VerifyFreezerExpectations();
// Make `pages_[2]` visible. It should take the spot of `pages_[3]]` in the
// list of most recently used pages. `pages_[4]` should be frozen.
EXPECT_CALL(*freezer(), UnfreezePageNode(pages_[2].get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[3].get()));
pages_[2]->SetIsVisible(true);
VerifyFreezerExpectations();
// Hide `pages_[3]` and `pages_[1]`. This should have no effect on freezing.
pages_[2]->SetIsVisible(false);
AdvanceClock(base::Milliseconds(1));
pages_[1]->SetIsVisible(false);
AdvanceClock(base::Milliseconds(1));
// Create new pages. At each page creation, the least recently used protected
// page should loose its protection and be frozen.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[4].get()));
auto [page7, frame7] = CreatePageAndFrameWithBrowsingInstanceId(
content::BrowsingInstanceId(100));
VerifyFreezerExpectations();
AdvanceClock(base::Milliseconds(1));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page5.get()));
auto [page8, frame8] = CreatePageAndFrameWithBrowsingInstanceId(
content::BrowsingInstanceId(101));
VerifyFreezerExpectations();
AdvanceClock(base::Milliseconds(1));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(page6.get()));
auto [page9, frame9] = CreatePageAndFrameWithBrowsingInstanceId(
content::BrowsingInstanceId(102));
VerifyFreezerExpectations();
AdvanceClock(base::Milliseconds(1));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[2].get()));
auto [page10, frame10] = CreatePageAndFrameWithBrowsingInstanceId(
content::BrowsingInstanceId(103));
VerifyFreezerExpectations();
AdvanceClock(base::Milliseconds(1));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[1].get()));
auto [page11, frame11] = CreatePageAndFrameWithBrowsingInstanceId(
content::BrowsingInstanceId(104));
VerifyFreezerExpectations();
AdvanceClock(base::Milliseconds(1));
}
// Verify that under "Infinite Tabs Freezing", a tab created visible (as opposed
// to hidden, as in other tests) doesn't have
// `CannotFreezeReason::kMostRecentlyUsed`, but still counts towards the limit
// of most recently used tabs protected against "Infinite Tabs Freezing".
TEST_F(FreezingPolicyInfiniteTabsTest, InitiallyVisible) {
// Create a new page, which takes the spot of the `pages_[0]` in the list
// of most recently used pages. `pages_[0]` should be frozen.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[0].get()));
auto page5 = CreateNode<PageNodeImpl>(
/*web_contents=*/nullptr, /*browsing_context_id=*/std::string(), GURL(),
PagePropertyFlags{PagePropertyFlag::kIsVisible});
EXPECT_TRUE(page5->IsVisible());
page5->SetType(PageType::kTab);
auto frame5 =
CreateFrameNodeAutoId(process_node(), page5.get(),
/* parent_frame_node=*/nullptr, kBrowsingInstanceA);
VerifyFreezerExpectations();
}
// Verify that under "Infinite Tabs Freezing", when there are more visible tabs
// than the desired number of protected tabs and they subsequently become
// hidden, freezing happens (as opposed to all tabs being transferred to the
// most recently used list, exceeding the limit).
TEST_F(FreezingPolicyInfiniteTabsTest, ManyVisibleTabs) {
// Create more visible tabs than the limit of protected tabs. All existing
// tabs are frozen.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[0].get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[1].get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[2].get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[3].get()));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[4].get()));
std::vector<TestNodeWrapper<PageNodeImpl>> more_pages;
std::vector<TestNodeWrapper<FrameNodeImpl>> more_frames;
for (int i = 0;
i < features::kInfiniteTabsFreezing_NumProtectedTabs.Get() * 2; ++i) {
more_pages.push_back(CreateNode<PageNodeImpl>(
/*web_contents=*/nullptr, /*browsing_context_id=*/std::string(), GURL(),
PagePropertyFlags{PagePropertyFlag::kIsVisible}));
more_pages.back()->SetType(PageType::kTab);
more_frames.push_back(CreateFrameNodeAutoId(
process_node(), more_pages.back().get(),
/* parent_frame_node=*/nullptr, content::BrowsingInstanceId(100 + i)));
}
VerifyFreezerExpectations();
// Hide half of tabs. They should be frozen immediately, not put in the list
// of most recently used, as there are already more visible tabs that the
// limit of protected tabs.
for (int i = 0; i < features::kInfiniteTabsFreezing_NumProtectedTabs.Get();
++i) {
EXPECT_CALL(*freezer(), MaybeFreezePageNode(more_pages[i].get()));
more_pages[i]->SetIsVisible(false);
VerifyFreezerExpectations();
}
}
// Verify that under "Infinite Tabs Freezing", a `CannotFreezeReason` that
// applies to all types of freezing is honored.
TEST_F(FreezingPolicyInfiniteTabsTest, UniversalCannotFreezeReason) {
// Create a new page, which takes the spot of the `pages_[0]` in the list
// of most recently used pages. `pages_[0]` should be frozen.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[0].get()));
auto [page5, frame5] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
AdvanceClock(base::Milliseconds(1));
VerifyFreezerExpectations();
// Add a `CannotFreezeReason` to `pages_[0]`. It should be unfrozen.
EXPECT_CALL(*freezer(), UnfreezePageNode(pages_[0].get()));
pages_[0]->SetIsHoldingWebLockForTesting(true);
VerifyFreezerExpectations();
// Add a `CannotFreezeReason` to `pages_[1]`. This has no effect since it's
// not frozen.
pages_[1]->SetIsHoldingWebLockForTesting(true);
// Create a new page, which takes the spot of `pages_[1]` in the list of most
// recently used pages. `pages_[1]` should not be frozen since it holds a Web
// Lock.
auto [page6, frame6] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceB);
AdvanceClock(base::Milliseconds(1));
// When `pages_[0]` and `pages_[1]` release their lock, they're both frozen.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[0].get()));
pages_[0]->SetIsHoldingWebLockForTesting(false);
VerifyFreezerExpectations();
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[1].get()));
pages_[1]->SetIsHoldingWebLockForTesting(false);
}
// Verify that under "Infinite Tabs Freezing", frozen tabs are periodically
// unfrozen.
TEST_F(FreezingPolicyInfiniteTabsTest, PeriodicUnfreeze) {
// Advance to the beginning of the next periodic unfreeze period.
AdvanceToAlignedTime(base::Minutes(1));
// Create a new page. This should remove
// `CannotFreezeReason::kMostRecentlyUsed` from `pages_[0]`. However, it's not
// frozen yet since it's still in its periodic unfreeze period.
auto [page, frame] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
ASSERT_FALSE(page->IsVisible());
// Advance to the end of the periodic unfreeze period. `pages_[0]` should be
// frozen.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[0].get()));
AdvanceClock(features::kInfiniteTabsFreezing_UnfreezeDuration.Get());
VerifyFreezerExpectations();
// Advance to the beginning of the next periodic unfreeze period. `pages_[0]`
// should be unfrozen.
EXPECT_CALL(*freezer(), UnfreezePageNode(pages_[0].get()));
AdvanceClock(features::kInfiniteTabsFreezing_UnfreezeInterval.Get() -
features::kInfiniteTabsFreezing_UnfreezeDuration.Get());
VerifyFreezerExpectations();
// Advance to the end of the periodic unfreeze period. `pages_[0]` should be
// frozen again.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[0].get()));
AdvanceClock(features::kInfiniteTabsFreezing_UnfreezeDuration.Get());
VerifyFreezerExpectations();
// Add a `CannotFreezeReason`. `pages_[0]` is unfrozen.
EXPECT_CALL(*freezer(), UnfreezePageNode(pages_[0].get()));
pages_[0]->SetUsesWebRTCForTesting(true);
VerifyFreezerExpectations();
// At the next periodic unfreeze period, `pages_[0]` remains unfrozen.
AdvanceClock(features::kInfiniteTabsFreezing_UnfreezeInterval.Get() -
features::kInfiniteTabsFreezing_UnfreezeDuration.Get());
// When the periodic unfreeze period ends, `pages_[0]` is not re-frozen.
AdvanceClock(features::kInfiniteTabsFreezing_UnfreezeDuration.Get());
// When the `CannotFreezeReason` is removed, `pages_[0]` is frozen.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[0].get()));
pages_[0]->SetUsesWebRTCForTesting(false);
VerifyFreezerExpectations();
}
// Verify that a page with a freeze vote can be frozen even if it's in the list
// of most recently used tabs (this list only affects Infinite Tabs Freezing).
TEST_F(FreezingPolicyInfiniteTabsTest, InteractionWithVoting) {
EXPECT_EQ(policy()->GetCanFreezeDetails(pages_[0].get()).can_freeze,
freezing::CanFreeze::kVaries);
ExpectCannotFreezeReasons(pages_[0].get(), FreezingType::kVoting, IsEmpty());
ExpectCannotFreezeReasons(pages_[0].get(), FreezingType::kInfiniteTabs,
ElementsAre(CannotFreezeReason::kMostRecentlyUsed));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[0].get()));
policy()->AddFreezeVote(pages_[0].get());
VerifyFreezerExpectations();
}
// Verify that a page which is CPU-intensive in the background while Battery
// Saver is active can be frozen even if it's in the list of most recently
// used tabs (this list only affects Infinite Tabs Freezing).
TEST_F(FreezingPolicyInfiniteTabsTest, InteractionWithBatterySaver) {
base::test::ScopedFeatureList feature_list{features::kFreezingOnBatterySaver};
policy()->ToggleFreezingOnBatterySaverMode(true);
EXPECT_EQ(policy()->GetCanFreezeDetails(pages_[0].get()).can_freeze,
freezing::CanFreeze::kVaries);
ExpectCannotFreezeReasons(pages_[0].get(), FreezingType::kBatterySaver,
IsEmpty());
ExpectCannotFreezeReasons(pages_[0].get(), FreezingType::kInfiniteTabs,
ElementsAre(CannotFreezeReason::kMostRecentlyUsed));
const resource_attribution::OriginInBrowsingInstanceContext kPage0Context{
url::Origin(), frames_[0]->GetBrowsingInstanceId()};
ReportCumulativeCPUUsage(kPage0Context, base::Seconds(60));
AdvanceClock(base::Seconds(60));
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[0].get()));
ReportCumulativeCPUUsage(kPage0Context, base::Seconds(75));
VerifyFreezerExpectations();
}
// Verify that visible pages which are not tabs don't affect Infinite Tabs
// Freezing.
TEST_F(FreezingPolicyInfiniteTabsTest, NonTab) {
// Create a new page of type `kTab` which takes the spot of the `pages_[0]` in
// the list of most recently used pages. `pages_[0]` should be frozen.
EXPECT_CALL(*freezer(), MaybeFreezePageNode(pages_[0].get()));
auto [page5, frame5] =
CreatePageAndFrameWithBrowsingInstanceId(kBrowsingInstanceA);
EXPECT_EQ(page5->GetType(), PageType::kTab);
AdvanceClock(base::Milliseconds(1));
VerifyFreezerExpectations();
// Create a new page of type `kExtension`. Unlike the previous case, this
// should have no effect on freezing.
auto non_tab_page = CreateNode<PageNodeImpl>(
/*web_contents=*/nullptr, /* browsing_context_id=*/std::string(), GURL(),
PagePropertyFlags{PagePropertyFlag::kIsVisible});
non_tab_page->SetType(PageType::kExtension);
auto non_tab_frame =
CreateFrameNodeAutoId(process_node(), non_tab_page.get(),
/* parent_frame_node=*/nullptr, kBrowsingInstanceB);
}
} // namespace performance_manager
|