Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
tools: bench.py stages result.json under a name this run owns, so an alias cannot eat the last run
xbshenge7db73efdaf1
diff --git a/tests/test_bench_out_dir.py b/tests/test_bench_out_dir.pyindex 378a44b2e..5ace01f6a 100644--- a/tests/test_bench_out_dir.py+++ b/tests/test_bench_out_dir.py@@ -19,10 +19,12 @@ be written is printed to stdout instead, with exit 1 saying the file is not it.script beside a stub tools/tv.py that records every command, so "nothing was asked of the TV" means thestub's log is not there - no TV, no network and no ADB key is needed."""+import errnoimport jsonimport osfrom pathlib import Pathimport shutil+import statimport subprocessimport sysimport tempfile@@ -133,8 +135,8 @@ class BenchOutDirTest(unittest.TestCase):self.assertLess(start, source.index(" samples = []"),"a folder that cannot be created has to be answered before measuring")# The write at the end is guarded, and the numbers are printed when it fails.- self.assertIn('part = path + ".part"', source)- self.assertIn("os.replace(part, path)", source)+ self.assertIn("os.open(stage, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666)", source)+ self.assertIn("os.replace(stage, path)", source)write = source.index(" failed = write_result(path, result)\n")self.assertIn("if failed is not None:", source[write:write + 400])self.assertIn("this run's only copy", source)@@ -150,13 +152,19 @@ class BenchOutDirTest(unittest.TestCase):class BenchResultWriteTest(unittest.TestCase):- """result.json is written through a part file, so a write that cannot finish keeps the last run's.+ """result.json is written through a staging file this run owns, so a failed write keeps the last.`open(path, "w")` truncates first: a run whose write failed - the disk that filled up during theminutes it measures, which is the failure bench.py's own message is about - left a half fileunder the name a reader opens, and took the result.json of the run before with it. Those numberscannot be measured again the same way (the tool says so itself), so the write ends inos.replace() and either lands whole or not at all.++ The staging name is random and created with O_EXCL, which is what keeps the guarantee whole: a+ fixed `result.json.part` was followed by `open()`, so a hardlink to the earlier result was+ truncated before the write and a symlink wrote through to whatever it pointed at, and a new file+ under a name that was there took the mode of a fresh one (0600 under mkstemp, 0644 under the old+ `open()`) instead of the mode the earlier result had."""def setUp(self):@@ -172,31 +180,89 @@ class BenchResultWriteTest(unittest.TestCase):def write(self, result):return self.bench.write_result(str(self.folder / "result.json"), result)+ def names(self):+ return sorted(p.name for p in self.folder.iterdir())++ def fail_after_a_few_bytes(self):+ """Make json.dump stop mid-write, the way a disk that fills up during the run does."""+ class HalfWrite:+ def dump(self, obj, handle, **kwargs): # noqa: D401 - a stand-in for json, not a test+ handle.write("{") # this run's first bytes reach the staging file+ raise OSError(errno.ENOSPC, "No space left on device")++ real = self.bench.json+ self.bench.json = HalfWrite()+ self.addCleanup(setattr, self.bench, "json", real)+def test_a_write_that_cannot_finish_leaves_the_earlier_result(self):earlier = {"keys": {"series": 3, "per_series": 36}, "response_ms": {"p50": 41}}(self.folder / "result.json").write_text(json.dumps(earlier, indent=2), encoding="utf-8")- # A part file that cannot be opened stands for a write that stops before a byte of this run's- # numbers reaches result.json: a disk that filled up mid-write answers the same way.- (self.folder / "result.json.part").mkdir()+ self.fail_after_a_few_bytes()failed = self.write({"keys": {}, "response_ms": {"p50": 99}})self.assertIsInstance(failed, OSError)self.assertEqual(earlier, json.loads((self.folder / "result.json").read_text(encoding="utf-8")),"a write that failed replaced the numbers of the run before it")+ self.assertEqual(["result.json"], self.names(),+ "a write that failed left its staging file in the results folder")- def test_a_finished_write_replaces_the_result_and_leaves_no_part_file(self):+ def test_a_finished_write_replaces_the_result_and_leaves_no_staging_file(self):(self.folder / "result.json").write_text('{"response_ms": {"p50": 41}}', encoding="utf-8")self.assertIsNone(self.write({"response_ms": {"p50": 99}}))self.assertEqual({"response_ms": {"p50": 99}},json.loads((self.folder / "result.json").read_text(encoding="utf-8")))- self.assertEqual(["result.json"], sorted(p.name for p in self.folder.iterdir()),- "a part file was left in the results folder")-- def test_a_part_file_a_killed_run_left_behind_is_overwritten(self):- # A run that was interrupted after its part file was opened leaves one behind; the next run- # has to write its own, not trip over it.- (self.folder / "result.json.part").write_text('{"response_ms": {"p50": 1', encoding="utf-8")+ self.assertEqual(["result.json"], self.names(),+ "a staging file was left in the results folder")++ @unittest.skipUnless(os.name == "posix", "file modes are a POSIX idea")+ def test_the_earlier_result_keeps_its_mode(self):+ result = self.folder / "result.json"+ result.write_text('{"response_ms": {"p50": 41}}', encoding="utf-8")+ os.chmod(result, 0o600)self.assertIsNone(self.write({"response_ms": {"p50": 99}}))- self.assertEqual(["result.json"], sorted(p.name for p in self.folder.iterdir()))+ self.assertEqual(0o600, stat.S_IMODE(os.stat(result).st_mode),+ "a successful write loosened the permissions of the result it replaced")++ @unittest.skipUnless(os.name == "posix", "file modes are a POSIX idea")+ def test_a_fresh_result_takes_the_mode_an_open_would_have_left(self):+ # 0666 masked by the umask, as `open("w")` left it: not the 0600 a bare mkstemp() makes,+ # which would take a result.json a group or another account could read before.+ previous = os.umask(0o022)+ self.addCleanup(os.umask, previous)+ self.assertIsNone(self.write({"response_ms": {"p50": 99}}))+ self.assertEqual(0o644, stat.S_IMODE(os.stat(self.folder / "result.json").st_mode))++ def test_a_hardlink_at_the_old_part_name_does_not_truncate_the_earlier_result(self):+ earlier = json.dumps({"response_ms": {"p50": 41}}, indent=2)+ result = self.folder / "result.json"+ result.write_text(earlier, encoding="utf-8")+ part = self.folder / "result.json.part"+ os.link(result, part) # a fixed staging name left from an older version of the tool+ self.fail_after_a_few_bytes()+ self.assertIsInstance(self.write({"response_ms": {"p50": 99}}), OSError)+ self.assertEqual(earlier, result.read_text(encoding="utf-8"),+ "the write went through the hardlink and truncated the earlier result")++ def test_a_symlink_at_the_old_part_name_is_not_written_through(self):+ earlier = '{"response_ms": {"p50": 41}}'+ (self.folder / "result.json").write_text(earlier, encoding="utf-8")+ elsewhere = self.folder / "another-result.json"+ elsewhere.write_text('{"keep": "me"}', encoding="utf-8")+ os.symlink(elsewhere, self.folder / "result.json.part")+ self.assertIsNone(self.write({"response_ms": {"p50": 99}}))+ self.assertEqual('{"keep": "me"}', elsewhere.read_text(encoding="utf-8"),+ "the write followed the symlink and overwrote the file it pointed at")++ def test_a_staging_file_a_killed_run_left_behind_is_left_alone(self):+ # A run killed after its staging file was opened leaves it under its own random name; the+ # next run writes its own and does not trip over, or clean up, a file it did not create.+ orphan = self.folder / ".result.json.0badc0de.part"+ orphan.write_text('{"response_ms": {"p50": 1', encoding="utf-8")+ self.assertIsNone(self.write({"response_ms": {"p50": 99}}))+ self.assertEqual({"response_ms": {"p50": 99}},+ json.loads((self.folder / "result.json").read_text(encoding="utf-8")))+ self.assertEqual('{"response_ms": {"p50": 1', orphan.read_text(encoding="utf-8"),+ "a staging file this run did not create was touched")+ self.assertEqual([".result.json.0badc0de.part", "result.json"], self.names())if __name__ == "__main__":diff --git a/tools/bench.py b/tools/bench.pyindex 64ca1b62a..a5f97fa10 100644--- a/tools/bench.py+++ b/tools/bench.py@@ -41,14 +41,17 @@ most of those keys and leaves a sample too small to say anything."""import argparseimport atexit+import errnoimport importlib.utilimport jsonimport osfrom pathlib import Pathimport re+import statimport statisticsimport sysimport time+import uuid# The sequence the key probe uses: moves inside a row and between rows, including the edges.DEFAULT_SEQUENCE = (22, 22, 22, 21, 21, 21, 20, 22, 22, 21, 21, 19)@@ -568,6 +571,25 @@ def stats(values):"p99": pick(0.99), "max": ordered[-1], "n": len(ordered)}+def staging_file(folder, name):+ """A new file beside the result, named so no run can collide with another, opened for writing.++ The name is random and created with O_EXCL, not a fixed `result.json.part`: `open()` on a name+ that is already there follows an alias, so a hardlink to the earlier result truncated it before+ the write and a symlink wrote through to whatever it pointed at. O_EXCL refuses a path that+ exists, symlink or not, and the mode is the one `open()` on the result used to leave (0666,+ masked by the umask), so a fresh result keeps the permissions it had.+ """+ for _ in range(8):+ stage = os.path.join(folder, f".{name}.{uuid.uuid4().hex[:8]}.part")+ try:+ fd = os.open(stage, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666)+ except FileExistsError:+ continue+ return stage, os.fdopen(fd, "w", encoding="utf-8")+ raise OSError(errno.EEXIST, "no free staging name beside the result")++def write_result(path, result):"""Write result.json, or return the OSError that stopped it and leave the earlier one alone.@@ -575,20 +597,34 @@ def write_result(path, result):filled up during the minutes the run takes, which is the failure the caller's message is about -took the result.json of the run before with it and left a half file under the name a readeropens. The numbers of that earlier run cannot be measured again the same way, so the write goes- to a part file and is renamed into place, the way tools/trace.py's --out and tools/recovery.py's- record already write theirs: either the new result.json is complete, or the one that was there- is untouched. A part file a killed run left behind is overwritten by the next one.+ to a staging file this run owns and is renamed into place, the way tools/trace.py's --out and+ tools/recovery.py's record already write theirs: either the new result.json is complete, or the+ one that was there is untouched, with its mode as well as its bytes - a successful write used to+ leave the earlier file's permissions where `open()` found them, and a fresh staging file does not.++ A staging file a killed run left behind is not touched by the next run, which writes its own+ name; it is the only thing an interrupted write can leave in the folder."""- part = path + ".part"+ folder, name = os.path.split(path)+ try:+ mode = stat.S_IMODE(os.stat(path).st_mode)+ except OSError:+ mode = None # no earlier result to match, so the new file takes the usual mode+ stage = Nonetry:- with open(part, "w", encoding="utf-8") as f:- json.dump(result, f, indent=2)- os.replace(part, path)+ stage, handle = staging_file(folder, name)+ with handle:+ json.dump(result, handle, indent=2)+ if mode is not None:+ os.chmod(stage, mode)+ os.replace(stage, path)+ stage = Noneexcept OSError as e:- try:- os.unlink(part)- except OSError:- pass # a part file that is a folder, or in a folder that went away: nothing to clean+ if stage is not None:+ try:+ os.unlink(stage)+ except OSError:+ pass # the folder went away with it: nothing to cleanreturn ereturn None